Coverage Report

Created: 2025-07-23 08:13

/src/pango/subprojects/glib/glib/gutils.c
Line
Count
Source (jump to first uncovered line)
1
/* GLIB - Library of useful routines for C programming
2
 * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
3
 *
4
 * SPDX-License-Identifier: LGPL-2.1-or-later
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
/*
21
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22
 * file for a list of people on the GLib Team.  See the ChangeLog
23
 * files for a list of changes.  These files are distributed with
24
 * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25
 */
26
27
/* 
28
 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
29
 */
30
31
#include "config.h"
32
33
#include "gutils.h"
34
#include "gutilsprivate.h"
35
36
#include <stdarg.h>
37
#include <stdlib.h>
38
#include <stdio.h>
39
#include <locale.h>
40
#include <string.h>
41
#include <ctype.h>    /* For tolower() */
42
#include <errno.h>
43
#include <sys/types.h>
44
#include <sys/stat.h>
45
#ifdef G_OS_UNIX
46
#include <pwd.h>
47
#include <sys/utsname.h>
48
#include <unistd.h>
49
#endif
50
#include <sys/types.h>
51
#ifdef HAVE_SYS_PARAM_H
52
#include <sys/param.h>
53
#endif
54
#ifdef HAVE_CRT_EXTERNS_H 
55
#include <crt_externs.h> /* for _NSGetEnviron */
56
#endif
57
#ifdef HAVE_SYS_AUXV_H
58
#include <sys/auxv.h>
59
#endif
60
61
#include "glib-init.h"
62
#include "glib-private.h"
63
#include "genviron.h"
64
#include "gfileutils.h"
65
#include "ggettext.h"
66
#include "ghash.h"
67
#include "gthread.h"
68
#include "gtestutils.h"
69
#include "gunicode.h"
70
#include "gstrfuncs.h"
71
#include "garray.h"
72
#include "glibintl.h"
73
#include "gstdio.h"
74
#include "gquark.h"
75
76
#ifdef G_PLATFORM_WIN32
77
#include "gconvert.h"
78
#include "gwin32.h"
79
#endif
80
81
82
#ifdef G_PLATFORM_WIN32
83
#  include <windows.h>
84
#  ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
85
#    define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
86
#    define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
87
#  endif
88
#  include <lmcons.h>   /* For UNLEN */
89
#endif /* G_PLATFORM_WIN32 */
90
91
#ifdef G_OS_WIN32
92
#  include <direct.h>
93
#  include <shlobj.h>
94
#  include <process.h>
95
#endif
96
97
#ifdef HAVE_CODESET
98
#include <langinfo.h>
99
#endif
100
101
/**
102
 * g_memmove: 
103
 * @dest: the destination address to copy the bytes to.
104
 * @src: the source address to copy the bytes from.
105
 * @len: the number of bytes to copy.
106
 *
107
 * Copies a block of memory @len bytes long, from @src to @dest.
108
 * The source and destination areas may overlap.
109
 *
110
 * Deprecated:2.40: Just use memmove().
111
 */
112
113
#ifdef G_OS_WIN32
114
#undef g_atexit
115
#endif
116
117
/**
118
 * g_atexit:
119
 * @func: (scope async): the function to call on normal program termination.
120
 * 
121
 * Specifies a function to be called at normal program termination.
122
 *
123
 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
124
 * macro that maps to a call to the atexit() function in the C
125
 * library. This means that in case the code that calls g_atexit(),
126
 * i.e. atexit(), is in a DLL, the function will be called when the
127
 * DLL is detached from the program. This typically makes more sense
128
 * than that the function is called when the GLib DLL is detached,
129
 * which happened earlier when g_atexit() was a function in the GLib
130
 * DLL.
131
 *
132
 * The behaviour of atexit() in the context of dynamically loaded
133
 * modules is not formally specified and varies wildly.
134
 *
135
 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
136
 * loaded module which is unloaded before the program terminates might
137
 * well cause a crash at program exit.
138
 *
139
 * Some POSIX systems implement atexit() like Windows, and have each
140
 * dynamically loaded module maintain an own atexit chain that is
141
 * called when the module is unloaded.
142
 *
143
 * On other POSIX systems, before a dynamically loaded module is
144
 * unloaded, the registered atexit functions (if any) residing in that
145
 * module are called, regardless where the code that registered them
146
 * resided. This is presumably the most robust approach.
147
 *
148
 * As can be seen from the above, for portability it's best to avoid
149
 * calling g_atexit() (or atexit()) except in the main executable of a
150
 * program.
151
 *
152
 * Deprecated:2.32: It is best to avoid g_atexit().
153
 */
154
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
155
void
156
g_atexit (GVoidFunc func)
157
0
{
158
0
  gint result;
159
0
  int errsv;
160
161
0
  result = atexit ((void (*)(void)) func);
162
0
  errsv = errno;
163
0
  if (result)
164
0
    {
165
0
      g_error ("Could not register atexit() function: %s",
166
0
               g_strerror (errsv));
167
0
    }
168
0
}
169
G_GNUC_END_IGNORE_DEPRECATIONS
170
171
/* Based on execvp() from GNU Libc.
172
 * Some of this code is cut-and-pasted into gspawn.c
173
 */
174
175
static gchar*
176
my_strchrnul (const gchar *str, 
177
        gchar        c)
178
0
{
179
0
  gchar *p = (gchar*)str;
180
0
  while (*p && (*p != c))
181
0
    ++p;
182
183
0
  return p;
184
0
}
185
186
#ifdef G_OS_WIN32
187
188
static gchar *inner_find_program_in_path (const gchar *program);
189
190
gchar*
191
g_find_program_in_path (const gchar *program)
192
{
193
  const gchar *last_dot = strrchr (program, '.');
194
195
  if (last_dot == NULL ||
196
      strchr (last_dot, '\\') != NULL ||
197
      strchr (last_dot, '/') != NULL)
198
    {
199
      const size_t program_length = strlen (program);
200
      gchar *pathext = g_build_path (";",
201
             ".exe;.cmd;.bat;.com",
202
             g_getenv ("PATHEXT"),
203
             NULL);
204
      gchar *p;
205
      gchar *decorated_program;
206
      gchar *retval;
207
208
      p = pathext;
209
      do
210
  {
211
    gchar *q = my_strchrnul (p, ';');
212
213
    decorated_program = g_malloc (program_length + (q-p) + 1);
214
    memcpy (decorated_program, program, program_length);
215
    memcpy (decorated_program+program_length, p, q-p);
216
    decorated_program [program_length + (q-p)] = '\0';
217
    
218
    retval = inner_find_program_in_path (decorated_program);
219
    g_free (decorated_program);
220
221
    if (retval != NULL)
222
      {
223
        g_free (pathext);
224
        return retval;
225
      }
226
    p = q;
227
  } while (*p++ != '\0');
228
      g_free (pathext);
229
      return NULL;
230
    }
231
  else
232
    return inner_find_program_in_path (program);
233
}
234
235
#endif
236
237
/**
238
 * g_find_program_in_path:
239
 * @program: (type filename): a program name in the GLib file name encoding
240
 * 
241
 * Locates the first executable named @program in the user's path, in the
242
 * same way that execvp() would locate it. Returns an allocated string
243
 * with the absolute path name, or %NULL if the program is not found in
244
 * the path. If @program is already an absolute path, returns a copy of
245
 * @program if @program exists and is executable, and %NULL otherwise.
246
 *  
247
 * On Windows, if @program does not have a file type suffix, tries
248
 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
249
 * the `PATHEXT` environment variable. 
250
 * 
251
 * On Windows, it looks for the file in the same way as CreateProcess() 
252
 * would. This means first in the directory where the executing
253
 * program was loaded from, then in the current directory, then in the
254
 * Windows 32-bit system directory, then in the Windows directory, and
255
 * finally in the directories in the `PATH` environment variable. If
256
 * the program is found, the return value contains the full name
257
 * including the type suffix.
258
 *
259
 * Returns: (type filename) (transfer full) (nullable): a newly-allocated
260
 *   string with the absolute path, or %NULL
261
 **/
262
#ifdef G_OS_WIN32
263
static gchar *
264
inner_find_program_in_path (const gchar *program)
265
#else
266
gchar*
267
g_find_program_in_path (const gchar *program)
268
#endif
269
0
{
270
0
  return g_find_program_for_path (program, NULL, NULL);
271
0
}
272
273
/**
274
 * g_find_program_for_path:
275
 * @program: (type filename): a program name in the GLib file name encoding
276
 * @path: (type filename) (nullable): the current dir where to search program
277
 * @working_dir: (type filename) (nullable): the working dir where to search
278
 *   program
279
 *
280
 * Locates the first executable named @program in @path, in the
281
 * same way that execvp() would locate it. Returns an allocated string
282
 * with the absolute path name (taking in account the @working_dir), or
283
 * %NULL if the program is not found in @path. If @program is already an
284
 * absolute path, returns a copy of @program if @program exists and is
285
 * executable, and %NULL otherwise.
286
 *
287
 * On Windows, if @path is %NULL, it looks for the file in the same way as
288
 * CreateProcess()  would. This means first in the directory where the
289
 * executing program was loaded from, then in the current directory, then in
290
 * the Windows 32-bit system directory, then in the Windows directory, and
291
 * finally in the directories in the `PATH` environment variable. If
292
 * the program is found, the return value contains the full name
293
 * including the type suffix.
294
 *
295
 * Returns: (type filename) (transfer full) (nullable): a newly-allocated
296
 *   string with the absolute path, or %NULL
297
 * Since: 2.76
298
 **/
299
char *
300
g_find_program_for_path (const char *program,
301
                         const char *path,
302
                         const char *working_dir)
303
0
{
304
0
  const char *original_path = path;
305
0
  const char *original_program = program;
306
0
  char *program_path = NULL;
307
0
  const gchar *p;
308
0
  gchar *name, *freeme;
309
#ifdef G_OS_WIN32
310
  const gchar *path_copy;
311
  gchar *filename = NULL, *appdir = NULL;
312
  gchar *sysdir = NULL, *windir = NULL;
313
  int n;
314
  wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
315
    wwindir[MAXPATHLEN];
316
#endif
317
0
  gsize len;
318
0
  gsize pathlen;
319
320
0
  g_return_val_if_fail (program != NULL, NULL);
321
322
  /* Use the working dir as program path if provided */
323
0
  if (working_dir && !g_path_is_absolute (program))
324
0
    {
325
0
      program_path = g_build_filename (working_dir, program, NULL);
326
0
      program = program_path;
327
0
    }
328
329
  /* If it is an absolute path, or a relative path including subdirectories,
330
   * don't look in PATH.
331
   */
332
0
  if (g_path_is_absolute (program)
333
0
      || strchr (original_program, G_DIR_SEPARATOR) != NULL
334
#ifdef G_OS_WIN32
335
      || strchr (original_program, '/') != NULL
336
#endif
337
0
      )
338
0
    {
339
0
      if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
340
0
    !g_file_test (program, G_FILE_TEST_IS_DIR))
341
0
        {
342
0
          gchar *out = NULL;
343
344
0
          if (g_path_is_absolute (program))
345
0
            {
346
0
              out = g_strdup (program);
347
0
            }
348
0
          else
349
0
            {
350
0
              char *cwd = g_get_current_dir ();
351
0
              out = g_build_filename (cwd, program, NULL);
352
0
              g_free (cwd);
353
0
            }
354
355
0
          g_free (program_path);
356
357
0
          return g_steal_pointer (&out);
358
0
        }
359
0
      else
360
0
        {
361
0
          g_clear_pointer (&program_path, g_free);
362
363
0
          if (g_path_is_absolute (original_program))
364
0
            return NULL;
365
0
        }
366
0
    }
367
368
0
  program = original_program;
369
370
0
  if G_LIKELY (original_path == NULL)
371
0
    path = g_getenv ("PATH");
372
0
  else
373
0
    path = original_path;
374
375
0
#if defined(G_OS_UNIX)
376
0
  if (path == NULL)
377
0
    {
378
      /* There is no 'PATH' in the environment.  The default
379
       * search path in GNU libc is the current directory followed by
380
       * the path 'confstr' returns for '_CS_PATH'.
381
       */
382
      
383
      /* In GLib we put . last, for security, and don't use the
384
       * unportable confstr(); UNIX98 does not actually specify
385
       * what to search if PATH is unset. POSIX may, dunno.
386
       */
387
      
388
0
      path = "/bin:/usr/bin:.";
389
0
    }
390
#else
391
  if G_LIKELY (original_path == NULL)
392
    {
393
      n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
394
      if (n > 0 && n < MAXPATHLEN)
395
        filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
396
397
      n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
398
      if (n > 0 && n < MAXPATHLEN)
399
        sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
400
401
      n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
402
      if (n > 0 && n < MAXPATHLEN)
403
        windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
404
405
      if (filename)
406
        {
407
          appdir = g_path_get_dirname (filename);
408
          g_free (filename);
409
        }
410
411
      path = g_strdup (path);
412
413
      if (windir)
414
        {
415
          const gchar *tem = path;
416
          path = g_strconcat (windir, ";", path, NULL);
417
          g_free ((gchar *) tem);
418
          g_free (windir);
419
        }
420
421
      if (sysdir)
422
        {
423
          const gchar *tem = path;
424
          path = g_strconcat (sysdir, ";", path, NULL);
425
          g_free ((gchar *) tem);
426
          g_free (sysdir);
427
        }
428
429
      {
430
        const gchar *tem = path;
431
        path = g_strconcat (".;", path, NULL);
432
        g_free ((gchar *) tem);
433
      }
434
435
      if (appdir)
436
        {
437
          const gchar *tem = path;
438
          path = g_strconcat (appdir, ";", path, NULL);
439
          g_free ((gchar *) tem);
440
          g_free (appdir);
441
        }
442
443
      path_copy = path;
444
    }
445
  else
446
    {
447
      path_copy = g_strdup (path);
448
    }
449
450
#endif
451
  
452
0
  len = strlen (program) + 1;
453
0
  pathlen = strlen (path);
454
0
  freeme = name = g_malloc (pathlen + len + 1);
455
  
456
  /* Copy the file name at the top, including '\0'  */
457
0
  memcpy (name + pathlen + 1, program, len);
458
0
  name = name + pathlen;
459
  /* And add the slash before the filename  */
460
0
  *name = G_DIR_SEPARATOR;
461
  
462
0
  p = path;
463
0
  do
464
0
    {
465
0
      char *startp;
466
0
      char *startp_path = NULL;
467
468
0
      path = p;
469
0
      p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
470
471
0
      if (p == path)
472
        /* Two adjacent colons, or a colon at the beginning or the end
473
         * of 'PATH' means to search the current directory.
474
         */
475
0
        startp = name + 1;
476
0
      else
477
0
        startp = memcpy (name - (p - path), path, p - path);
478
479
      /* Use the working dir as program path if provided */
480
0
      if (working_dir && !g_path_is_absolute (startp))
481
0
        {
482
0
          startp_path = g_build_filename (working_dir, startp, NULL);
483
0
          startp = startp_path;
484
0
        }
485
486
0
      if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
487
0
    !g_file_test (startp, G_FILE_TEST_IS_DIR))
488
0
        {
489
0
          gchar *ret;
490
0
          if (g_path_is_absolute (startp)) {
491
0
            ret = g_strdup (startp);
492
0
          } else {
493
0
            gchar *cwd = NULL;
494
0
            cwd = g_get_current_dir ();
495
0
            ret = g_build_filename (cwd, startp, NULL);
496
0
            g_free (cwd);
497
0
          }
498
499
0
          g_free (program_path);
500
0
          g_free (startp_path);
501
0
          g_free (freeme);
502
#ifdef G_OS_WIN32
503
    g_free ((gchar *) path_copy);
504
#endif
505
0
          return ret;
506
0
        }
