Repository navigation
Expand file tree
/
Copy pathmeson.build
More file actions
752 lines (699 loc) · 34.8 KB
/
Copy pathmeson.build
File metadata and controls
752 lines (699 loc) · 34.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
# SPDX-License-Identifier: MPL-2.0
# Copyright (c) 2021-2026 Seagate Technology LLC and/or its Affiliates, All Rights Reserved
project(
'openSeaChest',
'c',
version: 'v26.03.2',
license: 'MPL-2.0',
default_options: [
'meson_version: >=0.56.0',
'warning_level=2',
'b_pie=true',
'b_staticpic=true',
'b_asneeded=true',
'b_lundef=true',
'buildtype=release',
'b_ndebug=if-release',
'default_library=static',
'install_umask=022',
],
)
c = meson.get_compiler('c')
architecture = target_machine.cpu()
if architecture == ''
architecture = target_machine.cpu_family()
endif
# Add debug flag if debug option is enabled
if get_option('debug')
add_project_arguments('-D_DEBUG', language: 'c')
endif
# Add libc musl flag if enabled
if get_option('libc_musl')
add_project_arguments('-DUSING_MUSL_LIBC=1', language: 'c')
endif
# Add JSON format support flag if enabled
if get_option('json_outputformat')
add_project_arguments('-DFEATURE_JSONOUTPUT_SUPPORT', language: 'c')
endif
warning_flags = []
linker_flags = [] #additional linker flags to add per-compiler for hardening.
ssp_support_dep = [] #Solaris/illumos SSP support library dependency for executables
if c.get_id().contains('gcc') or c.get_id().contains('clang')
#TODO: Add -Wcast-align=strict and fix these issues to help ensure better portability
#NOTE: -Wsign-conversion can be useful while debugging, but there are numerous places this shows up
# and it is not useful, so only add it while debugging.
#NOTE: 4/4/2024 - adding flags from https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++
#NOTE: Where the check below succeeds (GCC >=14 on GNU/Linux) we add -fhardened on
# top of the explicit flags here; the explicit flags are equal or stronger than
# the -fhardened set, so no component is reduced. -fhardened is only supported
# on GNU/Linux targets (GCC docs), so Clang, MSVC, non-Linux builds, and older
# GCC rely on the explicit equivalents in this block (OpenSSF guide 3.26.2).
warning_flags = [
# '-Wcast-align=strict',
'-Wshadow=compatible-local',
'-Wbidi-chars=any', #rejects bidi override chars in source (Trojan Source); dropped by get_supported_arguments where unsupported
'-Wvla',
'-Wfloat-equal',
'-Wnull-dereference',
'-Wunused-const-variable',
'-Wunused-parameter',
'-Wunused-value',
'-Wduplicated-cond',
'-Wjump-misses-init',
'-Wstringop-overflow',
'-Wlogical-op',
'-Wshift-overflow',
'-Wshift-overflow=1',
'-Wshift-overflow=2',
'-Wdouble-promotion',
'-Werror=format-security',
'-Wold-style-definition',
'-Wstrict-prototypes',
'-Wmissing-declarations',
'-Wmissing-prototypes',
'-Wchar-subscripts',
'-Wundef',
'-Wformat',
'-Wformat=2',
'-Wint-conversion', #-Warith-conversion
'-Wenum-conversion',
'-Wfloat-conversion',
'-Wint-to-pointer-cast',
'-Wimplicit-fallthrough',
'-fstrict-flex-arrays=3',
'-fno-delete-null-pointer-checks',
'-fno-strict-overflow',
'-fno-strict-aliasing',
'-ftrivial-auto-var-init=zero',
'-fzero-init-padding-bits=all',
'-Wtrampolines', #GCC only at this time
'-Werror=implicit',
'-Werror=incompatible-pointer-types',
'-Wincompatible-pointer-types-discards-qualifiers',
'-Werror=int-conversion',
'-Werror=implicit-int',
'-Woverlength-strings',
'-Wnewline-eof',
'-Wno-c23-extensions', #We do not want this warning since we are already checking for when C23 extensions are available before we use them. If not, we use a compiler specific definition, or make it an empty definition.
'-Wparentheses',
'-Wextra-semi',
'-Wcast-qual',
'-Werror=sometimes-uninitialized',
'-Wuninitialized',
'-Wunevaluated-expression',
'-Wunsequenced',
'-Wvarargs',
'-Wwrite-strings',
'-Wrestrict',
'-Wstringop-truncation',
'-Werror=trigraphs',
'-Wunreachable-code',
'-Wcomment',
'-Wsequence-point',
'-Wreturn-type',
'-Wpointer-bool-conversion',
'-Wmismatched-dealloc',
'-Wfree-nonheap-object',
'-Wnullability', # Warnings for nullability annotations
'-Wnullability-completeness', # Warn if nullability annotations are incomplete
'-Wnullability-completeness-on-arrays', # Warn if nullability annotations are incomplete
# '-Wnullable-to-nonnull-conversion', # Basically warns so you have to cast to the correct nullability type. Not needed today -TJE
#'-Wswitch-enum',
'-Walloc-zero',
'-Walloc-size',
'-Wcalloc-transposed-args',
'-Werror=alloca', # Do not allow use of the alloca function
'-Wstring-compare', # Helps detect when strcmp is used when the programmer likely meant to use strncmp
'-Wfortify-source', # needed for diagnose_as_builtin attributes to work.
'-Wunused-but-set-variable',
]
if get_option('cc-suggest-attribute')
warning_flags += [
'-Wsuggest-attribute=pure',
'-Wsuggest-attribute=const',
'-Wsuggest-attribute=noreturn',
'-Wsuggest-attribute=returns_nonnull',
'-Wmissing-noreturn',
'-Wsuggest-attribute=malloc',
'-Wsuggest-attribute=format',
'-Wmissing-format-attribute',
'-Wsuggest-attribute=cold',
'-fipa-pure-const',
]
endif
if (c.get_id().contains('gcc') and c.version().version_compare('>=10.0')) or c.get_id().contains('clang')
#only enable the sign conversion warning on GCC 10 and up because it is way too noisy on earlier GCC versions than it is useful-TJE
#Clang supports it across all versions in our build matrix, so enable it there for parity
warning_flags += '-Wsign-conversion'
endif
if c.get_id().contains('gcc') and c.version().version_compare('>=14.0') and target_machine.system() == 'linux'
#KEEP IN SYNC: this -fhardened block is duplicated in 17 meson.build files (both repos)
#GNU/Linux + GCC >= 14: -fhardened is fully supported only on GNU/Linux; elsewhere GCC
#warns and applies it partially (GCC bug 126822/126823), so those targets use the
#explicit (equal-or-stronger) flags appended later.
#-Whardened + -Werror: false positive on GCC 14.2 (driver's own _FORTIFY_SOURCE),
#clean on 16.2.1 (both confirmed in real builds; 15.x untested).
#hardened_warn: 'disabled' (default) adds -Wno-hardened, 'auto' enables -Whardened
#on GCC >= 15, 'enabled' enables it unconditionally.
warning_flags += '-fhardened'
if get_option('hardened_warn').enabled() or (get_option('hardened_warn').auto() and c.version().version_compare('>=15.0'))
warning_flags += '-Whardened'
else
warning_flags += '-Wno-hardened'
endif
else
#-fhardened (above, where active) also enables _GLIBCXX_ASSERTIONS, so this
#is only needed for toolchains that lack -fhardened
warning_flags += '-D_GLIBCXX_ASSERTIONS'
endif
# ssp option: 'auto' (default) and 'enabled' both run the automatic
# probing below; 'disabled' skips the whole block and builds SSP-free.
if get_option('ssp').auto() or get_option('ssp').enabled()
# Check if -fstack-protector-strong links or not - some systems support
# the argument but are unable to link with it. Fall back to plain
# -fstack-protector when strong is unavailable.
# GCC's optimize attribute forces canary codegen on the probe function so
# the check does not depend on the compiler's per-function protection
# heuristics deciding that a small test function is not worth protecting.
stack_protector_test_code = '''
#if defined(__GNUC__) && !defined(__clang__)
__attribute__((noinline, optimize("-fstack-protector-all")))
#else
__attribute__((noinline))
#endif
int ssp_probe(void)
{
volatile char buf[8];
buf[0] = 1;
buf[7] = 2;
return buf[0] + buf[7];
}
int main(void) { return ssp_probe(); }
'''
# A link check rather than a compile: on some toolchains the SSP glue
# symbols (__stack_chk_fail[_local], __stack_chk_guard) are only
# provided by a static archive and must already resolve at link time
# (see golang/go#58385).
ssp_strong_ok = c.links(
stack_protector_test_code,
name: 'stack-protector-strong link support',
args: ['-fstack-protector-strong'],
)
ssp_regular_ok = false
if not ssp_strong_ok
#Fall back to plain -fstack-protector when strong is unavailable
ssp_regular_ok = c.links(
stack_protector_test_code,
name: 'stack-protector link support',
args: ['-fstack-protector'],
)
endif
# On Solaris/illumos the probe above can pass yet the final link still
# fails with undefined __stack_chk* symbols: the GCC driver adds the
# SSP support library only when a -fstack-protector flag sits on the
# same command line as the link, and the ninja link of the executables
# carries no such flag (glibc/musl resolve the glue through the
# always-linked libgcc, so the probe result is trusted there, see
# golang/go#58385). On sunos SSP is therefore enabled only when the
# platform ships the SSP library and the executables link it through
# ssp_support_dep; otherwise the build proceeds SSP-free. The
# subprojects run the same gate (without the flag) and expose
# ssp_support_dep through their declare_dependency() so that consumers
# of their libraries also link it on the final line.
if ssp_strong_ok or ssp_regular_ok
if target_machine.system() != 'sunos'
if ssp_strong_ok
warning_flags += '-fstack-protector-strong'
else
#plain -fstack-protector only instruments functions with local char
#arrays of 8 bytes or more; tighten the threshold to 4 bytes
#per OpenSSF guide 3.14.2 (dropped if the toolchain lacks the param)
warning_flags += ['-fstack-protector', '--param=ssp-buffer-size=4']
endif
else
#illumos (OmniOS, Tribblix, OpenIndiana) ships libssp_ns.a
ssp_ns_dep = c.find_library('ssp_ns', required: false)
if ssp_ns_dep.found()
ssp_support_dep = [ssp_ns_dep]
else
#classic Oracle Solaris ships libssp.a from the gcc package
ssp_dep = c.find_library('ssp', required: false)
if ssp_dep.found()
ssp_support_dep = [ssp_dep]
endif
endif
if ssp_support_dep.length() > 0
if ssp_strong_ok
warning_flags += '-fstack-protector-strong'
else
warning_flags += ['-fstack-protector', '--param=ssp-buffer-size=4']
endif
endif
endif
endif
endif
# Check if -fstack-clash-protection works or not. Some GCC for Windows
# versions (see
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90458) accept the flag
# and even link it, but the generated code crashes at runtime, so the
# probe is also run when possible.
# The large local buffer forces the stack probing code path the buggy
# versions break.
stack_clash_test_code = '''
__attribute__((noinline)) int clash_probe(void)
{
volatile char buf[65536];
buf[0] = 1;
return buf[0];
}
int main(void) { return clash_probe() - 1; }
'''
if c.links(
stack_clash_test_code,
name: 'stack-clash-protection link support',
args: ['-fstack-clash-protection'],
)
if meson.can_run_host_binaries()
stack_clash_result = c.run(
stack_clash_test_code,
name: 'stack-clash-protection run support',
args: [
'-fstack-clash-protection',
],
)
if stack_clash_result.returncode() == 0
warning_flags += '-fstack-clash-protection'
endif
else
#Host binaries cannot be executed in this environment - keep the flag, the link check passed
warning_flags += '-fstack-clash-protection'
endif
endif
if target_machine.cpu_family() == 'ppc64'
#power pc builds generate a lot of warnings/notes about ABI changes since GCC-5
#this flag is disabling them because this is way too noisy.
warning_flags += ['-Wno-psabi']
elif target_machine.cpu_family() == 'x86_64'
warning_flags += ['-fcf-protection=full'] #this may be linux only at this time.
#zero the callee-saved regs left by calls so they cannot seed ROP gadgets;
#skipped on Clang < 16 (codegen bug) and dropped by get_supported_arguments on older GCC
if not (c.get_id().contains('clang') and not c.version().version_compare('>=16.0'))
warning_flags += '-fzero-call-used-regs=used-gpr'
endif
elif target_machine.cpu_family() == 'aarch64'
warning_flags += ['-mbranch-protection=standard']
if not (c.get_id().contains('clang') and not c.version().version_compare('>=16.0'))
warning_flags += '-fzero-call-used-regs=used-gpr'
endif
endif
linker_flags += ['-Wl,-z,noexecstack', '-Wl,-z,relro', '-Wl,-z,now']
# lld-family linkers (lld-link for the MSVC interface, ld.lld for the GNU interface)
# do not know --no-copy-dt-needed-entries: they warn and ignore it, so the support
# probe "passes" (exit 0) and the flag ends up on every link line. lld already does
# not copy DT_NEEDED entries by default; state it explicitly only for toolchains
# where the probe genuinely validates it (older binutils < 2.22).
if not c.get_linker_id().contains('lld')
linker_flags += '-Wl,--no-copy-dt-needed-entries'
endif
#DF_1_NOOPEN (-z,nodlopen) is a build option so targets that must remain dlopen()-able
#can disable it; --no-copy-dt-needed-entries is the binutils default since 2.22 but is
#stated explicitly for systems that still link with older toolchains
if get_option('nodlopen')
linker_flags += '-Wl,-z,nodlopen'
endif
fortifytest = ''' #include <stdio.h>
int main() {
return 0;
}
'''
fortifyresult = c.compiles(
fortifytest,
name: '_FORTIFY_SOURCE override',
args: ['-U_FORTIFY_SOURCE', '-D_FORTIFY_SOURCE=5', '-Werror'],
)
if fortifyresult == true
warning_flags += ['-U_FORTIFY_SOURCE', '-D_FORTIFY_SOURCE=3']
endif
elif c.get_id().contains('msvc')
#See here for enabling/disabling msvc warnings:
#https://learn.microsoft.com/en-us/cpp/build/reference/compiler-option-warning-level?view=msvc-170
#warnings off by default: https://learn.microsoft.com/en-us/cpp/preprocessor/compiler-warnings-that-are-off-by-default?view=msvc-170
warning_flags = [
#Turn off the following warnings. If using /wall in Windows, many of these show all over the Windows API
#This is likely not an issue with meson, but matching VS project files for now
'/wd4214', # nonstandard extension used : bit field types other than int
'/wd4201', # nonstandard extension used : nameless struct/union
'/wd4668', # 'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives'. While like -Wundef, this creates too many warnings in system headers to use
'/wd4820', # 'bytes' bytes padding added after construct 'member_name'
'/wd4710', # 'function' : function not inlined
'/wd5045', # Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified
'/wd4711', # function 'function' selected for inline expansion
'/wd4324', # 'struct_name' : structure was padded due to __declspec(align())
'/wd4221', # nonstandard extension used : 'identifier' : cannot be initialized using address of automatic variable
'/wd4204', # nonstandard extension used : non-constant aggregate initializer
'/wd5105', # macro expansion producing 'defined' has undefined behavior
'/wd4746', # volatile access of '<expression>' is subject to /volatile:[iso|ms] setting; consider using __iso_volatile_load/store intrinsic functions.
#Turn on the following warnings to make the output more useful or like GCC/clang
'/w34255', # 'function' : no function prototype given: converting '()' to '(void)'
'/w34062', # enumerator 'identifier' in switch of enum 'enumeration' is not handled
'/w34101', # 'identifier' : unreferenced local variable
'/w34189', # 'identifier' : local variable is initialized but not referenced
'/w35031', # #pragma warning(pop): likely mismatch, popping warning state pushed in different file
'/w35032', # detected #pragma warning(push) with no corresponding #pragma warning(pop)
'/w35262', # implicit fall-through occurs here; are you missing a break statement? Use [[fallthrough]] when a break statement is intentionally omitted between cases
'/w34242', # identifier conversion from type 1 to type 2, possible loss of data (matches -wconversion above)
'/w34254', # operator conversion from type 1 to type 2, possible loss of data (matches -wconversion above)
'/w34287', # operator: unsigned/negative constant mismatch (matches -wconversion above)
'/w34296', # operator: expression is always false
'/w34365', # action: conversion from type 1 to type 2, signed/unsigned mismatch (matches -wconversion above)
'/w34388', # implicit conversion warning during a comparison (matches -wconversion above)
'/w34545', # expression before comma evaluates to a function which is missing an argument list
'/w34546', # function call before comma missing argument list
'/w34547', # 'operator' : operator before comma has no effect; expected operator with side-effect
'/w34548', # expression before comma has no effect; expected expression with side-effect
'/w34549', # 'operator1': operator before comma has no effect; did you intend 'operator2'?
'/w34574', # 'identifier' is defined to be '0': did you mean to use '#if identifier'?
'/w34605', # '/Dmacro' specified on current command line, but was not specified when precompiled header was built
'/w34555', # expression has no effect; expected expression with side-effect
'/w34774', # 'string' : format string expected in argument number is not a string literal
'/w34777', # 'function' : format string 'string' requires an argument of type 'type1', but variadic argument number has type 'type2'
'/w34826', # Conversion from 'type1' to 'type2' is sign-extended. This may cause unexpected runtime behavior (more -wconversion)
'/w35219', # implicit conversion from 'type-1' to 'type-2', possible loss of data (-wconversion)
'/w35240', # 'attribute-name': attribute is ignored in this syntactic position
'/w35245', # 'function': unreferenced function with internal linkage has been removed
'/w35264', # 'variable-name': 'const' variable is not used
'/w24302', # 'conversion': truncation from 'type1' to 'type2'
'/w14311', # 'variable': pointer truncation from 'type' to 'type'
'/w14312', # 'operation': conversion from 'type1' to 'type2' of greater size
'/w14319', # 'operator': zero extending 'type1' to 'type2' of greater size
#Treat the following as errors
'/we4431', # missing type specifier - int assumed. Note: C no longer supports default-int
'/we4905', # wide string literal cast to 'LPSTR'
'/we4906', # string literal cast to 'LPWSTR'
'/we4837', # trigraph detected: '??character' replaced by 'character'
'/we4628', # digraphs not supported with -Ze. Character sequence 'digraph' not interpreted as alternate token for 'char'
'/we4289', # nonstandard extension used : 'var' : loop control variable declared in the for-loop is used outside the for-loop scope
'/we4464', # relative include path contains '..'
'/GS', #security cookie for stack protection
'/sdl', #adds recommended security development lifecycle checks
'/Qspectre',
'/guard:cf', #control flow guard
'/d2guard4', #control flow guard
]
if target_machine.cpu_family() == 'x86_64' or target_machine.cpu_family() == 'x86'
# https://learn.microsoft.com/en-us/cpp/build/reference/qintel-jcc-erratum?view=msvc-170
warning_flags += '/QIntel-jcc-erratum'
endif
if c.has_argument('/std:clatest')
warning_flags += '/std:clatest'
elif c.has_argument('/std:c17')
warning_flags += '/std:c17'
elif c.has_argument('/std:c11')
warning_flags += '/std:c11'
endif
linker_flags += [
'/guard:cf', #control flow guard
'/SafeSEH', #on by default in x64 so it is unrecognized otherwise.
'/NXCOMPAT', #data execution prevention
'/dynamicbase', #address space randomization
]
elif c.get_id().contains('xlc')
#This section is for IBM's xlc compiler and warning options it may need.
#NOTE: xlcclang should be handled above
#See following links:
#https://www.ibm.com/docs/en/xl-c-and-cpp-aix/16.1?topic=reference-individual-xl-compiler-option-descriptions
#https://www.ibm.com/docs/en/xl-c-and-cpp-aix/16.1?topic=reference-supported-xl-compiler-options-by-different-invocations
#https://www.ibm.com/docs/en/xl-c-and-cpp-aix/16.1?topic=end-mapping-legacy-xl-compiler-options-gcc-options
#https://www.ibm.com/docs/en/xl-c-and-cpp-aix/16.1?topic=reference-individual-xl-compiler-option-descriptions
#https://www.ibm.com/docs/en/xl-c-and-cpp-aix/16.1?topic=descriptions-qlanglvl-std
warning_flags = []
endif
# =============================================================================
# REPRODUCIBLE BUILD SUPPORT
# =============================================================================
source_epoch = ''
posixshell = find_program('sh', required: false)
bashshell = find_program('bash', required: false)
# 1. Check for SOURCE_DATE_EPOCH environment variable using shell
if posixshell.found()
env_cmd = run_command(posixshell, '-c', 'echo $SOURCE_DATE_EPOCH', check: false)
if env_cmd.returncode() == 0 and env_cmd.stdout().strip() != ''
source_epoch = env_cmd.stdout().strip()
endif
elif bashshell.found()
env_cmd = run_command(bashshell, '-c', 'echo $SOURCE_DATE_EPOCH', check: false)
if env_cmd.returncode() == 0 and env_cmd.stdout().strip() != ''
source_epoch = env_cmd.stdout().strip()
endif
else
# Probably in Windows, so check for powershell and try to get the environment variable from there
powershell = find_program('pwsh', 'powershell', required: false)
if powershell.found()
env_cmd = run_command(
powershell,
'-NoProfile',
'-NonInteractive',
'-Command',
'[Environment]::GetEnvironmentVariable("SOURCE_DATE_EPOCH")',
check: false,
)
if env_cmd.returncode() == 0 and env_cmd.stdout().strip() != ''
source_epoch = env_cmd.stdout().strip()
endif
else
cmdexe = find_program('cmd.exe', required: false)
if cmdexe.found()
# cmd.exe is the last resort
env_cmd = run_command(cmdexe, '/c', 'echo %SOURCE_DATE_EPOCH%', check: false)
if env_cmd.returncode() == 0 and env_cmd.stdout().strip() != '' and env_cmd.stdout().strip() != '%SOURCE_DATE_EPOCH%'
source_epoch = env_cmd.stdout().strip()
endif
endif
endif
endif
# 2. If Env Var is empty, try to fetch from Git
if source_epoch == ''
git = find_program('git', required: false)
if git.found()
# Get the last commit timestamp (Unix Epoch format)
git_cmd = run_command(git, 'log', '-1', '--pretty=%ct', check: false)
if git_cmd.returncode() == 0
source_epoch = git_cmd.stdout().strip()
endif
endif
endif
# 3. If we found a timestamp, format it and pass to C compiler
if source_epoch != ''
# Format: "%b %d %Y" -> "Nov 17 2025"
# Note: __DATE__ uses space padding for days < 10 (e.g. "Nov 7 2025").
# Try Python first (most reliable, handles formatting consistently)
python = find_program('python3', 'python', required: false)
if python.found()
py_script = (
'import datetime; ' + 'ts = int(' + source_epoch + '); ' + 'dt = datetime.datetime.fromtimestamp(ts, datetime.timezone.utc);' + 'print(dt.strftime("%b %d %Y").replace(" 0", " "));'
)
date_cmd = run_command(python, '-c', py_script, check: false)
if date_cmd.returncode() == 0
formatted_date = date_cmd.stdout().strip()
message('Reproducible Build: Setting BUILD_TIMESTAMP to "' + formatted_date + '" (via Python)')
add_project_arguments('-DBUILD_TIMESTAMP="' + formatted_date + '"', language: 'c')
endif
endif
# Fallback to date command if Python failed or not found
if not python.found() or date_cmd.returncode() != 0
message('Reproducible Build: Python not available, trying date command')
# Try GNU date first (Linux, MUSL)
date_cmd = run_command('sh', '-c', 'date -u -d @' + source_epoch + ' "+%b %_d %Y" 2>/dev/null', check: false)
if date_cmd.returncode() != 0
# Try BSD date (FreeBSD, macOS, OpenBSD, NetBSD, DragonFlyBSD)
date_cmd = run_command('sh', '-c', 'date -u -r ' + source_epoch + ' "+%b %_d %Y" 2>/dev/null', check: false)
endif
if date_cmd.returncode() == 0
formatted_date = date_cmd.stdout().strip()
message('Reproducible Build: Setting BUILD_TIMESTAMP to "' + formatted_date + '" (via date command)')
add_project_arguments('-DBUILD_TIMESTAMP="' + formatted_date + '"', language: 'c')
else
message('Reproducible Build: Failed to format timestamp. Using compiler default (__DATE__).')
endif
endif
else
message('Reproducible Build: No SOURCE_DATE_EPOCH or Git found. Using compiler default (__DATE__).')
endif
# =============================================================================
add_project_arguments(c.get_supported_arguments(warning_flags), language: 'c')
add_project_link_arguments(c.get_supported_link_arguments(linker_flags), language: 'c')
small_code_cc_flags = []
small_code_link_flags = []
if (c.get_id() == 'gcc' or c.get_id() == 'clang') and target_machine.system() != 'windows'
small_code_cc_flags = ['-ffunction-sections', '-fdata-sections']
small_code_link_flags = ['-Wl,--gc-sections']
#if GCC less than 5, need to set -std=gnu99 at minimum. gnu11 became the default in 5, 17 default in 7 or 8.
#TODO: May be able to move to c11/gnu11 instead, but will need to do a lot of testing first
#skipping sunos since this was a compatibility issue that was reported earlier. May be able to find a better way to handle this in the future.
if not (target_machine.system() == 'sunos') and c.get_id().contains('gcc')
if c.version().version_compare('<5.0')
#4.7.4+ has C11 support, but c89 is the default standard so we need to change it.
if c.has_argument('-std=gnu11')
add_project_arguments('-std=gnu11', language: 'c')
elif c.has_argument('-std=gnu99')
# Add this argument to the list since C99 is a minimum required C compiler standard
add_project_arguments('-std=gnu99', language: 'c')
else
error('C99/GNU99 standard is required but was not able to be set!')
endif
endif
endif
endif
add_global_arguments(c.get_supported_arguments(small_code_cc_flags), language: 'c')
add_global_link_arguments(c.get_supported_link_arguments(small_code_link_flags), language: 'c')
if not get_option('tcg').enabled()
add_project_arguments('-DDISABLE_TCG_SUPPORT', language: 'c')
endif
if get_option('atasecsetpass').enabled()
add_project_arguments('-DENABLE_ATA_SET_PASSWORD', language: 'c')
endif
common_sources = ['src/EULA.c', 'src/openseachest_util_options.c']
os_deps = []
# This software targets Windows Vista and up
# note: It *might* be possible to get XP, but there are significant limitations
# that need handling within the code to make it work properly...or close to properly.
winsubsystem = 'console,6.0'
if target_machine.system() == 'windows'
windows = import('windows')
resources = windows.compile_resources('openSeaChest.rc')
common_sources += [resources]
add_project_arguments('-D_CRT_SECURE_NO_WARNINGS', language: 'c')
if target_machine.cpu_family() == 'aarch64' or target_machine.cpu_family() == 'arm'
# ARM support added in Windows 8.1 and up
winsubsystem = 'console,6.02'
endif
# GNU-mode compilers (gcc-family argument syntax) driving lld-link pass
# -Wl,/SUBSYSTEM:NAME,VER and the driver splits -Wl, on the first comma,
# leaking the version as a stray input file ("could not open '6.0'").
# MSVC-syntax compilers (cl.exe, clang-cl) pass the value as a single
# token, and other linkers (link.exe, ld.lld, MinGW ld.bfd/ld.gold) split
# it correctly, so they keep the comma-version. lld-link's CONSOLE
# defaults are already exactly 6.00 (x86/x64) / 6.02 (ARM), so the
# version-less value is value-identical there.
if c.get_argument_syntax() == 'gcc' and c.get_linker_id() == 'lld-link'
winsubsystem = winsubsystem.split(',')[0]
warning('GNU-mode compiler with lld-link: Windows subsystem set to "' + winsubsystem + '" (version stripped; equals lld-link CONSOLE default)')
endif
endif
usehelp2man = false
if target_machine.system() != 'windows'
if meson.can_run_host_binaries()
help2man = find_program('help2man', required: false)
if help2man.found()
usehelp2man = true
endif
endif
endif
# The subprojects' ssp option yields to this project's value (yield : true
# in their meson_options.txt), so nothing to forward.
opensea_common = subproject('opensea-common', default_options: 'default_library=static')
opensea_common_dep = opensea_common.get_variable('opensea_common_dep')
opensea_transport = subproject('opensea-transport', default_options: 'default_library=static')
opensea_transport_dep = opensea_transport.get_variable('opensea_transport_dep')
csmisupport = opensea_transport.get_variable('csmisupport')
if csmisupport.enabled()
add_project_arguments('-DENABLE_CSMI', language: 'c')
endif
opensea_operations = subproject('opensea-operations', default_options: 'default_library=static')
opensea_operations_dep = opensea_operations.get_variable('opensea_operations_dep')
jsonc_dep = disabler()
opensea_jsonformat_dep = disabler()
if get_option('json_outputformat')
message('json_outputformat=true: Build opensea_jsonformat')
add_project_arguments('-DFEATURE_JSONOUTPUT_SUPPORT', language: 'c')
force_jsonc_wrap = false
if host_machine.system() == 'sunos'
if meson.version().version_compare('>=1.2.0')
if target_machine.kernel() != 'illumos'
force_jsonc_wrap = true
endif
else
# Need a different way to decide illumos detection here.
force_jsonc_wrap = true
endif
endif
if force_jsonc_wrap
# Force subproject on Solaris
jsonc_proj = subproject(
'json-c',
default_options: [
'default_library=static',
'werror=false',
'build_apps=false',
'extra_libs=false',
'disable_json_pointer=false',
'disable_json_patch=false',
],
)
jsonc_dep = jsonc_proj.get_variable('jsonc_dep')
else
# Simplify json-c dependency with fallback
jsonc_dep = dependency(
'json-c',
required: true,
fallback: ['json-c', 'jsonc_dep'],
default_options: [
'default_library=static',
'werror=false',
'build_apps=false',
'extra_libs=false',
'disable_json_pointer=false',
'disable_json_patch=false',
],
)
endif
# Now that json-c is set up, build opensea-jsonformat subproject
# Pass BUILD_TIMESTAMP to opensea-jsonformat for reproducible builds
jsonformat_options = []
if source_epoch != ''
jsonformat_options += 'build_timestamp=' + formatted_date
endif
opensea_jsonformat = subproject('opensea-jsonformat', default_options: jsonformat_options)
opensea_jsonformat_dep = opensea_jsonformat.get_variable('opensea_jsonformat_dep')
endif
incdir = include_directories('include')
exe_src_map = {
#This exists to allow mapping an exe from a specific filename to a different output name.
#the openSeaChest_Format tool was called openSeaChest_FormatUnit before NVMe was added and needed this map for a while.
#This is no longer needed at this time, but may end up used in the future as more utilities are migrated to openSeaChest
}
foreach p : get_option('tools')
exe_deps = [
opensea_common_dep,
opensea_transport_dep,
opensea_operations_dep,
ssp_support_dep,
os_deps,
]
# Only add JSON dependencies if the feature is enabled
if get_option('json_outputformat')
exe_deps += [jsonc_dep, opensea_jsonformat_dep]
endif
executable(
'openSeaChest_' + p,
common_sources,
'utils/C/openSeaChest/openSeaChest_' + exe_src_map.get(p, p) + '.c',
dependencies: exe_deps,
include_directories: incdir,
install: true,
win_subsystem: winsubsystem,
gnu_symbol_visibility: 'hidden',
)
if usehelp2man
#use help2man to generate manpages before installing them
run_command(
help2man,
'-o',
meson.project_source_root() + '/docs/man/man8/openSeaChest_' + exe_src_map.get(p, p) + '.8',
meson.project_build_root() + '/openSeaChest_' + exe_src_map.get(p, p),
check: false,
)
endif
install_man('docs/man/man8/openSeaChest_' + exe_src_map.get(p, p) + '.8')
endforeach
install_man('docs/man/man8/openSeaChest.8')