1 /* gstdio.c - wrappers for C library functions
2 *
3 * Copyright 2004 Tor Lillqvist
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this library; if not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "config.h"
20 #include "glibconfig.h"
21
22 /* Don’t redefine (for example) g_open() to open(), since we actually want to
23 * define g_open() in this file and export it as a symbol. See gstdio.h. */
24 #define G_STDIO_WRAP_ON_UNIX
25
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <fcntl.h>
29
30 #ifdef G_OS_UNIX
31 #include <unistd.h>
32 #endif
33
34 #ifdef G_OS_WIN32
35 #include <windows.h>
36 #include <errno.h>
37 #include <wchar.h>
38 #include <direct.h>
39 #include <io.h>
40 #include <sys/utime.h>
41 #include <stdlib.h> /* for MB_CUR_MAX */
42 #else
43 #include <utime.h>
44 #include <errno.h>
45 #endif
46
47 #include "gstdio.h"
48 #include "gstdioprivate.h"
49
50 #if !defined (G_OS_UNIX) && !defined (G_OS_WIN32)
51 #error Please port this to your operating system
52 #endif
53
54 #if defined (_MSC_VER) && !defined(_WIN64)
55 #undef _wstat
56 #define _wstat _wstat32
57 #endif
58
59 #if defined (G_OS_WIN32)
60
61 /* We can't include Windows DDK and Windows SDK simultaneously,
62 * so let's copy this here from MinGW-w64 DDK.
63 * The structure is ultimately documented here:
64 * https://msdn.microsoft.com/en-us/library/ff552012(v=vs.85).aspx
65 */
66 typedef struct _REPARSE_DATA_BUFFER
67 {
68 ULONG ReparseTag;
69 USHORT ReparseDataLength;
70 USHORT Reserved;
71 union
72 {
73 struct
74 {
75 USHORT SubstituteNameOffset;
76 USHORT SubstituteNameLength;
77 USHORT PrintNameOffset;
78 USHORT PrintNameLength;
79 ULONG Flags;
80 WCHAR PathBuffer[1];
81 } SymbolicLinkReparseBuffer;
82 struct
83 {
84 USHORT SubstituteNameOffset;
85 USHORT SubstituteNameLength;
86 USHORT PrintNameOffset;
87 USHORT PrintNameLength;
88 WCHAR PathBuffer[1];
89 } MountPointReparseBuffer;
90 struct
91 {
92 UCHAR DataBuffer[1];
93 } GenericReparseBuffer;
94 };
95 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
96
97 static int
w32_error_to_errno(DWORD error_code)98 w32_error_to_errno (DWORD error_code)
99 {
100 switch (error_code)
101 {
102 case ERROR_ACCESS_DENIED:
103 return EACCES;
104 break;
105 case ERROR_ALREADY_EXISTS:
106 case ERROR_FILE_EXISTS:
107 return EEXIST;
108 case ERROR_FILE_NOT_FOUND:
109 return ENOENT;
110 break;
111 case ERROR_INVALID_FUNCTION:
112 return EFAULT;
113 break;
114 case ERROR_INVALID_HANDLE:
115 return EBADF;
116 break;
117 case ERROR_INVALID_PARAMETER:
118 return EINVAL;
119 break;
120 case ERROR_LOCK_VIOLATION:
121 case ERROR_SHARING_VIOLATION:
122 return EACCES;
123 break;
124 case ERROR_NOT_ENOUGH_MEMORY:
125 case ERROR_OUTOFMEMORY:
126 return ENOMEM;
127 break;
128 case ERROR_NOT_SAME_DEVICE:
129 return EXDEV;
130 break;
131 case ERROR_PATH_NOT_FOUND:
132 return ENOENT; /* or ELOOP, or ENAMETOOLONG */
133 break;
134 default:
135 return EIO;
136 break;
137 }
138 }
139
140 #include "gstdio-private.c"
141
142 /* Windows implementation of fopen() does not accept modes such as
143 * "wb+". The 'b' needs to be appended to "w+", i.e. "w+b". Note
144 * that otherwise these 2 modes are supposed to be aliases, hence
145 * swappable at will. TODO: Is this still true?
146 */
147 static void
_g_win32_fix_mode(wchar_t * mode)148 _g_win32_fix_mode (wchar_t *mode)
149 {
150 wchar_t *ptr;
151 wchar_t temp;
152
153 ptr = wcschr (mode, L'+');
154 if (ptr != NULL && (ptr - mode) > 1)
155 {
156 temp = mode[1];
157 mode[1] = *ptr;
158 *ptr = temp;
159 }
160 }
161
162 /* From
163 * https://support.microsoft.com/en-ca/help/167296/how-to-convert-a-unix-time-t-to-a-win32-filetime-or-systemtime
164 * FT = UT * 10000000 + 116444736000000000.
165 * Therefore:
166 * UT = (FT - 116444736000000000) / 10000000.
167 * Converts FILETIME to unix epoch time in form
168 * of a signed 64-bit integer (can be negative).
169 */
170 static gint64
_g_win32_filetime_to_unix_time(FILETIME * ft)171 _g_win32_filetime_to_unix_time (FILETIME *ft)
172 {
173 gint64 result;
174 /* 1 unit of FILETIME is 100ns */
175 const gint64 hundreds_of_usec_per_sec = 10000000;
176 /* The difference between January 1, 1601 UTC (FILETIME epoch) and UNIX epoch
177 * in hundreds of nanoseconds.
178 */
179 const gint64 filetime_unix_epoch_offset = 116444736000000000;
180
181 result = ((gint64) ft->dwLowDateTime) | (((gint64) ft->dwHighDateTime) << 32);
182 return (result - filetime_unix_epoch_offset) / hundreds_of_usec_per_sec;
183 }
184
185 # ifdef _MSC_VER
186 # ifndef S_IXUSR
187 # define _S_IRUSR _S_IREAD
188 # define _S_IWUSR _S_IWRITE
189 # define _S_IXUSR _S_IEXEC
190 # define S_IRUSR _S_IRUSR
191 # define S_IWUSR _S_IWUSR
192 # define S_IXUSR _S_IXUSR
193 # define S_IRGRP (S_IRUSR >> 3)
194 # define S_IWGRP (S_IWUSR >> 3)
195 # define S_IXGRP (S_IXUSR >> 3)
196 # define S_IROTH (S_IRGRP >> 3)
197 # define S_IWOTH (S_IWGRP >> 3)
198 # define S_IXOTH (S_IXGRP >> 3)
199 # endif
200 # ifndef S_ISDIR
201 # define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
202 # endif
203 # endif
204
205 /* Uses filename and BHFI to fill a stat64 structure.
206 * Tries to reproduce the behaviour and quirks of MS C runtime stat().
207 */
208 static int
_g_win32_fill_statbuf_from_handle_info(const wchar_t * filename,const wchar_t * filename_target,BY_HANDLE_FILE_INFORMATION * handle_info,struct __stat64 * statbuf)209 _g_win32_fill_statbuf_from_handle_info (const wchar_t *filename,
210 const wchar_t *filename_target,
211 BY_HANDLE_FILE_INFORMATION *handle_info,
212 struct __stat64 *statbuf)
213 {
214 wchar_t drive_letter_w = 0;
215 size_t drive_letter_size = MB_CUR_MAX;
216 char *drive_letter = _alloca (drive_letter_size);
217
218 /* If filename (target or link) is absolute,
219 * then use the drive letter from it as-is.
220 */
221 if (filename_target != NULL &&
222 filename_target[0] != L'\0' &&
223 filename_target[1] == L':')
224 drive_letter_w = filename_target[0];
225 else if (filename[0] != L'\0' &&
226 filename[1] == L':')
227 drive_letter_w = filename[0];
228
229 if (drive_letter_w > 0 &&
230 iswalpha (drive_letter_w) &&
231 iswascii (drive_letter_w) &&
232 wctomb (drive_letter, drive_letter_w) == 1)
233 statbuf->st_dev = toupper (drive_letter[0]) - 'A'; /* 0 means A: drive */
234 else
235 /* Otherwise use the PWD drive.
236 * Return value of 0 gives us 0 - 1 = -1,
237 * which is the "no idea" value for st_dev.
238 */
239 statbuf->st_dev = _getdrive () - 1;
240
241 statbuf->st_rdev = statbuf->st_dev;
242 /* Theoretically, it's possible to set it for ext-FS. No idea how.
243 * Meaningless for all filesystems that Windows normally uses.
244 */
245 statbuf->st_ino = 0;
246 statbuf->st_mode = 0;
247
248 if ((handle_info->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
249 statbuf->st_mode |= S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
250 else
251 statbuf->st_mode |= S_IFREG;
252 /* No idea what S_IFCHR means here. */
253 /* S_IFIFO is not even mentioned in MSDN */
254 /* S_IFBLK is also not mentioned */
255
256 /* The aim here is to reproduce MS stat() behaviour,
257 * even if it's braindead.
258 */
259 statbuf->st_mode |= S_IRUSR | S_IRGRP | S_IROTH;
260 if ((handle_info->dwFileAttributes & FILE_ATTRIBUTE_READONLY) != FILE_ATTRIBUTE_READONLY)
261 statbuf->st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
262
263 if (!S_ISDIR (statbuf->st_mode))
264 {
265 const wchar_t *name;
266 const wchar_t *dot = NULL;
267
268 if (filename_target != NULL)
269 name = filename_target;
270 else
271 name = filename;
272
273 do
274 {
275 wchar_t *last_dot = wcschr (name, L'.');
276 if (last_dot == NULL)
277 break;
278 dot = last_dot;
279 name = &last_dot[1];
280 }
281 while (TRUE);
282
283 if ((dot != NULL &&
284 (wcsicmp (dot, L".exe") == 0 ||
285 wcsicmp (dot, L".com") == 0 ||
286 wcsicmp (dot, L".bat") == 0 ||
287 wcsicmp (dot, L".cmd") == 0)))
288 statbuf->st_mode |= S_IXUSR | S_IXGRP | S_IXOTH;
289 }
290
291 statbuf->st_nlink = handle_info->nNumberOfLinks;
292 statbuf->st_uid = statbuf->st_gid = 0;
293 statbuf->st_size = (((guint64) handle_info->nFileSizeHigh) << 32) | handle_info->nFileSizeLow;
294 statbuf->st_ctime = _g_win32_filetime_to_unix_time (&handle_info->ftCreationTime);
295 statbuf->st_mtime = _g_win32_filetime_to_unix_time (&handle_info->ftLastWriteTime);
296 statbuf->st_atime = _g_win32_filetime_to_unix_time (&handle_info->ftLastAccessTime);
297
298 return 0;
299 }
300
301 /* Fills our private stat-like structure using data from
302 * a normal stat64 struct, BHFI, FSI and a reparse tag.
303 */
304 static void
_g_win32_fill_privatestat(const struct __stat64 * statbuf,const BY_HANDLE_FILE_INFORMATION * handle_info,const FILE_STANDARD_INFO * std_info,DWORD reparse_tag,GWin32PrivateStat * buf)305 _g_win32_fill_privatestat (const struct __stat64 *statbuf,
306 const BY_HANDLE_FILE_INFORMATION *handle_info,
307 const FILE_STANDARD_INFO *std_info,
308 DWORD reparse_tag,
309 GWin32PrivateStat *buf)
310 {
311 buf->st_dev = statbuf->st_dev;
312 buf->st_ino = statbuf->st_ino;
313 buf->st_mode = statbuf->st_mode;
314 buf->volume_serial = handle_info->dwVolumeSerialNumber;
315 buf->file_index = (((guint64) handle_info->nFileIndexHigh) << 32) | handle_info->nFileIndexLow;
316 buf->attributes = handle_info->dwFileAttributes;
317 buf->st_nlink = handle_info->nNumberOfLinks;
318 buf->st_size = (((guint64) handle_info->nFileSizeHigh) << 32) | handle_info->nFileSizeLow;
319 buf->allocated_size = std_info->AllocationSize.QuadPart;
320
321 buf->reparse_tag = reparse_tag;
322
323 buf->st_ctime = statbuf->st_ctime;
324 buf->st_atime = statbuf->st_atime;
325 buf->st_mtime = statbuf->st_mtime;
326 }
327
328 /* Read the link data from a symlink/mountpoint represented
329 * by the handle. Also reads reparse tag.
330 * @reparse_tag receives the tag. Can be %NULL if @buf or @alloc_buf
331 * is non-NULL.
332 * @buf receives the link data. Can be %NULL if reparse_tag is non-%NULL.
333 * Mutually-exclusive with @alloc_buf.
334 * @buf_size is the size of the @buf, in bytes.
335 * @alloc_buf points to a location where internally-allocated buffer
336 * pointer will be written. That buffer receives the
337 * link data. Mutually-exclusive with @buf.
338 * @terminate ensures that the buffer is NUL-terminated if
339 * it isn't already. Note that this can erase useful
340 * data if @buf is provided and @buf_size is too small.
341 * Specifically, with @buf_size <= 2 the buffer will
342 * receive an empty string, even if there is some
343 * data in the reparse point.
344 * The contents of @buf or @alloc_buf are presented as-is - could
345 * be non-NUL-terminated (unless @terminate is %TRUE) or even malformed.
346 * Returns the number of bytes (!) placed into @buf or @alloc_buf,
347 * including NUL-terminator (if any).
348 *
349 * Returned value of 0 means that there's no recognizable data in the
350 * reparse point. @alloc_buf will not be allocated in that case,
351 * and @buf will be left unmodified.
352 *
353 * If @buf and @alloc_buf are %NULL, returns 0 to indicate success.
354 * Returns -1 to indicate an error, sets errno.
355 */
356 static int
_g_win32_readlink_handle_raw(HANDLE h,DWORD * reparse_tag,gunichar2 * buf,gsize buf_size,gunichar2 ** alloc_buf,gboolean terminate)357 _g_win32_readlink_handle_raw (HANDLE h,
358 DWORD *reparse_tag,
359 gunichar2 *buf,
360 gsize buf_size,
361 gunichar2 **alloc_buf,
362 gboolean terminate)
363 {
364 DWORD error_code;
365 DWORD returned_bytes = 0;
366 BYTE *data;
367 gsize to_copy;
368 /* This is 16k. It's impossible to make DeviceIoControl() tell us
369 * the required size. NtFsControlFile() does have such a feature,
370 * but for some reason it doesn't work with CreateFile()-returned handles.
371 * The only alternative is to repeatedly call DeviceIoControl()
372 * with bigger and bigger buffers, until it succeeds.
373 * We choose to sacrifice stack space for speed.
374 */
375 BYTE max_buffer[sizeof (REPARSE_DATA_BUFFER) + MAXIMUM_REPARSE_DATA_BUFFER_SIZE] = {0,};
376 DWORD max_buffer_size = sizeof (REPARSE_DATA_BUFFER) + MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
377 REPARSE_DATA_BUFFER *rep_buf;
378
379 g_return_val_if_fail ((buf != NULL || alloc_buf != NULL || reparse_tag != NULL) &&
380 (buf == NULL || alloc_buf == NULL),
381 -1);
382
383 if (!DeviceIoControl (h, FSCTL_GET_REPARSE_POINT, NULL, 0,
384 max_buffer,
385 max_buffer_size,
386 &returned_bytes, NULL))
387 {
388 error_code = GetLastError ();
389 errno = w32_error_to_errno (error_code);
390 return -1;
391 }
392
393 rep_buf = (REPARSE_DATA_BUFFER *) max_buffer;
394
395 if (reparse_tag != NULL)
396 *reparse_tag = rep_buf->ReparseTag;
397
398 if (buf == NULL && alloc_buf == NULL)
399 return 0;
400
401 if (rep_buf->ReparseTag == IO_REPARSE_TAG_SYMLINK)
402 {
403 data = &((BYTE *) rep_buf->SymbolicLinkReparseBuffer.PathBuffer)[rep_buf->SymbolicLinkReparseBuffer.SubstituteNameOffset];
404
405 to_copy = rep_buf->SymbolicLinkReparseBuffer.SubstituteNameLength;
406 }
407 else if (rep_buf->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
408 {
409 data = &((BYTE *) rep_buf->MountPointReparseBuffer.PathBuffer)[rep_buf->MountPointReparseBuffer.SubstituteNameOffset];
410
411 to_copy = rep_buf->MountPointReparseBuffer.SubstituteNameLength;
412 }
413 else
414 to_copy = 0;
415
416 return _g_win32_copy_and_maybe_terminate (data, to_copy, buf, buf_size, alloc_buf, terminate);
417 }
418
419 /* Read the link data from a symlink/mountpoint represented
420 * by the @filename.
421 * @filename is the name of the file.
422 * @reparse_tag receives the tag. Can be %NULL if @buf or @alloc_buf
423 * is non-%NULL.
424 * @buf receives the link data. Mutually-exclusive with @alloc_buf.
425 * @buf_size is the size of the @buf, in bytes.
426 * @alloc_buf points to a location where internally-allocated buffer
427 * pointer will be written. That buffer receives the
428 * link data. Mutually-exclusive with @buf.
429 * @terminate ensures that the buffer is NUL-terminated if
430 * it isn't already
431 * The contents of @buf or @alloc_buf are presented as-is - could
432 * be non-NUL-terminated (unless @terminate is TRUE) or even malformed.
433 * Returns the number of bytes (!) placed into @buf or @alloc_buf.
434 * Returned value of 0 means that there's no recognizable data in the
435 * reparse point. @alloc_buf will not be allocated in that case,
436 * and @buf will be left unmodified.
437 * If @buf and @alloc_buf are %NULL, returns 0 to indicate success.
438 * Returns -1 to indicate an error, sets errno.
439 */
440 static int
_g_win32_readlink_utf16_raw(const gunichar2 * filename,DWORD * reparse_tag,gunichar2 * buf,gsize buf_size,gunichar2 ** alloc_buf,gboolean terminate)441 _g_win32_readlink_utf16_raw (const gunichar2 *filename,
442 DWORD *reparse_tag,
443 gunichar2 *buf,
444 gsize buf_size,
445 gunichar2 **alloc_buf,
446 gboolean terminate)
447 {
448 HANDLE h;
449 DWORD attributes;
450 DWORD to_copy;
451 DWORD error_code;
452
453 if ((attributes = GetFileAttributesW (filename)) == 0)
454 {
455 error_code = GetLastError ();
456 errno = w32_error_to_errno (error_code);
457 return -1;
458 }
459
460 if ((attributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
461 {
462 errno = EINVAL;
463 return -1;
464 }
465
466 /* To read symlink target we need to open the file as a reparse
467 * point and use DeviceIoControl() on it.
468 */
469 h = CreateFileW (filename,
470 FILE_READ_EA,
471 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
472 NULL, OPEN_EXISTING,
473 FILE_ATTRIBUTE_NORMAL
474 | FILE_FLAG_OPEN_REPARSE_POINT
475 | (attributes & FILE_ATTRIBUTE_DIRECTORY ? FILE_FLAG_BACKUP_SEMANTICS : 0),
476 NULL);
477
478 if (h == INVALID_HANDLE_VALUE)
479 {
480 error_code = GetLastError ();
481 errno = w32_error_to_errno (error_code);
482 return -1;
483 }
484
485 to_copy = _g_win32_readlink_handle_raw (h, reparse_tag, buf, buf_size, alloc_buf, terminate);
486
487 CloseHandle (h);
488
489 return to_copy;
490 }
491
492 /* Read the link data from a symlink/mountpoint represented
493 * by a UTF-16 filename or a file handle.
494 * @filename is the name of the file. Mutually-exclusive with @file_handle.
495 * @file_handle is the handle of the file. Mutually-exclusive with @filename.
496 * @reparse_tag receives the tag. Can be %NULL if @buf or @alloc_buf
497 * is non-%NULL.
498 * @buf receives the link data. Mutually-exclusive with @alloc_buf.
499 * @buf_size is the size of the @buf, in bytes.
500 * @alloc_buf points to a location where internally-allocated buffer
501 * pointer will be written. That buffer receives the
502 * link data. Mutually-exclusive with @buf.
503 * @terminate ensures that the buffer is NUL-terminated if
504 * it isn't already
505 * The contents of @buf or @alloc_buf are adjusted
506 * (extended or nt object manager prefix is stripped),
507 * but otherwise they are presented as-is - could be non-NUL-terminated
508 * (unless @terminate is TRUE) or even malformed.
509 * Returns the number of bytes (!) placed into @buf or @alloc_buf.
510 * Returned value of 0 means that there's no recognizable data in the
511 * reparse point. @alloc_buf will not be allocated in that case,
512 * and @buf will be left unmodified.
513 * Returns -1 to indicate an error, sets errno.
514 */
515 static int
_g_win32_readlink_utf16_handle(const gunichar2 * filename,HANDLE file_handle,DWORD * reparse_tag,gunichar2 * buf,gsize buf_size,gunichar2 ** alloc_buf,gboolean terminate)516 _g_win32_readlink_utf16_handle (const gunichar2 *filename,
517 HANDLE file_handle,
518 DWORD *reparse_tag,
519 gunichar2 *buf,
520 gsize buf_size,
521 gunichar2 **alloc_buf,
522 gboolean terminate)
523 {
524 int result;
525 gsize string_size;
526
527 g_return_val_if_fail ((buf != NULL || alloc_buf != NULL || reparse_tag != NULL) &&
528 (filename != NULL || file_handle != NULL) &&
529 (buf == NULL || alloc_buf == NULL) &&
530 (filename == NULL || file_handle == NULL),
531 -1);
532
533 if (filename)
534 result = _g_win32_readlink_utf16_raw (filename, reparse_tag, buf, buf_size, alloc_buf, terminate);
535 else
536 result = _g_win32_readlink_handle_raw (file_handle, reparse_tag, buf, buf_size, alloc_buf, terminate);
537
538 if (result <= 0)
539 return result;
540
541 /* Ensure that output is a multiple of sizeof (gunichar2),
542 * cutting any trailing partial gunichar2, if present.
543 */
544 result -= result % sizeof (gunichar2);
545
546 if (result <= 0)
547 return result;
548
549 /* DeviceIoControl () tends to return filenames as NT Object Manager
550 * names , i.e. "\\??\\C:\\foo\\bar".
551 * Remove the leading 4-byte "\\??\\" prefix, as glib (as well as many W32 API
552 * functions) is unprepared to deal with it. Unless it has no 'x:' drive
553 * letter part after the prefix, in which case we leave everything
554 * as-is, because the path could be "\\??\\Volume{GUID}" - stripping
555 * the prefix will allow it to be confused with relative links
556 * targeting "Volume{GUID}".
557 */
558 string_size = result / sizeof (gunichar2);
559 _g_win32_strip_extended_ntobjm_prefix (buf ? buf : *alloc_buf, &string_size);
560
561 return string_size * sizeof (gunichar2);
562 }
563
564 /* Works like stat() or lstat(), depending on the value of @for_symlink,
565 * but accepts filename in UTF-16 and fills our custom stat structure.
566 * The @filename must not have trailing slashes.
567 */
568 static int
_g_win32_stat_utf16_no_trailing_slashes(const gunichar2 * filename,GWin32PrivateStat * buf,gboolean for_symlink)569 _g_win32_stat_utf16_no_trailing_slashes (const gunichar2 *filename,
570 GWin32PrivateStat *buf,
571 gboolean for_symlink)
572 {
573 struct __stat64 statbuf;
574 BY_HANDLE_FILE_INFORMATION handle_info;
575 FILE_STANDARD_INFO std_info;
576 gboolean is_symlink = FALSE;
577 wchar_t *filename_target = NULL;
578 DWORD immediate_attributes;
579 DWORD open_flags;
580 gboolean is_directory;
581 DWORD reparse_tag = 0;
582 DWORD error_code;
583 BOOL succeeded_so_far;
584 HANDLE file_handle;
585
586 immediate_attributes = GetFileAttributesW (filename);
587
588 if (immediate_attributes == INVALID_FILE_ATTRIBUTES)
589 {
590 error_code = GetLastError ();
591 errno = w32_error_to_errno (error_code);
592
593 return -1;
594 }
595
596 is_symlink = (immediate_attributes & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT;
597 is_directory = (immediate_attributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY;
598
599 open_flags = FILE_ATTRIBUTE_NORMAL;
600
601 if (for_symlink && is_symlink)
602 open_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
603
604 if (is_directory)
605 open_flags |= FILE_FLAG_BACKUP_SEMANTICS;
606
607 file_handle = CreateFileW (filename, FILE_READ_ATTRIBUTES | FILE_READ_EA,
608 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
609 NULL, OPEN_EXISTING,
610 open_flags,
611 NULL);
612
613 if (file_handle == INVALID_HANDLE_VALUE)
614 {
615 error_code = GetLastError ();
616 errno = w32_error_to_errno (error_code);
617 return -1;
618 }
619
620 succeeded_so_far = GetFileInformationByHandle (file_handle,
621 &handle_info);
622 error_code = GetLastError ();
623
624 if (succeeded_so_far)
625 {
626 succeeded_so_far = GetFileInformationByHandleEx (file_handle,
627 FileStandardInfo,
628 &std_info,
629 sizeof (std_info));
630 error_code = GetLastError ();
631 }
632
633 if (!succeeded_so_far)
634 {
635 CloseHandle (file_handle);
636 errno = w32_error_to_errno (error_code);
637 return -1;
638 }
639
640 /* It's tempting to use GetFileInformationByHandleEx(FileAttributeTagInfo),
641 * but it always reports that the ReparseTag is 0.
642 * We already have a handle open for symlink, use that.
643 * For the target we have to specify a filename, and the function
644 * will open another handle internally.
645 */
646 if (is_symlink &&
647 _g_win32_readlink_utf16_handle (for_symlink ? NULL : filename,
648 for_symlink ? file_handle : NULL,
649 &reparse_tag,
650 NULL, 0,
651 for_symlink ? NULL : &filename_target,
652 TRUE) < 0)
653 {
654 CloseHandle (file_handle);
655 return -1;
656 }
657
658 CloseHandle (file_handle);
659
660 _g_win32_fill_statbuf_from_handle_info (filename,
661 filename_target,
662 &handle_info,
663 &statbuf);
664 g_free (filename_target);
665 _g_win32_fill_privatestat (&statbuf,
666 &handle_info,
667 &std_info,
668 reparse_tag,
669 buf);
670
671 return 0;
672 }
673
674 /* Works like fstat(), but fills our custom stat structure. */
675 static int
_g_win32_stat_fd(int fd,GWin32PrivateStat * buf)676 _g_win32_stat_fd (int fd,
677 GWin32PrivateStat *buf)
678 {
679 HANDLE file_handle;
680 gboolean succeeded_so_far;
681 DWORD error_code;
682 struct __stat64 statbuf;
683 BY_HANDLE_FILE_INFORMATION handle_info;
684 FILE_STANDARD_INFO std_info;
685 DWORD reparse_tag = 0;
686 gboolean is_symlink = FALSE;
687
688 file_handle = (HANDLE) _get_osfhandle (fd);
689
690 if (file_handle == INVALID_HANDLE_VALUE)
691 return -1;
692
693 succeeded_so_far = GetFileInformationByHandle (file_handle,
694 &handle_info);
695 error_code = GetLastError ();
696
697 if (succeeded_so_far)
698 {
699 succeeded_so_far = GetFileInformationByHandleEx (file_handle,
700 FileStandardInfo,
701 &std_info,
702 sizeof (std_info));
703 error_code = GetLastError ();
704 }
705
706 if (!succeeded_so_far)
707 {
708 errno = w32_error_to_errno (error_code);
709 return -1;
710 }
711
712 is_symlink = (handle_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT;
713
714 if (is_symlink &&
715 _g_win32_readlink_handle_raw (file_handle, &reparse_tag, NULL, 0, NULL, FALSE) < 0)
716 return -1;
717
718 if (_fstat64 (fd, &statbuf) != 0)
719 return -1;
720
721 _g_win32_fill_privatestat (&statbuf,
722 &handle_info,
723 &std_info,
724 reparse_tag,
725 buf);
726
727 return 0;
728 }
729
730 /* Works like stat() or lstat(), depending on the value of @for_symlink,
731 * but accepts filename in UTF-8 and fills our custom stat structure.
732 */
733 static int
_g_win32_stat_utf8(const gchar * filename,GWin32PrivateStat * buf,gboolean for_symlink)734 _g_win32_stat_utf8 (const gchar *filename,
735 GWin32PrivateStat *buf,
736 gboolean for_symlink)
737 {
738 wchar_t *wfilename;
739 int result;
740 gsize len;
741
742 if (filename == NULL)
743 {
744 errno = EINVAL;
745 return -1;
746 }
747
748 len = strlen (filename);
749
750 while (len > 0 && G_IS_DIR_SEPARATOR (filename[len - 1]))
751 len--;
752
753 if (len <= 0 ||
754 (g_path_is_absolute (filename) && len <= g_path_skip_root (filename) - filename))
755 len = strlen (filename);
756
757 wfilename = g_utf8_to_utf16 (filename, len, NULL, NULL, NULL);
758
759 if (wfilename == NULL)
760 {
761 errno = EINVAL;
762 return -1;
763 }
764
765 result = _g_win32_stat_utf16_no_trailing_slashes (wfilename, buf, for_symlink);
766
767 g_free (wfilename);
768
769 return result;
770 }
771
772 /* Works like stat(), but accepts filename in UTF-8
773 * and fills our custom stat structure.
774 */
775 int
g_win32_stat_utf8(const gchar * filename,GWin32PrivateStat * buf)776 g_win32_stat_utf8 (const gchar *filename,
777 GWin32PrivateStat *buf)
778 {
779 return _g_win32_stat_utf8 (filename, buf, FALSE);
780 }
781
782 /* Works like lstat(), but accepts filename in UTF-8
783 * and fills our custom stat structure.
784 */
785 int
g_win32_lstat_utf8(const gchar * filename,GWin32PrivateStat * buf)786 g_win32_lstat_utf8 (const gchar *filename,
787 GWin32PrivateStat *buf)
788 {
789 return _g_win32_stat_utf8 (filename, buf, TRUE);
790 }
791
792 /* Works like fstat(), but accepts filename in UTF-8
793 * and fills our custom stat structure.
794 */
795 int
g_win32_fstat(int fd,GWin32PrivateStat * buf)796 g_win32_fstat (int fd,
797 GWin32PrivateStat *buf)
798 {
799 return _g_win32_stat_fd (fd, buf);
800 }
801
802 /**
803 * g_win32_readlink_utf8:
804 * @filename: (type filename): a pathname in UTF-8
805 * @buf: (array length=buf_size) : a buffer to receive the reparse point
806 * target path. Mutually-exclusive
807 * with @alloc_buf.
808 * @buf_size: size of the @buf, in bytes
809 * @alloc_buf: points to a location where internally-allocated buffer
810 * pointer will be written. That buffer receives the
811 * link data. Mutually-exclusive with @buf.
812 * @terminate: ensures that the buffer is NUL-terminated if
813 * it isn't already. If %FALSE, the returned string
814 * might not be NUL-terminated (depends entirely on
815 * what the contents of the filesystem are).
816 *
817 * Tries to read the reparse point indicated by @filename, filling
818 * @buf or @alloc_buf with the path that the reparse point redirects to.
819 * The path will be UTF-8-encoded, and an extended path prefix
820 * or a NT object manager prefix will be removed from it, if
821 * possible, but otherwise the path is returned as-is. Specifically,
822 * it could be a "\\\\Volume{GUID}\\" path. It also might use
823 * backslashes as path separators.
824 *
825 * Returns: -1 on error (sets errno), 0 if there's no (recognizable)
826 * path in the reparse point (@alloc_buf will not be allocated in that case,
827 * and @buf will be left unmodified),
828 * or the number of bytes placed into @buf otherwise,
829 * including NUL-terminator (if present or if @terminate is TRUE).
830 * The buffer returned via @alloc_buf should be freed with g_free().
831 *
832 * Since: 2.60
833 */
834 int
g_win32_readlink_utf8(const gchar * filename,gchar * buf,gsize buf_size,gchar ** alloc_buf,gboolean terminate)835 g_win32_readlink_utf8 (const gchar *filename,
836 gchar *buf,
837 gsize buf_size,
838 gchar **alloc_buf,
839 gboolean terminate)
840 {
841 wchar_t *wfilename;
842 int result;
843 wchar_t *buf_utf16;
844 glong tmp_len;
845 gchar *tmp;
846
847 g_return_val_if_fail ((buf != NULL || alloc_buf != NULL) &&
848 (buf == NULL || alloc_buf == NULL),
849 -1);
850
851 wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
852
853 if (wfilename == NULL)
854 {
855 errno = EINVAL;
856 return -1;
857 }
858
859 result = _g_win32_readlink_utf16_handle (wfilename, NULL, NULL,
860 NULL, 0, &buf_utf16, terminate);
861
862 g_free (wfilename);
863
864 if (result <= 0)
865 return result;
866
867 tmp = g_utf16_to_utf8 (buf_utf16,
868 result / sizeof (gunichar2),
869 NULL,
870 &tmp_len,
871 NULL);
872
873 g_free (buf_utf16);
874
875 if (tmp == NULL)
876 {
877 errno = EINVAL;
878 return -1;
879 }
880
881 if (alloc_buf)
882 {
883 *alloc_buf = tmp;
884 return tmp_len;
885 }
886
887 if (tmp_len > buf_size)
888 tmp_len = buf_size;
889
890 memcpy (buf, tmp, tmp_len);
891 g_free (tmp);
892
893 return tmp_len;
894 }
895
896 #endif
897
898 /**
899 * g_access:
900 * @filename: (type filename): a pathname in the GLib file name encoding
901 * (UTF-8 on Windows)
902 * @mode: as in access()
903 *
904 * A wrapper for the POSIX access() function. This function is used to
905 * test a pathname for one or several of read, write or execute
906 * permissions, or just existence.
907 *
908 * On Windows, the file protection mechanism is not at all POSIX-like,
909 * and the underlying function in the C library only checks the
910 * FAT-style READONLY attribute, and does not look at the ACL of a
911 * file at all. This function is this in practise almost useless on
912 * Windows. Software that needs to handle file permissions on Windows
913 * more exactly should use the Win32 API.
914 *
915 * See your C library manual for more details about access().
916 *
917 * Returns: zero if the pathname refers to an existing file system
918 * object that has all the tested permissions, or -1 otherwise
919 * or on error.
920 *
921 * Since: 2.8
922 */
923 int
g_access(const gchar * filename,int mode)924 g_access (const gchar *filename,
925 int mode)
926 {
927 #ifdef G_OS_WIN32
928 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
929 int retval;
930 int save_errno;
931
932 if (wfilename == NULL)
933 {
934 errno = EINVAL;
935 return -1;
936 }
937
938 #ifndef X_OK
939 #define X_OK 1
940 #endif
941
942 retval = _waccess (wfilename, mode & ~X_OK);
943 save_errno = errno;
944
945 g_free (wfilename);
946
947 errno = save_errno;
948 return retval;
949 #else
950 return access (filename, mode);
951 #endif
952 }
953
954 /**
955 * g_chmod:
956 * @filename: (type filename): a pathname in the GLib file name encoding
957 * (UTF-8 on Windows)
958 * @mode: as in chmod()
959 *
960 * A wrapper for the POSIX chmod() function. The chmod() function is
961 * used to set the permissions of a file system object.
962 *
963 * On Windows the file protection mechanism is not at all POSIX-like,
964 * and the underlying chmod() function in the C library just sets or
965 * clears the FAT-style READONLY attribute. It does not touch any
966 * ACL. Software that needs to manage file permissions on Windows
967 * exactly should use the Win32 API.
968 *
969 * See your C library manual for more details about chmod().
970 *
971 * Returns: 0 if the operation succeeded, -1 on error
972 *
973 * Since: 2.8
974 */
975 int
g_chmod(const gchar * filename,int mode)976 g_chmod (const gchar *filename,
977 int mode)
978 {
979 #ifdef G_OS_WIN32
980 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
981 int retval;
982 int save_errno;
983
984 if (wfilename == NULL)
985 {
986 errno = EINVAL;
987 return -1;
988 }
989
990 retval = _wchmod (wfilename, mode);
991 save_errno = errno;
992
993 g_free (wfilename);
994
995 errno = save_errno;
996 return retval;
997 #else
998 return chmod (filename, mode);
999 #endif
1000 }
1001 /**
1002 * g_open:
1003 * @filename: (type filename): a pathname in the GLib file name encoding
1004 * (UTF-8 on Windows)
1005 * @flags: as in open()
1006 * @mode: as in open()
1007 *
1008 * A wrapper for the POSIX open() function. The open() function is
1009 * used to convert a pathname into a file descriptor.
1010 *
1011 * On POSIX systems file descriptors are implemented by the operating
1012 * system. On Windows, it's the C library that implements open() and
1013 * file descriptors. The actual Win32 API for opening files is quite
1014 * different, see MSDN documentation for CreateFile(). The Win32 API
1015 * uses file handles, which are more randomish integers, not small
1016 * integers like file descriptors.
1017 *
1018 * Because file descriptors are specific to the C library on Windows,
1019 * the file descriptor returned by this function makes sense only to
1020 * functions in the same C library. Thus if the GLib-using code uses a
1021 * different C library than GLib does, the file descriptor returned by
1022 * this function cannot be passed to C library functions like write()
1023 * or read().
1024 *
1025 * See your C library manual for more details about open().
1026 *
1027 * Returns: a new file descriptor, or -1 if an error occurred.
1028 * The return value can be used exactly like the return value
1029 * from open().
1030 *
1031 * Since: 2.6
1032 */
1033 int
g_open(const gchar * filename,int flags,int mode)1034 g_open (const gchar *filename,
1035 int flags,
1036 int mode)
1037 {
1038 #ifdef G_OS_WIN32
1039 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1040 int retval;
1041 int save_errno;
1042
1043 if (wfilename == NULL)
1044 {
1045 errno = EINVAL;
1046 return -1;
1047 }
1048
1049 retval = _wopen (wfilename, flags, mode);
1050 save_errno = errno;
1051
1052 g_free (wfilename);
1053
1054 errno = save_errno;
1055 return retval;
1056 #else
1057 int fd;
1058 do
1059 fd = open (filename, flags, mode);
1060 while (G_UNLIKELY (fd == -1 && errno == EINTR));
1061 return fd;
1062 #endif
1063 }
1064
1065 /**
1066 * g_creat:
1067 * @filename: (type filename): a pathname in the GLib file name encoding
1068 * (UTF-8 on Windows)
1069 * @mode: as in creat()
1070 *
1071 * A wrapper for the POSIX creat() function. The creat() function is
1072 * used to convert a pathname into a file descriptor, creating a file
1073 * if necessary.
1074 *
1075 * On POSIX systems file descriptors are implemented by the operating
1076 * system. On Windows, it's the C library that implements creat() and
1077 * file descriptors. The actual Windows API for opening files is
1078 * different, see MSDN documentation for CreateFile(). The Win32 API
1079 * uses file handles, which are more randomish integers, not small
1080 * integers like file descriptors.
1081 *
1082 * Because file descriptors are specific to the C library on Windows,
1083 * the file descriptor returned by this function makes sense only to
1084 * functions in the same C library. Thus if the GLib-using code uses a
1085 * different C library than GLib does, the file descriptor returned by
1086 * this function cannot be passed to C library functions like write()
1087 * or read().
1088 *
1089 * See your C library manual for more details about creat().
1090 *
1091 * Returns: a new file descriptor, or -1 if an error occurred.
1092 * The return value can be used exactly like the return value
1093 * from creat().
1094 *
1095 * Since: 2.8
1096 */
1097 int
g_creat(const gchar * filename,int mode)1098 g_creat (const gchar *filename,
1099 int mode)
1100 {
1101 #ifdef G_OS_WIN32
1102 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1103 int retval;
1104 int save_errno;
1105
1106 if (wfilename == NULL)
1107 {
1108 errno = EINVAL;
1109 return -1;
1110 }
1111
1112 retval = _wcreat (wfilename, mode);
1113 save_errno = errno;
1114
1115 g_free (wfilename);
1116
1117 errno = save_errno;
1118 return retval;
1119 #else
1120 return creat (filename, mode);
1121 #endif
1122 }
1123
1124 /**
1125 * g_rename:
1126 * @oldfilename: (type filename): a pathname in the GLib file name encoding
1127 * (UTF-8 on Windows)
1128 * @newfilename: (type filename): a pathname in the GLib file name encoding
1129 *
1130 * A wrapper for the POSIX rename() function. The rename() function
1131 * renames a file, moving it between directories if required.
1132 *
1133 * See your C library manual for more details about how rename() works
1134 * on your system. It is not possible in general on Windows to rename
1135 * a file that is open to some process.
1136 *
1137 * Returns: 0 if the renaming succeeded, -1 if an error occurred
1138 *
1139 * Since: 2.6
1140 */
1141 int
g_rename(const gchar * oldfilename,const gchar * newfilename)1142 g_rename (const gchar *oldfilename,
1143 const gchar *newfilename)
1144 {
1145 #ifdef G_OS_WIN32
1146 wchar_t *woldfilename = g_utf8_to_utf16 (oldfilename, -1, NULL, NULL, NULL);
1147 wchar_t *wnewfilename;
1148 int retval;
1149 int save_errno = 0;
1150
1151 if (woldfilename == NULL)
1152 {
1153 errno = EINVAL;
1154 return -1;
1155 }
1156
1157 wnewfilename = g_utf8_to_utf16 (newfilename, -1, NULL, NULL, NULL);
1158
1159 if (wnewfilename == NULL)
1160 {
1161 g_free (woldfilename);
1162 errno = EINVAL;
1163 return -1;
1164 }
1165
1166 if (MoveFileExW (woldfilename, wnewfilename, MOVEFILE_REPLACE_EXISTING))
1167 retval = 0;
1168 else
1169 {
1170 retval = -1;
1171 save_errno = w32_error_to_errno (GetLastError ());
1172 }
1173
1174 g_free (woldfilename);
1175 g_free (wnewfilename);
1176
1177 errno = save_errno;
1178 return retval;
1179 #else
1180 return rename (oldfilename, newfilename);
1181 #endif
1182 }
1183
1184 /**
1185 * g_mkdir:
1186 * @filename: (type filename): a pathname in the GLib file name encoding
1187 * (UTF-8 on Windows)
1188 * @mode: permissions to use for the newly created directory
1189 *
1190 * A wrapper for the POSIX mkdir() function. The mkdir() function
1191 * attempts to create a directory with the given name and permissions.
1192 * The mode argument is ignored on Windows.
1193 *
1194 * See your C library manual for more details about mkdir().
1195 *
1196 * Returns: 0 if the directory was successfully created, -1 if an error
1197 * occurred
1198 *
1199 * Since: 2.6
1200 */
1201 int
g_mkdir(const gchar * filename,int mode)1202 g_mkdir (const gchar *filename,
1203 int mode)
1204 {
1205 #ifdef G_OS_WIN32
1206 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1207 int retval;
1208 int save_errno;
1209
1210 if (wfilename == NULL)
1211 {
1212 errno = EINVAL;
1213 return -1;
1214 }
1215
1216 retval = _wmkdir (wfilename);
1217 save_errno = errno;
1218
1219 g_free (wfilename);
1220
1221 errno = save_errno;
1222 return retval;
1223 #else
1224 return mkdir (filename, mode);
1225 #endif
1226 }
1227
1228 /**
1229 * g_chdir:
1230 * @path: (type filename): a pathname in the GLib file name encoding
1231 * (UTF-8 on Windows)
1232 *
1233 * A wrapper for the POSIX chdir() function. The function changes the
1234 * current directory of the process to @path.
1235 *
1236 * See your C library manual for more details about chdir().
1237 *
1238 * Returns: 0 on success, -1 if an error occurred.
1239 *
1240 * Since: 2.8
1241 */
1242 int
g_chdir(const gchar * path)1243 g_chdir (const gchar *path)
1244 {
1245 #ifdef G_OS_WIN32
1246 wchar_t *wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
1247 int retval;
1248 int save_errno;
1249
1250 if (wpath == NULL)
1251 {
1252 errno = EINVAL;
1253 return -1;
1254 }
1255
1256 retval = _wchdir (wpath);
1257 save_errno = errno;
1258
1259 g_free (wpath);
1260
1261 errno = save_errno;
1262 return retval;
1263 #else
1264 return chdir (path);
1265 #endif
1266 }
1267
1268 /**
1269 * GStatBuf:
1270 *
1271 * A type corresponding to the appropriate struct type for the stat()
1272 * system call, depending on the platform and/or compiler being used.
1273 *
1274 * See g_stat() for more information.
1275 */
1276 /**
1277 * g_stat:
1278 * @filename: (type filename): a pathname in the GLib file name encoding
1279 * (UTF-8 on Windows)
1280 * @buf: a pointer to a stat struct, which will be filled with the file
1281 * information
1282 *
1283 * A wrapper for the POSIX stat() function. The stat() function
1284 * returns information about a file. On Windows the stat() function in
1285 * the C library checks only the FAT-style READONLY attribute and does
1286 * not look at the ACL at all. Thus on Windows the protection bits in
1287 * the @st_mode field are a fabrication of little use.
1288 *
1289 * On Windows the Microsoft C libraries have several variants of the
1290 * stat struct and stat() function with names like _stat(), _stat32(),
1291 * _stat32i64() and _stat64i32(). The one used here is for 32-bit code
1292 * the one with 32-bit size and time fields, specifically called _stat32().
1293 *
1294 * In Microsoft's compiler, by default struct stat means one with
1295 * 64-bit time fields while in MinGW struct stat is the legacy one
1296 * with 32-bit fields. To hopefully clear up this messs, the gstdio.h
1297 * header defines a type #GStatBuf which is the appropriate struct type
1298 * depending on the platform and/or compiler being used. On POSIX it
1299 * is just struct stat, but note that even on POSIX platforms, stat()
1300 * might be a macro.
1301 *
1302 * See your C library manual for more details about stat().
1303 *
1304 * Returns: 0 if the information was successfully retrieved,
1305 * -1 if an error occurred
1306 *
1307 * Since: 2.6
1308 */
1309 int
g_stat(const gchar * filename,GStatBuf * buf)1310 g_stat (const gchar *filename,
1311 GStatBuf *buf)
1312 {
1313 #ifdef G_OS_WIN32
1314 GWin32PrivateStat w32_buf;
1315 int retval = g_win32_stat_utf8 (filename, &w32_buf);
1316
1317 buf->st_dev = w32_buf.st_dev;
1318 buf->st_ino = w32_buf.st_ino;
1319 buf->st_mode = w32_buf.st_mode;
1320 buf->st_nlink = w32_buf.st_nlink;
1321 buf->st_uid = w32_buf.st_uid;
1322 buf->st_gid = w32_buf.st_gid;
1323 buf->st_rdev = w32_buf.st_dev;
1324 buf->st_size = w32_buf.st_size;
1325 buf->st_atime = w32_buf.st_atime;
1326 buf->st_mtime = w32_buf.st_mtime;
1327 buf->st_ctime = w32_buf.st_ctime;
1328
1329 return retval;
1330 #else
1331 return stat (filename, buf);
1332 #endif
1333 }
1334
1335 /**
1336 * g_lstat:
1337 * @filename: (type filename): a pathname in the GLib file name encoding
1338 * (UTF-8 on Windows)
1339 * @buf: a pointer to a stat struct, which will be filled with the file
1340 * information
1341 *
1342 * A wrapper for the POSIX lstat() function. The lstat() function is
1343 * like stat() except that in the case of symbolic links, it returns
1344 * information about the symbolic link itself and not the file that it
1345 * refers to. If the system does not support symbolic links g_lstat()
1346 * is identical to g_stat().
1347 *
1348 * See your C library manual for more details about lstat().
1349 *
1350 * Returns: 0 if the information was successfully retrieved,
1351 * -1 if an error occurred
1352 *
1353 * Since: 2.6
1354 */
1355 int
g_lstat(const gchar * filename,GStatBuf * buf)1356 g_lstat (const gchar *filename,
1357 GStatBuf *buf)
1358 {
1359 #ifdef HAVE_LSTAT
1360 /* This can't be Win32, so don't do the widechar dance. */
1361 return lstat (filename, buf);
1362 #elif defined (G_OS_WIN32)
1363 GWin32PrivateStat w32_buf;
1364 int retval = g_win32_lstat_utf8 (filename, &w32_buf);
1365
1366 buf->st_dev = w32_buf.st_dev;
1367 buf->st_ino = w32_buf.st_ino;
1368 buf->st_mode = w32_buf.st_mode;
1369 buf->st_nlink = w32_buf.st_nlink;
1370 buf->st_uid = w32_buf.st_uid;
1371 buf->st_gid = w32_buf.st_gid;
1372 buf->st_rdev = w32_buf.st_dev;
1373 buf->st_size = w32_buf.st_size;
1374 buf->st_atime = w32_buf.st_atime;
1375 buf->st_mtime = w32_buf.st_mtime;
1376 buf->st_ctime = w32_buf.st_ctime;
1377
1378 return retval;
1379 #else
1380 return g_stat (filename, buf);
1381 #endif
1382 }
1383
1384 /**
1385 * g_unlink:
1386 * @filename: (type filename): a pathname in the GLib file name encoding
1387 * (UTF-8 on Windows)
1388 *
1389 * A wrapper for the POSIX unlink() function. The unlink() function
1390 * deletes a name from the filesystem. If this was the last link to the
1391 * file and no processes have it opened, the diskspace occupied by the
1392 * file is freed.
1393 *
1394 * See your C library manual for more details about unlink(). Note
1395 * that on Windows, it is in general not possible to delete files that
1396 * are open to some process, or mapped into memory.
1397 *
1398 * Returns: 0 if the name was successfully deleted, -1 if an error
1399 * occurred
1400 *
1401 * Since: 2.6
1402 */
1403 int
g_unlink(const gchar * filename)1404 g_unlink (const gchar *filename)
1405 {
1406 #ifdef G_OS_WIN32
1407 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1408 int retval;
1409 int save_errno;
1410
1411 if (wfilename == NULL)
1412 {
1413 errno = EINVAL;
1414 return -1;
1415 }
1416
1417 retval = _wunlink (wfilename);
1418 save_errno = errno;
1419
1420 g_free (wfilename);
1421
1422 errno = save_errno;
1423 return retval;
1424 #else
1425 return unlink (filename);
1426 #endif
1427 }
1428
1429 /**
1430 * g_remove:
1431 * @filename: (type filename): a pathname in the GLib file name encoding
1432 * (UTF-8 on Windows)
1433 *
1434 * A wrapper for the POSIX remove() function. The remove() function
1435 * deletes a name from the filesystem.
1436 *
1437 * See your C library manual for more details about how remove() works
1438 * on your system. On Unix, remove() removes also directories, as it
1439 * calls unlink() for files and rmdir() for directories. On Windows,
1440 * although remove() in the C library only works for files, this
1441 * function tries first remove() and then if that fails rmdir(), and
1442 * thus works for both files and directories. Note however, that on
1443 * Windows, it is in general not possible to remove a file that is
1444 * open to some process, or mapped into memory.
1445 *
1446 * If this function fails on Windows you can't infer too much from the
1447 * errno value. rmdir() is tried regardless of what caused remove() to
1448 * fail. Any errno value set by remove() will be overwritten by that
1449 * set by rmdir().
1450 *
1451 * Returns: 0 if the file was successfully removed, -1 if an error
1452 * occurred
1453 *
1454 * Since: 2.6
1455 */
1456 int
g_remove(const gchar * filename)1457 g_remove (const gchar *filename)
1458 {
1459 #ifdef G_OS_WIN32
1460 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1461 int retval;
1462 int save_errno;
1463
1464 if (wfilename == NULL)
1465 {
1466 errno = EINVAL;
1467 return -1;
1468 }
1469
1470 retval = _wremove (wfilename);
1471 if (retval == -1)
1472 retval = _wrmdir (wfilename);
1473 save_errno = errno;
1474
1475 g_free (wfilename);
1476
1477 errno = save_errno;
1478 return retval;
1479 #else
1480 return remove (filename);
1481 #endif
1482 }
1483
1484 /**
1485 * g_rmdir:
1486 * @filename: (type filename): a pathname in the GLib file name encoding
1487 * (UTF-8 on Windows)
1488 *
1489 * A wrapper for the POSIX rmdir() function. The rmdir() function
1490 * deletes a directory from the filesystem.
1491 *
1492 * See your C library manual for more details about how rmdir() works
1493 * on your system.
1494 *
1495 * Returns: 0 if the directory was successfully removed, -1 if an error
1496 * occurred
1497 *
1498 * Since: 2.6
1499 */
1500 int
g_rmdir(const gchar * filename)1501 g_rmdir (const gchar *filename)
1502 {
1503 #ifdef G_OS_WIN32
1504 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1505 int retval;
1506 int save_errno;
1507
1508 if (wfilename == NULL)
1509 {
1510 errno = EINVAL;
1511 return -1;
1512 }
1513
1514 retval = _wrmdir (wfilename);
1515 save_errno = errno;
1516
1517 g_free (wfilename);
1518
1519 errno = save_errno;
1520 return retval;
1521 #else
1522 return rmdir (filename);
1523 #endif
1524 }
1525
1526 /**
1527 * g_fopen:
1528 * @filename: (type filename): a pathname in the GLib file name encoding
1529 * (UTF-8 on Windows)
1530 * @mode: a string describing the mode in which the file should be opened
1531 *
1532 * A wrapper for the stdio fopen() function. The fopen() function
1533 * opens a file and associates a new stream with it.
1534 *
1535 * Because file descriptors are specific to the C library on Windows,
1536 * and a file descriptor is part of the FILE struct, the FILE* returned
1537 * by this function makes sense only to functions in the same C library.
1538 * Thus if the GLib-using code uses a different C library than GLib does,
1539 * the FILE* returned by this function cannot be passed to C library
1540 * functions like fprintf() or fread().
1541 *
1542 * See your C library manual for more details about fopen().
1543 *
1544 * Returns: A FILE* if the file was successfully opened, or %NULL if
1545 * an error occurred
1546 *
1547 * Since: 2.6
1548 */
1549 FILE *
g_fopen(const gchar * filename,const gchar * mode)1550 g_fopen (const gchar *filename,
1551 const gchar *mode)
1552 {
1553 #ifdef G_OS_WIN32
1554 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1555 wchar_t *wmode;
1556 FILE *retval;
1557 int save_errno;
1558
1559 if (wfilename == NULL)
1560 {
1561 errno = EINVAL;
1562 return NULL;
1563 }
1564
1565 wmode = g_utf8_to_utf16 (mode, -1, NULL, NULL, NULL);
1566
1567 if (wmode == NULL)
1568 {
1569 g_free (wfilename);
1570 errno = EINVAL;
1571 return NULL;
1572 }
1573
1574 _g_win32_fix_mode (wmode);
1575 retval = _wfopen (wfilename, wmode);
1576 save_errno = errno;
1577
1578 g_free (wfilename);
1579 g_free (wmode);
1580
1581 errno = save_errno;
1582 return retval;
1583 #else
1584 return fopen (filename, mode);
1585 #endif
1586 }
1587
1588 /**
1589 * g_freopen:
1590 * @filename: (type filename): a pathname in the GLib file name encoding
1591 * (UTF-8 on Windows)
1592 * @mode: a string describing the mode in which the file should be opened
1593 * @stream: (nullable): an existing stream which will be reused, or %NULL
1594 *
1595 * A wrapper for the POSIX freopen() function. The freopen() function
1596 * opens a file and associates it with an existing stream.
1597 *
1598 * See your C library manual for more details about freopen().
1599 *
1600 * Returns: A FILE* if the file was successfully opened, or %NULL if
1601 * an error occurred.
1602 *
1603 * Since: 2.6
1604 */
1605 FILE *
g_freopen(const gchar * filename,const gchar * mode,FILE * stream)1606 g_freopen (const gchar *filename,
1607 const gchar *mode,
1608 FILE *stream)
1609 {
1610 #ifdef G_OS_WIN32
1611 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1612 wchar_t *wmode;
1613 FILE *retval;
1614 int save_errno;
1615
1616 if (wfilename == NULL)
1617 {
1618 errno = EINVAL;
1619 return NULL;
1620 }
1621
1622 wmode = g_utf8_to_utf16 (mode, -1, NULL, NULL, NULL);
1623
1624 if (wmode == NULL)
1625 {
1626 g_free (wfilename);
1627 errno = EINVAL;
1628 return NULL;
1629 }
1630
1631 _g_win32_fix_mode (wmode);
1632 retval = _wfreopen (wfilename, wmode, stream);
1633 save_errno = errno;
1634
1635 g_free (wfilename);
1636 g_free (wmode);
1637
1638 errno = save_errno;
1639 return retval;
1640 #else
1641 return freopen (filename, mode, stream);
1642 #endif
1643 }
1644
1645 /**
1646 * g_utime:
1647 * @filename: (type filename): a pathname in the GLib file name encoding
1648 * (UTF-8 on Windows)
1649 * @utb: a pointer to a struct utimbuf.
1650 *
1651 * A wrapper for the POSIX utime() function. The utime() function
1652 * sets the access and modification timestamps of a file.
1653 *
1654 * See your C library manual for more details about how utime() works
1655 * on your system.
1656 *
1657 * Returns: 0 if the operation was successful, -1 if an error occurred
1658 *
1659 * Since: 2.18
1660 */
1661 int
g_utime(const gchar * filename,struct utimbuf * utb)1662 g_utime (const gchar *filename,
1663 struct utimbuf *utb)
1664 {
1665 #ifdef G_OS_WIN32
1666 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1667 int retval;
1668 int save_errno;
1669
1670 if (wfilename == NULL)
1671 {
1672 errno = EINVAL;
1673 return -1;
1674 }
1675
1676 retval = _wutime (wfilename, (struct _utimbuf*) utb);
1677 save_errno = errno;
1678
1679 g_free (wfilename);
1680
1681 errno = save_errno;
1682 return retval;
1683 #else
1684 return utime (filename, utb);
1685 #endif
1686 }
1687
1688 /**
1689 * g_close:
1690 * @fd: A file descriptor
1691 * @error: a #GError
1692 *
1693 * This wraps the close() call; in case of error, %errno will be
1694 * preserved, but the error will also be stored as a #GError in @error.
1695 *
1696 * Besides using #GError, there is another major reason to prefer this
1697 * function over the call provided by the system; on Unix, it will
1698 * attempt to correctly handle %EINTR, which has platform-specific
1699 * semantics.
1700 *
1701 * Returns: %TRUE on success, %FALSE if there was an error.
1702 *
1703 * Since: 2.36
1704 */
1705 gboolean
g_close(gint fd,GError ** error)1706 g_close (gint fd,
1707 GError **error)
1708 {
1709 int res;
1710 res = close (fd);
1711 /* Just ignore EINTR for now; a retry loop is the wrong thing to do
1712 * on Linux at least. Anyone who wants to add a conditional check
1713 * for e.g. HP-UX is welcome to do so later...
1714 *
1715 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
1716 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
1717 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
1718 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
1719 */
1720 if (G_UNLIKELY (res == -1 && errno == EINTR))
1721 return TRUE;
1722 else if (res == -1)
1723 {
1724 int errsv = errno;
1725 g_set_error_literal (error, G_FILE_ERROR,
1726 g_file_error_from_errno (errsv),
1727 g_strerror (errsv));
1728 errno = errsv;
1729 return FALSE;
1730 }
1731 return TRUE;
1732 }
1733
1734