507
508
0
      g_free (startp_path);
509
0
    }
510
0
  while (*p++ != '\0');
511
512
0
  g_free (program_path);
513
0
  g_free (freeme);
514
#ifdef G_OS_WIN32
515
  g_free ((gchar *) path_copy);
516
#endif
517
518
0
  return NULL;
519
0
}
520
521
/* The functions below are defined this way for compatibility reasons.
522
 * See the note in gutils.h.
523
 */
524
525
/**
526
 * g_bit_nth_lsf:
527
 * @mask: a #gulong containing flags
528
 * @nth_bit: the index of the bit to start the search from
529
 *
530
 * Find the position of the first bit set in @mask, searching
531
 * from (but not including) @nth_bit upwards. Bits are numbered
532
 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
533
 * usually). To start searching from the 0th bit, set @nth_bit to -1.
534
 *
535
 * Returns: the index of the first bit set which is higher than @nth_bit, or -1
536
 *    if no higher bits are set
537
 */
538
gint
539
(g_bit_nth_lsf) (gulong mask,
540
                 gint   nth_bit)
541
0
{
542
0
  return g_bit_nth_lsf_impl (mask, nth_bit);
543
0
}
544
545
/**
546
 * g_bit_nth_msf:
547
 * @mask: a #gulong containing flags
548
 * @nth_bit: the index of the bit to start the search from
549
 *
550
 * Find the position of the first bit set in @mask, searching
551
 * from (but not including) @nth_bit downwards. Bits are numbered
552
 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
553
 * usually). To start searching from the last bit, set @nth_bit to
554
 * -1 or GLIB_SIZEOF_LONG * 8.
555
 *
556
 * Returns: the index of the first bit set which is lower than @nth_bit, or -1
557
 *    if no lower bits are set
558
 */
559
gint
560
(g_bit_nth_msf) (gulong mask,
561
                 gint   nth_bit)
562
0
{
563
0
  return g_bit_nth_msf_impl (mask, nth_bit);
564
0
}
565
566
567
/**
568
 * g_bit_storage:
569
 * @number: a #guint
570
 *
571
 * Gets the number of bits used to hold @number,
572
 * e.g. if @number is 4, 3 bits are needed.
573
 *
574
 * Returns: the number of bits used to hold @number
575
 */
576
guint
577
(g_bit_storage) (gulong number)
578
0
{
579
0
  return g_bit_storage_impl (number);
580
0
}
581
582
G_LOCK_DEFINE_STATIC (g_utils_global);
583
584
typedef struct
585
{
586
  gchar *user_name;
587
  gchar *real_name;
588
  gchar *home_dir;
589
} UserDatabaseEntry;
590
591
/* These must all be read/written with @g_utils_global held. */
592
static  gchar   *g_user_data_dir = NULL;
593
static  gchar  **g_system_data_dirs = NULL;
594
static  gchar   *g_user_cache_dir = NULL;
595
static  gchar   *g_user_config_dir = NULL;
596
static  gchar   *g_user_state_dir = NULL;
597
static  gchar   *g_user_runtime_dir = NULL;
598
static  gchar  **g_system_config_dirs = NULL;
599
static  gchar  **g_user_special_dirs = NULL;
600
static  gchar   *g_tmp_dir = NULL;
601
602
/* fifteen minutes of fame for everybody */
603
#define G_USER_DIRS_EXPIRE      15 * 60
604
605
#ifdef G_OS_WIN32
606
607
static gchar *
608
get_special_folder (REFKNOWNFOLDERID known_folder_guid_ptr)
609
{
610
  wchar_t *wcp = NULL;
611
  gchar *result = NULL;
612
  HRESULT hr;
613
614
  hr = SHGetKnownFolderPath (known_folder_guid_ptr, 0, NULL, &wcp);
615
616
  if (SUCCEEDED (hr))
617
    result = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
618
619
  CoTaskMemFree (wcp);
620
621
  return result;
622
}
623
624
static char *
625
get_windows_directory_root (void)
626
{
627
  wchar_t wwindowsdir[MAX_PATH];
628
629
  if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
630
    {
631
      /* Usually X:\Windows, but in terminal server environments
632
       * might be an UNC path, AFAIK.
633
       */
634
      char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
635
      char *p;
636
637
      if (windowsdir == NULL)
638
  return g_strdup ("C:\\");
639
640
      p = (char *) g_path_skip_root (windowsdir);
641
      if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
642
  p--;
643
      *p = '\0';
644
      return windowsdir;
645
    }
646
  else
647
    return g_strdup ("C:\\");
648
}
649
650
#endif
651
652
/* HOLDS: g_utils_global_lock */
653
static UserDatabaseEntry *
654
g_get_user_database_entry (void)
655
0
{
656
0
  static UserDatabaseEntry *entry;
657
658
0
  if (g_once_init_enter_pointer (&entry))
659
0
    {
660
0
      static UserDatabaseEntry e;
661
662
0
#ifdef G_OS_UNIX
663
0
      {
664
0
        struct passwd *pw = NULL;
665
0
        gpointer buffer = NULL;
666
0
        gint error;
667
0
        const char *logname;
668
669
0
#  if defined (HAVE_GETPWUID_R)
670
0
        struct passwd pwd;
671
0
#    ifdef _SC_GETPW_R_SIZE_MAX
672
        /* This returns the maximum length */
673
0
        glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
674
675
0
        if (bufsize < 0)
676
0
          bufsize = 64;
677
#    else /* _SC_GETPW_R_SIZE_MAX */
678
        glong bufsize = 64;
679
#    endif /* _SC_GETPW_R_SIZE_MAX */
680
681
0
        logname = g_getenv ("LOGNAME");
682
683
0
        do
684
0
          {
685
0
            g_free (buffer);
686
            /* we allocate 6 extra bytes to work around a bug in
687
             * Mac OS < 10.3. See #156446
688
             */
689
0
            buffer = g_malloc (bufsize + 6);
690
0
            errno = 0;
691
692
0
            if (logname) {
693
0
              error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
694
0
              if (!pw || (pw->pw_uid != getuid ())) {
695
                /* LOGNAME is lying, fall back to looking up the uid */
696
0
                error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
697
0
              }
698
0
            } else {
699
0
              error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
700
0
            }
701
0
            error = error < 0 ? errno : error;
702
703
0
            if (!pw)
704
0
              {
705
                /* we bail out prematurely if the user id can't be found
706
                 * (should be pretty rare case actually), or if the buffer
707
                 * should be sufficiently big and lookups are still not
708
                 * successful.
709
                 */
710
0
                if (error == 0 || error == ENOENT)
711
0
                  {
712
0
                    g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
713
0
                               (gulong) getuid ());
714
0
                    break;
715
0
                  }
716
0
                if (bufsize > 32 * 1024)
717
0
                  {
718
0
                    g_warning ("getpwuid_r(): failed due to: %s.",
719
0
                               g_strerror (error));
720
0
                    break;
721
0
                  }
722
723
0
                bufsize *= 2;
724
0
              }
725
0
          }
726
0
        while (!pw);
727
0
#  endif /* HAVE_GETPWUID_R */
728
729
0
        if (!pw)
730
0
          {
731
0
            pw = getpwuid (getuid ());
732
0
          }
733
0
        if (pw)
734
0
          {
735
0
            e.user_name = g_strdup (pw->pw_name);
736
737
0
#ifndef __BIONIC__
738
0
            if (pw->pw_gecos && *pw->pw_gecos != '\0' && pw->pw_name)
739
0
              {
740
0
                gchar **gecos_fields;
741
0
                gchar **name_parts;
742
0
                gchar *uppercase_pw_name;
743
744
                /* split the gecos field and substitute '&' */
745
0
                gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
746
0
                name_parts = g_strsplit (gecos_fields[0], "&", 0);
747
0
                uppercase_pw_name = g_strdup (pw->pw_name);
748
0
                uppercase_pw_name[0] = g_ascii_toupper (uppercase_pw_name[0]);
749
0
                e.real_name = g_strjoinv (uppercase_pw_name, name_parts);
750
0
                g_strfreev (gecos_fields);
751
0
                g_strfreev (name_parts);
752
0
                g_free (uppercase_pw_name);
753
0
              }
754
0
#endif
755
756
0
            if (!e.home_dir)
757
0
              e.home_dir = g_strdup (pw->pw_dir);
758
0
          }
759
0
        g_free (buffer);
760
0
      }
761
762
0
#endif /* G_OS_UNIX */
763
764
#ifdef G_OS_WIN32
765
      {
766
        guint len = UNLEN+1;
767
        wchar_t buffer[UNLEN+1];
768
769
        if (GetUserNameW (buffer, (LPDWORD) &len))
770
          {
771
            e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
772
            e.real_name = g_strdup (e.user_name);
773
          }
774
      }
775
#endif /* G_OS_WIN32 */
776
777
0
      if (!e.user_name)
778
0
        e.user_name = g_strdup ("somebody");
779
0
      if (!e.real_name)
780
0
        e.real_name = g_strdup ("Unknown");
781
782
0
      g_once_init_leave_pointer (&entry, &e);
783
0
    }
784
785
0
  return entry;
786
0
}
787
788
/**
789
 * g_get_user_name:
790
 *
791
 * Gets the user name of the current user. The encoding of the returned
792
 * string is system-defined. On UNIX, it might be the preferred file name
793
 * encoding, or something else, and there is no guarantee that it is even
794
 * consistent on a machine. On Windows, it is always UTF-8.
795
 *
796
 * Returns: (type filename) (transfer none): the user name of the current user.
797
 */
798
const gchar *
799
g_get_user_name (void)
800
0
{
801
0
  UserDatabaseEntry *entry;
802
803
0
  entry = g_get_user_database_entry ();
804
805
0
  return entry->user_name;
806
0
}
807
808
/**
809
 * g_get_real_name:
810
 *
811
 * Gets the real name of the user. This usually comes from the user's
812
 * entry in the `passwd` file. The encoding of the returned string is
813
 * system-defined. (On Windows, it is, however, always UTF-8.) If the
814
 * real user name cannot be determined, the string "Unknown" is 
815
 * returned.
816
 *
817
 * Returns: (type filename) (transfer none): the user's real name.
818
 */
819
const gchar *
820
g_get_real_name (void)
821
0
{
822
0
  UserDatabaseEntry *entry;
823
824
0
  entry = g_get_user_database_entry ();
825
826
0
  return entry->real_name;
827
0
}
828
829
/* Protected by @g_utils_global_lock. */
830
static gchar *g_home_dir = NULL;  /* (owned) (nullable before initialised) */
831
832
static gchar *
833
g_build_home_dir (void)
834
0
{
835
0
  gchar *home_dir;
836
837
  /* We first check HOME and use it if it is set */
838
0
  home_dir = g_strdup (g_getenv ("HOME"));
839
840
#ifdef G_OS_WIN32
841
  /* Only believe HOME if it is an absolute path and exists.
842
   *
843
   * We only do this check on Windows for a couple of reasons.
844
   * Historically, we only did it there because we used to ignore $HOME
845
   * on UNIX.  There are concerns about enabling it now on UNIX because
846
   * of things like autofs.  In short, if the user has a bogus value in
847
   * $HOME then they get what they pay for...
848
   */
849
  if (home_dir != NULL)
850
    {
851
      if (!(g_path_is_absolute (home_dir) &&
852
            g_file_test (home_dir, G_FILE_TEST_IS_DIR)))
853
        g_clear_pointer (&home_dir, g_free);
854
    }
855
856
  /* In case HOME is Unix-style (it happens), convert it to
857
   * Windows style.
858
   */
859
  if (home_dir != NULL)
860
    {
861
      gchar *p;
862
      while ((p = strchr (home_dir, '/')) != NULL)
863
        *p = '\\';
864
    }
865
866
  if (home_dir == NULL)
867
    {
868
      /* USERPROFILE is probably the closest equivalent to $HOME? */
869
      if (g_getenv ("USERPROFILE") != NULL)
870
        home_dir = g_strdup (g_getenv ("USERPROFILE"));
871
    }
872
873
  if (home_dir == NULL)
874
    home_dir = get_special_folder (&FOLDERID_Profile);
875
876
  if (home_dir == NULL)
877
    home_dir = get_windows_directory_root ();
878
#endif /* G_OS_WIN32 */
879
880
0
  if (home_dir == NULL)
881
0
    {
882
      /* If we didn't get it from any of those methods, we will have
883
       * to read the user database entry.
884
       */
885
0
      UserDatabaseEntry *entry = g_get_user_database_entry ();
886
0
      home_dir = g_strdup (entry->home_dir);
887
0
    }
888
889
  /* If we have been denied access to /etc/passwd (for example, by an
890
   * overly-zealous LSM), make up a junk value. The return value at this
891
   * point is explicitly documented as ‘undefined’. */
892
0
  if (home_dir == NULL)
893
0
    {
894
0
      g_warning ("Could not find home directory: $HOME is not set, and "
895
0
                 "user database could not be read.");
896
0
      home_dir = g_strdup ("/");
897
0
    }
898
899
0
  return g_steal_pointer (&home_dir);
900
0
}
901
902
/**
903
 * g_get_home_dir:
904
 *
905
 * Gets the current user's home directory.
906
 *
907
 * As with most UNIX tools, this function will return the value of the
908
 * `HOME` environment variable if it is set to an existing absolute path
909
 * name, falling back to the `passwd` file in the case that it is unset.
910
 *
911
 * If the path given in `HOME` is non-absolute, does not exist, or is
912
 * not a directory, the result is undefined.
913
 *
914
 * Before version 2.36 this function would ignore the `HOME` environment
915
 * variable, taking the value from the `passwd` database instead. This was
916
 * changed to increase the compatibility of GLib with other programs (and
917
 * the XDG basedir specification) and to increase testability of programs
918
 * based on GLib (by making it easier to run them from test frameworks).
919
 *
920
 * If your program has a strong requirement for either the new or the
921
 * old behaviour (and if you don't wish to increase your GLib
922
 * dependency to ensure that the new behaviour is in effect) then you
923
 * should either directly check the `HOME` environment variable yourself
924
 * or unset it before calling any functions in GLib.
925
 *
926
 * Returns: (type filename) (transfer none): the current user's home directory
927
 */
928
const gchar *
929
g_get_home_dir (void)
930
0
{
931
0
  const gchar *home_dir;
932
933
0
  G_LOCK (g_utils_global);
934
935
0
  if (g_home_dir == NULL)
936
0
    g_home_dir = g_build_home_dir ();
937
0
  home_dir = g_home_dir;
938
939
0
  G_UNLOCK (g_utils_global);
940
941
0
  return home_dir;
942
0
}
943
944
void
945
_g_unset_cached_tmp_dir (void)
946
0
{
947
0
  G_LOCK (g_utils_global);
948
  /* We have to leak the old value, as user code could be retaining pointers
949
   * to it. */
950
0
  g_ignore_leak (g_tmp_dir);
951
0
  g_tmp_dir = NULL;
952
0
  G_UNLOCK (g_utils_global);
953
0
}
954
955
/**
956
 * g_get_tmp_dir:
957
 *
958
 * Gets the directory to use for temporary files.
959
 *
960
 * On UNIX, this is taken from the `TMPDIR` environment variable.
961
 * If the variable is not set, `P_tmpdir` is
962
 * used, as defined by the system C library. Failing that, a
963
 * hard-coded default of "/tmp" is returned.
964
 *
965
 * On Windows, the `TEMP` environment variable is used, with the
966
 * root directory of the Windows installation (eg: "C:\") used
967
 * as a default.
968
 *
969
 * The encoding of the returned string is system-defined. On Windows,
970
 * it is always UTF-8. The return value is never %NULL or the empty
971
 * string.
972
 *
973
 * Returns: (type filename) (transfer none): the directory to use for temporary files.
974
 */
