gkdbus: Fix underflow and unreachable code bug
[platform/upstream/glib.git] / glib / gfileutils.c
1 /* gfileutils.c - File utility functions
2  *
3  *  Copyright 2000 Red Hat, Inc.
4  *
5  * SPDX-License-Identifier: LGPL-2.1-or-later
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
21 #include "config.h"
22 #include "glibconfig.h"
23
24 #include <sys/stat.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stdarg.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <stdlib.h>
34
35 #ifdef G_OS_UNIX
36 #include <unistd.h>
37 #endif
38 #ifdef G_OS_WIN32
39 #include <windows.h>
40 #include <io.h>
41 #endif /* G_OS_WIN32 */
42
43 #ifndef S_ISLNK
44 #define S_ISLNK(x) 0
45 #endif
46
47 #ifndef O_BINARY
48 #define O_BINARY 0
49 #endif
50
51 #ifndef O_CLOEXEC
52 #define O_CLOEXEC 0
53 #endif
54
55 #include "gfileutils.h"
56
57 #include "gstdio.h"
58 #include "gstdioprivate.h"
59 #include "glibintl.h"
60
61
62 /**
63  * SECTION:fileutils
64  * @title: File Utilities
65  * @short_description: various file-related functions
66  *
67  * Do not use these APIs unless you are porting a POSIX application to Windows.
68  * A more high-level file access API is provided as GIO — see the documentation
69  * for #GFile.
70  *
71  * There is a group of functions which wrap the common POSIX functions
72  * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
73  * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
74  * wrappers is to make it possible to handle file names with any Unicode
75  * characters in them on Windows without having to use ifdefs and the
76  * wide character API in the application code.
77  *
78  * On some Unix systems, these APIs may be defined as identical to their POSIX
79  * counterparts. For this reason, you must check for and include the necessary
80  * header files (such as `fcntl.h`) before using functions like g_creat(). You
81  * must also define the relevant feature test macros.
82  *
83  * The pathname argument should be in the GLib file name encoding.
84  * On POSIX this is the actual on-disk encoding which might correspond
85  * to the locale settings of the process (or the `G_FILENAME_ENCODING`
86  * environment variable), or not.
87  *
88  * On Windows the GLib file name encoding is UTF-8. Note that the
89  * Microsoft C library does not use UTF-8, but has separate APIs for
90  * current system code page and wide characters (UTF-16). The GLib
91  * wrappers call the wide character API if present (on modern Windows
92  * systems), otherwise convert to/from the system code page.
93  *
94  * Another group of functions allows to open and read directories
95  * in the GLib file name encoding. These are g_dir_open(),
96  * g_dir_read_name(), g_dir_rewind(), g_dir_close().
97  */
98
99 /**
100  * GFileError:
101  * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
102  *     the file (or other resource) or processes with special privileges
103  *     can perform the operation.
104  * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
105  *     for writing, or create or remove hard links to it.
106  * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
107  *     allow the attempted operation.
108  * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
109  * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
110  *     doesn't exist" error for ordinary files that are referenced in
111  *     contexts where they are expected to already exist.
112  * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
113  *     a directory is required.
114  * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
115  *     use the device represented by a file you specified, and it
116  *     couldn't find the device. This can mean that the device file was
117  *     installed incorrectly, or that the physical device is missing or
118  *     not correctly attached to the computer.
119  * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
120  *     does not support memory mapping.
121  * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
122  *     modified because it's on a read-only file system.
123  * @G_FILE_ERROR_TXTBSY: Text file busy.
124  * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
125  *     (GLib won't reliably return this, don't pass in pointers to bad
126  *     memory.)
127  * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
128  *     in looking up a file name. This often indicates a cycle of symbolic
129  *     links.
130  * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
131  *     file failed because the disk is full.
132  * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
133  *     more virtual memory because its capacity is full.
134  * @G_FILE_ERROR_MFILE: The current process has too many files open and
135  *     can't open any more. Duplicate descriptors do count toward this
136  *     limit.
137  * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
138  *     entire system.
139  * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
140  *     descriptor that has been closed or reading from a descriptor open
141  *     only for writing (or vice versa).
142  * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
143  *     various kinds of problems with passing the wrong argument to a
144  *     library function.
145  * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
146  *     other end of a pipe. Every library function that returns this
147  *     error code also generates a 'SIGPIPE' signal; this signal
148  *     terminates the program if not handled or blocked. Thus, your
149  *     program will never actually see this code unless it has handled
150  *     or blocked 'SIGPIPE'.
151  * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
152  *     work if you try again later.
153  * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
154  *     occurred and prevented completion of the call. When this
155  *     happens, you should try the call again.
156  * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
157  *    or write errors. i.e. the disk or other physical device hardware
158  *    is returning errors.
159  * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
160  *    file (or other resource) or processes with special privileges can
161  *    perform the operation.
162  * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
163  *    the system is missing some functionality.
164  * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
165  *    is the standard "failed for unspecified reason" error code present
166  *    in all #GError error code enumerations. Returned if no specific
167  *    code applies.
168  *
169  * Values corresponding to @errno codes returned from file operations
170  * on UNIX. Unlike @errno codes, GFileError values are available on
171  * all systems, even Windows. The exact meaning of each code depends
172  * on what sort of file operation you were performing; the UNIX
173  * documentation gives more details. The following error code descriptions
174  * come from the GNU C Library manual, and are under the copyright
175  * of that manual.
176  *
177  * It's not very portable to make detailed assumptions about exactly
178  * which errors will be returned from a given operation. Some errors
179  * don't occur on some systems, etc., sometimes there are subtle
180  * differences in when a system will report a given error, etc.
181  */
182
183 /**
184  * G_FILE_ERROR:
185  *
186  * Error domain for file operations. Errors in this domain will
187  * be from the #GFileError enumeration. See #GError for information
188  * on error domains.
189  */
190
191 /**
192  * GFileTest:
193  * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
194  *     (not a directory). Note that this test will also return %TRUE
195  *     if the tested file is a symlink to a regular file.
196  * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
197  * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
198  * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
199  * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
200  *     be a regular file.
201  *
202  * A test to perform on a file using g_file_test().
203  */
204
205 /**
206  * g_mkdir_with_parents:
207  * @pathname: (type filename): a pathname in the GLib file name encoding
208  * @mode: permissions to use for newly created directories
209  *
210  * Create a directory if it doesn't already exist. Create intermediate
211  * parent directories as needed, too.
212  *
213  * Returns: 0 if the directory already exists, or was successfully
214  * created. Returns -1 if an error occurred, with errno set.
215  *
216  * Since: 2.8
217  */
218 int
219 g_mkdir_with_parents (const gchar *pathname,
220                       int          mode)
221 {
222   gchar *fn, *p;
223
224   if (pathname == NULL || *pathname == '\0')
225     {
226       errno = EINVAL;
227       return -1;
228     }
229
230   /* try to create the full path first */
231   if (g_mkdir (pathname, mode) == 0)
232     return 0;
233   else if (errno == EEXIST)
234     {
235       if (!g_file_test (pathname, G_FILE_TEST_IS_DIR))
236         {
237           errno = ENOTDIR;
238           return -1;
239         }
240       return 0;
241     }
242
243   /* walk the full path and try creating each element */
244   fn = g_strdup (pathname);
245
246   if (g_path_is_absolute (fn))
247     p = (gchar *) g_path_skip_root (fn);
248   else
249     p = fn;
250
251   do
252     {
253       while (*p && !G_IS_DIR_SEPARATOR (*p))
254         p++;
255       
256       if (!*p)
257         p = NULL;
258       else
259         *p = '\0';
260       
261       if (!g_file_test (fn, G_FILE_TEST_EXISTS))
262         {
263           if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
264             {
265               int errno_save = errno;
266               if (errno != ENOENT || !p)
267                 {
268                   g_free (fn);
269                   errno = errno_save;
270                   return -1;
271                 }
272             }
273         }
274       else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
275         {
276           g_free (fn);
277           errno = ENOTDIR;
278           return -1;
279         }
280       if (p)
281         {
282           *p++ = G_DIR_SEPARATOR;
283           while (*p && G_IS_DIR_SEPARATOR (*p))
284             p++;
285         }
286     }
287   while (p);
288
289   g_free (fn);
290
291   return 0;
292 }
293
294 /**
295  * g_file_test:
296  * @filename: (type filename): a filename to test in the
297  *     GLib file name encoding
298  * @test: bitfield of #GFileTest flags
299  *
300  * Returns %TRUE if any of the tests in the bitfield @test are
301  * %TRUE. For example, `(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)`
302  * will return %TRUE if the file exists; the check whether it's a
303  * directory doesn't matter since the existence test is %TRUE. With
304  * the current set of available tests, there's no point passing in
305  * more than one test at a time.
306  *
307  * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
308  * so for a symbolic link to a regular file g_file_test() will return
309  * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
310  *
311  * Note, that for a dangling symbolic link g_file_test() will return
312  * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
313  *
314  * You should never use g_file_test() to test whether it is safe
315  * to perform an operation, because there is always the possibility
316  * of the condition changing before you actually perform the operation,
317  * see [TOCTOU](https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use).
318  *
319  * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
320  * to know whether it is safe to write to a file without being
321  * tricked into writing into a different location. It doesn't work!
322  *
323  * |[<!-- language="C" -->
324  *  // DON'T DO THIS
325  *  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) 
326  *    {
327  *      fd = g_open (filename, O_WRONLY);
328  *      // write to fd
329  *    }
330  *
331  *  // DO THIS INSTEAD
332  *  fd = g_open (filename, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);
333  *  if (fd == -1)
334  *    {
335  *      // check error
336  *      if (errno == ELOOP)
337  *        // file is a symlink and can be ignored
338  *      else
339  *        // handle errors as before
340  *    }
341  *  else
342  *    {
343  *      // write to fd
344  *    }
345  * ]|
346  *
347  * Another thing to note is that %G_FILE_TEST_EXISTS and
348  * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
349  * system call. This usually doesn't matter, but if your program
350  * is setuid or setgid it means that these tests will give you
351  * the answer for the real user ID and group ID, rather than the
352  * effective user ID and group ID.
353  *
354  * On Windows, there are no symlinks, so testing for
355  * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
356  * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
357  * its name indicates that it is executable, checking for well-known
358  * extensions and those listed in the `PATHEXT` environment variable.
359  *
360  * Returns: whether a test was %TRUE
361  **/
362 gboolean
363 g_file_test (const gchar *filename,
364              GFileTest    test)
365 {
366 #ifdef G_OS_WIN32
367   DWORD attributes;
368   wchar_t *wfilename;
369 #endif
370
371   g_return_val_if_fail (filename != NULL, FALSE);
372
373 #ifdef G_OS_WIN32
374 /* stuff missing in std vc6 api */
375 #  ifndef INVALID_FILE_ATTRIBUTES
376 #    define INVALID_FILE_ATTRIBUTES -1
377 #  endif
378 #  ifndef FILE_ATTRIBUTE_DEVICE
379 #    define FILE_ATTRIBUTE_DEVICE 64
380 #  endif
381   wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
382
383   if (wfilename == NULL)
384     return FALSE;
385
386   attributes = GetFileAttributesW (wfilename);
387
388   g_free (wfilename);
389
390   if (attributes == INVALID_FILE_ATTRIBUTES)
391     return FALSE;
392
393   if (test & G_FILE_TEST_EXISTS)
394     return TRUE;
395       
396   if (test & G_FILE_TEST_IS_REGULAR)
397     {
398       if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
399         return TRUE;
400     }
401
402   if (test & G_FILE_TEST_IS_DIR)
403     {
404       if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
405         return TRUE;
406     }
407
408   /* "while" so that we can exit this "loop" with a simple "break" */
409   while (test & G_FILE_TEST_IS_EXECUTABLE)
410     {
411       const gchar *lastdot = strrchr (filename, '.');
412       const gchar *pathext = NULL, *p;
413       int extlen;
414
415       if (lastdot == NULL)
416         break;
417
418       if (_stricmp (lastdot, ".exe") == 0 ||
419           _stricmp (lastdot, ".cmd") == 0 ||
420           _stricmp (lastdot, ".bat") == 0 ||
421           _stricmp (lastdot, ".com") == 0)
422         return TRUE;
423
424       /* Check if it is one of the types listed in %PATHEXT% */
425
426       pathext = g_getenv ("PATHEXT");
427       if (pathext == NULL)
428         break;
429
430       pathext = g_utf8_casefold (pathext, -1);
431
432       lastdot = g_utf8_casefold (lastdot, -1);
433       extlen = strlen (lastdot);
434
435       p = pathext;
436       while (TRUE)
437         {
438           const gchar *q = strchr (p, ';');
439           if (q == NULL)
440             q = p + strlen (p);
441           if (extlen == q - p &&
442               memcmp (lastdot, p, extlen) == 0)
443             {
444               g_free ((gchar *) pathext);
445               g_free ((gchar *) lastdot);
446               return TRUE;
447             }
448           if (*q)
449             p = q + 1;
450           else
451             break;
452         }
453
454       g_free ((gchar *) pathext);
455       g_free ((gchar *) lastdot);
456       break;
457     }
458
459   return FALSE;
460 #else
461   if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
462     return TRUE;
463   
464   if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
465     {
466       if (getuid () != 0)
467         return TRUE;
468
469       /* For root, on some POSIX systems, access (filename, X_OK)
470        * will succeed even if no executable bits are set on the
471        * file. We fall through to a stat test to avoid that.
472        */
473     }
474   else
475     test &= ~G_FILE_TEST_IS_EXECUTABLE;
476
477   if (test & G_FILE_TEST_IS_SYMLINK)
478     {
479       struct stat s;
480
481       if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
482         return TRUE;
483     }
484   
485   if (test & (G_FILE_TEST_IS_REGULAR |
486               G_FILE_TEST_IS_DIR |
487               G_FILE_TEST_IS_EXECUTABLE))
488     {
489       struct stat s;
490       
491       if (stat (filename, &s) == 0)
492         {
493           if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
494             return TRUE;
495           
496           if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
497             return TRUE;
498
499           /* The extra test for root when access (file, X_OK) succeeds.
500            */
501           if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
502               ((s.st_mode & S_IXOTH) ||
503                (s.st_mode & S_IXUSR) ||
504                (s.st_mode & S_IXGRP)))
505             return TRUE;
506         }
507     }
508
509   return FALSE;
510 #endif
511 }
512
513 G_DEFINE_QUARK (g-file-error-quark, g_file_error)
514
515 /**
516  * g_file_error_from_errno:
517  * @err_no: an "errno" value
518  *
519  * Gets a #GFileError constant based on the passed-in @err_no.
520  *
521  * For example, if you pass in `EEXIST` this function returns
522  * %G_FILE_ERROR_EXIST. Unlike `errno` values, you can portably
523  * assume that all #GFileError values will exist.
524  *
525  * Normally a #GFileError value goes into a #GError returned
526  * from a function that manipulates files. So you would use
527  * g_file_error_from_errno() when constructing a #GError.
528  *
529  * Returns: #GFileError corresponding to the given @err_no
530  **/
531 GFileError
532 g_file_error_from_errno (gint err_no)
533 {
534   switch (err_no)
535     {
536 #ifdef EEXIST
537     case EEXIST:
538       return G_FILE_ERROR_EXIST;
539 #endif
540
541 #ifdef EISDIR
542     case EISDIR:
543       return G_FILE_ERROR_ISDIR;
544 #endif
545
546 #ifdef EACCES
547     case EACCES:
548       return G_FILE_ERROR_ACCES;
549 #endif
550
551 #ifdef ENAMETOOLONG
552     case ENAMETOOLONG:
553       return G_FILE_ERROR_NAMETOOLONG;
554 #endif
555
556 #ifdef ENOENT
557     case ENOENT:
558       return G_FILE_ERROR_NOENT;
559 #endif
560
561 #ifdef ENOTDIR
562     case ENOTDIR:
563       return G_FILE_ERROR_NOTDIR;
564 #endif
565
566 #ifdef ENXIO
567     case ENXIO:
568       return G_FILE_ERROR_NXIO;
569 #endif
570
571 #ifdef ENODEV
572     case ENODEV:
573       return G_FILE_ERROR_NODEV;
574 #endif
575
576 #ifdef EROFS
577     case EROFS:
578       return G_FILE_ERROR_ROFS;
579 #endif
580
581 #ifdef ETXTBSY
582     case ETXTBSY:
583       return G_FILE_ERROR_TXTBSY;
584 #endif
585
586 #ifdef EFAULT
587     case EFAULT:
588       return G_FILE_ERROR_FAULT;
589 #endif
590
591 #ifdef ELOOP
592     case ELOOP:
593       return G_FILE_ERROR_LOOP;
594 #endif
595
596 #ifdef ENOSPC
597     case ENOSPC:
598       return G_FILE_ERROR_NOSPC;
599 #endif
600
601 #ifdef ENOMEM
602     case ENOMEM:
603       return G_FILE_ERROR_NOMEM;
604 #endif
605
606 #ifdef EMFILE
607     case EMFILE:
608       return G_FILE_ERROR_MFILE;
609 #endif
610
611 #ifdef ENFILE
612     case ENFILE:
613       return G_FILE_ERROR_NFILE;
614 #endif
615
616 #ifdef EBADF
617     case EBADF:
618       return G_FILE_ERROR_BADF;
619 #endif
620
621 #ifdef EINVAL
622     case EINVAL:
623       return G_FILE_ERROR_INVAL;
624 #endif
625
626 #ifdef EPIPE
627     case EPIPE:
628       return G_FILE_ERROR_PIPE;
629 #endif
630
631 #ifdef EAGAIN
632     case EAGAIN:
633       return G_FILE_ERROR_AGAIN;
634 #endif
635
636 #ifdef EINTR
637     case EINTR:
638       return G_FILE_ERROR_INTR;
639 #endif
640
641 #ifdef EIO
642     case EIO:
643       return G_FILE_ERROR_IO;
644 #endif
645
646 #ifdef EPERM
647     case EPERM:
648       return G_FILE_ERROR_PERM;
649 #endif
650
651 #ifdef ENOSYS
652     case ENOSYS:
653       return G_FILE_ERROR_NOSYS;
654 #endif
655
656     default:
657       return G_FILE_ERROR_FAILED;
658     }
659 }
660
661 static char *
662 format_error_message (const gchar  *filename,
663                       const gchar  *format_string,
664                       int           saved_errno) G_GNUC_FORMAT(2);
665
666 #pragma GCC diagnostic push
667 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
668
669 static char *
670 format_error_message (const gchar  *filename,
671                       const gchar  *format_string,
672                       int           saved_errno)
673 {
674   gchar *display_name;
675   gchar *msg;
676
677   display_name = g_filename_display_name (filename);
678   msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
679   g_free (display_name);
680
681   return msg;
682 }
683
684 #pragma GCC diagnostic pop
685
686 /* format string must have two '%s':
687  *
688  *   - the place for the filename
689  *   - the place for the strerror
690  */
691 static void
692 set_file_error (GError      **error,
693                 const gchar  *filename,
694                 const gchar  *format_string,
695                 int           saved_errno)
696 {
697   char *msg = format_error_message (filename, format_string, saved_errno);
698
699   g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
700                        msg);
701   g_free (msg);
702 }
703
704 static gboolean
705 get_contents_stdio (const gchar  *filename,
706                     FILE         *f,
707                     gchar       **contents,
708                     gsize        *length,
709                     GError      **error)
710 {
711   gchar buf[4096];
712   gsize bytes;  /* always <= sizeof(buf) */
713   gchar *str = NULL;
714   gsize total_bytes = 0;
715   gsize total_allocated = 0;
716   gchar *tmp;
717   gchar *display_filename;
718
719   g_assert (f != NULL);
720
721   while (!feof (f))
722     {
723       gint save_errno;
724
725       bytes = fread (buf, 1, sizeof (buf), f);
726       save_errno = errno;
727
728       if (total_bytes > G_MAXSIZE - bytes)
729           goto file_too_large;
730
731       /* Possibility of overflow eliminated above. */
732       while (total_bytes + bytes >= total_allocated)
733         {
734           if (str)
735             {
736               if (total_allocated > G_MAXSIZE / 2)
737                   goto file_too_large;
738               total_allocated *= 2;
739             }
740           else
741             {
742               total_allocated = MIN (bytes + 1, sizeof (buf));
743             }
744
745           tmp = g_try_realloc (str, total_allocated);
746
747           if (tmp == NULL)
748             {
749               display_filename = g_filename_display_name (filename);
750               g_set_error (error,
751                            G_FILE_ERROR,
752                            G_FILE_ERROR_NOMEM,
753                            g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file “%s”", "Could not allocate %lu bytes to read file “%s”", (gulong)total_allocated),
754                            (gulong) total_allocated,
755                            display_filename);
756               g_free (display_filename);
757
758               goto error;
759             }
760
761           str = tmp;
762         }
763
764       if (ferror (f))
765         {
766           display_filename = g_filename_display_name (filename);
767           g_set_error (error,
768                        G_FILE_ERROR,
769                        g_file_error_from_errno (save_errno),
770                        _("Error reading file “%s”: %s"),
771                        display_filename,
772                        g_strerror (save_errno));
773           g_free (display_filename);
774
775           goto error;
776         }
777
778       g_assert (str != NULL);
779       memcpy (str + total_bytes, buf, bytes);
780
781       total_bytes += bytes;
782     }
783
784   fclose (f);
785
786   if (total_allocated == 0)
787     {
788       str = g_new (gchar, 1);
789       total_bytes = 0;
790     }
791
792   str[total_bytes] = '\0';
793
794   if (length)
795     *length = total_bytes;
796
797   *contents = str;
798
799   return TRUE;
800
801  file_too_large:
802   display_filename = g_filename_display_name (filename);
803   g_set_error (error,
804                G_FILE_ERROR,
805                G_FILE_ERROR_FAILED,
806                _("File “%s” is too large"),
807                display_filename);
808   g_free (display_filename);
809
810  error:
811
812   g_free (str);
813   fclose (f);
814
815   return FALSE;
816 }
817
818 #ifndef G_OS_WIN32
819
820 static gboolean
821 get_contents_regfile (const gchar  *filename,
822                       struct stat  *stat_buf,
823                       gint          fd,
824                       gchar       **contents,
825                       gsize        *length,
826                       GError      **error)
827 {
828   gchar *buf;
829   gsize bytes_read;
830   gsize size;
831   gsize alloc_size;
832   gchar *display_filename;
833   
834   size = stat_buf->st_size;
835
836   alloc_size = size + 1;
837   buf = g_try_malloc (alloc_size);
838
839   if (buf == NULL)
840     {
841       display_filename = g_filename_display_name (filename);
842       g_set_error (error,
843                    G_FILE_ERROR,
844                    G_FILE_ERROR_NOMEM,
845                            g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file “%s”", "Could not allocate %lu bytes to read file “%s”", (gulong)alloc_size),
846                    (gulong) alloc_size, 
847                    display_filename);
848       g_free (display_filename);
849       goto error;
850     }
851   
852   bytes_read = 0;
853   while (bytes_read < size)
854     {
855       gssize rc;
856           
857       rc = read (fd, buf + bytes_read, size - bytes_read);
858
859       if (rc < 0)
860         {
861           if (errno != EINTR) 
862             {
863               int save_errno = errno;
864
865               g_free (buf);
866               display_filename = g_filename_display_name (filename);
867               g_set_error (error,
868                            G_FILE_ERROR,
869                            g_file_error_from_errno (save_errno),
870                            _("Failed to read from file “%s”: %s"),
871                            display_filename, 
872                            g_strerror (save_errno));
873               g_free (display_filename);
874               goto error;
875             }
876         }
877       else if (rc == 0)
878         break;
879       else
880         bytes_read += rc;
881     }
882       
883   buf[bytes_read] = '\0';
884
885   if (length)
886     *length = bytes_read;
887   
888   *contents = buf;
889
890   close (fd);
891
892   return TRUE;
893
894  error:
895
896   close (fd);
897   
898   return FALSE;
899 }
900
901 static gboolean
902 get_contents_posix (const gchar  *filename,
903                     gchar       **contents,
904                     gsize        *length,
905                     GError      **error)
906 {
907   struct stat stat_buf;
908   gint fd;
909
910   /* O_BINARY useful on Cygwin */
911   fd = open (filename, O_RDONLY | O_BINARY | O_CLOEXEC);
912
913   if (fd < 0)
914     {
915       int saved_errno = errno;
916
917       if (error)
918         set_file_error (error,
919                         filename,
920                         _("Failed to open file “%s”: %s"),
921                         saved_errno);
922
923       return FALSE;
924     }
925
926   /* I don't think this will ever fail, aside from ENOMEM, but. */
927   if (fstat (fd, &stat_buf) < 0)
928     {
929       int saved_errno = errno;
930       if (error)
931         set_file_error (error,
932                         filename,
933                         _("Failed to get attributes of file “%s”: fstat() failed: %s"),
934                         saved_errno);
935       close (fd);
936
937       return FALSE;
938     }
939
940   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
941     {
942       gboolean retval = get_contents_regfile (filename,
943                                               &stat_buf,
944                                               fd,
945                                               contents,
946                                               length,
947                                               error);
948
949       return retval;
950     }
951   else
952     {
953       FILE *f;
954       gboolean retval;
955
956       f = fdopen (fd, "r");
957       
958       if (f == NULL)
959         {
960           int saved_errno = errno;
961           if (error)
962             set_file_error (error,
963                             filename,
964                             _("Failed to open file “%s”: fdopen() failed: %s"),
965                             saved_errno);
966
967           return FALSE;
968         }
969   
970       retval = get_contents_stdio (filename, f, contents, length, error);
971
972       return retval;
973     }
974 }
975
976 #else  /* G_OS_WIN32 */
977
978 static gboolean
979 get_contents_win32 (const gchar  *filename,
980                     gchar       **contents,
981                     gsize        *length,
982                     GError      **error)
983 {
984   FILE *f;
985   gboolean retval;
986   
987   f = g_fopen (filename, "rb");
988
989   if (f == NULL)
990     {
991       int saved_errno = errno;
992       if (error)
993         set_file_error (error,
994                         filename,
995                         _("Failed to open file “%s”: %s"),
996                         saved_errno);
997
998       return FALSE;
999     }
1000   
1001   retval = get_contents_stdio (filename, f, contents, length, error);
1002
1003   return retval;
1004 }
1005
1006 #endif
1007
1008 /**
1009  * g_file_get_contents:
1010  * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
1011  * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
1012  *     the returned string
1013  * @length: (nullable): location to store length in bytes of the contents, or %NULL
1014  * @error: return location for a #GError, or %NULL
1015  *
1016  * Reads an entire file into allocated memory, with good error
1017  * checking.
1018  *
1019  * If the call was successful, it returns %TRUE and sets @contents to the file
1020  * contents and @length to the length of the file contents in bytes. The string
1021  * stored in @contents will be nul-terminated, so for text files you can pass
1022  * %NULL for the @length argument. If the call was not successful, it returns
1023  * %FALSE and sets @error. The error domain is %G_FILE_ERROR. Possible error
1024  * codes are those in the #GFileError enumeration. In the error case,
1025  * @contents is set to %NULL and @length is set to zero.
1026  *
1027  * Returns: %TRUE on success, %FALSE if an error occurred
1028  **/
1029 gboolean
1030 g_file_get_contents (const gchar  *filename,
1031                      gchar       **contents,
1032                      gsize        *length,
1033                      GError      **error)
1034 {  
1035   g_return_val_if_fail (filename != NULL, FALSE);
1036   g_return_val_if_fail (contents != NULL, FALSE);
1037
1038   *contents = NULL;
1039   if (length)
1040     *length = 0;
1041
1042 #ifdef G_OS_WIN32
1043   return get_contents_win32 (filename, contents, length, error);
1044 #else
1045   return get_contents_posix (filename, contents, length, error);
1046 #endif
1047 }
1048
1049 static gboolean
1050 rename_file (const char  *old_name,
1051              const char  *new_name,
1052              gboolean     do_fsync,
1053              GError     **err)
1054 {
1055   errno = 0;
1056   if (g_rename (old_name, new_name) == -1)
1057     {
1058       int save_errno = errno;
1059       gchar *display_old_name = g_filename_display_name (old_name);
1060       gchar *display_new_name = g_filename_display_name (new_name);
1061
1062       g_set_error (err,
1063                    G_FILE_ERROR,
1064                    g_file_error_from_errno (save_errno),
1065                    _("Failed to rename file “%s” to “%s”: g_rename() failed: %s"),
1066                    display_old_name,
1067                    display_new_name,
1068                    g_strerror (save_errno));
1069
1070       g_free (display_old_name);
1071       g_free (display_new_name);
1072       
1073       return FALSE;
1074     }
1075
1076   /* In order to guarantee that the *new* contents of the file are seen in
1077    * future, fsync() the directory containing the file. Otherwise if the file
1078    * system was unmounted cleanly now, it would be undefined whether the old
1079    * or new contents of the file were visible after recovery.
1080    *
1081    * This assumes the @old_name and @new_name are in the same directory. */
1082 #ifdef HAVE_FSYNC
1083   if (do_fsync)
1084     {
1085       gchar *dir = g_path_get_dirname (new_name);
1086       int dir_fd = g_open (dir, O_RDONLY | O_CLOEXEC, 0);
1087
1088       if (dir_fd >= 0)
1089         {
1090           g_fsync (dir_fd);
1091           g_close (dir_fd, NULL);
1092         }
1093
1094       g_free (dir);
1095     }
1096 #endif  /* HAVE_FSYNC */
1097
1098   return TRUE;
1099 }
1100
1101 static gboolean
1102 fd_should_be_fsynced (int                    fd,
1103                       const gchar           *test_file,
1104                       GFileSetContentsFlags  flags)
1105 {
1106 #ifdef HAVE_FSYNC
1107   struct stat statbuf;
1108
1109   /* If the final destination exists and is > 0 bytes, we want to sync the
1110    * newly written file to ensure the data is on disk when we rename over
1111    * the destination. Otherwise if we get a system crash we can lose both
1112    * the new and the old file on some filesystems. (I.E. those that don't
1113    * guarantee the data is written to the disk before the metadata.)
1114    *
1115    * There is no difference (in file system terms) if the old file doesn’t
1116    * already exist, apart from the fact that if the system crashes and the new
1117    * data hasn’t been fsync()ed, there is only one bit of old data to lose (that
1118    * the file didn’t exist in the first place). In some situations, such as
1119    * trashing files, the old file never exists, so it seems reasonable to avoid
1120    * the fsync(). This is not a widely applicable optimisation though.
1121    */
1122   if ((flags & (G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE)) &&
1123       (flags & G_FILE_SET_CONTENTS_ONLY_EXISTING))
1124     {
1125       errno = 0;
1126       if (g_lstat (test_file, &statbuf) == 0)
1127         return (statbuf.st_size > 0);
1128       else if (errno == ENOENT)
1129         return FALSE;
1130       else
1131         return TRUE;  /* lstat() failed; be cautious */
1132     }
1133   else
1134     {
1135       return (flags & (G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE));
1136     }
1137 #else  /* if !HAVE_FSYNC */
1138   return FALSE;
1139 #endif  /* !HAVE_FSYNC */
1140 }
1141
1142 static gboolean
1143 truncate_file (int          fd,
1144                off_t        length,
1145                const char  *dest_file,
1146                GError     **error)
1147 {
1148   while (
1149 #ifdef G_OS_WIN32
1150     g_win32_ftruncate (fd, length) < 0
1151 #else
1152     ftruncate (fd, length) < 0
1153 #endif
1154     )
1155     {
1156       int saved_errno = errno;
1157
1158       if (saved_errno == EINTR)
1159         continue;
1160
1161       if (error != NULL)
1162         set_file_error (error,
1163                         dest_file,
1164                         "Failed to write file “%s”: ftruncate() failed: %s",
1165                         saved_errno);
1166       return FALSE;
1167     }
1168
1169   return TRUE;
1170 }
1171
1172 /* closes @fd once it’s finished (on success or error) */
1173 static gboolean
1174 write_to_file (const gchar  *contents,
1175                gsize         length,
1176                int           fd,
1177                const gchar  *dest_file,
1178                gboolean      do_fsync,
1179                GError      **err)
1180 {
1181 #ifdef HAVE_FALLOCATE
1182   if (length > 0)
1183     {
1184       /* We do this on a 'best effort' basis... It may not be supported
1185        * on the underlying filesystem.
1186        */
1187       (void) fallocate (fd, 0, 0, length);
1188     }
1189 #endif
1190   while (length > 0)
1191     {
1192       gssize s;
1193
1194 #ifdef G_OS_WIN32
1195       /* 'write' on windows uses int types, so limit count to G_MAXINT */
1196       s = write (fd, contents, MIN (length, (gsize) G_MAXINT));
1197 #else
1198       /* Limit count to G_MAXSSIZE to fit into the return value. */
1199       s = write (fd, contents, MIN (length, (gsize) G_MAXSSIZE));
1200 #endif
1201       if (s < 0)
1202         {
1203           int saved_errno = errno;
1204           if (saved_errno == EINTR)
1205             continue;
1206
1207           if (err)
1208             set_file_error (err,
1209                             dest_file, _("Failed to write file “%s”: write() failed: %s"),
1210                             saved_errno);
1211           close (fd);
1212
1213           return FALSE;
1214         }
1215
1216       g_assert ((gsize) s <= length);
1217
1218       contents += s;
1219       length -= s;
1220     }
1221
1222
1223 #ifdef HAVE_FSYNC
1224   errno = 0;
1225   if (do_fsync && g_fsync (fd) != 0)
1226     {
1227       int saved_errno = errno;
1228       if (err)
1229         set_file_error (err,
1230                         dest_file, _("Failed to write file “%s”: fsync() failed: %s"),
1231                         saved_errno);
1232       close (fd);
1233
1234       return FALSE;
1235     }
1236 #endif
1237
1238   errno = 0;
1239   if (!g_close (fd, err))
1240     return FALSE;
1241
1242   return TRUE;
1243 }
1244
1245 /**
1246  * g_file_set_contents:
1247  * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1248  *   encoding
1249  * @contents: (array length=length) (element-type guint8): string to write to the file
1250  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1251  * @error: return location for a #GError, or %NULL
1252  *
1253  * Writes all of @contents to a file named @filename. This is a convenience
1254  * wrapper around calling g_file_set_contents_full() with `flags` set to
1255  * `G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING` and
1256  * `mode` set to `0666`.
1257  *
1258  * Returns: %TRUE on success, %FALSE if an error occurred
1259  *
1260  * Since: 2.8
1261  */
1262 gboolean
1263 g_file_set_contents (const gchar  *filename,
1264                      const gchar  *contents,
1265                      gssize        length,
1266                      GError      **error)
1267 {
1268   return g_file_set_contents_full (filename, contents, length,
1269                                    G_FILE_SET_CONTENTS_CONSISTENT |
1270                                    G_FILE_SET_CONTENTS_ONLY_EXISTING,
1271                                    0666, error);
1272 }
1273
1274 /**
1275  * g_file_set_contents_full:
1276  * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1277  *   encoding
1278  * @contents: (array length=length) (element-type guint8): string to write to the file
1279  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1280  * @flags: flags controlling the safety vs speed of the operation
1281  * @mode: file mode, as passed to `open()`; typically this will be `0666`
1282  * @error: return location for a #GError, or %NULL
1283  *
1284  * Writes all of @contents to a file named @filename, with good error checking.
1285  * If a file called @filename already exists it will be overwritten.
1286  *
1287  * @flags control the properties of the write operation: whether it’s atomic,
1288  * and what the tradeoff is between returning quickly or being resilient to
1289  * system crashes.
1290  *
1291  * As this function performs file I/O, it is recommended to not call it anywhere
1292  * where blocking would cause problems, such as in the main loop of a graphical
1293  * application. In particular, if @flags has any value other than
1294  * %G_FILE_SET_CONTENTS_NONE then this function may call `fsync()`.
1295  *
1296  * If %G_FILE_SET_CONTENTS_CONSISTENT is set in @flags, the operation is atomic
1297  * in the sense that it is first written to a temporary file which is then
1298  * renamed to the final name.
1299  *
1300  * Notes:
1301  *
1302  * - On UNIX, if @filename already exists hard links to @filename will break.
1303  *   Also since the file is recreated, existing permissions, access control
1304  *   lists, metadata etc. may be lost. If @filename is a symbolic link,
1305  *   the link itself will be replaced, not the linked file.
1306  *
1307  * - On UNIX, if @filename already exists and is non-empty, and if the system
1308  *   supports it (via a journalling filesystem or equivalent), and if
1309  *   %G_FILE_SET_CONTENTS_CONSISTENT is set in @flags, the `fsync()` call (or
1310  *   equivalent) will be used to ensure atomic replacement: @filename
1311  *   will contain either its old contents or @contents, even in the face of
1312  *   system power loss, the disk being unsafely removed, etc.
1313  *
1314  * - On UNIX, if @filename does not already exist or is empty, there is a
1315  *   possibility that system power loss etc. after calling this function will
1316  *   leave @filename empty or full of NUL bytes, depending on the underlying
1317  *   filesystem, unless %G_FILE_SET_CONTENTS_DURABLE and
1318  *   %G_FILE_SET_CONTENTS_CONSISTENT are set in @flags.
1319  *
1320  * - On Windows renaming a file will not remove an existing file with the
1321  *   new name, so on Windows there is a race condition between the existing
1322  *   file being removed and the temporary file being renamed.
1323  *
1324  * - On Windows there is no way to remove a file that is open to some
1325  *   process, or mapped into memory. Thus, this function will fail if
1326  *   @filename already exists and is open.
1327  *
1328  * If the call was successful, it returns %TRUE. If the call was not successful,
1329  * it returns %FALSE and sets @error. The error domain is %G_FILE_ERROR.
1330  * Possible error codes are those in the #GFileError enumeration.
1331  *
1332  * Note that the name for the temporary file is constructed by appending up
1333  * to 7 characters to @filename.
1334  *
1335  * If the file didn’t exist before and is created, it will be given the
1336  * permissions from @mode. Otherwise, the permissions of the existing file may
1337  * be changed to @mode depending on @flags, or they may remain unchanged.
1338  *
1339  * Returns: %TRUE on success, %FALSE if an error occurred
1340  *
1341  * Since: 2.66
1342  */
1343 gboolean
1344 g_file_set_contents_full (const gchar            *filename,
1345                           const gchar            *contents,
1346                           gssize                  length,
1347                           GFileSetContentsFlags   flags,
1348                           int                     mode,
1349                           GError                **error)
1350 {
1351   g_return_val_if_fail (filename != NULL, FALSE);
1352   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1353   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1354   g_return_val_if_fail (length >= -1, FALSE);
1355
1356   /* @flags are handled as follows:
1357    *  - %G_FILE_SET_CONTENTS_NONE: write directly to @filename, no fsync()s
1358    *  - %G_FILE_SET_CONTENTS_CONSISTENT: write to temp file, fsync() it, rename()
1359    *  - %G_FILE_SET_CONTENTS_CONSISTENT | ONLY_EXISTING: as above, but skip the
1360    *    fsync() if @filename doesn’t exist or is empty
1361    *  - %G_FILE_SET_CONTENTS_DURABLE: write directly to @filename, fsync() it
1362    *  - %G_FILE_SET_CONTENTS_DURABLE | ONLY_EXISTING: as above, but skip the
1363    *    fsync() if @filename doesn’t exist or is empty
1364    *  - %G_FILE_SET_CONTENTS_CONSISTENT | DURABLE: write to temp file, fsync()
1365    *    it, rename(), fsync() containing directory
1366    *  - %G_FILE_SET_CONTENTS_CONSISTENT | DURABLE | ONLY_EXISTING: as above, but
1367    *    skip both fsync()s if @filename doesn’t exist or is empty
1368    */
1369
1370   if (length < 0)
1371     length = strlen (contents);
1372
1373   if (flags & G_FILE_SET_CONTENTS_CONSISTENT)
1374     {
1375       gchar *tmp_filename = NULL;
1376       GError *rename_error = NULL;
1377       gboolean retval;
1378       int fd;
1379       gboolean do_fsync;
1380
1381       tmp_filename = g_strdup_printf ("%s.XXXXXX", filename);
1382
1383       errno = 0;
1384       fd = g_mkstemp_full (tmp_filename, O_RDWR | O_BINARY | O_CLOEXEC, mode);
1385
1386       if (fd == -1)
1387         {
1388           int saved_errno = errno;
1389           if (error)
1390             set_file_error (error,
1391                             tmp_filename, _("Failed to create file “%s”: %s"),
1392                             saved_errno);
1393           retval = FALSE;
1394           goto consistent_out;
1395         }
1396
1397       do_fsync = fd_should_be_fsynced (fd, filename, flags);
1398       if (!write_to_file (contents, length, g_steal_fd (&fd), tmp_filename, do_fsync, error))
1399         {
1400           g_unlink (tmp_filename);
1401           retval = FALSE;
1402           goto consistent_out;
1403         }
1404
1405       if (!rename_file (tmp_filename, filename, do_fsync, &rename_error))
1406         {
1407 #ifndef G_OS_WIN32
1408
1409           g_unlink (tmp_filename);
1410           g_propagate_error (error, rename_error);
1411           retval = FALSE;
1412           goto consistent_out;
1413
1414 #else /* G_OS_WIN32 */
1415
1416           /* Renaming failed, but on Windows this may just mean
1417            * the file already exists. So if the target file
1418            * exists, try deleting it and do the rename again.
1419            */
1420           if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1421             {
1422               g_unlink (tmp_filename);
1423               g_propagate_error (error, rename_error);
1424               retval = FALSE;
1425               goto consistent_out;
1426             }
1427
1428           g_error_free (rename_error);
1429
1430           if (g_unlink (filename) == -1)
1431             {
1432               int saved_errno = errno;
1433               if (error)
1434                 set_file_error (error,
1435                                 filename,
1436                                 _("Existing file “%s” could not be removed: g_unlink() failed: %s"),
1437                                 saved_errno);
1438               g_unlink (tmp_filename);
1439               retval = FALSE;
1440               goto consistent_out;
1441             }
1442
1443           if (!rename_file (tmp_filename, filename, flags, error))
1444             {
1445               g_unlink (tmp_filename);
1446               retval = FALSE;
1447               goto consistent_out;
1448             }
1449
1450 #endif  /* G_OS_WIN32 */
1451         }
1452
1453       retval = TRUE;
1454
1455 consistent_out:
1456       g_free (tmp_filename);
1457       return retval;
1458     }
1459   else
1460     {
1461       int direct_fd;
1462       int open_flags;
1463       gboolean do_fsync;
1464
1465       open_flags = O_RDWR | O_BINARY | O_CREAT | O_CLOEXEC;
1466 #ifdef O_NOFOLLOW
1467       /* Windows doesn’t have symlinks, so O_NOFOLLOW is unnecessary there. */
1468       open_flags |= O_NOFOLLOW;
1469 #endif
1470
1471       errno = 0;
1472       direct_fd = g_open (filename, open_flags, mode);
1473
1474       if (direct_fd < 0)
1475         {
1476           int saved_errno = errno;
1477
1478 #ifdef O_NOFOLLOW
1479           /* ELOOP indicates that @filename is a symlink, since we used
1480            * O_NOFOLLOW (alternately it could indicate that @filename contains
1481            * looping or too many symlinks). In either case, try again on the
1482            * %G_FILE_SET_CONTENTS_CONSISTENT code path.
1483            *
1484            * FreeBSD uses EMLINK instead of ELOOP
1485            * (https://www.freebsd.org/cgi/man.cgi?query=open&sektion=2#STANDARDS),
1486            * and NetBSD uses EFTYPE
1487            * (https://netbsd.gw.com/cgi-bin/man-cgi?open+2+NetBSD-current). */
1488 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1489           if (saved_errno == EMLINK)
1490 #elif defined(__NetBSD__)
1491           if (saved_errno == EFTYPE)
1492 #else
1493           if (saved_errno == ELOOP)
1494 #endif
1495             return g_file_set_contents_full (filename, contents, length,
1496                                              flags | G_FILE_SET_CONTENTS_CONSISTENT,
1497                                              mode, error);
1498 #endif  /* O_NOFOLLOW */
1499
1500           if (error)
1501             set_file_error (error,
1502                             filename, _("Failed to open file “%s”: %s"),
1503                             saved_errno);
1504           return FALSE;
1505         }
1506
1507       do_fsync = fd_should_be_fsynced (direct_fd, filename, flags);
1508       if (!truncate_file (direct_fd, 0, filename, error))
1509         return FALSE;
1510       if (!write_to_file (contents, length, g_steal_fd (&direct_fd), filename,
1511                           do_fsync, error))
1512         return FALSE;
1513     }
1514
1515   return TRUE;
1516 }
1517
1518 /*
1519  * get_tmp_file based on the mkstemp implementation from the GNU C library.
1520  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1521  */
1522 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1523
1524 static gint
1525 get_tmp_file (gchar            *tmpl,
1526               GTmpFileCallback  f,
1527               int               flags,
1528               int               mode)
1529 {
1530   char *XXXXXX;
1531   int count, fd;
1532   static const char letters[] =
1533     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1534   static const int NLETTERS = sizeof (letters) - 1;
1535   gint64 value;
1536   gint64 now_us;
1537   static int counter = 0;
1538
1539   g_return_val_if_fail (tmpl != NULL, -1);
1540
1541   /* find the last occurrence of "XXXXXX" */
1542   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1543
1544   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1545     {
1546       errno = EINVAL;
1547       return -1;
1548     }
1549
1550   /* Get some more or less random data.  */
1551   now_us = g_get_real_time ();
1552   value = ((now_us % G_USEC_PER_SEC) ^ (now_us / G_USEC_PER_SEC)) + counter++;
1553
1554   for (count = 0; count < 100; value += 7777, ++count)
1555     {
1556       gint64 v = value;
1557
1558       /* Fill in the random bits.  */
1559       XXXXXX[0] = letters[v % NLETTERS];
1560       v /= NLETTERS;
1561       XXXXXX[1] = letters[v % NLETTERS];
1562       v /= NLETTERS;
1563       XXXXXX[2] = letters[v % NLETTERS];
1564       v /= NLETTERS;
1565       XXXXXX[3] = letters[v % NLETTERS];
1566       v /= NLETTERS;
1567       XXXXXX[4] = letters[v % NLETTERS];
1568       v /= NLETTERS;
1569       XXXXXX[5] = letters[v % NLETTERS];
1570
1571       fd = f (tmpl, flags, mode);
1572
1573       if (fd >= 0)
1574         return fd;
1575       else if (errno != EEXIST)
1576         /* Any other error will apply also to other names we might
1577          *  try, and there are 2^32 or so of them, so give up now.
1578          */
1579         return -1;
1580     }
1581
1582   /* We got out of the loop because we ran out of combinations to try.  */
1583   errno = EEXIST;
1584   return -1;
1585 }
1586
1587 /* Some GTmpFileCallback implementations.
1588  *
1589  * Note: we cannot use open() or g_open() directly because even though
1590  * they appear compatible, they may be vararg functions and calling
1591  * varargs functions through a non-varargs type is undefined.
1592  */
1593 static gint
1594 wrap_g_mkdir (const gchar *filename,
1595               int          flags G_GNUC_UNUSED,
1596               int          mode)
1597 {
1598   /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1599   return g_mkdir (filename, mode);
1600 }
1601
1602 static gint
1603 wrap_g_open (const gchar *filename,
1604                 int          flags,
1605                 int          mode)
1606 {
1607   return g_open (filename, flags, mode);
1608 }
1609
1610 /**
1611  * g_mkdtemp_full: (skip)
1612  * @tmpl: (type filename): template directory name
1613  * @mode: permissions to create the temporary directory with
1614  *
1615  * Creates a temporary directory. See the mkdtemp() documentation
1616  * on most UNIX-like systems.
1617  *
1618  * The parameter is a string that should follow the rules for
1619  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1620  * g_mkdtemp_full() is slightly more flexible than mkdtemp() in that the
1621  * sequence does not have to occur at the very end of the template
1622  * and you can pass a @mode. The X string will be modified to form
1623  * the name of a directory that didn't exist. The string should be
1624  * in the GLib file name encoding. Most importantly, on Windows it
1625  * should be in UTF-8.
1626  *
1627  * If you are going to be creating a temporary directory inside the
1628  * directory returned by g_get_tmp_dir(), you might want to use
1629  * g_dir_make_tmp() instead.
1630  *
1631  * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1632  *   modified to hold the directory name. In case of errors, %NULL is
1633  *   returned, and %errno will be set.
1634  *
1635  * Since: 2.30
1636  */
1637 gchar *
1638 g_mkdtemp_full (gchar *tmpl,
1639                 gint   mode)
1640 {
1641   if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1642     return NULL;
1643   else
1644     return tmpl;
1645 }
1646
1647 /**
1648  * g_mkdtemp: (skip)
1649  * @tmpl: (type filename): template directory name
1650  *
1651  * Creates a temporary directory. See the mkdtemp() documentation
1652  * on most UNIX-like systems.
1653  *
1654  * The parameter is a string that should follow the rules for
1655  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1656  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1657  * sequence does not have to occur at the very end of the template.
1658  * The X string will be modified to form the name of a directory that
1659  * didn't exist.
1660  * The string should be in the GLib file name encoding. Most importantly,
1661  * on Windows it should be in UTF-8.
1662  *
1663  * If you are going to be creating a temporary directory inside the
1664  * directory returned by g_get_tmp_dir(), you might want to use
1665  * g_dir_make_tmp() instead.
1666  *
1667  * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1668  *   modified to hold the directory name.  In case of errors, %NULL is
1669  *   returned and %errno will be set.
1670  *
1671  * Since: 2.30
1672  */
1673 gchar *
1674 g_mkdtemp (gchar *tmpl)
1675 {
1676   return g_mkdtemp_full (tmpl, 0700);
1677 }
1678
1679 /**
1680  * g_mkstemp_full: (skip)
1681  * @tmpl: (type filename): template filename
1682  * @flags: flags to pass to an open() call in addition to O_EXCL
1683  *   and O_CREAT, which are passed automatically
1684  * @mode: permissions to create the temporary file with
1685  *
1686  * Opens a temporary file. See the mkstemp() documentation
1687  * on most UNIX-like systems.
1688  *
1689  * The parameter is a string that should follow the rules for
1690  * mkstemp() templates, i.e. contain the string "XXXXXX".
1691  * g_mkstemp_full() is slightly more flexible than mkstemp()
1692  * in that the sequence does not have to occur at the very end of the
1693  * template and you can pass a @mode and additional @flags. The X
1694  * string will be modified to form the name of a file that didn't exist.
1695  * The string should be in the GLib file name encoding. Most importantly,
1696  * on Windows it should be in UTF-8.
1697  *
1698  * Returns: A file handle (as from open()) to the file
1699  *   opened for reading and writing. The file handle should be
1700  *   closed with close(). In case of errors, -1 is returned
1701  *   and %errno will be set.
1702  *
1703  * Since: 2.22
1704  */
1705 gint
1706 g_mkstemp_full (gchar *tmpl,
1707                 gint   flags,
1708                 gint   mode)
1709 {
1710   /* tmpl is in UTF-8 on Windows, thus use g_open() */
1711   return get_tmp_file (tmpl, wrap_g_open,
1712                        flags | O_CREAT | O_EXCL, mode);
1713 }
1714
1715 /**
1716  * g_mkstemp: (skip)
1717  * @tmpl: (type filename): template filename
1718  *
1719  * Opens a temporary file. See the mkstemp() documentation
1720  * on most UNIX-like systems.
1721  *
1722  * The parameter is a string that should follow the rules for
1723  * mkstemp() templates, i.e. contain the string "XXXXXX".
1724  * g_mkstemp() is slightly more flexible than mkstemp() in that the
1725  * sequence does not have to occur at the very end of the template.
1726  * The X string will be modified to form the name of a file that
1727  * didn't exist. The string should be in the GLib file name encoding.
1728  * Most importantly, on Windows it should be in UTF-8.
1729  *
1730  * Returns: A file handle (as from open()) to the file
1731  *   opened for reading and writing. The file is opened in binary
1732  *   mode on platforms where there is a difference. The file handle
1733  *   should be closed with close(). In case of errors, -1 is
1734  *   returned and %errno will be set.
1735  */
1736 gint
1737 g_mkstemp (gchar *tmpl)
1738 {
1739   return g_mkstemp_full (tmpl, O_RDWR | O_BINARY | O_CLOEXEC, 0600);
1740 }
1741
1742 static gint
1743 g_get_tmp_name (const gchar      *tmpl,
1744                 gchar           **name_used,
1745                 GTmpFileCallback  f,
1746                 gint              flags,
1747                 gint              mode,
1748                 GError          **error)
1749 {
1750   int retval;
1751   const char *tmpdir;
1752   const char *sep;
1753   char *fulltemplate;
1754   const char *slash;
1755
1756   if (tmpl == NULL)
1757     tmpl = ".XXXXXX";
1758
1759   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1760 #ifdef G_OS_WIN32
1761       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1762 #endif
1763       )
1764     {
1765       gchar *display_tmpl = g_filename_display_name (tmpl);
1766       char c[2];
1767       c[0] = *slash;
1768       c[1] = '\0';
1769
1770       g_set_error (error,
1771                    G_FILE_ERROR,
1772                    G_FILE_ERROR_FAILED,
1773                    _("Template “%s” invalid, should not contain a “%s”"),
1774                    display_tmpl, c);
1775       g_free (display_tmpl);
1776
1777       return -1;
1778     }
1779
1780   if (strstr (tmpl, "XXXXXX") == NULL)
1781     {
1782       gchar *display_tmpl = g_filename_display_name (tmpl);
1783       g_set_error (error,
1784                    G_FILE_ERROR,
1785                    G_FILE_ERROR_FAILED,
1786                    _("Template “%s” doesn’t contain XXXXXX"),
1787                    display_tmpl);
1788       g_free (display_tmpl);
1789       return -1;
1790     }
1791
1792   tmpdir = g_get_tmp_dir ();
1793
1794   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1795     sep = "";
1796   else
1797     sep = G_DIR_SEPARATOR_S;
1798
1799   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1800
1801   retval = get_tmp_file (fulltemplate, f, flags, mode);
1802   if (retval == -1)
1803     {
1804       int saved_errno = errno;
1805       if (error)
1806         set_file_error (error,
1807                         fulltemplate,
1808                         _("Failed to create file “%s”: %s"),
1809                         saved_errno);
1810       g_free (fulltemplate);
1811       return -1;
1812     }
1813
1814   *name_used = fulltemplate;
1815
1816   return retval;
1817 }
1818
1819 /**
1820  * g_file_open_tmp:
1821  * @tmpl: (type filename) (nullable): Template for file name, as in
1822  *   g_mkstemp(), basename only, or %NULL for a default template
1823  * @name_used: (out) (type filename): location to store actual name used,
1824  *   or %NULL
1825  * @error: return location for a #GError
1826  *
1827  * Opens a file for writing in the preferred directory for temporary
1828  * files (as returned by g_get_tmp_dir()).
1829  *
1830  * @tmpl should be a string in the GLib file name encoding containing
1831  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1832  * However, unlike these functions, the template should only be a
1833  * basename, no directory components are allowed. If template is
1834  * %NULL, a default template is used.
1835  *
1836  * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1837  * modified, and might thus be a read-only literal string.
1838  *
1839  * Upon success, and if @name_used is non-%NULL, the actual name used
1840  * is returned in @name_used. This string should be freed with g_free()
1841  * when not needed any longer. The returned name is in the GLib file
1842  * name encoding.
1843  *
1844  * Returns: A file handle (as from open()) to the file opened for
1845  *   reading and writing. The file is opened in binary mode on platforms
1846  *   where there is a difference. The file handle should be closed with
1847  *   close(). In case of errors, -1 is returned and @error will be set.
1848  */
1849 gint
1850 g_file_open_tmp (const gchar  *tmpl,
1851                  gchar       **name_used,
1852                  GError      **error)
1853 {
1854   gchar *fulltemplate;
1855   gint result;
1856
1857   g_return_val_if_fail (error == NULL || *error == NULL, -1);
1858
1859   result = g_get_tmp_name (tmpl, &fulltemplate,
1860                            wrap_g_open,
1861                            O_CREAT | O_EXCL | O_RDWR | O_BINARY | O_CLOEXEC,
1862                            0600,
1863                            error);
1864   if (result != -1)
1865     {
1866       if (name_used)
1867         *name_used = fulltemplate;
1868       else
1869         g_free (fulltemplate);
1870     }
1871
1872   return result;
1873 }
1874
1875 /**
1876  * g_dir_make_tmp:
1877  * @tmpl: (type filename) (nullable): Template for directory name,
1878  *   as in g_mkdtemp(), basename only, or %NULL for a default template
1879  * @error: return location for a #GError
1880  *
1881  * Creates a subdirectory in the preferred directory for temporary
1882  * files (as returned by g_get_tmp_dir()).
1883  *
1884  * @tmpl should be a string in the GLib file name encoding containing
1885  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1886  * However, unlike these functions, the template should only be a
1887  * basename, no directory components are allowed. If template is
1888  * %NULL, a default template is used.
1889  *
1890  * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1891  * modified, and might thus be a read-only literal string.
1892  *
1893  * Returns: (type filename) (transfer full): The actual name used. This string
1894  *   should be freed with g_free() when not needed any longer and is
1895  *   is in the GLib file name encoding. In case of errors, %NULL is
1896  *   returned and @error will be set.
1897  *
1898  * Since: 2.30
1899  */
1900 gchar *
1901 g_dir_make_tmp (const gchar  *tmpl,
1902                 GError      **error)
1903 {
1904   gchar *fulltemplate;
1905
1906   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1907
1908   if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1909     return NULL;
1910   else
1911     return fulltemplate;
1912 }
1913
1914 static gchar *
1915 g_build_path_va (const gchar  *separator,
1916                  const gchar  *first_element,
1917                  va_list      *args,
1918                  gchar       **str_array)
1919 {
1920   GString *result;
1921   gint separator_len = strlen (separator);
1922   gboolean is_first = TRUE;
1923   gboolean have_leading = FALSE;
1924   const gchar *single_element = NULL;
1925   const gchar *next_element;
1926   const gchar *last_trailing = NULL;
1927   gint i = 0;
1928
1929   result = g_string_new (NULL);
1930
1931   if (str_array)
1932     next_element = str_array[i++];
1933   else
1934     next_element = first_element;
1935
1936   while (TRUE)
1937     {
1938       const gchar *element;
1939       const gchar *start;
1940       const gchar *end;
1941
1942       if (next_element)
1943         {
1944           element = next_element;
1945           if (str_array)
1946             next_element = str_array[i++];
1947           else
1948             next_element = va_arg (*args, gchar *);
1949         }
1950       else
1951         break;
1952
1953       /* Ignore empty elements */
1954       if (!*element)
1955         continue;
1956       
1957       start = element;
1958
1959       if (separator_len)
1960         {
1961           while (strncmp (start, separator, separator_len) == 0)
1962             start += separator_len;
1963         }
1964
1965       end = start + strlen (start);
1966       
1967       if (separator_len)
1968         {
1969           while (end >= start + separator_len &&
1970                  strncmp (end - separator_len, separator, separator_len) == 0)
1971             end -= separator_len;
1972           
1973           last_trailing = end;
1974           while (last_trailing >= element + separator_len &&
1975                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1976             last_trailing -= separator_len;
1977
1978           if (!have_leading)
1979             {
1980               /* If the leading and trailing separator strings are in the
1981                * same element and overlap, the result is exactly that element
1982                */
1983               if (last_trailing <= start)
1984                 single_element = element;
1985                   
1986               g_string_append_len (result, element, start - element);
1987               have_leading = TRUE;
1988             }
1989           else
1990             single_element = NULL;
1991         }
1992
1993       if (end == start)
1994         continue;
1995
1996       if (!is_first)
1997         g_string_append (result, separator);
1998       
1999       g_string_append_len (result, start, end - start);
2000       is_first = FALSE;
2001     }
2002
2003   if (single_element)
2004     {
2005       g_string_free (result, TRUE);
2006       return g_strdup (single_element);
2007     }
2008   else
2009     {
2010       if (last_trailing)
2011         g_string_append (result, last_trailing);
2012   
2013       return g_string_free (result, FALSE);
2014     }
2015 }
2016
2017 /**
2018  * g_build_pathv:
2019  * @separator: a string used to separator the elements of the path.
2020  * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
2021  *   array of strings containing the path elements.
2022  * 
2023  * Behaves exactly like g_build_path(), but takes the path elements
2024  * as a string array, instead of variadic arguments.
2025  *
2026  * This function is mainly meant for language bindings.
2027  *
2028  * Returns: (type filename) (transfer full): a newly-allocated string that
2029  *     must be freed with g_free().
2030  *
2031  * Since: 2.8
2032  */
2033 gchar *
2034 g_build_pathv (const gchar  *separator,
2035                gchar       **args)
2036 {
2037   if (!args)
2038     return NULL;
2039
2040   return g_build_path_va (separator, NULL, NULL, args);
2041 }
2042
2043
2044 /**
2045  * g_build_path:
2046  * @separator: (type filename): a string used to separator the elements of the path.
2047  * @first_element: (type filename): the first element in the path
2048  * @...: remaining elements in path, terminated by %NULL
2049  * 
2050  * Creates a path from a series of elements using @separator as the
2051  * separator between elements.
2052  *
2053  * At the boundary between two elements, any trailing occurrences of
2054  * separator in the first element, or leading occurrences of separator
2055  * in the second element are removed and exactly one copy of the
2056  * separator is inserted.
2057  *
2058  * Empty elements are ignored.
2059  *
2060  * The number of leading copies of the separator on the result is
2061  * the same as the number of leading copies of the separator on
2062  * the first non-empty element.
2063  *
2064  * The number of trailing copies of the separator on the result is
2065  * the same as the number of trailing copies of the separator on
2066  * the last non-empty element. (Determination of the number of
2067  * trailing copies is done without stripping leading copies, so
2068  * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
2069  *
2070  * However, if there is only a single non-empty element, and there
2071  * are no characters in that element not part of the leading or
2072  * trailing separators, then the result is exactly the original value
2073  * of that element.
2074  *
2075  * Other than for determination of the number of leading and trailing
2076  * copies of the separator, elements consisting only of copies
2077  * of the separator are ignored.
2078  *
2079  * Returns: (type filename) (transfer full): the newly allocated path
2080  **/
2081 gchar *
2082 g_build_path (const gchar *separator,
2083               const gchar *first_element,
2084               ...)
2085 {
2086   gchar *str;
2087   va_list args;
2088
2089   g_return_val_if_fail (separator != NULL, NULL);
2090
2091   va_start (args, first_element);
2092   str = g_build_path_va (separator, first_element, &args, NULL);
2093   va_end (args);
2094
2095   return str;
2096 }
2097
2098 #ifdef G_OS_WIN32
2099
2100 static gchar *
2101 g_build_pathname_va (const gchar  *first_element,
2102                      va_list      *args,
2103                      gchar       **str_array)
2104 {
2105   /* Code copied from g_build_pathv(), and modified to use two
2106    * alternative single-character separators.
2107    */
2108   GString *result;
2109   gboolean is_first = TRUE;
2110   gboolean have_leading = FALSE;
2111   const gchar *single_element = NULL;
2112   const gchar *next_element;
2113   const gchar *last_trailing = NULL;
2114   gchar current_separator = '\\';
2115   gint i = 0;
2116
2117   result = g_string_new (NULL);
2118
2119   if (str_array)
2120     next_element = str_array[i++];
2121   else
2122     next_element = first_element;
2123   
2124   while (TRUE)
2125     {
2126       const gchar *element;
2127       const gchar *start;
2128       const gchar *end;
2129
2130       if (next_element)
2131         {
2132           element = next_element;
2133           if (str_array)
2134             next_element = str_array[i++];
2135           else
2136             next_element = va_arg (*args, gchar *);
2137         }
2138       else
2139         break;
2140
2141       /* Ignore empty elements */
2142       if (!*element)
2143         continue;
2144       
2145       start = element;
2146
2147       if (TRUE)
2148         {
2149           while (start &&
2150                  (*start == '\\' || *start == '/'))
2151             {
2152               current_separator = *start;
2153               start++;
2154             }
2155         }
2156
2157       end = start + strlen (start);
2158       
2159       if (TRUE)
2160         {
2161           while (end >= start + 1 &&
2162                  (end[-1] == '\\' || end[-1] == '/'))
2163             {
2164               current_separator = end[-1];
2165               end--;
2166             }
2167           
2168           last_trailing = end;
2169           while (last_trailing >= element + 1 &&
2170                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
2171             last_trailing--;
2172
2173           if (!have_leading)
2174             {
2175               /* If the leading and trailing separator strings are in the
2176                * same element and overlap, the result is exactly that element
2177                */
2178               if (last_trailing <= start)
2179                 single_element = element;
2180                   
2181               g_string_append_len (result, element, start - element);
2182               have_leading = TRUE;
2183             }
2184           else
2185             single_element = NULL;
2186         }
2187
2188       if (end == start)
2189         continue;
2190
2191       if (!is_first)
2192         g_string_append_len (result, &current_separator, 1);
2193       
2194       g_string_append_len (result, start, end - start);
2195       is_first = FALSE;
2196     }
2197
2198   if (single_element)
2199     {
2200       g_string_free (result, TRUE);
2201       return g_strdup (single_element);
2202     }
2203   else
2204     {
2205       if (last_trailing)
2206         g_string_append (result, last_trailing);
2207   
2208       return g_string_free (result, FALSE);
2209     }
2210 }
2211
2212 #endif
2213
2214 static gchar *
2215 g_build_filename_va (const gchar  *first_argument,
2216                      va_list      *args,
2217                      gchar       **str_array)
2218 {
2219   gchar *str;
2220
2221 #ifndef G_OS_WIN32
2222   str = g_build_path_va (G_DIR_SEPARATOR_S, first_argument, args, str_array);
2223 #else
2224   str = g_build_pathname_va (first_argument, args, str_array);
2225 #endif
2226
2227   return str;
2228 }
2229
2230 /**
2231  * g_build_filename_valist:
2232  * @first_element: (type filename): the first element in the path
2233  * @args: va_list of remaining elements in path
2234  *
2235  * Creates a filename from a list of elements using the correct
2236  * separator for the current platform.
2237  *
2238  * Behaves exactly like g_build_filename(), but takes the path elements
2239  * as a va_list.
2240  *
2241  * This function is mainly meant for implementing other variadic arguments
2242  * functions.
2243  *
2244  * Returns: (type filename) (transfer full): the newly allocated path
2245  *
2246  * Since: 2.56
2247  */
2248 gchar *
2249 g_build_filename_valist (const gchar  *first_element,
2250                          va_list      *args)
2251 {
2252   g_return_val_if_fail (first_element != NULL, NULL);
2253
2254   return g_build_filename_va (first_element, args, NULL);
2255 }
2256
2257 /**
2258  * g_build_filenamev:
2259  * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
2260  *   array of strings containing the path elements.
2261  * 
2262  * Creates a filename from a vector of elements using the correct
2263  * separator for the current platform.
2264  *
2265  * This function behaves exactly like g_build_filename(), but takes the path
2266  * elements as a string array, instead of varargs. This function is mainly
2267  * meant for language bindings.
2268  *
2269  * If you are building a path programmatically you may want to use
2270  * #GPathBuf instead.
2271  *
2272  * Returns: (type filename) (transfer full): the newly allocated path
2273  *
2274  * Since: 2.8
2275  */
2276 gchar *
2277 g_build_filenamev (gchar **args)
2278 {
2279   return g_build_filename_va (NULL, NULL, args);
2280 }
2281
2282 /**
2283  * g_build_filename:
2284  * @first_element: (type filename): the first element in the path
2285  * @...: remaining elements in path, terminated by %NULL
2286  * 
2287  * Creates a filename from a series of elements using the correct
2288  * separator for the current platform.
2289  *
2290  * On Unix, this function behaves identically to `g_build_path
2291  * (G_DIR_SEPARATOR_S, first_element, ....)`.
2292  *
2293  * On Windows, it takes into account that either the backslash
2294  * (`\` or slash (`/`) can be used as separator in filenames, but
2295  * otherwise behaves as on UNIX. When file pathname separators need
2296  * to be inserted, the one that last previously occurred in the
2297  * parameters (reading from left to right) is used.
2298  *
2299  * No attempt is made to force the resulting filename to be an absolute
2300  * path. If the first element is a relative path, the result will
2301  * be a relative path.
2302  *
2303  * If you are building a path programmatically you may want to use
2304  * #GPathBuf instead.
2305  *
2306  * Returns: (type filename) (transfer full): the newly allocated path
2307  */
2308 gchar *
2309 g_build_filename (const gchar *first_element, 
2310                   ...)
2311 {
2312   gchar *str;
2313   va_list args;
2314
2315   va_start (args, first_element);
2316   str = g_build_filename_va (first_element, &args, NULL);
2317   va_end (args);
2318
2319   return str;
2320 }
2321
2322 /**
2323  * g_file_read_link:
2324  * @filename: (type filename): the symbolic link
2325  * @error: return location for a #GError
2326  *
2327  * Reads the contents of the symbolic link @filename like the POSIX
2328  * `readlink()` function.
2329  *
2330  * The returned string is in the encoding used for filenames. Use
2331  * g_filename_to_utf8() to convert it to UTF-8.
2332  *
2333  * The returned string may also be a relative path. Use g_build_filename()
2334  * to convert it to an absolute path:
2335  *
2336  * |[<!-- language="C" -->
2337  * g_autoptr(GError) local_error = NULL;
2338  * g_autofree gchar *link_target = g_file_read_link ("/etc/localtime", &local_error);
2339  *
2340  * if (local_error != NULL)
2341  *   g_error ("Error reading link: %s", local_error->message);
2342  *
2343  * if (!g_path_is_absolute (link_target))
2344  *   {
2345  *     g_autofree gchar *absolute_link_target = g_build_filename ("/etc", link_target, NULL);
2346  *     g_free (link_target);
2347  *     link_target = g_steal_pointer (&absolute_link_target);
2348  *   }
2349  * ]|
2350  *
2351  * Returns: (type filename) (transfer full): A newly-allocated string with
2352  *   the contents of the symbolic link, or %NULL if an error occurred.
2353  *
2354  * Since: 2.4
2355  */
2356 gchar *
2357 g_file_read_link (const gchar  *filename,
2358                   GError      **error)
2359 {
2360 #if defined (HAVE_READLINK)
2361   gchar *buffer;
2362   size_t size;
2363   gssize read_size;
2364   
2365   g_return_val_if_fail (filename != NULL, NULL);
2366   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2367
2368   size = 256;
2369   buffer = g_malloc (size);
2370   
2371   while (TRUE) 
2372     {
2373       read_size = readlink (filename, buffer, size);
2374       if (read_size < 0)
2375         {
2376           int saved_errno = errno;
2377           if (error)
2378             set_file_error (error,
2379                             filename,
2380                             _("Failed to read the symbolic link “%s”: %s"),
2381                             saved_errno);
2382           g_free (buffer);
2383           return NULL;
2384         }
2385     
2386       if ((size_t) read_size < size)
2387         {
2388           buffer[read_size] = 0;
2389           return buffer;
2390         }
2391       
2392       size *= 2;
2393       buffer = g_realloc (buffer, size);
2394     }
2395 #elif defined (G_OS_WIN32)
2396   gchar *buffer;
2397   gssize read_size;
2398   
2399   g_return_val_if_fail (filename != NULL, NULL);
2400   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2401
2402   read_size = g_win32_readlink_utf8 (filename, NULL, 0, &buffer, TRUE);
2403   if (read_size < 0)
2404     {
2405       int saved_errno = errno;
2406       if (error)
2407         set_file_error (error,
2408                         filename,
2409                         _("Failed to read the symbolic link “%s”: %s"),
2410                         saved_errno);
2411       return NULL;
2412     }
2413   else if (read_size == 0)
2414     return strdup ("");
2415   else
2416     return buffer;
2417 #else
2418   g_return_val_if_fail (filename != NULL, NULL);
2419   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2420
2421   g_set_error_literal (error,
2422                        G_FILE_ERROR,
2423                        G_FILE_ERROR_INVAL,
2424                        _("Symbolic links not supported"));
2425         
2426   return NULL;
2427 #endif
2428 }
2429
2430 /**
2431  * g_path_is_absolute:
2432  * @file_name: (type filename): a file name
2433  *
2434  * Returns %TRUE if the given @file_name is an absolute file name.
2435  * Note that this is a somewhat vague concept on Windows.
2436  *
2437  * On POSIX systems, an absolute file name is well-defined. It always
2438  * starts from the single root directory. For example "/usr/local".
2439  *
2440  * On Windows, the concepts of current drive and drive-specific
2441  * current directory introduce vagueness. This function interprets as
2442  * an absolute file name one that either begins with a directory
2443  * separator such as "\Users\tml" or begins with the root on a drive,
2444  * for example "C:\Windows". The first case also includes UNC paths
2445  * such as "\\\\myserver\docs\foo". In all cases, either slashes or
2446  * backslashes are accepted.
2447  *
2448  * Note that a file name relative to the current drive root does not
2449  * truly specify a file uniquely over time and across processes, as
2450  * the current drive is a per-process value and can be changed.
2451  *
2452  * File names relative the current directory on some specific drive,
2453  * such as "D:foo/bar", are not interpreted as absolute by this
2454  * function, but they obviously are not relative to the normal current
2455  * directory as returned by getcwd() or g_get_current_dir()
2456  * either. Such paths should be avoided, or need to be handled using
2457  * Windows-specific code.
2458  *
2459  * Returns: %TRUE if @file_name is absolute
2460  */
2461 gboolean
2462 g_path_is_absolute (const gchar *file_name)
2463 {
2464   g_return_val_if_fail (file_name != NULL, FALSE);
2465
2466   if (G_IS_DIR_SEPARATOR (file_name[0]))
2467     return TRUE;
2468
2469 #ifdef G_OS_WIN32
2470   /* Recognize drive letter on native Windows */
2471   if (g_ascii_isalpha (file_name[0]) &&
2472       file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2473     return TRUE;
2474 #endif
2475
2476   return FALSE;
2477 }
2478
2479 /**
2480  * g_path_skip_root:
2481  * @file_name: (type filename): a file name
2482  *
2483  * Returns a pointer into @file_name after the root component,
2484  * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2485  * is not an absolute path it returns %NULL.
2486  *
2487  * Returns: (type filename) (nullable): a pointer into @file_name after the
2488  *     root component
2489  */
2490 const gchar *
2491 g_path_skip_root (const gchar *file_name)
2492 {
2493   g_return_val_if_fail (file_name != NULL, NULL);
2494
2495 #ifdef G_PLATFORM_WIN32
2496   /* Skip \\server\share or //server/share */
2497   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2498       G_IS_DIR_SEPARATOR (file_name[1]) &&
2499       file_name[2] &&
2500       !G_IS_DIR_SEPARATOR (file_name[2]))
2501     {
2502       gchar *p;
2503       p = strchr (file_name + 2, G_DIR_SEPARATOR);
2504
2505 #ifdef G_OS_WIN32
2506       {
2507         gchar *q;
2508
2509         q = strchr (file_name + 2, '/');
2510         if (p == NULL || (q != NULL && q < p))
2511         p = q;
2512       }
2513 #endif
2514
2515       if (p && p > file_name + 2 && p[1])
2516         {
2517           file_name = p + 1;
2518
2519           while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2520             file_name++;
2521
2522           /* Possibly skip a backslash after the share name */
2523           if (G_IS_DIR_SEPARATOR (file_name[0]))
2524             file_name++;
2525
2526           return (gchar *)file_name;
2527         }
2528     }
2529 #endif
2530
2531   /* Skip initial slashes */
2532   if (G_IS_DIR_SEPARATOR (file_name[0]))
2533     {
2534       while (G_IS_DIR_SEPARATOR (file_name[0]))
2535         file_name++;
2536       return (gchar *)file_name;
2537     }
2538
2539 #ifdef G_OS_WIN32
2540   /* Skip X:\ */
2541   if (g_ascii_isalpha (file_name[0]) &&
2542       file_name[1] == ':' &&
2543       G_IS_DIR_SEPARATOR (file_name[2]))
2544     return (gchar *)file_name + 3;
2545 #endif
2546
2547   return NULL;
2548 }
2549
2550 /**
2551  * g_basename:
2552  * @file_name: (type filename): the name of the file
2553  *
2554  * Gets the name of the file without any leading directory
2555  * components. It returns a pointer into the given file name
2556  * string.
2557  *
2558  * Returns: (type filename): the name of the file without any leading
2559  *   directory components
2560  *
2561  * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2562  *   that g_path_get_basename() allocates new memory for the
2563  *   returned string, unlike this function which returns a pointer
2564  *   into the argument.
2565  */
2566 const gchar *
2567 g_basename (const gchar *file_name)
2568 {
2569   gchar *base;
2570
2571   g_return_val_if_fail (file_name != NULL, NULL);
2572
2573   base = strrchr (file_name, G_DIR_SEPARATOR);
2574
2575 #ifdef G_OS_WIN32
2576   {
2577     gchar *q;
2578     q = strrchr (file_name, '/');
2579     if (base == NULL || (q != NULL && q > base))
2580       base = q;
2581   }
2582 #endif
2583
2584   if (base)
2585     return base + 1;
2586
2587 #ifdef G_OS_WIN32
2588   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2589     return (gchar*) file_name + 2;
2590 #endif
2591
2592   return (gchar*) file_name;
2593 }
2594
2595 /**
2596  * g_path_get_basename:
2597  * @file_name: (type filename): the name of the file
2598  *
2599  * Gets the last component of the filename.
2600  *
2601  * If @file_name ends with a directory separator it gets the component
2602  * before the last slash. If @file_name consists only of directory
2603  * separators (and on Windows, possibly a drive letter), a single
2604  * separator is returned. If @file_name is empty, it gets ".".
2605  *
2606  * Returns: (type filename) (transfer full): a newly allocated string
2607  *   containing the last component of the filename
2608  */
2609 gchar *
2610 g_path_get_basename (const gchar *file_name)
2611 {
2612   gssize base;
2613   gssize last_nonslash;
2614   gsize len;
2615   gchar *retval;
2616
2617   g_return_val_if_fail (file_name != NULL, NULL);
2618
2619   if (file_name[0] == '\0')
2620     return g_strdup (".");
2621
2622   last_nonslash = strlen (file_name) - 1;
2623
2624   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2625     last_nonslash--;
2626
2627   if (last_nonslash == -1)
2628     /* string only containing slashes */
2629     return g_strdup (G_DIR_SEPARATOR_S);
2630
2631 #ifdef G_OS_WIN32
2632   if (last_nonslash == 1 &&
2633       g_ascii_isalpha (file_name[0]) &&
2634       file_name[1] == ':')
2635     /* string only containing slashes and a drive */
2636     return g_strdup (G_DIR_SEPARATOR_S);
2637 #endif
2638   base = last_nonslash;
2639
2640   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2641     base--;
2642
2643 #ifdef G_OS_WIN32
2644   if (base == -1 &&
2645       g_ascii_isalpha (file_name[0]) &&
2646       file_name[1] == ':')
2647     base = 1;
2648 #endif /* G_OS_WIN32 */
2649
2650   len = last_nonslash - base;
2651   retval = g_malloc (len + 1);
2652   memcpy (retval, file_name + (base + 1), len);
2653   retval [len] = '\0';
2654
2655   return retval;
2656 }
2657
2658 /**
2659  * g_dirname:
2660  * @file_name: (type filename): the name of the file
2661  *
2662  * Gets the directory components of a file name.
2663  *
2664  * If the file name has no directory components "." is returned.
2665  * The returned string should be freed when no longer needed.
2666  *
2667  * Returns: (type filename) (transfer full): the directory components of the file
2668  *
2669  * Deprecated: use g_path_get_dirname() instead
2670  */
2671
2672 /**
2673  * g_path_get_dirname:
2674  * @file_name: (type filename): the name of the file
2675  *
2676  * Gets the directory components of a file name. For example, the directory
2677  * component of `/usr/bin/test` is `/usr/bin`. The directory component of `/`
2678  * is `/`.
2679  *
2680  * If the file name has no directory components "." is returned.
2681  * The returned string should be freed when no longer needed.
2682  *
2683  * Returns: (type filename) (transfer full): the directory components of the file
2684  */
2685 gchar *
2686 g_path_get_dirname (const gchar *file_name)
2687 {
2688   gchar *base;
2689   gsize len;
2690
2691   g_return_val_if_fail (file_name != NULL, NULL);
2692
2693   base = strrchr (file_name, G_DIR_SEPARATOR);
2694
2695 #ifdef G_OS_WIN32
2696   {
2697     gchar *q;
2698     q = strrchr (file_name, '/');
2699     if (base == NULL || (q != NULL && q > base))
2700       base = q;
2701   }
2702 #endif
2703
2704   if (!base)
2705     {
2706 #ifdef G_OS_WIN32
2707       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2708         {
2709           gchar drive_colon_dot[4];
2710
2711           drive_colon_dot[0] = file_name[0];
2712           drive_colon_dot[1] = ':';
2713           drive_colon_dot[2] = '.';
2714           drive_colon_dot[3] = '\0';
2715
2716           return g_strdup (drive_colon_dot);
2717         }
2718 #endif
2719     return g_strdup (".");
2720     }
2721
2722   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2723     base--;
2724
2725 #ifdef G_OS_WIN32
2726   /* base points to the char before the last slash.
2727    *
2728    * In case file_name is the root of a drive (X:\) or a child of the
2729    * root of a drive (X:\foo), include the slash.
2730    *
2731    * In case file_name is the root share of an UNC path
2732    * (\\server\share), add a slash, returning \\server\share\ .
2733    *
2734    * In case file_name is a direct child of a share in an UNC path
2735    * (\\server\share\foo), include the slash after the share name,
2736    * returning \\server\share\ .
2737    */
2738   if (base == file_name + 1 &&
2739       g_ascii_isalpha (file_name[0]) &&
2740       file_name[1] == ':')
2741     base++;
2742   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2743            G_IS_DIR_SEPARATOR (file_name[1]) &&
2744            file_name[2] &&
2745            !G_IS_DIR_SEPARATOR (file_name[2]) &&
2746            base >= file_name + 2)
2747     {
2748       const gchar *p = file_name + 2;
2749       while (*p && !G_IS_DIR_SEPARATOR (*p))
2750         p++;
2751       if (p == base + 1)
2752         {
2753           len = (guint) strlen (file_name) + 1;
2754           base = g_new (gchar, len + 1);
2755           strcpy (base, file_name);
2756           base[len-1] = G_DIR_SEPARATOR;
2757           base[len] = 0;
2758           return base;
2759         }
2760       if (G_IS_DIR_SEPARATOR (*p))
2761         {
2762           p++;
2763           while (*p && !G_IS_DIR_SEPARATOR (*p))
2764             p++;
2765           if (p == base + 1)
2766             base++;
2767         }
2768     }
2769 #endif
2770
2771   len = (guint) 1 + base - file_name;
2772   base = g_new (gchar, len + 1);
2773   memmove (base, file_name, len);
2774   base[len] = 0;
2775
2776   return base;
2777 }
2778
2779 /**
2780  * g_canonicalize_filename:
2781  * @filename: (type filename): the name of the file
2782  * @relative_to: (type filename) (nullable): the relative directory, or %NULL
2783  * to use the current working directory
2784  *
2785  * Gets the canonical file name from @filename. All triple slashes are turned into
2786  * single slashes, and all `..` and `.`s resolved against @relative_to.
2787  *
2788  * Symlinks are not followed, and the returned path is guaranteed to be absolute.
2789  *
2790  * If @filename is an absolute path, @relative_to is ignored. Otherwise,
2791  * @relative_to will be prepended to @filename to make it absolute. @relative_to
2792  * must be an absolute path, or %NULL. If @relative_to is %NULL, it'll fallback
2793  * to g_get_current_dir().
2794  *
2795  * This function never fails, and will canonicalize file paths even if they don't
2796  * exist.
2797  *
2798  * No file system I/O is done.
2799  *
2800  * Returns: (type filename) (transfer full): a newly allocated string with the
2801  *   canonical file path
2802  *
2803  * Since: 2.58
2804  */
2805 gchar *
2806 g_canonicalize_filename (const gchar *filename,
2807                          const gchar *relative_to)
2808 {
2809   gchar *canon, *input, *output, *after_root, *output_start;
2810
2811   g_return_val_if_fail (relative_to == NULL || g_path_is_absolute (relative_to), NULL);
2812
2813   if (!g_path_is_absolute (filename))
2814     {
2815       gchar *cwd_allocated = NULL;
2816       const gchar  *cwd;
2817
2818       if (relative_to != NULL)
2819         cwd = relative_to;
2820       else
2821         cwd = cwd_allocated = g_get_current_dir ();
2822
2823       canon = g_build_filename (cwd, filename, NULL);
2824       g_free (cwd_allocated);
2825     }
2826   else
2827     {
2828       canon = g_strdup (filename);
2829     }
2830
2831   after_root = (char *)g_path_skip_root (canon);
2832
2833   if (after_root == NULL)
2834     {
2835       /* This shouldn't really happen, as g_get_current_dir() should
2836          return an absolute pathname, but bug 573843 shows this is
2837          not always happening */
2838       g_free (canon);
2839       return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
2840     }
2841
2842   /* Find the first dir separator and use the canonical dir separator. */
2843   for (output = after_root - 1;
2844        (output >= canon) && G_IS_DIR_SEPARATOR (*output);
2845        output--)
2846     *output = G_DIR_SEPARATOR;
2847
2848   /* 1 to re-increment after the final decrement above (so that output >= canon),
2849    * and 1 to skip the first `/`. There might not be a first `/` if
2850    * the @canon is a Windows `//server/share` style path with no
2851    * trailing directories. @after_root will be '\0' in that case. */
2852   output++;
2853   if (*output == G_DIR_SEPARATOR)
2854     output++;
2855
2856   /* POSIX allows double slashes at the start to mean something special
2857    * (as does windows too). So, "//" != "/", but more than two slashes
2858    * is treated as "/".
2859    */
2860   if (after_root - output == 1)
2861     output++;
2862
2863   input = after_root;
2864   output_start = output;
2865   while (*input)
2866     {
2867       /* input points to the next non-separator to be processed. */
2868       /* output points to the next location to write to. */
2869       g_assert (input > canon && G_IS_DIR_SEPARATOR (input[-1]));
2870       g_assert (output > canon && G_IS_DIR_SEPARATOR (output[-1]));
2871       g_assert (input >= output);
2872
2873       /* Ignore repeated dir separators. */
2874       while (G_IS_DIR_SEPARATOR (input[0]))
2875        input++;
2876
2877       /* Ignore single dot directory components. */
2878       if (input[0] == '.' && (input[1] == 0 || G_IS_DIR_SEPARATOR (input[1])))
2879         {
2880            if (input[1] == 0)
2881              break;
2882            input += 2;
2883         }
2884       /* Remove double-dot directory components along with the preceding
2885        * path component. */
2886       else if (input[0] == '.' && input[1] == '.' &&
2887                (input[2] == 0 || G_IS_DIR_SEPARATOR (input[2])))
2888         {
2889           if (output > output_start)
2890             {
2891               do
2892                 {
2893                   output--;
2894                 }
2895               while (!G_IS_DIR_SEPARATOR (output[-1]) && output > output_start);
2896             }
2897           if (input[2] == 0)
2898             break;
2899           input += 3;
2900         }
2901       /* Copy the input to the output until the next separator,
2902        * while converting it to canonical separator */
2903       else
2904         {
2905           while (*input && !G_IS_DIR_SEPARATOR (*input))
2906             *output++ = *input++;
2907           if (input[0] == 0)
2908             break;
2909           input++;
2910           *output++ = G_DIR_SEPARATOR;
2911         }
2912     }
2913
2914   /* Remove a potentially trailing dir separator */
2915   if (output > output_start && G_IS_DIR_SEPARATOR (output[-1]))
2916     output--;
2917
2918   *output = '\0';
2919
2920   return canon;
2921 }
2922
2923 #if defined(MAXPATHLEN)
2924 #define G_PATH_LENGTH MAXPATHLEN
2925 #elif defined(PATH_MAX)
2926 #define G_PATH_LENGTH PATH_MAX
2927 #elif defined(_PC_PATH_MAX)
2928 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2929 #else
2930 #define G_PATH_LENGTH 2048
2931 #endif
2932
2933 /**
2934  * g_get_current_dir:
2935  *
2936  * Gets the current directory.
2937  *
2938  * The returned string should be freed when no longer needed.
2939  * The encoding of the returned string is system defined.
2940  * On Windows, it is always UTF-8.
2941  *
2942  * Since GLib 2.40, this function will return the value of the "PWD"
2943  * environment variable if it is set and it happens to be the same as
2944  * the current directory.  This can make a difference in the case that
2945  * the current directory is the target of a symbolic link.
2946  *
2947  * Returns: (type filename) (transfer full): the current directory
2948  */
2949 gchar *
2950 g_get_current_dir (void)
2951 {
2952 #ifdef G_OS_WIN32
2953
2954   gchar *dir = NULL;
2955   wchar_t dummy[2], *wdir;
2956   DWORD len;
2957
2958   len = GetCurrentDirectoryW (2, dummy);
2959   wdir = g_new (wchar_t, len);
2960
2961   if (GetCurrentDirectoryW (len, wdir) == len - 1)
2962     dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2963
2964   g_free (wdir);
2965
2966   if (dir == NULL)
2967     dir = g_strdup ("\\");
2968
2969   return dir;
2970
2971 #else
2972   const gchar *pwd;
2973   gchar *buffer = NULL;
2974   gchar *dir = NULL;
2975   static gsize buffer_size = 0;
2976   struct stat pwdbuf, dotbuf;
2977
2978   pwd = g_getenv ("PWD");
2979   if (pwd != NULL &&
2980       g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2981       dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2982     return g_strdup (pwd);
2983
2984   if (buffer_size == 0)
2985     buffer_size = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2986
2987   while (buffer_size < G_MAXSIZE / 2)
2988     {
2989       g_free (buffer);
2990       buffer = g_new (gchar, buffer_size);
2991       *buffer = 0;
2992       dir = getcwd (buffer, buffer_size);
2993
2994       if (dir || errno != ERANGE)
2995         break;
2996
2997       buffer_size *= 2;
2998     }
2999
3000   /* Check that getcwd() nul-terminated the string. It should do, but the specs
3001    * don’t actually explicitly state that:
3002    * https://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html */
3003   g_assert (dir == NULL || strnlen (dir, buffer_size) < buffer_size);
3004
3005   if (!dir || !*buffer)
3006     {
3007       /* Fallback return value */
3008       g_assert (buffer_size >= 2);
3009       buffer[0] = G_DIR_SEPARATOR;
3010       buffer[1] = 0;
3011     }
3012
3013   dir = g_strdup (buffer);
3014   g_free (buffer);
3015
3016   return dir;
3017
3018 #endif /* !G_OS_WIN32 */
3019 }
3020
3021 #ifdef G_OS_WIN32
3022
3023 /* Binary compatibility versions. Not for newly compiled code. */
3024
3025 _GLIB_EXTERN gboolean g_file_test_utf8         (const gchar  *filename,
3026                                                 GFileTest     test);
3027 _GLIB_EXTERN gboolean g_file_get_contents_utf8 (const gchar  *filename,
3028                                                 gchar       **contents,
3029                                                 gsize        *length,
3030                                                 GError      **error);
3031 _GLIB_EXTERN gint     g_mkstemp_utf8           (gchar        *tmpl);
3032 _GLIB_EXTERN gint     g_file_open_tmp_utf8     (const gchar  *tmpl,
3033                                                 gchar       **name_used,
3034                                                 GError      **error);
3035 _GLIB_EXTERN gchar   *g_get_current_dir_utf8   (void);
3036
3037
3038 gboolean
3039 g_file_test_utf8 (const gchar *filename,
3040                   GFileTest    test)
3041 {
3042   return g_file_test (filename, test);
3043 }
3044
3045 gboolean
3046 g_file_get_contents_utf8 (const gchar  *filename,
3047                           gchar       **contents,
3048                           gsize        *length,
3049                           GError      **error)
3050 {
3051   return g_file_get_contents (filename, contents, length, error);
3052 }
3053
3054 gint
3055 g_mkstemp_utf8 (gchar *tmpl)
3056 {
3057   return g_mkstemp (tmpl);
3058 }
3059
3060 gint
3061 g_file_open_tmp_utf8 (const gchar  *tmpl,
3062                       gchar       **name_used,
3063                       GError      **error)
3064 {
3065   return g_file_open_tmp (tmpl, name_used, error);
3066 }
3067
3068 gchar *
3069 g_get_current_dir_utf8 (void)
3070 {
3071   return g_get_current_dir ();
3072 }
3073
3074 #endif