1 /*
2  A C++ interface to POSIX functions.
3 
4  Copyright (c) 2012 - 2016, Victor Zverovich
5  All rights reserved.
6 
7  For the license information refer to format.h.
8  */
9 
10 // Disable bogus MSVC warnings.
11 #ifndef _CRT_SECURE_NO_WARNINGS
12 # define _CRT_SECURE_NO_WARNINGS
13 #endif
14 
15 #include "posix.h"
16 
17 #include <limits.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 
21 #ifndef _WIN32
22 # include <unistd.h>
23 #else
24 # ifndef WIN32_LEAN_AND_MEAN
25 #  define WIN32_LEAN_AND_MEAN
26 # endif
27 # include <windows.h>
28 # include <io.h>
29 
30 # define O_CREAT _O_CREAT
31 # define O_TRUNC _O_TRUNC
32 
33 # ifndef S_IRUSR
34 #  define S_IRUSR _S_IREAD
35 # endif
36 
37 # ifndef S_IWUSR
38 #  define S_IWUSR _S_IWRITE
39 # endif
40 
41 # ifdef __MINGW32__
42 #  define _SH_DENYNO 0x40
43 # endif
44 
45 #endif  // _WIN32
46 
47 #ifdef fileno
48 # undef fileno
49 #endif
50 
51 namespace {
52 #ifdef _WIN32
53 // Return type of read and write functions.
54 typedef int RWResult;
55 
56 // On Windows the count argument to read and write is unsigned, so convert
57 // it from size_t preventing integer overflow.
convert_rwcount(std::size_t count)58 inline unsigned convert_rwcount(std::size_t count) {
59   return count <= UINT_MAX ? static_cast<unsigned>(count) : UINT_MAX;
60 }
61 #else
62 // Return type of read and write functions.
63 typedef ssize_t RWResult;
64 
65 inline std::size_t convert_rwcount(std::size_t count) { return count; }
66 #endif
67 }
68 
~BufferedFile()69 fmt::BufferedFile::~BufferedFile() FMT_NOEXCEPT {
70   if (file_ && FMT_SYSTEM(fclose(file_)) != 0)
71     fmt::report_system_error(errno, "cannot close file");
72 }
73 
BufferedFile(fmt::CStringRef filename,fmt::CStringRef mode)74 fmt::BufferedFile::BufferedFile(
75     fmt::CStringRef filename, fmt::CStringRef mode) {
76   FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), 0);
77   if (!file_)
78     FMT_THROW(SystemError(errno, "cannot open file {}", filename));
79 }
80 
close()81 void fmt::BufferedFile::close() {
82   if (!file_)
83     return;
84   int result = FMT_SYSTEM(fclose(file_));
85   file_ = FMT_NULL;
86   if (result != 0)
87     FMT_THROW(SystemError(errno, "cannot close file"));
88 }
89 
90 // A macro used to prevent expansion of fileno on broken versions of MinGW.
91 #define FMT_ARGS
92 
fileno() const93 int fmt::BufferedFile::fileno() const {
94   int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_));
95   if (fd == -1)
96     FMT_THROW(SystemError(errno, "cannot get file descriptor"));
97   return fd;
98 }
99 
File(fmt::CStringRef path,int oflag)100 fmt::File::File(fmt::CStringRef path, int oflag) {
101   int mode = S_IRUSR | S_IWUSR;
102 #if defined(_WIN32) && !defined(__MINGW32__)
103   fd_ = -1;
104   FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
105 #else
106   FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode)));
107 #endif
108   if (fd_ == -1)
109     FMT_THROW(SystemError(errno, "cannot open file {}", path));
110 }
111 
~File()112 fmt::File::~File() FMT_NOEXCEPT {
113   // Don't retry close in case of EINTR!
114   // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
115   if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0)
116     fmt::report_system_error(errno, "cannot close file");
117 }
118 
close()119 void fmt::File::close() {
120   if (fd_ == -1)
121     return;
122   // Don't retry close in case of EINTR!
123   // See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
124   int result = FMT_POSIX_CALL(close(fd_));
125   fd_ = -1;
126   if (result != 0)
127     FMT_THROW(SystemError(errno, "cannot close file"));
128 }
129 
size() const130 fmt::LongLong fmt::File::size() const {
131 #ifdef _WIN32
132   // Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT
133   // is less than 0x0500 as is the case with some default MinGW builds.
134   // Both functions support large file sizes.
135   DWORD size_upper = 0;
136   HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_));
137   DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper));
138   if (size_lower == INVALID_FILE_SIZE) {
139     DWORD error = GetLastError();
140     if (error != NO_ERROR)
141       FMT_THROW(WindowsError(GetLastError(), "cannot get file size"));
142   }
143   fmt::ULongLong long_size = size_upper;
144   return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower;
145 #else
146   typedef struct stat Stat;
147   Stat file_stat = Stat();
148   if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1)
149     FMT_THROW(SystemError(errno, "cannot get file attributes"));
150   FMT_STATIC_ASSERT(sizeof(fmt::LongLong) >= sizeof(file_stat.st_size),
151       "return type of File::size is not large enough");
152   return file_stat.st_size;
153 #endif
154 }
155 
read(void * buffer,std::size_t count)156 std::size_t fmt::File::read(void *buffer, std::size_t count) {
157   RWResult result = 0;
158   FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
159   if (result < 0)
160     FMT_THROW(SystemError(errno, "cannot read from file"));
161   return internal::to_unsigned(result);
162 }
163 
write(const void * buffer,std::size_t count)164 std::size_t fmt::File::write(const void *buffer, std::size_t count) {
165   RWResult result = 0;
166   FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
167   if (result < 0)
168     FMT_THROW(SystemError(errno, "cannot write to file"));
169   return internal::to_unsigned(result);
170 }
171 
dup(int fd)172 fmt::File fmt::File::dup(int fd) {
173   // Don't retry as dup doesn't return EINTR.
174   // http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html
175   int new_fd = FMT_POSIX_CALL(dup(fd));
176   if (new_fd == -1)
177     FMT_THROW(SystemError(errno, "cannot duplicate file descriptor {}", fd));
178   return File(new_fd);
179 }
180 
dup2(int fd)181 void fmt::File::dup2(int fd) {
182   int result = 0;
183   FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
184   if (result == -1) {
185     FMT_THROW(SystemError(errno,
186       "cannot duplicate file descriptor {} to {}", fd_, fd));
187   }
188 }
189 
dup2(int fd,ErrorCode & ec)190 void fmt::File::dup2(int fd, ErrorCode &ec) FMT_NOEXCEPT {
191   int result = 0;
192   FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
193   if (result == -1)
194     ec = ErrorCode(errno);
195 }
196 
pipe(File & read_end,File & write_end)197 void fmt::File::pipe(File &read_end, File &write_end) {
198   // Close the descriptors first to make sure that assignments don't throw
199   // and there are no leaks.
200   read_end.close();
201   write_end.close();
202   int fds[2] = {};
203 #ifdef _WIN32
204   // Make the default pipe capacity same as on Linux 2.6.11+.
205   enum { DEFAULT_CAPACITY = 65536 };
206   int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY));
207 #else
208   // Don't retry as the pipe function doesn't return EINTR.
209   // http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
210   int result = FMT_POSIX_CALL(pipe(fds));
211 #endif
212   if (result != 0)
213     FMT_THROW(SystemError(errno, "cannot create pipe"));
214   // The following assignments don't throw because read_fd and write_fd
215   // are closed.
216   read_end = File(fds[0]);
217   write_end = File(fds[1]);
218 }
219 
fdopen(const char * mode)220 fmt::BufferedFile fmt::File::fdopen(const char *mode) {
221   // Don't retry as fdopen doesn't return EINTR.
222   FILE *f = FMT_POSIX_CALL(fdopen(fd_, mode));
223   if (!f)
224     FMT_THROW(SystemError(errno, "cannot associate stream with file descriptor"));
225   BufferedFile file(f);
226   fd_ = -1;
227   return file;
228 }
229 
getpagesize()230 long fmt::getpagesize() {
231 #ifdef _WIN32
232   SYSTEM_INFO si;
233   GetSystemInfo(&si);
234   return si.dwPageSize;
235 #else
236   long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
237   if (size < 0)
238     FMT_THROW(SystemError(errno, "cannot get memory page size"));
239   return size;
240 #endif
241 }
242