975
const gchar *
976
g_get_tmp_dir (void)
977
0
{
978
0
  G_LOCK (g_utils_global);
979
980
0
  if (g_tmp_dir == NULL)
981
0
    {
982
0
      gchar *tmp;
983
984
0
      tmp = g_strdup (g_getenv ("G_TEST_TMPDIR"));
985
986
0
      if (tmp == NULL || *tmp == '\0')
987
0
        {
988
0
          g_free (tmp);
989
0
          tmp = g_strdup (g_getenv (
990
#ifdef G_OS_WIN32
991
            "TEMP"
992
#else /* G_OS_WIN32 */
993
0
            "TMPDIR"
994
0
#endif /* G_OS_WIN32 */
995
0
          ));
996
0
        }
997
998
#ifdef G_OS_WIN32
999
      if (tmp == NULL || *tmp == '\0')
1000
        {
1001
          g_free (tmp);
1002
          tmp = get_windows_directory_root ();
1003
        }
1004
#else /* G_OS_WIN32 */
1005
1006
0
#ifdef P_tmpdir
1007
0
      if (tmp == NULL || *tmp == '\0')
1008
0
        {
1009
0
          gsize k;
1010
0
          g_free (tmp);
1011
0
          tmp = g_strdup (P_tmpdir);
1012
0
          k = strlen (tmp);
1013
0
          if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
1014
0
            tmp[k - 1] = '\0';
1015
0
        }
1016
0
#endif /* P_tmpdir */
1017
1018
0
      if (tmp == NULL || *tmp == '\0')
1019
0
        {
1020
0
          g_free (tmp);
1021
0
          tmp = g_strdup ("/tmp");
1022
0
        }
1023
0
#endif /* !G_OS_WIN32 */
1024
1025
0
      g_tmp_dir = g_steal_pointer (&tmp);
1026
0
    }
1027
1028
0
  G_UNLOCK (g_utils_global);
1029
1030
0
  return g_tmp_dir;
1031
0
}
1032
1033
/**
1034
 * g_get_host_name:
1035
 *
1036
 * Return a name for the machine. 
1037
 *
1038
 * The returned name is not necessarily a fully-qualified domain name,
1039
 * or even present in DNS or some other name service at all. It need
1040
 * not even be unique on your local network or site, but usually it
1041
 * is. Callers should not rely on the return value having any specific
1042
 * properties like uniqueness for security purposes. Even if the name
1043
 * of the machine is changed while an application is running, the
1044
 * return value from this function does not change. The returned
1045
 * string is owned by GLib and should not be modified or freed. If no
1046
 * name can be determined, a default fixed string "localhost" is
1047
 * returned.
1048
 *
1049
 * The encoding of the returned string is UTF-8.
1050
 *
1051
 * Returns: (transfer none): the host name of the machine.
1052
 *
1053
 * Since: 2.8
1054
 */
1055
const gchar *
1056
g_get_host_name (void)
1057
0
{
1058
0
  static gchar *hostname;
1059
1060
0
  if (g_once_init_enter_pointer (&hostname))
1061
0
    {
1062
0
      gboolean failed;
1063
0
      gchar *utmp = NULL;
1064
1065
0
#ifndef G_OS_WIN32
1066
0
      gsize size;
1067
      /* The number 256 * 256 is taken from the value of _POSIX_HOST_NAME_MAX,
1068
       * which is 255. Since we use _POSIX_HOST_NAME_MAX + 1 (= 256) in the
1069
       * fallback case, we pick 256 * 256 as the size of the larger buffer here.
1070
       * It should be large enough. It doesn't looks reasonable to name a host
1071
       * with a string that is longer than 64 KiB.
1072
       */
1073
0
      const gsize size_large = (gsize) 256 * 256;
1074
0
      gchar *tmp;
1075
1076
0
#ifdef _SC_HOST_NAME_MAX
1077
0
      {
1078
0
        glong max;
1079
1080
0
        max = sysconf (_SC_HOST_NAME_MAX);
1081
0
        if (max > 0 && (gsize) max <= G_MAXSIZE - 1)
1082
0
          size = (gsize) max + 1;
1083
0
        else
1084
0
#ifdef HOST_NAME_MAX
1085
0
          size = HOST_NAME_MAX + 1;
1086
#else
1087
          size = _POSIX_HOST_NAME_MAX + 1;
1088
#endif /* HOST_NAME_MAX */
1089
0
      }
1090
#else
1091
      /* Fallback to some reasonable value */
1092
      size = 256;
1093
#endif /* _SC_HOST_NAME_MAX */
1094
0
      tmp = g_malloc (size);
1095
0
      failed = (gethostname (tmp, size) == -1);
1096
0
      if (failed && size < size_large)
1097
0
        {
1098
          /* Try again with a larger buffer if 'size' may be too small. */
1099
0
          g_free (tmp);
1100
0
          tmp = g_malloc (size_large);
1101
0
          failed = (gethostname (tmp, size_large) == -1);
1102
0
        }
1103
1104
0
      if (failed)
1105
0
        g_clear_pointer (&tmp, g_free);
1106
0
      utmp = tmp;
1107
#else
1108
      wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
1109
      DWORD size = sizeof (tmp) / sizeof (tmp[0]);
1110
      failed = (!GetComputerNameW (tmp, &size));
1111
      if (!failed)
1112
        utmp = g_utf16_to_utf8 (tmp, size, NULL, NULL, NULL);
1113
      if (utmp == NULL)
1114
        failed = TRUE;
1115
#endif
1116
1117
0
      g_once_init_leave_pointer (&hostname, failed ? g_strdup ("localhost") : utmp);
1118
0
    }
1119
1120
0
  return hostname;
1121
0
}
1122
1123
static const gchar *g_prgname = NULL; /* always a quark */
1124
1125
/**
1126
 * g_get_prgname:
1127
 *
1128
 * Gets the name of the program. This name should not be localized,
1129
 * in contrast to g_get_application_name().
1130
 *
1131
 * If you are using #GApplication the program name is set in
1132
 * g_application_run(). In case of GDK or GTK it is set in
1133
 * gdk_init(), which is called by gtk_init() and the
1134
 * #GtkApplication::startup handler. The program name is found by
1135
 * taking the last component of @argv[0].
1136
 *
1137
 * Returns: (nullable) (transfer none): the name of the program,
1138
 *   or %NULL if it has not been set yet. The returned string belongs
1139
 *   to GLib and must not be modified or freed.
1140
 */
1141
const gchar*
1142
g_get_prgname (void)
1143
190M
{
1144
190M
  return g_atomic_pointer_get (&g_prgname);
1145
190M
}
1146
1147
/**
1148
 * g_set_prgname:
1149
 * @prgname: the name of the program.
1150
 *
1151
 * Sets the name of the program. This name should not be localized,
1152
 * in contrast to g_set_application_name().
1153
 *
1154
 * If you are using #GApplication the program name is set in
1155
 * g_application_run(). In case of GDK or GTK it is set in
1156
 * gdk_init(), which is called by gtk_init() and the
1157
 * #GtkApplication::startup handler. By default, the program name is
1158
 * found by taking the last component of @argv[0].
1159
 *
1160
 * Since GLib 2.72, this function can be called multiple times
1161
 * and is fully thread safe. Prior to GLib 2.72, this function
1162
 * could only be called once per process.
1163
 *
1164
 * See the [GTK documentation](https://docs.gtk.org/gtk4/migrating-3to4.html#set-a-proper-application-id)
1165
 * for requirements on integrating g_set_prgname() with GTK applications.
1166
 */
1167
void
1168
g_set_prgname (const gchar *prgname)
1169
0
{
1170
0
  prgname = g_intern_string (prgname);
1171
0
  g_atomic_pointer_set (&g_prgname, prgname);
1172
0
}
1173
1174
/**
1175
 * g_set_prgname_once:
1176
 * @prgname: the name of the program.
1177
 *
1178
 * If g_get_prgname() is not set, this is the same as setting
1179
 * the name via g_set_prgname() and %TRUE is returned. Otherwise,
1180
 * does nothing and returns %FALSE. This is thread-safe.
1181
 *
1182
 * Returns: whether g_prgname was initialized by the call.
1183
 */
1184
gboolean
1185
g_set_prgname_once (const gchar *prgname)
1186
0
{
1187
  /* if @prgname is NULL, then this has the same effect as calling
1188
   * (g_get_prgname()==NULL). */
1189
0
  prgname = g_intern_string (prgname);
1190
0
  return g_atomic_pointer_compare_and_exchange (&g_prgname, NULL, prgname);
1191
0
}
1192
1193
static gchar *g_application_name = NULL;
1194
1195
/**
1196
 * g_get_application_name:
1197
 * 
1198
 * Gets a human-readable name for the application, as set by
1199
 * g_set_application_name(). This name should be localized if
1200
 * possible, and is intended for display to the user.  Contrast with
1201
 * g_get_prgname(), which gets a non-localized name. If
1202
 * g_set_application_name() has not been called, returns the result of
1203
 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1204
 * been called).
1205
 * 
1206
 * Returns: (transfer none) (nullable): human-readable application
1207
 *   name. May return %NULL
1208
 *
1209
 * Since: 2.2
1210
 **/
1211
const gchar *
1212
g_get_application_name (void)
1213
0
{
1214
0
  const char *retval;
1215
1216
0
  retval = g_atomic_pointer_get (&g_application_name);
1217
1218
0
  if (retval)
1219
0
    return retval;
1220
1221
0
  return g_get_prgname ();
1222
0
}
1223
1224
/**
1225
 * g_set_application_name:
1226
 * @application_name: localized name of the application
1227
 *
1228
 * Sets a human-readable name for the application. This name should be
1229
 * localized if possible, and is intended for display to the user.
1230
 * Contrast with g_set_prgname(), which sets a non-localized name.
1231
 * g_set_prgname() will be called automatically by gtk_init(),
1232
 * but g_set_application_name() will not.
1233
 *
1234
 * Note that for thread safety reasons, this function can only
1235
 * be called once.
1236
 *
1237
 * The application name will be used in contexts such as error messages,
1238
 * or when displaying an application's name in the task list.
1239
 * 
1240
 * Since: 2.2
1241
 **/
1242
void
1243
g_set_application_name (const gchar *application_name)
1244
0
{
1245
0
  char *name;
1246
1247
0
  g_return_if_fail (application_name);
1248
1249
0
  name = g_strdup (application_name);
1250
1251
0
  if (!g_atomic_pointer_compare_and_exchange (&g_application_name, NULL, name))
1252
0
    {
1253
0
      g_warning ("g_set_application_name() called multiple times");
1254
0
      g_free (name);
1255
0
    }
1256
0
}
1257
1258
#ifdef G_OS_WIN32
1259
/* For the past versions we can just
1260
 * hardcode all the names.
1261
 */
1262
static const struct winver
1263
{
1264
  gint major;
1265
  gint minor;
1266
  gint sp;
1267
  const char *version;
1268
  const char *spversion;
1269
} versions[] =
1270
{
1271
  {6, 2, 0, "8", ""},
1272
  {6, 1, 1, "7", " SP1"},
1273
  {6, 1, 0, "7", ""},
1274
  {6, 0, 2, "Vista", " SP2"},
1275
  {6, 0, 1, "Vista", " SP1"},
1276
  {6, 0, 0, "Vista", ""},
1277
  {5, 1, 3, "XP", " SP3"},
1278
  {5, 1, 2, "XP", " SP2"},
1279
  {5, 1, 1, "XP", " SP1"},
1280
  {5, 1, 0, "XP", ""},
1281
  {0, 0, 0, NULL, NULL},
1282
};
1283
1284
static gchar *
1285
get_registry_str (HKEY root_key, const wchar_t *path, const wchar_t *value_name)
1286
{
1287
  HKEY key_handle;
1288
  DWORD req_value_data_size;
1289
  DWORD req_value_data_size2;
1290
  LONG status;
1291
  DWORD value_type_w;
1292
  DWORD value_type_w2;
1293
  char *req_value_data;
1294
  gchar *result;
1295
1296
  status = RegOpenKeyExW (root_key, path, 0, KEY_READ, &key_handle);
1297
  if (status != ERROR_SUCCESS)
1298
    return NULL;
1299
1300
  req_value_data_size = 0;
1301
  status = RegQueryValueExW (key_handle,
1302
                             value_name,
1303
                             NULL,
1304
                             &value_type_w,
1305
                             NULL,
1306
                             &req_value_data_size);
1307
1308
  if (status != ERROR_MORE_DATA && status != ERROR_SUCCESS)
1309
    {
1310
      RegCloseKey (key_handle);
1311
1312
      return NULL;
1313
    }
1314
1315
  req_value_data = g_malloc (req_value_data_size);
1316
  req_value_data_size2 = req_value_data_size;
1317
1318
  status = RegQueryValueExW (key_handle,
1319
                             value_name,
1320
                             NULL,
1321
                             &value_type_w2,
1322
                             (gpointer) req_value_data,
1323
                             &req_value_data_size2);
1324
1325
  result = NULL;
1326
1327
  if (status == ERROR_SUCCESS && value_type_w2 == REG_SZ)
1328
    result = g_utf16_to_utf8 ((gunichar2 *) req_value_data,
1329
                              req_value_data_size / sizeof (gunichar2),
1330
                              NULL,
1331
                              NULL,
1332
                              NULL);
1333
1334
  g_free (req_value_data);
1335
  RegCloseKey (key_handle);
1336
1337
  return result;
1338
}
1339
1340
/* Windows 8.1 can be either plain or with Update 1,
1341
 * depending on its build number (9200 or 9600).
1342
 */
1343
static gchar *
1344
get_windows_8_1_update (void)
1345
{
1346
  gchar *current_build;
1347
  gchar *result = NULL;
1348
1349
  current_build = get_registry_str (HKEY_LOCAL_MACHINE,
1350
                                    L"SOFTWARE"
1351
                                    L"\\Microsoft"
1352
                                    L"\\Windows NT"
1353
                                    L"\\CurrentVersion",
1354
                                    L"CurrentBuild");
1355
1356
  if (current_build != NULL)
1357
    {
1358
      wchar_t *end;
1359
      long build = wcstol ((const wchar_t *) current_build, &end, 10);
1360
1361
      if (build <= INT_MAX &&
1362
          build >= INT_MIN &&
1363
          errno == 0 &&
1364
          *end == L'\0')
1365
        {
1366
          if (build >= 9600)
1367
            result = g_strdup ("Update 1");
1368
        }
1369
    }
1370
1371
  g_clear_pointer (&current_build, g_free);
1372
1373
  return result;
1374
}
1375
1376
static gchar *
1377
get_windows_version (gboolean with_windows)
1378
{
1379
  GString *version = g_string_new (NULL);
1380
  gboolean is_win_server = FALSE;
1381
1382
  if (g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_ANY))
1383
    {
1384
      gchar *win10_release;
1385
      gboolean is_win11 = FALSE;
1386
      OSVERSIONINFOEXW osinfo;
1387
1388
      /* Are we on Windows 2016/2019/2022 Server? */
1389
      is_win_server = g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_SERVER);
