summaryrefslogtreecommitdiff
path: root/ecos/packages/language/c/libc/stdio/current/src/common/stream.cxx
blob: f25e79b13c5609a3162ec73a1790f380c71f5cfd (plain)
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
//========================================================================
//
//      stream.cxx
//
//      Implementations of internal C library stdio stream functions
//
//========================================================================
// ####ECOSGPLCOPYRIGHTBEGIN####                                            
// -------------------------------------------                              
// This file is part of eCos, the Embedded Configurable Operating System.   
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2006 Free Software Foundation, Inc.
//
// eCos is free software; you can redistribute it and/or modify it under    
// the terms of the GNU General Public License as published by the Free     
// Software Foundation; either version 2 or (at your option) any later      
// version.                                                                 
//
// eCos is distributed in the hope that it will be useful, but WITHOUT      
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or    
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License    
// for more details.                                                        
//
// You should have received a copy of the GNU General Public License        
// along with eCos; if not, write to the Free Software Foundation, Inc.,    
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.            
//
// As a special exception, if other files instantiate templates or use      
// macros or inline functions from this file, or you compile this file      
// and link it with other works to produce a work based on this file,       
// this file does not by itself cause the resulting work to be covered by   
// the GNU General Public License. However the source code for this file    
// must still be made available in accordance with section (3) of the GNU   
// General Public License v2.                                               
//
// This exception does not invalidate any other reasons why a work based    
// on this file might be covered by the GNU General Public License.         
// -------------------------------------------                              
// ####ECOSGPLCOPYRIGHTEND####                                              
//========================================================================
//#####DESCRIPTIONBEGIN####
//
// Author(s):     jlarmour
// Contributors:  
// Date:          2000-04-20
// Purpose:     
// Description: 
// Usage:       
//
//####DESCRIPTIONEND####
//
//========================================================================

// CONFIGURATION

#include <pkgconf/libc_stdio.h>   // Configuration header

// INCLUDES

#include <cyg/infra/cyg_type.h>    // Common project-wide type definitions
#include <cyg/infra/cyg_ass.h>     // Assertion infrastructure
#include <stddef.h>                // NULL and size_t from compiler
#include <errno.h>                 // Error codes
#include <string.h>                // memcpy() and memset()
#include <cyg/libc/stdio/stream.hxx>     // Header for this file
#include <cyg/libc/stdio/stdiosupp.hxx>  // Stdio support functions


#include <cyg/libc/stdio/io.inl>     // I/O system inlines


// FUNCTIONS

Cyg_StdioStream::Cyg_StdioStream(cyg_stdio_handle_t dev,
                                 OpenMode open_mode,
                                 cyg_bool append, cyg_bool binary,
                                 int buffer_mode, cyg_ucount32 buffer_size,
                                 cyg_uint8 *buffer_addr )
#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
    : io_buf( buffer_size, buffer_addr )
#endif
{
    initialize( dev, open_mode, append, binary, buffer_mode,
                buffer_size, buffer_addr);
}

