1 /* gstdio.c - wrappers for C library functions
3 * Copyright 2004 Tor Lillqvist
5 * SPDX-License-Identifier: LGPL-2.1-or-later
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this library; if not, see <http://www.gnu.org/licenses/>.
22 #include "glibconfig.h"
24 /* Don’t redefine (for example) g_open() to open(), since we actually want to
25 * define g_open() in this file and export it as a symbol. See gstdio.h. */
26 #define G_STDIO_WRAP_ON_UNIX
28 #include <sys/types.h>
42 #include <sys/utime.h>
43 #include <stdlib.h> /* for MB_CUR_MAX */
50 #include "gstdioprivate.h"
52 #if !defined (G_OS_UNIX) && !defined (G_OS_WIN32)
53 #error Please port this to your operating system
56 #if defined (_MSC_VER) && !defined(_WIN64)
58 #define _wstat _wstat32
61 #if defined (G_OS_WIN32)
63 /* We can't include Windows DDK and Windows SDK simultaneously,
64 * so let's copy this here from MinGW-w64 DDK.
65 * The structure is ultimately documented here:
66 * https://msdn.microsoft.com/en-us/library/ff552012(v=vs.85).aspx
68 typedef struct _REPARSE_DATA_BUFFER
71 USHORT ReparseDataLength;
77 USHORT SubstituteNameOffset;
78 USHORT SubstituteNameLength;
79 USHORT PrintNameOffset;
80 USHORT PrintNameLength;
83 } SymbolicLinkReparseBuffer;
86 USHORT SubstituteNameOffset;
87 USHORT SubstituteNameLength;
88 USHORT PrintNameOffset;
89 USHORT PrintNameLength;
91 } MountPointReparseBuffer;
95 } GenericReparseBuffer;
97 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
100 w32_error_to_errno (DWORD error_code)
104 case ERROR_ACCESS_DENIED:
107 case ERROR_ALREADY_EXISTS:
108 case ERROR_FILE_EXISTS:
110 case ERROR_FILE_NOT_FOUND:
113 case ERROR_INVALID_FUNCTION:
116 case ERROR_INVALID_HANDLE:
119 case ERROR_INVALID_PARAMETER:
122 case ERROR_LOCK_VIOLATION:
123 case ERROR_SHARING_VIOLATION:
126 case ERROR_NOT_ENOUGH_MEMORY:
127 case ERROR_OUTOFMEMORY:
130 case ERROR_NOT_SAME_DEVICE:
133 case ERROR_PATH_NOT_FOUND:
134 return ENOENT; /* or ELOOP, or ENAMETOOLONG */
142 #include "gstdio-private.c"
144 /* Windows implementation of fopen() does not accept modes such as
145 * "wb+". The 'b' needs to be appended to "w+", i.e. "w+b". Note
146 * that otherwise these 2 modes are supposed to be aliases, hence
147 * swappable at will. TODO: Is this still true?
150 _g_win32_fix_mode (wchar_t *mode)
155 ptr = wcschr (mode, L'+');
156 if (ptr != NULL && (ptr - mode) > 1)
165 * https://support.microsoft.com/en-ca/help/167296/how-to-convert-a-unix-time-t-to-a-win32-filetime-or-systemtime
166 * FT = UT * 10000000 + 116444736000000000.
168 * UT = (FT - 116444736000000000) / 10000000.
169 * Converts FILETIME to unix epoch time in form
170 * of a signed 64-bit integer (can be negative).
172 * The function that does the reverse can be found in
173 * gio/glocalfileinfo.c.
176 _g_win32_filetime_to_unix_time (const FILETIME *ft,
180 /* 1 unit of FILETIME is 100ns */
181 const gint64 hundreds_of_usec_per_sec = 10000000;
182 /* The difference between January 1, 1601 UTC (FILETIME epoch) and UNIX epoch
183 * in hundreds of nanoseconds.
185 const gint64 filetime_unix_epoch_offset = 116444736000000000;
187 result = ((gint64) ft->dwLowDateTime) | (((gint64) ft->dwHighDateTime) << 32);
188 result -= filetime_unix_epoch_offset;
191 *nsec = (result % hundreds_of_usec_per_sec) * 100;
193 return result / hundreds_of_usec_per_sec;
198 # define _S_IRUSR _S_IREAD
199 # define _S_IWUSR _S_IWRITE
200 # define _S_IXUSR _S_IEXEC
201 # define S_IRUSR _S_IRUSR
202 # define S_IWUSR _S_IWUSR
203 # define S_IXUSR _S_IXUSR
204 # define S_IRGRP (S_IRUSR >> 3)
205 # define S_IWGRP (S_IWUSR >> 3)
206 # define S_IXGRP (S_IXUSR >> 3)
207 # define S_IROTH (S_IRGRP >> 3)
208 # define S_IWOTH (S_IWGRP >> 3)
209 # define S_IXOTH (S_IXGRP >> 3)
212 # define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
216 /* Uses filename and BHFI to fill a stat64 structure.
217 * Tries to reproduce the behaviour and quirks of MS C runtime stat().
220 _g_win32_fill_statbuf_from_handle_info (const wchar_t *filename,
221 const wchar_t *filename_target,
222 const BY_HANDLE_FILE_INFORMATION *handle_info,
223 struct __stat64 *statbuf)
225 wchar_t drive_letter_w = 0;
226 size_t drive_letter_size = MB_CUR_MAX;
227 char *drive_letter = _alloca (drive_letter_size);
229 /* If filename (target or link) is absolute,
230 * then use the drive letter from it as-is.
232 if (filename_target != NULL &&
233 filename_target[0] != L'\0' &&
234 filename_target[1] == L':')
235 drive_letter_w = filename_target[0];
236 else if (filename[0] != L'\0' &&
238 drive_letter_w = filename[0];
240 if (drive_letter_w > 0 &&
241 iswalpha (drive_letter_w) &&
242 iswascii (drive_letter_w) &&
243 wctomb (drive_letter, drive_letter_w) == 1)
244 statbuf->st_dev = toupper (drive_letter[0]) - 'A'; /* 0 means A: drive */
246 /* Otherwise use the PWD drive.
247 * Return value of 0 gives us 0 - 1 = -1,
248 * which is the "no idea" value for st_dev.
250 statbuf->st_dev = _getdrive () - 1;
252 statbuf->st_rdev = statbuf->st_dev;
253 /* Theoretically, it's possible to set it for ext-FS. No idea how.
254 * Meaningless for all filesystems that Windows normally uses.
257 statbuf->st_mode = 0;
259 if ((handle_info->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
260 statbuf->st_mode |= S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
262 statbuf->st_mode |= S_IFREG;
263 /* No idea what S_IFCHR means here. */
264 /* S_IFIFO is not even mentioned in MSDN */
265 /* S_IFBLK is also not mentioned */
267 /* The aim here is to reproduce MS stat() behaviour,
268 * even if it's braindead.
270 statbuf->st_mode |= S_IRUSR | S_IRGRP | S_IROTH;
271 if ((handle_info->dwFileAttributes & FILE_ATTRIBUTE_READONLY) != FILE_ATTRIBUTE_READONLY)
272 statbuf->st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
274 if (!S_ISDIR (statbuf->st_mode))
277 const wchar_t *dot = NULL;
279 if (filename_target != NULL)
280 name = filename_target;
286 wchar_t *last_dot = wcschr (name, L'.');
287 if (last_dot == NULL)
295 (wcsicmp (dot, L".exe") == 0 ||
296 wcsicmp (dot, L".com") == 0 ||
297 wcsicmp (dot, L".bat") == 0 ||
298 wcsicmp (dot, L".cmd") == 0)))
299 statbuf->st_mode |= S_IXUSR | S_IXGRP | S_IXOTH;
302 statbuf->st_nlink = handle_info->nNumberOfLinks;
303 statbuf->st_uid = statbuf->st_gid = 0;
304 statbuf->st_size = (((guint64) handle_info->nFileSizeHigh) << 32) | handle_info->nFileSizeLow;
305 statbuf->st_ctime = _g_win32_filetime_to_unix_time (&handle_info->ftCreationTime, NULL);
306 statbuf->st_mtime = _g_win32_filetime_to_unix_time (&handle_info->ftLastWriteTime, NULL);
307 statbuf->st_atime = _g_win32_filetime_to_unix_time (&handle_info->ftLastAccessTime, NULL);
312 /* Fills our private stat-like structure using data from
313 * a normal stat64 struct, BHFI, FSI and a reparse tag.
316 _g_win32_fill_privatestat (const struct __stat64 *statbuf,
317 const BY_HANDLE_FILE_INFORMATION *handle_info,
318 const FILE_STANDARD_INFO *std_info,
320 GWin32PrivateStat *buf)
324 buf->st_dev = statbuf->st_dev;
325 buf->st_ino = statbuf->st_ino;
326 buf->st_mode = statbuf->st_mode;
327 buf->volume_serial = handle_info->dwVolumeSerialNumber;
328 buf->file_index = (((guint64) handle_info->nFileIndexHigh) << 32) | handle_info->nFileIndexLow;
329 buf->attributes = handle_info->dwFileAttributes;
330 buf->st_nlink = handle_info->nNumberOfLinks;
331 buf->st_size = (((guint64) handle_info->nFileSizeHigh) << 32) | handle_info->nFileSizeLow;
332 buf->allocated_size = std_info->AllocationSize.QuadPart;
334 buf->reparse_tag = reparse_tag;
336 buf->st_ctim.tv_sec = _g_win32_filetime_to_unix_time (&handle_info->ftCreationTime, &nsec);
337 buf->st_ctim.tv_nsec = nsec;
338 buf->st_mtim.tv_sec = _g_win32_filetime_to_unix_time (&handle_info->ftLastWriteTime, &nsec);
339 buf->st_mtim.tv_nsec = nsec;
340 buf->st_atim.tv_sec = _g_win32_filetime_to_unix_time (&handle_info->ftLastAccessTime, &nsec);
341 buf->st_atim.tv_nsec = nsec;
344 /* Read the link data from a symlink/mountpoint represented
345 * by the handle. Also reads reparse tag.
346 * @reparse_tag receives the tag. Can be %NULL if @buf or @alloc_buf
348 * @buf receives the link data. Can be %NULL if reparse_tag is non-%NULL.
349 * Mutually-exclusive with @alloc_buf.
350 * @buf_size is the size of the @buf, in bytes.
351 * @alloc_buf points to a location where internally-allocated buffer
352 * pointer will be written. That buffer receives the
353 * link data. Mutually-exclusive with @buf.
354 * @terminate ensures that the buffer is NUL-terminated if
355 * it isn't already. Note that this can erase useful
356 * data if @buf is provided and @buf_size is too small.
357 * Specifically, with @buf_size <= 2 the buffer will
358 * receive an empty string, even if there is some
359 * data in the reparse point.
360 * The contents of @buf or @alloc_buf are presented as-is - could
361 * be non-NUL-terminated (unless @terminate is %TRUE) or even malformed.
362 * Returns the number of bytes (!) placed into @buf or @alloc_buf,
363 * including NUL-terminator (if any).
365 * Returned value of 0 means that there's no recognizable data in the
366 * reparse point. @alloc_buf will not be allocated in that case,
367 * and @buf will be left unmodified.
369 * If @buf and @alloc_buf are %NULL, returns 0 to indicate success.
370 * Returns -1 to indicate an error, sets errno.
373 _g_win32_readlink_handle_raw (HANDLE h,
377 gunichar2 **alloc_buf,
381 DWORD returned_bytes = 0;
384 /* This is 16k. It's impossible to make DeviceIoControl() tell us
385 * the required size. NtFsControlFile() does have such a feature,
386 * but for some reason it doesn't work with CreateFile()-returned handles.
387 * The only alternative is to repeatedly call DeviceIoControl()
388 * with bigger and bigger buffers, until it succeeds.
389 * We choose to sacrifice stack space for speed.
391 BYTE max_buffer[sizeof (REPARSE_DATA_BUFFER) + MAXIMUM_REPARSE_DATA_BUFFER_SIZE] = {0,};
392 DWORD max_buffer_size = sizeof (REPARSE_DATA_BUFFER) + MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
393 REPARSE_DATA_BUFFER *rep_buf;
395 g_return_val_if_fail ((buf != NULL || alloc_buf != NULL || reparse_tag != NULL) &&
396 (buf == NULL || alloc_buf == NULL),
399 if (!DeviceIoControl (h, FSCTL_GET_REPARSE_POINT, NULL, 0,
402 &returned_bytes, NULL))
404 error_code = GetLastError ();
405 errno = w32_error_to_errno (error_code);
409 rep_buf = (REPARSE_DATA_BUFFER *) max_buffer;
411 if (reparse_tag != NULL)
412 *reparse_tag = rep_buf->ReparseTag;
414 if (buf == NULL && alloc_buf == NULL)
417 if (rep_buf->ReparseTag == IO_REPARSE_TAG_SYMLINK)
419 data = &((BYTE *) rep_buf->SymbolicLinkReparseBuffer.PathBuffer)[rep_buf->SymbolicLinkReparseBuffer.SubstituteNameOffset];
421 to_copy = rep_buf->SymbolicLinkReparseBuffer.SubstituteNameLength;
423 else if (rep_buf->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
425 data = &((BYTE *) rep_buf->MountPointReparseBuffer.PathBuffer)[rep_buf->MountPointReparseBuffer.SubstituteNameOffset];
427 to_copy = rep_buf->MountPointReparseBuffer.SubstituteNameLength;
432 return _g_win32_copy_and_maybe_terminate (data, to_copy, buf, buf_size, alloc_buf, terminate);
435 /* Read the link data from a symlink/mountpoint represented
437 * @filename is the name of the file.
438 * @reparse_tag receives the tag. Can be %NULL if @buf or @alloc_buf
440 * @buf receives the link data. Mutually-exclusive with @alloc_buf.
441 * @buf_size is the size of the @buf, in bytes.
442 * @alloc_buf points to a location where internally-allocated buffer
443 * pointer will be written. That buffer receives the
444 * link data. Mutually-exclusive with @buf.
445 * @terminate ensures that the buffer is NUL-terminated if
447 * The contents of @buf or @alloc_buf are presented as-is - could
448 * be non-NUL-terminated (unless @terminate is TRUE) or even malformed.
449 * Returns the number of bytes (!) placed into @buf or @alloc_buf.
450 * Returned value of 0 means that there's no recognizable data in the
451 * reparse point. @alloc_buf will not be allocated in that case,
452 * and @buf will be left unmodified.
453 * If @buf and @alloc_buf are %NULL, returns 0 to indicate success.
454 * Returns -1 to indicate an error, sets errno.
457 _g_win32_readlink_utf16_raw (const gunichar2 *filename,
461 gunichar2 **alloc_buf,
469 if ((attributes = GetFileAttributesW (filename)) == 0)
471 error_code = GetLastError ();
472 errno = w32_error_to_errno (error_code);
476 if ((attributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
482 /* To read symlink target we need to open the file as a reparse
483 * point and use DeviceIoControl() on it.
485 h = CreateFileW (filename,
487 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
489 FILE_ATTRIBUTE_NORMAL
490 | FILE_FLAG_OPEN_REPARSE_POINT
491 | (attributes & FILE_ATTRIBUTE_DIRECTORY ? FILE_FLAG_BACKUP_SEMANTICS : 0),
494 if (h == INVALID_HANDLE_VALUE)
496 error_code = GetLastError ();
497 errno = w32_error_to_errno (error_code);
501 to_copy = _g_win32_readlink_handle_raw (h, reparse_tag, buf, buf_size, alloc_buf, terminate);
508 /* Read the link data from a symlink/mountpoint represented
509 * by a UTF-16 filename or a file handle.
510 * @filename is the name of the file. Mutually-exclusive with @file_handle.
511 * @file_handle is the handle of the file. Mutually-exclusive with @filename.
512 * @reparse_tag receives the tag. Can be %NULL if @buf or @alloc_buf
514 * @buf receives the link data. Mutually-exclusive with @alloc_buf.
515 * @buf_size is the size of the @buf, in bytes.
516 * @alloc_buf points to a location where internally-allocated buffer
517 * pointer will be written. That buffer receives the
518 * link data. Mutually-exclusive with @buf.
519 * @terminate ensures that the buffer is NUL-terminated if
521 * The contents of @buf or @alloc_buf are adjusted
522 * (extended or nt object manager prefix is stripped),
523 * but otherwise they are presented as-is - could be non-NUL-terminated
524 * (unless @terminate is TRUE) or even malformed.
525 * Returns the number of bytes (!) placed into @buf or @alloc_buf.
526 * Returned value of 0 means that there's no recognizable data in the
527 * reparse point. @alloc_buf will not be allocated in that case,
528 * and @buf will be left unmodified.
529 * Returns -1 to indicate an error, sets errno.
532 _g_win32_readlink_utf16_handle (const gunichar2 *filename,
537 gunichar2 **alloc_buf,
543 g_return_val_if_fail ((buf != NULL || alloc_buf != NULL || reparse_tag != NULL) &&
544 (filename != NULL || file_handle != NULL) &&
545 (buf == NULL || alloc_buf == NULL) &&
546 (filename == NULL || file_handle == NULL),
550 result = _g_win32_readlink_utf16_raw (filename, reparse_tag, buf, buf_size, alloc_buf, terminate);
552 result = _g_win32_readlink_handle_raw (file_handle, reparse_tag, buf, buf_size, alloc_buf, terminate);
557 /* Ensure that output is a multiple of sizeof (gunichar2),
558 * cutting any trailing partial gunichar2, if present.
560 result -= result % sizeof (gunichar2);
565 /* DeviceIoControl () tends to return filenames as NT Object Manager
566 * names , i.e. "\\??\\C:\\foo\\bar".
567 * Remove the leading 4-byte "\\??\\" prefix, as glib (as well as many W32 API
568 * functions) is unprepared to deal with it. Unless it has no 'x:' drive
569 * letter part after the prefix, in which case we leave everything
570 * as-is, because the path could be "\\??\\Volume{GUID}" - stripping
571 * the prefix will allow it to be confused with relative links
572 * targeting "Volume{GUID}".
574 string_size = result / sizeof (gunichar2);
575 _g_win32_strip_extended_ntobjm_prefix (buf ? buf : *alloc_buf, &string_size);
577 return string_size * sizeof (gunichar2);
580 /* Works like stat() or lstat(), depending on the value of @for_symlink,
581 * but accepts filename in UTF-16 and fills our custom stat structure.
582 * The @filename must not have trailing slashes.
585 _g_win32_stat_utf16_no_trailing_slashes (const gunichar2 *filename,
586 GWin32PrivateStat *buf,
587 gboolean for_symlink)
589 struct __stat64 statbuf;
590 BY_HANDLE_FILE_INFORMATION handle_info;
591 FILE_STANDARD_INFO std_info;
592 gboolean is_symlink = FALSE;
593 wchar_t *filename_target = NULL;
594 DWORD immediate_attributes;
596 gboolean is_directory;
597 DWORD reparse_tag = 0;
599 BOOL succeeded_so_far;
602 immediate_attributes = GetFileAttributesW (filename);
604 if (immediate_attributes == INVALID_FILE_ATTRIBUTES)
606 error_code = GetLastError ();
607 errno = w32_error_to_errno (error_code);
612 is_symlink = (immediate_attributes & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT;
613 is_directory = (immediate_attributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY;
615 open_flags = FILE_ATTRIBUTE_NORMAL;
617 if (for_symlink && is_symlink)
618 open_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
621 open_flags |= FILE_FLAG_BACKUP_SEMANTICS;
623 file_handle = CreateFileW (filename, FILE_READ_ATTRIBUTES | FILE_READ_EA,
624 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
629 if (file_handle == INVALID_HANDLE_VALUE)
631 error_code = GetLastError ();
632 errno = w32_error_to_errno (error_code);
636 succeeded_so_far = GetFileInformationByHandle (file_handle,
638 error_code = GetLastError ();
640 if (succeeded_so_far)
642 succeeded_so_far = GetFileInformationByHandleEx (file_handle,
646 error_code = GetLastError ();
649 if (!succeeded_so_far)
651 CloseHandle (file_handle);
652 errno = w32_error_to_errno (error_code);
656 /* It's tempting to use GetFileInformationByHandleEx(FileAttributeTagInfo),
657 * but it always reports that the ReparseTag is 0.
658 * We already have a handle open for symlink, use that.
659 * For the target we have to specify a filename, and the function
660 * will open another handle internally.
663 _g_win32_readlink_utf16_handle (for_symlink ? NULL : filename,
664 for_symlink ? file_handle : NULL,
667 for_symlink ? NULL : &filename_target,
670 CloseHandle (file_handle);
674 CloseHandle (file_handle);
676 _g_win32_fill_statbuf_from_handle_info (filename,
680 g_free (filename_target);
681 _g_win32_fill_privatestat (&statbuf,
690 /* Works like fstat(), but fills our custom stat structure. */
692 _g_win32_stat_fd (int fd,
693 GWin32PrivateStat *buf)
696 gboolean succeeded_so_far;
698 struct __stat64 statbuf;
699 BY_HANDLE_FILE_INFORMATION handle_info;
700 FILE_STANDARD_INFO std_info;
701 DWORD reparse_tag = 0;
702 gboolean is_symlink = FALSE;
704 file_handle = (HANDLE) _get_osfhandle (fd);
706 if (file_handle == INVALID_HANDLE_VALUE)
709 succeeded_so_far = GetFileInformationByHandle (file_handle,
711 error_code = GetLastError ();
713 if (succeeded_so_far)
715 succeeded_so_far = GetFileInformationByHandleEx (file_handle,
719 error_code = GetLastError ();
722 if (!succeeded_so_far)
724 errno = w32_error_to_errno (error_code);
728 is_symlink = (handle_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT;
731 _g_win32_readlink_handle_raw (file_handle, &reparse_tag, NULL, 0, NULL, FALSE) < 0)
734 if (_fstat64 (fd, &statbuf) != 0)
737 _g_win32_fill_privatestat (&statbuf,
746 /* Works like stat() or lstat(), depending on the value of @for_symlink,
747 * but accepts filename in UTF-8 and fills our custom stat structure.
750 _g_win32_stat_utf8 (const gchar *filename,
751 GWin32PrivateStat *buf,
752 gboolean for_symlink)
758 if (filename == NULL)
764 len = strlen (filename);
766 while (len > 0 && G_IS_DIR_SEPARATOR (filename[len - 1]))
770 (g_path_is_absolute (filename) && len <= (gsize) (g_path_skip_root (filename) - filename)))
771 len = strlen (filename);
773 wfilename = g_utf8_to_utf16 (filename, len, NULL, NULL, NULL);
775 if (wfilename == NULL)
781 result = _g_win32_stat_utf16_no_trailing_slashes (wfilename, buf, for_symlink);
788 /* Works like stat(), but accepts filename in UTF-8
789 * and fills our custom stat structure.
792 g_win32_stat_utf8 (const gchar *filename,
793 GWin32PrivateStat *buf)
795 return _g_win32_stat_utf8 (filename, buf, FALSE);
798 /* Works like lstat(), but accepts filename in UTF-8
799 * and fills our custom stat structure.
802 g_win32_lstat_utf8 (const gchar *filename,
803 GWin32PrivateStat *buf)
805 return _g_win32_stat_utf8 (filename, buf, TRUE);
808 /* Works like fstat(), but accepts filename in UTF-8
809 * and fills our custom stat structure.
812 g_win32_fstat (int fd,
813 GWin32PrivateStat *buf)
815 return _g_win32_stat_fd (fd, buf);
819 * g_win32_readlink_utf8:
820 * @filename: (type filename): a pathname in UTF-8
821 * @buf: (array length=buf_size) : a buffer to receive the reparse point
822 * target path. Mutually-exclusive
824 * @buf_size: size of the @buf, in bytes
825 * @alloc_buf: points to a location where internally-allocated buffer
826 * pointer will be written. That buffer receives the
827 * link data. Mutually-exclusive with @buf.
828 * @terminate: ensures that the buffer is NUL-terminated if
829 * it isn't already. If %FALSE, the returned string
830 * might not be NUL-terminated (depends entirely on
831 * what the contents of the filesystem are).
833 * Tries to read the reparse point indicated by @filename, filling
834 * @buf or @alloc_buf with the path that the reparse point redirects to.
835 * The path will be UTF-8-encoded, and an extended path prefix
836 * or a NT object manager prefix will be removed from it, if
837 * possible, but otherwise the path is returned as-is. Specifically,
838 * it could be a "\\\\Volume{GUID}\\" path. It also might use
839 * backslashes as path separators.
841 * Returns: -1 on error (sets errno), 0 if there's no (recognizable)
842 * path in the reparse point (@alloc_buf will not be allocated in that case,
843 * and @buf will be left unmodified),
844 * or the number of bytes placed into @buf otherwise,
845 * including NUL-terminator (if present or if @terminate is TRUE).
846 * The buffer returned via @alloc_buf should be freed with g_free().
851 g_win32_readlink_utf8 (const gchar *filename,
863 g_return_val_if_fail ((buf != NULL || alloc_buf != NULL) &&
864 (buf == NULL || alloc_buf == NULL),
867 wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
869 if (wfilename == NULL)
875 result = _g_win32_readlink_utf16_handle (wfilename, NULL, NULL,
876 NULL, 0, &buf_utf16, terminate);
883 tmp = g_utf16_to_utf8 (buf_utf16,
884 result / sizeof (gunichar2),
903 if ((gsize) tmp_len > buf_size)
906 memcpy (buf, tmp, tmp_len);
916 * @filename: (type filename): a pathname in the GLib file name encoding
918 * @mode: as in access()
920 * A wrapper for the POSIX access() function. This function is used to
921 * test a pathname for one or several of read, write or execute
922 * permissions, or just existence.
924 * On Windows, the file protection mechanism is not at all POSIX-like,
925 * and the underlying function in the C library only checks the
926 * FAT-style READONLY attribute, and does not look at the ACL of a
927 * file at all. This function is this in practise almost useless on
928 * Windows. Software that needs to handle file permissions on Windows
929 * more exactly should use the Win32 API.
931 * See your C library manual for more details about access().
933 * Returns: zero if the pathname refers to an existing file system
934 * object that has all the tested permissions, or -1 otherwise
940 g_access (const gchar *filename,
944 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
948 if (wfilename == NULL)
958 retval = _waccess (wfilename, mode & ~X_OK);
966 return access (filename, mode);
972 * @filename: (type filename): a pathname in the GLib file name encoding
974 * @mode: as in chmod()
976 * A wrapper for the POSIX chmod() function. The chmod() function is
977 * used to set the permissions of a file system object.
979 * On Windows the file protection mechanism is not at all POSIX-like,
980 * and the underlying chmod() function in the C library just sets or
981 * clears the FAT-style READONLY attribute. It does not touch any
982 * ACL. Software that needs to manage file permissions on Windows
983 * exactly should use the Win32 API.
985 * See your C library manual for more details about chmod().
987 * Returns: 0 if the operation succeeded, -1 on error
992 g_chmod (const gchar *filename,
996 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1000 if (wfilename == NULL)
1006 retval = _wchmod (wfilename, mode);
1014 return chmod (filename, mode);
1019 * @filename: (type filename): a pathname in the GLib file name encoding
1020 * (UTF-8 on Windows)
1021 * @flags: as in open()
1022 * @mode: as in open()
1024 * A wrapper for the POSIX open() function. The open() function is
1025 * used to convert a pathname into a file descriptor.
1027 * On POSIX systems file descriptors are implemented by the operating
1028 * system. On Windows, it's the C library that implements open() and
1029 * file descriptors. The actual Win32 API for opening files is quite
1030 * different, see MSDN documentation for CreateFile(). The Win32 API
1031 * uses file handles, which are more randomish integers, not small
1032 * integers like file descriptors.
1034 * Because file descriptors are specific to the C library on Windows,
1035 * the file descriptor returned by this function makes sense only to
1036 * functions in the same C library. Thus if the GLib-using code uses a
1037 * different C library than GLib does, the file descriptor returned by
1038 * this function cannot be passed to C library functions like write()
1041 * See your C library manual for more details about open().
1043 * Returns: a new file descriptor, or -1 if an error occurred.
1044 * The return value can be used exactly like the return value
1050 g_open (const gchar *filename,
1055 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1059 if (wfilename == NULL)
1065 retval = _wopen (wfilename, flags, mode);
1075 fd = open (filename, flags, mode);
1076 while (G_UNLIKELY (fd == -1 && errno == EINTR));
1083 * @filename: (type filename): a pathname in the GLib file name encoding
1084 * (UTF-8 on Windows)
1085 * @mode: as in creat()
1087 * A wrapper for the POSIX creat() function. The creat() function is
1088 * used to convert a pathname into a file descriptor, creating a file
1091 * On POSIX systems file descriptors are implemented by the operating
1092 * system. On Windows, it's the C library that implements creat() and
1093 * file descriptors. The actual Windows API for opening files is
1094 * different, see MSDN documentation for CreateFile(). The Win32 API
1095 * uses file handles, which are more randomish integers, not small
1096 * integers like file descriptors.
1098 * Because file descriptors are specific to the C library on Windows,
1099 * the file descriptor returned by this function makes sense only to
1100 * functions in the same C library. Thus if the GLib-using code uses a
1101 * different C library than GLib does, the file descriptor returned by
1102 * this function cannot be passed to C library functions like write()
1105 * See your C library manual for more details about creat().
1107 * Returns: a new file descriptor, or -1 if an error occurred.
1108 * The return value can be used exactly like the return value
1114 g_creat (const gchar *filename,
1118 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1122 if (wfilename == NULL)
1128 retval = _wcreat (wfilename, mode);
1136 return creat (filename, mode);
1142 * @oldfilename: (type filename): a pathname in the GLib file name encoding
1143 * (UTF-8 on Windows)
1144 * @newfilename: (type filename): a pathname in the GLib file name encoding
1146 * A wrapper for the POSIX rename() function. The rename() function
1147 * renames a file, moving it between directories if required.
1149 * See your C library manual for more details about how rename() works
1150 * on your system. It is not possible in general on Windows to rename
1151 * a file that is open to some process.
1153 * Returns: 0 if the renaming succeeded, -1 if an error occurred
1158 g_rename (const gchar *oldfilename,
1159 const gchar *newfilename)
1162 wchar_t *woldfilename = g_utf8_to_utf16 (oldfilename, -1, NULL, NULL, NULL);
1163 wchar_t *wnewfilename;
1167 if (woldfilename == NULL)
1173 wnewfilename = g_utf8_to_utf16 (newfilename, -1, NULL, NULL, NULL);
1175 if (wnewfilename == NULL)
1177 g_free (woldfilename);
1182 if (MoveFileExW (woldfilename, wnewfilename, MOVEFILE_REPLACE_EXISTING))
1187 save_errno = w32_error_to_errno (GetLastError ());
1190 g_free (woldfilename);
1191 g_free (wnewfilename);
1196 return rename (oldfilename, newfilename);
1202 * @filename: (type filename): a pathname in the GLib file name encoding
1203 * (UTF-8 on Windows)
1204 * @mode: permissions to use for the newly created directory
1206 * A wrapper for the POSIX mkdir() function. The mkdir() function
1207 * attempts to create a directory with the given name and permissions.
1208 * The mode argument is ignored on Windows.
1210 * See your C library manual for more details about mkdir().
1212 * Returns: 0 if the directory was successfully created, -1 if an error
1218 g_mkdir (const gchar *filename,
1222 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1226 if (wfilename == NULL)
1232 retval = _wmkdir (wfilename);
1240 return mkdir (filename, mode);
1246 * @path: (type filename): a pathname in the GLib file name encoding
1247 * (UTF-8 on Windows)
1249 * A wrapper for the POSIX chdir() function. The function changes the
1250 * current directory of the process to @path.
1252 * See your C library manual for more details about chdir().
1254 * Returns: 0 on success, -1 if an error occurred.
1259 g_chdir (const gchar *path)
1262 wchar_t *wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
1272 retval = _wchdir (wpath);
1280 return chdir (path);
1287 * A type corresponding to the appropriate struct type for the stat()
1288 * system call, depending on the platform and/or compiler being used.
1290 * See g_stat() for more information.
1294 * @filename: (type filename): a pathname in the GLib file name encoding
1295 * (UTF-8 on Windows)
1296 * @buf: a pointer to a stat struct, which will be filled with the file
1299 * A wrapper for the POSIX stat() function. The stat() function
1300 * returns information about a file. On Windows the stat() function in
1301 * the C library checks only the FAT-style READONLY attribute and does
1302 * not look at the ACL at all. Thus on Windows the protection bits in
1303 * the @st_mode field are a fabrication of little use.
1305 * On Windows the Microsoft C libraries have several variants of the
1306 * stat struct and stat() function with names like _stat(), _stat32(),
1307 * _stat32i64() and _stat64i32(). The one used here is for 32-bit code
1308 * the one with 32-bit size and time fields, specifically called _stat32().
1310 * In Microsoft's compiler, by default struct stat means one with
1311 * 64-bit time fields while in MinGW struct stat is the legacy one
1312 * with 32-bit fields. To hopefully clear up this messs, the gstdio.h
1313 * header defines a type #GStatBuf which is the appropriate struct type
1314 * depending on the platform and/or compiler being used. On POSIX it
1315 * is just struct stat, but note that even on POSIX platforms, stat()
1318 * See your C library manual for more details about stat().
1320 * Returns: 0 if the information was successfully retrieved,
1321 * -1 if an error occurred
1326 g_stat (const gchar *filename,
1330 GWin32PrivateStat w32_buf;
1331 int retval = g_win32_stat_utf8 (filename, &w32_buf);
1333 buf->st_dev = w32_buf.st_dev;
1334 buf->st_ino = w32_buf.st_ino;
1335 buf->st_mode = w32_buf.st_mode;
1336 buf->st_nlink = w32_buf.st_nlink;
1337 buf->st_uid = w32_buf.st_uid;
1338 buf->st_gid = w32_buf.st_gid;
1339 buf->st_rdev = w32_buf.st_dev;
1340 buf->st_size = w32_buf.st_size;
1341 buf->st_atime = w32_buf.st_atim.tv_sec;
1342 buf->st_mtime = w32_buf.st_mtim.tv_sec;
1343 buf->st_ctime = w32_buf.st_ctim.tv_sec;
1347 return stat (filename, buf);
1353 * @filename: (type filename): a pathname in the GLib file name encoding
1354 * (UTF-8 on Windows)
1355 * @buf: a pointer to a stat struct, which will be filled with the file
1358 * A wrapper for the POSIX lstat() function. The lstat() function is
1359 * like stat() except that in the case of symbolic links, it returns
1360 * information about the symbolic link itself and not the file that it
1361 * refers to. If the system does not support symbolic links g_lstat()
1362 * is identical to g_stat().
1364 * See your C library manual for more details about lstat().
1366 * Returns: 0 if the information was successfully retrieved,
1367 * -1 if an error occurred
1372 g_lstat (const gchar *filename,
1376 /* This can't be Win32, so don't do the widechar dance. */
1377 return lstat (filename, buf);
1378 #elif defined (G_OS_WIN32)
1379 GWin32PrivateStat w32_buf;
1380 int retval = g_win32_lstat_utf8 (filename, &w32_buf);
1382 buf->st_dev = w32_buf.st_dev;
1383 buf->st_ino = w32_buf.st_ino;
1384 buf->st_mode = w32_buf.st_mode;
1385 buf->st_nlink = w32_buf.st_nlink;
1386 buf->st_uid = w32_buf.st_uid;
1387 buf->st_gid = w32_buf.st_gid;
1388 buf->st_rdev = w32_buf.st_dev;
1389 buf->st_size = w32_buf.st_size;
1390 buf->st_atime = w32_buf.st_atim.tv_sec;
1391 buf->st_mtime = w32_buf.st_mtim.tv_sec;
1392 buf->st_ctime = w32_buf.st_ctim.tv_sec;
1396 return g_stat (filename, buf);
1402 * @filename: (type filename): a pathname in the GLib file name encoding
1403 * (UTF-8 on Windows)
1405 * A wrapper for the POSIX unlink() function. The unlink() function
1406 * deletes a name from the filesystem. If this was the last link to the
1407 * file and no processes have it opened, the diskspace occupied by the
1410 * See your C library manual for more details about unlink(). Note
1411 * that on Windows, it is in general not possible to delete files that
1412 * are open to some process, or mapped into memory.
1414 * Returns: 0 if the name was successfully deleted, -1 if an error
1420 g_unlink (const gchar *filename)
1423 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1427 if (wfilename == NULL)
1433 retval = _wunlink (wfilename);
1441 return unlink (filename);
1447 * @filename: (type filename): a pathname in the GLib file name encoding
1448 * (UTF-8 on Windows)
1450 * A wrapper for the POSIX remove() function. The remove() function
1451 * deletes a name from the filesystem.
1453 * See your C library manual for more details about how remove() works
1454 * on your system. On Unix, remove() removes also directories, as it
1455 * calls unlink() for files and rmdir() for directories. On Windows,
1456 * although remove() in the C library only works for files, this
1457 * function tries first remove() and then if that fails rmdir(), and
1458 * thus works for both files and directories. Note however, that on
1459 * Windows, it is in general not possible to remove a file that is
1460 * open to some process, or mapped into memory.
1462 * If this function fails on Windows you can't infer too much from the
1463 * errno value. rmdir() is tried regardless of what caused remove() to
1464 * fail. Any errno value set by remove() will be overwritten by that
1467 * Returns: 0 if the file was successfully removed, -1 if an error
1473 g_remove (const gchar *filename)
1476 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1480 if (wfilename == NULL)
1486 retval = _wremove (wfilename);
1488 retval = _wrmdir (wfilename);
1496 return remove (filename);
1502 * @filename: (type filename): a pathname in the GLib file name encoding
1503 * (UTF-8 on Windows)
1505 * A wrapper for the POSIX rmdir() function. The rmdir() function
1506 * deletes a directory from the filesystem.
1508 * See your C library manual for more details about how rmdir() works
1511 * Returns: 0 if the directory was successfully removed, -1 if an error
1517 g_rmdir (const gchar *filename)
1520 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1524 if (wfilename == NULL)
1530 retval = _wrmdir (wfilename);
1538 return rmdir (filename);
1544 * @filename: (type filename): a pathname in the GLib file name encoding
1545 * (UTF-8 on Windows)
1546 * @mode: a string describing the mode in which the file should be opened
1548 * A wrapper for the stdio `fopen()` function. The `fopen()` function
1549 * opens a file and associates a new stream with it.
1551 * Because file descriptors are specific to the C library on Windows,
1552 * and a file descriptor is part of the `FILE` struct, the `FILE*` returned
1553 * by this function makes sense only to functions in the same C library.
1554 * Thus if the GLib-using code uses a different C library than GLib does,
1555 * the FILE* returned by this function cannot be passed to C library
1556 * functions like `fprintf()` or `fread()`.
1558 * See your C library manual for more details about `fopen()`.
1560 * As `close()` and `fclose()` are part of the C library, this implies that it is
1561 * currently impossible to close a file if the application C library and the C library
1562 * used by GLib are different. Convenience functions like g_file_set_contents_full()
1563 * avoid this problem.
1565 * Returns: A `FILE*` if the file was successfully opened, or %NULL if
1571 g_fopen (const gchar *filename,
1575 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1580 if (wfilename == NULL)
1586 wmode = g_utf8_to_utf16 (mode, -1, NULL, NULL, NULL);
1595 _g_win32_fix_mode (wmode);
1596 retval = _wfopen (wfilename, wmode);
1605 return fopen (filename, mode);
1611 * @filename: (type filename): a pathname in the GLib file name encoding
1612 * (UTF-8 on Windows)
1613 * @mode: a string describing the mode in which the file should be opened
1614 * @stream: (nullable): an existing stream which will be reused, or %NULL
1616 * A wrapper for the POSIX freopen() function. The freopen() function
1617 * opens a file and associates it with an existing stream.
1619 * See your C library manual for more details about freopen().
1621 * Returns: A FILE* if the file was successfully opened, or %NULL if
1622 * an error occurred.
1627 g_freopen (const gchar *filename,
1632 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1637 if (wfilename == NULL)
1643 wmode = g_utf8_to_utf16 (mode, -1, NULL, NULL, NULL);
1652 _g_win32_fix_mode (wmode);
1653 retval = _wfreopen (wfilename, wmode, stream);
1662 return freopen (filename, mode, stream);
1668 * @fd: a file descriptor
1670 * A wrapper for the POSIX `fsync()` function. On Windows, `_commit()` will be
1671 * used. On macOS, `fcntl(F_FULLFSYNC)` will be used.
1672 * The `fsync()` function is used to synchronize a file's in-core
1673 * state with that of the disk.
1675 * This wrapper will handle retrying on `EINTR`.
1677 * See the C library manual for more details about fsync().
1679 * Returns: 0 on success, or -1 if an error occurred.
1680 * The return value can be used exactly like the return value from fsync().
1688 return _commit (fd);
1689 #elif defined(HAVE_FSYNC) || defined(HAVE_FCNTL_F_FULLFSYNC)
1692 #ifdef HAVE_FCNTL_F_FULLFSYNC
1693 retval = fcntl (fd, F_FULLFSYNC, 0);
1695 retval = fsync (fd);
1697 while (G_UNLIKELY (retval < 0 && errno == EINTR));
1706 * @filename: (type filename): a pathname in the GLib file name encoding
1707 * (UTF-8 on Windows)
1708 * @utb: a pointer to a struct utimbuf.
1710 * A wrapper for the POSIX utime() function. The utime() function
1711 * sets the access and modification timestamps of a file.
1713 * See your C library manual for more details about how utime() works
1716 * Returns: 0 if the operation was successful, -1 if an error occurred
1721 g_utime (const gchar *filename,
1722 struct utimbuf *utb)
1725 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1729 if (wfilename == NULL)
1735 retval = _wutime (wfilename, (struct _utimbuf*) utb);
1743 return utime (filename, utb);
1749 * @fd: A file descriptor
1752 * This wraps the close() call. In case of error, %errno will be
1753 * preserved, but the error will also be stored as a #GError in @error.
1754 * In case of success, %errno is undefined.
1756 * Besides using #GError, there is another major reason to prefer this
1757 * function over the call provided by the system; on Unix, it will
1758 * attempt to correctly handle %EINTR, which has platform-specific
1761 * It is a bug to call this function with an invalid file descriptor.
1763 * On POSIX platforms since GLib 2.76, this function is async-signal safe
1764 * if (and only if) @error is %NULL and @fd is a valid open file descriptor.
1765 * This makes it safe to call from a signal handler or a #GSpawnChildSetupFunc
1766 * under those conditions.
1767 * See [`signal(7)`](man:signal(7)) and
1768 * [`signal-safety(7)`](man:signal-safety(7)) for more details.
1770 * Returns: %TRUE on success, %FALSE if there was an error.
1780 /* Important: if @error is NULL, we must not do anything that is
1781 * not async-signal-safe.
1791 /* Just ignore EINTR for now; a retry loop is the wrong thing to do
1792 * on Linux at least. Anyone who wants to add a conditional check
1793 * for e.g. HP-UX is welcome to do so later...
1795 * close_func_with_invalid_fds() in gspawn.c has similar logic.
1797 * https://lwn.net/Articles/576478/
1798 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
1799 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
1800 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
1801 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
1803 * `close$NOCANCEL()` in gstdioprivate.h, on macOS, ensures that the fd is
1804 * closed even if it did return EINTR.
1811 g_set_error_literal (error, G_FILE_ERROR,
1812 g_file_error_from_errno (errsv),
1813 g_strerror (errsv));
1818 /* There is a bug. Fail an assertion. Note that this function is supposed to be
1819 * async-signal-safe, but in case an assertion fails, all bets are already off. */
1822 /* Closing an non-negative, invalid file descriptor is a bug. The bug is
1823 * not necessarily in the caller of g_close(), but somebody else
1824 * might have wrongly closed fd. In any case, there is a serious bug
1826 g_critical ("g_close(fd:%d) failed with EBADF. The tracking of file descriptors got messed up", fd);
1830 /* Closing a negative "file descriptor" is less problematic. It's still a nonsensical action
1831 * from the caller. Assert against that too. */
1832 g_critical ("g_close(fd:%d) failed with EBADF. This is not a valid file descriptor", fd);
1845 * g_clear_fd: (skip)
1846 * @fd_ptr: (not optional) (inout) (transfer full): a pointer to a file descriptor
1847 * @error: Used to return an error on failure
1849 * If @fd_ptr points to a file descriptor, close it and return
1850 * whether closing it was successful, like g_close().
1851 * If @fd_ptr points to a negative number, return %TRUE without closing
1853 * In both cases, set @fd_ptr to `-1` before returning.
1855 * Like g_close(), if closing the file descriptor fails, the error is
1856 * stored in both %errno and @error. If this function succeeds,
1857 * %errno is undefined.
1859 * On POSIX platforms, this function is async-signal safe
1860 * if @error is %NULL and @fd_ptr points to either a negative number or a
1861 * valid open file descriptor.
1862 * This makes it safe to call from a signal handler or a #GSpawnChildSetupFunc
1863 * under those conditions.
1864 * See [`signal(7)`](man:signal(7)) and
1865 * [`signal-safety(7)`](man:signal-safety(7)) for more details.
1867 * It is a programming error for @fd_ptr to point to a non-negative
1868 * number that is not a valid file descriptor.
1870 * A typical use of this function is to clean up a file descriptor at
1871 * the end of its scope, whether it has been set successfully or not:
1875 * operate_on_fd (GError **error)
1877 * gboolean ret = FALSE;
1880 * fd = open_a_fd (error);
1885 * if (!do_something (fd, error))
1888 * if (!g_clear_fd (&fd, error))
1894 * // OK to call even if fd was never opened or was already closed
1895 * g_clear_fd (&fd, NULL);
1900 * This function is also useful in conjunction with #g_autofd.
1902 * Returns: %TRUE on success
1909 * Macro to add an attribute to a file descriptor variable to ensure
1910 * automatic cleanup using g_clear_fd().
1912 * This macro behaves like #g_autofree rather than g_autoptr(): it is
1913 * an attribute supplied before the type name, rather than wrapping the
1916 * Otherwise, this macro has similar constraints as g_autoptr(): it is
1917 * only supported on GCC and clang, and the variable must be initialized
1918 * (to either a valid file descriptor or a negative number).
1920 * Using this macro is async-signal-safe if the constraints described above
1921 * are met, so it can be used in a signal handler or after `fork()`.
1923 * Any error from closing the file descriptor when it goes out of scope
1924 * is ignored. Use g_clear_fd() if error-checking is required.
1928 * operate_on_fds (GError **error)
1930 * g_autofd int fd1 = open_a_fd (..., error);
1931 * g_autofd int fd2 = -1;
1933 * // it is safe to return early here, nothing will be closed
1937 * fd2 = open_a_fd (..., error);
1939 * // fd1 will be closed automatically if we return here
1943 * // fd1 and fd2 will be closed automatically if we return here
1944 * if (!do_something_useful (fd1, fd2, error))
1947 * // fd2 will be closed automatically if we return here
1948 * if (!g_clear_fd (&fd1, error))
1951 * // fd2 will be automatically closed here if still open