1390
1391
      /*
1392
       * This always succeeds if we get here, since the
1393
       * g_win32_check_windows_version() already did this!
1394
       * We want the OSVERSIONINFOEXW here for more even
1395
       * fine-grained versioning items
1396
       */
1397
      _g_win32_call_rtl_version (&osinfo);
1398
1399
      if (!is_win_server)
1400
        {
1401
          /*
1402
           * Windows 11 is actually Windows 10.0.22000+,
1403
           * so look at the build number
1404
           */
1405
          is_win11 = (osinfo.dwBuildNumber >= 22000);
1406
        }
1407
      else
1408
        {
1409
          /*
1410
           * Windows 2022 Server is actually Windows 10.0.20348+,
1411
           * Windows 2019 Server is actually Windows 10.0.17763+,
1412
           * Windows 2016 Server is actually Windows 10.0.14393+,
1413
           * so look at the build number
1414
           */
1415
          g_string_append (version, "Server");
1416
          if (osinfo.dwBuildNumber >= 20348)
1417
            g_string_append (version, " 2022");
1418
          else if (osinfo.dwBuildNumber >= 17763)
1419
            g_string_append (version, " 2019");
1420
          else
1421
            g_string_append (version, " 2016");
1422
        }
1423
1424
      if (is_win11)
1425
        g_string_append (version, "11");
1426
      else if (!is_win_server)
1427
        g_string_append (version, "10");
1428
1429
      /* Windows 10/Server 2016+ is identified by its ReleaseId or
1430
       * DisplayVersion (since 20H2), such as
1431
       * 1511, 1607, 1703, 1709, 1803, 1809 or 1903 etc.
1432
       * The first version of Windows 10 has no release number.
1433
       */
1434
      win10_release = get_registry_str (HKEY_LOCAL_MACHINE,
1435
                                        L"SOFTWARE"
1436
                                        L"\\Microsoft"
1437
                                        L"\\Windows NT"
1438
                                        L"\\CurrentVersion",
1439
                                        L"ReleaseId");
1440
1441
      if (win10_release != NULL)
1442
        {
1443
          if (g_strcmp0 (win10_release, "2009") != 0)
1444
            g_string_append_printf (version, " %s", win10_release);
1445
          else
1446
            {
1447
              g_free (win10_release);
1448
1449
              win10_release = get_registry_str (HKEY_LOCAL_MACHINE,
1450
                                                L"SOFTWARE"
1451
                                                L"\\Microsoft"
1452
                                                L"\\Windows NT"
1453
                                                L"\\CurrentVersion",
1454
                                                L"DisplayVersion");
1455
1456
              if (win10_release != NULL)
1457
                g_string_append_printf (version, " %s", win10_release);
1458
              else
1459
                g_string_append_printf (version, " 2009");
1460
            }
1461
        }
1462
1463
      g_free (win10_release);
1464
    }
1465
  else if (g_win32_check_windows_version (6, 3, 0, G_WIN32_OS_ANY))
1466
    {
1467
      gchar *win81_update;
1468
1469
      if (g_win32_check_windows_version (6, 3, 0, G_WIN32_OS_WORKSTATION))
1470
        g_string_append (version, "8.1");
1471
      else
1472
        g_string_append (version, "Server 2012 R2");
1473
1474
      win81_update = get_windows_8_1_update ();
1475
1476
      if (win81_update != NULL)
1477
        g_string_append_printf (version, " %s", win81_update);
1478
1479
      g_free (win81_update);
1480
    }
1481
  else
1482
    {
1483
      gint i;
1484
1485
      for (i = 0; versions[i].major > 0; i++)
1486
        {
1487
          if (!g_win32_check_windows_version (versions[i].major, versions[i].minor, versions[i].sp, G_WIN32_OS_ANY))
1488
            continue;
1489
1490
          g_string_append (version, versions[i].version);
1491
1492
          if (g_win32_check_windows_version (versions[i].major, versions[i].minor, versions[i].sp, G_WIN32_OS_SERVER))
1493
            {
1494
              /*
1495
               * This condition should now always hold, since Windows
1496
               * 7+/Server 2008 R2+ is now required
1497
               */
1498
              if (versions[i].major == 6)
1499
                {
1500
                  g_string_append (version, "Server");
1501
                  if (versions[i].minor == 2)
1502
                    g_string_append (version, " 2012");
1503
                  else if (versions[i].minor == 1)
1504
                    g_string_append (version, " 2008 R2");
1505
                  else
1506
                    g_string_append (version, " 2008");
1507
                }
1508
            }
1509
1510
          g_string_append (version, versions[i].spversion);
1511
1512
          break;
1513
        }
1514
    }
1515
1516
  if (version->len == 0)
1517
    {
1518
      g_string_free (version, TRUE);
1519
1520
      return NULL;
1521
    }
1522
1523
  if (with_windows)
1524
    g_string_prepend (version, "Windows ");
1525
1526
  return g_string_free (version, FALSE);
1527
}
1528
#endif
1529
1530
#if defined (G_OS_UNIX) && !defined (__APPLE__)
1531
static gchar *
1532
get_os_info_from_os_release (const gchar *key_name,
1533
                             const gchar *buffer)
1534
0
{
1535
0
  GStrv lines;
1536
0
  gchar *prefix;
1537
0
  size_t i;
1538
0
  gchar *result = NULL;
1539
1540
0
  lines = g_strsplit (buffer, "\n", -1);
1541
0
  prefix = g_strdup_printf ("%s=", key_name);
1542
0
  for (i = 0; lines[i] != NULL; i++)
1543
0
    {
1544
0
      const gchar *line = lines[i];
1545
0
      const gchar *value;
1546
1547
0
      if (g_str_has_prefix (line, prefix))
1548
0
        {
1549
0
          value = line + strlen (prefix);
1550
0
          result = g_shell_unquote (value, NULL);
1551
0
          if (result == NULL)
1552
0
            result = g_strdup (value);
1553
0
          break;
1554
0
        }
1555
0
    }
1556
0
  g_strfreev (lines);
1557
0
  g_free (prefix);
1558
1559
0
#ifdef __linux__
1560
  /* Default values in spec */
1561
0
  if (result == NULL)
1562
0
    {
1563
0
      if (g_str_equal (key_name, G_OS_INFO_KEY_NAME))
1564
0
        return g_strdup ("Linux");
1565
0
      if (g_str_equal (key_name, G_OS_INFO_KEY_ID))
1566
0
        return g_strdup ("linux");
1567
0
      if (g_str_equal (key_name, G_OS_INFO_KEY_PRETTY_NAME))
1568
0
        return g_strdup ("Linux");
1569
0
    }
1570
0
#endif
1571
1572
0
  return g_steal_pointer (&result);
1573
0
}
1574
1575
static gchar *
1576
get_os_info_from_uname (const gchar *key_name)
1577
0
{
1578
0
  struct utsname info;
1579
1580
0
  if (uname (&info) == -1)
1581
0
    return NULL;
1582
1583
0
  if (strcmp (key_name, G_OS_INFO_KEY_NAME) == 0)
1584
0
    return g_strdup (info.sysname);
1585
0
  else if (strcmp (key_name, G_OS_INFO_KEY_VERSION) == 0)
1586
0
    return g_strdup (info.release);
1587
0
  else if (strcmp (key_name, G_OS_INFO_KEY_PRETTY_NAME) == 0)
1588
0
    return g_strdup_printf ("%s %s", info.sysname, info.release);
1589
0
  else if (strcmp (key_name, G_OS_INFO_KEY_ID) == 0)
1590
0
    {
1591
0
      gchar *result = g_ascii_strdown (info.sysname, -1);
1592
1593
0
      g_strcanon (result, "abcdefghijklmnopqrstuvwxyz0123456789_-.", '_');
1594
0
      return g_steal_pointer (&result);
1595
0
    }
1596
0
  else if (strcmp (key_name, G_OS_INFO_KEY_VERSION_ID) == 0)
1597
0
    {
1598
      /* We attempt to convert the version string to the format returned by
1599
       * config.guess, which is the script used to generate target triplets
1600
       * in GNU autotools. There are a lot of rules in the script. We only
1601
       * implement a few rules which are easy to understand here.
1602
       *
1603
       * config.guess can be found at https://savannah.gnu.org/projects/config.
1604
       */
1605
0
      gchar *result;
1606
1607
0
      if (strcmp (info.sysname, "NetBSD") == 0)
1608
0
        {
1609
          /* sed -e 's,[-_].*,,' */
1610
0
          gssize len = G_MAXSSIZE;
1611
0
          const gchar *c;
1612
1613
0
          if ((c = strchr (info.release, '-')) != NULL)
1614
0
            len = MIN (len, c - info.release);
1615
0
          if ((c = strchr (info.release, '_')) != NULL)
1616
0
            len = MIN (len, c - info.release);
1617
0
          if (len == G_MAXSSIZE)
1618
0
            len = -1;
1619
1620
0
          result = g_ascii_strdown (info.release, len);
1621
0
        }
1622
0
      else if (strcmp (info.sysname, "GNU") == 0)
1623
0
        {
1624
          /* sed -e 's,/.*$,,' */
1625
0
          gssize len = -1;
1626
0
          const gchar *c = strchr (info.release, '/');
1627
1628
0
          if (c != NULL)
1629
0
            len = c - info.release;
1630
1631
0
          result = g_ascii_strdown (info.release, len);
1632
0
        }
1633
0
      else if (g_str_has_prefix (info.sysname, "GNU/") ||
1634
0
               strcmp (info.sysname, "FreeBSD") == 0 ||
1635
0
               strcmp (info.sysname, "DragonFly") == 0)
1636
0
        {
1637
          /* sed -e 's,[-(].*,,' */
1638
0
          gssize len = G_MAXSSIZE;
1639
0
          const gchar *c;
1640
1641
0
          if ((c = strchr (info.release, '-')) != NULL)
1642
0
            len = MIN (len, c - info.release);
1643
0
          if ((c = strchr (info.release, '(')) != NULL)
1644
0
            len = MIN (len, c - info.release);
1645
0
          if (len == G_MAXSSIZE)
1646
0
            len = -1;
1647
1648
0
          result = g_ascii_strdown (info.release, len);
1649
0
        }
1650
0
      else
1651
0
        result = g_ascii_strdown (info.release, -1);
1652
1653
0
      g_strcanon (result, "abcdefghijklmnopqrstuvwxyz0123456789_-.", '_');
1654
0
      return g_steal_pointer (&result);
1655
0
    }
1656
0
  else
1657
0
    return NULL;
1658
0
}
1659
#endif  /* defined (G_OS_UNIX) && !defined (__APPLE__) */
1660
1661
/**
1662
 * g_get_os_info:
1663
 * @key_name: a key for the OS info being requested, for example %G_OS_INFO_KEY_NAME.
1664
 *
1665
 * Get information about the operating system.
1666
 *
1667
 * On Linux this comes from the `/etc/os-release` file. On other systems, it may
1668
 * come from a variety of sources. You can either use the standard key names
1669
 * like %G_OS_INFO_KEY_NAME or pass any UTF-8 string key name. For example,
1670
 * `/etc/os-release` provides a number of other less commonly used values that may
1671
 * be useful. No key is guaranteed to be provided, so the caller should always
1672
 * check if the result is %NULL.
1673
 *
1674
 * Returns: (nullable): The associated value for the requested key or %NULL if
1675
 *   this information is not provided.
1676
 *
1677
 * Since: 2.64
1678
 **/
1679
gchar *
1680
g_get_os_info (const gchar *key_name)
1681
0
{
1682
#if defined (__APPLE__)
1683
  if (g_strcmp0 (key_name, G_OS_INFO_KEY_NAME) == 0)
1684
    return g_strdup ("macOS");
1685
  else
1686
    return NULL;
1687
#elif defined (G_OS_UNIX)
1688
  const gchar * const os_release_files[] = { "/etc/os-release", "/usr/lib/os-release" };
1689
0
  gsize i;
1690
0
  gchar *buffer = NULL;
1691
0
  gchar *result = NULL;
1692
1693
0
  g_return_val_if_fail (key_name != NULL, NULL);
1694
1695
0
  for (i = 0; i < G_N_ELEMENTS (os_release_files); i++)
1696
0
    {
1697
0
      GError *error = NULL;
1698
0
      gboolean file_missing;
1699
1700
0
      if (g_file_get_contents (os_release_files[i], &buffer, NULL, &error))
1701
0
        break;
1702
1703
0
      file_missing = g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT);
1704
0
      g_clear_error (&error);
1705
1706
0
      if (!file_missing)
1707
0
        return NULL;
1708
0
    }
1709
1710
0
  if (buffer != NULL)
1711
0
    result = get_os_info_from_os_release (key_name, buffer);
1712
0
  else
1713
0
    result = get_os_info_from_uname (key_name);
1714
1715
0
  g_free (buffer);
1716
0
  return g_steal_pointer (&result);
1717
#elif defined (G_OS_WIN32)
1718
  if (g_strcmp0 (key_name, G_OS_INFO_KEY_NAME) == 0)
1719
    return g_strdup ("Windows");
1720
  else if (g_strcmp0 (key_name, G_OS_INFO_KEY_ID) == 0)
1721
    return g_strdup ("windows");
1722
  else if (g_strcmp0 (key_name, G_OS_INFO_KEY_PRETTY_NAME) == 0)
1723
    /* Windows XP SP2 or Windows 10 1903 or Windows 7 Server SP1 */
1724
    return get_windows_version (TRUE);
1725
  else if (g_strcmp0 (key_name, G_OS_INFO_KEY_VERSION) == 0)
1726
    /* XP SP2 or 10 1903 or 7 Server SP1 */
1727
    return get_windows_version (FALSE);
1728
  else if (g_strcmp0 (key_name, G_OS_INFO_KEY_VERSION_ID) == 0)
1729
    {
1730
      /* xp_sp2 or 10_1903 or 7_server_sp1 */
1731
      gchar *result;
1732
      gchar *version = get_windows_version (FALSE);
1733
1734
      if (version == NULL)
1735
        return NULL;
1736
1737
      result = g_ascii_strdown (version, -1);
1738
      g_free (version);
1739
1740
      return g_strcanon (result, "abcdefghijklmnopqrstuvwxyz0123456789_-.", '_');
1741
    }
1742
  else if (g_strcmp0 (key_name, G_OS_INFO_KEY_HOME_URL) == 0)
1743
    return g_strdup ("https://microsoft.com/windows/");
1744
  else if (g_strcmp0 (key_name, G_OS_INFO_KEY_DOCUMENTATION_URL) == 0)
1745
    return g_strdup ("https://docs.microsoft.com/");
1746
  else if (g_strcmp0 (key_name, G_OS_INFO_KEY_SUPPORT_URL) == 0)
1747
    return g_strdup ("https://support.microsoft.com/");
1748
  else if (g_strcmp0 (key_name, G_OS_INFO_KEY_BUG_REPORT_URL) == 0)
1749
    return g_strdup ("https://support.microsoft.com/contactus/");
1750
  else if (g_strcmp0 (key_name, G_OS_INFO_KEY_PRIVACY_POLICY_URL) == 0)
1751
    return g_strdup ("https://privacy.microsoft.com/");
1752
  else
1753
    return NULL;
1754
#endif
1755
0
}
1756
1757
/* Set @global_str to a copy of @new_value if it’s currently unset or has a
1758
 * different value. If its current value matches @new_value, do nothing. If
1759
 * replaced, we have to leak the old value as client code could still have
1760
 * pointers to it. */