void Cyg_StdioStream::initialize(cyg_stdio_handle_t dev,
                                 OpenMode open_mode,
                                 cyg_bool append, cyg_bool binary,
                                 int buffer_mode, cyg_ucount32 buffer_size,
                                 cyg_uint8 *buffer_addr )
{

#ifdef CYGDBG_USE_ASSERTS
    magic_validity_word = 0xbadbad;
#endif

    my_device = dev;

    // Clear all flags
    memset( &flags, 0, sizeof(flags) );

    switch (open_mode) {
    case CYG_STREAM_READ:
        flags.opened_for_read = true;
        break;
    case CYG_STREAM_WRITE:
        flags.opened_for_write = true;
        break;
    case CYG_STREAM_READWRITE_NOCREATE:
    case CYG_STREAM_READWRITE_CREATE:
        flags.opened_for_read = true;
        flags.opened_for_write = true;
        break;
    default:
        error=EINVAL;
        return;
    } // switch
        
    
    if (flags.opened_for_write) {
#if 0
        // FIXME: need some replacement for this
        if (!my_device->write_blocking) {
            error = EDEVNOSUPP;
            return;
        } // if
#endif
#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
        flags.last_buffer_op_was_read = false;
#endif
    } // if


    if (flags.opened_for_read) {
#if 0
        // FIXME: need some replacement for this
        if (!my_device->read_blocking) {
            error = EDEVNOSUPP;
            return;
        } // if
#endif

        // NB also if opened for read AND write, then say last op was read
#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
        flags.last_buffer_op_was_read = true;
#endif
    } // if

    flags.binary = binary ? 1 : 0;

    error = ENOERR;
    
    // in due course we would do an equivalent to fseek(...,0, SEEK_END);
    // when appending. for now, there's nothing, except set eof
    
    flags.at_eof = append ? 1 : 0;

    position = 0;

#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO

    switch (buffer_mode) {
    case _IONBF:
        CYG_ASSERT( (buffer_size == 0) && (buffer_addr == NULL),
                    "No buffering wanted but size/address specified!" );
        flags.buffering = flags.line_buffering = false;
        break;
    case _IOLBF:
        flags.buffering = true;
        flags.line_buffering = true;
        break;
    case _IOFBF:
        flags.buffering = true;
        flags.line_buffering = false;
        break;
    default:
        error = EINVAL;
        return;
    } // switch

    // one way of checking the buffer was set up correctly
    if (flags.buffering && io_buf.get_buffer_size()==-1) {
        error = ENOMEM;
        return;
    }

#endif

#if 0 // FIXME - Need to set binary mode.
    if (my_device->open) {
        error = (*my_device->open)( my_device->cookie, 
                                    binary ? CYG_DEVICE_OPEN_MODE_RAW
                                           : CYG_DEVICE_OPEN_MODE_TEXT );
        if (error != ENOERR)
            return; // keep error code the same
    } // if
    
#endif

#ifdef CYGDBG_USE_ASSERTS
    magic_validity_word = 0x7b4321ce;
#endif
    
} // Cyg_StdioStream constructor


Cyg_StdioStream::Cyg_StdioStream( OpenMode open_mode,
                                 cyg_ucount32 buffer_size,
                                  cyg_uint8 *buffer_addr )
#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
    : io_buf( buffer_size, buffer_addr )
#endif
{
    initialize( CYG_STDIO_HANDLE_NULL, open_mode, false, false, _IOFBF,
                buffer_size, buffer_addr );

    if( error != ENOERR )
        return;
    
    switch( open_mode )
    {
    case CYG_STREAM_READ:
        // Fix up the stream so it looks like the buffer contents has just
        // been read in.
#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
        io_buf.set_bytes_written( buffer_size );
#endif
        break;
        
    case CYG_STREAM_WRITE:
        // Fix up the stream so it looks like the buffer is ready to accept
        // new data.
        break;

    default:
        error = EINVAL;
        return;
    }
}


Cyg_ErrNo
Cyg_StdioStream::refill_read_buffer( void )
{
    Cyg_ErrNo read_err;
    cyg_uint8 *buffer;
    cyg_uint32 len;

    CYG_ASSERTCLASS( this, "Stream object is not a valid stream!" );
    
    if (!lock_me())
        return EBADF;  // assume file is now invalid

    // first just check that we _can_ read this device!
    if (!flags.opened_for_read) {
        unlock_me();
        return EINVAL;
    }
    
#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
    // If there is pending output to write, then this will check and
    // write it
    if (flags.buffering) {
        read_err = flush_output_unlocked();

        // we're now reading
        flags.last_buffer_op_was_read = true;

        // flush ALL streams
        if (read_err == ENOERR)
            read_err = cyg_libc_stdio_flush_all_but(this);

        if (read_err != ENOERR) {
            unlock_me();
            return read_err;
        } // if

        len = io_buf.get_buffer_addr_to_write( (cyg_uint8**)&buffer );
        if (!len) { // no buffer space available
            unlock_me();
            return ENOERR;  // isn't an error, just needs user to read out data
        } // if
    }
    else
#endif

    if (!flags.readbuf_char_in_use) {
        len = 1;
        buffer = &readbuf_char;
    }
    else {
        // no buffer space available
        unlock_me();
        return ENOERR;  // isn't an error, just needs user to read out data
    } // else

    read_err = cyg_stdio_read(my_device, buffer, &len);


#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
    if (flags.buffering)
        io_buf.set_bytes_written( len );
    else
#endif
        flags.readbuf_char_in_use = len ? 1 : 0;

    unlock_me();

    if (read_err == ENOERR) {
        if (len == 0) {
            read_err = EAGAIN;
            flags.at_eof = true;
        }
        else
            flags.at_eof = false;
    } // if
    
    return read_err;
} // refill_read_buffer()


