Commit | Line | Data |
---|---|---|
33b14136 | 1 | /* |
ab5be9fa | 2 | * Copyright (C) 2013 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
33b14136 | 3 | * |
ab5be9fa | 4 | * SPDX-License-Identifier: LGPL-2.1-only |
33b14136 | 5 | * |
33b14136 MD |
6 | */ |
7 | ||
6c1c0768 | 8 | #define _LGPL_SOURCE |
28ab034a | 9 | #include "readwrite.hpp" |
aeb16260 | 10 | |
c9e313bc | 11 | #include <common/compat/errno.hpp> |
edf4b93e | 12 | |
28ab034a JG |
13 | #include <limits.h> |
14 | #include <unistd.h> | |
33b14136 MD |
15 | |
16 | /* | |
17 | * lttng_read and lttng_write take care of EINTR and partial read/write. | |
18 | * Upon success, they return the "count" received as parameter. | |
19 | * They can return a negative value if an error occurs. | |
20 | * If a value lower than the requested "count" is returned, it means an | |
83f4233d | 21 | * error occurred. |
33b14136 MD |
22 | * The error can be checked by querying errno. |
23 | */ | |
24 | ssize_t lttng_read(int fd, void *buf, size_t count) | |
25 | { | |
26 | size_t i = 0; | |
27 | ssize_t ret; | |
28 | ||
a0377dfe | 29 | LTTNG_ASSERT(buf); |
aeb16260 | 30 | |
636ae5db DG |
31 | /* |
32 | * Deny a read count that can be bigger then the returned value max size. | |
33 | * This makes the function to never return an overflow value. | |
34 | */ | |
35 | if (count > SSIZE_MAX) { | |
36 | return -EINVAL; | |
37 | } | |
38 | ||
33b14136 | 39 | do { |
a6bc4ca9 | 40 | ret = read(fd, (char *) buf + i, count - i); |
33b14136 MD |
41 | if (ret < 0) { |
42 | if (errno == EINTR) { | |
28ab034a | 43 | continue; /* retry operation */ |
33b14136 MD |
44 | } else { |
45 | goto error; | |
46 | } | |
47 | } | |
48 | i += ret; | |
a0377dfe | 49 | LTTNG_ASSERT(i <= count); |
33b14136 MD |
50 | } while (count - i > 0 && ret > 0); |
51 | return i; | |
52 | ||
53 | error: | |
54 | if (i == 0) { | |
55 | return -1; | |
56 | } else { | |
57 | return i; | |
58 | } | |
59 | } | |
60 | ||
61 | ssize_t lttng_write(int fd, const void *buf, size_t count) | |
62 | { | |
63 | size_t i = 0; | |
64 | ssize_t ret; | |
65 | ||
a0377dfe | 66 | LTTNG_ASSERT(buf); |
aeb16260 | 67 | |
636ae5db DG |
68 | /* |
69 | * Deny a write count that can be bigger then the returned value max size. | |
70 | * This makes the function to never return an overflow value. | |
71 | */ | |
72 | if (count > SSIZE_MAX) { | |
73 | return -EINVAL; | |
74 | } | |
75 | ||
33b14136 | 76 | do { |
a6bc4ca9 | 77 | ret = write(fd, (char *) buf + i, count - i); |
33b14136 MD |
78 | if (ret < 0) { |
79 | if (errno == EINTR) { | |
28ab034a | 80 | continue; /* retry operation */ |
33b14136 MD |
81 | } else { |
82 | goto error; | |
83 | } | |
84 | } | |
85 | i += ret; | |
a0377dfe | 86 | LTTNG_ASSERT(i <= count); |
33b14136 MD |
87 | } while (count - i > 0 && ret > 0); |
88 | return i; | |
89 | ||
90 | error: | |
91 | if (i == 0) { | |
92 | return -1; | |
93 | } else { | |
94 | return i; | |
95 | } | |
96 | } |