1761
static void
1762
set_str_if_different (gchar       **global_str,
1763
                      const gchar  *type,
1764
                      const gchar  *new_value)
1765
0
{
1766
0
  if (*global_str == NULL ||
1767
0
      !g_str_equal (new_value, *global_str))
1768
0
    {
1769
0
      g_debug ("g_set_user_dirs: Setting %s to %s", type, new_value);
1770
1771
      /* We have to leak the old value, as user code could be retaining pointers
1772
       * to it. */
1773
0
      g_ignore_leak (*global_str);
1774
0
      *global_str = g_strdup (new_value);
1775
0
    }
1776
0
}
1777
1778
static void
1779
set_strv_if_different (gchar                ***global_strv,
1780
                       const gchar            *type,
1781
                       const gchar  * const   *new_value)
1782
0
{
1783
0
  if (*global_strv == NULL ||
1784
0
      !g_strv_equal (new_value, (const gchar * const *) *global_strv))
1785
0
    {
1786
0
      gchar *new_value_str = g_strjoinv (":", (gchar **) new_value);
1787
0
      g_debug ("g_set_user_dirs: Setting %s to %s", type, new_value_str);
1788
0
      g_free (new_value_str);
1789
1790
      /* We have to leak the old value, as user code could be retaining pointers
1791
       * to it. */
1792
0
      g_ignore_strv_leak (*global_strv);
1793
0
      *global_strv = g_strdupv ((gchar **) new_value);
1794
0
    }
1795
0
}
1796
1797
/*
1798
 * g_set_user_dirs:
1799
 * @first_dir_type: Type of the first directory to set
1800
 * @...: Value to set the first directory to, followed by additional type/value
1801
 *    pairs, followed by %NULL
1802
 *
1803
 * Set one or more ‘user’ directories to custom values. This is intended to be
1804
 * used by test code (particularly with the %G_TEST_OPTION_ISOLATE_DIRS option)
1805
 * to override the values returned by the following functions, so that test
1806
 * code can be run without touching an installed system and user data:
1807
 *
1808
 *  - g_get_home_dir() — use type `HOME`, pass a string
1809
 *  - g_get_user_cache_dir() — use type `XDG_CACHE_HOME`, pass a string
1810
 *  - g_get_system_config_dirs() — use type `XDG_CONFIG_DIRS`, pass a
1811
 *    %NULL-terminated string array
1812
 *  - g_get_user_config_dir() — use type `XDG_CONFIG_HOME`, pass a string
1813
 *  - g_get_system_data_dirs() — use type `XDG_DATA_DIRS`, pass a
1814
 *    %NULL-terminated string array
1815
 *  - g_get_user_data_dir() — use type `XDG_DATA_HOME`, pass a string
1816
 *  - g_get_user_runtime_dir() — use type `XDG_RUNTIME_DIR`, pass a string
1817
 *
1818
 * The list must be terminated with a %NULL type. All of the values must be
1819
 * non-%NULL — passing %NULL as a value won’t reset a directory. If a reference
1820
 * to a directory from the calling environment needs to be kept, copy it before
1821
 * the first call to g_set_user_dirs(). g_set_user_dirs() can be called multiple
1822
 * times.
1823
 *
1824
 * Since: 2.60
1825
 */
1826
/*< private > */
1827
void
1828
g_set_user_dirs (const gchar *first_dir_type,
1829
                 ...)
1830
0
{
1831
0
  va_list args;
1832
0
  const gchar *dir_type;
1833
1834
0
  G_LOCK (g_utils_global);
1835
1836
0
  va_start (args, first_dir_type);
1837
1838
0
  for (dir_type = first_dir_type; dir_type != NULL; dir_type = va_arg (args, const gchar *))
1839
0
    {
1840
0
      gconstpointer dir_value = va_arg (args, gconstpointer);
1841
0
      g_assert (dir_value != NULL);
1842
1843
0
      if (g_str_equal (dir_type, "HOME"))
1844
0
        set_str_if_different (&g_home_dir, dir_type, dir_value);
1845
0
      else if (g_str_equal (dir_type, "XDG_CACHE_HOME"))
1846
0
        set_str_if_different (&g_user_cache_dir, dir_type, dir_value);
1847
0
      else if (g_str_equal (dir_type, "XDG_CONFIG_DIRS"))
1848
0
        set_strv_if_different (&g_system_config_dirs, dir_type, dir_value);
1849
0
      else if (g_str_equal (dir_type, "XDG_CONFIG_HOME"))
1850
0
        set_str_if_different (&g_user_config_dir, dir_type, dir_value);
1851
0
      else if (g_str_equal (dir_type, "XDG_DATA_DIRS"))
1852
0
        set_strv_if_different (&g_system_data_dirs, dir_type, dir_value);
1853
0
      else if (g_str_equal (dir_type, "XDG_DATA_HOME"))
1854
0
        set_str_if_different (&g_user_data_dir, dir_type, dir_value);
1855
0
      else if (g_str_equal (dir_type, "XDG_STATE_HOME"))
1856
0
        set_str_if_different (&g_user_state_dir, dir_type, dir_value);
1857
0
      else if (g_str_equal (dir_type, "XDG_RUNTIME_DIR"))
1858
0
        set_str_if_different (&g_user_runtime_dir, dir_type, dir_value);
1859
0
      else
1860
0
        g_assert_not_reached ();
1861
0
    }
1862
1863
0
  va_end (args);
1864
1865
0
  G_UNLOCK (g_utils_global);
1866
0
}
1867
1868
static gchar *
1869
g_build_user_data_dir (void)
1870
0
{
1871
0
  gchar *data_dir = NULL;
1872
0
  const gchar *data_dir_env = g_getenv ("XDG_DATA_HOME");
1873
1874
0
  if (data_dir_env && data_dir_env[0])
1875
0
    data_dir = g_strdup (data_dir_env);
1876
#ifdef G_OS_WIN32
1877
  else
1878
    data_dir = get_special_folder (&FOLDERID_LocalAppData);
1879
#endif
1880
0
  if (!data_dir || !data_dir[0])
1881
0
    {
1882
0
      gchar *home_dir = g_build_home_dir ();
1883
0
      g_free (data_dir);
1884
0
      data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1885
0
      g_free (home_dir);
1886
0
    }
1887
1888
0
  return g_steal_pointer (&data_dir);
1889
0
}
1890
1891
/**
1892
 * g_get_user_data_dir:
1893
 * 
1894
 * Returns a base directory in which to access application data such
1895
 * as icons that is customized for a particular user.  
1896
 *
1897
 * On UNIX platforms this is determined using the mechanisms described
1898
 * in the
1899
 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1900
 * In this case the directory retrieved will be `XDG_DATA_HOME`.
1901
 *
1902
 * On Windows it follows XDG Base Directory Specification if `XDG_DATA_HOME`
1903
 * is defined. If `XDG_DATA_HOME` is undefined, the folder to use for local (as
1904
 * opposed to roaming) application data is used instead. See the
1905
 * [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
1906
 * Note that in this case on Windows it will be the same
1907
 * as what g_get_user_config_dir() returns.
1908
 *
1909
 * The return value is cached and modifying it at runtime is not supported, as
1910
 * it’s not thread-safe to modify environment variables at runtime.
1911
 *
1912
 * Returns: (type filename) (transfer none): a string owned by GLib that must
1913
 *   not be modified or freed.
1914
 *
1915
 * Since: 2.6
1916
 **/
1917
const gchar *
1918
g_get_user_data_dir (void)
1919
0
{
1920
0
  const gchar *user_data_dir;
1921
1922
0
  G_LOCK (g_utils_global);
1923
1924
0
  if (g_user_data_dir == NULL)
1925
0
    g_user_data_dir = g_build_user_data_dir ();
1926
0
  user_data_dir = g_user_data_dir;
1927
1928
0
  G_UNLOCK (g_utils_global);
1929
1930
0
  return user_data_dir;
1931
0
}
1932
1933
static gchar *
1934
g_build_user_config_dir (void)
1935
0
{
1936
0
  gchar *config_dir = NULL;
1937
0
  const gchar *config_dir_env = g_getenv ("XDG_CONFIG_HOME");
1938
1939
0
  if (config_dir_env && config_dir_env[0])
1940
0
    config_dir = g_strdup (config_dir_env);
1941
#ifdef G_OS_WIN32
1942
  else
1943
    config_dir = get_special_folder (&FOLDERID_LocalAppData);
1944
#endif
1945
0
  if (!config_dir || !config_dir[0])
1946
0
    {
1947
0
      gchar *home_dir = g_build_home_dir ();
1948
0
      g_free (config_dir);
1949
0
      config_dir = g_build_filename (home_dir, ".config", NULL);
1950
0
      g_free (home_dir);
1951
0
    }
1952
1953
0
  return g_steal_pointer (&config_dir);
1954
0
}
1955
1956
/**
1957
 * g_get_user_config_dir:
1958
 * 
1959
 * Returns a base directory in which to store user-specific application 
1960
 * configuration information such as user preferences and settings. 
1961
 *
1962
 * On UNIX platforms this is determined using the mechanisms described
1963
 * in the
1964
 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1965
 * In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1966
 *
1967
 * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_HOME` is defined.
1968
 * If `XDG_CONFIG_HOME` is undefined, the folder to use for local (as opposed
1969
 * to roaming) application data is used instead. See the
1970
 * [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
1971
 * Note that in this case on Windows it will be  the same
1972
 * as what g_get_user_data_dir() returns.
1973
 *
1974
 * The return value is cached and modifying it at runtime is not supported, as
1975
 * it’s not thread-safe to modify environment variables at runtime.
1976
 *
1977
 * Returns: (type filename) (transfer none): a string owned by GLib that
1978
 *   must not be modified or freed.
1979
 * Since: 2.6
1980
 **/
1981
const gchar *
1982
g_get_user_config_dir (void)
1983
0
{
1984
0
  const gchar *user_config_dir;
1985
1986
0
  G_LOCK (g_utils_global);
1987
1988
0
  if (g_user_config_dir == NULL)
1989
0
    g_user_config_dir = g_build_user_config_dir ();
1990
0
  user_config_dir = g_user_config_dir;
1991
1992
0
  G_UNLOCK (g_utils_global);
1993
1994
0
  return user_config_dir;
1995
0
}
1996
1997
static gchar *
1998
g_build_user_cache_dir (void)
1999
0
{
2000
0
  gchar *cache_dir = NULL;
2001
0
  const gchar *cache_dir_env = g_getenv ("XDG_CACHE_HOME");
2002
2003
0
  if (cache_dir_env && cache_dir_env[0])
2004
0
    cache_dir = g_strdup (cache_dir_env);
2005
#ifdef G_OS_WIN32
2006
  else
2007
    cache_dir = get_special_folder (&FOLDERID_InternetCache);
2008
#endif
2009
0
  if (!cache_dir || !cache_dir[0])
2010
0
    {
2011
0
      gchar *home_dir = g_build_home_dir ();
2012
0
      g_free (cache_dir);
2013
0
      cache_dir = g_build_filename (home_dir, ".cache", NULL);
2014
0
      g_free (home_dir);
2015
0
    }
2016
2017
0
  return g_steal_pointer (&cache_dir);
2018
0
}
2019
2020
/**
2021
 * g_get_user_cache_dir:
2022
 * 
2023
 * Returns a base directory in which to store non-essential, cached
2024
 * data specific to particular user.
2025
 *
2026
 * On UNIX platforms this is determined using the mechanisms described
2027
 * in the
2028
 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2029
 * In this case the directory retrieved will be `XDG_CACHE_HOME`.
2030
 *
2031
 * On Windows it follows XDG Base Directory Specification if `XDG_CACHE_HOME` is defined.
2032
 * If `XDG_CACHE_HOME` is undefined, the directory that serves as a common
2033
 * repository for temporary Internet files is used instead. A typical path is
2034
 * `C:\Documents and Settings\username\Local Settings\Temporary Internet Files`.
2035
 * See the [documentation for `FOLDERID_InternetCache`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
2036
 *
2037
 * The return value is cached and modifying it at runtime is not supported, as
2038
 * it’s not thread-safe to modify environment variables at runtime.
2039
 *
2040
 * Returns: (type filename) (transfer none): a string owned by GLib that
2041
 *   must not be modified or freed.
2042
 * Since: 2.6
2043
 **/
2044
const gchar *
2045
g_get_user_cache_dir (void)
2046
0
{
2047
0
  const gchar *user_cache_dir;
2048
2049
0
  G_LOCK (g_utils_global);
2050
2051
0
  if (g_user_cache_dir == NULL)
2052
0
    g_user_cache_dir = g_build_user_cache_dir ();
2053
0
  user_cache_dir = g_user_cache_dir;
2054
2055
0
  G_UNLOCK (g_utils_global);
2056
2057
0
  return user_cache_dir;
2058
0
}
2059
2060
static gchar *
2061
g_build_user_state_dir (void)
2062
0
{
2063
0
  gchar *state_dir = NULL;
2064
0
  const gchar *state_dir_env = g_getenv ("XDG_STATE_HOME");
2065
2066
0
  if (state_dir_env && state_dir_env[0])
2067
0
    state_dir = g_strdup (state_dir_env);
2068
#ifdef G_OS_WIN32
2069
  else
2070
    state_dir = get_special_folder (&FOLDERID_LocalAppData);
2071
#endif
2072
0
  if (!state_dir || !state_dir[0])
2073
0
    {
2074
0
      gchar *home_dir = g_build_home_dir ();
2075
0
      g_free (state_dir);
2076
0
      state_dir = g_build_filename (home_dir, ".local/state", NULL);
2077
0
      g_free (home_dir);
2078
0
    }
2079
2080
0
  return g_steal_pointer (&state_dir);
2081
0
}
2082
2083
/**
2084
 * g_get_user_state_dir:
2085
 *
2086
 * Returns a base directory in which to store state files specific to
2087
 * particular user.
2088
 *
2089
 * On UNIX platforms this is determined using the mechanisms described
2090
 * in the
2091
 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2092
 * In this case the directory retrieved will be `XDG_STATE_HOME`.
2093
 *
2094
 * On Windows it follows XDG Base Directory Specification if `XDG_STATE_HOME` is defined.
2095
 * If `XDG_STATE_HOME` is undefined, the folder to use for local (as opposed
2096
 * to roaming) application data is used instead. See the
2097
 * [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
2098
 * Note that in this case on Windows it will be the same
2099
 * as what g_get_user_data_dir() returns.
2100
 *
2101
 * The return value is cached and modifying it at runtime is not supported, as
2102
 * it’s not thread-safe to modify environment variables at runtime.
2103
 *
2104
 * Returns: (type filename) (transfer none): a string owned by GLib that
2105
 *   must not be modified or freed.
2106
 *
2107
 * Since: 2.72
2108
 **/
2109
const gchar *
2110
g_get_user_state_dir (void)
2111
0
{
2112
0
  const gchar *user_state_dir;
2113
2114
0
  G_LOCK (g_utils_global);
2115
2116
0
  if (g_user_state_dir == NULL)
2117
0
    g_user_state_dir = g_build_user_state_dir ();
2118
0
  user_state_dir = g_user_state_dir;
2119
2120
0
  G_UNLOCK (g_utils_global);
2121
2122
0
  return user_state_dir;
2123
0
}
2124
2125
static gchar *
2126
g_build_user_runtime_dir (void)
2127
0
{
2128
0
  gchar *runtime_dir = NULL;
2129
0
  const gchar *runtime_dir_env = g_getenv ("XDG_RUNTIME_DIR");
2130
2131
0
  if (runtime_dir_env && runtime_dir_env[0])
2132
0
    {
2133
0
      runtime_dir = g_strdup (runtime_dir_env);
2134
2135
      /* If the XDG_RUNTIME_DIR environment variable is set, we are being told by
2136
       * the OS that this directory exists and is appropriately configured
2137
       * already.
2138
       */
2139
0
    }
2140
0
  else
2141
0
    {
2142
0
      runtime_dir = g_build_user_cache_dir ();
2143
2144
      /* Fallback case: the directory may not yet exist.
2145
       *
2146
       * The user should be able to rely on the directory existing
2147
       * when the function returns.  Probably it already does, but
2148
       * let's make sure.  Just do mkdir() directly since it will be
2149
       * no more expensive than a stat() in the case that the
2150
       * directory already exists and is a lot easier.
2151
       *
2152
       * $XDG_CACHE_HOME is probably ~/.cache/ so as long as $HOME
2153
       * exists this will work.  If the user changed $XDG_CACHE_HOME
2154
       * then they can make sure that it exists...
2155
       */
2156
0
      (void) g_mkdir (runtime_dir, 0700);
2157
0
    }
2158
2159
0
  return g_steal_pointer (&runtime_dir);
2160
0
}
2161
2162
/**
2163
 * g_get_user_runtime_dir:
2164
 *
2165
 * Returns a directory that is unique to the current user on the local
2166
 * system.
2167
 *
2168
 * This is determined using the mechanisms described
2169
 * in the 
2170
 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2171
 * This is the directory
2172
 * specified in the `XDG_RUNTIME_DIR` environment variable.
2173
 * In the case that this variable is not set, we return the value of
2174
 * g_get_user_cache_dir(), after verifying that it exists.
2175
 *
2176
 * The return value is cached and modifying it at runtime is not supported, as
2177
 * it’s not thread-safe to modify environment variables at runtime.
2178
 *
2179
 * Returns: (type filename): a string owned by GLib that must not be
2180
 *     modified or freed.
2181
 *
2182
 * Since: 2.28
2183
 **/
2184
const gchar *
2185
g_get_user_runtime_dir (void)
2186
0
{
2187
0
  const gchar *user_runtime_dir;
2188
2189
0
  G_LOCK (g_utils_global);
2190
2191
0
  if (g_user_runtime_dir == NULL)
2192
0
    g_user_runtime_dir = g_build_user_runtime_dir ();
2193
0
  user_runtime_dir = g_user_runtime_dir;
2194
2195
0
  G_UNLOCK (g_utils_global);
2196
2197
0
  return user_runtime_dir;
2198
0
}
2199
2200
#ifdef HAVE_COCOA
2201
2202
/* Implemented in gutils-macos.m */
2203
void load_user_special_dirs_macos (gchar **table);
2204
2205
static void
2206
load_user_special_dirs (void)
2207
{
2208
  load_user_special_dirs_macos (g_user_special_dirs);
2209
}
2210
2211
#elif defined(G_OS_WIN32)
2212
2213
static void
2214
load_user_special_dirs (void)
2215
{
2216
  g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (&FOLDERID_Desktop);
2217
  g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (&FOLDERID_Documents);
2218
2219
  g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (&FOLDERID_Downloads);
2220
  if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2221
    g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (&FOLDERID_Desktop);
2222
2223
  g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (&FOLDERID_Music);
2224
  g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (&FOLDERID_Pictures);
2225
2226
  g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (&FOLDERID_Public);
2227
  if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2228
    g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (&FOLDERID_PublicDocuments);
2229
2230
  g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (&FOLDERID_Templates);
2231
  g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (&FOLDERID_Videos);
2232
}
2233
2234
#else /* default is unix */
2235
2236
/* adapted from xdg-user-dir-lookup.c
2237
 *
2238
 * Copyright (C) 2007 Red Hat Inc.
2239
 *
2240
 * Permission is hereby granted, free of charge, to any person
2241
 * obtaining a copy of this software and associated documentation files
2242
 * (the "Software"), to deal in the Software without restriction,
2243
 * including without limitation the rights to use, copy, modify, merge,
2244
 * publish, distribute, sublicense, and/or sell copies of the Software,
2245
 * and to permit persons to whom the Software is furnished to do so,
2246
 * subject to the following conditions: 
2247
 *
2248
 * The above copyright notice and this permission notice shall be
2249
 * included in all copies or substantial portions of the Software. 
2250
 *
2251
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2252
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2253
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2254
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2255
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2256
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2257
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2258
 * SOFTWARE.
2259
 */
2260
static void
2261
load_user_special_dirs (void)
2262
0
{
2263
0
  gchar *config_dir = NULL;
2264
0
  gchar *config_file;
2265
0
  gchar *data;
2266
0
  gchar **lines;
2267
0
  gint n_lines, i;
2268
  
2269
0
  config_dir = g_build_user_config_dir ();
2270
0
  config_file = g_build_filename (config_dir,
2271
0
                                  "user-dirs.dirs",
2272
0
                                  NULL);
2273
0
  g_free (config_dir);
2274
2275
0
  if (!g_file_get_contents (config_file, &data, NULL, NULL))
2276
0
    {
2277
0
      g_free (config_file);
2278
0
      return;
2279
0
    }
2280
2281
0
  lines = g_strsplit (data, "\n", -1);
2282
0
  n_lines = g_strv_length (lines);
2283
0
  g_free (data);
2284
  
2285
0
  for (i = 0; i < n_lines; i++)
2286
0
    {
2287
0
      gchar *buffer = lines[i];
2288
0
      gchar *d, *p;
2289
0
      gint len;
2290
0
      gboolean is_relative = FALSE;
2291
0
      GUserDirectory directory;
2292
2293
      /* Remove newline at end */
2294
0
      len = strlen (buffer);
2295
0
      if (len > 0 && buffer[len - 1] == '\n')
2296
0
  buffer[len - 1] = 0;
2297
      
2298
0
      p = buffer;
2299
0
      while (*p == ' ' || *p == '\t')
2300
0
  p++;
2301
      
2302
0
      if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2303
0
        {
2304
0
          directory = G_USER_DIRECTORY_DESKTOP;
2305
0
          p += strlen ("XDG_DESKTOP_DIR");
2306
0
        }
2307
0
      else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2308
0
        {
2309
0
          directory = G_USER_DIRECTORY_DOCUMENTS;
2310
0
          p += strlen ("XDG_DOCUMENTS_DIR");
2311
0
        }
2312
0
      else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2313
0
        {
2314
0
          directory = G_USER_DIRECTORY_DOWNLOAD;
2315
0
          p += strlen ("XDG_DOWNLOAD_DIR");
2316
0
        }
2317
0
      else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2318
0
        {
2319
0
          directory = G_USER_DIRECTORY_MUSIC;
2320
0
          p += strlen ("XDG_MUSIC_DIR");
2321
0
        }
2322
0
      else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2323
0
        {
2324
0
          directory = G_USER_DIRECTORY_PICTURES;
2325
0
          p += strlen ("XDG_PICTURES_DIR");
2326
0
        }
2327
0
      else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2328
0
        {
2329
0
          directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2330
0
          p += strlen ("XDG_PUBLICSHARE_DIR");
2331
0
        }
2332
0
      else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2333
0
        {
2334
0
          directory = G_USER_DIRECTORY_TEMPLATES;
2335
0
          p += strlen ("XDG_TEMPLATES_DIR");
2336
0
        }
2337
0
      else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2338
0
        {
2339
0
          directory = G_USER_DIRECTORY_VIDEOS;
2340
0
          p += strlen ("XDG_VIDEOS_DIR");
2341
0
        }
2342
0
      else
2343
0
  continue;
2344
2345
0
      while (*p == ' ' || *p == '\t')
2346
0
  p++;
2347
2348
0
      if (*p != '=')
2349
0
  continue;
2350
0
      p++;
2351
2352
0
      while (*p == ' ' || *p == '\t')
2353
0
  p++;
2354
2355
0
      if (*p != '"')
2356
0
  continue;
2357
0
      p++;
2358
2359
0
      if (strncmp (p, "$HOME", 5) == 0)
2360
0
  {
2361
0
    p += 5;
2362
0
    is_relative = TRUE;
2363
0
  }
2364
0
      else if (*p != '/')
2365
0
  continue;
2366
2367
0
      d = strrchr (p, '"');
2368
0
      if (!d)
2369
0
        continue;
2370
0
      *d = 0;
2371
2372
0
      d = p;
2373
      
2374
      /* remove trailing slashes */
2375
0
      len = strlen (d);
2376
0
      if (d[len - 1] == '/')
2377
0
        d[len - 1] = 0;
2378
      
2379
0
      if (is_relative)
2380
0
        {
2381
0
          gchar *home_dir = g_build_home_dir ();
2382
0
          g_user_special_dirs[directory] = g_build_filename (home_dir, d, NULL);
2383
0
          g_free (home_dir);
2384
0
        }
2385
0
      else
2386
0
  g_user_special_dirs[directory] = g_strdup (d);
2387
0
    }
2388
2389
0
  g_strfreev (lines);
2390
0
  g_free (config_file);
2391
0
}
2392
2393
#endif /* platform-specific load_user_special_dirs implementations */
2394
2395
2396
/**
2397
 * g_reload_user_special_dirs_cache:
2398
 *
2399
 * Resets the cache used for g_get_user_special_dir(), so
2400
 * that the latest on-disk version is used. Call this only
2401
 * if you just changed the data on disk yourself.
2402
 *
2403
 * Due to thread safety issues this may cause leaking of strings
2404
 * that were previously returned from g_get_user_special_dir()
2405
 * that can't be freed. We ensure to only leak the data for
2406
 * the directories that actually changed value though.
2407
 *
2408
 * Since: 2.22
2409
 */
2410
void
2411
g_reload_user_special_dirs_cache (void)
2412
0
{
2413
0
  int i;
2414
2415
0
  G_LOCK (g_utils_global);
2416
2417
0
  if (g_user_special_dirs != NULL)
2418
0
    {
2419
      /* save a copy of the pointer, to check if some memory can be preserved */
2420
0
      char **old_g_user_special_dirs = g_user_special_dirs;
2421
0
      char *old_val;
2422
2423
      /* recreate and reload our cache */
2424
0
      g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2425
0
      load_user_special_dirs ();
2426
2427
      /* only leak changed directories */
2428
0
      for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2429
0
        {
2430
0
          old_val = old_g_user_special_dirs[i];
2431
0
          if (g_user_special_dirs[i] == NULL)
2432
0
            {
2433
0
              g_user_special_dirs[i] = old_val;
2434
0
            }
2435
0
          else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2436
0
            {
2437
              /* don't leak */
2438
0
              g_free (g_user_special_dirs[i]);
2439
0
              g_user_special_dirs[i] = old_val;
2440
0
            }
2441
0
          else
2442
0
            g_free (old_val);
2443
0
        }
2444
2445
      /* free the old array */
2446
0
      g_free (old_g_user_special_dirs);
2447
0
    }
2448
2449
0
  G_UNLOCK (g_utils_global);
2450
0
}
2451
2452
/**
2453
 * g_get_user_special_dir:
2454
 * @directory: the logical id of special directory
2455
 *
2456
 * Returns the full path of a special directory using its logical id.
2457
 *
2458
 * On UNIX this is done using the XDG special user directories.
2459
 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2460
 * falls back to `$HOME/Desktop` when XDG special user directories have
2461
 * not been set up. 
2462
 *
2463
 * Depending on the platform, the user might be able to change the path
2464
 * of the special directory without requiring the session to restart; GLib
2465
 * will not reflect any change once the special directories are loaded.
2466
 *
2467
 * Returns: (type filename) (nullable): the path to the specified special
2468
 *   directory, or %NULL if the logical id was not found. The returned string is
2469
 *   owned by GLib and should not be modified or freed.
2470
 *
2471
 * Since: 2.14
2472
 */
2473
const gchar *
2474
g_get_user_special_dir (GUserDirectory directory)
2475
0
{
2476
0
  const gchar *user_special_dir;
2477
2478
0
  g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2479
0
                        directory < G_USER_N_DIRECTORIES, NULL);
2480
2481
0
  G_LOCK (g_utils_global);
2482
2483
0
  if (G_UNLIKELY (g_user_special_dirs == NULL))
2484
0
    {
2485
0
      g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2486
2487
0
      load_user_special_dirs ();
2488
2489
      /* Special-case desktop for historical compatibility */
2490
0
      if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2491
0
        {
2492
0
          gchar *home_dir = g_build_home_dir ();
2493
0
          g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (home_dir, "Desktop", NULL);
2494
0
          g_free (home_dir);
2495
0
        }
2496
0
    }
2497
0
  user_special_dir = g_user_special_dirs[directory];
2498
2499
0
  G_UNLOCK (g_utils_global);
2500
2501
0
  return user_special_dir;
2502
0
}
2503
2504
#ifdef G_OS_WIN32
2505
2506
#undef g_get_system_data_dirs
2507
2508
static HMODULE
2509
get_module_for_address (gconstpointer address)
2510
{
2511
  /* Holds the g_utils_global lock */
2512
2513
  HMODULE hmodule = NULL;
2514
2515
  if (!address)
2516
    return NULL;
2517
2518
  if (!GetModuleHandleExW (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2519
         GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2520
         address, &hmodule))
2521
    {
2522
      MEMORY_BASIC_INFORMATION mbi;
2523
      VirtualQuery (address, &mbi, sizeof (mbi));
2524
      hmodule = (HMODULE) mbi.AllocationBase;
2525
    }
2526
2527
  return hmodule;
2528
}
2529
2530
static gchar *
2531
get_module_share_dir (gconstpointer address)
2532
{
2533
  HMODULE hmodule;
2534
  gchar *filename;
2535
  gchar *retval;
2536
2537
  hmodule = get_module_for_address (address);
2538
  if (hmodule == NULL)
2539
    return NULL;
2540
2541
  filename = g_win32_get_package_installation_directory_of_module (hmodule);
2542
  retval = g_build_filename (filename, "share", NULL);
2543
  g_free (filename);
2544
2545
  return retval;
2546
}
2547
2548
static const gchar * const *
2549
g_win32_get_system_data_dirs_for_module_real (void (*address_of_function)(void))
2550
{
2551
  GArray *data_dirs;
2552
  HMODULE hmodule;
2553
  static GHashTable *per_module_data_dirs = NULL;
2554
  gchar **retval;
2555
  gchar *p;
2556
  gchar *exe_root;
2557
2558
  hmodule = NULL;
2559
  if (address_of_function)
2560
    {
2561
      G_LOCK (g_utils_global);
2562
      hmodule = get_module_for_address (address_of_function);
2563
      if (hmodule != NULL)
2564
  {
2565
    if (per_module_data_dirs == NULL)
2566
      per_module_data_dirs = g_hash_table_new (NULL, NULL);
2567
    else
2568
      {
2569
        retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2570
        
2571
        if (retval != NULL)
2572
    {
2573
      G_UNLOCK (g_utils_global);
2574
      return (const gchar * const *) retval;
2575
    }
2576
      }
2577
  }
2578
    }
2579
2580
  data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2581
2582
  /* Documents and Settings\All Users\Application Data */
2583
  p = get_special_folder (&FOLDERID_ProgramData);
2584
  if (p)
2585
    g_array_append_val (data_dirs, p);
2586
2587
  /* Documents and Settings\All Users\Documents */
2588
  p = get_special_folder (&FOLDERID_PublicDocuments);
2589
  if (p)
2590
    g_array_append_val (data_dirs, p);
2591
2592
  /* Using the above subfolders of Documents and Settings perhaps
2593
   * makes sense from a Windows perspective.
2594
   *
2595
   * But looking at the actual use cases of this function in GTK
2596
   * and GNOME software, what we really want is the "share"
2597
   * subdirectory of the installation directory for the package
2598
   * our caller is a part of.
2599
   *
2600
   * The address_of_function parameter, if non-NULL, points to a
2601
   * function in the calling module. Use that to determine that
2602
   * module's installation folder, and use its "share" subfolder.
2603
   *
2604
   * Additionally, also use the "share" subfolder of the installation
2605
   * locations of GLib and the .exe file being run.
2606
   *
2607
   * To guard against none of the above being what is really wanted,
2608
   * callers of this function should have Win32-specific code to look
2609
   * up their installation folder themselves, and handle a subfolder
2610
   * "share" of it in the same way as the folders returned from this
2611
   * function.
2612
   */
2613
2614
  p = get_module_share_dir (address_of_function);
2615
  if (p)
2616
    g_array_append_val (data_dirs, p);
2617
    
2618
  if (glib_dll != NULL)
2619
    {
2620
      gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2621
      p = g_build_filename (glib_root, "share", NULL);
2622
      if (p)
2623
  g_array_append_val (data_dirs, p);
2624
      g_free (glib_root);
2625
    }
2626
  
2627
  exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2628
  p = g_build_filename (exe_root, "share", NULL);
2629
  if (p)
2630
    g_array_append_val (data_dirs, p);
2631
  g_free (exe_root);
2632
2633
  retval = (gchar **) g_array_free (data_dirs, FALSE);
2634
2635
  if (address_of_function)
2636
    {
2637
      if (hmodule != NULL)
2638
  g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2639
      G_UNLOCK (g_utils_global);
2640
    }
2641
2642
  return (const gchar * const *) retval;
2643
}
2644
2645
const gchar * const *
2646
g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
2647
{
2648
  gboolean should_call_g_get_system_data_dirs;
2649
2650
  should_call_g_get_system_data_dirs = TRUE;
2651
  /* These checks are the same as the ones that g_build_system_data_dirs() does.
2652
   * Please keep them in sync.
2653
   */
2654
  G_LOCK (g_utils_global);
2655
2656
  if (!g_system_data_dirs)
2657
    {
2658
      const gchar *data_dirs = g_getenv ("XDG_DATA_DIRS");
2659
2660
      if (!data_dirs || !data_dirs[0])
2661
        should_call_g_get_system_data_dirs = FALSE;
2662
    }
2663
2664
  G_UNLOCK (g_utils_global);
2665
2666
  /* There is a subtle difference between g_win32_get_system_data_dirs_for_module (NULL),
2667
   * which is what GLib code can normally call,
2668
   * and g_win32_get_system_data_dirs_for_module (&_g_win32_get_system_data_dirs),
2669
   * which is what the inline function used by non-GLib code calls.
2670
   * The former gets prefix relative to currently-running executable,
2671
   * the latter - relative to the module that calls _g_win32_get_system_data_dirs()
2672
   * (disguised as g_get_system_data_dirs()), which could be an executable or
2673
   * a DLL that is located somewhere else.
2674
   * This is why that inline function in gutils.h exists, and why we can't just
2675
   * call g_get_system_data_dirs() from there - because we need to get the address
2676
   * local to the non-GLib caller-module.
2677
   */
2678
2679
  /*
2680
   * g_get_system_data_dirs() will fall back to calling
2681
   * g_win32_get_system_data_dirs_for_module_real(NULL) if XDG_DATA_DIRS is NULL
2682
   * or an empty string. The checks above ensure that we do not call it in such
2683
   * cases and use the address_of_function that we've been given by the inline function.
2684
   * The reason we're calling g_get_system_data_dirs /at all/ is to give
2685
   * XDG_DATA_DIRS precedence (if it is set).
2686
   */
2687
  if (should_call_g_get_system_data_dirs)
2688
    return g_get_system_data_dirs ();
2689
2690
  return g_win32_get_system_data_dirs_for_module_real (address_of_function);
2691
}
2692
2693
#endif
2694
2695
static gchar **
2696
g_build_system_data_dirs (void)
2697
0
{
2698
0
  gchar **data_dir_vector = NULL;
2699
0
  gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2700
2701
  /* These checks are the same as the ones that g_win32_get_system_data_dirs_for_module()
2702
   * does. Please keep them in sync.
2703
   */
2704
0
#ifndef G_OS_WIN32
2705
0
  if (!data_dirs || !data_dirs[0])
2706
0
    data_dirs = "/usr/local/share/:/usr/share/";
2707
2708
0
  data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2709
#else
2710
  if (!data_dirs || !data_dirs[0])
2711
    data_dir_vector = g_strdupv ((gchar **) g_win32_get_system_data_dirs_for_module_real (NULL));
2712
  else
2713
    data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2714
#endif
2715
2716
0
  return g_steal_pointer (&data_dir_vector);
2717
0
}
2718
2719
/**
2720
 * g_get_system_data_dirs:
2721
 * 
2722
 * Returns an ordered list of base directories in which to access 
2723
 * system-wide application data.
2724
 *
2725
 * On UNIX platforms this is determined using the mechanisms described
2726
 * in the
2727
 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
2728
 * In this case the list of directories retrieved will be `XDG_DATA_DIRS`.
2729
 *
2730
 * On Windows it follows XDG Base Directory Specification if `XDG_DATA_DIRS` is defined.
2731
 * If `XDG_DATA_DIRS` is undefined,
2732
 * the first elements in the list are the Application Data
2733
 * and Documents folders for All Users. (These can be determined only
2734
 * on Windows 2000 or later and are not present in the list on other
2735
 * Windows versions.) See documentation for FOLDERID_ProgramData and
2736
 * FOLDERID_PublicDocuments.
2737
 *
2738
 * Then follows the "share" subfolder in the installation folder for
2739
 * the package containing the DLL that calls this function, if it can
2740
 * be determined.
2741
 * 
2742
 * Finally the list contains the "share" subfolder in the installation
2743
 * folder for GLib, and in the installation folder for the package the
2744
 * application's .exe file belongs to.
2745
 *
2746
 * The installation folders above are determined by looking up the
2747
 * folder where the module (DLL or EXE) in question is located. If the
2748
 * folder's name is "bin", its parent is used, otherwise the folder
2749
 * itself.
2750
 *
2751
 * Note that on Windows the returned list can vary depending on where
2752
 * this function is called.
2753
 *
2754
 * The return value is cached and modifying it at runtime is not supported, as
2755
 * it’s not thread-safe to modify environment variables at runtime.
2756
 *
2757
 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2758
 *     a %NULL-terminated array of strings owned by GLib that must not be
2759
 *     modified or freed.
2760
 * 
2761
 * Since: 2.6
2762
 **/
