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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
|
#include <errno.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#if __MLIBC_GLIBC_OPTION
#include <stdio_ext.h>
#endif
#include <bits/ensure.h>
#include <mlibc/debug.hpp>
#include <abi-bits/fcntl.h>
#include <frg/allocation.hpp>
#include <frg/mutex.hpp>
#include <mlibc/allocator.hpp>
#include <mlibc/file-io.hpp>
#include <mlibc/ansi-sysdeps.hpp>
#include <mlibc/lock.hpp>
namespace mlibc {
// --------------------------------------------------------------------------------------
// abstract_file implementation.
// --------------------------------------------------------------------------------------
namespace {
using file_list = frg::intrusive_list<
abstract_file,
frg::locate_member<
abstract_file,
frg::default_list_hook<abstract_file>,
&abstract_file::_list_hook
>
>;
// Useful when debugging the FILE implementation.
constexpr bool globallyDisableBuffering = false;
// The maximum number of characters we permit the user to ungetc.
constexpr size_t ungetBufferSize = 8;
// List of files that will be flushed before exit().
file_list &global_file_list() {
static frg::eternal<file_list> list;
return list.get();
};
}
// For pipe-like streams (seek returns ESPIPE), we need to make sure
// that the buffer only ever contains all-dirty or all-clean data.
// Regarding _type and _bufmode:
// As we might construct FILE objects for FDs that are not actually
// open (e.g. for std{in,out,err}), we defer the type determination and cache the result.
abstract_file::abstract_file(void (*do_dispose)(abstract_file *))
: _type{stream_type::unknown}, _bufmode{buffer_mode::unknown}, _do_dispose{do_dispose} {
// TODO: For __fwriting to work correctly, set the __io_mode to 1 if the write is write-only.
__buffer_ptr = nullptr;
__unget_ptr = nullptr;
__buffer_size = 4096;
__offset = 0;
__io_offset = 0;
__valid_limit = 0;
__dirty_begin = 0;
__dirty_end = 0;
__io_mode = 0;
__status_bits = 0;
global_file_list().push_back(this);
}
abstract_file::~abstract_file() {
if(__dirty_begin != __dirty_end)
mlibc::infoLogger() << "mlibc warning: File is not flushed before destruction"
<< frg::endlog;
if(__buffer_ptr)
getAllocator().free(__buffer_ptr - ungetBufferSize);
auto it = global_file_list().iterator_to(this);
global_file_list().erase(it);
}
void abstract_file::dispose() {
if(!_do_dispose)
return;
_do_dispose(this);
}
// Note that read() and write() are asymmetric:
// While read() can trigger a write-back, write() can never trigger a read-ahead().
// This peculiarity is reflected in their code.
int abstract_file::read(char *buffer, size_t max_size, size_t *actual_size) {
__ensure(max_size);
if(_init_bufmode())
return -1;
size_t unget_length = 0;
if (__unget_ptr != __buffer_ptr) {
unget_length = frg::min(max_size, (size_t)(__buffer_ptr - __unget_ptr));
memcpy(buffer, __unget_ptr, unget_length);
__unget_ptr += unget_length;
buffer += unget_length;
max_size -= unget_length;
if (max_size == 0) {
*actual_size = unget_length;
return 0;
}
}
if(globallyDisableBuffering || _bufmode == buffer_mode::no_buffer) {
size_t io_size;
if(int e = io_read(buffer, max_size, &io_size); e) {
__status_bits |= __MLIBC_ERROR_BIT;
return e;
}
if(!io_size)
__status_bits |= __MLIBC_EOF_BIT;
*actual_size = io_size + unget_length;
return 0;
}
// Ensure correct buffer type for pipe-like streams.
// TODO: In order to support pipe-like streams we need to write-back the buffer.
if(__io_mode && __valid_limit)
mlibc::panicLogger() << "mlibc: Cannot read-write to same pipe-like stream"
<< frg::endlog;
__io_mode = 0;
// Clear the buffer, then buffer new data.
if(__offset == __valid_limit) {
// TODO: We only have to write-back/reset if __valid_limit reaches the buffer end.
if(int e = _write_back(); e)
return e;
if(int e = _reset(); e)
return e;
// Perform a read-ahead.
_ensure_allocation();
size_t io_size;
if(int e = io_read(__buffer_ptr, __buffer_size, &io_size); e) {
__status_bits |= __MLIBC_ERROR_BIT;
return e;
}
if(!io_size) {
__status_bits |= __MLIBC_EOF_BIT;
*actual_size = 0;
return 0;
}
__io_offset = io_size;
__valid_limit = io_size;
}
// Return data from the buffer.
__ensure(__offset < __valid_limit);
auto chunk = frg::min(size_t(__valid_limit - __offset), max_size);
memcpy(buffer, __buffer_ptr + __offset, chunk);
__offset += chunk;
*actual_size = chunk + unget_length;
return 0;
}
int abstract_file::write(const char *buffer, size_t max_size, size_t *actual_size) {
__ensure(max_size);
if(_init_bufmode())
return -1;
if(globallyDisableBuffering || _bufmode == buffer_mode::no_buffer) {
// As we do not buffer, nothing can be dirty.
__ensure(__dirty_begin == __dirty_end);
size_t io_size;
if(int e = io_write(buffer, max_size, &io_size); e) {
__status_bits |= __MLIBC_ERROR_BIT;
return e;
}
*actual_size = io_size;
return 0;
}
// Flush the buffer if necessary.
if(__offset == __buffer_size) {
if(int e = _write_back(); e)
return e;
if(int e = _reset(); e)
return e;
}
// Ensure correct buffer type for pipe-like streams.
// TODO: We could full support pipe-like files
// by ungetc()ing all data before a write happens,
// however, for now we just report an error.
if(!__io_mode && __valid_limit) // TODO: Only check this for pipe-like streams.
mlibc::panicLogger() << "mlibc: Cannot read-write to same pipe-like stream"
<< frg::endlog;
__io_mode = 1;
__ensure(__offset < __buffer_size);
auto chunk = frg::min(__buffer_size - __offset, max_size);
// Line-buffered streams perform I/O on full lines.
bool flush_line = false;
if(_bufmode == buffer_mode::line_buffer) {
auto nl = reinterpret_cast<char *>(memchr(buffer, '\n', chunk));
if(nl) {
chunk = nl + 1 - buffer;
flush_line = true;
}
}
__ensure(chunk);
// Buffer data (without necessarily performing I/O).
_ensure_allocation();
memcpy(__buffer_ptr + __offset, buffer, chunk);
if(__dirty_begin != __dirty_end) {
__dirty_begin = frg::min(__dirty_begin, __offset);
__dirty_end = frg::max(__dirty_end, __offset + chunk);
}else{
__dirty_begin = __offset;
__dirty_end = __offset + chunk;
}
__valid_limit = frg::max(__offset + chunk, __valid_limit);
__offset += chunk;
// Flush line-buffered streams.
if(flush_line) {
if(_write_back())
return -1;
}
*actual_size = chunk;
return 0;
}
int abstract_file::unget(char c) {
if (!__unget_ptr) {
// This can happen if the file is unbuffered, but we still need
// a space to store ungetc'd data.
__ensure(!__buffer_ptr);
_ensure_allocation();
__ensure(__unget_ptr);
}
if ((size_t)(__buffer_ptr - __unget_ptr) + 1 > ungetBufferSize)
return EOF;
else {
*(--__unget_ptr) = c;
return c;
}
}
int abstract_file::update_bufmode(buffer_mode mode) {
// setvbuf() has undefined behavior if I/O has been performed.
__ensure(__dirty_begin == __dirty_end
&& "update_bufmode() must only be called before performing I/O");
_bufmode = mode;
return 0;
}
void abstract_file::purge() {
__offset = 0;
__io_offset = 0;
__valid_limit = 0;
__dirty_end = __dirty_begin;
__unget_ptr = __buffer_ptr;
}
int abstract_file::flush() {
if (__dirty_end != __dirty_begin) {
if (int e = _write_back(); e)
return e;
}
if (int e = _save_pos(); e)
return e;
purge();
return 0;
}
int abstract_file::tell(off_t *current_offset) {
off_t seek_offset;
if(int e = io_seek(0, SEEK_CUR, &seek_offset); e)
return e;
*current_offset = seek_offset + (off_t(__offset) - off_t(__io_offset));
return 0;
}
int abstract_file::seek(off_t offset, int whence) {
if(int e = _write_back(); e)
return e;
off_t new_offset;
if(whence == SEEK_CUR) {
auto seek_offset = offset + (off_t(__offset) - off_t(__io_offset));
if(int e = io_seek(seek_offset, whence, &new_offset); e) {
__status_bits |= __MLIBC_ERROR_BIT;
return e;
}
}else{
__ensure(whence == SEEK_SET || whence == SEEK_END);
if(int e = io_seek(offset, whence, &new_offset); e) {
__status_bits |= __MLIBC_ERROR_BIT;
return e;
}
}
// We just forget the current buffer.
// TODO: If the seek is "small", we can just modify our internal offset.
purge();
return 0;
}
int abstract_file::_init_type() {
if(_type != stream_type::unknown)
return 0;
if(int e = determine_type(&_type); e)
return e;
__ensure(_type != stream_type::unknown);
return 0;
}
int abstract_file::_init_bufmode() {
if(_bufmode != buffer_mode::unknown)
return 0;
if(determine_bufmode(&_bufmode))
return -1;
__ensure(_bufmode != buffer_mode::unknown);
return 0;
}
int abstract_file::_write_back() {
if(int e = _init_type(); e)
return e;
if(__dirty_begin == __dirty_end)
return 0;
// For non-pipe streams, first do a seek to reset the
// I/O position to zero, then do a write().
if(_type == stream_type::file_like) {
if(__io_offset != __dirty_begin) {
__ensure(__dirty_begin - __io_offset > 0);
off_t new_offset;
if(int e = io_seek(off_t(__dirty_begin) - off_t(__io_offset), SEEK_CUR, &new_offset); e)
return e;
__io_offset = __dirty_begin;
}
}else{
__ensure(_type == stream_type::pipe_like);
__ensure(__io_offset == __dirty_begin);
}
// Now, we are in the correct position to write-back everything.
while(__io_offset < __dirty_end) {
size_t io_size;
if(int e = io_write(__buffer_ptr + __io_offset, __dirty_end - __io_offset, &io_size); e) {
__status_bits |= __MLIBC_ERROR_BIT;
return e;
}
__ensure(io_size > 0 && "io_write() is expected to always write at least one byte");
__io_offset += io_size;
__dirty_begin += io_size;
}
return 0;
}
int abstract_file::_save_pos() {
if (int e = _init_type(); e)
return e;
if (int e = _init_bufmode(); e)
return e;
if (_type == stream_type::file_like && _bufmode != buffer_mode::no_buffer) {
off_t new_offset;
auto seek_offset = (off_t(__offset) - off_t(__io_offset));
if (int e = io_seek(seek_offset, SEEK_CUR, &new_offset); e) {
__status_bits |= __MLIBC_ERROR_BIT;
mlibc::infoLogger() << "hit io_seek() error " << e << frg::endlog;
return e;
}
return 0;
}
return 0; // nothing to do for the rest
}
int abstract_file::_reset() {
if(int e = _init_type(); e)
return e;
// For pipe-like files, we must not forget already read data.
// TODO: Report this error to the user.
if(_type == stream_type::pipe_like)
__ensure(__offset == __valid_limit);
__ensure(__dirty_begin == __dirty_end);
__offset = 0;
__io_offset = 0;
__valid_limit = 0;
return 0;
}
// This may still be called when buffering is disabled, for ungetc.
void abstract_file::_ensure_allocation() {
if(__buffer_ptr)
return;
auto ptr = getAllocator().allocate(__buffer_size + ungetBufferSize);
__buffer_ptr = reinterpret_cast<char *>(ptr) + ungetBufferSize;
__unget_ptr = __buffer_ptr;
}
// --------------------------------------------------------------------------------------
// fd_file implementation.
// --------------------------------------------------------------------------------------
fd_file::fd_file(int fd, void (*do_dispose)(abstract_file *), bool force_unbuffered)
: abstract_file{do_dispose}, _fd{fd}, _force_unbuffered{force_unbuffered} { }
int fd_file::fd() {
return _fd;
}
int fd_file::close() {
if(__dirty_begin != __dirty_end)
mlibc::infoLogger() << "mlibc warning: File is not flushed before closing"
<< frg::endlog;
if(int e = mlibc::sys_close(_fd); e)
return e;
return 0;
}
int fd_file::reopen(const char *path, const char *mode) {
int mode_flags = parse_modestring(mode);
int fd;
if(int e = sys_open(path, mode_flags, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH, &fd); e) {
return e;
}
flush();
close();
getAllocator().deallocate(__buffer_ptr, __buffer_size + ungetBufferSize);
__buffer_ptr = nullptr;
__unget_ptr = nullptr;
__buffer_size = 4096;
_reset();
_fd = fd;
if(mode_flags & O_APPEND) {
seek(0, SEEK_END);
}
return 0;
}
int fd_file::determine_type(stream_type *type) {
off_t offset;
int e = mlibc::sys_seek(_fd, 0, SEEK_CUR, &offset);
if(!e) {
*type = stream_type::file_like;
return 0;
}else if(e == ESPIPE) {
*type = stream_type::pipe_like;
return 0;
}else{
return e;
}
}
int fd_file::determine_bufmode(buffer_mode *mode) {
// When isatty() is not implemented, we fall back to the safest default (no buffering).
if(!mlibc::sys_isatty) {
MLIBC_MISSING_SYSDEP();
*mode = buffer_mode::no_buffer;
return 0;
}
if(_force_unbuffered) {
*mode = buffer_mode::no_buffer;
return 0;
}
if(int e = mlibc::sys_isatty(_fd); !e) {
*mode = buffer_mode::line_buffer;
return 0;
}else if(e == ENOTTY) {
*mode = buffer_mode::full_buffer;
return 0;
}else{
mlibc::infoLogger() << "mlibc: sys_isatty() failed while determining whether"
" stream is interactive" << frg::endlog;
return -1;
}
}
int fd_file::io_read(char *buffer, size_t max_size, size_t *actual_size) {
ssize_t s;
if(int e = mlibc::sys_read(_fd, buffer, max_size, &s); e)
return e;
*actual_size = s;
return 0;
}
int fd_file::io_write(const char *buffer, size_t max_size, size_t *actual_size) {
ssize_t s;
if(int e = mlibc::sys_write(_fd, buffer, max_size, &s); e)
return e;
*actual_size = s;
return 0;
}
int fd_file::io_seek(off_t offset, int whence, off_t *new_offset) {
if(int e = mlibc::sys_seek(_fd, offset, whence, new_offset); e)
return e;
return 0;
}
int fd_file::parse_modestring(const char *mode) {
// Consume the first char; this must be 'r', 'w' or 'a'.
int flags = 0;
bool has_plus = strchr(mode, '+');
if(*mode == 'r') {
if(has_plus) {
flags = O_RDWR;
}else{
flags = O_RDONLY;
}
}else if(*mode == 'w') {
if(has_plus) {
flags = O_RDWR;
}else{
flags = O_WRONLY;
}
flags |= O_CREAT | O_TRUNC;
}else if(*mode == 'a') {
if(has_plus) {
flags = O_APPEND | O_RDWR;
}else{
flags = O_APPEND | O_WRONLY;
}
flags |= O_CREAT;
}else{
mlibc::infoLogger() << "Illegal fopen() mode '" << *mode << "'" << frg::endlog;
}
mode += 1;
// Consume additional flags.
while(*mode) {
if(*mode == '+') {
mode++; // This is already handled above.
}else if(*mode == 'b') {
mode++; // mlibc assumes that there is no distinction between text and binary.
}else if(*mode == 'e') {
flags |= O_CLOEXEC;
mode++;
}else{
mlibc::infoLogger() << "Illegal fopen() flag '" << mode << "'" << frg::endlog;
mode++;
}
}
return flags;
}
} // namespace mlibc
namespace {
mlibc::fd_file stdin_file{0};
mlibc::fd_file stdout_file{1};
mlibc::fd_file stderr_file{2, nullptr, true};
struct stdio_guard {
stdio_guard() { }
~stdio_guard() {
// Only flush the files but do not close them.
for(auto it : mlibc::global_file_list()) {
if(int e = it->flush(); e)
mlibc::infoLogger() << "mlibc warning: Failed to flush file before exit()"
<< frg::endlog;
}
}
} global_stdio_guard;
}
FILE *stderr = &stderr_file;
FILE *stdin = &stdin_file;
FILE *stdout = &stdout_file;
int fileno_unlocked(FILE *file_base) {
auto file = static_cast<mlibc::fd_file *>(file_base);
return file->fd();
}
int fileno(FILE *file_base) {
auto file = static_cast<mlibc::fd_file *>(file_base);
frg::unique_lock lock(file->_lock);
return fileno_unlocked(file_base);
}
FILE *fopen(const char *path, const char *mode) {
int flags = mlibc::fd_file::parse_modestring(mode);
int fd;
if(int e = mlibc::sys_open(path, flags, 0666, &fd); e) {
errno = e;
return nullptr;
}
return frg::construct<mlibc::fd_file>(getAllocator(), fd,
mlibc::file_dispose_cb<mlibc::fd_file>);
}
int fclose(FILE *file_base) {
auto file = static_cast<mlibc::abstract_file *>(file_base);
int e = 0;
if(file->flush())
e = EOF;
if(file->close())
e = EOF;
file->dispose();
return e;
}
int fseek(FILE *file_base, long offset, int whence) {
auto file = static_cast<mlibc::abstract_file *>(file_base);
frg::unique_lock lock(file->_lock);
if(int e = file->seek(offset, whence); e) {
errno = e;
return -1;
}
return 0;
}
long ftell(FILE *file_base) {
auto file = static_cast<mlibc::abstract_file *>(file_base);
frg::unique_lock lock(file->_lock);
off_t current_offset;
if(int e = file->tell(¤t_offset); e) {
errno = e;
return -1;
}
return current_offset;
}
int fflush_unlocked(FILE *file_base) {
if(file_base == NULL) {
// Only flush the files but do not close them.
for(auto it : mlibc::global_file_list()) {
if(int e = it->flush(); e)
mlibc::infoLogger() << "mlibc warning: Failed to flush file"
<< frg::endlog;
}
return 0;
}
auto file = static_cast<mlibc::abstract_file *>(file_base);
if(file->flush())
return EOF;
return 0;
}
int fflush(FILE *file_base) {
if(file_base == NULL) {
// Only flush the files but do not close them.
for(auto it : mlibc::global_file_list()) {
frg::unique_lock lock(it->_lock);
if(int e = it->flush(); e)
mlibc::infoLogger() << "mlibc warning: Failed to flush file"
<< frg::endlog;
}
return 0;
}
auto file = static_cast<mlibc::abstract_file *>(file_base);
frg::unique_lock lock(file->_lock);
if (file->flush())
return EOF;
return 0;
}
int setvbuf(FILE *file_base, char *, int mode, size_t) {
// TODO: We could also honor the buffer, but for now use just set the mode.
auto file = static_cast<mlibc::abstract_file *>(file_base);
if(mode == _IONBF) {
if(int e = file->update_bufmode(mlibc::buffer_mode::no_buffer); e) {
errno = e;
return -1;
}
}else if(mode == _IOLBF) {
if(int e = file->update_bufmode(mlibc::buffer_mode::line_buffer); e) {
errno = e;
return -1;
}
}else if(mode == _IOFBF) {
if(int e = file->update_bufmode(mlibc::buffer_mode::full_buffer); e) {
errno = e;
return -1;
}
}else{
errno = EINVAL;
return -1;
}
return 0;
}
void rewind(FILE *file_base) {
auto file = static_cast<mlibc::abstract_file *>(file_base);
frg::unique_lock lock(file->_lock);
file->seek(0, SEEK_SET);
file_base->__status_bits &= ~(__MLIBC_EOF_BIT | __MLIBC_ERROR_BIT);
}
int ungetc(int c, FILE *file_base) {
if (c == EOF)
return EOF;
auto file = static_cast<mlibc::abstract_file *>(file_base);
frg::unique_lock lock(file->_lock);
return file->unget(c);
}
#if __MLIBC_GLIBC_OPTION
void __fpurge(FILE *file_base) {
auto file = static_cast<mlibc::abstract_file *>(file_base);
frg::unique_lock lock(file->_lock);
file->purge();
}
#endif
|