-
Notifications
You must be signed in to change notification settings - Fork 0
/
SConstruct
2463 lines (2154 loc) · 91 KB
/
SConstruct
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
# SCons build recipe for the GPSD project
# Important targets:
#
# build - build the software (default)
# dist - make distribution tarball
# install - install programs, libraries, and manual pages
# uninstall - undo an install
#
# check - run regression and unit tests.
# audit - run code-auditing tools
# testbuild - test-build the code from a tarball
# website - refresh the website
# release - ship a release
#
# --clean - clean all normal build targets
# sconsclean - clean up scons dotfiles (but not the database: .sconsign.dblite)
#
# Setting the DESTDIR environment variable will prefix the install destinations
# without changing the --prefix prefix.
# Unfinished items:
# * Out-of-directory builds: see http://www.scons.org/wiki/UsingBuildDir
# * Coveraging mode: gcc "-coverage" flag requires a hack
# for building the python bindings
# * Python 3 compatibility in this recipe
# Since SCons 3.0.0 forces print_function on us, it needs to be unconditional.
# This is recognized to be a bug in SCons, but we need to live with it for now,
# and we'll need this for eventual Python 3 compatibility, anyway.
# Python requires this to precede any non-comment code.
from __future__ import print_function
# Release identification begins here
gpsd_version = "3.18~dev"
# client library version
libgps_version_current = 23
libgps_version_revision = 0
libgps_version_age = 0
# Release identification ends here
# Hosting information (mainly used for templating web pages) begins here
# Each variable foo has a corresponding @FOO@ expanded in .in files.
# There are no project-dependent URLs or references to the hosting site
# anywhere else in the distribution; preserve this property!
sitename = "Savannah"
sitesearch = "catb.org"
website = "http://catb.org/gpsd"
mainpage = "https://savannah.nongnu.org/projects/gpsd/"
webupload = "login.ibiblio.org:/public/html/catb/gpsd"
cgiupload = "[email protected]:/var/www/cgi-bin/"
scpupload = "dl.sv.nongnu.org:/releases/gpsd/"
mailman = "https://lists.nongnu.org/mailman/listinfo/"
admin = "https://savannah.nongnu.org/project/admin/?group=gpsd"
download = "http://download-mirror.savannah.gnu.org/releases/gpsd/"
bugtracker = "https://savannah.nongnu.org/bugs/?group=gpsd"
browserepo = "http://git.savannah.gnu.org/cgit/gpsd.git"
clonerepo = "https://savannah.nongnu.org/git/?group=gpsd"
gitrepo = "git://git.savannah.nongnu.org/gpsd.git"
webform = "http://www.thyrsus.com/cgi-bin/gps_report.cgi"
formserver = "[email protected]"
devmail = "[email protected]"
usermail = "[email protected]"
annmail = "[email protected]"
ircchan = "irc://chat.freenode.net/#gpsd"
tiplink = "<a href='https://www.patreon.com/esr'>" \
"leave a remittance at Patreon</a>"
tipwidget = '<p><a href="https://www.patreon.com/esr">' \
'Donate here to support continuing development.</a></p>'
# Hosting information ends here
EnsureSConsVersion(2, 3, 0)
import ast
import copy
import glob
import operator
import os
import platform
import re
import subprocess
import sys
import time
from distutils import sysconfig
from distutils.util import get_platform
from functools import reduce
import SCons
PYTHON_SYSCONFIG_IMPORT = 'from distutils import sysconfig'
# replacement for functions from the commands module, which is deprecated.
import subprocess
def _getstatusoutput(cmd, input=None, shell=True, cwd=None, env=None):
pipe = subprocess.Popen(cmd, shell=shell, cwd=cwd, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(output, errout) = pipe.communicate(input=input)
status = pipe.returncode
return (status, output)
def _getoutput(cmd, input=None, shell=True, cwd=None, env=None):
return _getstatusoutput(cmd, input, shell, cwd, env)[1]
# Spawn replacement that suppresses non-error stderr
def filtered_spawn(sh, escape, cmd, args, env):
proc = subprocess.Popen([sh, '-c', ' '.join(args)],
env=env, close_fds=True, stderr=subprocess.PIPE)
_, stderr = proc.communicate()
if proc.returncode:
sys.stderr.write(stderr)
return proc.returncode
#
# Build-control options
#
# without this, scons will not rebuild an existing target when the
# source changes.
Decider('timestamp-match')
# Start by reading configuration variables from the cache
opts = Variables('.scons-option-cache')
systemd_dir = '/lib/systemd/system'
systemd = os.path.exists(systemd_dir)
# Set distribution-specific defaults here
imloads = True
boolopts = (
# GPS protocols
("nmea0183", True, "NMEA0183 support"),
("ashtech", True, "Ashtech support"),
("earthmate", True, "DeLorme EarthMate Zodiac support"),
("evermore", True, "EverMore binary support"),
("fv18", True, "San Jose Navigation FV-18 support"),
("garmin", True, "Garmin kernel driver support"),
("garmintxt", True, "Garmin Simple Text support"),
("geostar", True, "Geostar Protocol support"),
("itrax", True, "iTrax hardware support"),
("mtk3301", True, "MTK-3301 support"),
("navcom", True, "Navcom NCT support"),
("oncore", True, "Motorola OnCore chipset support"),
("sirf", True, "SiRF chipset support"),
("skytraq", True, "Skytraq chipset support"),
("superstar2", True, "Novatel SuperStarII chipset support"),
("tnt", True, "True North Technologies support"),
("tripmate", True, "DeLorme TripMate support"),
("tsip", True, "Trimble TSIP support"),
("ublox", True, "u-blox Protocol support"),
("fury", True, "Jackson Labs Fury and Firefly support"),
("nmea2000", True, "NMEA2000/CAN support"),
# Non-GPS protocols
("aivdm", True, "AIVDM support"),
("gpsclock", True, "GPSClock support"),
("ntrip", True, "NTRIP support"),
("oceanserver", True, "OceanServer support"),
("isync", True, "Spectratime iSync LNRClok/GRCLOK support"),
("rtcm104v2", True, "rtcm104v2 support"),
("rtcm104v3", True, "rtcm104v3 support"),
("passthrough", True, "build support for passing through JSON"),
# Time service
("ntp", True, "NTP time hinting support"),
("ntpshm", True, "NTP time hinting via shared memory"),
("pps", True, "PPS time syncing support"),
("oscillator", True, "Disciplined oscillator support"),
# Export methods
("socket_export", True, "data export over sockets"),
("dbus_export", True, "enable DBUS export support"),
("shm_export", True, "export via shared memory"),
# Communication
('usb', True, "libusb support for USB devices"),
("bluez", True, "BlueZ support for Bluetooth devices"),
("ipv6", True, "build IPv6 support"),
("netfeed", True, "build support for handling TCP/IP data sources"),
# Other daemon options
("force_global", False, "force daemon to listen on all addressses"),
("timing", False, "latency timing support"),
("control_socket", True, "control socket for hotplug notifications"),
("systemd", systemd, "systemd socket activation"),
# Client-side options
("clientdebug", True, "client debugging support"),
("ncurses", True, "build with ncurses"),
("libgpsmm", True, "build C++ bindings"),
("qt", True, "build QT bindings"),
# Daemon options
("reconfigure", True, "allow gpsd to change device settings"),
("controlsend", True, "allow gpsctl/gpsmon to change device settings"),
("nofloats", False, "float ops are expensive, suppress error estimates"),
("squelch", False, "squelch gpsd_log/gpsd_hexdump to save cpu"),
# Build control
("gpsd", True, "gpsd itself"),
("gpsdclients", True, "gspd client programs"),
("shared", True, "build shared libraries, not static"),
("implicit_link", imloads, "implicit linkage is supported in shared libs"),
("python", True, "build Python support and modules."),
("debug", False, "include debug information in build"),
("profiling", False, "build with profiling enabled"),
("coveraging", False, "build with code coveraging enabled"),
("nostrip", False, "don't symbol-strip binaries at link time"),
("manbuild", True, "build help in man and HTML formats"),
("leapfetch", True, "fetch up-to-date data on leap seconds."),
("minimal", False, "turn off every option not set on the command line"),
("timeservice", False, "time-service configuration"),
("magic_hat", sys.platform.startswith('linux'),
"special Linux PPS hack for Raspberry Pi et al"),
("xgps", True, "include xgps and xgpsspeed."),
# Test control
("slow", False, "run tests with realistic (slow) delays"),
)
for (name, default, help) in boolopts:
opts.Add(BoolVariable(name, help, default))
# Gentoo, Fedora, opensuse systems use uucp for ttyS* and ttyUSB*
if os.path.exists("/etc/gentoo-release"):
def_group = "uucp"
else:
def_group = "dialout"
nonboolopts = (
("gpsd_user", "nobody", "privilege revocation user",),
("gpsd_group", def_group, "privilege revocation group"),
("prefix", "/usr/local", "installation directory prefix"),
("target_python", "python", "target Python version as command"),
("python_libdir", "", "Python module directory prefix"),
("max_clients", '64', "maximum allowed clients"),
("max_devices", '4', "maximum allowed devices"),
("fixed_port_speed", 0, "fixed serial port speed"),
("fixed_stop_bits", 0, "fixed serial port stop bits"),
("target", "", "cross-development target"),
("sysroot", "", "cross-development system root"),
("qt_versioned", "", "version for versioned Qt"),
("python_coverage", "coverage run", "coverage command for Python progs"),
)
for (name, default, help) in nonboolopts:
opts.Add(name, help, default)
pathopts = (
("sysconfdir", "etc", "system configuration directory"),
("bindir", "bin", "application binaries directory"),
("includedir", "include", "header file directory"),
("libdir", "lib", "system libraries"),
("sbindir", "sbin", "system binaries directory"),
("mandir", "share/man", "manual pages directory"),
("docdir", "share/doc", "documents directory"),
("udevdir", "/lib/udev", "udev rules directory"),
("pkgconfig", "$libdir/pkgconfig", "pkgconfig file directory"),
)
for (name, default, help) in pathopts:
opts.Add(PathVariable(name, help, default, PathVariable.PathAccept))
#
# Environment creation
#
import_env = (
"DISPLAY", # Required for dia to run under scons
"GROUPS", # Required by gpg
"HOME", # Required by gpg
"LOGNAME", # LOGNAME is required for the flocktest production.
"MACOSX_DEPLOYMENT_TARGET", # Required by MacOSX 10.4 and probably earlier
'PATH', # Required for ccache and Coverity scan-build
# Pass more environment variables to pkg-config (required for crossbuilds)
'PKG_CONFIG_LIBDIR',
'PKG_CONFIG_PATH', # Set .pc file directory in a crossbuild
# Pass more environment variables to pkg-config (required for crossbuilds)
'PKG_CONFIG_SYSROOT_DIR',
'STAGING_DIR', # Required by the OpenWRT and CeroWrt builds.
'STAGING_PREFIX', # Required by the OpenWRT and CeroWrt builds.
'WRITE_PAD', # So we can test WRITE_PAD values on the fly.
)
envs = {}
for var in import_env:
if var in os.environ:
envs[var] = os.environ[var]
envs["GPSD_HOME"] = os.getcwd()
env = Environment(tools=["default", "tar", "textfile"], options=opts, ENV=envs)
# Minimal build turns off every option not set on the command line,
if ARGUMENTS.get('minimal'):
for (name, default, help) in boolopts:
# Ensure gpsd and gpsdclients are always enabled unless explicitly
# turned off.
if ((default is True
and not ARGUMENTS.get(name)
and not (name is "gpsd" or name is "gpsdclients"))):
env[name] = False
# Time-service build = stripped-down with some diagnostic tools
if ARGUMENTS.get('timeservice'):
timerelated = ("gpsd",
"nmea0183", # For generic hats of unknown type.
"ublox", # For the Uputronics board
"mtk3301", # For the Adafruit HAT
"ipv6",
"magic_hat",
"ncurses",
"ntp",
"ntpshm",
"oscillator",
"pps",
"socket_export", )
for (name, default, help) in boolopts:
if ((default is True
and not ARGUMENTS.get(name)
and name not in timerelated)):
env[name] = False
# NTPSHM requires NTP
if env['ntpshm']:
env['ntp'] = True
# Many drivers require NMEA0183 - in case we select timeserver/minimal
# followed by one of these.
for driver in ('ashtech',
'earthmate',
'fury',
'fv18',
'gpsclock',
'mtk3301',
'oceanserver',
'skytraq',
'tnt',
'tripmate', ):
if env[driver]:
env['nmea0183'] = True
break
# iSync uses ublox underneath, so we force to enable it
if env['isync']:
env['ublox'] = True
opts.Save('.scons-option-cache', env)
env.SConsignFile(".sconsign.dblite")
for (name, default, help) in pathopts:
env[name] = env.subst(env[name])
env['VERSION'] = gpsd_version
env['SC_PYTHON'] = sys.executable # Path to SCons Python
# Set defaults from environment. Note that scons doesn't cope well
# with multi-word CPPFLAGS/LDFLAGS/SHLINKFLAGS values; you'll have to
# explicitly quote them or (better yet) use the "=" form of GNU option
# settings.
env['STRIP'] = "strip"
env['PKG_CONFIG'] = "pkg-config"
for i in ["AR", "ARFLAGS", "CCFLAGS", "CFLAGS", "CC", "CXX", "CXXFLAGS",
"LINKFLAGS", "STRIP", "PKG_CONFIG", "LD", "TAR"]:
if i in os.environ:
j = i
if i == "LD":
i = "SHLINK"
if i in ("CFLAGS", "CCFLAGS", "LINKFLAGS"):
env.Replace(**{j: Split(os.getenv(i))})
else:
env.Replace(**{j: os.getenv(i)})
for flag in ["LDFLAGS", "SHLINKFLAGS", "CPPFLAGS"]:
if i in os.environ:
env.MergeFlags({flag: Split(os.getenv(flag))})
# Keep scan-build options in the environment
for key, value in os.environ.items():
if key.startswith('CCC_'):
env.Append(ENV={key: value})
# Placeholder so we can kluge together something like VPATH builds.
# $SRCDIR replaces occurrences for $(srcdir) in the autotools build.
env['SRCDIR'] = '.'
# We may need to force slow regression tests to get around race
# conditions in the pty layer, especially on a loaded machine.
if env["slow"]:
env['REGRESSOPTS'] = "-S"
else:
env['REGRESSOPTS'] = ""
if env.GetOption("silent"):
env['REGRESSOPTS'] += " -Q"
def announce(msg):
if not env.GetOption("silent"):
print(msg)
# DESTDIR environment variable means user prefix the installation root.
DESTDIR = os.environ.get('DESTDIR', '')
def installdir(dir, add_destdir=True):
# use os.path.join to handle absolute paths properly.
wrapped = os.path.join(env['prefix'], env[dir])
if add_destdir:
wrapped = os.path.normpath(DESTDIR + os.path.sep + wrapped)
wrapped.replace("/usr/etc", "/etc")
wrapped.replace("/usr/lib/systemd", "/lib/systemd")
return wrapped
# Honor the specified installation prefix in link paths.
if env["sysroot"]:
env.Prepend(LIBPATH=[env["sysroot"] + installdir('libdir',
add_destdir=False)])
# Give deheader a way to set compiler flags
if 'MORECFLAGS' in os.environ:
env.Append(CFLAGS=Split(os.environ['MORECFLAGS']))
# Don't change CCFLAGS if already set by environment.
if 'CCFLAGS' not in os.environ:
# Should we build with profiling?
if env['profiling']:
env.Append(CCFLAGS=['-pg'])
env.Append(LDFLAGS=['-pg'])
# Should we build with coveraging?
if env['coveraging']:
env.Append(CFLAGS=['-coverage'])
env.Append(LDFLAGS=['-coverage'])
env.Append(LINKFLAGS=['-coverage'])
# Should we build with debug symbols?
if env['debug']:
env.Append(CCFLAGS=['-g3'])
# Should we build with optimisation?
if env['debug'] or env['coveraging']:
env.Append(CCFLAGS=['-O0'])
else:
env.Append(CCFLAGS=['-O2'])
# We are C99, tell the world
# env.Append(CFLAGS=['-D_ISOC99_SOURCE'])
# Turn on fault reporting
env.Append(CFLAGS=['-DTHORCOM_FAULT_REPORTING'])
# We are POSIX 2001, tell the world
# env.Append(CFLAGS=['-D_POSIX_C_SOURCE=200112L'])
# Get a slight speedup by not doing automatic RCS and SCCS fetches.
env.SourceCode('.', None)
# Cross-development
devenv = (("ADDR2LINE", "addr2line"),
("AR", "ar"),
("AS", "as"),
("CXX", "c++"),
("CXXFILT", "c++filt"),
("CPP", "cpp"),
("GXX", "g++"),
("CC", "gcc"),
("GCCBUG", "gccbug"),
("GCOV", "gcov"),
("GPROF", "gprof"),
("LD", "ld"),
("NM", "nm"),
("OBJCOPY", "objcopy"),
("OBJDUMP", "objdump"),
("RANLIB", "ranlib"),
("READELF", "readelf"),
("SIZE", "size"),
("STRINGS", "strings"),
("STRIP", "strip"))
if env['target']:
for (name, toolname) in devenv:
env[name] = env['target'] + '-' + toolname
if env['sysroot']:
env.MergeFlags({"CFLAGS": ["--sysroot=%s" % env['sysroot']]})
env.MergeFlags({"LINKFLAGS": ["--sysroot=%s" % env['sysroot']]})
# Build help
def cmp(a, b):
return (a > b) - (a < b)
Help("""Arguments may be a mixture of switches and targets in any order.
Switches apply to the entire build regardless of where they are in the order.
Important switches include:
prefix=/usr probably what you want for production tools
Options are cached in a file named .scons-option-cache and persist to later
invocations. The file is editable. Delete it to start fresh. Current option
values can be listed with 'scons -h'.
""" + opts.GenerateHelpText(env, sort=cmp))
# Configuration
def CheckPKG(context, name):
context.Message('Checking pkg-config for %s... ' % name)
ret = context.TryAction('%s --exists \'%s\''
% (env['PKG_CONFIG'], name))[0]
context.Result(ret)
return ret
# Stylesheet URLs for making HTML and man pages from DocBook XML.
docbook_url_stem = 'http://docbook.sourceforge.net/release/xsl/current/'
docbook_man_uri = docbook_url_stem + 'manpages/docbook.xsl'
docbook_html_uri = docbook_url_stem + 'html/docbook.xsl'
def CheckXsltproc(context):
context.Message('Checking that xsltproc can make man pages... ')
ofp = open("xmltest.xml", "w")
ofp.write('''
<refentry id="foo.1">
<refmeta>
<refentrytitle>foo</refentrytitle>
<manvolnum>1</manvolnum>
<refmiscinfo class='date'>9 Aug 2004</refmiscinfo>
</refmeta>
<refnamediv id='name'>
<refname>foo</refname>
<refpurpose>check man page generation from docbook source</refpurpose>
</refnamediv>
</refentry>
''')
ofp.close()
probe = "xsltproc --nonet --noout '%s' xmltest.xml" % (docbook_man_uri,)
ret = context.TryAction(probe)[0]
os.remove("xmltest.xml")
if os.path.exists("foo.1"):
os.remove("foo.1")
context.Result(ret)
return ret
def CheckCompilerOption(context, option):
context.Message('Checking if compiler accepts %s... ' % (option,))
old_CFLAGS = context.env['CFLAGS']
context.env.Append(CFLAGS=option)
ret = context.TryLink("""
int main(int argc, char **argv) {
return 0;
}
""", '.c')
if not ret:
context.env.Replace(CFLAGS=old_CFLAGS)
context.Result(ret)
return ret
def CheckHeaderDefines(context, file, define):
context.Message('Checking if %s supplies %s... ' % (file, define))
ret = context.TryLink("""
#include <%s>
#ifndef %s
#error %s is not defined
#endif
int main(int argc, char **argv) {
return 0;
}
""" % (file, define, define), '.c')
context.Result(ret)
return ret
def CheckCompilerDefines(context, define):
context.Message('Checking if compiler supplies %s... ' % (define,))
ret = context.TryLink("""
#ifndef %s
#error %s is not defined
#endif
int main(int argc, char **argv) {
return 0;
}
""" % (define, define), '.c')
context.Result(ret)
return ret
# Check if this compiler is C11 or better
def CheckC11(context):
context.Message('Checking if compiler is C11... ')
ret = context.TryLink("""
#if (__STDC_VERSION__ < 201112L)
#error Not C11
#endif
int main(int argc, char **argv) {
return 0;
}
""", '.c')
context.Result(ret)
return ret
def GetPythonValue(context, name, imp, expr, brief=False):
context.Message('Obtaining Python %s... ' % name)
context.sconf.cached = 0 # Avoid bogus "(cached)"
if not env['target_python']:
status, value = 0, str(eval(expr))
else:
command = [target_python_path, '-c',
'%s; print(%s)' % (imp, expr)]
try:
status, value = _getstatusoutput(command, shell=False)
except OSError:
status = -1
if status == 0:
value = value.strip()
else:
value = ''
announce("Python command failed - disabling Python.")
env['python'] = False
context.Result('failed' if status else 'ok' if brief else value)
return value
def GetLoadPath(context):
context.Message("Getting system load path... ")
cleaning = env.GetOption('clean')
helping = env.GetOption('help')
config = Configure(env, custom_tests={
'CheckPKG': CheckPKG,
'CheckXsltproc': CheckXsltproc,
'CheckCompilerOption': CheckCompilerOption,
'CheckCompilerDefines': CheckCompilerDefines,
'CheckC11': CheckC11,
'CheckHeaderDefines': CheckHeaderDefines,
'GetPythonValue': GetPythonValue})
# Always set up LIBPATH so that cleaning works properly.
env.Prepend(LIBPATH=[os.path.realpath(os.curdir)])
if cleaning or helping:
dbusflags = []
rtlibs = []
usbflags = []
bluezflags = []
ncurseslibs = []
confdefs = []
manbuilder = False
htmlbuilder = False
tiocmiwait = True # For cleaning, which works on any OS
else:
# OS X aliases gcc to clang
# clang accepts -pthread, then warns it is unused.
if ((config.CheckCompilerOption("-pthread")
and not sys.platform.startswith('darwin'))):
env.MergeFlags("-pthread")
confdefs = ["/* gpsd_config.h generated by scons, do not hand-hack. */\n"]
confdefs.append('#ifndef GPSD_CONFIG_H\n')
confdefs.append('#define VERSION "%s"\n' % gpsd_version)
confdefs.append('#define GPSD_URL "%s"\n' % website)
cxx = config.CheckCXX()
if not cxx and env["libgpsmm"]:
announce("C++ doesn't work, suppressing libgpsmm build.")
env["libgpsmm"] = False
# define a helper function for pkg-config - we need to pass
# --static for static linking, too.
#
# Using "--libs-only-L --libs-only-l" instead of "--libs" avoids
# a superfluous "-rpath" option in some FreeBSD cases, and the resulting
# scons crash.
# However, it produces incorrect results for Qt5Network in OSX, so
# it can't be used unconditionally.
def pkg_config(pkg, shared=env['shared'], rpath_hack=False):
libs = '--libs-only-L --libs-only-l' if rpath_hack else '--libs'
if not shared:
libs += ' --static'
return ['!%s --cflags %s %s' % (env['PKG_CONFIG'], libs, pkg)]
# The actual distinction here is whether the platform has ncurses in the
# base system or not. If it does, pkg-config is not likely to tell us
# anything useful. FreeBSD does, Linux doesn't. Most likely other BSDs
# are like FreeBSD.
ncurseslibs = []
if env['ncurses']:
if config.CheckPKG('ncurses'):
ncurseslibs = pkg_config('ncurses', rpath_hack=True)
if config.CheckPKG('tinfo'):
ncurseslibs += pkg_config('tinfo', rpath_hack=True)
# It's not yet known whether rpath_hack is appropriate for
# ncurses5-config.
elif WhereIs('ncurses5-config'):
ncurseslibs = ['!ncurses5-config --libs --cflags']
elif WhereIs('ncursesw5-config'):
ncurseslibs = ['!ncursesw5-config --libs --cflags']
elif sys.platform.startswith('freebsd'):
ncurseslibs = ['-lncurses']
elif sys.platform.startswith('openbsd'):
ncurseslibs = ['-lcurses']
elif sys.platform.startswith('darwin'):
ncurseslibs = ['-lcurses']
else:
announce('Turning off ncurses support, library not found.')
env['ncurses'] = False
if env['usb']:
# In FreeBSD except version 7, USB libraries are in the base system
if config.CheckPKG('libusb-1.0'):
confdefs.append("#define HAVE_LIBUSB 1\n")
try:
usbflags = pkg_config('libusb-1.0')
except OSError:
announce("pkg_config is confused about the state "
"of libusb-1.0.")
usbflags = []
elif sys.platform.startswith("freebsd"):
confdefs.append("#define HAVE_LIBUSB 1\n")
usbflags = ["-lusb"]
else:
confdefs.append("/* #undef HAVE_LIBUSB */\n")
usbflags = []
else:
confdefs.append("/* #undef HAVE_LIBUSB */\n")
usbflags = []
env["usb"] = False
if config.CheckLib('librt'):
confdefs.append("#define HAVE_LIBRT 1\n")
# System library - no special flags
rtlibs = ["-lrt"]
else:
confdefs.append("/* #undef HAVE_LIBRT */\n")
rtlibs = []
if env['dbus_export'] and config.CheckPKG('dbus-1'):
confdefs.append("#define HAVE_DBUS 1\n")
dbusflags = pkg_config("dbus-1")
env.MergeFlags(dbusflags)
else:
confdefs.append("/* #undef HAVE_DBUS */\n")
dbusflags = []
if env["dbus_export"]:
announce("Turning off dbus-export support, library not found.")
env["dbus_export"] = False
if env['bluez'] and config.CheckPKG('bluez'):
confdefs.append("#define ENABLE_BLUEZ 1\n")
bluezflags = pkg_config('bluez')
else:
confdefs.append("/* #undef ENABLE_BLUEZ */\n")
bluezflags = []
if env["bluez"]:
announce("Turning off Bluetooth support, library not found.")
env["bluez"] = False
# in_port_t is not defined on Android
if not config.CheckType("in_port_t", "#include <netinet/in.h>"):
announce("Did not find in_port_t typedef, assuming unsigned short int")
confdefs.append("typedef unsigned short int in_port_t;\n")
# SUN_LEN is not defined on Android
if ((not config.CheckDeclaration("SUN_LEN", "#include <sys/un.h>")
and not config.CheckDeclaration("SUN_LEN", "#include <linux/un.h>"))):
announce("SUN_LEN is not system-defined, using local definition")
confdefs.append("#ifndef SUN_LEN\n")
confdefs.append("#define SUN_LEN(ptr) "
"((size_t) (((struct sockaddr_un *) 0)->sun_path) "
"+ strlen((ptr)->sun_path))\n")
confdefs.append("#endif /* SUN_LEN */\n")
if config.CheckHeader(["bits/sockaddr.h", "linux/can.h"]):
confdefs.append("#define HAVE_LINUX_CAN_H 1\n")
announce("You have kernel CANbus available.")
else:
confdefs.append("/* #undef HAVE_LINUX_CAN_H */\n")
announce("You do not have kernel CANbus available.")
env["nmea2000"] = False
# check for C11 or better, and __STDC__NO_ATOMICS__ is not defined
# before looking for stdatomic.h
if ((config.CheckC11()
and not config.CheckCompilerDefines("__STDC_NO_ATOMICS__")
and config.CheckHeader("stdatomic.h"))):
confdefs.append("#define HAVE_STDATOMIC_H 1\n")
else:
confdefs.append("/* #undef HAVE_STDATOMIC_H */\n")
if config.CheckHeader("libkern/OSAtomic.h"):
confdefs.append("#define HAVE_OSATOMIC_H 1\n")
else:
confdefs.append("/* #undef HAVE_OSATOMIC_H */\n")
announce("No memory barriers - SHM export and time hinting "
"may not be reliable.")
# endian.h is required for rtcm104v2 unless the compiler defines
# __ORDER_BIG_ENDIAN__, __ORDER_LITTLE_ENDIAN__ and __BYTE_ORDER__
if config.CheckCompilerDefines("__ORDER_BIG_ENDIAN__") \
and config.CheckCompilerDefines("__ORDER_LITTLE_ENDIAN__") \
and config.CheckCompilerDefines("__BYTE_ORDER__"):
confdefs.append("#define HAVE_BUILTIN_ENDIANNESS 1\n")
confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
announce("Your compiler has built-in endianness support.")
else:
confdefs.append("/* #undef HAVE_BUILTIN_ENDIANNESS\n */")
if config.CheckHeader("endian.h"):
confdefs.append("#define HAVE_ENDIAN_H 1\n")
confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
confdefs.append("/* #undef HAVE_MACHINE_ENDIAN_H */\n")
elif config.CheckHeader("sys/endian.h"):
confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
confdefs.append("#define HAVE_SYS_ENDIAN_H 1\n")
confdefs.append("/* #undef HAVE_MACHINE_ENDIAN_H */\n")
elif config.CheckHeader("machine/endian.h"):
confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
confdefs.append("#define HAVE_MACHINE_ENDIAN_H 1\n")
else:
confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
confdefs.append("/* #undef HAVE_MACHINE_ENDIAN_H */\n")
announce("You do not have the endian.h header file. "
"RTCM V2 support disabled.")
env["rtcm104v2"] = False
for hdr in ("sys/un", "sys/socket", "sys/select", "netdb", "netinet/in",
"netinet/ip", "arpa/inet", "syslog", "termios", "winsock2"):
if config.CheckHeader(hdr + ".h"):
confdefs.append("#define HAVE_%s_H 1\n"
% hdr.replace("/", "_").upper())
else:
confdefs.append("/* #undef HAVE_%s_H */\n"
% hdr.replace("/", "_").upper())
# check function after libraries, because some function require libraries
# for example clock_gettime() require librt on Linux glibc < 2.17
for f in ("daemon", "strlcpy", "strlcat", "clock_gettime", "strptime",
"gmtime_r", "inet_ntop", "fcntl", "fork"):
if config.CheckFunc(f):
confdefs.append("#define HAVE_%s 1\n" % f.upper())
else:
confdefs.append("/* #undef HAVE_%s */\n" % f.upper())
if config.CheckHeader(["sys/types.h", "sys/time.h", "sys/timepps.h"]):
env.MergeFlags("-DHAVE_SYS_TIMEPPS_H=1")
kpps = True
else:
kpps = False
if env["magic_hat"]:
announce("Forcing magic_hat=no since RFC2783 API is unavailable")
env["magic_hat"] = False
tiocmiwait = config.CheckHeaderDefines("sys/ioctl.h", "TIOCMIWAIT")
if env["pps"] and not tiocmiwait and not kpps:
announce("Forcing pps=no (neither TIOCMIWAIT nor RFC2783 "
"API is available)")
env["pps"] = False
# Map options to libraries required to support them that might be absent.
optionrequires = {
"bluez": ["libbluetooth"],
"dbus_export": ["libdbus-1"],
}
keys = list(map(lambda x: (x[0], x[2]), boolopts)) \
+ list(map(lambda x: (x[0], x[2]), nonboolopts)) \
+ list(map(lambda x: (x[0], x[2]), pathopts))
keys.sort()
for (key, help) in keys:
value = env[key]
if value and key in optionrequires:
for required in optionrequires[key]:
if not config.CheckLib(required):
announce("%s not found, %s cannot be enabled."
% (required, key))
value = False
break
confdefs.append("/* %s */" % help)
if isinstance(value, bool):
if value:
confdefs.append("#define %s_ENABLE 1\n" % key.upper())
else:
confdefs.append("/* #undef %s_ENABLE */\n" % key.upper())
elif value in (0, "", "(undefined)"):
confdefs.append("/* #undef %s */\n" % key.upper())
else:
if value.isdigit():
confdefs.append("#define %s %s\n" % (key.upper(), value))
else:
confdefs.append("#define %s \"%s\"\n" % (key.upper(), value))
# Simplifies life on hackerboards like the Raspberry Pi
if env['magic_hat']:
confdefs.append('''\
/* Magic device which, if present, means to grab a static /dev/pps0 for KPPS */
#define MAGIC_HAT_GPS "/dev/ttyAMA0"
/* Generic device which, if present, means: */
/* to grab a static /dev/pps0 for KPPS */
#define MAGIC_LINK_GPS "/dev/gpsd0"
''')
confdefs.append('''\
#define GPSD_CONFIG_H
#endif /* GPSD_CONFIG_H */
''')
manbuilder = htmlbuilder = None
if env['manbuild']:
if config.CheckXsltproc():
build = "xsltproc --nonet %s $SOURCE >$TARGET"
htmlbuilder = build % docbook_html_uri
manbuilder = build % docbook_man_uri
elif WhereIs("xmlto"):
xmlto = "xmlto %s $SOURCE || mv `basename $TARGET` " \
"`dirname $TARGET`"
htmlbuilder = xmlto % "html-nochunks"
manbuilder = xmlto % "man"
else:
announce("Neither xsltproc nor xmlto found, documentation "
"cannot be built.")
else:
announce("Build of man and HTML documentation is disabled.")
if manbuilder:
env['BUILDERS']["Man"] = Builder(action=manbuilder)
env['BUILDERS']["HTML"] = Builder(action=htmlbuilder,
src_suffix=".xml", suffix=".html")
# Determine if Qt network libraries are present, and
# if not, force qt to off
if env["qt"]:
qt_net_name = 'Qt%sNetwork' % env["qt_versioned"]
qt_network = config.CheckPKG(qt_net_name)
if not qt_network:
env["qt"] = False
announce('Turning off Qt support, library not found.')
# If supported by the compiler, enable all warnings except uninitialized
# and missing-field-initializers, which we can't help triggering because
# of the way some of the JSON-parsing code is generated.
# Also not including -Wcast-qual and -Wimplicit-function-declaration,
# because we can't seem to keep scons from passing these to g++.
#
# Do this after the other config checks, to keep warnings out of them.
for option in ('-Wextra', '-Wall', '-Wno-uninitialized',
'-Wno-missing-field-initializers',
'-Wcast-align', '-Wmissing-declarations',
'-Wmissing-prototypes',
'-Wstrict-prototypes', '-Wpointer-arith', '-Wreturn-type'):
if option not in config.env['CFLAGS']:
config.CheckCompilerOption(option)
# Set up configuration for target Python
PYTHON_LIBDIR_CALL = 'sysconfig.get_python_lib()'
PYTHON_CONFIG_NAMES = ['CC', 'CXX', 'OPT', 'BASECFLAGS',
'CCSHARED', 'LDSHARED', 'SO', 'INCLUDEPY', 'LDFLAGS']
PYTHON_CONFIG_QUOTED = ["'%s'" % s for s in PYTHON_CONFIG_NAMES]
PYTHON_CONFIG_CALL = ('sysconfig.get_config_vars(%s)'
% ', '.join(PYTHON_CONFIG_QUOTED))
if helping:
# If helping just get usable config info from the local Python
target_python_path = ''
py_config_text = str(eval(PYTHON_CONFIG_CALL))
python_libdir = str(eval(PYTHON_LIBDIR_CALL))
else:
if env['python'] and env['target_python']:
try:
config.CheckProg
except AttributeError: # Older scons versions don't have CheckProg
target_python_path = env['target_python']
else:
target_python_path = config.CheckProg(env['target_python'])
if not target_python_path:
announce("Target Python doesn't exist - disabling Python.")
env['python'] = False
if env['python']:
# Maximize consistency by using the reported sys.executable
target_python_path = config.GetPythonValue('exe path',
'import sys',
'sys.executable',
brief=cleaning)
if env['python_libdir']:
python_libdir = env['python_libdir']
else:
python_libdir = config.GetPythonValue('lib dir',
PYTHON_SYSCONFIG_IMPORT,
PYTHON_LIBDIR_CALL,
brief=cleaning)
py_config_text = config.GetPythonValue('config vars',
PYTHON_SYSCONFIG_IMPORT,