-
Notifications
You must be signed in to change notification settings - Fork 10.8k
/
file.cpp
444 lines (389 loc) · 13.3 KB
/
file.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//===--- Implementation of a platform independent file data structure -----===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "file.h"
#include "src/__support/CPP/span.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
namespace __llvm_libc {
size_t File::write_unlocked(const void *data, size_t len) {
if (!write_allowed()) {
errno = EBADF;
err = true;
return 0;
}
prev_op = FileOp::WRITE;
if (bufmode == _IOFBF) { // fully buffered
return write_unlocked_fbf(static_cast<const uint8_t *>(data), len);
} else if (bufmode == _IOLBF) { // line buffered
return write_unlocked_lbf(static_cast<const uint8_t *>(data), len);
} else /*if (bufmode == _IONBF) */ { // unbuffered
size_t ret_val =
write_unlocked_nbf(static_cast<const uint8_t *>(data), len);
flush_unlocked();
return ret_val;
}
}
size_t File::write_unlocked_nbf(const uint8_t *data, size_t len) {
if (pos > 0) { // If the buffer is not empty
// Flush the buffer
const size_t write_size = pos;
size_t bytes_written = platform_write(this, buf, write_size);
pos = 0; // Buffer is now empty so reset pos to the beginning.
// If less bytes were written than expected, then an error occurred.
if (bytes_written < write_size) {
err = true;
return 0; // No bytes from data were written, so return 0.
}
}
size_t written = platform_write(this, data, len);
if (written < len)
err = true;
return written;
}
size_t File::write_unlocked_fbf(const uint8_t *data, size_t len) {
const size_t init_pos = pos;
const size_t bufspace = bufsize - pos;
// If data is too large to be buffered at all, then just write it unbuffered.
if (len > bufspace + bufsize)
return write_unlocked_nbf(data, len);
// we split |data| (conceptually) using the split point. Then we handle the
// two pieces separately.
const size_t split_point = len < bufspace ? len : bufspace;
// The primary piece is the piece of |data| we want to write to the buffer
// before flushing. It will always fit into the buffer, since the split point
// is defined as being min(len, bufspace), and it will always exist if len is
// non-zero.
cpp::span<const uint8_t> primary(data, split_point);
// The second piece is the remainder of |data|. It is written to the buffer if
// it fits, or written directly to the output if it doesn't. If the primary
// piece fits entirely in the buffer, the remainder may be nothing.
cpp::span<const uint8_t> remainder(
static_cast<const uint8_t *>(data) + split_point, len - split_point);
cpp::span<uint8_t> bufref(static_cast<uint8_t *>(buf), bufsize);
// Copy the first piece into the buffer.
// TODO: Replace the for loop below with a call to internal memcpy.
for (size_t i = 0; i < primary.size(); ++i)
bufref[pos + i] = primary[i];
pos += primary.size();
// If there is no remainder, we can return early, since the first piece has
// fit completely into the buffer.
if (remainder.size() == 0)
return len;
// We need to flush the buffer now, since there is still data and the buffer
// is full.
const size_t write_size = pos;
size_t bytes_written = platform_write(this, buf, write_size);
pos = 0; // Buffer is now empty so reset pos to the beginning.
// If less bytes were written than expected, then an error occurred. Return
// the number of bytes that have been written from |data|.
if (bytes_written < write_size) {
err = true;
return bytes_written <= init_pos ? 0 : bytes_written - init_pos;
}
// The second piece is handled basically the same as the first, although we
// know that if the second piece has data in it then the buffer has been
// flushed, meaning that pos is always 0.
if (remainder.size() < bufsize) {
// TODO: Replace the for loop below with a call to internal memcpy.
for (size_t i = 0; i < remainder.size(); ++i)
bufref[i] = remainder[i];
pos = remainder.size();
} else {
size_t bytes_written =
platform_write(this, remainder.data(), remainder.size());
// If less bytes were written than expected, then an error occurred. Return
// the number of bytes that have been written from |data|.
if (bytes_written < remainder.size()) {
err = true;
return primary.size() + bytes_written;
}
}
return len;
}
size_t File::write_unlocked_lbf(const uint8_t *data, size_t len) {
constexpr uint8_t NEWLINE_CHAR = '\n';
size_t last_newline = len;
for (size_t i = len; i >= 1; --i) {
if (data[i - 1] == NEWLINE_CHAR) {
last_newline = i - 1;
break;
}
}
// If there is no newline, treat this as fully buffered.
if (last_newline == len) {
return write_unlocked_fbf(data, len);
}
// we split |data| (conceptually) using the split point. Then we handle the
// two pieces separately.
const size_t split_point = last_newline + 1;
// The primary piece is everything in |data| up to the newline. It's written
// unbuffered to the output.
cpp::span<const uint8_t> primary(data, split_point);
// The second piece is the remainder of |data|. It is written fully buffered,
// meaning it may stay in the buffer if it fits.
cpp::span<const uint8_t> remainder(
static_cast<const uint8_t *>(data) + split_point, len - split_point);
size_t written = 0;
written = write_unlocked_nbf(primary.data(), primary.size());
if (written < primary.size()) {
err = true;
return written;
}
flush_unlocked();
written += write_unlocked_fbf(remainder.data(), remainder.size());
if (written < len) {
err = true;
return written;
}
return len;
}
size_t File::read_unlocked(void *data, size_t len) {
if (!read_allowed()) {
errno = EBADF;
err = true;
return 0;
}
prev_op = FileOp::READ;
cpp::span<uint8_t> bufref(static_cast<uint8_t *>(buf), bufsize);
cpp::span<uint8_t> dataref(static_cast<uint8_t *>(data), len);
// Because read_limit is always greater than equal to pos,
// available_data is never a wrapped around value.
size_t available_data = read_limit - pos;
if (len <= available_data) {
// TODO: Replace the for loop below with a call to internal memcpy.
for (size_t i = 0; i < len; ++i)
dataref[i] = bufref[i + pos];
pos += len;
return len;
}
// Copy all of the available data.
// TODO: Replace the for loop with a call to internal memcpy.
for (size_t i = 0; i < available_data; ++i)
dataref[i] = bufref[i + pos];
read_limit = pos = 0; // Reset the pointers.
// Update the dataref to reflect that fact that we have already
// copied |available_data| into |data|.
dataref = cpp::span<uint8_t>(dataref.data() + available_data,
dataref.size() - available_data);
size_t to_fetch = len - available_data;
if (to_fetch > bufsize) {
size_t fetched_size = platform_read(this, dataref.data(), to_fetch);
if (fetched_size < to_fetch) {
if (errno == 0)
eof = true;
else
err = true;
return available_data + fetched_size;
}
return len;
}
// Fetch and buffer another buffer worth of data.
size_t fetched_size = platform_read(this, buf, bufsize);
read_limit += fetched_size;
size_t transfer_size = fetched_size >= to_fetch ? to_fetch : fetched_size;
for (size_t i = 0; i < transfer_size; ++i)
dataref[i] = bufref[i];
pos += transfer_size;
if (fetched_size < to_fetch) {
if (errno == 0)
eof = true;
else
err = true;
}
return transfer_size + available_data;
}
int File::ungetc_unlocked(int c) {
// There is no meaning to unget if:
// 1. You are trying to push back EOF.
// 2. Read operations are not allowed on this file.
// 3. The previous operation was a write operation.
if (c == EOF || !read_allowed() || (prev_op == FileOp::WRITE))
return EOF;
cpp::span<uint8_t> bufref(static_cast<uint8_t *>(buf), bufsize);
if (read_limit == 0) {
// If |read_limit| is zero, it can mean three things:
// a. This file was just created.
// b. The previous operation was a seek operation.
// c. The previous operation was a read operation which emptied
// the buffer.
// For all the above cases, we simply write |c| at the beginning
// of the buffer and bump |read_limit|. Note that |pos| will also
// be zero in this case, so we don't need to adjust it.
bufref[0] = static_cast<unsigned char>(c);
++read_limit;
} else {
// If |read_limit| is non-zero, it means that there is data in the buffer
// from a previous read operation. Which would also mean that |pos| is not
// zero. So, we decrement |pos| and write |c| in to the buffer at the new
// |pos|. If too many ungetc operations are performed without reads, it
// can lead to (pos == 0 but read_limit != 0). We will just error out in
// such a case.
if (pos == 0)
return EOF;
--pos;
bufref[pos] = static_cast<unsigned char>(c);
}
eof = false; // There is atleast one character that can be read now.
err = false; // This operation was a success.
return c;
}
int File::seek(long offset, int whence) {
FileLock lock(this);
if (prev_op == FileOp::WRITE && pos > 0) {
size_t transferred_size = platform_write(this, buf, pos);
if (transferred_size < pos) {
err = true;
return -1;
}
} else if (prev_op == FileOp::READ && whence == SEEK_CUR) {
// More data could have been read out from the platform file than was
// required. So, we have to adjust the offset we pass to platform seek
// function. Note that read_limit >= pos is always true.
offset -= (read_limit - pos);
}
pos = read_limit = 0;
prev_op = FileOp::SEEK;
// Reset the eof flag as a seek might move the file positon to some place
// readable.
eof = false;
long platform_pos = platform_seek(this, offset, whence);
if (platform_pos >= 0)
return 0;
else
return -1;
}
long File::tell() {
FileLock lock(this);
long platform_offset;
if (eof)
platform_offset = platform_seek(this, 0, SEEK_END);
else
platform_offset = platform_seek(this, 0, SEEK_CUR);
if (platform_offset < 0)
return -1;
if (prev_op == FileOp::READ)
return platform_offset - (read_limit - pos);
else if (prev_op == FileOp::WRITE)
return platform_offset + pos;
else
return platform_offset;
}
int File::flush_unlocked() {
if (prev_op == FileOp::WRITE && pos > 0) {
size_t transferred_size = platform_write(this, buf, pos);
if (transferred_size < pos) {
err = true;
return -1;
}
pos = 0;
return platform_flush(this);
}
// TODO: Add POSIX behavior for input streams.
return 0;
}
int File::close() {
{
FileLock lock(this);
if (prev_op == FileOp::WRITE && pos > 0) {
size_t transferred_size = platform_write(this, buf, pos);
if (transferred_size < pos) {
err = true;
return -1;
}
}
if (platform_close(this) != 0)
return -1;
if (own_buf)
free(buf);
}
free(this);
return 0;
}
int File::set_buffer(void *buffer, size_t size, int buffer_mode) {
// We do not need to lock the file as this method should be called before
// other operations are performed on the file.
if (buffer != nullptr && size == 0)
return EINVAL;
switch (buffer_mode) {
case _IOFBF:
case _IOLBF:
case _IONBF:
break;
default:
return EINVAL;
}
if (buffer == nullptr && size != 0 && buffer_mode != _IONBF) {
// We exclude the case of buffer_mode == _IONBF in this branch
// because we don't need to allocate buffer in such a case.
if (own_buf) {
buf = realloc(buf, size);
} else {
buf = malloc(size);
own_buf = true;
}
bufsize = size;
// TODO: Handle allocation failures.
} else {
if (own_buf)
free(buf);
if (buffer_mode != _IONBF) {
buf = static_cast<uint8_t *>(buffer);
bufsize = size;
} else {
// We don't need any buffer.
buf = nullptr;
bufsize = 0;
}
own_buf = false;
}
bufmode = buffer_mode;
adjust_buf();
return 0;
}
File::ModeFlags File::mode_flags(const char *mode) {
// First character in |mode| should be 'a', 'r' or 'w'.
if (*mode != 'a' && *mode != 'r' && *mode != 'w')
return 0;
// There should be exaclty one main mode ('a', 'r' or 'w') character.
// If there are more than one main mode characters listed, then
// we will consider |mode| as incorrect and return 0;
int main_mode_count = 0;
ModeFlags flags = 0;
for (; *mode != '\0'; ++mode) {
switch (*mode) {
case 'r':
flags |= static_cast<ModeFlags>(OpenMode::READ);
++main_mode_count;
break;
case 'w':
flags |= static_cast<ModeFlags>(OpenMode::WRITE);
++main_mode_count;
break;
case '+':
flags |= static_cast<ModeFlags>(OpenMode::PLUS);
break;
case 'b':
flags |= static_cast<ModeFlags>(ContentType::BINARY);
break;
case 'a':
flags |= static_cast<ModeFlags>(OpenMode::APPEND);
++main_mode_count;
break;
case 'x':
flags |= static_cast<ModeFlags>(CreateType::EXCLUSIVE);
break;
default:
return 0;
}
}
if (main_mode_count != 1)
return 0;
return flags;
}
} // namespace __llvm_libc