Cyg_ErrNo
Cyg_StdioStream::read( cyg_uint8 *user_buffer, cyg_ucount32 buffer_length,
                       cyg_ucount32 *bytes_read )
{
    Cyg_ErrNo read_err=ENOERR;
    CYG_ASSERTCLASS( this, "Stream object is not a valid stream!" );
    
    *bytes_read = 0;

    if (!lock_me())
        return EBADF;  // assume file is now invalid

    if (!flags.opened_for_read) {
        unlock_me();
        return EINVAL;
    }

#ifdef CYGFUN_LIBC_STDIO_ungetc
    if (flags.unread_char_buf_in_use && buffer_length) {
        *user_buffer++ = unread_char_buf;
        ++*bytes_read;
        flags.unread_char_buf_in_use = false;
        --buffer_length;
    } // if

#endif // ifdef CYGFUN_LIBC_STDIO_ungetc

#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
    if (flags.buffering) {

        // need to flush output if we were writing before
        if (!flags.last_buffer_op_was_read) {
            Cyg_ErrNo err = flush_output_unlocked();

            if (ENOERR != err) {
                unlock_me();
                return err;
            }            
        }
            
        cyg_uint8 *buff_to_read_from;
        cyg_ucount32 bytes_available;
    
        bytes_available = io_buf.get_buffer_addr_to_read(
              (cyg_uint8 **)&buff_to_read_from );
        
        cyg_ucount32 count =
            (bytes_available < buffer_length) ? bytes_available : buffer_length;

        if (count) {
            memcpy( user_buffer, buff_to_read_from, count );
            io_buf.set_bytes_read( count );
            *bytes_read += count;
        } // if

    } // if
    else
        
#endif

    if (flags.readbuf_char_in_use && buffer_length) {
        *user_buffer = readbuf_char;
        *bytes_read = 1;
        flags.readbuf_char_in_use = false;
    }


    // if we are unbuffered, we read as much as we can directly from the 
    // file system at this point.
    //
    // unless we do this, we could end up reading byte-by-byte from the filing system
    // due to the readbuf_char scheme.
    if (
#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
        !flags.buffering &&
#endif
        (*bytes_read<buffer_length)) {
        cyg_uint32 len;
        len=buffer_length-*bytes_read;
        read_err = cyg_stdio_read(my_device, user_buffer + *bytes_read, &len);      
        *bytes_read+=len;
    }
    
    position += *bytes_read;
    
    unlock_me();

    return read_err;
} // read()


