]> git.buserror.net Git - polintos/scott/priv.git/blob - lib/c++/stlport/fstream.cpp
Add STLport 5.1.4
[polintos/scott/priv.git] / lib / c++ / stlport / fstream.cpp
1 /*
2  * Copyright (c) 1999
3  * Silicon Graphics Computer Systems, Inc.
4  *
5  * Copyright (c) 1999
6  * Boris Fomitchev
7  *
8  * This material is provided "as is", with absolutely no warranty expressed
9  * or implied. Any use is at your own risk.
10  *
11  * Permission to use or copy this software for any purpose is hereby granted
12  * without fee, provided the above notices are retained on all copies.
13  * Permission to modify the code and to distribute modified code is granted,
14  * provided the above notices are retained, and a notice that the code was
15  * modified is included with the above copyright notice.
16  *
17  */
18
19
20 #include "stlport_prefix.h"
21
22 #if defined  (__SUNPPRO_CC)  && !defined (_STLP_NO_NEW_C_HEADERS)
23 #  include <time.h>
24 // For sunpro, it chokes if time.h is included through stat.h
25 #endif
26
27 #include <fstream>
28
29 #ifdef __CYGWIN__
30 #  define __int64 long long
31 #endif
32
33 #if defined (_STLP_USE_UNIX_IO)
34 extern "C" {
35 // open/close/read/write
36 #  include <sys/stat.h>           // For stat
37 #  if !defined (_CRAY) && ! defined (__EMX__)
38 #    include <sys/mman.h>           // For mmap
39 #  endif
40
41 //  on HP-UX 11, this one contradicts with pthread.h on pthread_atfork, unless we unset this
42 #  if defined (__hpux) && defined (__GNUC__)
43 #    undef _INCLUDE_POSIX1C_SOURCE
44 #  endif
45
46 #  include <unistd.h>
47 #  include <fcntl.h>
48 }
49 #  ifdef __APPLE__
50 #    include <sys/sysctl.h>
51 #  endif
52 #elif defined (_STLP_USE_WIN32_IO)
53 #  define WIN32_LEAN_AND_MEAN
54 #  include <windows.h>
55
56 #  ifdef __BORLANDC__
57 #      include <cfcntl.h>            // For _O_RDONLY, etc
58 #    include <sys/stat.h>         // For _fstat
59 #  elif !defined(_STLP_WCE)
60 #    include <io.h>               // For _get_osfhandle
61 #    include <fcntl.h>            // For _O_RDONLY, etc
62 #    include <sys/stat.h>         // For _fstat
63 #  endif
64 #  define _TEXTBUF_SIZE 0x1000
65 #elif defined (_STLP_USE_UNIX_EMULATION_IO)
66 #  if defined( __MSL__ )
67 #    include <unistd.h>
68 #  else
69 #    include <io.h>
70 #  endif
71 #  include <fcntl.h>
72 #  include <sys/stat.h>
73 #elif defined (_STLP_USE_STDIO_IO)
74 #  include <cstdio>
75 #  if !(defined(__MRC__) || defined(__SC__) || defined(__ISCPP__) )
76 extern "C" {
77 #    include <sys/stat.h>
78 }
79 #  endif
80 #  if defined( __MSL__ )
81 #    include <unix.h>
82 #  endif
83 #  if defined(__ISCPP__)
84 #    include <c_locale_is/filestat.h>
85 #  endif
86 #  if defined(__BEOS__) && defined(__INTEL__)
87 #    include <fcntl.h>
88 #    include <sys/stat.h>         // For _fstat
89 #    define _S_IREAD S_IREAD
90 #    define _S_IWRITE S_IWRITE
91 #    define _S_IFREG S_IFREG
92 #  endif
93 #else
94 #  error "Configure i/o !"
95 #endif
96
97 #if defined (_STLP_USE_WIN32_IO)
98 const _STLP_fd INVALID_STLP_FD = INVALID_HANDLE_VALUE;
99 #  if !defined (INVALID_SET_FILE_POINTER)
100 #    define INVALID_SET_FILE_POINTER 0xffffffff
101 #  endif
102 #elif defined (_STLP_USE_UNIX_EMULATION_IO) || defined (_STLP_USE_STDIO_IO) || defined (_STLP_USE_UNIX_IO)
103 const _STLP_fd INVALID_STLP_FD = -1;
104 #else
105 #  error "Configure i/o !"
106 #endif
107
108 // map permission masks
109 #if defined (_STLP_USE_UNIX_EMULATION_IO) || defined (_STLP_USE_STDIO_IO)
110 #  ifndef S_IRUSR
111 #    define S_IRUSR _S_IREAD
112 #    define S_IWUSR _S_IWRITE
113 #    define S_IRGRP _S_IREAD
114 #    define S_IWGRP _S_IWRITE
115 #    define S_IROTH _S_IREAD
116 #    define S_IWOTH _S_IWRITE
117 #  endif
118 #  ifndef O_RDONLY
119 #    define O_RDONLY _O_RDONLY
120 #    define O_WRONLY _O_WRONLY
121 #    define O_RDWR   _O_RDWR
122 #    define O_APPEND _O_APPEND
123 #    define O_CREAT  _O_CREAT
124 #    define O_TRUNC  _O_TRUNC
125 #    define O_TEXT   _O_TEXT
126 #    define O_BINARY _O_BINARY
127 #  endif
128
129 #  ifdef __MSL__
130 #    define _O_TEXT 0x0
131 #    if !defined( O_TEXT )
132 #      define O_TEXT _O_TEXT
133 #    endif
134 #    define _S_IFREG S_IFREG
135 #    define S_IREAD        S_IRUSR
136 #    define S_IWRITE       S_IWUSR
137 #    define S_IEXEC        S_IXUSR
138 #    define _S_IWRITE S_IWRITE
139 #    define _S_IREAD S_IREAD
140 #    define _open open
141 #    define _lseek lseek
142 #    define _close close
143 #    define _read read
144 #    define _write write
145 #  endif
146 #endif
147
148 #ifndef O_ACCMODE
149 #  define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
150 #endif
151
152 #include "fstream_impl.h"
153
154 #ifdef _STLP_LONG_LONG
155 #  define ULL(x) ((unsigned _STLP_LONG_LONG)x)
156 #elif defined(__MRC__) || defined(__SC__)    //*TY 02/25/2000 - added support for MPW compilers
157 #  include <Math64.h>
158 #  define ULL(x) (U64SetU(x))
159 #elif defined(__ISCPP__)
160 #  include "uint64.h"
161 #else
162 #  error "there should be some long long type on the system!"
163 #endif
164
165 _STLP_BEGIN_NAMESPACE
166 // Compare with streamoff definition in stl/char_traits.h!
167
168 #ifdef _STLP_USE_DEFAULT_FILE_OFFSET
169 #  define FOPEN fopen
170 #  define FSEEK fseek
171 #  define FSTAT fstat
172 #  define STAT  stat
173 #  define FTELL ftell
174 #  define LSEEK lseek
175 #  define MMAP  mmap
176 #  define OPEN  open
177 #elif defined(_LARGEFILE_SOURCE) || defined(_LARGEFILE64_SOURCE) /* || defined(__USE_FILE_OFFSET64) */ \
178       /* || (defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)) */ /* || defined(__sgi) */
179 #  define FOPEN fopen64
180 #  define FSEEK fseeko64
181 #  define FSTAT fstat64
182 #  define STAT  stat64
183 #  define FTELL ftello64
184 #  define LSEEK lseek64
185 #  define MMAP  mmap64
186 #  define OPEN  open64
187 #else
188 #  define OPEN  open
189 #  define FSEEK fseek
190 #  define FSTAT fstat
191 #  define STAT  stat
192 #  define FTELL ftell
193 #  define LSEEK lseek
194 #  define MMAP  mmap
195 #  define OPEN  open
196 #endif
197 #ifdef _STLP_USE_UNIX_IO
198 #  ifndef MAP_FAILED /* MMAP failure return code */
199 #    define MAP_FAILED -1
200 #  endif
201 #elif defined (_STLP_USE_UNIX_EMULATION_IO)
202 #  define LSEEK _lseek
203 #endif
204
205 #if !defined(__MSL__) && !defined(__MRC__) && !defined(__SC__) && !defined(_STLP_WCE)    //*TY 04/15/2000 - exclude mpw compilers also
206 static ios_base::openmode flag_to_openmode(int mode) {
207   ios_base::openmode ret = ios_base::__default_mode;
208
209   switch(mode & O_ACCMODE) {
210   case O_RDONLY:
211     ret = ios_base::in; break;
212   case O_WRONLY:
213     ret = ios_base::out; break;
214   case O_RDWR:
215     ret = ios_base::in | ios_base::out; break;
216   }
217
218   if (mode & O_APPEND)
219     ret |= ios_base::app;
220
221 #  if defined (_STLP_USE_WIN32_IO)
222   if (mode & O_BINARY)
223     ret |= ios_base::binary;
224 #  endif
225
226   return ret;
227 }
228 #endif /* MSL */
229
230 _STLP_MOVE_TO_PRIV_NAMESPACE
231
232 // Helper functions for _Filebuf_base.
233
234 bool __is_regular_file(_STLP_fd fd) {
235
236 #if defined (_STLP_UNIX)
237
238   struct STAT buf;
239   return FSTAT(fd, &buf) == 0 && S_ISREG(buf.st_mode);
240
241 #elif defined(__MRC__) || defined(__SC__)    //*TY 02/25/2000 - added support for MPW compilers
242
243 #  pragma unused(fd)
244   return true;  // each file is a regular file under mac os, isn't it? (we don't have fstat())
245
246 #elif defined(_STLP_USE_UNIX_EMULATION_IO) || defined (_STLP_USE_STDIO_IO)
247
248   struct STAT buf;
249   return FSTAT(fd, &buf) == 0 && (buf.st_mode & _S_IFREG) != 0 ;
250
251 #elif defined (_STLP_USE_WIN32_IO) && !defined(_STLP_WCE)
252
253   return (GetFileType(fd) & ~FILE_TYPE_REMOTE) == FILE_TYPE_DISK;
254
255 #else
256   (void)fd;    // dwa 4/27/00 - suppress unused parameter warning
257   return false;
258 #endif
259 }
260
261 // Number of characters in the file.
262 streamoff __file_size(_STLP_fd fd) {
263   streamoff ret = 0;
264
265 #if defined (_STLP_UNIX)
266
267   struct STAT buf;
268   if (FSTAT(fd, &buf) == 0 && S_ISREG(buf.st_mode))
269     ret = buf.st_size > 0 ? buf.st_size : 0;
270
271 #elif defined(__MRC__) || defined(__SC__)    //*TY 02/25/2000 - added support for MPW compilers
272
273 #  pragma unused(fd)
274
275 #elif defined(_STLP_USE_UNIX_EMULATION_IO) || defined (_STLP_USE_STDIO_IO)
276
277   struct STAT buf;
278   if (FSTAT(fd, &buf) == 0 && (buf.st_mode & _S_IFREG) != 0)
279     ret = buf.st_size > 0 ? buf.st_size : 0;
280
281 #elif defined (_STLP_USE_WIN32_IO)
282
283  LARGE_INTEGER li;
284  li.LowPart = GetFileSize(fd, (unsigned long*) &li.HighPart);
285  if (li.LowPart != INVALID_FILE_SIZE || GetLastError() == NO_ERROR)
286    ret = li.QuadPart;
287
288 #else
289   (void)fd;    // dwa 4/27/00 - suppress unused parameter warning
290 #endif
291   return ret;
292 }
293
294 _STLP_MOVE_TO_STD_NAMESPACE
295
296 // Visual C++ and Intel use this, but not Metrowerks
297 // Also MinGW, msvcrt.dll (but not crtdll.dll) dependent version
298 #if (!defined (__MSL__) && !defined (_STLP_WCE) && defined (_STLP_MSVC_LIB) && defined (_WIN32)) || \
299     (defined (__MINGW32__) && defined (__MSVCRT__))
300
301 // fcntl(fileno, F_GETFL) for Microsoft library
302 // 'semi-documented' defines:
303 #  define IOINFO_L2E          5
304 #  define IOINFO_ARRAY_ELTS   (1 << IOINFO_L2E)
305 #  define _pioinfo(i) ( __pioinfo[(i) >> IOINFO_L2E] + \
306               ((i) & (IOINFO_ARRAY_ELTS - 1)) )
307 #  define FAPPEND         0x20    // O_APPEND flag
308 #  define FTEXT           0x80    // O_TEXT flag
309 // end of 'semi-documented' defines
310
311 // 'semi-documented' internal structure
312 extern "C" {
313   struct ioinfo {
314     long osfhnd;    // the real os HANDLE
315     char osfile;    // file handle flags
316     char pipech;    // pipe buffer
317 #  if defined (_MT)
318     // multi-threaded locking
319     int lockinitflag;
320     CRITICAL_SECTION lock;
321 #  endif  /* _MT */
322   };
323 #  if defined (__MINGW32__)
324  __MINGW_IMPORT ioinfo * __pioinfo[];
325 #  else
326   extern _CRTIMP ioinfo * __pioinfo[];
327 #  endif
328 } // extern "C"
329 // end of 'semi-documented' declarations
330
331 static ios_base::openmode _get_osfflags(int fd, HANDLE oshandle) {
332   char dosflags = 0;
333   if (fd >= 0)
334     dosflags = _pioinfo(fd)->osfile;
335   //else
336     //the file will be considered as open in binary mode with no append attribute
337   // end of 'semi-documented' stuff
338
339   int mode = 0;
340   if (dosflags & FAPPEND)
341     mode |= O_APPEND;
342
343   if (dosflags & FTEXT)
344     mode |= O_TEXT;
345   else
346     mode |= O_BINARY;
347
348   // For Read/Write access we have to guess
349   DWORD dummy, dummy2;
350   BOOL writeOk = WriteFile(oshandle, &dummy2, 0, &dummy, 0);
351   BOOL readOk = ReadFile(oshandle, &dummy2, 0, &dummy, NULL);
352   if (writeOk && readOk)
353     mode |= O_RDWR;
354   else if (readOk)
355     mode |= O_RDONLY;
356   else
357     mode |= O_WRONLY;
358
359   return flag_to_openmode(mode);
360 }
361
362 #elif defined (__DMC__)
363
364 #  define FHND_APPEND 0x04
365 #  define FHND_DEVICE 0x08
366 #  define FHND_TEXT   0x10
367
368 extern "C" unsigned char __fhnd_info[_NFILE];
369
370 static ios_base::openmode _get_osfflags(int fd, HANDLE oshandle) {
371   int mode = 0;
372
373   if (__fhnd_info[fd] & FHND_APPEND)
374     mode |= O_APPEND;
375
376   if (__fhnd_info[fd] & FHND_TEXT == 0)
377     mode |= O_BINARY;
378
379   for (FILE *fp = &_iob[0]; fp < &_iob[_NFILE]; fp++) {
380     if ((fileno(fp) == fd) && (fp->_flag & (_IOREAD | _IOWRT | _IORW))) {
381       const int osflags = fp->_flag;
382
383       if ((osflags & _IOREAD) && !(osflags & _IOWRT) && !(osflags & _IORW))
384         mode |= O_RDONLY;
385       else if ((osflags & _IOWRT) && !(osflags & _IOREAD) && !(osflags & _IORW))
386         mode |= O_WRONLY;
387       else
388         mode |= O_RDWR;
389       break;
390     }
391   }
392
393   return flag_to_openmode(mode);
394 }
395 #endif
396
397 size_t _Filebuf_base::_M_page_size = 4096;
398
399 _Filebuf_base::_Filebuf_base()
400   : _M_file_id(INVALID_STLP_FD),
401 #if defined (_STLP_USE_WIN32_IO)
402     _M_view_id(0),
403 #endif
404     _M_openmode(0),
405     _M_is_open(false),
406     _M_should_close(false)
407 {}
408
409 void _Filebuf_base::_S_initialize() {
410 #if defined (_STLP_UNIX)  && !defined (__DJGPP) && !defined (_CRAY)
411 #  if defined (__APPLE__)
412   int mib[2];
413   size_t pagesize, len;
414   mib[0] = CTL_HW;
415   mib[1] = HW_PAGESIZE;
416   len = sizeof(pagesize);
417   sysctl(mib, 2, &pagesize, &len, NULL, 0);
418   _M_page_size = pagesize;
419 #  elif defined (__DJGPP) && defined (_CRAY)
420   _M_page_size = BUFSIZ;
421 #  else
422   _M_page_size = sysconf(_SC_PAGESIZE);
423 #  endif
424 #elif defined (_STLP_USE_WIN32_IO)
425   SYSTEM_INFO SystemInfo;
426   GetSystemInfo(&SystemInfo);
427   _M_page_size = SystemInfo.dwPageSize;
428   // might be .dwAllocationGranularity
429 #endif
430 }
431
432 // Return the size of the file.  This is a wrapper for stat.
433 // Returns zero if the size cannot be determined or is ill-defined.
434 streamoff _Filebuf_base::_M_file_size() {
435   return _STLP_PRIV __file_size(_M_file_id);
436 }
437
438 bool _Filebuf_base::_M_open(const char* name, ios_base::openmode openmode,
439                             long permission) {
440   _STLP_fd file_no;
441
442   if (_M_is_open)
443     return false;
444
445 #if defined (_STLP_USE_UNIX_IO) || defined (_STLP_USE_UNIX_EMULATION_IO)
446   int flags = 0;
447
448   // Unix makes no distinction between text and binary files.
449   switch(openmode & (~ios_base::ate & ~ios_base::binary)) {
450   case ios_base::out:
451   case ios_base::out | ios_base::trunc:
452     flags = O_WRONLY | O_CREAT | O_TRUNC;
453     break;
454   case ios_base::out | ios_base::app:
455     flags = O_WRONLY | O_CREAT | O_APPEND;
456     break;
457   case ios_base::in:
458     flags = O_RDONLY;
459     permission = 0;             // Irrelevant unless we're writing.
460     break;
461   case ios_base::in | ios_base::out:
462     flags = O_RDWR;
463     break;
464   case ios_base::in | ios_base::out | ios_base::trunc:
465     flags = O_RDWR | O_CREAT | O_TRUNC;
466     break;
467   default:                      // The above are the only combinations of
468     return false;               // flags allowed by the C++ standard.
469   }
470
471 #  if defined (_STLP_USE_UNIX_EMULATION_IO)
472   if (openmode & ios_base::binary)
473     flags |= O_BINARY;
474   else
475     flags |= O_TEXT;
476
477   file_no = _open(name, flags, permission);
478 #  else
479   file_no = OPEN(name, flags, permission);
480 #  endif /* _STLP_USE_UNIX_EMULATION_IO */
481
482   if (file_no < 0)
483     return false;
484
485   _M_is_open = true;
486
487   if (openmode & ios_base::ate)
488     if (LSEEK(file_no, 0, SEEK_END) == -1)
489       _M_is_open = false;
490
491 #elif defined (_STLP_USE_STDIO_IO)
492   // use FILE-based i/o
493   const char* flags;
494
495   switch(openmode & (~ios_base::ate)) {
496   case ios_base::out:
497   case ios_base::out | ios_base::trunc:
498     flags = "w";
499     break;
500
501   case ios_base::out | ios_base::binary:
502   case ios_base::out | ios_base::trunc | ios_base::binary:
503     flags = "wb";
504     break;
505
506   case ios_base::out | ios_base::app:
507     flags = "a";
508     break;
509
510   case ios_base::out | ios_base::app | ios_base::binary:
511     flags = "ab";
512     break;
513
514   case ios_base::in:
515     flags = "r";
516     break;
517
518   case ios_base::in | ios_base::binary:
519     flags = "rb";
520     break;
521
522   case ios_base::in | ios_base::out:
523     flags = "r+";
524     break;
525
526   case ios_base::in | ios_base::out | ios_base::binary:
527     flags = "r+b";
528     break;
529
530
531   case ios_base::in | ios_base::out | ios_base::trunc:
532     flags = "w+";
533     break;
534
535   case ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary:
536     flags = "w+b";
537     break;
538
539   default:                      // The above are the only combinations of
540     return false;               // flags allowed by the C++ standard.
541   }
542
543   // fbp : TODO : set permissions !
544   (void)permission; // currently unused    //*TY 02/26/2000 - added to suppress warning message
545   _M_file = FOPEN(name, flags);
546
547   if (_M_file) {
548     file_no = fileno(_M_file);
549   }
550   else
551     return false;
552
553   // unset buffering immediately
554   setbuf(_M_file, 0);
555
556   _M_is_open = true;
557
558   if (openmode & ios_base::ate) {
559     if (FSEEK(_M_file, 0, SEEK_END) == -1)
560       _M_is_open = false;
561   }
562
563 #elif defined (_STLP_USE_WIN32_IO)
564   DWORD dwDesiredAccess, dwCreationDisposition;
565   bool doTruncate = false;
566
567   switch (openmode & (~ios_base::ate & ~ios_base::binary)) {
568   case ios_base::out:
569   case ios_base::out | ios_base::trunc:
570     dwDesiredAccess = GENERIC_WRITE;
571     dwCreationDisposition = OPEN_ALWAYS;
572     // boris : even though it is very non-intuitive, standard
573     // requires them both to behave same.
574     doTruncate = true;
575     break;
576   case ios_base::out | ios_base::app:
577     dwDesiredAccess = GENERIC_WRITE;
578     dwCreationDisposition = OPEN_ALWAYS;
579     break;
580   case ios_base::in:
581     dwDesiredAccess = GENERIC_READ;
582     dwCreationDisposition = OPEN_EXISTING;
583     permission = 0;             // Irrelevant unless we're writing.
584     break;
585   case ios_base::in | ios_base::out:
586     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
587     dwCreationDisposition = OPEN_EXISTING;
588     break;
589   case ios_base::in | ios_base::out | ios_base::trunc:
590     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
591     dwCreationDisposition = OPEN_ALWAYS;
592     doTruncate = true;
593     break;
594   default:                      // The above are the only combinations of
595     return false;               // flags allowed by the C++ standard.
596   }
597
598   DWORD dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
599
600 #  if defined(_STLP_USE_WIDE_INTERFACE)
601     file_no = CreateFile (_STLP_PRIV __ASCIIToWide(name).c_str(),
602 #  else
603     file_no = CreateFileA(name,
604 #  endif
605                           dwDesiredAccess, dwShareMode, 0,
606                           dwCreationDisposition, permission, 0);
607
608   if (file_no == INVALID_STLP_FD)
609     return false;
610
611   if ((doTruncate && SetEndOfFile(file_no) == 0) ||
612       (((openmode & ios_base::ate) != 0) &&
613        (SetFilePointer(file_no, 0, NULL, FILE_END) == INVALID_SET_FILE_POINTER))) {
614     CloseHandle(file_no);
615     return false;
616   }
617
618   _M_is_open = true;
619
620 #else
621 #  error "Port!"
622 #endif /* __unix */
623
624   _M_file_id = file_no;
625   _M_should_close = _M_is_open;
626   _M_openmode = openmode;
627
628   if (_M_is_open)
629     _M_regular_file = _STLP_PRIV __is_regular_file(_M_file_id);
630
631   return (_M_is_open != 0);
632 }
633
634
635 bool _Filebuf_base::_M_open(const char* name, ios_base::openmode openmode) {
636   // This doesn't really grant everyone in the world read/write
637   // access.  On Unix, file-creation system calls always clear
638   // bits that are set in the umask from the permissions flag.
639 #ifdef _STLP_USE_WIN32_IO
640   return this->_M_open(name, openmode, FILE_ATTRIBUTE_NORMAL);
641 #elif defined(__MRC__) || defined(__SC__)    //*TY 02/26/2000 - added support for MPW compilers
642   return this->_M_open(name, openmode, 0);
643 #else
644   return this->_M_open(name, openmode, S_IRUSR | S_IWUSR | S_IRGRP |
645                                        S_IWGRP | S_IROTH | S_IWOTH);
646 #endif
647 }
648
649
650 #if defined (_STLP_USE_WIN32_IO)
651 bool _Filebuf_base::_M_open(_STLP_fd __id, ios_base::openmode init_mode) {
652 #  if (defined (_STLP_MSVC_LIB) && !defined (_STLP_WCE)) || \
653       (defined (__MINGW32__) && defined (__MSVCRT__)) || defined (__DMC__)
654
655   if (_M_is_open || __id == INVALID_STLP_FD)
656     return false;
657
658   if (init_mode != ios_base::__default_mode)
659     _M_openmode = init_mode;
660   else
661     _M_openmode = _get_osfflags(-1, __id);
662
663   _M_is_open = true;
664   _M_file_id = __id;
665   _M_should_close = false;
666   _M_regular_file = _STLP_PRIV __is_regular_file(_M_file_id);
667
668   return true;
669 #  else
670   (void)__id;
671   (void)init_mode;    // dwa 4/27/00 - suppress unused parameter warning
672
673   // not available for the API
674   return false;
675
676 #  endif
677 }
678 #endif /* _STLP_USE_WIN32_IO */
679
680 // Associated the filebuf with a file descriptor pointing to an already-
681 // open file.  Mode is set to be consistent with the way that the file
682 // was opened.
683 bool _Filebuf_base::_M_open(int file_no, ios_base::openmode init_mode) {
684   if (_M_is_open || file_no < 0)
685     return false;
686
687 #if defined (_STLP_UNIX)
688   (void)init_mode;    // dwa 4/27/00 - suppress unused parameter warning
689   int mode ;
690   mode = fcntl(file_no, F_GETFL);
691
692   if (mode == -1)
693     return false;
694
695   _M_openmode = flag_to_openmode(mode);
696   _M_file_id = file_no;
697 #elif defined(__MRC__) || defined(__SC__)    //*TY 02/26/2000 - added support for MPW compilers
698   (void)init_mode;    // dwa 4/27/00 - suppress unused parameter warning
699   switch (_iob[file_no]._flag & (_IOREAD|_IOWRT|_IORW) )
700   {
701   case _IOREAD:
702     _M_openmode = ios_base::in; break;
703   case _IOWRT:
704     _M_openmode = ios_base::out; break;
705   case _IORW:
706     _M_openmode = ios_base::in | ios_base::out; break;
707   default:
708     return false;
709   }
710   _M_file_id = file_no;
711 #elif defined (_STLP_USE_UNIX_EMULATION_IO) || defined (_STLP_USE_STDIO_IO)
712   (void)init_mode;    // dwa 4/27/00 - suppress unused parameter warning
713   int mode ;
714   struct STAT buf;
715   if (FSTAT(file_no, &buf) != 0)
716     return false;
717   mode = buf.st_mode;
718
719   switch(mode & (_S_IWRITE | _S_IREAD) ) {
720   case _S_IREAD:
721     _M_openmode = ios_base::in; break;
722   case _S_IWRITE:
723     _M_openmode = ios_base::out; break;
724   case (_S_IWRITE | _S_IREAD):
725     _M_openmode = ios_base::in | ios_base::out; break;
726   default:
727     return false;
728   }
729   _M_file_id = file_no;
730 #elif (defined (_STLP_USE_WIN32_IO) && defined (_STLP_MSVC_LIB) && !defined (_STLP_WCE) ) || \
731       (defined (__MINGW32__) && defined (__MSVCRT__)) || \
732        defined (__DMC__)
733
734   HANDLE oshandle = (HANDLE)_get_osfhandle(file_no);
735   if (oshandle == INVALID_STLP_FD)
736     return false;
737
738   if (init_mode != ios_base::__default_mode)
739     _M_openmode = init_mode;
740   else
741     _M_openmode = _get_osfflags(file_no, oshandle);
742
743   _M_file_id = oshandle;
744 #else
745   (void)init_mode;    // dwa 4/27/00 - suppress unused parameter warning
746   // not available for the API
747 #  define _STLP_NO_IMPLEMENTATION
748 #endif
749
750 #if !defined (_STLP_NO_IMPLEMENTATION)
751   _M_is_open = true;
752   _M_should_close = false;
753   _M_regular_file = _STLP_PRIV __is_regular_file(_M_file_id);
754   return true;
755 #else
756 #  undef _STLP_NO_IMPLEMENTATION
757   return false;
758 #endif
759 }
760
761 bool _Filebuf_base::_M_close() {
762   if (!_M_is_open)
763     return false;
764
765   bool ok;
766
767   if (!_M_should_close)
768     ok = true;
769   else {
770
771 #if defined (_STLP_USE_UNIX_IO)
772
773     ok = (close(_M_file_id) == 0);
774
775 #elif defined (_STLP_USE_UNIX_EMULATION_IO)
776
777     ok = (_close(_M_file_id) == 0);
778
779 #elif defined (_STLP_USE_STDIO_IO)
780
781     ok = (fclose(_M_file) == 0);
782
783 #elif defined (_STLP_USE_WIN32_IO)
784
785     if (_M_file_id != INVALID_STLP_FD) {
786       ok = (CloseHandle(_M_file_id) != 0);
787     }
788     else {
789       ok = false;
790     }
791
792 #else
793
794     ok = false;
795
796 #endif /* _STLP_USE_UNIX_IO */
797   }
798
799   _M_is_open = _M_should_close = false;
800   _M_openmode = 0;
801   return ok;
802 }
803
804
805 #define _STLP_LF 10
806 #define _STLP_CR 13
807 #define _STLP_CTRLZ 26
808
809 // Read up to n characters into a buffer.  Return value is number of
810 // characters read.
811 ptrdiff_t _Filebuf_base::_M_read(char* buf, ptrdiff_t n) {
812 #if defined (_STLP_USE_UNIX_IO)
813
814   return read(_M_file_id, buf, n);
815
816 #elif defined (_STLP_USE_UNIX_EMULATION_IO)
817
818   return _read(_M_file_id, buf, n);
819
820 #elif defined (_STLP_USE_WIN32_IO)
821   ptrdiff_t readen = 0;
822   //Here cast to size_t is safe as n cannot be negative.
823   size_t chunkSize = (min)(size_t(0xffffffff), __STATIC_CAST(size_t, n));
824   // The following, while validating that we are still able to extract chunkSize
825   // charaters to the buffer, avoids extraction of too small chunk of datas
826   // which would be counter performant.
827   while (__STATIC_CAST(size_t, (n - readen)) >= chunkSize) {
828     DWORD NumberOfBytesRead;
829     ReadFile(_M_file_id, buf + readen, __STATIC_CAST(DWORD, chunkSize), &NumberOfBytesRead, 0);
830
831     if (NumberOfBytesRead == 0)
832       break;
833
834     if (!(_M_openmode & ios_base::binary)) {
835       // translate CR-LFs to LFs in the buffer
836       char *to = buf + readen;
837       char *from = to;
838       char *last = from + NumberOfBytesRead - 1;
839       for (; from <= last && *from != _STLP_CTRLZ; ++from) {
840         if (*from != _STLP_CR)
841           *to++ = *from;
842         else { // found CR
843           if (from < last) { // not at buffer end
844             if (*(from + 1) != _STLP_LF)
845               *to++ = _STLP_CR;
846           }
847           else { // last char is CR, peek for LF
848             char peek = ' ';
849             DWORD NumberOfBytesPeeked;
850             ReadFile(_M_file_id, (LPVOID)&peek, 1, &NumberOfBytesPeeked, 0);
851             if (NumberOfBytesPeeked != 0) {
852               if (peek != _STLP_LF) { //not a <CR><LF> combination
853                 *to++ = _STLP_CR;
854                 if ((to < buf + n) && (peek != _STLP_CR))
855                   //We have enough place to store peek and it is no a special
856                   //_STLP_CR character, we can store it.
857                   *to++ = peek;
858                 else
859                   SetFilePointer(_M_file_id, (LONG)-1, 0, SEEK_CUR);
860               }
861               else {
862                 // A <CR><LF> combination, we keep the <LF>:
863                 *to++ = _STLP_LF;
864               }
865             }
866             else {
867               /* This case is tedious, we could
868                *  - put peek back in the file but this would then generate an infinite loop
869                *  - report an error as we don't know if in a future call to ReadFile we won't then
870                *    get a <LF>. Doing so would make all files with a <CR> last an invalid file
871                *    for STLport, a hard solution for STLport clients.
872                *  - store the <CR> in the returned buffer, the chosen solution, even if in this
873                *    case we could miss a <CR><LF> combination.
874                */
875               *to++ = _STLP_CR;
876             }
877           }
878         } // found CR
879       } // for
880       // seek back to TEXT end of file if hit CTRL-Z
881       if (from <= last) // terminated due to CTRLZ
882         SetFilePointer(_M_file_id, (LONG)((last+1) - from), 0, SEEK_CUR);
883       readen += to - (buf + readen);
884     }
885     else
886       readen += NumberOfBytesRead;
887   }
888   return readen;
889
890 #elif defined (_STLP_USE_STDIO_IO)
891
892   return fread(buf, 1, n, _M_file);
893
894 #else
895 #  error "Port!"
896 #endif /* __unix */
897 }
898
899 // Write n characters from a buffer.  Return value: true if we managed
900 // to write the entire buffer, false if we didn't.
901 bool _Filebuf_base::_M_write(char* buf, ptrdiff_t n) {
902   for (;;) {
903     ptrdiff_t written;
904
905 #if defined (_STLP_USE_UNIX_IO)
906
907     written = write(_M_file_id, buf, n);
908
909 #elif defined (_STLP_USE_UNIX_EMULATION_IO)
910
911     written = _write(_M_file_id, buf, n);
912
913 #elif defined (_STLP_USE_WIN32_IO)
914
915     //In the following implementation we are going to cast most of the ptrdiff_t
916     //values in size_t to work with coherent unsigned values. Doing so make code
917     //more simple especially in the min function call.
918
919     // In append mode, every write does an implicit seek to the end
920     // of the file.
921     if (_M_openmode & ios_base::app)
922       _M_seek(0, ios_base::end);
923
924     if (_M_openmode & ios_base::binary) {
925       // binary mode
926       size_t bytes_to_write = (size_t)n;
927       DWORD NumberOfBytesWritten;
928       written = 0;
929       for (; bytes_to_write != 0;) {
930         WriteFile(_M_file_id, buf + written,
931                   __STATIC_CAST(DWORD, (min)(size_t(0xffffffff), bytes_to_write)),
932                   &NumberOfBytesWritten, 0);
933         if (NumberOfBytesWritten == 0)
934           return false;
935         bytes_to_write -= NumberOfBytesWritten;
936         written += NumberOfBytesWritten;
937       }
938     }
939     else {
940       char textbuf[_TEXTBUF_SIZE + 1]; // extra 1 in case LF at end
941       char * nextblock = buf, * ptrtextbuf = textbuf;
942       char * endtextbuf = textbuf + _TEXTBUF_SIZE;
943       char * endblock = buf + n;
944       ptrdiff_t nextblocksize = (min) (n, (ptrdiff_t)_TEXTBUF_SIZE);
945       char * nextlf;
946
947       while ( (nextblocksize > 0) &&
948               (nextlf = (char *)memchr(nextblock, _STLP_LF, nextblocksize)) != 0) {
949         ptrdiff_t linelength = nextlf - nextblock;
950         memcpy(ptrtextbuf, nextblock, linelength);
951         ptrtextbuf += linelength;
952         nextblock += (linelength + 1);
953         * ptrtextbuf ++ = _STLP_CR;
954         * ptrtextbuf ++ = _STLP_LF;
955         nextblocksize = (min) (ptrdiff_t(endblock - nextblock),
956                                (max) (ptrdiff_t(0), ptrdiff_t(endtextbuf - ptrtextbuf)));
957       }
958       // write out what's left, > condition is here since for LF at the end ,
959       // endtextbuf may get < ptrtextbuf ...
960       if (nextblocksize > 0) {
961         memcpy(ptrtextbuf, nextblock, nextblocksize);
962         ptrtextbuf += nextblocksize;
963         nextblock += nextblocksize;
964       }
965       // now write out the translated buffer
966       char * writetextbuf = textbuf;
967       for (size_t NumberOfBytesToWrite = (size_t)(ptrtextbuf - textbuf);
968            NumberOfBytesToWrite;) {
969         DWORD NumberOfBytesWritten;
970         WriteFile((HANDLE)_M_file_id, writetextbuf,
971                   __STATIC_CAST(DWORD, (min)(size_t(0xffffffff), NumberOfBytesToWrite)),
972                   &NumberOfBytesWritten, 0);
973         if (!NumberOfBytesWritten) // write shortfall
974           return false;
975         writetextbuf += NumberOfBytesWritten;
976         NumberOfBytesToWrite -= NumberOfBytesWritten;
977       }
978       // count non-translated characters
979       written = (nextblock - buf);
980     }
981
982 #elif defined (_STLP_USE_STDIO_IO)
983
984     written = fwrite(buf, 1, n, _M_file);
985
986 #else
987 #  error "Port!"
988 #endif /* __unix */
989
990     if (n == written)
991       return true;
992     else if (written > 0 && written < n) {
993       n -= written;
994       buf += written;
995     }
996     else
997       return false;
998   }
999 }
1000
1001
1002 #ifdef _STLP_USE_WIN32_IO
1003 #  define STL_SEEK_SET FILE_BEGIN
1004 #  define STL_SEEK_CUR FILE_CURRENT
1005 #  define STL_SEEK_END FILE_END
1006 #else
1007 #  define STL_SEEK_SET SEEK_SET
1008 #  define STL_SEEK_CUR SEEK_CUR
1009 #  define STL_SEEK_END SEEK_END
1010 #endif
1011
1012 // Wrapper for lseek or the like.
1013 streamoff _Filebuf_base::_M_seek(streamoff offset, ios_base::seekdir dir) {
1014   streamoff result = -1;
1015   int whence;
1016
1017   switch(dir) {
1018   case ios_base::beg:
1019     if (offset < 0 /* || offset > _M_file_size() */ )
1020       return streamoff(-1);
1021     whence = STL_SEEK_SET;
1022     break;
1023   case ios_base::cur:
1024     whence = STL_SEEK_CUR;
1025     break;
1026   case ios_base::end:
1027     if (/* offset > 0 || */  -offset > _M_file_size() )
1028       return streamoff(-1);
1029     whence = STL_SEEK_END;
1030     break;
1031   default:
1032     return streamoff(-1);
1033   }
1034
1035 #if defined (_STLP_USE_UNIX_IO) || defined (_STLP_USE_UNIX_EMULATION_IO)
1036
1037   result = LSEEK(_M_file_id, offset, whence);
1038
1039 #elif defined (_STLP_USE_STDIO_IO)
1040
1041   result = FSEEK(_M_file, offset, whence);
1042
1043 #elif defined (_STLP_USE_WIN32_IO)
1044
1045   LARGE_INTEGER li;
1046   li.QuadPart = offset;
1047   li.LowPart = SetFilePointer(_M_file_id, li.LowPart, &li.HighPart, whence);
1048   if (li.LowPart != INVALID_SET_FILE_POINTER || GetLastError() == NO_ERROR)
1049     result = li.QuadPart;
1050
1051 #else
1052 #  error "Port!"
1053 #endif
1054
1055   return result;
1056 }
1057
1058
1059 // Attempts to memory-map len bytes of the current file, starting
1060 // at position offset.  Precondition: offset is a multiple of the
1061 // page size.  Postcondition: return value is a null pointer if the
1062 // memory mapping failed.  Otherwise the return value is a pointer to
1063 // the memory-mapped file and the file position is set to offset.
1064 void* _Filebuf_base::_M_mmap(streamoff offset, streamoff len) {
1065   void* base;
1066 #if defined (_STLP_UNIX) && !defined(__DJGPP) && !defined(_CRAY)
1067   base = MMAP(0, len, PROT_READ, MAP_PRIVATE, _M_file_id, offset);
1068   if (base != (void*)MAP_FAILED) {
1069     if (LSEEK(_M_file_id, offset + len, SEEK_SET) < 0) {
1070       this->_M_unmap(base, len);
1071       base = 0;
1072     }
1073   } else
1074     base =0;
1075
1076 #elif defined (_STLP_USE_WIN32_IO)
1077   _M_view_id = CreateFileMapping(_M_file_id, (PSECURITY_ATTRIBUTES)0 ,
1078                                  PAGE_READONLY, 0 /* len >> 32 */ ,
1079                                  0 /* len & 0xFFFFFFFF */ , // low-order DWORD of size
1080                                  0);
1081
1082   if (_M_view_id) {
1083 #  if 0
1084 /*
1085     printf("view %x created from file %x, error = %d, size = %d, map_offset = %d map_len = %d\n",
1086      _M_view_id, _M_file_id, GetLastError(),
1087      (int)cur_filesize, ULL(offset) & 0xffffffff, len);
1088 */
1089 #  endif
1090     base = MapViewOfFile(_M_view_id, FILE_MAP_READ, __STATIC_CAST(DWORD, ULL(offset) >> 32),
1091                          __STATIC_CAST(DWORD, ULL(offset) & 0xffffffff),
1092 #  if !defined (__DMC__)
1093                          __STATIC_CAST(SIZE_T, len));
1094 #  else
1095                          __STATIC_CAST(DWORD, len));
1096 #  endif
1097     // check if mapping succeded and is usable
1098     if (base == 0  || _M_seek(offset + len, ios_base::beg) < 0) {
1099       this->_M_unmap(base, len);
1100       base = 0;
1101     }
1102   } else
1103     base = 0;
1104 #else
1105   (void)len;    //*TY 02/26/2000 - unused variables
1106   (void)offset;    //*TY 02/26/2000 -
1107   base = 0;
1108 #endif
1109   return base;
1110 }
1111
1112 void _Filebuf_base::_M_unmap(void* base, streamoff len) {
1113   // precondition : there is a valid mapping at the moment
1114 #if defined (_STLP_UNIX)  && !defined(__DJGPP) && !defined(_CRAY)
1115   munmap((char*)base, len);
1116 #elif defined (_STLP_USE_WIN32_IO)
1117   if (base != NULL)
1118     UnmapViewOfFile(base);
1119   // destroy view handle as well
1120   if (_M_view_id != NULL)
1121     CloseHandle(_M_view_id);
1122   _M_view_id = NULL;
1123   (void)len; //unused variable
1124 #else
1125   (void)len;    //*TY 02/26/2000 - unused variables
1126   (void)base;   //*TY 02/26/2000 -
1127 #endif
1128 }
1129
1130 // fbp : let us map 1 MB maximum, just be sure not to trash VM
1131 #define MMAP_CHUNK 0x100000L
1132
1133 int _STLP_CALL
1134 _Underflow<char, char_traits<char> >::_M_doit (basic_filebuf<char, char_traits<char> >* __this) {
1135   if (!__this->_M_in_input_mode) {
1136     if (!__this->_M_switch_to_input_mode())
1137       return traits_type::eof();
1138   }
1139   else if (__this->_M_in_putback_mode) {
1140     __this->_M_exit_putback_mode();
1141     if (__this->gptr() != __this->egptr()) {
1142       int_type __c = traits_type::to_int_type(*__this->gptr());
1143       return __c;
1144     }
1145   }
1146
1147   // If it's a disk file, and if the internal and external character
1148   // sequences are guaranteed to be identical, then try to use memory
1149   // mapped I/O.  Otherwise, revert to ordinary read.
1150   if (__this->_M_base.__regular_file()
1151       && __this->_M_always_noconv
1152       && __this->_M_base._M_in_binary_mode()) {
1153     // If we've mmapped part of the file already, then unmap it.
1154     if (__this->_M_mmap_base)
1155       __this->_M_base._M_unmap(__this->_M_mmap_base, __this->_M_mmap_len);
1156     __this->_M_mmap_base = 0;
1157     __this->_M_mmap_len = 0;
1158
1159     // Determine the position where we start mapping.  It has to be
1160     // a multiple of the page size.
1161     streamoff __cur = __this->_M_base._M_seek(0, ios_base::cur);
1162     streamoff __size = __this->_M_base._M_file_size();
1163     if (__size > 0 && __cur >= 0 && __cur < __size) {
1164       streamoff __offset = (__cur / __this->_M_base.__page_size()) * __this->_M_base.__page_size();
1165       streamoff __remainder = __cur - __offset;
1166
1167       __this->_M_mmap_len = __size - __offset;
1168
1169       if (__this->_M_mmap_len > MMAP_CHUNK)
1170         __this->_M_mmap_len = MMAP_CHUNK;
1171
1172       if ((__this->_M_mmap_base =
1173         __this->_M_base._M_mmap(__offset, __this->_M_mmap_len)) != 0) {
1174         __this->setg((char*) __this->_M_mmap_base,
1175                      (char*) __this->_M_mmap_base + __STATIC_CAST(ptrdiff_t, __remainder),
1176                      (char*) __this->_M_mmap_base + __STATIC_CAST(ptrdiff_t, __this->_M_mmap_len));
1177         return traits_type::to_int_type(*__this->gptr());
1178       }
1179     } else /* size > 0 ... */ {
1180       // There is nothing to map. We unmapped the file above, now zap pointers.
1181       __this->_M_mmap_base = 0;
1182       __this->_M_mmap_len = 0;
1183     }
1184   }
1185
1186   return __this->_M_underflow_aux();
1187 }
1188
1189
1190 //----------------------------------------------------------------------
1191 // Force instantiation of filebuf and fstream classes.
1192 #if !defined(_STLP_NO_FORCE_INSTANTIATE)
1193
1194 template class basic_filebuf<char, char_traits<char> >;
1195 template class basic_ifstream<char, char_traits<char> >;
1196 template class basic_ofstream<char, char_traits<char> >;
1197 template class basic_fstream<char, char_traits<char> >;
1198
1199 #  if !defined (_STLP_NO_WCHAR_T)
1200 template class _Underflow<wchar_t, char_traits<wchar_t> >;
1201 template class basic_filebuf<wchar_t, char_traits<wchar_t> >;
1202 template class basic_ifstream<wchar_t, char_traits<wchar_t> >;
1203 template class basic_ofstream<wchar_t, char_traits<wchar_t> >;
1204 template class basic_fstream<wchar_t, char_traits<wchar_t> >;
1205 #  endif /* _STLP_NO_WCHAR_T */
1206
1207 #endif
1208
1209 _STLP_END_NAMESPACE
1210
1211 // Local Variables:
1212 // mode:C++
1213 // End: