Imported Upstream version 2.64.5
[platform/upstream/glib.git] / meson.build
1 project('glib', 'c', 'cpp',
2   version : '2.64.5',
3   # NOTE: We keep this pinned at 0.49 because that's what Debian 10 ships
4   meson_version : '>= 0.49.2',
5   default_options : [
6     'buildtype=debugoptimized',
7     'warning_level=1',
8     'c_std=gnu99'
9   ]
10 )
11
12 cc = meson.get_compiler('c')
13 cxx = meson.get_compiler('cpp')
14
15 cc_can_run = not meson.is_cross_build() or meson.has_exe_wrapper()
16
17 if cc.get_id() == 'msvc'
18   # Ignore several spurious warnings for things glib does very commonly
19   # If a warning is completely useless and spammy, use '/wdXXXX' to suppress it
20   # If a warning is harmless but hard to fix, use '/woXXXX' so it's shown once
21   # NOTE: Only add warnings here if you are sure they're spurious
22   add_project_arguments('/wd4035', '/wd4715', '/wd4116',
23     '/wd4046', '/wd4068', '/wo4090', '/FImsvc_recommended_pragmas.h',language : 'c')
24   # Disable SAFESEH with MSVC for plugins and libs that use external deps that
25   # are built with MinGW
26   noseh_link_args = ['/SAFESEH:NO']
27   # Set the input and exec encoding to utf-8, like is the default with GCC
28   add_project_arguments(cc.get_supported_arguments(['/utf-8']), language: 'c')
29 else
30   noseh_link_args = []
31   # -mms-bitfields vs -fnative-struct ?
32 endif
33
34 host_system = host_machine.system()
35
36 glib_version = meson.project_version()
37 glib_api_version = '2.0'
38 version_arr = glib_version.split('.')
39 major_version = version_arr[0].to_int()
40 minor_version = version_arr[1].to_int()
41 micro_version = version_arr[2].to_int()
42
43 interface_age = minor_version.is_odd() ? 0 : micro_version
44 binary_age = 100 * minor_version + micro_version
45
46 soversion = 0
47 # Maintain compatibility with previous libtool versioning
48 # current = minor * 100 + micro
49 current = binary_age - interface_age
50 library_version = '@0@.@1@.@2@'.format(soversion, current, interface_age)
51 darwin_versions = [current + 1, '@0@.@1@'.format(current + 1, interface_age)]
52
53 configinc = include_directories('.')
54 glibinc = include_directories('glib')
55 gobjectinc = include_directories('gobject')
56 gmoduleinc = include_directories('gmodule')
57 gioinc = include_directories('gio')
58
59 glib_prefix = get_option('prefix')
60 glib_bindir = join_paths(glib_prefix, get_option('bindir'))
61 glib_libdir = join_paths(glib_prefix, get_option('libdir'))
62 glib_libexecdir = join_paths(glib_prefix, get_option('libexecdir'))
63 glib_datadir = join_paths(glib_prefix, get_option('datadir'))
64 glib_pkgdatadir = join_paths(glib_datadir, 'glib-2.0')
65 glib_includedir = join_paths(glib_prefix, get_option('includedir'))
66 if get_option('gio_module_dir') != ''
67   glib_giomodulesdir = join_paths(glib_prefix, get_option('gio_module_dir'))
68 else
69   glib_giomodulesdir = join_paths(glib_libdir, 'gio', 'modules')
70 endif
71
72 glib_pkgconfigreldir = join_paths(glib_libdir, 'pkgconfig')
73
74 if get_option('charsetalias_dir') != ''
75   glib_charsetaliasdir = join_paths(glib_prefix, get_option('charsetalias_dir'))
76 else
77   glib_charsetaliasdir = glib_libdir
78 endif
79
80 installed_tests_metadir = join_paths(glib_datadir, 'installed-tests', meson.project_name())
81 installed_tests_execdir = join_paths(glib_libexecdir, 'installed-tests', meson.project_name())
82 installed_tests_enabled = get_option('installed_tests')
83 installed_tests_template = files('template.test.in')
84 installed_tests_template_tap = files('template-tap.test.in')
85
86 # Don’t build the tests unless we can run them (either natively, in an exe wrapper, or by installing them for later use)
87 build_tests = not meson.is_cross_build() or (meson.is_cross_build() and meson.has_exe_wrapper()) or installed_tests_enabled
88
89 add_project_arguments('-D_GNU_SOURCE', language: 'c')
90
91 # Disable strict aliasing;
92 # see https://bugzilla.gnome.org/show_bug.cgi?id=791622
93 if cc.has_argument('-fno-strict-aliasing')
94   add_project_arguments('-fno-strict-aliasing', language: 'c')
95 endif
96
97 ########################
98 # Configuration begins #
99 ########################
100 glib_conf = configuration_data()
101 glibconfig_conf = configuration_data()
102
103 # accumulated list of defines as we check for them, so we can easily
104 # use them later in test programs (autoconf does this automatically)
105 glib_conf_prefix = ''
106
107 glib_conf.set('GLIB_MAJOR_VERSION', major_version)
108 glib_conf.set('GLIB_MINOR_VERSION', minor_version)
109 glib_conf.set('GLIB_MICRO_VERSION', micro_version)
110 glib_conf.set('GLIB_INTERFACE_AGE', interface_age)
111 glib_conf.set('GLIB_BINARY_AGE', binary_age)
112 glib_conf.set_quoted('GETTEXT_PACKAGE', 'glib20')
113 glib_conf.set_quoted('PACKAGE_BUGREPORT', 'https://gitlab.gnome.org/GNOME/glib/issues/new')
114 glib_conf.set_quoted('PACKAGE_NAME', 'glib')
115 glib_conf.set_quoted('PACKAGE_STRING', 'glib @0@'.format(meson.project_version()))
116 glib_conf.set_quoted('PACKAGE_TARNAME', 'glib')
117 glib_conf.set_quoted('PACKAGE_URL', '')
118 glib_conf.set_quoted('PACKAGE_VERSION', meson.project_version())
119 glib_conf.set('ENABLE_NLS', 1)
120
121 # used by the .rc.in files
122 glibconfig_conf.set('LT_CURRENT_MINUS_AGE', soversion)
123
124 glib_conf.set('_GNU_SOURCE', 1)
125
126 if host_system == 'windows'
127   # Poll doesn't work on devices on Windows
128   glib_conf.set('BROKEN_POLL', true)
129 endif
130
131 if host_system == 'windows' and cc.get_id() != 'msvc' and cc.get_id() != 'clang-cl'
132   # FIXME: Ideally we shouldn't depend on this on Windows and should use
133   # 64 bit capable Windows API that also works with MSVC.
134   # The autotools build did set this for mingw and while meson sets it
135   # for gcc/clang by default, it doesn't do so on Windows.
136   glib_conf.set('_FILE_OFFSET_BITS', 64)
137 endif
138
139 # Check for GNU visibility attributes
140 g_have_gnuc_visibility = cc.compiles('''
141   void
142   __attribute__ ((visibility ("hidden")))
143        f_hidden (void)
144   {
145   }
146   void
147   __attribute__ ((visibility ("internal")))
148        f_internal (void)
149   {
150   }
151   void
152   __attribute__ ((visibility ("default")))
153        f_default (void)
154   {
155   }
156   int main (void)
157   {
158     f_hidden();
159     f_internal();
160     f_default();
161     return 0;
162   }
163   ''',
164   # Not supported by MSVC, but MSVC also won't support visibility,
165   # so it's OK to pass -Werror explicitly. Replace with
166   # override_options : 'werror=true' once that is supported
167   args: ['-Werror'],
168   name : 'GNU C visibility attributes test')
169
170 if g_have_gnuc_visibility
171   glibconfig_conf.set('G_HAVE_GNUC_VISIBILITY', '1')
172 endif
173
174 # Detect and set symbol visibility
175 glib_hidden_visibility_args = []
176 if get_option('default_library') != 'static'
177   if host_system == 'windows' or host_system == 'cygwin'
178     glib_conf.set('DLL_EXPORT', true)
179     if cc.get_id() == 'msvc' or cc.get_id() == 'clang-cl'
180       glib_conf.set('_GLIB_EXTERN', '__declspec(dllexport) extern')
181     elif cc.has_argument('-fvisibility=hidden')
182       glib_conf.set('_GLIB_EXTERN', '__attribute__((visibility("default"))) __declspec(dllexport) extern')
183       glib_hidden_visibility_args = ['-fvisibility=hidden']
184     endif
185   elif cc.has_argument('-fvisibility=hidden')
186     glib_conf.set('_GLIB_EXTERN', '__attribute__((visibility("default"))) extern')
187     glib_hidden_visibility_args = ['-fvisibility=hidden']
188   endif
189 endif
190
191 if get_option('default_library') == 'static'
192     glibconfig_conf.set('GLIB_STATIC_COMPILATION', '1')
193     glibconfig_conf.set('GOBJECT_STATIC_COMPILATION', '1')
194 endif
195
196 # Cygwin glib port maintainers made it clear
197 # (via the patches they apply) that they want no
198 # part of glib W32 code, therefore we do not define
199 # G_PLATFORM_WIN32 for host_system == 'cygwin'.
200 # This makes G_PLATFORM_WIN32 a synonym for
201 # G_OS_WIN32.
202 if host_system == 'windows'
203   glib_os = '''#define G_OS_WIN32
204 #define G_PLATFORM_WIN32'''
205 elif host_system == 'cygwin'
206   glib_os = '''#define G_OS_UNIX
207 #define G_WITH_CYGWIN'''
208 else
209   glib_os = '#define G_OS_UNIX'
210 endif
211 glibconfig_conf.set('glib_os', glib_os)
212
213 # We need to know the build type to determine what .lib files we need on Visual Studio
214 # for dependencies that don't normally come with pkg-config files for Visual Studio builds
215 buildtype = get_option('buildtype')
216
217 glib_debug_cflags = []
218 if buildtype.startswith('debug')
219   glib_debug_cflags += ['-DG_ENABLE_DEBUG']
220 elif buildtype == 'release'
221   glib_debug_cflags += ['-DG_DISABLE_CAST_CHECKS']
222 endif
223
224 add_project_arguments(glib_debug_cflags, language: 'c')
225
226 # check for header files
227
228 headers = [
229   'alloca.h',
230   'crt_externs.h',
231   'dirent.h', # MSC does not come with this by default
232   'float.h',
233   'fstab.h',
234   'grp.h',
235   'inttypes.h',
236   'limits.h',
237   'linux/magic.h',
238   'locale.h',
239   'mach/mach_time.h',
240   'memory.h',
241   'mntent.h',
242   'poll.h',
243   'pwd.h',
244   'sched.h',
245   'spawn.h',
246   'stdint.h',
247   'stdlib.h',
248   'string.h',
249   'strings.h',
250   'sys/auxv.h',
251   'sys/event.h',
252   'sys/filio.h',
253   'sys/inotify.h',
254   'sys/mkdev.h',
255   'sys/mntctl.h',
256   'sys/mnttab.h',
257   'sys/mount.h',
258   'sys/param.h',
259   'sys/resource.h',
260   'sys/select.h',
261   'sys/statfs.h',
262   'sys/stat.h',
263   'sys/statvfs.h',
264   'sys/sysctl.h',
265   'sys/time.h', # MSC does not come with this by default
266   'sys/times.h',
267   'sys/types.h',
268   'sys/uio.h',
269   'sys/vfs.h',
270   'sys/vfstab.h',
271   'sys/vmount.h',
272   'sys/wait.h',
273   'termios.h',
274   'unistd.h',
275   'values.h',
276   'wchar.h',
277   'xlocale.h',
278 ]
279
280 foreach h : headers
281   if cc.has_header(h)
282     define = 'HAVE_' + h.underscorify().to_upper()
283     glib_conf.set(define, 1)
284     glib_conf_prefix = glib_conf_prefix + '#define @0@ 1\n'.format(define)
285   endif
286 endforeach
287
288 # FIXME: Use cc.check_header from Meson 0.47.
289 # FreeBSD includes a malloc.h which always throw compilation error.
290 if cc.compiles('#include <malloc.h>', name : 'malloc.h')
291   glib_conf.set('HAVE_MALLOC_H', 1)
292   glib_conf_prefix = glib_conf_prefix + '#define HAVE_MALLOC_H 1\n'
293 endif
294
295 if cc.has_header('linux/netlink.h')
296   glib_conf.set('HAVE_NETLINK', 1)
297 endif
298
299 if glib_conf.has('HAVE_LOCALE_H')
300   if cc.has_header_symbol('locale.h', 'LC_MESSAGES')
301     glib_conf.set('HAVE_LC_MESSAGES', 1)
302   endif
303 endif
304
305 struct_stat_blkprefix = '''
306 #include <sys/types.h>
307 #include <sys/stat.h>
308 #ifdef HAVE_UNISTD_H
309 #include <unistd.h>
310 #endif
311 #ifdef HAVE_SYS_STATFS_H
312 #include <sys/statfs.h>
313 #endif
314 #ifdef HAVE_SYS_PARAM_H
315 #include <sys/param.h>
316 #endif
317 #ifdef HAVE_SYS_MOUNT_H
318 #include <sys/mount.h>
319 #endif
320 '''
321
322 struct_members = [
323   [ 'stat', 'st_mtimensec' ],
324   [ 'stat', 'st_mtim.tv_nsec' ],
325   [ 'stat', 'st_atimensec' ],
326   [ 'stat', 'st_atim.tv_nsec' ],
327   [ 'stat', 'st_ctimensec' ],
328   [ 'stat', 'st_ctim.tv_nsec' ],
329   [ 'stat', 'st_birthtime' ],
330   [ 'stat', 'st_birthtimensec' ],
331   [ 'stat', 'st_birthtim' ],
332   [ 'stat', 'st_birthtim.tv_nsec' ],
333   [ 'stat', 'st_blksize', struct_stat_blkprefix ],
334   [ 'stat', 'st_blocks', struct_stat_blkprefix ],
335   [ 'statfs', 'f_fstypename', struct_stat_blkprefix ],
336   [ 'statfs', 'f_bavail', struct_stat_blkprefix ],
337   [ 'dirent', 'd_type', '''#include <sys/types.h>
338                            #include <dirent.h>''' ],
339   [ 'statvfs', 'f_basetype', '#include <sys/statvfs.h>' ],
340   [ 'statvfs', 'f_fstypename', '#include <sys/statvfs.h>' ],
341   [ 'tm', 'tm_gmtoff', '#include <time.h>' ],
342   [ 'tm', '__tm_gmtoff', '#include <time.h>' ],
343 ]
344
345 foreach m : struct_members
346   header_check_prefix = glib_conf_prefix
347   if m.length() == 3
348     header_check_prefix = header_check_prefix + m[2]
349   else
350     header_check_prefix = header_check_prefix + '#include <sys/stat.h>'
351   endif
352   if cc.has_member('struct ' + m[0], m[1], prefix : header_check_prefix)
353     define = 'HAVE_STRUCT_@0@_@1@'.format(m[0].to_upper(), m[1].underscorify().to_upper())
354     glib_conf.set(define, 1)
355     glib_conf_prefix = glib_conf_prefix + '#define @0@ 1\n'.format(define)
356   else
357   endif
358 endforeach
359
360 # Compiler flags
361 if cc.get_id() == 'gcc' or cc.get_id() == 'clang'
362   warning_c_args = [
363     '-Wduplicated-branches',
364     '-Wimplicit-fallthrough',
365     '-Wmisleading-indentation',
366     '-Wstrict-prototypes',
367     '-Wunused',
368     # Due to maintained deprecated code, we do not want to see unused parameters
369     '-Wno-unused-parameter',
370     # Due to pervasive use of things like GPOINTER_TO_UINT(), we do not support
371     # building with -Wbad-function-cast.
372     '-Wno-bad-function-cast',
373     '-Wno-cast-function-type',
374     # Due to function casts through (void*) we cannot support -Wpedantic:
375     # https://wiki.gnome.org/Projects/GLib/CompilerRequirements#Function_pointer_conversions.
376     '-Wno-pedantic',
377     # A zero-length format string shouldn't be considered an issue.
378     '-Wno-format-zero-length',
379     '-Werror=declaration-after-statement',
380     '-Werror=format=2',
381     '-Werror=implicit-function-declaration',
382     '-Werror=init-self',
383     '-Werror=missing-include-dirs',
384     '-Werror=missing-prototypes',
385     '-Werror=pointer-arith',
386   ]
387   warning_c_link_args = [
388     '-Wl,-z,nodelete',
389   ]
390   if get_option('bsymbolic_functions')
391     warning_c_link_args += ['-Wl,-Bsymbolic-functions']
392   endif
393 else
394   warning_c_args = []
395   warning_c_link_args = []
396 endif
397
398 add_project_arguments(cc.get_supported_arguments(warning_c_args), language: 'c')
399
400 # FIXME: We cannot build some of the GResource tests with -z nodelete, which
401 # means we cannot use that flag in add_project_link_arguments(), and must add
402 # it to the relevant targets manually. We do the same with -Bsymbolic-functions
403 # because that is what the autotools build did.
404 # See https://github.com/mesonbuild/meson/pull/3520 for a way to eventually
405 # improve this.
406 glib_link_flags = cc.get_supported_link_arguments(warning_c_link_args)
407
408 # Windows SDK requirements and checks
409 if host_system == 'windows'
410   # Check whether we're building for UWP apps
411   code = '''
412   #include <windows.h>
413   #if !(WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP))
414   #error "Not building for UWP"
415   #endif'''
416   if cc.compiles(code, name : 'building for UWP')
417     glib_conf.set('G_WINAPI_ONLY_APP', true)
418     # We require Windows 10+ on WinRT
419     glib_conf.set('_WIN32_WINNT', '0x0A00')
420   else
421     # We require Windows 7+ on Win32
422     glib_conf.set('_WIN32_WINNT', '0x0601')
423   endif
424 endif
425
426 functions = [
427   'endmntent',
428   'endservent',
429   'fallocate',
430   'fchmod',
431   'fchown',
432   'fdwalk',
433   'fsync',
434   'getauxval',
435   'getc_unlocked',
436   'getfsstat',
437   'getgrgid_r',
438   'getmntent_r',
439   'getpwuid_r',
440   'getresuid',
441   'getvfsstat',
442   'gmtime_r',
443   'hasmntopt',
444   'inotify_init1',
445   'issetugid',
446   'kevent',
447   'kqueue',
448   'lchmod',
449   'lchown',
450   'link',
451   'localtime_r',
452   'lstat',
453   'mbrtowc',
454   'memalign',
455   'mmap',
456   'newlocale',
457   'pipe2',
458   'poll',
459   'prlimit',
460   'readlink',
461   'recvmmsg',
462   'sendmmsg',
463   'setenv',
464   'setmntent',
465   'strerror_r',
466   'strnlen',
467   'strsignal',
468   'strtod_l',
469   'strtoll_l',
470   'strtoull_l',
471   'symlink',
472   'timegm',
473   'unsetenv',
474   'uselocale',
475   'utimes',
476   'valloc',
477   'vasprintf',
478   'vsnprintf',
479   'wcrtomb',
480   'wcslen',
481   'wcsnlen',
482   'sysctlbyname',
483   '_NSGetEnviron',
484 ]
485
486 if glib_conf.has('HAVE_SYS_STATVFS_H')
487   functions += ['statvfs']
488 else
489   have_func_statvfs = false
490 endif
491 if glib_conf.has('HAVE_SYS_STATFS_H') or glib_conf.has('HAVE_SYS_MOUNT_H')
492   functions += ['statfs']
493 else
494   have_func_statfs = false
495 endif
496
497 if host_system == 'windows'
498   iphlpapi_dep = cc.find_library('iphlpapi')
499   iphlpapi_funcs = ['if_nametoindex', 'if_indextoname']
500   foreach ifunc : iphlpapi_funcs
501     iphl_prefix =  '''#define _WIN32_WINNT @0@
502       #include <winsock2.h>
503       #include <iphlpapi.h>'''.format(glib_conf.get('_WIN32_WINNT'))
504     if cc.has_function(ifunc,
505                        prefix : iphl_prefix,
506                        dependencies : iphlpapi_dep)
507       idefine = 'HAVE_' + ifunc.underscorify().to_upper()
508       glib_conf.set(idefine, 1)
509       glib_conf_prefix = glib_conf_prefix + '#define @0@ 1\n'.format(idefine)
510       set_variable('have_func_' + ifunc, true)
511     else
512       set_variable('have_func_' + ifunc, false)
513     endif
514   endforeach
515 else
516   functions += ['if_indextoname', 'if_nametoindex']
517 endif
518
519 # AIX splice is something else
520 if host_system != 'aix'
521   functions += ['splice']
522 endif
523
524 foreach f : functions
525   if cc.has_function(f)
526     define = 'HAVE_' + f.underscorify().to_upper()
527     glib_conf.set(define, 1)
528     glib_conf_prefix = glib_conf_prefix + '#define @0@ 1\n'.format(define)
529     set_variable('have_func_' + f, true)
530   else
531     set_variable('have_func_' + f, false)
532   endif
533 endforeach
534
535 # Check that stpcpy() is usable; must use header.
536 # cc.has_function() in some cases (clang, gcc 10+) assumes that if the
537 # compiler provides a builtin of the same name that the function exists, while
538 # it's in fact not provided by any header or library. This is true for
539 # stpcpy() on Windows using clang and gcc as well as posix_memalign() using
540 # gcc on Windows. Skip these checks on Windows for now to avoid false
541 # positives. See https://github.com/mesonbuild/meson/pull/7116,
542 # https://github.com/mesonbuild/meson/issues/3672 and
543 # https://github.com/mesonbuild/meson/issues/5628.
544 # FIXME: Once meson no longer returns success for stpcpy() and
545 # posix_memalign() on Windows using GCC and clang we can remove this.
546 if host_system != 'windows' and cc.has_function('stpcpy', prefix : '#include <string.h>')
547   glib_conf.set('HAVE_STPCPY', 1)
548 endif
549
550 # Check that posix_memalign() is usable; must use header
551 if host_system != 'windows' and cc.has_function('posix_memalign', prefix : '#include <stdlib.h>')
552   glib_conf.set('HAVE_POSIX_MEMALIGN', 1)
553 endif
554
555 # Check that posix_spawn() is usable; must use header
556 if cc.has_function('posix_spawn', prefix : '#include <spawn.h>')
557   glib_conf.set('HAVE_POSIX_SPAWN', 1)
558 endif
559
560 # Check whether strerror_r returns char *
561 if have_func_strerror_r
562   if cc.compiles('''#define _GNU_SOURCE
563                     #include <string.h>
564                     int func (void) {
565                       char error_string[256];
566                       char *ptr = strerror_r (-2, error_string, 256);
567                       char c = *strerror_r (-2, error_string, 256);
568                       return c != 0 && ptr != (void*) 0L;
569                     }
570                  ''',
571                  name : 'strerror_r() returns char *')
572     glib_conf.set('STRERROR_R_CHAR_P', 1,
573                   description: 'Defined if strerror_r returns char *')
574   endif
575 endif
576
577 # Special-case these functions that have alternative names on Windows/MSVC
578 if cc.has_function('snprintf') or cc.has_header_symbol('stdio.h', 'snprintf')
579   glib_conf.set('HAVE_SNPRINTF', 1)
580   glib_conf_prefix = glib_conf_prefix + '#define HAVE_SNPRINTF 1\n'
581 elif cc.has_function('_snprintf') or cc.has_header_symbol('stdio.h', '_snprintf')
582   hack_define = '1\n#define snprintf _snprintf'
583   glib_conf.set('HAVE_SNPRINTF', hack_define)
584   glib_conf_prefix = glib_conf_prefix + '#define HAVE_SNPRINTF ' + hack_define
585 endif
586
587 if cc.has_function('strcasecmp')
588   glib_conf.set('HAVE_STRCASECMP', 1)
589   glib_conf_prefix = glib_conf_prefix + '#define HAVE_STRCASECMP 1\n'
590 elif cc.has_function('_stricmp')
591   hack_define = '1\n#define strcasecmp _stricmp'
592   glib_conf.set('HAVE_STRCASECMP', hack_define)
593   glib_conf_prefix = glib_conf_prefix + '#define HAVE_STRCASECMP ' + hack_define
594 endif
595
596 if cc.has_function('strncasecmp')
597   glib_conf.set('HAVE_STRNCASECMP', 1)
598   glib_conf_prefix = glib_conf_prefix + '#define HAVE_STRNCASECMP 1\n'
599 elif cc.has_function('_strnicmp')
600   hack_define = '1\n#define strncasecmp _strnicmp'
601   glib_conf.set('HAVE_STRNCASECMP', hack_define)
602   glib_conf_prefix = glib_conf_prefix + '#define HAVE_STRNCASECMP ' + hack_define
603 endif
604
605 if cc.has_header_symbol('sys/sysmacros.h', 'major')
606   glib_conf.set('MAJOR_IN_SYSMACROS', 1)
607 elif cc.has_header_symbol('sys/mkdev.h', 'major')
608   glib_conf.set('MAJOR_IN_MKDEV', 1)
609 elif cc.has_header_symbol('sys/types.h', 'major')
610   glib_conf.set('MAJOR_IN_TYPES', 1)
611 endif
612
613 if cc.has_header_symbol('dlfcn.h', 'RTLD_LAZY')
614   glib_conf.set('HAVE_RTLD_LAZY', 1)
615 endif
616
617 if cc.has_header_symbol('dlfcn.h', 'RTLD_NOW')
618   glib_conf.set('HAVE_RTLD_NOW', 1)
619 endif
620
621 if cc.has_header_symbol('dlfcn.h', 'RTLD_GLOBAL')
622   glib_conf.set('HAVE_RTLD_GLOBAL', 1)
623 endif
624
625 have_rtld_next = false
626 if cc.has_header_symbol('dlfcn.h', 'RTLD_NEXT', args: '-D_GNU_SOURCE')
627   have_rtld_next = true
628   glib_conf.set('HAVE_RTLD_NEXT', 1)
629 endif
630
631 # Check whether to use statfs or statvfs
632 # Some systems have both statfs and statvfs, pick the most "native" for these
633 if have_func_statfs and have_func_statvfs
634   # on solaris and irix, statfs doesn't even have the f_bavail field
635   if not glib_conf.has('HAVE_STRUCT_STATFS_F_BAVAIL')
636     have_func_statfs = false
637   else
638     # at least on linux, statfs is the actual syscall
639     have_func_statvfs = false
640   endif
641 endif
642 if have_func_statfs
643   glib_conf.set('USE_STATFS', 1)
644   stat_func_to_use = 'statfs'
645 elif have_func_statvfs
646   glib_conf.set('USE_STATVFS', 1)
647   stat_func_to_use = 'statvfs'
648 else
649   stat_func_to_use = 'neither'
650 endif
651 message('Checking whether to use statfs or statvfs .. ' + stat_func_to_use)
652
653 if host_system == 'linux'
654   if cc.has_function('mkostemp',
655                      prefix: '''#define _GNU_SOURCE
656                                 #include <stdlib.h>''')
657     glib_conf.set('HAVE_MKOSTEMP', 1)
658   endif
659 endif
660
661 osx_ldflags = []
662 glib_have_os_x_9_or_later = false
663 glib_have_carbon = false
664 glib_have_cocoa = false
665 if host_system == 'darwin'
666   add_languages('objc')
667   objcc = meson.get_compiler('objc')
668
669   osx_ldflags += ['-Wl,-framework,CoreFoundation']
670
671   # Mac OS X Carbon support
672   glib_have_carbon = objcc.compiles('''#include <Carbon/Carbon.h>
673                                        #include <CoreServices/CoreServices.h>''',
674                                     name : 'Mac OS X Carbon support')
675
676   if glib_have_carbon
677     glib_conf.set('HAVE_CARBON', true)
678     osx_ldflags += '-Wl,-framework,Carbon'
679     glib_have_os_x_9_or_later = objcc.compiles('''#include <AvailabilityMacros.h>
680                                                   #if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
681                                                   #error Compiling for minimum OS X version before 10.9
682                                                   #endif''',
683                                                name : 'OS X 9 or later')
684   endif
685
686   # Mac OS X Cocoa support
687   glib_have_cocoa = objcc.compiles('''#include <Cocoa/Cocoa.h>
688                                       #ifdef GNUSTEP_BASE_VERSION
689                                       #error "Detected GNUstep, not Cocoa"
690                                       #endif''',
691                                    name : 'Mac OS X Cocoa support')
692
693   if glib_have_cocoa
694     glib_conf.set('HAVE_COCOA', true)
695     osx_ldflags += ['-Wl,-framework,Foundation', '-Wl,-framework,AppKit']
696   endif
697
698   # FIXME: libgio mix C and objC source files and there is no way to reliably
699   # know which language flags it's going to use to link. Add to both languages
700   # for now. See https://github.com/mesonbuild/meson/issues/3585.
701   add_project_link_arguments(osx_ldflags, language : ['objc', 'c'])
702 endif
703
704 # Check for futex(2)
705 if cc.links('''#include <linux/futex.h>
706                #include <sys/syscall.h>
707                #include <unistd.h>
708                int main (int argc, char ** argv) {
709                  syscall (__NR_futex, NULL, FUTEX_WAKE, FUTEX_WAIT);
710                  return 0;
711                }''', name : 'futex(2) system call')
712   glib_conf.set('HAVE_FUTEX', 1)
713 endif
714
715 # Check for eventfd(2)
716 if cc.links('''#include <sys/eventfd.h>
717                #include <unistd.h>
718                int main (int argc, char ** argv) {
719                  eventfd (0, EFD_CLOEXEC);
720                  return 0;
721                }''', name : 'eventfd(2) system call')
722   glib_conf.set('HAVE_EVENTFD', 1)
723 endif
724
725 clock_gettime_test_code = '''
726   #include <time.h>
727   struct timespec t;
728   int main (int argc, char ** argv) {
729     return clock_gettime(CLOCK_REALTIME, &t);
730   }'''
731 librt = []
732 if cc.links(clock_gettime_test_code, name : 'clock_gettime')
733   glib_conf.set('HAVE_CLOCK_GETTIME', 1)
734 elif cc.links(clock_gettime_test_code, args : '-lrt', name : 'clock_gettime in librt')
735   glib_conf.set('HAVE_CLOCK_GETTIME', 1)
736   librt = cc.find_library('rt')
737 endif
738
739 dlopen_dlsym_test_code = '''
740 #include <dlfcn.h>
741 int glib_underscore_test (void) { return 42; }
742 int main (int argc, char ** argv) {
743   void *f1 = (void*)0, *f2 = (void*)0, *handle;
744   handle = dlopen ((void*)0, 0);
745   if (handle) {
746     f1 = dlsym (handle, "glib_underscore_test");
747     f2 = dlsym (handle, "_glib_underscore_test");
748   }
749   return (!f2 || f1);
750 }'''
751 libdl_dep = []
752 if cc.links(dlopen_dlsym_test_code, name : 'dlopen() and dlsym() in system libraries')
753   have_dlopen_dlsym = true
754 elif cc.links(dlopen_dlsym_test_code, args : '-ldl', name : 'dlopen() and dlsym() in libdl')
755   have_dlopen_dlsym = true
756   libdl_dep = cc.find_library('dl')
757 else
758   have_dlopen_dlsym = false
759 endif
760
761 # if statfs() takes 2 arguments (Posix) or 4 (Solaris)
762 if have_func_statfs
763   if cc.compiles(glib_conf_prefix + '''
764                  #include <unistd.h>
765                         #ifdef HAVE_SYS_PARAM_H
766                         #include <sys/param.h>
767                         #endif
768                         #ifdef HAVE_SYS_VFS_H
769                         #include <sys/vfs.h>
770                         #endif
771                         #ifdef HAVE_SYS_MOUNT_H
772                         #include <sys/mount.h>
773                         #endif
774                         #ifdef HAVE_SYS_STATFS_H
775                         #include <sys/statfs.h>
776                         #endif
777                         void some_func (void) {
778                           struct statfs st;
779                           statfs("/", &st);
780                         }''', name : 'number of arguments to statfs() (n=2)')
781     glib_conf.set('STATFS_ARGS', 2)
782   elif cc.compiles(glib_conf_prefix + '''
783                    #include <unistd.h>
784                           #ifdef HAVE_SYS_PARAM_H
785                           #include <sys/param.h>
786                           #endif
787                           #ifdef HAVE_SYS_VFS_H
788                           #include <sys/vfs.h>
789                           #endif
790                           #ifdef HAVE_SYS_MOUNT_H
791                           #include <sys/mount.h>
792                           #endif
793                           #ifdef HAVE_SYS_STATFS_H
794                           #include <sys/statfs.h>
795                           #endif
796                           void some_func (void) {
797                             struct statfs st;
798                             statfs("/", &st, sizeof (st), 0);
799                           }''', name : 'number of arguments to statfs() (n=4)')
800     glib_conf.set('STATFS_ARGS', 4)
801   else
802     error('Unable to determine number of arguments to statfs()')
803   endif
804 endif
805
806 # open takes O_DIRECTORY as an option
807 #AC_MSG_CHECKING([])
808 if cc.compiles('''#include <fcntl.h>
809                   #include <sys/types.h>
810                   #include <sys/stat.h>
811                   void some_func (void) {
812                     open(0, O_DIRECTORY, 0);
813                   }''', name : 'open() option O_DIRECTORY')
814   glib_conf.set('HAVE_OPEN_O_DIRECTORY', 1)
815 endif
816
817 # Check whether there is a vsnprintf() function with C99 semantics installed.
818 # (similar tests to AC_FUNC_VSNPRINTF_C99)
819 # Check whether there is a snprintf() function with C99 semantics installed.
820 # (similar tests to AC_FUNC_SNPRINTF_C99)
821 # Check whether there is a printf() function with Unix98 semantics installed.
822 # (similar tests to AC_FUNC_PRINTF_UNIX98)
823 have_good_vsnprintf = false
824 have_good_snprintf = false
825 have_good_printf = false
826
827 if host_system == 'windows' and (cc.get_id() == 'msvc' or cc.get_id() == 'clang-cl')
828   # Unfortunately the Visual Studio 2015+ implementations of C99-style
829   # snprintf and vsnprintf don't seem to be quite good enough.
830   # (Sorry, I don't know exactly what is the problem,
831   # but it is related to floating point formatting and decimal point vs. comma.)
832   # The simple tests in AC_FUNC_VSNPRINTF_C99 and AC_FUNC_SNPRINTF_C99 aren't
833   # rigorous enough to notice, though.
834   glib_conf.set('HAVE_C99_SNPRINTF', false)
835   glib_conf.set('HAVE_C99_VSNPRINTF', false)
836   glib_conf.set('HAVE_UNIX98_PRINTF', false)
837 elif not cc_can_run and host_system in ['ios', 'darwin']
838   # All these are true when compiling natively on macOS, so we should use good
839   # defaults when building for iOS and tvOS.
840   glib_conf.set('HAVE_C99_SNPRINTF', true)
841   glib_conf.set('HAVE_C99_VSNPRINTF', true)
842   glib_conf.set('HAVE_UNIX98_PRINTF', true)
843   have_good_vsnprintf = true
844   have_good_snprintf = true
845   have_good_printf = true
846 else
847   vsnprintf_c99_test_code = '''
848 #include <stdio.h>
849 #include <stdarg.h>
850
851 int
852 doit(char * s, ...)
853 {
854   char buffer[32];
855   va_list args;
856   int r;
857
858   va_start(args, s);
859   r = vsnprintf(buffer, 5, s, args);
860   va_end(args);
861
862   if (r != 7)
863     exit(1);
864
865   /* AIX 5.1 and Solaris seems to have a half-baked vsnprintf()
866      implementation. The above will return 7 but if you replace
867      the size of the buffer with 0, it borks! */
868   va_start(args, s);
869   r = vsnprintf(buffer, 0, s, args);
870   va_end(args);
871
872   if (r != 7)
873     exit(1);
874
875   exit(0);
876 }
877
878 int
879 main(void)
880 {
881   doit("1234567");
882   exit(1);
883 }'''
884
885   if cc_can_run
886     rres = cc.run(vsnprintf_c99_test_code, name : 'C99 vsnprintf')
887     if rres.compiled() and rres.returncode() == 0
888       glib_conf.set('HAVE_C99_VSNPRINTF', 1)
889       have_good_vsnprintf = true
890     endif
891   else
892       have_good_vsnprintf = meson.get_cross_property('have_c99_vsnprintf', false)
893       glib_conf.set('HAVE_C99_VSNPRINTF', have_good_vsnprintf)
894   endif
895
896   snprintf_c99_test_code = '''
897 #include <stdio.h>
898 #include <stdarg.h>
899
900 int
901 doit()
902 {
903   char buffer[32];
904   va_list args;
905   int r;
906
907   r = snprintf(buffer, 5, "1234567");
908
909   if (r != 7)
910     exit(1);
911
912   r = snprintf(buffer, 0, "1234567");
913
914   if (r != 7)
915     exit(1);
916
917   r = snprintf(NULL, 0, "1234567");
918
919   if (r != 7)
920     exit(1);
921
922   exit(0);
923 }
924
925 int
926 main(void)
927 {
928   doit();
929   exit(1);
930 }'''
931
932   if cc_can_run
933     rres = cc.run(snprintf_c99_test_code, name : 'C99 snprintf')
934     if rres.compiled() and rres.returncode() == 0
935       glib_conf.set('HAVE_C99_SNPRINTF', 1)
936       have_good_snprintf = true
937     endif
938   else
939       have_good_snprintf = meson.get_cross_property('have_c99_snprintf', false)
940       glib_conf.set('HAVE_C99_SNPRINTF', have_good_snprintf)
941   endif
942
943   printf_unix98_test_code = '''
944 #include <stdio.h>
945
946 int
947 main (void)
948 {
949   char buffer[128];
950
951   sprintf (buffer, "%2\$d %3\$d %1\$d", 1, 2, 3);
952   if (strcmp ("2 3 1", buffer) == 0)
953     exit (0);
954   exit (1);
955 }'''
956
957   if cc_can_run
958     rres = cc.run(printf_unix98_test_code, name : 'Unix98 printf positional parameters')
959     if rres.compiled() and rres.returncode() == 0
960       glib_conf.set('HAVE_UNIX98_PRINTF', 1)
961       have_good_printf = true
962     endif
963   else
964       have_good_printf = meson.get_cross_property('have_unix98_printf', false)
965       glib_conf.set('HAVE_UNIX98_PRINTF', have_good_printf)
966   endif
967 endif
968
969 if host_system == 'windows'
970   glib_conf.set_quoted('EXEEXT', '.exe')
971 else
972   glib_conf.set('EXEEXT', '')
973 endif
974
975 # Our printf is 'good' only if vsnpintf()/snprintf()/printf() supports C99 well enough
976 use_system_printf = have_good_vsnprintf and have_good_snprintf and have_good_printf
977 glib_conf.set('USE_SYSTEM_PRINTF', use_system_printf)
978 glibconfig_conf.set('GLIB_USING_SYSTEM_PRINTF', use_system_printf)
979
980 if not use_system_printf
981   # gnulib has vasprintf so override the previous check
982   glib_conf.set('HAVE_VASPRINTF', 1)
983 endif
984
985 # Check for nl_langinfo and CODESET
986 if cc.links('''#include <langinfo.h>
987                int main (int argc, char ** argv) {
988                  char *codeset = nl_langinfo (CODESET);
989                  return 0;
990                }''', name : 'nl_langinfo and CODESET')
991   glib_conf.set('HAVE_LANGINFO_CODESET', 1)
992   glib_conf.set('HAVE_CODESET', 1)
993 endif
994
995 # Check for nl_langinfo and LC_TIME parts that are needed in gdatetime.c
996 if cc.links('''#include <langinfo.h>
997                int main (int argc, char ** argv) {
998                  char *str;
999                  str = nl_langinfo (PM_STR);
1000                  str = nl_langinfo (D_T_FMT);
1001                  str = nl_langinfo (D_FMT);
1002                  str = nl_langinfo (T_FMT);
1003                  str = nl_langinfo (T_FMT_AMPM);
1004                  str = nl_langinfo (MON_1);
1005                  str = nl_langinfo (ABMON_12);
1006                  str = nl_langinfo (DAY_1);
1007                  str = nl_langinfo (ABDAY_7);
1008                  return 0;
1009                }''', name : 'nl_langinfo (PM_STR)')
1010   glib_conf.set('HAVE_LANGINFO_TIME', 1)
1011 endif
1012 if cc.links('''#include <langinfo.h>
1013                int main (int argc, char ** argv) {
1014                  char *str;
1015                  str = nl_langinfo (_NL_CTYPE_OUTDIGIT0_MB);
1016                  str = nl_langinfo (_NL_CTYPE_OUTDIGIT1_MB);
1017                  str = nl_langinfo (_NL_CTYPE_OUTDIGIT2_MB);
1018                  str = nl_langinfo (_NL_CTYPE_OUTDIGIT3_MB);
1019                  str = nl_langinfo (_NL_CTYPE_OUTDIGIT4_MB);
1020                  str = nl_langinfo (_NL_CTYPE_OUTDIGIT5_MB);
1021                  str = nl_langinfo (_NL_CTYPE_OUTDIGIT6_MB);
1022                  str = nl_langinfo (_NL_CTYPE_OUTDIGIT7_MB);
1023                  str = nl_langinfo (_NL_CTYPE_OUTDIGIT8_MB);
1024                  str = nl_langinfo (_NL_CTYPE_OUTDIGIT9_MB);
1025                  return 0;
1026                }''', name : 'nl_langinfo (_NL_CTYPE_OUTDIGITn_MB)')
1027   glib_conf.set('HAVE_LANGINFO_OUTDIGIT', 1)
1028 endif
1029
1030 # Check for nl_langinfo and alternative month names
1031 if cc.links('''#ifndef _GNU_SOURCE
1032               # define _GNU_SOURCE
1033               #endif
1034               #include <langinfo.h>
1035                int main (int argc, char ** argv) {
1036                  char *str;
1037                  str = nl_langinfo (ALTMON_1);
1038                  str = nl_langinfo (ALTMON_2);
1039                  str = nl_langinfo (ALTMON_3);
1040                  str = nl_langinfo (ALTMON_4);
1041                  str = nl_langinfo (ALTMON_5);
1042                  str = nl_langinfo (ALTMON_6);
1043                  str = nl_langinfo (ALTMON_7);
1044                  str = nl_langinfo (ALTMON_8);
1045                  str = nl_langinfo (ALTMON_9);
1046                  str = nl_langinfo (ALTMON_10);
1047                  str = nl_langinfo (ALTMON_11);
1048                  str = nl_langinfo (ALTMON_12);
1049                  return 0;
1050                }''', name : 'nl_langinfo (ALTMON_n)')
1051   glib_conf.set('HAVE_LANGINFO_ALTMON', 1)
1052 endif
1053
1054 # Check for nl_langinfo and abbreviated alternative month names
1055 if cc.links('''#ifndef _GNU_SOURCE
1056               # define _GNU_SOURCE
1057               #endif
1058               #include <langinfo.h>
1059                int main (int argc, char ** argv) {
1060                  char *str;
1061                  str = nl_langinfo (_NL_ABALTMON_1);
1062                  str = nl_langinfo (_NL_ABALTMON_2);
1063                  str = nl_langinfo (_NL_ABALTMON_3);
1064                  str = nl_langinfo (_NL_ABALTMON_4);
1065                  str = nl_langinfo (_NL_ABALTMON_5);
1066                  str = nl_langinfo (_NL_ABALTMON_6);
1067                  str = nl_langinfo (_NL_ABALTMON_7);
1068                  str = nl_langinfo (_NL_ABALTMON_8);
1069                  str = nl_langinfo (_NL_ABALTMON_9);
1070                  str = nl_langinfo (_NL_ABALTMON_10);
1071                  str = nl_langinfo (_NL_ABALTMON_11);
1072                  str = nl_langinfo (_NL_ABALTMON_12);
1073                  return 0;
1074                }''', name : 'nl_langinfo (_NL_ABALTMON_n)')
1075   glib_conf.set('HAVE_LANGINFO_ABALTMON', 1)
1076 endif
1077
1078 # Check if C compiler supports the 'signed' keyword
1079 if not cc.compiles('''signed char x;''', name : 'signed')
1080   glib_conf.set('signed', '/* NOOP */')
1081 endif
1082
1083 # Check if the ptrdiff_t type exists
1084 if cc.has_header_symbol('stddef.h', 'ptrdiff_t')
1085   glib_conf.set('HAVE_PTRDIFF_T', 1)
1086 endif
1087
1088 # Check for sig_atomic_t type
1089 if cc.links('''#include <signal.h>
1090                #include <sys/types.h>
1091                sig_atomic_t val = 42;
1092                int main (int argc, char ** argv) {
1093                  return val == 42 ? 0 : 1;
1094                }''', name : 'sig_atomic_t')
1095   glib_conf.set('HAVE_SIG_ATOMIC_T', 1)
1096 endif
1097
1098 # Check if 'long long' works
1099 # jm_AC_TYPE_LONG_LONG
1100 if cc.compiles('''long long ll = 1LL;
1101                   int i = 63;
1102                   int some_func (void) {
1103                     long long llmax = (long long) -1;
1104                     return ll << i | ll >> i | llmax / ll | llmax % ll;
1105                   }''', name : 'long long')
1106   glib_conf.set('HAVE_LONG_LONG', 1)
1107   have_long_long = true
1108 else
1109   have_long_long = false
1110 endif
1111
1112 # Test whether the compiler supports the 'long double' type.
1113 if cc.compiles('''/* The Stardent Vistra knows sizeof(long double), but does not support it.  */
1114                   long double foo = 0.0;
1115                   /* On Ultrix 4.3 cc, long double is 4 and double is 8.  */
1116                   int array [2*(sizeof(long double) >= sizeof(double)) - 1];''',
1117                name : 'long double')
1118   glib_conf.set('HAVE_LONG_DOUBLE', 1)
1119 endif
1120
1121 # Test whether <stddef.h> has the 'wchar_t' type.
1122 if cc.has_header_symbol('stddef.h', 'wchar_t')
1123   glib_conf.set('HAVE_WCHAR_T', 1)
1124 endif
1125
1126 # Test whether <wchar.h> has the 'wint_t' type.
1127 if cc.has_header_symbol('wchar.h', 'wint_t')
1128   glib_conf.set('HAVE_WINT_T', 1)
1129 endif
1130
1131 found_uintmax_t = false
1132
1133 # Define HAVE_INTTYPES_H_WITH_UINTMAX if <inttypes.h> exists,
1134 # doesn't clash with <sys/types.h>, and declares uintmax_t.
1135 # jm_AC_HEADER_INTTYPES_H
1136 if cc.compiles('''#include <sys/types.h>
1137                   #include <inttypes.h>
1138                   void some_func (void) {
1139                     uintmax_t i = (uintmax_t) -1;
1140                   }''', name : 'uintmax_t in inttypes.h')
1141   glib_conf.set('HAVE_INTTYPES_H_WITH_UINTMAX', 1)
1142   found_uintmax_t = true
1143 endif
1144
1145 # Define HAVE_STDINT_H_WITH_UINTMAX if <stdint.h> exists,
1146 # doesn't clash with <sys/types.h>, and declares uintmax_t.
1147 # jm_AC_HEADER_STDINT_H
1148 if cc.compiles('''#include <sys/types.h>
1149                   #include <stdint.h>
1150                   void some_func (void) {
1151                     uintmax_t i = (uintmax_t) -1;
1152                   }''', name : 'uintmax_t in stdint.h')
1153   glib_conf.set('HAVE_STDINT_H_WITH_UINTMAX', 1)
1154   found_uintmax_t = true
1155 endif
1156
1157 # Define intmax_t to 'long' or 'long long'
1158 # if it is not already defined in <stdint.h> or <inttypes.h>.
1159 # For simplicity, we assume that a header file defines 'intmax_t' if and
1160 # only if it defines 'uintmax_t'.
1161 if found_uintmax_t
1162   glib_conf.set('HAVE_INTMAX_T', 1)
1163 elif have_long_long
1164   glib_conf.set('intmax_t', 'long long')
1165 else
1166   glib_conf.set('intmax_t', 'long')
1167 endif
1168
1169 char_size = cc.sizeof('char')
1170 short_size = cc.sizeof('short')
1171 int_size = cc.sizeof('int')
1172 voidp_size = cc.sizeof('void*')
1173 long_size = cc.sizeof('long')
1174 if have_long_long
1175   long_long_size = cc.sizeof('long long')
1176 else
1177   long_long_size = 0
1178 endif
1179 sizet_size = cc.sizeof('size_t')
1180 if cc.get_id() == 'msvc' or cc.get_id() == 'clang-cl'
1181   ssizet_size = cc.sizeof('SSIZE_T', prefix : '#include <BaseTsd.h>')
1182 else
1183   ssizet_size = cc.sizeof('ssize_t')
1184 endif
1185
1186 # Some platforms (Apple) hard-code int64_t to long long instead of
1187 # using long on 64-bit architectures. This can cause type mismatch
1188 # warnings when trying to interface with code using the standard
1189 # library type. Test for the warnings and set gint64 to whichever
1190 # works.
1191 if long_long_size == long_size
1192   if cc.compiles('''#if defined(_AIX) && !defined(__GNUC__)
1193                     #pragma options langlvl=stdc99
1194                     #endif
1195                     #pragma GCC diagnostic error "-Wincompatible-pointer-types"
1196                     #include <stdint.h>
1197                     #include <stdio.h>
1198                     int main () {
1199                       int64_t i1 = 1;
1200                       long *i2 = &i1;
1201                       return 1;
1202                     }''', name : 'int64_t is long')
1203     int64_t_typedef = 'long'
1204   elif cc.compiles('''#if defined(_AIX) && !defined(__GNUC__)
1205                       #pragma options langlvl=stdc99
1206                       #endif
1207                       #pragma GCC diagnostic error "-Wincompatible-pointer-types"
1208                       #include <stdint.h>
1209                       #include <stdio.h>
1210                       int main () {
1211                         int64_t i1 = 1;
1212                         long long *i2 = &i1;
1213                         return 1;
1214                       }''', name : 'int64_t is long long')
1215     int64_t_typedef = 'long long'
1216   endif
1217 endif
1218
1219 int64_m = 'll'
1220 char_align = cc.alignment('char')
1221 short_align = cc.alignment('short')
1222 int_align = cc.alignment('int')
1223 voidp_align = cc.alignment('void*')
1224 long_align = cc.alignment('long')
1225 long_long_align = cc.alignment('long long')
1226 # NOTE: We don't check for size of __int64 because long long is guaranteed to
1227 # be 64-bit in C99, and it is available on all supported compilers
1228 sizet_align = cc.alignment('size_t')
1229
1230 glib_conf.set('ALIGNOF_UNSIGNED_LONG', long_align)
1231
1232 glib_conf.set('SIZEOF_CHAR', char_size)
1233 glib_conf.set('SIZEOF_INT', int_size)
1234 glib_conf.set('SIZEOF_SHORT', short_size)
1235 glib_conf.set('SIZEOF_LONG', long_size)
1236 glib_conf.set('SIZEOF_LONG_LONG', long_long_size)
1237 glib_conf.set('SIZEOF_SIZE_T', sizet_size)
1238 glib_conf.set('SIZEOF_SSIZE_T', ssizet_size)
1239 glib_conf.set('SIZEOF_VOID_P', voidp_size)
1240 glib_conf.set('SIZEOF_WCHAR_T', cc.sizeof('wchar_t', prefix: '#include <stddef.h>'))
1241
1242 if short_size == 2
1243   gint16 = 'short'
1244   gint16_modifier='h'
1245   gint16_format='hi'
1246   guint16_format='hu'
1247 elif int_size == 2
1248   gint16 = 'int'
1249   gint16_modifier=''
1250   gint16_format='i'
1251   guint16_format='u'
1252 else
1253   error('Compiler provides no native 16-bit integer type')
1254 endif
1255 glibconfig_conf.set('gint16', gint16)
1256 glibconfig_conf.set_quoted('gint16_modifier', gint16_modifier)
1257 glibconfig_conf.set_quoted('gint16_format', gint16_format)
1258 glibconfig_conf.set_quoted('guint16_format', guint16_format)
1259
1260 if short_size == 4
1261   gint32 = 'short'
1262   gint32_modifier='h'
1263   gint32_format='hi'
1264   guint32_format='hu'
1265   guint32_align = short_align
1266 elif int_size == 4
1267   gint32 = 'int'
1268   gint32_modifier=''
1269   gint32_format='i'
1270   guint32_format='u'
1271   guint32_align = int_align
1272 elif long_size == 4
1273   gint32 = 'long'
1274   gint32_modifier='l'
1275   gint32_format='li'
1276   guint32_format='lu'
1277   guint32_align = long_align
1278 else
1279   error('Compiler provides no native 32-bit integer type')
1280 endif
1281 glibconfig_conf.set('gint32', gint32)
1282 glibconfig_conf.set_quoted('gint32_modifier', gint32_modifier)
1283 glibconfig_conf.set_quoted('gint32_format', gint32_format)
1284 glibconfig_conf.set_quoted('guint32_format', guint32_format)
1285 glib_conf.set('ALIGNOF_GUINT32', guint32_align)
1286
1287 if int_size == 8
1288   gint64 = 'int'
1289   gint64_modifier=''
1290   gint64_format='i'
1291   guint64_format='u'
1292   glib_extension=''
1293   gint64_constant='(val)'
1294   guint64_constant='(val)'
1295   guint64_align = int_align
1296 elif long_size == 8 and (long_long_size != long_size or int64_t_typedef == 'long')
1297   gint64 = 'long'
1298   glib_extension=''
1299   gint64_modifier='l'
1300   gint64_format='li'
1301   guint64_format='lu'
1302   gint64_constant='(val##L)'
1303   guint64_constant='(val##UL)'
1304   guint64_align = long_align
1305 elif long_long_size == 8 and (long_long_size != long_size or int64_t_typedef == 'long long')
1306   gint64 = 'long long'
1307   glib_extension='G_GNUC_EXTENSION '
1308   gint64_modifier=int64_m
1309   gint64_format=int64_m + 'i'
1310   guint64_format=int64_m + 'u'
1311   gint64_constant='(G_GNUC_EXTENSION (val##LL))'
1312   guint64_constant='(G_GNUC_EXTENSION (val##ULL))'
1313   guint64_align = long_long_align
1314 else
1315   error('Compiler provides no native 64-bit integer type')
1316 endif
1317 glibconfig_conf.set('glib_extension', glib_extension)
1318 glibconfig_conf.set('gint64', gint64)
1319 glibconfig_conf.set_quoted('gint64_modifier', gint64_modifier)
1320 glibconfig_conf.set_quoted('gint64_format', gint64_format)
1321 glibconfig_conf.set_quoted('guint64_format', guint64_format)
1322 glibconfig_conf.set('gint64_constant', gint64_constant)
1323 glibconfig_conf.set('guint64_constant', guint64_constant)
1324 glib_conf.set('ALIGNOF_GUINT64', guint64_align)
1325
1326 if host_system == 'windows'
1327   glibconfig_conf.set('g_pid_type', 'void*')
1328   glibconfig_conf.set_quoted('g_pid_format', 'p')
1329   if host_machine.cpu_family() == 'x86_64'
1330     glibconfig_conf.set_quoted('g_pollfd_format', '%#' + int64_m + 'x')
1331   else
1332     glibconfig_conf.set_quoted('g_pollfd_format', '%#x')
1333   endif
1334   glibconfig_conf.set('g_dir_separator', '\\\\')
1335   glibconfig_conf.set('g_searchpath_separator', ';')
1336 else
1337   glibconfig_conf.set('g_pid_type', 'int')
1338   glibconfig_conf.set_quoted('g_pid_format', 'i')
1339   glibconfig_conf.set_quoted('g_pollfd_format', '%d')
1340   glibconfig_conf.set('g_dir_separator', '/')
1341   glibconfig_conf.set('g_searchpath_separator', ':')
1342 endif
1343
1344 g_sizet_compatibility = {
1345   'short': sizet_size == short_size,
1346   'int': sizet_size == int_size,
1347   'long': sizet_size == long_size,
1348   'long long': sizet_size == long_long_size,
1349 }
1350
1351 # Do separate checks for gcc/clang (and ignore other compilers for now), since
1352 # we need to explicitly pass -Werror to the compilers.
1353 # FIXME: https://github.com/mesonbuild/meson/issues/5399
1354 # We can’t simplify these checks using a foreach loop because dictionary keys
1355 # have to be string literals.
1356 # FIXME: https://github.com/mesonbuild/meson/issues/5231
1357 if cc.get_id() == 'gcc' or cc.get_id() == 'clang'
1358   g_sizet_compatibility += {
1359     'short': g_sizet_compatibility['short'] and cc.compiles(
1360         '''#include <stddef.h>
1361         size_t f (size_t *i) { return *i + 1; }
1362         int main (void) {
1363           unsigned short i = 0;
1364           f (&i);
1365           return 0;
1366         }''',
1367         args: ['-Werror'],
1368         name : 'GCC size_t typedef is short'),
1369     'int': g_sizet_compatibility['int'] and cc.compiles(
1370         '''#include <stddef.h>
1371         size_t f (size_t *i) { return *i + 1; }
1372         int main (void) {
1373           unsigned int i = 0;
1374           f (&i);
1375           return 0;
1376         }''',
1377         args: ['-Werror'],
1378         name : 'GCC size_t typedef is int'),
1379     'long': g_sizet_compatibility['long'] and cc.compiles(
1380         '''#include <stddef.h>
1381         size_t f (size_t *i) { return *i + 1; }
1382         int main (void) {
1383           unsigned long i = 0;
1384           f (&i);
1385           return 0;
1386         }''',
1387         args: ['-Werror'],
1388         name : 'GCC size_t typedef is long'),
1389     'long long': g_sizet_compatibility['long long'] and cc.compiles(
1390         '''#include <stddef.h>
1391         size_t f (size_t *i) { return *i + 1; }
1392         int main (void) {
1393           unsigned long long i = 0;
1394           f (&i);
1395           return 0;
1396         }''',
1397         args: ['-Werror'],
1398         name : 'GCC size_t typedef is long long'),
1399   }
1400 endif
1401
1402 if g_sizet_compatibility['short']
1403   glibconfig_conf.set('glib_size_type_define', 'short')
1404   glibconfig_conf.set_quoted('gsize_modifier', 'h')
1405   glibconfig_conf.set_quoted('gssize_modifier', 'h')
1406   glibconfig_conf.set_quoted('gsize_format', 'hu')
1407   glibconfig_conf.set_quoted('gssize_format', 'hi')
1408   glibconfig_conf.set('glib_msize_type', 'SHRT')
1409 elif g_sizet_compatibility['int']
1410   glibconfig_conf.set('glib_size_type_define', 'int')
1411   glibconfig_conf.set_quoted('gsize_modifier', '')
1412   glibconfig_conf.set_quoted('gssize_modifier', '')
1413   glibconfig_conf.set_quoted('gsize_format', 'u')
1414   glibconfig_conf.set_quoted('gssize_format', 'i')
1415   glibconfig_conf.set('glib_msize_type', 'INT')
1416 elif g_sizet_compatibility['long']
1417   glibconfig_conf.set('glib_size_type_define', 'long')
1418   glibconfig_conf.set_quoted('gsize_modifier', 'l')
1419   glibconfig_conf.set_quoted('gssize_modifier', 'l')
1420   glibconfig_conf.set_quoted('gsize_format', 'lu')
1421   glibconfig_conf.set_quoted('gssize_format', 'li')
1422   glibconfig_conf.set('glib_msize_type', 'LONG')
1423 elif g_sizet_compatibility['long long']
1424   glibconfig_conf.set('glib_size_type_define', 'long long')
1425   glibconfig_conf.set_quoted('gsize_modifier', int64_m)
1426   glibconfig_conf.set_quoted('gssize_modifier', int64_m)
1427   glibconfig_conf.set_quoted('gsize_format', int64_m + 'u')
1428   glibconfig_conf.set_quoted('gssize_format', int64_m + 'i')
1429   glibconfig_conf.set('glib_msize_type', 'INT64')
1430 else
1431   error('Could not determine size of size_t.')
1432 endif
1433
1434 if voidp_size == int_size
1435   glibconfig_conf.set('glib_intptr_type_define', 'int')
1436   glibconfig_conf.set_quoted('gintptr_modifier', '')
1437   glibconfig_conf.set_quoted('gintptr_format', 'i')
1438   glibconfig_conf.set_quoted('guintptr_format', 'u')
1439   glibconfig_conf.set('glib_gpi_cast', '(gint)')
1440   glibconfig_conf.set('glib_gpui_cast', '(guint)')
1441 elif voidp_size == long_size
1442   glibconfig_conf.set('glib_intptr_type_define', 'long')
1443   glibconfig_conf.set_quoted('gintptr_modifier', 'l')
1444   glibconfig_conf.set_quoted('gintptr_format', 'li')
1445   glibconfig_conf.set_quoted('guintptr_format', 'lu')
1446   glibconfig_conf.set('glib_gpi_cast', '(glong)')
1447   glibconfig_conf.set('glib_gpui_cast', '(gulong)')
1448 elif voidp_size == long_long_size
1449   glibconfig_conf.set('glib_intptr_type_define', 'long long')
1450   glibconfig_conf.set_quoted('gintptr_modifier', int64_m)
1451   glibconfig_conf.set_quoted('gintptr_format', int64_m + 'i')
1452   glibconfig_conf.set_quoted('guintptr_format', int64_m + 'u')
1453   glibconfig_conf.set('glib_gpi_cast', '(gint64)')
1454   glibconfig_conf.set('glib_gpui_cast', '(guint64)')
1455 else
1456   error('Could not determine size of void *')
1457 endif
1458
1459 if long_size != 8 and long_long_size != 8 and int_size != 8
1460   error('GLib requires a 64-bit type. You might want to consider using the GNU C compiler.')
1461 endif
1462
1463 glibconfig_conf.set('gintbits', int_size * 8)
1464 glibconfig_conf.set('glongbits', long_size * 8)
1465 glibconfig_conf.set('gsizebits', sizet_size * 8)
1466 glibconfig_conf.set('gssizebits', ssizet_size * 8)
1467
1468 # XXX: https://gitlab.gnome.org/GNOME/glib/issues/1413
1469 if host_system == 'windows'
1470   g_module_suffix = 'dll'
1471 else
1472   g_module_suffix = 'so'
1473 endif
1474 glibconfig_conf.set('g_module_suffix', g_module_suffix)
1475
1476 glibconfig_conf.set('GLIB_MAJOR_VERSION', major_version)
1477 glibconfig_conf.set('GLIB_MINOR_VERSION', minor_version)
1478 glibconfig_conf.set('GLIB_MICRO_VERSION', micro_version)
1479 glibconfig_conf.set('GLIB_VERSION', glib_version)
1480
1481 glibconfig_conf.set('glib_void_p', voidp_size)
1482 glibconfig_conf.set('glib_long', long_size)
1483 glibconfig_conf.set('glib_size_t', sizet_size)
1484 glibconfig_conf.set('glib_ssize_t', ssizet_size)
1485 if host_machine.endian() == 'big'
1486   glibconfig_conf.set('g_byte_order', 'G_BIG_ENDIAN')
1487   glibconfig_conf.set('g_bs_native', 'BE')
1488   glibconfig_conf.set('g_bs_alien', 'LE')
1489 else
1490   glibconfig_conf.set('g_byte_order', 'G_LITTLE_ENDIAN')
1491   glibconfig_conf.set('g_bs_native', 'LE')
1492   glibconfig_conf.set('g_bs_alien', 'BE')
1493 endif
1494
1495 # === va_copy checks ===
1496 # we currently check for all three va_copy possibilities, so we get
1497 # all results in config.log for bug reports.
1498
1499 va_copy_func = ''
1500 foreach try_func : [ '__va_copy', 'va_copy' ]
1501   if cc.compiles('''#include <stdarg.h>
1502                     #include <stdlib.h>
1503                     #ifdef _MSC_VER
1504                     # include "msvc_recommended_pragmas.h"
1505                     #endif
1506                     void f (int i, ...) {
1507                     va_list args1, args2;
1508                     va_start (args1, i);
1509                     @0@ (args2, args1);
1510                     if (va_arg (args2, int) != 42 || va_arg (args1, int) != 42)
1511                       exit (1);
1512                     va_end (args1); va_end (args2);
1513                     }
1514                     int main() {
1515                       f (0, 42);
1516                       return 0;
1517                     }'''.format(try_func),
1518                     name : try_func + ' check')
1519     va_copy_func = try_func
1520   endif
1521 endforeach
1522 if va_copy_func != ''
1523   glib_conf.set('G_VA_COPY', va_copy_func)
1524   glib_vacopy = '#define G_VA_COPY ' + va_copy_func
1525 else
1526   glib_vacopy = '/* #undef G_VA_COPY */'
1527 endif
1528
1529 va_list_val_copy_prog = '''
1530   #include <stdarg.h>
1531   #include <stdlib.h>
1532   void f (int i, ...) {
1533     va_list args1, args2;
1534     va_start (args1, i);
1535     args2 = args1;
1536     if (va_arg (args2, int) != 42 || va_arg (args1, int) != 42)
1537       exit (1);
1538     va_end (args1); va_end (args2);
1539   }
1540   int main() {
1541     f (0, 42);
1542     return 0;
1543   }'''
1544
1545 if cc_can_run
1546   rres = cc.run(va_list_val_copy_prog, name : 'va_lists can be copied as values')
1547   glib_va_val_copy = rres.returncode() == 0
1548 else
1549   glib_va_val_copy = meson.get_cross_property('va_val_copy', true)
1550 endif
1551 if not glib_va_val_copy
1552   glib_vacopy = glib_vacopy + '\n#define G_VA_COPY_AS_ARRAY 1'
1553   glib_conf.set('G_VA_COPY_AS_ARRAY', 1)
1554 endif
1555 glibconfig_conf.set('glib_vacopy', glib_vacopy)
1556
1557 # check for flavours of varargs macros
1558 g_have_iso_c_varargs = cc.compiles('''
1559   void some_func (void) {
1560     int a(int p1, int p2, int p3);
1561     #define call_a(...) a(1,__VA_ARGS__)
1562     call_a(2,3);
1563   }''', name : 'ISO C99 varargs macros in C')
1564
1565 if g_have_iso_c_varargs
1566   glibconfig_conf.set('g_have_iso_c_varargs', '''
1567 #ifndef __cplusplus
1568 # define G_HAVE_ISO_VARARGS 1
1569 #endif''')
1570 endif
1571
1572 g_have_iso_cxx_varargs = cxx.compiles('''
1573   void some_func (void) {
1574     int a(int p1, int p2, int p3);
1575     #define call_a(...) a(1,__VA_ARGS__)
1576     call_a(2,3);
1577   }''', name : 'ISO C99 varargs macros in C++')
1578
1579 if g_have_iso_cxx_varargs
1580   glibconfig_conf.set('g_have_iso_cxx_varargs', '''
1581 #ifdef __cplusplus
1582 # define G_HAVE_ISO_VARARGS 1
1583 #endif''')
1584 endif
1585
1586 g_have_gnuc_varargs = cc.compiles('''
1587   void some_func (void) {
1588     int a(int p1, int p2, int p3);
1589     #define call_a(params...) a(1,params)
1590     call_a(2,3);
1591   }''', name : 'GNUC varargs macros')
1592
1593 if cc.has_header('alloca.h')
1594   glibconfig_conf.set('GLIB_HAVE_ALLOCA_H', true)
1595 endif
1596 has_syspoll = cc.has_header('sys/poll.h')
1597 has_systypes = cc.has_header('sys/types.h')
1598 if has_syspoll
1599   glibconfig_conf.set('GLIB_HAVE_SYS_POLL_H', true)
1600 endif
1601 has_winsock2 = cc.has_header('winsock2.h')
1602
1603 if has_syspoll and has_systypes
1604   poll_includes = '''
1605       #include<sys/poll.h>
1606       #include<sys/types.h>'''
1607 elif has_winsock2
1608   poll_includes = '''
1609       #define _WIN32_WINNT @0@
1610       #include <winsock2.h>'''.format(glib_conf.get('_WIN32_WINNT'))
1611 else
1612   # FIXME?
1613   error('FIX POLL* defines')
1614 endif
1615
1616 poll_defines = [
1617   [ 'POLLIN', 'g_pollin', 1 ],
1618   [ 'POLLOUT', 'g_pollout', 4 ],
1619   [ 'POLLPRI', 'g_pollpri', 2 ],
1620   [ 'POLLERR', 'g_pollerr', 8 ],
1621   [ 'POLLHUP', 'g_pollhup', 16 ],
1622   [ 'POLLNVAL', 'g_pollnval', 32 ],
1623 ]
1624
1625 if has_syspoll and has_systypes
1626   foreach d : poll_defines
1627     val = cc.compute_int(d[0], prefix: poll_includes)
1628     glibconfig_conf.set(d[1], val)
1629   endforeach
1630 elif has_winsock2
1631   # Due to a missed bug in configure.ac the poll test
1632   # never succeeded on Windows and used some pre-defined
1633   # values as a fallback. Keep using them to maintain
1634   # ABI compatibility with autotools builds of glibs
1635   # and with *any* glib-using code compiled against them,
1636   # since these values end up in a public header glibconfig.h.
1637   foreach d : poll_defines
1638     glibconfig_conf.set(d[1], d[2])
1639   endforeach
1640 endif
1641
1642 # Internet address families
1643 # FIXME: what about Cygwin (G_WITH_CYGWIN)
1644 if host_system == 'windows'
1645   inet_includes = '''
1646       #include <winsock2.h>'''
1647 else
1648   inet_includes = '''
1649       #include <sys/types.h>
1650       #include <sys/socket.h>'''
1651 endif
1652
1653 inet_defines = [
1654   [ 'AF_UNIX', 'g_af_unix' ],
1655   [ 'AF_INET', 'g_af_inet' ],
1656   [ 'AF_INET6', 'g_af_inet6' ],
1657   [ 'MSG_OOB', 'g_msg_oob' ],
1658   [ 'MSG_PEEK', 'g_msg_peek' ],
1659   [ 'MSG_DONTROUTE', 'g_msg_dontroute' ],
1660 ]
1661 foreach d : inet_defines
1662   val = cc.compute_int(d[0], prefix: inet_includes)
1663   glibconfig_conf.set(d[1], val)
1664 endforeach
1665
1666 # We need a more robust approach here...
1667 host_cpu_family = host_machine.cpu_family()
1668 if host_cpu_family == 'x86' or host_cpu_family == 'x86_64' or host_cpu_family == 's390' or host_cpu_family == 's390x' or host_cpu_family.startswith('arm') or host_cpu_family == 'aarch64' or host_cpu_family.startswith('crisv32') or host_cpu_family.startswith('etrax')
1669   glib_memory_barrier_needed = false
1670 elif host_cpu_family.startswith('sparc') or host_cpu_family.startswith('alpha') or host_cpu_family.startswith('powerpc') or host_cpu_family == 'ia64'
1671   glib_memory_barrier_needed = true
1672 else
1673   warning('Unknown host cpu: ' + host_cpu_family)
1674   glib_memory_barrier_needed = true
1675 endif
1676 glibconfig_conf.set('G_ATOMIC_OP_MEMORY_BARRIER_NEEDED', glib_memory_barrier_needed)
1677
1678 # We need to decide at configure time if GLib will use real atomic
1679 # operations ("lock free") or emulated ones with a mutex.  This is
1680 # because we must put this information in glibconfig.h so we know if
1681 # it is safe or not to inline using compiler intrinsics directly from
1682 # the header.
1683 #
1684 # We also publish the information via G_ATOMIC_LOCK_FREE in case the
1685 # user is interested in knowing if they can use the atomic ops across
1686 # processes.
1687 #
1688 # We can currently support the atomic ops natively when building GLib
1689 # with recent versions of GCC or MSVC.
1690 #
1691 # Note that the atomic ops are only available with GCC on x86 when
1692 # using -march=i486 or higher.  If we detect that the atomic ops are
1693 # not available but would be available given the right flags, we want
1694 # to abort and advise the user to fix their CFLAGS.  It's better to do
1695 # that then to silently fall back on emulated atomic ops just because
1696 # the user had the wrong build environment.
1697 atomictest = '''int main() {
1698   volatile int atomic = 2;
1699   __sync_bool_compare_and_swap (&atomic, 2, 3);
1700   return 0;
1701 }
1702 '''
1703
1704 atomicdefine = '''
1705 #ifndef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4
1706 #error "compiler has atomic ops, but doesn't define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4"
1707 #endif
1708 '''
1709
1710 # We know that we can always use real ("lock free") atomic operations with MSVC
1711 if cc.get_id() == 'msvc' or cc.get_id() == 'clang-cl' or cc.links(atomictest, name : 'atomic ops')
1712   have_atomic_lock_free = true
1713   if cc.get_id() == 'gcc' and not cc.compiles(atomicdefine, name : 'atomic ops define')
1714     # Old gcc release may provide
1715     # __sync_bool_compare_and_swap but doesn't define
1716     # __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4
1717     glib_conf.set('__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4', true)
1718   endif
1719 else
1720   have_atomic_lock_free = false
1721   if host_machine.cpu_family() == 'x86' and cc.links(atomictest, args : '-march=i486')
1722     error('GLib must be built with -march=i486 or later.')
1723   endif
1724 endif
1725 glibconfig_conf.set('G_ATOMIC_LOCK_FREE', have_atomic_lock_free)
1726
1727 # === Threads ===
1728
1729 # Determination of thread implementation
1730 if host_system == 'windows' and not get_option('force_posix_threads')
1731   thread_dep = []
1732   threads_implementation = 'win32'
1733   glibconfig_conf.set('g_threads_impl_def', 'WIN32')
1734   glib_conf.set('THREADS_WIN32', 1)
1735 else
1736   thread_dep = dependency('threads')
1737   threads_implementation = 'posix'
1738   pthread_prefix = '''
1739       #ifndef _GNU_SOURCE
1740       # define _GNU_SOURCE
1741       #endif
1742       #include <pthread.h>'''
1743   glibconfig_conf.set('g_threads_impl_def', 'POSIX')
1744   glib_conf.set('THREADS_POSIX', 1)
1745   if cc.has_header_symbol('pthread.h', 'pthread_attr_setstacksize')
1746     glib_conf.set('HAVE_PTHREAD_ATTR_SETSTACKSIZE', 1)
1747   endif
1748   if cc.has_header_symbol('pthread.h', 'pthread_attr_setinheritsched')
1749     glib_conf.set('HAVE_PTHREAD_ATTR_SETINHERITSCHED', 1)
1750   endif
1751   if cc.has_header_symbol('pthread.h', 'pthread_condattr_setclock')
1752     glib_conf.set('HAVE_PTHREAD_CONDATTR_SETCLOCK', 1)
1753   endif
1754   if cc.has_header_symbol('pthread.h', 'pthread_cond_timedwait_relative_np')
1755     glib_conf.set('HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP', 1)
1756   endif
1757   if cc.has_header_symbol('pthread.h', 'pthread_getname_np', prefix : pthread_prefix)
1758     glib_conf.set('HAVE_PTHREAD_GETNAME_NP', 1)
1759   endif
1760
1761   if cc.has_header_symbol('sys/syscall.h', 'SYS_sched_getattr')
1762     glib_conf.set('HAVE_SYS_SCHED_GETATTR', 1)
1763   endif
1764
1765   # Assume that pthread_setname_np is available in some form; same as configure
1766   if cc.links(pthread_prefix + '''
1767               int main() {
1768                 pthread_setname_np("example");
1769                 return 0;
1770               }''',
1771               name : 'pthread_setname_np(const char*)',
1772               dependencies : thread_dep)
1773     # macOS and iOS
1774     glib_conf.set('HAVE_PTHREAD_SETNAME_NP_WITHOUT_TID', 1)
1775   elif cc.links(pthread_prefix + '''
1776                 int main() {
1777                   pthread_setname_np(pthread_self(), "example");
1778                   return 0;
1779                 }''',
1780                 name : 'pthread_setname_np(pthread_t, const char*)',
1781                 dependencies : thread_dep)
1782     # Linux, Solaris, etc.
1783     glib_conf.set('HAVE_PTHREAD_SETNAME_NP_WITH_TID', 1)
1784   elif cc.links(pthread_prefix + '''
1785                 int main() {
1786                   pthread_setname_np(pthread_self(), "%s", "example");
1787                   return 0;
1788                 }''',
1789                 name : 'pthread_setname_np(pthread_t, const char*, void*)',
1790                 dependencies : thread_dep)
1791     # NetBSD
1792     glib_conf.set('HAVE_PTHREAD_SETNAME_NP_WITH_TID_AND_ARG', 1)
1793   elif cc.links(pthread_prefix + '''
1794                 #include <pthread_np.h>
1795                 int main() {
1796                   pthread_set_name_np(pthread_self(), "example");
1797                   return 0;
1798                 }''',
1799                 name : 'pthread_set_name_np(pthread_t, const char*)',
1800                 dependencies : thread_dep)
1801     # FreeBSD, DragonFlyBSD, OpenBSD, etc.
1802     glib_conf.set('HAVE_PTHREAD_SET_NAME_NP', 1)
1803   endif
1804 endif
1805
1806 # FIXME: we should make it print the result and always return 0, so that
1807 # the output in meson shows up as green
1808 stack_grows_check_prog = '''
1809   volatile int *a = 0, *b = 0;
1810   void f (int i) {
1811     volatile int x = 5;
1812     if (i == 0)
1813       b = &x;
1814     else
1815       f (i - 1);
1816   }
1817   int main () {
1818     volatile int y = 7;
1819     a = &y;
1820     f (100);
1821     return b > a ? 0 : 1;
1822   }'''
1823
1824 if cc_can_run
1825   rres = cc.run(stack_grows_check_prog, name : 'stack grows check')
1826   growing_stack = rres.returncode() == 0
1827 else
1828   growing_stack = meson.get_cross_property('growing_stack', false)
1829 endif
1830
1831 glibconfig_conf.set10('G_HAVE_GROWING_STACK', growing_stack)
1832
1833 # Tests for iconv
1834 #
1835 # We should never use the MinGW C library's iconv because it may not be
1836 # available in the actual runtime environment. On Windows, we always use
1837 # the built-in implementation
1838 iconv_opt = get_option('iconv')
1839 if host_system == 'windows'
1840   libiconv = []
1841   # We have a #include "win_iconv.c" in gconvert.c on Windows, so we don't need
1842   # any external library for it
1843   if iconv_opt != 'auto'
1844     warning('-Diconv was set to @0@, which was ignored')
1845   endif
1846 else
1847   found_iconv = false
1848   if ['auto', 'libc'].contains(iconv_opt) and cc.has_function('iconv_open')
1849     libiconv = []
1850     found_iconv = true
1851   endif
1852   if not found_iconv and ['auto', 'external'].contains(iconv_opt) and cc.has_header_symbol('iconv.h', 'iconv_open')
1853     libiconv = [cc.find_library('iconv')]
1854     found_iconv = true
1855   endif
1856
1857   if not found_iconv
1858     error('iconv implementation "@0@" not found'.format(iconv_opt))
1859   endif
1860 endif
1861
1862 if get_option('internal_pcre')
1863   pcre = []
1864   use_system_pcre = false
1865 else
1866   pcre = dependency('libpcre', version: '>= 8.31', required : false) # Should check for Unicode support, too. FIXME
1867   if not pcre.found()
1868     if cc.get_id() == 'msvc' or cc.get_id() == 'clang-cl'
1869     # MSVC: Search for the PCRE library by the configuration, which corresponds
1870     # to the output of CMake builds of PCRE.  Note that debugoptimized
1871     # is really a Release build with .PDB files.
1872       if buildtype == 'debug'
1873         pcre = cc.find_library('pcred', required : false)
1874       else
1875         pcre = cc.find_library('pcre', required : false)
1876       endif
1877     endif
1878   endif
1879   use_system_pcre = pcre.found()
1880 endif
1881 glib_conf.set('USE_SYSTEM_PCRE', use_system_pcre)
1882
1883 use_pcre_static_flag = false
1884
1885 if host_system == 'windows'
1886   if not use_system_pcre
1887     use_pcre_static_flag = true
1888   else
1889     pcre_static = cc.links('''#define PCRE_STATIC
1890                               #include <pcre.h>
1891                               int main() {
1892                                 void *p = NULL;
1893                                 pcre_free(p);
1894                                 return 0;
1895                               }''',
1896                            dependencies: pcre,
1897                            name : 'Windows system PCRE is a static build')
1898     if pcre_static
1899       use_pcre_static_flag = true
1900     endif
1901   endif
1902 endif
1903
1904 libm = cc.find_library('m', required : false)
1905 libffi_dep = dependency('libffi', version : '>= 3.0.0', fallback : ['libffi', 'ffi_dep'])
1906
1907 # Don't use the bundled ZLib sources until we are sure that we can't find it on
1908 # the system
1909 libz_dep = dependency('zlib', required : false)
1910 if not libz_dep.found()
1911   if cc.get_id() != 'msvc' and cc.get_id() != 'clang-cl'
1912     libz_dep = cc.find_library('z', required : false)
1913   else
1914     libz_dep = cc.find_library('zlib1', required : false)
1915     if not libz_dep.found()
1916       libz_dep = cc.find_library('zlib', required : false)
1917     endif
1918   endif
1919   if not libz_dep.found() or not cc.has_header('zlib.h')
1920     libz_dep = subproject('zlib').get_variable('zlib_dep')
1921   endif
1922 endif
1923
1924 # First check in libc, fallback to libintl, and as last chance build
1925 # proxy-libintl subproject.
1926 # FIXME: glib-gettext.m4 has much more checks to detect broken/uncompatible
1927 # implementations. This could be extended if issues are found in some platforms.
1928 if cc.has_function('ngettext')
1929   libintl = []
1930   have_bind_textdomain_codeset = cc.has_function('bind_textdomain_codeset')
1931 else
1932   libintl = cc.find_library('intl', required : false)
1933   if not libintl.found()
1934     libintl = subproject('proxy-libintl').get_variable('intl_dep')
1935     have_bind_textdomain_codeset = true  # proxy-libintl supports it
1936   else
1937     have_bind_textdomain_codeset = cc.has_function('bind_textdomain_codeset',
1938                                                    dependencies : libintl)
1939   endif
1940 endif
1941
1942 glib_conf.set('HAVE_BIND_TEXTDOMAIN_CODESET', have_bind_textdomain_codeset)
1943
1944 # We require gettext to always be present
1945 glib_conf.set('HAVE_DCGETTEXT', 1)
1946 glib_conf.set('HAVE_GETTEXT', 1)
1947
1948 glib_conf.set_quoted('GLIB_LOCALE_DIR', join_paths(glib_datadir, 'locale'))
1949
1950 # libmount is only used by gio, but we need to fetch the libs to generate the
1951 # pkg-config file below
1952 libmount_dep = []
1953 if host_system == 'linux'
1954   libmount_dep = dependency('mount', version : '>=2.23', required : get_option('libmount'))
1955   glib_conf.set('HAVE_LIBMOUNT', libmount_dep.found())
1956 endif
1957
1958 if host_system == 'windows'
1959   winsock2 = cc.find_library('ws2_32')
1960 endif
1961
1962 selinux_dep = []
1963 if host_system == 'linux'
1964   selinux_dep = dependency('libselinux', required: get_option('selinux'))
1965
1966   glib_conf.set('HAVE_SELINUX', selinux_dep.found())
1967 endif
1968
1969 xattr_dep = []
1970 if host_system != 'windows' and get_option('xattr')
1971   # either glibc or libattr can provide xattr support
1972   # for both of them, we check for getxattr being in
1973   # the library and a valid xattr header.
1974
1975   # try glibc
1976   if cc.has_function('getxattr') and cc.has_header('sys/xattr.h')
1977     glib_conf.set('HAVE_SYS_XATTR_H', 1)
1978     glib_conf_prefix = glib_conf_prefix + '#define @0@ 1\n'.format('HAVE_SYS_XATTR_H')
1979   #failure. try libattr
1980   elif cc.has_header_symbol('attr/xattr.h', 'getxattr')
1981     glib_conf.set('HAVE_ATTR_XATTR_H', 1)
1982     glib_conf_prefix = glib_conf_prefix + '#define @0@ 1\n'.format('HAVE_ATTR_XATTR_H')
1983     xattr_dep = [cc.find_library('xattr')]
1984   else
1985     error('No getxattr implementation found in C library or libxattr')
1986   endif
1987
1988   glib_conf.set('HAVE_XATTR', 1)
1989   if cc.compiles(glib_conf_prefix + '''
1990                  #include <stdio.h>
1991                  #ifdef HAVE_SYS_TYPES_H
1992                  #include <sys/types.h>
1993                  #endif
1994                  #ifdef HAVE_SYS_XATTR_H
1995                  #include <sys/xattr.h>
1996                  #elif HAVE_ATTR_XATTR_H
1997                  #include <attr/xattr.h>
1998                  #endif
1999
2000                  int main (void) {
2001                    ssize_t len = getxattr("", "", NULL, 0, 0, XATTR_NOFOLLOW);
2002                    return len;
2003                  }''',
2004                  name : 'XATTR_NOFOLLOW')
2005     glib_conf.set('HAVE_XATTR_NOFOLLOW', 1)
2006   endif
2007 endif
2008
2009 # If strlcpy is present (BSD and similar), check that it conforms to the BSD
2010 # specification. Specifically Solaris 8's strlcpy() does not, see
2011 # https://bugzilla.gnome.org/show_bug.cgi?id=53933 for further context.
2012 if cc.has_function('strlcpy')
2013   if cc_can_run
2014     rres = cc.run('''#include <stdlib.h>
2015                     #include <string.h>
2016                     int main() {
2017                       char p[10];
2018                       (void) strlcpy (p, "hi", 10);
2019                       if (strlcat (p, "bye", 0) != 3)
2020                         return 1;
2021                       return 0;
2022                     }''',
2023                   name : 'OpenBSD strlcpy/strlcat')
2024     if rres.compiled() and rres.returncode() == 0
2025       glib_conf.set('HAVE_STRLCPY', 1)
2026     endif
2027   elif meson.get_cross_property('have_strlcpy', false)
2028     glib_conf.set('HAVE_STRLCPY', 1)
2029   endif
2030 endif
2031
2032 cmdline_test_code = '''
2033 #include <fcntl.h>
2034 #include <sys/stat.h>
2035 #include <stdio.h>
2036 #include <stdlib.h>
2037 #undef NDEBUG
2038 #include <assert.h>
2039
2040 static int
2041 __getcmdline (void)
2042 {
2043 /* This code is a dumbed-down version of g_file_get_contents() */
2044 #ifndef O_BINARY
2045 #define O_BINARY 0
2046 #endif
2047 #define BUFSIZE 1024
2048   char result[BUFSIZE];
2049   struct stat stat_buf;
2050
2051   int fd = open ("/proc/self/cmdline", O_RDONLY|O_BINARY);
2052   assert (fd >= 0);
2053   assert (fstat (fd, &stat_buf) == 0);
2054
2055   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
2056     assert (read (fd, result, BUFSIZE) > 0);
2057   else
2058     {
2059       FILE *f = fdopen (fd, "r");
2060       assert (f != NULL);
2061       assert (fread (result, 1, BUFSIZE, f) > 0);
2062     }
2063
2064   return 0;
2065 }
2066
2067 int
2068 main (void)
2069 {
2070   exit (__getcmdline ());
2071 }'''
2072
2073 if cc_can_run
2074   rres = cc.run(cmdline_test_code, name : '/proc/self/cmdline')
2075   have_proc_self_cmdline = rres.compiled() and rres.returncode() == 0
2076 else
2077   have_proc_self_cmdline = meson.get_cross_property('have_proc_self_cmdline', false)
2078 endif
2079
2080 glib_conf.set('HAVE_PROC_SELF_CMDLINE', have_proc_self_cmdline)
2081
2082 python = import('python').find_installation('python3')
2083 # used for '#!/usr/bin/env <name>'
2084 python_name = 'python3'
2085
2086 python_version = python.language_version()
2087 python_version_req = '>=3.5'
2088 if not python_version.version_compare(python_version_req)
2089   error('Requires Python @0@, @1@ found.'.format(python_version_req, python_version))
2090 endif
2091
2092 # Determine which user environment-dependent files that we want to install
2093 have_bash = find_program('bash', required : false).found() # For completion scripts
2094 have_sh = find_program('sh', required : false).found() # For glib-gettextize
2095
2096 # Some installed tests require a custom environment
2097 env_program = find_program('env', required: installed_tests_enabled)
2098
2099 # FIXME: How to detect Solaris? https://github.com/mesonbuild/meson/issues/1578
2100 if host_system == 'sunos'
2101   glib_conf.set('_XOPEN_SOURCE_EXTENDED', 1)
2102   glib_conf.set('_XOPEN_SOURCE', 2)
2103   glib_conf.set('__EXTENSIONS__',1)
2104 endif
2105
2106 # Sadly Meson does not expose this value:
2107 # https://github.com/mesonbuild/meson/pull/3460
2108 if host_system == 'windows'
2109   # Autotools explicitly removed --Wl,--export-all-symbols from windows builds,
2110   # with no explanation. Do the same here for now but this could be revisited if
2111   # if causes issues.
2112   export_dynamic_ldflags = []
2113 elif host_system == 'cygwin'
2114   export_dynamic_ldflags = ['-Wl,--export-all-symbols']
2115 elif host_system == 'darwin'
2116   export_dynamic_ldflags = []
2117 elif host_system == 'sunos'
2118   export_dynamic_ldflags = []
2119 else
2120   export_dynamic_ldflags = ['-Wl,--export-dynamic']
2121 endif
2122
2123 win32_cflags = []
2124 win32_ldflags = []
2125 if host_system == 'windows' and cc.get_id() != 'msvc' and cc.get_id() != 'clang-cl'
2126   # Ensure MSVC-compatible struct packing convention is used when
2127   # compiling for Win32 with gcc. It is used for the whole project and exposed
2128   # in glib-2.0.pc.
2129   win32_cflags = ['-mms-bitfields']
2130   add_project_arguments(win32_cflags, language : 'c')
2131
2132   # Win32 API libs, used only by libglib and exposed in glib-2.0.pc
2133   win32_ldflags = ['-lws2_32', '-lole32', '-lwinmm', '-lshlwapi']
2134 elif host_system == 'cygwin'
2135   win32_ldflags = ['-luser32', '-lkernel32']
2136 endif
2137
2138 # Tracing: dtrace
2139 want_dtrace = get_option('dtrace')
2140 enable_dtrace = false
2141
2142 # Since dtrace support is opt-in we just error out if it was requested but
2143 # is not available. We don't bother with autodetection yet.
2144 if want_dtrace
2145   if glib_have_carbon
2146     error('GLib dtrace support not yet compatible with macOS dtrace')
2147   endif
2148   dtrace = find_program('dtrace', required : true) # error out if not found
2149   if not cc.has_header('sys/sdt.h')
2150     error('dtrace support needs sys/sdt.h header')
2151   endif
2152   # FIXME: autotools build also passes -fPIC -DPIC but is it needed in this case?
2153   dtrace_obj_gen = generator(dtrace,
2154     output : '@BASENAME@.o',
2155     arguments : ['-G', '-s', '@INPUT@', '-o', '@OUTPUT@'])
2156   # FIXME: $(SED) -e "s,define STAP_HAS_SEMAPHORES 1,undef STAP_HAS_SEMAPHORES,"
2157   #               -e "s,define _SDT_HAS_SEMAPHORES 1,undef _SDT_HAS_SEMAPHORES,"
2158   dtrace_hdr_gen = generator(dtrace,
2159     output : '@BASENAME@.h',
2160     arguments : ['-h', '-s', '@INPUT@', '-o', '@OUTPUT@'])
2161   glib_conf.set('HAVE_DTRACE', 1)
2162   enable_dtrace = true
2163 endif
2164
2165 # systemtap
2166 want_systemtap = get_option('systemtap')
2167 enable_systemtap = false
2168
2169 if want_systemtap and enable_dtrace
2170   tapset_install_dir = get_option('tapset_install_dir')
2171   if tapset_install_dir == ''
2172     tapset_install_dir = join_paths(get_option('datadir'), 'systemtap/tapset', host_machine.cpu_family())
2173   endif
2174   stp_cdata = configuration_data()
2175   stp_cdata.set('ABS_GLIB_RUNTIME_LIBDIR', glib_libdir)
2176   stp_cdata.set('LT_CURRENT', minor_version * 100)
2177   stp_cdata.set('LT_REVISION', micro_version)
2178   enable_systemtap = true
2179 endif
2180
2181 test_timeout = 60
2182 test_timeout_slow = 180
2183
2184 pkg = import('pkgconfig')
2185 windows = import('windows')
2186 subdir('glib')
2187 subdir('gobject')
2188 subdir('gthread')
2189 subdir('gmodule')
2190 subdir('gio')
2191 subdir('fuzzing')
2192 if build_tests
2193   subdir('tests')
2194 endif
2195
2196 # xgettext is optional (on Windows for instance)
2197 if find_program('xgettext', required : get_option('nls')).found()
2198   subdir('po')
2199 endif
2200
2201 # Install glib-gettextize executable, if a UNIX-style shell is found
2202 if have_sh
2203   # These should not contain " quotes around the values
2204   gettextize_conf = configuration_data()
2205   gettextize_conf.set('PACKAGE', 'glib')
2206   gettextize_conf.set('VERSION', meson.project_version())
2207   gettextize_conf.set('prefix', glib_prefix)
2208   gettextize_conf.set('datarootdir', glib_datadir)
2209   gettextize_conf.set('datadir', glib_datadir)
2210   configure_file(input : 'glib-gettextize.in',
2211     install_dir : glib_bindir,
2212     output : 'glib-gettextize',
2213     configuration : gettextize_conf)
2214 endif
2215
2216 # Install m4 macros that other projects use
2217 install_data('m4macros/glib-2.0.m4', 'm4macros/glib-gettext.m4', 'm4macros/gsettings.m4',
2218   install_dir : join_paths(get_option('datadir'), 'aclocal'))
2219
2220 if host_system != 'windows'
2221   # Install Valgrind suppression file (except on Windows,
2222   # as Valgrind is currently not supported on Windows)
2223   install_data('glib.supp',
2224     install_dir : join_paths(get_option('datadir'), 'glib-2.0', 'valgrind'))
2225 endif
2226
2227 configure_file(output : 'config.h', configuration : glib_conf)
2228
2229 if host_system == 'windows'
2230   install_headers([ 'msvc_recommended_pragmas.h' ], subdir : 'glib-2.0')
2231 endif
2232
2233 if get_option('man')
2234   xsltproc = find_program('xsltproc', required : true)
2235   xsltproc_command = [
2236     xsltproc,
2237     '--nonet',
2238     '--stringparam', 'man.output.quietly', '1',
2239     '--stringparam', 'funcsynopsis.style', 'ansi',
2240     '--stringparam', 'man.th.extra1.suppress', '1',
2241     '--stringparam', 'man.authors.section.enabled', '0',
2242     '--stringparam', 'man.copyright.section.enabled', '0',
2243     '-o', '@OUTPUT@',
2244     'http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl',
2245     '@INPUT@',
2246   ]
2247   man1_dir = join_paths(glib_prefix, get_option('mandir'), 'man1')
2248 endif
2249
2250 gnome = import('gnome')
2251 subdir('docs/reference')