Cyg_ErrNo
Cyg_StdioStream::read_byte( cyg_uint8 *c )
{
    Cyg_ErrNo err=ENOERR;

    CYG_ASSERTCLASS( this, "Stream object is not a valid stream!" );
    
    if (!lock_me())
        return EBADF;  // assume file is now invalid

    if (!flags.opened_for_read) {
        unlock_me();
        return EINVAL;
    }

# ifdef CYGFUN_LIBC_STDIO_ungetc
    if (flags.unread_char_buf_in_use) {
        *c = unread_char_buf;
        flags.unread_char_buf_in_use = false;
        position++;
        unlock_me();
        return ENOERR;
    } // if
# endif // ifdef CYGFUN_LIBC_STDIO_ungetc

#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
    if (flags.buffering) {
        // need to flush output if we were writing before
        if (!flags.last_buffer_op_was_read)
            err = flush_output_unlocked();

        if (ENOERR != err) {
            unlock_me();
            return err;
        }            
            
        cyg_uint8 *buff_to_read_from;
        cyg_ucount32 bytes_available;
    
        bytes_available=io_buf.get_buffer_addr_to_read(&buff_to_read_from);

        if (bytes_available) {
            *c = *buff_to_read_from;
            io_buf.set_bytes_read(1);
            position++;
        }
        else
            err = EAGAIN;
    } // if
    else
    
#endif


    if (flags.readbuf_char_in_use) {
        *c = readbuf_char;
        flags.readbuf_char_in_use = false;
        position++;
    }
    else
        err = EAGAIN;

    unlock_me();

    return err;
} // read_byte()


Cyg_ErrNo
Cyg_StdioStream::peek_byte( cyg_uint8 *c )
{
    Cyg_ErrNo err=ENOERR;

    CYG_ASSERTCLASS( this, "Stream object is not a valid stream!" );
    
    if (!lock_me())
        return EBADF;  // assume file is now invalid

    if (!flags.opened_for_read) {
        unlock_me();
        return EINVAL;
    }

    // this should really only be called after refill_read_buffer, but just
    // in case
#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
    if (flags.buffering)
        err = flush_output_unlocked();

    if (err != ENOERR)
        return err;

    // we're now reading
    flags.last_buffer_op_was_read = true;
#endif

# ifdef CYGFUN_LIBC_STDIO_ungetc
    if (flags.unread_char_buf_in_use) {
        *c = unread_char_buf;
        unlock_me();
        return ENOERR;
    } // if
# endif // ifdef CYGFUN_LIBC_STDIO_ungetc

#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
    if (flags.buffering) {
        cyg_uint8 *buff_to_read_from;
        cyg_ucount32 bytes_available;
    
        bytes_available=io_buf.get_buffer_addr_to_read(&buff_to_read_from);

        if (bytes_available) {
            *c = *buff_to_read_from;
        }
        else
            err = EAGAIN;
    } // if
    else
    
#endif


    if (flags.readbuf_char_in_use) {
        *c = readbuf_char;
    }
    else
        err = EAGAIN;

    unlock_me();

    return err;
} // peek_byte()


Cyg_ErrNo
Cyg_StdioStream::flush_output_unlocked( void )
{
#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
    Cyg_ErrNo write_err=ENOERR;
    cyg_uint8 *buffer;
    cyg_uint32 len;

    CYG_ASSERTCLASS( this, "Stream object is not a valid stream!" );
    
    if ( flags.last_buffer_op_was_read )
        return ENOERR;

    // first just check that we _can_ write to the device!
    if ( !flags.opened_for_write )
        return EINVAL;

    // shortcut if nothing to do
    if (io_buf.get_buffer_space_used() == 0)
        return ENOERR;
        
    len = io_buf.get_buffer_addr_to_read( (cyg_uint8 **)&buffer );
    
    CYG_ASSERT( len > 0, 
                "There should be data to read but there isn't!");

    write_err = cyg_stdio_write(my_device, buffer, &len);

    // since we're doing a concerted flush, we tell the I/O layer to
    // flush too, otherwise output may just sit there forever
    if (!write_err)
        cyg_stdio_flush( my_device );
    
        // we've just read it all, so just wipe it out
    io_buf.drain_buffer();

    return write_err;

#else // ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO

    CYG_ASSERTCLASS( this, "Stream object is not a valid stream!" );
    
    return ENOERR;

#endif // ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
} // flush_output_unlocked()