2763
const gchar * const * 
2764
g_get_system_data_dirs (void)
2765
0
{
2766
0
  const gchar * const *system_data_dirs;
2767
2768
0
  G_LOCK (g_utils_global);
2769
2770
0
  if (g_system_data_dirs == NULL)
2771
0
    g_system_data_dirs = g_build_system_data_dirs ();
2772
0
  system_data_dirs = (const gchar * const *) g_system_data_dirs;
2773
2774
0
  G_UNLOCK (g_utils_global);
2775
2776
0
  return system_data_dirs;
2777
0
}
2778
2779
static gchar **
2780
g_build_system_config_dirs (void)
2781
0
{
2782
0
  gchar **conf_dir_vector = NULL;
2783
0
  const gchar *conf_dirs = g_getenv ("XDG_CONFIG_DIRS");
2784
#ifdef G_OS_WIN32
2785
  if (conf_dirs)
2786
    {
2787
      conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2788
    }
2789
  else
2790
    {
2791
      gchar *special_conf_dirs = get_special_folder (&FOLDERID_ProgramData);
2792
2793
      if (special_conf_dirs)
2794
        conf_dir_vector = g_strsplit (special_conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2795
      else
2796
        /* Return empty list */
2797
        conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2798
2799
      g_free (special_conf_dirs);
2800
    }
2801
#else
2802
0
  if (!conf_dirs || !conf_dirs[0])
2803
0
    conf_dirs = "/etc/xdg";
2804
2805
0
  conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2806
0
#endif
2807
2808
0
  return g_steal_pointer (&conf_dir_vector);
2809
0
}
2810
2811
/**
2812
 * g_get_system_config_dirs:
2813
 * 
2814
 * Returns an ordered list of base directories in which to access 
2815
 * system-wide configuration information.
2816
 *
2817
 * On UNIX platforms this is determined using the mechanisms described
2818
 * in the
2819
 * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2820
 * In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
2821
 *
2822
 * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_DIRS` is defined.
2823
 * If `XDG_CONFIG_DIRS` is undefined, the directory that contains application
2824
 * data for all users is used instead. A typical path is
2825
 * `C:\Documents and Settings\All Users\Application Data`.
2826
 * This folder is used for application data
2827
 * that is not user specific. For example, an application can store
2828
 * a spell-check dictionary, a database of clip art, or a log file in the
2829
 * FOLDERID_ProgramData folder. This information will not roam and is available
2830
 * to anyone using the computer.
2831
 *
2832
 * The return value is cached and modifying it at runtime is not supported, as
2833
 * it’s not thread-safe to modify environment variables at runtime.
2834
 *
2835
 * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2836
 *     a %NULL-terminated array of strings owned by GLib that must not be
2837
 *     modified or freed.
2838
 * 
2839
 * Since: 2.6
2840
 **/
2841
const gchar * const *
2842
g_get_system_config_dirs (void)
2843
0
{
2844
0
  const gchar * const *system_config_dirs;
2845
2846
0
  G_LOCK (g_utils_global);
2847
2848
0
  if (g_system_config_dirs == NULL)
2849
0
    g_system_config_dirs = g_build_system_config_dirs ();
2850
0
  system_config_dirs = (const gchar * const *) g_system_config_dirs;
2851
2852
0
  G_UNLOCK (g_utils_global);
2853
2854
0
  return system_config_dirs;
2855
0
}
2856
2857
/**
2858
 * g_nullify_pointer:
2859
 * @nullify_location: (not nullable): the memory address of the pointer.
2860
 *
2861
 * Set the pointer at the specified location to %NULL.
2862
 **/
2863
void
2864
g_nullify_pointer (gpointer *nullify_location)
2865
0
{
2866
0
  g_return_if_fail (nullify_location != NULL);
2867
2868
0
  *nullify_location = NULL;
2869
0
}
2870
2871
0
#define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2872
0
#define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2873
0
#define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2874
0
#define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2875
0
#define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2876
0
#define EXABYTE_FACTOR  (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2877
2878
0
#define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2879
0
#define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2880
0
#define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2881
0
#define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2882
0
#define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2883
0
#define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2884
2885
/**
2886
 * g_format_size:
2887
 * @size: a size in bytes
2888
 *
2889
 * Formats a size (for example the size of a file) into a human readable
2890
 * string.  Sizes are rounded to the nearest size prefix (kB, MB, GB)
2891
 * and are displayed rounded to the nearest tenth. E.g. the file size
2892
 * 3292528 bytes will be converted into the string "3.2 MB". The returned string
2893
 * is UTF-8, and may use a non-breaking space to separate the number and units,
2894
 * to ensure they aren’t separated when line wrapped.
2895
 *
2896
 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2897
 *
2898
 * This string should be freed with g_free() when not needed any longer.
2899
 *
2900
 * See g_format_size_full() for more options about how the size might be
2901
 * formatted.
2902
 *
2903
 * Returns: (transfer full): a newly-allocated formatted string containing
2904
 *   a human readable file size
2905
 *
2906
 * Since: 2.30
2907
 */
2908
gchar *
2909
g_format_size (guint64 size)
2910
0
{
2911
0
  return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2912
0
}
2913
2914
/**
2915
 * GFormatSizeFlags:
2916
 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2917
 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2918
 *     of the returned string.  For example, "45.6 kB (45,612 bytes)".
2919
 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2920
 *     suffixes. IEC units should only be used for reporting things with
2921
 *     a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2922
 *     Network and storage sizes should be reported in the normal SI units.
2923
 * @G_FORMAT_SIZE_BITS: set the size as a quantity in bits, rather than
2924
 *     bytes, and return units in bits. For example, ‘Mbit’ rather than ‘MB’.
2925
 * @G_FORMAT_SIZE_ONLY_VALUE: return only value, without unit; this should
2926
 *     not be used together with @G_FORMAT_SIZE_LONG_FORMAT
2927
 *     nor @G_FORMAT_SIZE_ONLY_UNIT. Since: 2.74
2928
 * @G_FORMAT_SIZE_ONLY_UNIT: return only unit, without value; this should
2929
 *     not be used together with @G_FORMAT_SIZE_LONG_FORMAT
2930
 *     nor @G_FORMAT_SIZE_ONLY_VALUE. Since: 2.74
2931
 *
2932
 * Flags to modify the format of the string returned by g_format_size_full().
2933
 */
2934
2935
#pragma GCC diagnostic push
2936
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
2937
2938
/**
2939
 * g_format_size_full:
2940
 * @size: a size in bytes
2941
 * @flags: #GFormatSizeFlags to modify the output
2942
 *
2943
 * Formats a size.
2944
 *
2945
 * This function is similar to g_format_size() but allows for flags
2946
 * that modify the output. See #GFormatSizeFlags.
2947
 *
2948
 * Returns: (transfer full): a newly-allocated formatted string
2949
 *   containing a human readable file size
2950
 *
2951
 * Since: 2.30
2952
 */
2953
gchar *
2954
g_format_size_full (guint64          size,
2955
                    GFormatSizeFlags flags)
2956
0
{
2957
0
  struct Format
2958
0
  {
2959
0
    guint64 factor;
2960
0
    char string[10];
2961
0
  };
2962
2963
0
  typedef enum
2964
0
  {
2965
0
    FORMAT_BYTES,
2966
0
    FORMAT_BYTES_IEC,
2967
0
    FORMAT_BITS,
2968
0
    FORMAT_BITS_IEC
2969
0
  } FormatIndex;
2970
2971
0
  const struct Format formats[4][6] = {
2972
0
    {
2973
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 kB" */
2974
0
      { KILOBYTE_FACTOR, N_("kB") },
2975
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 MB" */
2976
0
      { MEGABYTE_FACTOR, N_("MB") },
2977
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 GB" */
2978
0
      { GIGABYTE_FACTOR, N_("GB") },
2979
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 TB" */
2980
0
      { TERABYTE_FACTOR, N_("TB") },
2981
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 PB" */
2982
0
      { PETABYTE_FACTOR, N_("PB") },
2983
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 EB" */
2984
0
      { EXABYTE_FACTOR,  N_("EB") }
2985
0
    },
2986
0
    {
2987
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 KiB" */
2988
0
      { KIBIBYTE_FACTOR, N_("KiB") },
2989
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 MiB" */
2990
0
      { MEBIBYTE_FACTOR, N_("MiB") },
2991
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 GiB" */
2992
0
      { GIBIBYTE_FACTOR, N_("GiB") },
2993
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 TiB" */
2994
0
      { TEBIBYTE_FACTOR, N_("TiB") },
2995
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 PiB" */
2996
0
      { PEBIBYTE_FACTOR, N_("PiB") },
2997
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 EiB" */
2998
0
      { EXBIBYTE_FACTOR, N_("EiB") }
2999
0
    },
3000
0
    {
3001
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 kbit" */
3002
0
      { KILOBYTE_FACTOR, N_("kbit") },
3003
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 Mbit" */
3004
0
      { MEGABYTE_FACTOR, N_("Mbit") },
3005
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 Gbit" */
3006
0
      { GIGABYTE_FACTOR, N_("Gbit") },
3007
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 Tbit" */
3008
0
      { TERABYTE_FACTOR, N_("Tbit") },
3009
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 Pbit" */
3010
0
      { PETABYTE_FACTOR, N_("Pbit") },
3011
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 Ebit" */
3012
0
      { EXABYTE_FACTOR,  N_("Ebit") }
3013
0
    },
3014
0
    {
3015
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 Kibit" */
3016
0
      { KIBIBYTE_FACTOR, N_("Kibit") },
3017
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 Mibit" */
3018
0
      { MEBIBYTE_FACTOR, N_("Mibit") },
3019
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 Gibit" */
3020
0
      { GIBIBYTE_FACTOR, N_("Gibit") },
3021
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 Tibit" */
3022
0
      { TEBIBYTE_FACTOR, N_("Tibit") },
3023
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 Pibit" */
3024
0
      { PEBIBYTE_FACTOR, N_("Pibit") },
3025
      /* Translators: A unit symbol for size formatting, showing for example: "13.0 Eibit" */
3026
0
      { EXBIBYTE_FACTOR, N_("Eibit") }
3027
0
    }
3028
0
  };
3029
3030
0
  GString *string;
3031
0
  FormatIndex index;
3032
3033
0
  g_return_val_if_fail ((flags & (G_FORMAT_SIZE_LONG_FORMAT | G_FORMAT_SIZE_ONLY_VALUE)) != (G_FORMAT_SIZE_LONG_FORMAT | G_FORMAT_SIZE_ONLY_VALUE), NULL);
3034
0
  g_return_val_if_fail ((flags & (G_FORMAT_SIZE_LONG_FORMAT | G_FORMAT_SIZE_ONLY_UNIT)) != (G_FORMAT_SIZE_LONG_FORMAT | G_FORMAT_SIZE_ONLY_UNIT), NULL);
3035
0
  g_return_val_if_fail ((flags & (G_FORMAT_SIZE_ONLY_VALUE | G_FORMAT_SIZE_ONLY_UNIT)) != (G_FORMAT_SIZE_ONLY_VALUE | G_FORMAT_SIZE_ONLY_UNIT), NULL);
3036
3037
0
  string = g_string_new (NULL);
3038
3039
0
  switch (flags & ~(G_FORMAT_SIZE_LONG_FORMAT | G_FORMAT_SIZE_ONLY_VALUE | G_FORMAT_SIZE_ONLY_UNIT))
3040
0
    {
3041
0
    case G_FORMAT_SIZE_DEFAULT:
3042
0
      index = FORMAT_BYTES;
3043
0
      break;
3044
0
    case (G_FORMAT_SIZE_DEFAULT | G_FORMAT_SIZE_IEC_UNITS):
3045
0
      index = FORMAT_BYTES_IEC;
3046
0
      break;
3047
0
    case G_FORMAT_SIZE_BITS:
3048
0
      index = FORMAT_BITS;
3049
0
      break;
3050
0
    case (G_FORMAT_SIZE_BITS | G_FORMAT_SIZE_IEC_UNITS):
3051
0
      index = FORMAT_BITS_IEC;
3052
0
      break;
3053
0
    default:
3054
0
      g_assert_not_reached ();
3055
0
    }
3056
3057
3058
0
  if (size < formats[index][0].factor)
3059
0
    {
3060
0
      const char * units;
3061
3062
0
      if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
3063
0
        {
3064
0
          units = g_dngettext (GETTEXT_PACKAGE, "byte", "bytes", (guint) size);
3065
0
        }
3066
0
      else
3067
0
        {
3068
0
          units = g_dngettext (GETTEXT_PACKAGE, "bit", "bits", (guint) size);
3069
0
        }
3070
3071
0
      if ((flags & G_FORMAT_SIZE_ONLY_UNIT) != 0)
3072
0
        g_string_append (string, units);
3073
0
      else if ((flags & G_FORMAT_SIZE_ONLY_VALUE) != 0)
3074
        /* Translators: The "%u" is replaced with the size value, like "13"; it could
3075
         * be part of "13 bytes", but only the number is requested this time. */
3076
0
        g_string_printf (string, C_("format-size", "%u"), (guint) size);
3077
0
      else
3078
0
        {
3079
          /* Translators: The first "%u" is replaced with the value, the "%s" with a unit of the value.
3080
           * The order can be changed with "%$2s %$1u". An example: "13 bytes" */
3081
0
          g_string_printf (string, C_("format-size", "%u %s"), (guint) size, units);
3082
0
        }
3083
3084
0
      flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
3085
0
    }
3086
0
  else
3087
0
    {
3088
0
      const gsize n = G_N_ELEMENTS (formats[index]);
3089
0
      const gchar * units;
3090
0
      gdouble value;
3091
0
      gsize i;
3092
3093
      /*
3094
       * Point the last format (the highest unit) by default
3095
       * and then then scan all formats, starting with the 2nd one
3096
       * because the 1st is already managed by with the plural form
3097
       */
3098
0
      const struct Format * f = &formats[index][n - 1];
3099
3100
0
      for (i = 1; i < n; i++)
3101
0
        {
3102
0
          if (size < formats[index][i].factor)
3103
0
            {
3104
0
              f = &formats[index][i - 1];
3105
0
              break;
3106
0
            }
3107
0
        }
3108
3109
0
      units = _(f->string);
3110
0
      value = (gdouble) size / (gdouble) f->factor;
3111
3112
0
      if ((flags & G_FORMAT_SIZE_ONLY_UNIT) != 0)
3113
0
        g_string_append (string, units);
3114
0
      else if ((flags & G_FORMAT_SIZE_ONLY_VALUE) != 0)
3115
        /* Translators: The "%.1f" is replaced with the size value, like "13.0"; it could
3116
         * be part of "13.0 MB", but only the number is requested this time. */
3117
0
        g_string_printf (string, C_("format-size", "%.1f"), value);
3118
0
      else
3119
0
        {
3120
          /* Translators: The first "%.1f" is replaced with the value, the "%s" with a unit of the value.
3121
           * The order can be changed with "%$2s %$1.1f". Keep the no-break space between the value and
3122
           * the unit symbol. An example: "13.0 MB" */
3123
0
          g_string_printf (string, C_("format-size", "%.1f %s"), value, units);
3124
0
        }
3125
0
    }
3126
3127
0
  if (flags & G_FORMAT_SIZE_LONG_FORMAT)
3128
0
    {
3129
      /* First problem: we need to use the number of bytes to decide on
3130
       * the plural form that is used for display, but the number of
3131
       * bytes potentially exceeds the size of a guint (which is what
3132
       * ngettext() takes).
3133
       *
3134
       * From a pragmatic standpoint, it seems that all known languages
3135
       * base plural forms on one or both of the following:
3136
       *
3137
       *   - the lowest digits of the number
3138
       *
3139
       *   - if the number if greater than some small value
3140
       *
3141
       * Here's how we fake it:  Draw an arbitrary line at one thousand.
3142
       * If the number is below that, then fine.  If it is above it,
3143
       * then we take the modulus of the number by one thousand (in
3144
       * order to keep the lowest digits) and add one thousand to that
3145
       * (in order to ensure that 1001 is not treated the same as 1).
3146
       */
3147
0
      guint plural_form = size < 1000 ? size : size % 1000 + 1000;
3148
3149
      /* Second problem: we need to translate the string "%u byte/bit" and
3150
       * "%u bytes/bits" for pluralisation, but the correct number format to
3151
       * use for a gsize is different depending on which architecture
3152
       * we're on.
3153
       *
3154
       * Solution: format the number separately and use "%s bytes/bits" on
3155
       * all platforms.
3156
       */
3157
0
      const gchar *translated_format;
3158
0
      gchar *formatted_number;
3159
3160
0
      if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
3161
0
        {
3162
          /* Translators: the %s in "%s bytes" will always be replaced by a number. */
3163
0
          translated_format = g_dngettext (GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
3164
0
        }
3165
0
      else
3166
0
        {
3167
          /* Translators: the %s in "%s bits" will always be replaced by a number. */
3168
0
          translated_format = g_dngettext (GETTEXT_PACKAGE, "%s bit", "%s bits", plural_form);
3169
0
        }
3170
0
      formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
3171
3172
0
      g_string_append (string, " (");
3173
0
      g_string_append_printf (string, translated_format, formatted_number);
3174
0
      g_free (formatted_number);
3175
0
      g_string_append (string, ")");
3176
0
    }
3177
3178
0
  return g_string_free (string, FALSE);
3179
0
}
3180
3181
#pragma GCC diagnostic pop
3182
3183
/**
3184
 * g_format_size_for_display:
3185
 * @size: a size in bytes
3186
 *
3187
 * Formats a size (for example the size of a file) into a human
3188
 * readable string. Sizes are rounded to the nearest size prefix
3189
 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
3190
 * E.g. the file size 3292528 bytes will be converted into the
3191
 * string "3.1 MB".
3192
 *
3193
 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
3194
 *
3195
 * This string should be freed with g_free() when not needed any longer.
3196
 *
3197
 * Returns: (transfer full): a newly-allocated formatted string
3198
 *   containing a human readable file size
3199
 *
3200
 * Since: 2.16
3201
 *
3202
 * Deprecated:2.30: This function is broken due to its use of SI
3203
 *     suffixes to denote IEC units. Use g_format_size() instead.
3204
 */
3205
gchar *
3206
g_format_size_for_display (goffset size)
3207
0
{
3208
0
  if (size < (goffset) KIBIBYTE_FACTOR)
3209
0
    return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
3210
0
  else
3211
0
    {
3212
0
      gdouble displayed_size;
3213
3214
0
      if (size < (goffset) MEBIBYTE_FACTOR)
3215
0
        {
3216
0
          displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
3217
          /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
3218
           * mean 1024 bytes.  I am aware that 'KB' is not correct, but it has been preserved for reasons of
3219
           * compatibility.  Users will not see this string unless a program is using this deprecated function.
3220
           * Please translate as literally as possible.
3221
           */
3222
0
          return g_strdup_printf (_("%.1f KB"), displayed_size);
3223
0
        }
3224
0
      else if (size < (goffset) GIBIBYTE_FACTOR)
3225
0
        {
3226
0
          displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
3227
0
          return g_strdup_printf (_("%.1f MB"), displayed_size);
3228
0
        }
3229
0
      else if (size < (goffset) TEBIBYTE_FACTOR)
3230
0
        {
3231
0
          displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
3232
0
          return g_strdup_printf (_("%.1f GB"), displayed_size);
3233
0
        }
3234
0
      else if (size < (goffset) PEBIBYTE_FACTOR)
3235
0
        {
3236
0
          displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
3237
0
          return g_strdup_printf (_("%.1f TB"), displayed_size);
3238
0
        }
3239
0
      else if (size < (goffset) EXBIBYTE_FACTOR)
3240
0
        {
3241
0
          displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
3242
0
          return g_strdup_printf (_("%.1f PB"), displayed_size);
3243
0
        }
3244
0
      else
3245
0
        {
3246
0
          displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
3247
0
          return g_strdup_printf (_("%.1f EB"), displayed_size);
3248
0
        }
3249
0
    }
3250
0
}
3251
3252
#if defined (G_OS_WIN32) && !defined (_WIN64)
3253
3254
/* Binary compatibility versions. Not for newly compiled code. */
3255
3256
_GLIB_EXTERN const gchar *g_get_user_name_utf8        (void);
3257
_GLIB_EXTERN const gchar *g_get_real_name_utf8        (void);
3258
_GLIB_EXTERN const gchar *g_get_home_dir_utf8         (void);
3259
_GLIB_EXTERN const gchar *g_get_tmp_dir_utf8          (void);
3260
_GLIB_EXTERN gchar       *g_find_program_in_path_utf8 (const gchar *program);
3261
3262
gchar *
3263
g_find_program_in_path_utf8 (const gchar *program)
3264
{
3265
  return g_find_program_in_path (program);
3266
}
3267
3268
const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
3269
const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
3270
const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
3271
const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
3272
3273
#endif
3274
3275
/* Private API:
3276
 *
3277
 * Returns %TRUE if the current process was executed as setuid
3278
 */ 
3279
gboolean
3280
g_check_setuid (void)
3281
0
{
3282
0
#if defined(HAVE_SYS_AUXV_H) && defined(HAVE_GETAUXVAL) && defined(AT_SECURE)
3283
0
  unsigned long value;
3284
0
  int errsv;
3285
3286
0
  errno = 0;
3287
0
  value = getauxval (AT_SECURE);
3288
0
  errsv = errno;
3289
0
  if (errsv)
3290
0
    g_error ("getauxval () failed: %s", g_strerror (errsv));
3291
0
  return value;
3292
#elif defined(HAVE_ISSETUGID) && !defined(__ANDROID__)
3293
  /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
3294
3295
  /* Android had it in older versions but the new 64 bit ABI does not
3296
   * have it anymore, and some versions of the 32 bit ABI neither.
3297
   * https://code.google.com/p/android-developer-preview/issues/detail?id=168
3298
   */
3299
  return issetugid ();
3300
#elif defined(G_OS_UNIX)
3301
  uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
3302
  gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
3303
3304
  static gsize check_setuid_initialised;
3305
  static gboolean is_setuid;
3306
3307
  if (g_once_init_enter (&check_setuid_initialised))
3308
    {
3309
#ifdef HAVE_GETRESUID
3310
      /* These aren't in the header files, so we prototype them here.
3311
       */
3312
      int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
3313
      int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
3314
      
3315
      if (getresuid (&ruid, &euid, &suid) != 0 ||
3316
          getresgid (&rgid, &egid, &sgid) != 0)
3317
#endif /* HAVE_GETRESUID */
3318
        {
3319
          suid = ruid = getuid ();
3320
          sgid = rgid = getgid ();
3321
          euid = geteuid ();
3322
          egid = getegid ();
3323
        }
3324
3325
      is_setuid = (ruid != euid || ruid != suid ||
3326
                   rgid != egid || rgid != sgid);
3327
3328
      g_once_init_leave (&check_setuid_initialised, 1);
3329
    }
3330
  return is_setuid;
3331
#else
3332
  return FALSE;
3333
#endif
3334
0
}
3335
3336
#ifdef G_OS_WIN32
3337
/**
3338
 * g_abort:
3339
 *
3340
 * A wrapper for the POSIX abort() function.
3341
 *
3342
 * On Windows it is a function that makes extra effort (including a call
3343
 * to abort()) to ensure that a debugger-catchable exception is thrown
3344
 * before the program terminates.
3345
 *
3346
 * See your C library manual for more details about abort().
3347
 *
3348
 * Since: 2.50
3349
 */
3350
void
3351
g_abort (void)
3352
{
3353
  /* One call to break the debugger
3354
   * We check if a debugger is actually attached to
3355
   * avoid a windows error reporting popup window
3356
   * when run in a test harness / on CI
3357
   */
3358
  if (IsDebuggerPresent ())
3359
    DebugBreak ();
3360
  /* One call in case CRT changes its abort() behaviour */
3361
  abort ();
3362
  /* And one call to bind them all and terminate the program for sure */
3363
  ExitProcess (127);
3364
}
3365
#endif