generated from oracle/template-repo
-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathconfigure.py
More file actions
executable file
·4361 lines (3852 loc) · 193 KB
/
configure.py
File metadata and controls
executable file
·4361 lines (3852 loc) · 193 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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
# -*- coding: utf-8 -*-
# pylint: disable=bare-except
# pylint: disable=consider-using-f-string
# pylint: disable=global-statement
# pylint: disable=line-too-long
# pylint: disable=too-many-lines
# pylint: disable=unnecessary-semicolon
# pylint: disable=import-error
# pylint: disable=import-outside-toplevel
# pylint: disable=invalid-name
# pylint: disable=multiple-statements
# pylint: disable=line-too-long
# $Id: configure.py 113488 2026-03-20 21:02:11Z klaus.espenlaub@oracle.com $
#
# The following checks for the right (i.e. most recent) Python binary available
# and re-starts the script using that binary (like a shell wrapper).
#
# Using a shebang like "#!/bin/env python" on newer Fedora/Debian distros is banned [1]
# and also won't work on other newer distros (Ubuntu >= 23.10), as those only ship
# python3 without a python->python3 symlink anymore.
#
# [1] https://lists.fedoraproject.org/archives/list/devel@lists.fedoraproject.org/message/2PD5RNJRKPN2DVTNGJSBHR5RUSVZSDZI/
''':'
for python_bin in python3 python
do
type "$python_bin" > /dev/null 2>&1 && exec "$python_bin" "$0" "$@"
done
echo >&2 "ERROR: Python not found! Please install this first in order to run this program."
exit 1
':'''
#
# Configuration script for building VirtualBox.
#
# Requires >= Python 3.6.
#
__copyright__ = \
"""
Copyright (C) 2025-2026 Oracle and/or its affiliates.
This file is part of VirtualBox base platform packages, as
available from https://www.virtualbox.org.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, in version 3 of the
License.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <https://www.gnu.org/licenses>.
SPDX-License-Identifier: GPL-3.0-only
"""
#
# The script is designed to check for the presence of various libraries and tools required for building VirtualBox.
# It uses a modular approach with classes like `LibraryCheck`, `ToolCheck` and 'FeatureCheck' to verify the availability
# of dependencies. Those classes are derived from a common CheckBase class.
#
# Each class instance represents a specific library, tool or feature and contains methods to check for its presence,
# validates its version, and provides appropriate feedback.
#
# - LibraryCheck: A class which checks for a certain (system or third-party library) required for building VirtualBox.
# - ToolCheck : A third party tool (binary, script, ...) required for building VirtualBox or one of its dependencies.
# - FeatureCheck: A feature of VirtualBox which needs further checking in order to get built.
# Only use this as a last resort if our regular (in-tree) Makefiles can't (or won't) handle this!
#
# To add a new library check:
# 1. Create an instance of `LibraryCheck` with the required parameters (name, header files, library files, etc.).
# 2. Append this instance to the `g_aoLibs` list.
#
# To add a new tool check:
# 1. Create an instance of `ToolCheck` with the required parameters (name, command names, etc.).
# 2. Append this instance to the `g_aoTools` list.
#
# To add a new feature check:
# 1. Create an instance of `FeatureCheck` with the required parameters (name, etc.).
# 2. Append this instance to the `g_aoFeatures` list.
#
# The script handles different build targets and architectures, and it generates output files like 'AutoConfig.kmk'
# and 'env.sh' / 'env.bat' based on the checks performed.
#
# External Python modules or other dependencies are not allowed!
#
__revision__ = "$Revision: 113488 $"
import argparse
import collections;
import ctypes
import datetime
import fnmatch
import glob
import importlib;
import io
import os
import platform
import re
import shlex
import shutil
import signal
import subprocess
import sysconfig # Since Python 3.2.
import sys
import tempfile
# Check for minimum Python version first.
g_uMinPythonVerTuple = (3, 6);
if sys.version_info < g_uMinPythonVerTuple:
sys.exit(f"Python {g_uMinPythonVerTuple[0]}.{g_uMinPythonVerTuple[1]} or newer is required, found {sys.version_info.major}.{sys.version_info.minor}")
# Handle to log file (if any).
g_fhLog = None;
g_sScriptPath = os.path.abspath(os.path.dirname(__file__));
g_sScriptName = os.path.basename(__file__);
g_sOutPath = os.path.join(g_sScriptPath, 'out');
class Log(io.TextIOBase):
"""
Duplicates output to multiple file-like objects (used for logging and stdout).
"""
def __init__(self, *files):
self.asFiles = files;
def write(self, data):
"""
Write data to all files.
"""
for f in self.asFiles:
f.write(data);
def flush(self):
"""
Flushes all files.
"""
for f in self.asFiles:
if not f.closed:
f.flush();
class BuildArch:
"""
Supported build architectures enumeration.
These are a subset of the kBuild architectures, (except ‚'any' and 'unknown').
"""
ANY = "any";
X86 = "x86";
AMD64 = "amd64";
ARM64 = "arm64";
UNKNOWN = "unknown";
# Map to translate the Python architecture to kBuild architecture.
g_mapPythonArch2BuildArch = {
"i386": BuildArch.X86,
"i686": BuildArch.X86,
"x86_64": BuildArch.AMD64,
"amd64": BuildArch.AMD64,
"aarch64": BuildArch.ARM64,
"arm64": BuildArch.ARM64
};
# Supported build architectures.
g_aeBuildArchs = [ BuildArch.X86, BuildArch.AMD64, BuildArch.ARM64 ];
# Defines the host architecture (pythonic name).
g_sHostArch = platform.machine().lower();
# Solaris detection kludge (skip SPARC for simplicity, ASSUMES Intel).
if 'i86pc' in g_sHostArch:
g_sHostArch = "x86_64" if "64" in platform.architecture()[0] else "i686";
# Maps host arch to build arch.
g_enmHostArch = g_mapPythonArch2BuildArch.get(g_sHostArch, BuildArch.UNKNOWN);
# Maps Python (interpreter) arch to build arch. Matches g_enmHostArch.
g_enmPythonArch = g_enmHostArch;
class BuildTarget:
"""
Supported build targets enumeration.
These represent the kBuild targets (KBUILD_TARGET + KBUILD_HOST).
"""
ANY = "os-agonstic";
LINUX = "linux";
DOS = "dos";
WINDOWS = "win";
DARWIN = "darwin";
SOLARIS = "solaris";
FREEBSD = "freebsd";
NETBSD = "netbsd";
OPENBSD = "openbsd";
OS2 = "os2";
UNKNOWN = "unknown";
# Supported build targets.
g_aeBuildTargets = [ BuildTarget.LINUX, BuildTarget.WINDOWS, BuildTarget.DARWIN, BuildTarget.SOLARIS ];
g_fDebug = False; # Enables debug mode. For development.
g_fContOnErr = False; # Continue on fatal errors.
g_sFileLog = 'configure.log'; # Log file path.
g_cVerbosity = 0; # Verbosity level (0=none, 1=min, 5=max).
g_cErrors = 0; # Number of error messages.
g_asErrors = []; # List of error messages.
g_cWarnings = 0; # Number of warning messages.
g_asWarnings = []; # List of warning messages.
# Defines the host target.
# Note! In kBuild term this is the 'host OS' (KBUILD_HOST). (In GCC cross-build
# terms, this is the build OS.)
g_sHostOS = platform.system();
# Maps Python system string to kBuild OS names.
g_enmHostOS = {
"Linux": BuildTarget.LINUX,
"Windows": BuildTarget.WINDOWS,
"Darwin": BuildTarget.DARWIN,
"Solaris": BuildTarget.SOLARIS,
"SunOS": BuildTarget.SOLARIS,
"FreeBSD": BuildTarget.FREEBSD,
"NetBSD": BuildTarget.NETBSD,
"OpenBSD": BuildTarget.OPENBSD,
"": BuildTarget.UNKNOWN
}.get(g_sHostOS, BuildTarget.UNKNOWN);
# The command line arguments. Populated in main().
g_oArgs = None;
class BuildType:
"""
Supported build types enumeration.
This resembles the kBuild targets.
"""
DEBUG = "debug";
RELEASE = "release";
PROFILE = "profile";
ASAN = "asan";
# Supported build types.
g_aeBuildTypes = [ BuildType.DEBUG, BuildType.RELEASE, BuildType.PROFILE, BuildType.ASAN ];
# Maps Visual Studio build architecture to (kBuild dir name, Windows SDK dir name).
g_mapWinVSArch2Dir = {
BuildArch.X86 : ('x86', 'Hostx86'),
BuildArch.AMD64: ('x64', 'Hostx64'),
BuildArch.ARM64: ('arm64', 'Hostarm64')
};
# Maps Visual Studio build architecture to (kBuild dir name, Windows SDK dir name).
g_mapWinSDK10Arch2Dir = {
BuildArch.X86 : ('x86', 'Hostx86'),
BuildArch.AMD64: ('x64', 'Hostx64'),
BuildArch.ARM64: ('arm64', 'Hostx64')
};
class PkgMgr:
"""
Enumeration for package managers.
"""
PKGCFG = "pkg-config";
BREW = "brew";
VCPKG = "vcpkg";
class PkgMgrVarPKGCFG:
"""
Enumeration for pkg-config variables.
"""
BINDIR = "--variable=bindir";
CFLAGS = "--cflags";
INCDIR = "--cflags-only-I";
EXECPREFIX = "--variable=exec_prefix";
LIBS = "--libs";
LIBDIR = "--variable=libdir";
LIBEXEC = "--variable=libexecdir";
PREFIX = "--variable=prefix";
class PkgMgrVarBREW:
"""
Enumeration for brew variables.
"""
PREFIX = "--prefix";
class PkgMgrVarVCPKG:
"""
Enumeration for vcpkg variables.
"""
PREFIX = "--x-install-root";
class PkgMgrVar:
""""
Class which holds the implemented variables for package managers.
Note: Not all package managers implement all variables.
"""
BINDIR = { PkgMgr.PKGCFG: PkgMgrVarPKGCFG.BINDIR };
CFLAGS = { PkgMgr.PKGCFG: PkgMgrVarPKGCFG.CFLAGS };
INCDIR = { PkgMgr.PKGCFG: PkgMgrVarPKGCFG.INCDIR };
EXECPREFIX = { PkgMgr.PKGCFG: PkgMgrVarPKGCFG.EXECPREFIX };
LIBS = { PkgMgr.PKGCFG: PkgMgrVarPKGCFG.LIBS };
LIBDIR = { PkgMgr.PKGCFG: PkgMgrVarPKGCFG.LIBDIR };
LIBEXEC = { PkgMgr.PKGCFG: PkgMgrVarPKGCFG.LIBEXEC };
PREFIX = { PkgMgr.PKGCFG: PkgMgrVarPKGCFG.PREFIX,
PkgMgr.BREW : PkgMgrVarBREW.PREFIX,
PkgMgr.VCPKG : PkgMgrVarVCPKG.PREFIX };
# Dictionary of path lists to prepend to something.
# See command line arguments '--prepend-<something>-path'.
# Note: The keys must match <something>, e.g. 'programfiles' (for parsing).
g_asPathsPrepend = { 'programfiles' : [], 'ewdk' : [], 'tools' : [] };
# Dictionary of path lists to append to something.
# See command line arguments '--append-<something>-path'.
# Note: The keys must match <something>, e.g. 'programfiles' (for parsing).
g_asPathsAppend = { 'programfiles' : [], 'ewdk' : [], 'tools' : [] };
def printWarn(sMessage, fLogOnly = False, fDontCount = False):
"""
Prints warning message to stdout.
"""
_ = fLogOnly;
print(f"[WARN]: {sMessage}", file=sys.stdout);
if not fDontCount:
globals()['g_cWarnings'] += 1;
globals()['g_asWarnings'].extend([ sMessage ]);
def printError(sMessage, fLogOnly = False, fDontCount = False):
"""
Prints an error message to stderr.
"""
_ = fLogOnly;
print(f"[ERROR]: {sMessage}", file=sys.stdout);
if not fDontCount:
globals()['g_cErrors'] += 1;
globals()['g_asErrors'].extend([ sMessage ]);
def printVerbose(uVerbosity, sMessage, fLogOnly = False):
"""
Prints a verbose message if the global verbosity level is high enough.
"""
_ = fLogOnly;
if g_cVerbosity >= uVerbosity:
print(f"=== {sMessage}");
def printLog(sMessage, sPrefix = '---'):
"""
Prints a log message to the log.
"""
if g_fhLog:
g_fhLog.write(f'{sPrefix} {sMessage}\n');
def printLogHeader():
"""
Prints the log header.
"""
printLog(f'Log created: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}');
printLog(f'Revision: {__revision__}');
printLog(f'Generated by: {g_sScriptName} ' + ' '.join(sys.argv[1:]));
printLog(f'Working directory: {os.getcwd()}');
printLog(f'Python version: {sys.version}');
printLog(f'Platform: {platform.platform()} ({platform.machine()})');
printLog('');
def pathExists(sPath, fNoLog = False):
"""
Checks if a path exists.
Returns success as boolean.
"""
fRc = sPath and os.path.exists(sPath);
if not fNoLog:
printLog('Checking if path exists: ' + (sPath if sPath else '<None>') + (' [YES]' if fRc else ' [NO]'));
return fRc;
def isDir(sDir, fNoLog = False):
"""
Checks if a path is a directory.
Returns success as boolean.
"""
fRc = sDir and os.path.isdir(sDir);
if not fNoLog:
printLog('Checking if directory exists: ' + (sDir if sDir else '<None>') + (' [YES]' if fRc else ' [NO]'));
return fRc;
def isFile(sFile, fNoLog = False):
"""
Checks if a path is a file.
Returns success as boolean.
"""
fRc = sFile and os.path.isfile(sFile);
if not fNoLog:
printLog('Checking if file exists: ' + (sFile if sFile else '<None>') + (' [YES]' if fRc else ' [NO]'));
return fRc;
def getExeSuff(enmBuildTarget = g_enmHostOS):
"""
Returns the (dot) executable suffix for a given build target.
Defaults to the host target.
"""
if enmBuildTarget != BuildTarget.WINDOWS:
return '';
return ".exe";
# Map of library suffixes. Index 0 marks the ending for static libs, index 1 for dynamic ones.
g_mapLibSuffix = {
BuildTarget.WINDOWS: [ ".lib", ".dll" ],
BuildTarget.LINUX: [ ".a", ".so" ],
BuildTarget.SOLARIS: [ ".a", ".so" ],
BuildTarget.DARWIN: [ ".a", ".dylib" ]
}
def getFileLibSuff(sFilename, enmBuildTarget = g_enmHostOS, sDefaultSuff = None):
"""
Returns the suffix of the given library file name. Must match the given target (host target by default).
If no suffix found and sDefaultSuff is empty, the dynamic suffix for the given target will be returned.
"""
asExt = os.path.splitext(sFilename);
if asExt and len(asExt) >= 1:
sSuff = asExt[1];
if not sSuff:
sSuff = sDefaultSuff if sDefaultSuff else g_mapLibSuffix[enmBuildTarget][1];
assert sSuff in g_mapLibSuffix[enmBuildTarget];
return sSuff;
return '';
def getLibSuff(fStatic = True, enmBuildTarget = g_enmHostOS):
"""
Returns the (dot) library suffix for a given build target.
By default static libraries suffixes will be returned.
Defaults to the host target.
"""
return g_mapLibSuffix[enmBuildTarget][0 if fStatic else 1];
def hasLibSuff(sFilename, fStatic = True):
"""
Return True if a given file name has a (static) library suffix,
or False if not.
"""
assert sFilename;
return sFilename.endswith(getLibSuff(fStatic));
def withLibSuff(sFile, fStatic = True):
"""
Returns sFile with a (static) library suffix.
With sFile already has a (static) library suffix, the original
value will be returned.
"""
assert sFile;
if hasLibSuff(sFile, fStatic):
return sFile;
return sFile + getLibSuff(fStatic);
def stripLibSuff(sLib):
"""
Strips common static/dynamic library suffixes (UNIX, macOS, Windows) from a filename.
Returns None if no or empty library is specified.
"""
if not sLib:
return None;
# Handle .so.X[.Y...] versioned shared libraries.
sLib = re.sub(r'\.so(\.\d+)*$', '', sLib);
# Handle .dylib (macOS), .dll/.lib (Windows), .a (static).
sLib = re.sub(r'\.(dylib|dll|lib|a)$', '', sLib, flags = re.IGNORECASE);
return sLib;
def stripPrefix(s, p):
"""
Strips a prefix from a string if present. Exists in Python 3.9 as str.removeprefix(p).
Returns string with prefix removed.
"""
if s.startswith(p):
return s[len(p):];
else:
return s;
def stripPrefixFromWhitespaceSeparatedString(s, p):
"""
Strips a prefix from all the parts of a string separated by whitespace.
Returns string with prefixes removed, now separated by single space.
"""
return ' '.join([stripPrefix(str(i), p) for i in s.split()]);
def checkWhich(sCmdName, sToolDesc = None, sCustomPath = None, asVersionSwitches = None, fMultiline = False):
"""
Helper to check for a command in PATH or custom path.
Returns a tuple of (command path, version [string or array]) or (None, None) if not found.
The version string can be None if not found.
If fMultiline is specified, the version returned either represents a string or an array.
"""
if not sCmdName:
return None, None;
sExeSuff = getExeSuff();
if not sCmdName.endswith(sExeSuff):
sCmdName += sExeSuff;
printVerbose(1, f"Checking which '{sCmdName}' ...");
sCmdPath = None;
if sCustomPath:
sCmdPath = os.path.join(sCustomPath, sCmdName);
if isFile(sCmdPath) and os.access(sCmdPath, os.X_OK):
printVerbose(1, f"Found '{sCmdName}' at custom path: {sCustomPath}");
else:
printVerbose(1, f"'{sCmdName}' not found at custom path: {sCustomPath}");
return None, None;
else:
sCmdPath = shutil.which(sCmdName);
if sCmdPath:
printVerbose(1, f"Found '{sCmdName}' at: {sCmdPath}");
# Try to get version.
if sCmdPath:
if not asVersionSwitches:
asVersionSwitches = [ '--version', '-V', '/?', '/h', '/help', '-version', 'version' ];
try:
for sSwitch in asVersionSwitches:
fWinCreationFlags = 0;
if g_enmHostOS == BuildTarget.WINDOWS: # Watcom wlink hacks:
fWinCreationFlags = getattr(subprocess, 'DETACHED_PROCESS', 0) | getattr(subprocess, 'CREATE_NO_WINDOW', 0);
oProc = subprocess.run([ sCmdPath, sSwitch ],
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
check=False, timeout=10, creationflags=fWinCreationFlags);
if oProc.returncode == 0:
oVerRet = None; # String or array (depending on fMultiline).
asVer = None;
try:
asVer = oProc.stdout.decode('utf-8', 'replace').strip().splitlines();
except UnicodeDecodeError:
pass;
if not asVer: # Some programs (java, for instance) output their version info in stderr.
try:
asVer = oProc.stderr.decode('utf-8', 'replace').strip().splitlines();
except UnicodeDecodeError:
pass;
if asVer:
oVerRet = asVer[0] if not fMultiline else asVer;
printVerbose(1, f"Detected version for '{sCmdName}' is: {oVerRet}");
else:
printVerbose(1, f"No version for '{sCmdName}' returned");
return sCmdPath, oVerRet;
return sCmdPath, None;
except subprocess.SubprocessError as ex:
printError(f"Error while checking version of {sToolDesc if sToolDesc else sCmdName}: {str(ex)}");
return None, None;
printVerbose(1, f"'{sCmdName}' not found in PATH.");
return None, None;
def getLinkerArgs(asLibPaths, asLibFiles, enmBuildTarget):
"""
Returns the linker arguments for the library as a list.
Returns an empty list for no arguments.
"""
if not asLibFiles:
return [];
asLinkerArg = [];
if enmBuildTarget == BuildTarget.WINDOWS:
asLinkerArg.extend([ '/link' ]);
for sLibCur in asLibFiles:
if not sLibCur:
continue;
if enmBuildTarget == BuildTarget.WINDOWS:
asLinkerArg.extend([ withLibSuff(sLibCur) ]);
else:
sLibPath = os.path.dirname(sLibCur);
# Absolute path not covered by the library paths?
if sLibPath and sLibPath not in asLibPaths:
asLinkerArg += [ f'{sLibCur}' ];
else:
sLibName = os.path.basename(sLibCur);
# Remove 'lib' prefix if present for -l on UNIX-y OSes (libfoo -> -lfoo):
if sLibName.startswith('lib'):
sLibName = sLibName[3:];
sLibName = stripLibSuff(sLibName);
asLinkerArg += [ f'-l{sLibName}' ];
return asLinkerArg;
def hasCPPHeader(asHeader):
"""
Rough guess which headers require C++.
Header selection is based on the library test programs of this file.
Returns True if it requires C++, False if C only.
"""
if len(asHeader) == 0:
return False; # ASSUME C on empty headers.
asCPPHdr = [ 'c++', 'iostream', 'Qt', 'QtGlobal', 'qcoreapplication.h', 'stdsoap2.h' ];
for sCurHdr in asHeader:
if sCurHdr.endswith(('.hpp', '.hxx', '.hh')):
return True;
sMatch = [h for h in asCPPHdr if h in sCurHdr];
if sMatch:
return True;
return False;
def getWinError(uCode):
"""
Returns an error string for a given Windows error code.
"""
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
wszBuf = ctypes.create_unicode_buffer(2048);
dwBuf = ctypes.windll.kernel32.FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
None, uCode, 0, # Default language.
wszBuf, len(wszBuf), None);
if dwBuf:
return wszBuf.value.strip();
return f'{uCode:#x}'; # Return the plain error (as hex).
def getSignalName(uSig):
"""
Returns the name of a POSIX signal.
"""
try:
return signal.Signals(uSig).name;
except ValueError:
pass;
return f"SIG{uSig}";
def getSignalDesc(uSig):
"""
Returns the description of a POSIX signal.
"""
strsignal = getattr(signal, "strsignal", None);
if callable(strsignal):
try:
sDesc = strsignal(uSig);
if sDesc:
return sDesc;
except ValueError:
pass;
return "";
def getPosixError(uCode):
"""
Returns an error string for a given POSIX error code.
"""
uSig = None;
if 0 <= uCode <= 255:
if uCode > 128: # Signal (128 + signal number)
uSig = uCode - 128;
else:
return f"Exit status {uCode}";
elif uCode < 0: # Signal
uSig = abs(uCode);
sName = getSignalName(uSig);
sDesc = getSignalDesc(uSig);
if sDesc:
return f"Killed by signal {sName} ({sDesc})";
return f"Killed by signal {sName}";
def compileAndRun(sName, asIncPaths, asLibPaths, asIncFiles, asLibFiles, \
sCode, fRun = True, \
enmBuildTarget = g_enmHostOS, enmBuildArch = g_enmHostArch,
oEnv = None, asCompilerArgs = None, asLinkerArgs = None, asDefines = None, fLog = True, fErrorsAsWarnings = False):
"""
Compiles and runs (executes) a test program.
Returns a tuple (Success, StdOut, StdErr).
"""
_ = enmBuildArch;
fRet = False;
sStdOut = sStdErr = None;
printVerbose(1, f'Compiling and executing "{sName}" ...');
if enmBuildTarget == BuildTarget.WINDOWS:
fCPP = True;
sCompiler = g_oArgs.config_cpp_compiler;
else:
fCPP = hasCPPHeader(asIncFiles);
sCompiler = g_oArgs.config_cpp_compiler if fCPP else g_oArgs.config_c_compiler;
if not sCompiler:
printError(f'No compiler found for test program "{sName}"');
return False, None, None;
if g_fDebug:
sTempDir = tempfile.gettempdir();
else:
sTempDir = tempfile.mkdtemp();
asFilesToDelete = []; # For cleanup
sFileSource = os.path.join(sTempDir, "testlib.cpp" if fCPP else "testlib.c");
asFilesToDelete.extend( [sFileSource] );
sFileImage = os.path.join(sTempDir, "testlib" if enmBuildTarget != BuildTarget.WINDOWS else "testlib.exe");
asFilesToDelete.extend( [sFileImage] );
with open(sFileSource, "w", encoding = 'utf-8') as fh:
fh.write(sCode);
fh.close();
asCmd = [ sCompiler ];
oProcEnv = EnvManager(oEnv.env if oEnv else g_oEnv.env);
if g_fDebug:
if enmBuildTarget == BuildTarget.WINDOWS:
asCmd.extend( [ '/showIncludes' ]);
if enmBuildTarget == BuildTarget.WINDOWS:
if fCPP: # Stuff required by qt6. Probably doesn't hurt for other stuff either.
asCmd.extend([ '/Zc:__cplusplus' ]);
asCmd.extend([ '/std:c++17' ]);
asCmd.extend([ '/permissive-' ]);
if asIncPaths:
for sIncPath in asIncPaths:
oProcEnv.prependPath('INCLUDE', sIncPath);
if asLibPaths:
for sLibPath in asLibPaths:
oProcEnv.prependPath('LIB', sLibPath);
if asDefines:
for sDefine in asDefines:
asCmd.extend( [ '/D' + sDefine ] );
asCmd.extend( [ sFileSource ] );
asCmd.extend( [ '/Fe:' + sFileImage ] );
else: # Non-Windows
if asIncPaths:
for sIncPath in asIncPaths:
asCmd.extend( [ f'-I{sIncPath}' ] );
if asLibPaths:
for sLibPath in asLibPaths:
asCmd.extend( [ f'-L{sLibPath}' ] );
if asDefines:
for sDefine in asDefines:
asCmd.extend( [ f'-D{sDefine}' ] );
asCmd.extend( [ sFileSource ] );
asCmd.extend( [ '-fPIC' ] );
asCmd.extend( [ '-o', sFileImage ] );
if asCompilerArgs:
for sDef in asCompilerArgs:
asCmd.extend( [ sDef ] );
asCmd.extend(getLinkerArgs(asLibPaths, asLibFiles, enmBuildTarget));
if asLinkerArgs:
asCmd.extend(asLinkerArgs);
if g_fDebug:
printLog( 'Process environment:');
oProcEnv.printLog(' ', [ 'PATH', 'INCLUDE', 'LIB' ]);
printLog( 'Process command line:');
printLog(f' {asCmd}');
try:
# Add the compiler's path to PATH.
oProcEnv.prependPath('PATH', os.path.dirname(sCompiler));
# Try compiling the test source file.
oProc = subprocess.run(asCmd, env = oProcEnv.env, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, check = False, timeout = 15);
if oProc.returncode != 0:
sStdOut = oProc.stdout.decode("utf-8", errors="ignore");
if fLog:
fnLog = printWarn if fErrorsAsWarnings else printError;
fnLog(f'Compilation of test program for {sName} failed');
fnLog(f' { " ".join(asCmd) }', fDontCount = True);
fnLog(sStdOut, fDontCount = True);
else:
printLog(f'Compilation of test program for {sName} successful');
if not fRun:
fRet = True;
else:
# Try executing the compiled binary and capture stdout + stderr.
try:
printVerbose(2, f"Executing '{sFileImage}' ...");
oProc = subprocess.run([ sFileImage ], env = oProcEnv.env, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, check = False, timeout = 10);
if oProc.returncode == 0:
printLog(f'Running test program for {sName} successful (exit code 0)');
sStdOut = oProc.stdout.decode('utf-8', 'replace').strip();
fRet = True;
else:
sStdErr = oProc.stderr.decode("utf-8", errors="ignore") if oProc.stderr else None;
if fLog:
fnLog = printError;
if enmBuildTarget not in [ BuildTarget.WINDOWS ]:
# Some build boxes don't like running X stuff and simply SIGSEGV, so just skip those errors for now.
if oProc.returncode == -11 \
or oProc.returncode == 139: # 128 + Signal number
printVerbose(1, f'Treating return code {oProc.returncode} as warning instead of error');
printVerbose(1, 'Running on headless build box (no X11, ...)?');
fnLog = printWarn; # Just warn, don't fail.
fRet = True; # Ditto.
fnLog(f"Execution of test binary for {sName} failed with return code {oProc.returncode}:");
if enmBuildTarget == BuildTarget.WINDOWS:
fnLog(f"Windows Error { getWinError(oProc.returncode) }", fDontCount = True);
else:
fnLog(getPosixError(oProc.returncode), fDontCount = True);
if sStdErr:
fnLog(sStdErr, fDontCount = True);
except subprocess.SubprocessError as ex:
if fLog:
printError(f"Execution of test binary for {sName} failed: {str(ex)}");
printError(f' {sFileImage}', fDontCount = True);
except PermissionError as e:
printError(f'Compiler not found: {str(e)}');
except FileNotFoundError as e:
printError( 'Compiler not found:', fDontCount = True);
printError(f' { " ".join(asCmd) }', fDontCount = True);
printError(str(e));
except subprocess.SubprocessError as e:
printError( 'Invoking compiler failed:', fDontCount = True);
printError(f' { " ".join(asCmd) }', fDontCount = True);
printError(str(e));
# Clean up.
try:
if not g_fDebug:
for sFileToDel in asFilesToDelete:
try:
os.remove(sFileToDel);
except PermissionError:
pass;
os.rmdir(sTempDir);
except OSError as ex:
if fLog:
printVerbose(1, f"Failed to remove temporary files in '{sTempDir}': {str(ex)}");
return fRet, sStdOut, sStdErr;
def getPackageLibs(sPackageName):
"""
Returns a tuple (success, list) of libraries of a given package.
"""
try:
#
# Linux, Solaris and macOS
#
if g_enmHostOS in [ BuildTarget.LINUX, BuildTarget.SOLARIS, BuildTarget.DARWIN ]:
# Use pkg-config on Linux and macOS.
sCmd = f"pkg-config --libs {shlex.quote(sPackageName)}"
oProc = subprocess.run([ sCmd ], check = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True);
if oProc \
and oProc.returncode == 0:
asArg = shlex.split(oProc.stdout.strip());
asLibDir = [];
asLibName = [];
asLibs = [];
# Gather library dirs and names.
for sCurArg in asArg:
if sCurArg.startswith("-L"):
asLibDir.append(sCurArg[2:]);
elif sCurArg.startswith("-l"):
asLibName.append(sCurArg[2:]);
# For each lib, search in the lib_dirs for its corresponding file.
for sCurLibName in asLibName:
fFound = False;
asLibPattern = [ f'lib{sCurLibName}.dylib',
f'lib{sCurLibName}.so',
f'lib{sCurLibName}.a' ];
for sCurLibDir in asLibDir:
for sCurPattern in asLibPattern:
sCandidate = os.path.join(sCurLibDir, sCurPattern);
asMatches = glob.glob(sCandidate);
if asMatches:
asLibs.append(os.path.abspath(asMatches[0]));
fFound = True;
break;
if fFound:
break;
return True, asLibs;
#
# Windows
#
elif g_enmHostOS == BuildTarget.WINDOWS:
sVcPkgRoot = g_oEnv['VCPKG_ROOT'];
if sVcPkgRoot:
triplet = 'arm64-windows';
lib_dirs = [
os.path.join(sVcPkgRoot, 'installed', triplet, 'lib'),
os.path.join(sVcPkgRoot, 'installed', triplet, 'debug', 'lib')
]
libs = []
for lib_dir in lib_dirs:
if isDir(lib_dir):
for file in os.listdir(lib_dir):
if sPackageName.lower() in file.lower() and file.endswith(('.lib', '.a', '.so', '.dll', '.dylib')):
libs.append(os.path.join(lib_dir, file));
print(f"Found libraries for package '{sPackageName}' in vcpkg: {libs}");
else:
raise RuntimeError('Unsupported OS');
except subprocess.CalledProcessError:
printVerbose(1, f'Package "{sPackageName}" invalid or not found');
return False, None;
def getPackageVar(sPackageName, enmPkgMgrVar : PkgMgrVar):
"""
Returns the package variable for a given package.
Returns a tuple (Success status, Output [string, list]).
"""
try:
if not enmPkgMgrVar:
return True, '';
asCmd = None;
if g_enmHostOS in [ BuildTarget.LINUX, BuildTarget.SOLARIS, BuildTarget.DARWIN ] \
and PkgMgr.PKGCFG in enmPkgMgrVar:
# Use pkg-config on Linux and Solaris.
# On Darwin we ask pkg-config (needs to be installed through brew) first,
# then try brew down below.
asCmd = [ PkgMgr.PKGCFG,
enmPkgMgrVar[PkgMgr.PKGCFG],
shlex.quote(sPackageName) ];
elif g_enmHostOS == BuildTarget.WINDOWS:
# Detect VCPKG.
# See: https://learn.microsoft.com/en-us/vcpkg/ + https://vcpkg.io
sCmd, _ = checkWhich('vcpkg');
if sCmd:
sVcPkgRoot = g_oEnv.get('config_vcpkg_root', os.environ['VCPKG_ROOT'] if 'VCPKG_ROOT' in os.environ else None);
if sVcPkgRoot:
printVerbose(1, f"vcpkg found at '{sVcPkgRoot}'");
asCmd = [ sCmd ];
## @todo Implement this.
else:
printError('vcpkg found, but VCPKG_ROOT is not defined');
else:
raise RuntimeError('Unsupported OS');
if asCmd:
oProc = subprocess.run(asCmd, check = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True);
if oProc.returncode == 0 \
and oProc.stdout:
sRet = oProc.stdout.strip();
# Output parsing.
if enmPkgMgrVar == PkgMgrVar.INCDIR:
sRet = [f[2:] for f in sRet.split()];
return True, sRet;
# If pkg-config fails on Darwin, try asking brew instead.
if g_enmHostOS == BuildTarget.DARWIN \
and PkgMgr.BREW in enmPkgMgrVar:
asCmd = [ PkgMgr.BREW,
enmPkgMgrVar[PkgMgr.BREW],
sPackageName ];
oProc = subprocess.run(asCmd, check = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True);
if oProc.returncode == 0 \
and oProc.stdout:
sRet = oProc.stdout.strip();
return True, sRet;
except subprocess.CalledProcessError as ex:
printVerbose(1, f'Package "{sPackageName}" invalid or not found: {ex}');
return False, None;
def getPackagePath(sPackageName):
"""
Returns the package path for a given package.
"""
return getPackageVar(sPackageName, PkgMgrVar.PREFIX);
class CheckBase:
"""
Base class for checks.
"""
def __init__(self, sName, enmBuildTarget = g_enmHostOS, enmBuildArch = g_enmHostArch, aeTargets = None, aeArchs = None, aeTargetsExcluded = None):
"""
Constructor.
"""
self.sName = sName;
# Build target (i.e. BuildTarget.LINUX) to use.
# Defaults to global build target if not explicitly specified.
# Note! In kBuild term this is the 'target OS' (KBUILD_TARGET).
self.enmBuildTarget = enmBuildTarget;
# Build architecture (i.e. BuildArch.amd64) to use.
# Defaults to global build architecture if not explicitly specified.
# Note! In kBuild term this is the 'target architecture' (KBUILD_TARGET_ARCH).
self.enmBuildArch = enmBuildArch;
# Defines the list of targets which require this component.
self.aeTargets = [ BuildTarget.ANY ] if aeTargets is None else aeTargets;
# Defines the list of architectures which require this component.
self.aeArchs = [ BuildArch.ANY ] if aeArchs is None else aeArchs;
# Defines the list of excluded targets NOT requiring this component.
self.aeTargetsExcluded = aeTargetsExcluded if aeTargetsExcluded else [];
def print(self, sMessage):
"""
Prints info about the check.
"""
print(f'{self.sName}: {sMessage}');
def printLog(self, sMessage):
"""
Prints info about the check.
"""
printLog(f'{self.sName}: {sMessage}');
def printError(self, sMessage, fDontCount = False):
"""
Prints error about the check.
"""
printError(f'{self.sName}: {sMessage}', fDontCount = fDontCount);
def printWarn(self, sMessage, fDontCount = False):