Cyg_ErrNo
Cyg_StdioStream::write( const cyg_uint8 *buffer,
                        cyg_ucount32 buffer_length,
                        cyg_ucount32 *bytes_written )
{
    Cyg_ErrNo write_err = ENOERR;

    CYG_ASSERTCLASS( this, "Stream object is not a valid stream!" );
    
    *bytes_written = 0;

    if (!lock_me())
        return EBADF;  // assume file is now invalid

    // first just check that we _can_ write to the device!
    if ( !flags.opened_for_write ) {
        unlock_me();
        return EINVAL;
    }

#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
    if (flags.last_buffer_op_was_read == true) {
#ifdef CYGPKG_LIBC_STDIO_FILEIO
        if ( 0 != io_buf.get_buffer_space_used() )
        {
            off_t newpos = position;
            io_buf.drain_buffer();  // nuke input bytes to prevent confusion
            Cyg_ErrNo err = cyg_stdio_lseek( my_device, &newpos, SEEK_SET );
            if (err) {
                unlock_me();
                return err;
            }
        }
#else
        io_buf.drain_buffer();  // nuke input bytes to prevent confusion
#endif
    }

    flags.last_buffer_op_was_read = false;

    if (!flags.buffering) {
#endif
        cyg_uint32 len = buffer_length;

        write_err = cyg_stdio_write(my_device, buffer, &len);

        *bytes_written = len;

#ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO
    } // if
    else {
        cyg_ucount32 bytes_available;
        cyg_ucount32 bytes_to_write;
        cyg_ucount32 newline_pos;
        cyg_uint8 *write_addr;
        cyg_bool must_flush = false;
        
        while ( buffer_length > 0 ) {
            bytes_available =
                io_buf.get_buffer_addr_to_write( &write_addr );
            
            // we need to flush if we've no room or the buffer has an up
            // and coming newline
            if ( !bytes_available || must_flush ) {
                write_err = flush_output_unlocked();
                
                // harmless even if there was an error
                bytes_available =
                    io_buf.get_buffer_addr_to_write( &write_addr );

                CYG_ASSERT( bytes_available > 0,
                            "Help! still no bytes available in "
                            "write buffer" );
            } // if
            
            if (write_err) {
                unlock_me();
                return write_err;
            } // if
            
            // choose the lower of the buffer available and the length
            // to write
            bytes_to_write=(bytes_available < buffer_length) 
                ? bytes_available
                : buffer_length;
        
            // if we're line buffered, we may want want to flush if there's
            // a newline character, so lets find out
        
            if (flags.line_buffering) {
                for (newline_pos=0;
                     newline_pos<bytes_to_write;
                     newline_pos++) {
                    if (buffer[newline_pos] == '\n') {
                        break;
                    } // if
                } // for
                // if we didn't reach the end
                if (newline_pos != bytes_to_write) {
                    // shrink bytes_to_write down to the bit we need to
                    // flush including the newline itself
                    bytes_to_write = newline_pos + 1;
                    must_flush = true;
                } // if
            } // if
            
            memcpy( write_addr, buffer, bytes_to_write );
            
            *bytes_written += bytes_to_write;
            buffer += bytes_to_write;
            buffer_length -= bytes_to_write;
            io_buf.set_bytes_written( bytes_to_write );

            position += bytes_to_write;
            
        } // while
        
        if ( must_flush ) {
            write_err = flush_output_unlocked();
        } // if
    } // else
#endif // ifdef CYGSEM_LIBC_STDIO_WANT_BUFFERED_IO

    unlock_me();

    return write_err;
} // write()

//
// class Cyg_OutputStream
//

Cyg_ErrNo
Cyg_OutputStream::write( const cyg_uint8 *buffer, cyg_ucount32 buffer_length,
    cyg_ucount32 *bytes_written )
{
    CYG_FAIL("Cyg_OutputStream::write(): pure virtual called");
    return ENOSYS;
}

Cyg_ErrNo
Cyg_OutputStream::get_error( void )
{
    CYG_FAIL("Cyg_OutputStream::get_error(): pure virtual called");
    return ENOSYS;
}



// EOF stream.cxx