SConstruct 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862
  1. # SCons build recipe for the GPSD project
  2. # Important targets:
  3. #
  4. # build - build the software (default)
  5. # dist - make distribution tarball (requires GNU tar)
  6. # install - install programs, libraries, and manual pages
  7. # uninstall - undo an install
  8. #
  9. # check - run regression and unit tests.
  10. # audit - run code-auditing tools
  11. # testbuild - test-build the code from a tarball
  12. # website - refresh the website
  13. # release - ship a release
  14. #
  15. # --clean - clean all normal build targets
  16. # sconsclean - clean up scons dotfiles (but not the database: .sconsign.*.dblite)
  17. #
  18. # Setting the DESTDIR environment variable will prefix the install destinations
  19. # without changing the --prefix prefix.
  20. # Unfinished items:
  21. # * Out-of-directory builds: see http://www.scons.org/wiki/UsingBuildDir
  22. # * Coveraging mode: gcc "-coverage" flag requires a hack
  23. # for building the python bindings
  24. # * Python 3 compatibility in this recipe
  25. # Since SCons 3.0.0 forces print_function on us, it needs to be unconditional.
  26. # This is recognized to be a bug in SCons, but we need to live with it for now,
  27. # and we'll need this for eventual Python 3 compatibility, anyway.
  28. # Python requires this to precede any non-comment code.
  29. from __future__ import print_function
  30. import ast
  31. import functools
  32. import glob
  33. import imp # for imp.find_module('gps'), imp deprecated in 3.4
  34. # for conditional_leapsecond_fetch(), make_leapsecond_include()
  35. import leapsecond
  36. import operator
  37. import os
  38. import pickle
  39. import re
  40. # replacement for functions from the commands module, which is deprecated.
  41. import subprocess
  42. import sys
  43. import time
  44. from distutils import sysconfig
  45. import SCons
  46. # Release identification begins here.
  47. #
  48. # Actual releases follow the normal X.Y or X.Y.Z scheme. The version
  49. # number in git between releases has the form X.Y~dev, when it is
  50. # expected that X.Y will be the next actual release. As an example,
  51. # when 3.18.1 is the last release, and 3.19 is the expected next
  52. # release, the version in git will be 3.19~dev. Note that ~ is used,
  53. # because there is some precedent, ~ is an allowed version number in
  54. # the Debian version rules, and it does not cause confusion with
  55. # whether - separates components of the package name, separates the
  56. # name from the version, or separates version componnents.
  57. #
  58. # Keep in sync with gps/__init__.py
  59. # There are about 16 files with copies of the version number; make
  60. # sure to update all of them.
  61. #
  62. # package version
  63. gpsd_version = "3.19.1~dev"
  64. # client library version
  65. libgps_version_current = 25
  66. libgps_version_revision = 0
  67. libgps_version_age = 0
  68. libgps_version = "%d.%d.%d" % (libgps_version_current, libgps_version_age,
  69. libgps_version_revision)
  70. #
  71. # Release identification ends here
  72. # Hosting information (mainly used for templating web pages) begins here
  73. # Each variable foo has a corresponding @FOO@ expanded in .in files.
  74. # There are no project-dependent URLs or references to the hosting site
  75. # anywhere else in the distribution; preserve this property!
  76. annmail = "gpsd-announce@nongnu.org"
  77. bugtracker = "https://gitlab.com/gpsd/gpsd/issues"
  78. cgiupload = "root@thyrsus.com:/var/www/cgi-bin/"
  79. clonerepo = "git@gitlab.com:gpsd/gpsd.git"
  80. devmail = "gpsd-dev@lists.nongnu.org"
  81. download = "http://download-mirror.savannah.gnu.org/releases/gpsd/"
  82. formserver = "www@thyrsus.com"
  83. gitrepo = "git@gitlab.com:gpsd/gpsd.git"
  84. ircchan = "irc://chat.freenode.net/#gpsd"
  85. mailman = "https://lists.nongnu.org/mailman/listinfo/"
  86. mainpage = "https://gpsd.io"
  87. projectpage = "https://gitlab.com/gpsd/gpsd"
  88. scpupload = "garyemiller@dl.sv.nongnu.org:/releases/gpsd/"
  89. sitename = "GPSD"
  90. sitesearch = "gpsd.io"
  91. tiplink = "<a href='https://www.patreon.com/esr'>" \
  92. "leave a remittance at Patreon</a>"
  93. tipwidget = '<p><a href="https://www.patreon.com/esr">' \
  94. 'Donate here to support continuing development.</a></p>'
  95. usermail = "gpsd-users@lists.nongnu.org"
  96. webform = "http://www.thyrsus.com/cgi-bin/gps_report.cgi"
  97. website = "https://gpsd.io/"
  98. # Hosting information ends here
  99. # gpsd needs Scons version at least 2.3
  100. EnsureSConsVersion(2, 3, 0)
  101. # gpsd needs Python version at least 2.6
  102. EnsurePythonVersion(2, 6)
  103. PYTHON_SYSCONFIG_IMPORT = 'from distutils import sysconfig'
  104. # Utility productions
  105. def Utility(target, source, action, **kwargs):
  106. target = env.Command(target=target, source=source, action=action, **kwargs)
  107. env.AlwaysBuild(target)
  108. env.Precious(target)
  109. return target
  110. def UtilityWithHerald(herald, target, source, action, **kwargs):
  111. if not env.GetOption('silent'):
  112. action = ['@echo "%s"' % herald] + action
  113. return Utility(target=target, source=source, action=action, **kwargs)
  114. def _getstatusoutput(cmd, nput=None, shell=True, cwd=None, env=None):
  115. pipe = subprocess.Popen(cmd, shell=shell, cwd=cwd, env=env,
  116. stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  117. (output, errout) = pipe.communicate(input=nput)
  118. status = pipe.returncode
  119. return (status, output)
  120. def _getoutput(cmd, nput=None, shell=True, cwd=None, env=None):
  121. return _getstatusoutput(cmd, nput, shell, cwd, env)[1]
  122. # Spawn replacement that suppresses non-error stderr
  123. def filtered_spawn(sh, escape, cmd, args, env):
  124. proc = subprocess.Popen([sh, '-c', ' '.join(args)],
  125. env=env, close_fds=True, stderr=subprocess.PIPE)
  126. _, stderr = proc.communicate()
  127. if proc.returncode:
  128. sys.stderr.write(stderr)
  129. return proc.returncode
  130. #
  131. # Build-control options
  132. #
  133. # without this, scons will not rebuild an existing target when the
  134. # source changes.
  135. Decider('timestamp-match')
  136. # support building with various Python versions.
  137. sconsign_file = '.sconsign.{}.dblite'.format(pickle.HIGHEST_PROTOCOL)
  138. SConsignFile(sconsign_file)
  139. # Start by reading configuration variables from the cache
  140. opts = Variables('.scons-option-cache')
  141. systemd_dir = '/lib/systemd/system'
  142. systemd = os.path.exists(systemd_dir)
  143. # Set distribution-specific defaults here
  144. imloads = True
  145. boolopts = (
  146. # GPS protocols
  147. ("ashtech", True, "Ashtech support"),
  148. ("earthmate", True, "DeLorme EarthMate Zodiac support"),
  149. ("evermore", True, "EverMore binary support"),
  150. ("fury", True, "Jackson Labs Fury and Firefly support"),
  151. ("fv18", True, "San Jose Navigation FV-18 support"),
  152. ("garmin", True, "Garmin kernel driver support"),
  153. ("garmintxt", True, "Garmin Simple Text support"),
  154. ("geostar", True, "Geostar Protocol support"),
  155. ("greis", True, "Javad GREIS support"),
  156. ("itrax", True, "iTrax hardware support"),
  157. ("mtk3301", True, "MTK-3301 support"),
  158. ("navcom", True, "Navcom NCT support"),
  159. ("nmea0183", True, "NMEA0183 support"),
  160. ("nmea2000", True, "NMEA2000/CAN support"),
  161. ("oncore", True, "Motorola OnCore chipset support"),
  162. ("sirf", True, "SiRF chipset support"),
  163. ("skytraq", True, "Skytraq chipset support"),
  164. ("superstar2", True, "Novatel SuperStarII chipset support"),
  165. ("tnt", True, "True North Technologies support"),
  166. ("tripmate", True, "DeLorme TripMate support"),
  167. ("tsip", True, "Trimble TSIP support"),
  168. ("ublox", True, "u-blox Protocol support"),
  169. # Non-GPS protocols
  170. ("aivdm", True, "AIVDM support"),
  171. ("gpsclock", True, "GPSClock support"),
  172. ("isync", True, "Spectratime iSync LNRClok/GRCLOK support"),
  173. ("ntrip", True, "NTRIP support"),
  174. ("oceanserver", True, "OceanServer support"),
  175. ("passthrough", True, "build support for passing through JSON"),
  176. ("rtcm104v2", True, "rtcm104v2 support"),
  177. ("rtcm104v3", True, "rtcm104v3 support"),
  178. # Time service
  179. ("oscillator", True, "Disciplined oscillator support"),
  180. # Export methods
  181. ("dbus_export", True, "enable DBUS export support"),
  182. ("shm_export", True, "export via shared memory"),
  183. ("socket_export", True, "data export over sockets"),
  184. # Communication
  185. ("bluez", True, "BlueZ support for Bluetooth devices"),
  186. ("netfeed", True, "build support for handling TCP/IP data sources"),
  187. ('usb', True, "libusb support for USB devices"),
  188. # Other daemon options
  189. ("control_socket", True, "control socket for hotplug notifications"),
  190. ("force_global", False, "force daemon to listen on all addressses"),
  191. ("systemd", systemd, "systemd socket activation"),
  192. # Client-side options
  193. ("clientdebug", True, "client debugging support"),
  194. ("libgpsmm", True, "build C++ bindings"),
  195. ("ncurses", True, "build with ncurses"),
  196. ("qt", True, "build Qt bindings"),
  197. # Daemon options
  198. ("controlsend", True, "allow gpsctl/gpsmon to change device settings"),
  199. ("reconfigure", True, "allow gpsd to change device settings"),
  200. ("squelch", False, "squelch gpsd_log/gpsd_hexdump to save cpu"),
  201. # Build control
  202. ("coveraging", False, "build with code coveraging enabled"),
  203. ("debug", False, "include debug information in build"),
  204. ("gpsdclients", True, "gspd client programs"),
  205. ("gpsd", True, "gpsd itself"),
  206. ("implicit_link", imloads, "implicit linkage is supported in shared libs"),
  207. ("leapfetch", True, "fetch up-to-date data on leap seconds."),
  208. ("magic_hat", sys.platform.startswith('linux'),
  209. "special Linux PPS hack for Raspberry Pi et al"),
  210. ("manbuild", True, "build help in man and HTML formats"),
  211. ("minimal", False, "turn off every option not set on the command line"),
  212. ("nostrip", False, "don't symbol-strip binaries at link time"),
  213. ("profiling", False, "build with profiling enabled"),
  214. ("python", True, "build Python support and modules."),
  215. ("shared", True, "build shared libraries, not static"),
  216. ("timeservice", False, "time-service configuration"),
  217. ("xgps", True, "include xgps and xgpsspeed."),
  218. # Test control
  219. ("slow", False, "run tests with realistic (slow) delays"),
  220. )
  221. # now step on the boolopts just read from '.scons-option-cache'
  222. for (name, default, helpd) in boolopts:
  223. opts.Add(BoolVariable(name, helpd, default))
  224. # Gentoo, Fedora, opensuse systems use uucp for ttyS* and ttyUSB*
  225. if os.path.exists("/etc/gentoo-release"):
  226. def_group = "uucp"
  227. else:
  228. def_group = "dialout"
  229. nonboolopts = (
  230. ("gpsd_group", def_group, "privilege revocation group"),
  231. ("gpsd_user", "nobody", "privilege revocation user",),
  232. ("max_clients", '64', "maximum allowed clients"),
  233. ("max_devices", '4', "maximum allowed devices"),
  234. ("prefix", "/usr/local", "installation directory prefix"),
  235. ("python_coverage", "coverage run", "coverage command for Python progs"),
  236. ("python_libdir", "", "Python module directory prefix"),
  237. ("qt_versioned", "", "version for versioned Qt"),
  238. ("sysroot", "", "cross-development system root"),
  239. ("target", "", "cross-development target"),
  240. ("target_python", "python", "target Python version as command"),
  241. )
  242. # now step on the non boolopts just read from '.scons-option-cache'
  243. for (name, default, helpd) in nonboolopts:
  244. opts.Add(name, helpd, default)
  245. pathopts = (
  246. ("bindir", "bin", "application binaries directory"),
  247. ("docdir", "share/doc", "documents directory"),
  248. ("includedir", "include", "header file directory"),
  249. ("libdir", "lib", "system libraries"),
  250. ("mandir", "share/man", "manual pages directory"),
  251. ("pkgconfig", "$libdir/pkgconfig", "pkgconfig file directory"),
  252. ("sbindir", "sbin", "system binaries directory"),
  253. ("sysconfdir", "etc", "system configuration directory"),
  254. ("udevdir", "/lib/udev", "udev rules directory"),
  255. )
  256. # now step on the path options just read from '.scons-option-cache'
  257. for (name, default, helpd) in pathopts:
  258. opts.Add(PathVariable(name, helpd, default, PathVariable.PathAccept))
  259. #
  260. # Environment creation
  261. #
  262. import_env = (
  263. # Variables used by programs invoked during the build
  264. "DISPLAY", # Required for dia to run under scons
  265. "GROUPS", # Required by gpg
  266. "HOME", # Required by gpg
  267. "LOGNAME", # LOGNAME is required for the flocktest production.
  268. 'PATH', # Required for ccache and Coverity scan-build
  269. 'CCACHE_DIR', # Required for ccache
  270. 'CCACHE_RECACHE', # Required for ccache (probably there are more)
  271. # pkg-config (required for crossbuilds at least, and probably pkgsrc)
  272. 'PKG_CONFIG_LIBDIR',
  273. 'PKG_CONFIG_PATH',
  274. 'PKG_CONFIG_SYSROOT_DIR',
  275. # Variables for specific packaging/build systems
  276. "MACOSX_DEPLOYMENT_TARGET", # MacOSX 10.4 (and probably earlier)
  277. 'STAGING_DIR', # OpenWRT and CeroWrt
  278. 'STAGING_PREFIX', # OpenWRT and CeroWrt
  279. 'CWRAPPERS_CONFIG_DIR', # pkgsrc
  280. # Variables used in testing
  281. 'WRITE_PAD', # So we can test WRITE_PAD values on the fly.
  282. )
  283. envs = {}
  284. for var in import_env:
  285. if var in os.environ:
  286. envs[var] = os.environ[var]
  287. envs["GPSD_HOME"] = os.getcwd()
  288. env = Environment(tools=["default", "tar", "textfile"], options=opts, ENV=envs)
  289. # Minimal build turns off every option not set on the command line,
  290. if ARGUMENTS.get('minimal'):
  291. for (name, default, helpd) in boolopts:
  292. # Ensure gpsd and gpsdclients are always enabled unless explicitly
  293. # turned off.
  294. if ((default is True and
  295. not ARGUMENTS.get(name) and
  296. name not in ("gpsd", "gpsdclients"))):
  297. env[name] = False
  298. # Time-service build = stripped-down with some diagnostic tools
  299. if ARGUMENTS.get('timeservice'):
  300. timerelated = ("gpsd",
  301. "ipv6",
  302. "magic_hat",
  303. "mtk3301", # For the Adafruit HAT
  304. "ncurses",
  305. "nmea0183", # For generic hats of unknown type.
  306. "oscillator",
  307. "socket_export",
  308. "ublox", # For the Uputronics board
  309. )
  310. for (name, default, helpd) in boolopts:
  311. if ((default is True and
  312. not ARGUMENTS.get(name) and
  313. name not in timerelated)):
  314. env[name] = False
  315. # Many drivers require NMEA0183 - in case we select timeserver/minimal
  316. # followed by one of these.
  317. for driver in ('ashtech',
  318. 'earthmate',
  319. 'fury',
  320. 'fv18',
  321. 'gpsclock',
  322. 'mtk3301',
  323. 'oceanserver',
  324. 'skytraq',
  325. 'tnt',
  326. 'tripmate', ):
  327. if env[driver]:
  328. env['nmea0183'] = True
  329. break
  330. # iSync uses ublox underneath, so we force to enable it
  331. if env['isync']:
  332. env['ublox'] = True
  333. opts.Save('.scons-option-cache', env)
  334. for (name, default, helpd) in pathopts:
  335. env[name] = env.subst(env[name])
  336. env['VERSION'] = gpsd_version
  337. env['SC_PYTHON'] = sys.executable # Path to SCons Python
  338. # Set defaults from environment. Note that scons doesn't cope well
  339. # with multi-word CPPFLAGS/LDFLAGS/SHLINKFLAGS values; you'll have to
  340. # explicitly quote them or (better yet) use the "=" form of GNU option
  341. # settings.
  342. # Scons also uses different internal names than most other build-systems.
  343. # So we rely on MergeFlags/ParseFlags to do the right thing for us.
  344. env['STRIP'] = "strip"
  345. env['PKG_CONFIG'] = "pkg-config"
  346. for i in ["AR", "CC", "CXX", "LD",
  347. "PKG_CONFIG", "STRIP", "TAR"]:
  348. if i in os.environ:
  349. j = i
  350. if i == "LD":
  351. i = "SHLINK"
  352. env[i] = os.getenv(j)
  353. for i in ["ARFLAGS", "CFLAGS", "CXXFLAGS", "LDFLAGS", "SHLINKFLAGS",
  354. "CPPFLAGS", "CCFLAGS", "LINKFLAGS"]:
  355. if i in os.environ:
  356. env.MergeFlags(Split(os.getenv(i)))
  357. # Keep scan-build options in the environment
  358. for key, value in os.environ.items():
  359. if key.startswith('CCC_'):
  360. env.Append(ENV={key: value})
  361. # Placeholder so we can kluge together something like VPATH builds.
  362. # $SRCDIR replaces occurrences for $(srcdir) in the autotools build.
  363. # scons can get confused if this is not a full path
  364. env['SRCDIR'] = os.getcwd()
  365. # We may need to force slow regression tests to get around race
  366. # conditions in the pty layer, especially on a loaded machine.
  367. if env["slow"]:
  368. env['REGRESSOPTS'] = "-S"
  369. else:
  370. env['REGRESSOPTS'] = ""
  371. if env.GetOption("silent"):
  372. env['REGRESSOPTS'] += " -Q"
  373. def announce(msg):
  374. if not env.GetOption("silent"):
  375. print(msg)
  376. # DESTDIR environment variable means user prefix the installation root.
  377. DESTDIR = os.environ.get('DESTDIR', '')
  378. def installdir(idir, add_destdir=True):
  379. # use os.path.join to handle absolute paths properly.
  380. wrapped = os.path.join(env['prefix'], env[idir])
  381. if add_destdir:
  382. wrapped = os.path.normpath(DESTDIR + os.path.sep + wrapped)
  383. wrapped.replace("/usr/etc", "/etc")
  384. wrapped.replace("/usr/lib/systemd", "/lib/systemd")
  385. return wrapped
  386. # Honor the specified installation prefix in link paths.
  387. if env["sysroot"]:
  388. env.Prepend(LIBPATH=[env["sysroot"] + installdir('libdir',
  389. add_destdir=False)])
  390. # Give deheader a way to set compiler flags
  391. if 'MORECFLAGS' in os.environ:
  392. env.Append(CFLAGS=Split(os.environ['MORECFLAGS']))
  393. # Don't change CCFLAGS if already set by environment.
  394. if 'CCFLAGS' in os.environ:
  395. announce('Warning: CCFLAGS from environment overriding scons settings')
  396. else:
  397. # Should we build with profiling?
  398. if env['profiling']:
  399. env.Append(CCFLAGS=['-pg'])
  400. env.Append(LDFLAGS=['-pg'])
  401. # Should we build with coveraging?
  402. if env['coveraging']:
  403. env.Append(CFLAGS=['-coverage'])
  404. env.Append(LDFLAGS=['-coverage'])
  405. env.Append(LINKFLAGS=['-coverage'])
  406. # Should we build with debug symbols?
  407. if env['debug']:
  408. env.Append(CCFLAGS=['-g3'])
  409. # Should we build with optimisation?
  410. if env['debug'] or env['coveraging']:
  411. env.Append(CCFLAGS=['-O0'])
  412. else:
  413. env.Append(CCFLAGS=['-O2'])
  414. # Cross-development
  415. devenv = (("ADDR2LINE", "addr2line"),
  416. ("AR", "ar"),
  417. ("AS", "as"),
  418. ("CXX", "c++"),
  419. ("CXXFILT", "c++filt"),
  420. ("CPP", "cpp"),
  421. ("GXX", "g++"),
  422. ("CC", "gcc"),
  423. ("GCCBUG", "gccbug"),
  424. ("GCOV", "gcov"),
  425. ("GPROF", "gprof"),
  426. ("LD", "ld"),
  427. ("NM", "nm"),
  428. ("OBJCOPY", "objcopy"),
  429. ("OBJDUMP", "objdump"),
  430. ("RANLIB", "ranlib"),
  431. ("READELF", "readelf"),
  432. ("SIZE", "size"),
  433. ("STRINGS", "strings"),
  434. ("STRIP", "strip"))
  435. if env['target']:
  436. for (name, toolname) in devenv:
  437. env[name] = env['target'] + '-' + toolname
  438. if env['sysroot']:
  439. env.MergeFlags({"CFLAGS": ["--sysroot=%s" % env['sysroot']]})
  440. env.MergeFlags({"LINKFLAGS": ["--sysroot=%s" % env['sysroot']]})
  441. # Build help
  442. def cmp(a, b):
  443. return (a > b) - (a < b)
  444. Help("""Arguments may be a mixture of switches and targets in any order.
  445. Switches apply to the entire build regardless of where they are in the order.
  446. Important switches include:
  447. prefix=/usr probably what packagers want
  448. Options are cached in a file named .scons-option-cache and persist to later
  449. invocations. The file is editable. Delete it to start fresh. Current option
  450. values can be listed with 'scons -h'.
  451. """ + opts.GenerateHelpText(env, sort=cmp))
  452. # Configuration
  453. def CheckPKG(context, name):
  454. context.Message('Checking pkg-config for %s... ' % name)
  455. ret = context.TryAction('%s --exists \'%s\''
  456. % (env['PKG_CONFIG'], name))[0]
  457. context.Result(ret)
  458. return ret
  459. # Stylesheet URLs for making HTML and man pages from DocBook XML.
  460. docbook_url_stem = 'http://docbook.sourceforge.net/release/xsl/current/'
  461. docbook_man_uri = docbook_url_stem + 'manpages/docbook.xsl'
  462. docbook_html_uri = docbook_url_stem + 'html/docbook.xsl'
  463. def CheckXsltproc(context):
  464. context.Message('Checking that xsltproc can make man pages... ')
  465. ofp = open("man/xmltest.xml", "w")
  466. ofp.write('''
  467. <refentry id="foo.1">
  468. <refmeta>
  469. <refentrytitle>foo</refentrytitle>
  470. <manvolnum>1</manvolnum>
  471. <refmiscinfo class='date'>9 Aug 2004</refmiscinfo>
  472. </refmeta>
  473. <refnamediv id='name'>
  474. <refname>foo</refname>
  475. <refpurpose>check man page generation from docbook source</refpurpose>
  476. </refnamediv>
  477. </refentry>
  478. ''')
  479. ofp.close()
  480. probe = ("xsltproc --encoding UTF-8 --output man/foo.1 --nonet "
  481. "--noout '%s' man/xmltest.xml" % (docbook_man_uri,))
  482. ret = context.TryAction(probe)[0]
  483. os.remove("man/xmltest.xml")
  484. if os.path.exists("man/foo.1"):
  485. os.remove("man/foo.1")
  486. else:
  487. # failed to create output
  488. ret = False
  489. context.Result(ret)
  490. return ret
  491. def CheckCompilerOption(context, option):
  492. context.Message('Checking if compiler accepts %s... ' % (option,))
  493. old_CFLAGS = context.env['CFLAGS'][:] # Get a *copy* of the old list
  494. context.env.Append(CFLAGS=option)
  495. ret = context.TryLink("""
  496. int main(int argc, char **argv) {
  497. (void) argc; (void) argv;
  498. return 0;
  499. }
  500. """, '.c')
  501. if not ret:
  502. context.env.Replace(CFLAGS=old_CFLAGS)
  503. context.Result(ret)
  504. return ret
  505. def CheckHeaderDefines(context, file, define):
  506. context.Message('Checking if %s supplies %s... ' % (file, define))
  507. ret = context.TryLink("""
  508. #include <%s>
  509. #ifndef %s
  510. #error %s is not defined
  511. #endif
  512. int main(int argc, char **argv) {
  513. (void) argc; (void) argv;
  514. return 0;
  515. }
  516. """ % (file, define, define), '.c')
  517. context.Result(ret)
  518. return ret
  519. def CheckCompilerDefines(context, define):
  520. context.Message('Checking if compiler supplies %s... ' % (define,))
  521. ret = context.TryLink("""
  522. #ifndef %s
  523. #error %s is not defined
  524. #endif
  525. int main(int argc, char **argv) {
  526. (void) argc; (void) argv;
  527. return 0;
  528. }
  529. """ % (define, define), '.c')
  530. context.Result(ret)
  531. return ret
  532. # Check if this compiler is C11 or better
  533. def CheckC11(context):
  534. context.Message('Checking if compiler is C11... ')
  535. ret = context.TryLink("""
  536. #if (__STDC_VERSION__ < 201112L)
  537. #error Not C11
  538. #endif
  539. int main(int argc, char **argv) {
  540. (void) argc; (void) argv;
  541. return 0;
  542. }
  543. """, '.c')
  544. context.Result(ret)
  545. return ret
  546. def GetPythonValue(context, name, imp, expr, brief=False):
  547. context.Message('Obtaining Python %s... ' % name)
  548. context.sconf.cached = 0 # Avoid bogus "(cached)"
  549. if not env['target_python']:
  550. status, value = 0, str(eval(expr))
  551. else:
  552. command = [target_python_path, '-c', '%s; print(%s)' % (imp, expr)]
  553. try:
  554. status, value = _getstatusoutput(command, shell=False)
  555. except OSError:
  556. status = -1
  557. if status == 0:
  558. value = value.strip()
  559. else:
  560. value = ''
  561. announce('Python command "%s" failed - disabling Python.\n'
  562. 'Python components will NOT be installed' %
  563. command[2])
  564. env['python'] = False
  565. context.Result('failed' if status else 'ok' if brief else value)
  566. return value
  567. def GetLoadPath(context):
  568. context.Message("Getting system load path... ")
  569. cleaning = env.GetOption('clean')
  570. helping = env.GetOption('help')
  571. # Always set up LIBPATH so that cleaning works properly.
  572. env.Prepend(LIBPATH=[os.path.realpath(os.curdir)])
  573. # from scons 3.0.5, any changes to env after this, until after
  574. # config.Finish(), will be lost. Use config.env until then.
  575. # CheckXsltproc works, but result is incorrectly saved as "no"
  576. config = Configure(env, custom_tests={
  577. 'CheckPKG': CheckPKG,
  578. 'CheckXsltproc': CheckXsltproc,
  579. 'CheckCompilerOption': CheckCompilerOption,
  580. 'CheckCompilerDefines': CheckCompilerDefines,
  581. 'CheckC11': CheckC11,
  582. 'CheckHeaderDefines': CheckHeaderDefines,
  583. 'GetPythonValue': GetPythonValue})
  584. # Use print, rather than announce, so we see it in -s mode.
  585. print("This system is: %s" % sys.platform)
  586. libgps_flags = []
  587. if cleaning or helping:
  588. bluezflags = []
  589. confdefs = []
  590. dbusflags = []
  591. htmlbuilder = False
  592. manbuilder = False
  593. ncurseslibs = []
  594. rtlibs = []
  595. mathlibs = []
  596. tiocmiwait = True # For cleaning, which works on any OS
  597. usbflags = []
  598. else:
  599. # OS X aliases gcc to clang
  600. # clang accepts -pthread, then warns it is unused.
  601. if not config.CheckCC():
  602. announce("ERROR: CC doesn't work")
  603. if ((config.CheckCompilerOption("-pthread") and
  604. not sys.platform.startswith('darwin'))):
  605. config.env.MergeFlags("-pthread")
  606. confdefs = ["/* gpsd_config.h generated by scons, do not hand-hack. */\n"]
  607. confdefs.append('#ifndef GPSD_CONFIG_H\n')
  608. confdefs.append('#define VERSION "%s"\n' % gpsd_version)
  609. confdefs.append('#define GPSD_URL "%s"\n' % website)
  610. # TODO: Move these into an if block only on systems with glibc.
  611. # needed for isfinite(), pselect(), etc.
  612. # for strnlen() before glibc 2.10
  613. # glibc 2.10+ needs 200908L (or XOPEN 700+) for strnlen()
  614. # on newer glibc _DEFAULT_SOURCE resets _POSIX_C_SOURCE
  615. # we set it just in case
  616. confdefs.append('#if !defined(_POSIX_C_SOURCE)')
  617. confdefs.append('#define _POSIX_C_SOURCE 200809L')
  618. confdefs.append('#endif\n')
  619. # for daemon(), cfmakeraw(), strsep() and setgroups()
  620. # on glibc 2.19+
  621. # may also be added by pkg_config
  622. # on linux this eventually sets _USE_XOPEN
  623. confdefs.append('#if !defined(_DEFAULT_SOURCE)')
  624. confdefs.append('#define _DEFAULT_SOURCE')
  625. confdefs.append('#endif\n')
  626. # sys/un.h, and more, needs __USE_MISC with glibc and osX
  627. # __USE_MISC is set by _DEFAULT_SOURCE or _BSD_SOURCE
  628. # TODO: Many of these are now specified by POSIX. Check if
  629. # defining _XOPEN_SOURCE is necessary, and limit to systems where
  630. # it is.
  631. # 500 means X/Open 1995
  632. # getsid(), isascii(), nice(), putenv(), strdup(), sys/ipc.h need 500
  633. # 600 means X/Open 2004
  634. # Ubuntu and OpenBSD isfinite() needs 600
  635. # 700 means X/Open 2008
  636. # glibc 2.10+ needs 700+ for strnlen()
  637. # Python.h wants 600 or 700
  638. # removed 2 Jul 2019 to see if anything breaks...
  639. # confdefs.append('#if !defined(_XOPEN_SOURCE)')
  640. # confdefs.append('#define _XOPEN_SOURCE 700')
  641. # confdefs.append('#endif\n')
  642. # Reinstated for FreeBSD (below) 16-Aug-2019
  643. if sys.platform.startswith('linux'):
  644. # for cfmakeraw(), strsep(), etc. on CentOS 7
  645. # glibc 2.19 and before
  646. # sets __USE_MISC
  647. confdefs.append('#if !defined(_BSD_SOURCE)')
  648. confdefs.append('#define _BSD_SOURCE')
  649. confdefs.append('#endif\n')
  650. # for strnlen() and struct ifreq
  651. # glibc before 2.10, deprecated in 2.10+
  652. confdefs.append('#if !defined(_GNU_SOURCE)')
  653. confdefs.append('#define _GNU_SOURCE 1')
  654. confdefs.append('#endif\n')
  655. elif sys.platform.startswith('darwin'):
  656. # strlcpy() and SIGWINCH need _DARWIN_C_SOURCE
  657. confdefs.append('#if !defined(_DARWIN_C_SOURCE)')
  658. confdefs.append('#define _DARWIN_C_SOURCE 1\n')
  659. confdefs.append('#endif\n')
  660. # vsnprintf() needs __DARWIN_C_LEVEL >= 200112L
  661. # snprintf() needs __DARWIN_C_LEVEL >= 200112L
  662. # _DARWIN_C_SOURCE forces __DARWIN_C_LEVEL to 900000L
  663. # see <sys/cdefs.h>
  664. # set internal lib versions at link time.
  665. libgps_flags = ["-Wl,-current_version,%s" % libgps_version,
  666. "-Wl,-compatibility_version,%s" % libgps_version,
  667. "-Wl,-install_name,%s/$TARGET" %
  668. installdir('libdir', add_destdir=False)]
  669. elif sys.platform.startswith('freebsd'):
  670. # for isascii(), putenv(), nice(), strptime()
  671. confdefs.append('#if !defined(_XOPEN_SOURCE)')
  672. confdefs.append('#define _XOPEN_SOURCE 700')
  673. confdefs.append('#endif\n')
  674. # required to define u_int in sys/time.h
  675. confdefs.append('#if !defined(_BSD_SOURCE)')
  676. confdefs.append("#define _BSD_SOURCE 1\n")
  677. confdefs.append('#endif\n')
  678. # required to get strlcpy(), and more, from string.h
  679. confdefs.append('#if !defined(__BSD_VISIBLE)')
  680. confdefs.append("#define __BSD_VISIBLE 1\n")
  681. confdefs.append('#endif\n')
  682. elif sys.platform.startswith('openbsd'):
  683. # required to define u_int in sys/time.h
  684. confdefs.append('#if !defined(_BSD_SOURCE)')
  685. confdefs.append("#define _BSD_SOURCE 1\n")
  686. confdefs.append('#endif\n')
  687. # required to get strlcpy(), and more, from string.h
  688. confdefs.append('#if !defined(__BSD_VISIBLE)')
  689. confdefs.append("#define __BSD_VISIBLE 1\n")
  690. confdefs.append('#endif\n')
  691. elif sys.platform.startswith('netbsd'):
  692. # required to get strlcpy(), and more, from string.h
  693. confdefs.append('#if !defined(_NETBSD_SOURCE)')
  694. confdefs.append("#define _NETBSD_SOURCE 1\n")
  695. confdefs.append('#endif\n')
  696. cxx = config.CheckCXX()
  697. if not cxx and config.env["libgpsmm"]:
  698. announce("C++ doesn't work, suppressing libgpsmm build.")
  699. config.env["libgpsmm"] = False
  700. # define a helper function for pkg-config - we need to pass
  701. # --static for static linking, too.
  702. #
  703. # Using "--libs-only-L --libs-only-l" instead of "--libs" avoids
  704. # a superfluous "-rpath" option in some FreeBSD cases, and the resulting
  705. # scons crash.
  706. # However, it produces incorrect results for Qt5Network in OSX, so
  707. # it can't be used unconditionally.
  708. def pkg_config(pkg, shared=env['shared'], rpath_hack=False):
  709. libs = '--libs-only-L --libs-only-l' if rpath_hack else '--libs'
  710. if not shared:
  711. libs += ' --static'
  712. return ['!%s --cflags %s %s' % (env['PKG_CONFIG'], libs, pkg)]
  713. # The actual distinction here is whether the platform has ncurses in the
  714. # base system or not. If it does, pkg-config is not likely to tell us
  715. # anything useful. FreeBSD does, Linux doesn't. Most likely other BSDs
  716. # are like FreeBSD.
  717. ncurseslibs = []
  718. if config.env['ncurses']:
  719. if not config.CheckHeader(["curses.h"]):
  720. announce('Turning off ncurses support, curses.h not found.')
  721. config.env['ncurses'] = False
  722. elif config.CheckPKG('ncurses'):
  723. ncurseslibs = pkg_config('ncurses', rpath_hack=True)
  724. if config.CheckPKG('tinfo'):
  725. ncurseslibs += pkg_config('tinfo', rpath_hack=True)
  726. # It's not yet known whether rpath_hack is appropriate for
  727. # ncurses5-config.
  728. elif WhereIs('ncurses5-config'):
  729. ncurseslibs = ['!ncurses5-config --libs --cflags']
  730. elif WhereIs('ncursesw5-config'):
  731. ncurseslibs = ['!ncursesw5-config --libs --cflags']
  732. elif sys.platform.startswith('freebsd'):
  733. ncurseslibs = ['-lncurses']
  734. elif sys.platform.startswith('openbsd'):
  735. ncurseslibs = ['-lcurses']
  736. elif sys.platform.startswith('darwin'):
  737. ncurseslibs = ['-lcurses']
  738. else:
  739. announce('Turning off ncurses support, library not found.')
  740. config.env['ncurses'] = False
  741. if config.env['usb']:
  742. # In FreeBSD except version 7, USB libraries are in the base system
  743. if config.CheckPKG('libusb-1.0'):
  744. confdefs.append("#define HAVE_LIBUSB 1\n")
  745. try:
  746. usbflags = pkg_config('libusb-1.0')
  747. except OSError:
  748. announce("pkg_config is confused about the state "
  749. "of libusb-1.0.")
  750. usbflags = []
  751. elif sys.platform.startswith("freebsd"):
  752. confdefs.append("#define HAVE_LIBUSB 1\n")
  753. usbflags = ["-lusb"]
  754. else:
  755. confdefs.append("/* #undef HAVE_LIBUSB */\n")
  756. usbflags = []
  757. else:
  758. confdefs.append("/* #undef HAVE_LIBUSB */\n")
  759. usbflags = []
  760. config.env["usb"] = False
  761. if config.CheckLib('librt'):
  762. confdefs.append("#define HAVE_LIBRT 1\n")
  763. # System library - no special flags
  764. rtlibs = ["-lrt"]
  765. else:
  766. confdefs.append("/* #undef HAVE_LIBRT */\n")
  767. rtlibs = []
  768. # The main reason we check for libm explicitly is to set up the config
  769. # environment for CheckFunc for sincos(). But it doesn't hurt to omit
  770. # the '-lm' when it isn't appropriate.
  771. if config.CheckLib('libm'):
  772. mathlibs = ['-lm']
  773. else:
  774. mathlibs = []
  775. # FreeBSD uses -lthr for pthreads
  776. if config.CheckLib('libthr'):
  777. confdefs.append("#define HAVE_LIBTHR 1\n")
  778. # System library - no special flags
  779. rtlibs += ["-lthr"]
  780. else:
  781. confdefs.append("/* #undef HAVE_LIBTHR */\n")
  782. if config.env['dbus_export'] and config.CheckPKG('dbus-1'):
  783. confdefs.append("#define HAVE_DBUS 1\n")
  784. dbusflags = pkg_config("dbus-1")
  785. config.env.MergeFlags(dbusflags)
  786. else:
  787. confdefs.append("/* #undef HAVE_DBUS */\n")
  788. dbusflags = []
  789. if config.env["dbus_export"]:
  790. announce("Turning off dbus-export support, library not found.")
  791. config.env["dbus_export"] = False
  792. if config.env['bluez'] and config.CheckPKG('bluez'):
  793. confdefs.append("#define ENABLE_BLUEZ 1\n")
  794. bluezflags = pkg_config('bluez')
  795. else:
  796. confdefs.append("/* #undef ENABLE_BLUEZ */\n")
  797. bluezflags = []
  798. if config.env["bluez"]:
  799. announce("Turning off Bluetooth support, library not found.")
  800. config.env["bluez"] = False
  801. # in_port_t is not defined on Android
  802. if not config.CheckType("in_port_t", "#include <netinet/in.h>"):
  803. announce("Did not find in_port_t typedef, assuming unsigned short int")
  804. confdefs.append("typedef unsigned short int in_port_t;\n")
  805. # SUN_LEN is not defined on Android
  806. if ((not config.CheckDeclaration("SUN_LEN", "#include <sys/un.h>") and
  807. not config.CheckDeclaration("SUN_LEN", "#include <linux/un.h>"))):
  808. announce("SUN_LEN is not system-defined, using local definition")
  809. confdefs.append("#ifndef SUN_LEN\n")
  810. confdefs.append("#define SUN_LEN(ptr) "
  811. "((size_t) (((struct sockaddr_un *) 0)->sun_path) "
  812. "+ strlen((ptr)->sun_path))\n")
  813. confdefs.append("#endif /* SUN_LEN */\n")
  814. if config.CheckHeader(["linux/can.h"]):
  815. confdefs.append("#define HAVE_LINUX_CAN_H 1\n")
  816. announce("You have kernel CANbus available.")
  817. else:
  818. confdefs.append("/* #undef HAVE_LINUX_CAN_H */\n")
  819. announce("You do not have kernel CANbus available.")
  820. config.env["nmea2000"] = False
  821. # check for C11 or better, and __STDC__NO_ATOMICS__ is not defined
  822. # before looking for stdatomic.h
  823. if ((config.CheckC11() and
  824. not config.CheckCompilerDefines("__STDC_NO_ATOMICS__") and
  825. config.CheckHeader("stdatomic.h"))):
  826. confdefs.append("#define HAVE_STDATOMIC_H 1\n")
  827. else:
  828. confdefs.append("/* #undef HAVE_STDATOMIC_H */\n")
  829. if config.CheckHeader("libkern/OSAtomic.h"):
  830. confdefs.append("#define HAVE_OSATOMIC_H 1\n")
  831. else:
  832. confdefs.append("/* #undef HAVE_OSATOMIC_H */\n")
  833. announce("No memory barriers - SHM export and time hinting "
  834. "may not be reliable.")
  835. # endian.h is required for rtcm104v2 unless the compiler defines
  836. # __ORDER_BIG_ENDIAN__, __ORDER_LITTLE_ENDIAN__ and __BYTE_ORDER__
  837. if config.CheckCompilerDefines("__ORDER_BIG_ENDIAN__") \
  838. and config.CheckCompilerDefines("__ORDER_LITTLE_ENDIAN__") \
  839. and config.CheckCompilerDefines("__BYTE_ORDER__"):
  840. confdefs.append("#define HAVE_BUILTIN_ENDIANNESS 1\n")
  841. confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
  842. confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
  843. announce("Your compiler has built-in endianness support.")
  844. else:
  845. confdefs.append("/* #undef HAVE_BUILTIN_ENDIANNESS\n */")
  846. if config.CheckHeader("endian.h"):
  847. confdefs.append("#define HAVE_ENDIAN_H 1\n")
  848. confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
  849. confdefs.append("/* #undef HAVE_MACHINE_ENDIAN_H */\n")
  850. elif config.CheckHeader("sys/endian.h"):
  851. confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
  852. confdefs.append("#define HAVE_SYS_ENDIAN_H 1\n")
  853. confdefs.append("/* #undef HAVE_MACHINE_ENDIAN_H */\n")
  854. elif config.CheckHeader("machine/endian.h"):
  855. confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
  856. confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
  857. confdefs.append("#define HAVE_MACHINE_ENDIAN_H 1\n")
  858. else:
  859. confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
  860. confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
  861. confdefs.append("/* #undef HAVE_MACHINE_ENDIAN_H */\n")
  862. announce("You do not have the endian.h header file. "
  863. "RTCM V2 support disabled.")
  864. config.env["rtcm104v2"] = False
  865. for hdr in ("arpa/inet",
  866. "netdb",
  867. "netinet/in",
  868. "netinet/ip",
  869. "sys/sysmacros", # for major(), on linux
  870. "sys/socket",
  871. "sys/un",
  872. "syslog",
  873. "termios",
  874. "winsock2"
  875. ):
  876. if config.CheckHeader(hdr + ".h"):
  877. confdefs.append("#define HAVE_%s_H 1\n"
  878. % hdr.replace("/", "_").upper())
  879. else:
  880. confdefs.append("/* #undef HAVE_%s_H */\n"
  881. % hdr.replace("/", "_").upper())
  882. # check function after libraries, because some function require libraries
  883. # for example clock_gettime() require librt on Linux glibc < 2.17
  884. for f in ("cfmakeraw", "clock_gettime", "daemon", "fcntl", "fork",
  885. "gmtime_r", "inet_ntop", "strlcat", "strlcpy", "strptime"):
  886. if config.CheckFunc(f):
  887. confdefs.append("#define HAVE_%s 1\n" % f.upper())
  888. else:
  889. confdefs.append("/* #undef HAVE_%s */\n" % f.upper())
  890. # Apple may supply sincos() as __sincos(), or not at all
  891. if config.CheckFunc('sincos'):
  892. confdefs.append('#define HAVE_SINCOS\n')
  893. elif config.CheckFunc('__sincos'):
  894. confdefs.append('#define sincos __sincos\n#define HAVE_SINCOS\n')
  895. else:
  896. confdefs.append('/* #undef HAVE_SINCOS */\n')
  897. if config.CheckHeader(["sys/types.h", "sys/time.h", "sys/timepps.h"]):
  898. confdefs.append("#define HAVE_SYS_TIMEPPS_H 1\n")
  899. kpps = True
  900. else:
  901. kpps = False
  902. if config.env["magic_hat"]:
  903. announce("Forcing magic_hat=no since RFC2783 API is unavailable")
  904. config.env["magic_hat"] = False
  905. tiocmiwait = config.CheckHeaderDefines("sys/ioctl.h", "TIOCMIWAIT")
  906. if not tiocmiwait and not kpps:
  907. announce("Neither TIOCMIWAIT nor RFC2783 API is available)")
  908. if config.env["timeservice"]:
  909. announce("ERROR: timeservice specified, but no PPS available")
  910. Exit(1)
  911. # Map options to libraries required to support them that might be absent.
  912. optionrequires = {
  913. "bluez": ["libbluetooth"],
  914. "dbus_export": ["libdbus-1"],
  915. }
  916. keys = list(map(lambda x: (x[0], x[2]), boolopts)) \
  917. + list(map(lambda x: (x[0], x[2]), nonboolopts)) \
  918. + list(map(lambda x: (x[0], x[2]), pathopts))
  919. keys.sort()
  920. for (key, helpd) in keys:
  921. value = config.env[key]
  922. if value and key in optionrequires:
  923. for required in optionrequires[key]:
  924. if not config.CheckLib(required):
  925. announce("%s not found, %s cannot be enabled."
  926. % (required, key))
  927. value = False
  928. break
  929. confdefs.append("/* %s */" % helpd)
  930. if isinstance(value, bool):
  931. if value:
  932. confdefs.append("#define %s_ENABLE 1\n" % key.upper())
  933. else:
  934. confdefs.append("/* #undef %s_ENABLE */\n" % key.upper())
  935. elif value in (0, "", "(undefined)"):
  936. confdefs.append("/* #undef %s */\n" % key.upper())
  937. else:
  938. if value.isdigit():
  939. confdefs.append("#define %s %s\n" % (key.upper(), value))
  940. else:
  941. confdefs.append("#define %s \"%s\"\n" % (key.upper(), value))
  942. # Simplifies life on hackerboards like the Raspberry Pi
  943. if config.env['magic_hat']:
  944. confdefs.append('''\
  945. /* Magic device which, if present, means to grab a static /dev/pps0 for KPPS */
  946. #define MAGIC_HAT_GPS "/dev/ttyAMA0"
  947. /* Generic device which, if present, means: */
  948. /* to grab a static /dev/pps0 for KPPS */
  949. #define MAGIC_LINK_GPS "/dev/gpsd0"
  950. ''')
  951. confdefs.append('''\
  952. #define GPSD_CONFIG_H
  953. #endif /* GPSD_CONFIG_H */
  954. ''')
  955. manbuilder = htmlbuilder = None
  956. if config.env['manbuild']:
  957. if config.CheckXsltproc():
  958. build = ("xsltproc --encoding UTF-8 --output $TARGET"
  959. " --nonet %s $SOURCE")
  960. htmlbuilder = build % docbook_html_uri
  961. manbuilder = build % docbook_man_uri
  962. elif WhereIs("xmlto"):
  963. xmlto = "xmlto -o `dirname $TARGET` %s $SOURCE"
  964. htmlbuilder = xmlto % "html-nochunks"
  965. manbuilder = xmlto % "man"
  966. else:
  967. announce("Neither xsltproc nor xmlto found, documentation "
  968. "cannot be built.")
  969. else:
  970. announce("Build of man and HTML documentation is disabled.")
  971. if manbuilder:
  972. # 18.2. Attaching a Builder to a Construction Environment
  973. config.env.Append(BUILDERS={"Man": Builder(action=manbuilder,
  974. src_suffix=".xml")})
  975. config.env.Append(BUILDERS={"HTML": Builder(action=htmlbuilder,
  976. src_suffix=".xml",
  977. suffix=".html")})
  978. # Determine if Qt network libraries are present, and
  979. # if not, force qt to off
  980. if config.env["qt"]:
  981. qt_net_name = 'Qt%sNetwork' % config.env["qt_versioned"]
  982. qt_network = config.CheckPKG(qt_net_name)
  983. if not qt_network:
  984. config.env["qt"] = False
  985. announce('Turning off Qt support, library not found.')
  986. # If supported by the compiler, enable all warnings except uninitialized
  987. # and missing-field-initializers, which we can't help triggering because
  988. # of the way some of the JSON-parsing code is generated.
  989. # Also not including -Wcast-qual and -Wimplicit-function-declaration,
  990. # because we can't seem to keep scons from passing these to g++.
  991. #
  992. # Do this after the other config checks, to keep warnings out of them.
  993. for option in ('-Wall',
  994. '-Wcast-align',
  995. '-Wextra',
  996. # -Wimplicit-fallthrough same as
  997. # -Wimplicit-fallthrough=3, except osX hates the
  998. # second flavor
  999. '-Wimplicit-fallthrough',
  1000. '-Wmissing-declarations',
  1001. '-Wmissing-prototypes',
  1002. '-Wno-missing-field-initializers',
  1003. '-Wno-uninitialized',
  1004. '-Wpointer-arith',
  1005. '-Wreturn-type',
  1006. '-Wstrict-prototypes',
  1007. '-Wvla',
  1008. ):
  1009. if option not in config.env['CFLAGS']:
  1010. config.CheckCompilerOption(option)
  1011. # OSX needs to set the ID for installed shared libraries. See if this is OSX
  1012. # and whether we have the tool.
  1013. # Set up configuration for target Python
  1014. PYTHON_LIBDIR_CALL = 'sysconfig.get_python_lib()'
  1015. PYTHON_CONFIG_NAMES = ['CC', 'CXX', 'OPT', 'BASECFLAGS',
  1016. 'CCSHARED', 'LDSHARED', 'SO', 'INCLUDEPY', 'LDFLAGS']
  1017. PYTHON_CONFIG_QUOTED = ["'%s'" % s for s in PYTHON_CONFIG_NAMES]
  1018. PYTHON_CONFIG_CALL = ('sysconfig.get_config_vars(%s)'
  1019. % ', '.join(PYTHON_CONFIG_QUOTED))
  1020. # ugly hack from http://www.catb.org/esr/faqs/practical-python-porting/
  1021. # handle python2/3 strings
  1022. def polystr(o):
  1023. if isinstance(o, str):
  1024. return o
  1025. if isinstance(o, bytes):
  1026. return str(o, encoding='latin-1')
  1027. raise ValueError
  1028. if helping:
  1029. # If helping just get usable config info from the local Python
  1030. target_python_path = ''
  1031. py_config_text = str(eval(PYTHON_CONFIG_CALL))
  1032. python_libdir = str(eval(PYTHON_LIBDIR_CALL))
  1033. else:
  1034. if config.env['python'] and config.env['target_python']:
  1035. try:
  1036. config.CheckProg
  1037. except AttributeError: # Older scons versions don't have CheckProg
  1038. target_python_path = config.env['target_python']
  1039. else:
  1040. target_python_path = config.CheckProg(config.env['target_python'])
  1041. if not target_python_path:
  1042. announce("Target Python doesn't exist - disabling Python.")
  1043. config.env['python'] = False
  1044. if config.env['python']:
  1045. # Maximize consistency by using the reported sys.executable
  1046. target_python_path = config.GetPythonValue('exe path',
  1047. 'import sys',
  1048. 'sys.executable',
  1049. brief=cleaning)
  1050. if config.env['python_libdir']:
  1051. python_libdir = config.env['python_libdir']
  1052. else:
  1053. python_libdir = config.GetPythonValue('lib dir',
  1054. PYTHON_SYSCONFIG_IMPORT,
  1055. PYTHON_LIBDIR_CALL,
  1056. brief=cleaning)
  1057. # follow FHS, put in /usr/local/libXX, not /usr/libXX
  1058. # may be lib, lib32 or lib64
  1059. python_libdir = polystr(python_libdir)
  1060. python_libdir = python_libdir.replace("/usr/lib",
  1061. "/usr/local/lib")
  1062. py_config_text = config.GetPythonValue('config vars',
  1063. PYTHON_SYSCONFIG_IMPORT,
  1064. PYTHON_CONFIG_CALL,
  1065. brief=True)
  1066. if config.env['python']: # May have been turned off by error
  1067. config.env['PYTHON'] = polystr(target_python_path)
  1068. # For regress-driver
  1069. config.env['ENV']['PYTHON'] = polystr(target_python_path)
  1070. py_config_vars = ast.literal_eval(py_config_text.decode())
  1071. py_config_vars = [[] if x is None else x for x in py_config_vars]
  1072. python_config = dict(zip(PYTHON_CONFIG_NAMES, py_config_vars))
  1073. announce(python_config)
  1074. env = config.Finish()
  1075. # All configuration should be finished. env can now be modified.
  1076. if not (cleaning or helping):
  1077. # Be explicit about what we're doing.
  1078. changelatch = False
  1079. for (name, default, helpd) in boolopts + nonboolopts + pathopts:
  1080. if env[name] != env.subst(default):
  1081. if not changelatch:
  1082. announce("Altered configuration variables:")
  1083. changelatch = True
  1084. announce("%s = %s (default %s): %s"
  1085. % (name, env[name], env.subst(default), helpd))
  1086. if not changelatch:
  1087. announce("All configuration flags are defaulted.")
  1088. # Gentoo systems can have a problem with the Python path
  1089. if os.path.exists("/etc/gentoo-release"):
  1090. announce("This is a Gentoo system.")
  1091. announce("Adjust your PYTHONPATH to see library directories "
  1092. "under /usr/local/lib")
  1093. # Should we build the Qt binding?
  1094. if env["qt"] and env["shared"]:
  1095. qt_env = env.Clone()
  1096. qt_env.MergeFlags('-DUSE_QT')
  1097. qt_env.Append(OBJPREFIX='qt-')
  1098. if not (cleaning or helping):
  1099. try:
  1100. qt_env.MergeFlags(pkg_config(qt_net_name))
  1101. except OSError:
  1102. announce("pkg_config is confused about the state of %s."
  1103. % qt_net_name)
  1104. qt_env = None
  1105. else:
  1106. qt_env = None
  1107. # Set up for Python coveraging if needed
  1108. if env['coveraging'] and env['python_coverage'] and not (cleaning or helping):
  1109. pycov_default = opts.options[opts.keys().index('python_coverage')].default
  1110. pycov_current = env['python_coverage']
  1111. pycov_list = pycov_current.split()
  1112. if env.GetOption('num_jobs') > 1 and pycov_current == pycov_default:
  1113. pycov_list.append('--parallel-mode')
  1114. # May need absolute path to coveraging tool if 'PythonXX' is prefixed
  1115. pycov_path = env.WhereIs(pycov_list[0])
  1116. if pycov_path:
  1117. pycov_list[0] = pycov_path
  1118. env['PYTHON_COVERAGE'] = ' '.join(pycov_list)
  1119. env['ENV']['PYTHON_COVERAGE'] = ' '.join(pycov_list)
  1120. else:
  1121. announce('Python coverage tool not found - disabling Python coverage.')
  1122. env['python_coverage'] = '' # So we see it in the options
  1123. # Two shared libraries provide most of the code for the C programs
  1124. # gpsd client library
  1125. libgps_sources = [
  1126. "ais_json.c",
  1127. "bits.c",
  1128. "gpsdclient.c",
  1129. "gps_maskdump.c",
  1130. "gpsutils.c",
  1131. "hex.c",
  1132. "json.c",
  1133. "libgps_core.c",
  1134. "libgps_dbus.c",
  1135. "libgps_json.c",
  1136. "libgps_shm.c",
  1137. "libgps_sock.c",
  1138. "netlib.c",
  1139. "os_compat.c",
  1140. "rtcm2_json.c",
  1141. "rtcm3_json.c",
  1142. "shared_json.c",
  1143. "timespec_str.c",
  1144. ]
  1145. if env['libgpsmm']:
  1146. libgps_sources.append("libgpsmm.cpp")
  1147. # gpsd server library
  1148. libgpsd_sources = [
  1149. "bsd_base64.c",
  1150. "crc24q.c",
  1151. "driver_ais.c",
  1152. "driver_evermore.c",
  1153. "driver_garmin.c",
  1154. "driver_garmin_txt.c",
  1155. "driver_geostar.c",
  1156. "driver_greis.c",
  1157. "driver_greis_checksum.c",
  1158. "driver_italk.c",
  1159. "driver_navcom.c",
  1160. "driver_nmea0183.c",
  1161. "driver_nmea2000.c",
  1162. "driver_oncore.c",
  1163. "driver_rtcm2.c",
  1164. "driver_rtcm3.c",
  1165. "drivers.c",
  1166. "driver_sirf.c",
  1167. "driver_skytraq.c",
  1168. "driver_superstar2.c",
  1169. "driver_tsip.c",
  1170. "driver_ubx.c",
  1171. "driver_zodiac.c",
  1172. "geoid.c",
  1173. "gpsd_json.c",
  1174. "isgps.c",
  1175. "libgpsd_core.c",
  1176. "matrix.c",
  1177. "net_dgpsip.c",
  1178. "net_gnss_dispatch.c",
  1179. "net_ntrip.c",
  1180. "ntpshmread.c",
  1181. "ntpshmwrite.c",
  1182. "packet.c",
  1183. "ppsthread.c",
  1184. "pseudoais.c",
  1185. "pseudonmea.c",
  1186. "serial.c",
  1187. "subframe.c",
  1188. "timebase.c",
  1189. ]
  1190. if not env["shared"]:
  1191. def Library(env, target, sources, version, parse_flags=None):
  1192. return env.StaticLibrary(target,
  1193. [env.StaticObject(s) for s in sources],
  1194. parse_flags=parse_flags)
  1195. def LibraryInstall(env, libdir, sources, version):
  1196. return env.Install(libdir, sources)
  1197. else:
  1198. def Library(env, target, sources, version, parse_flags=None):
  1199. # Note: We have a possibility of getting either Object or file
  1200. # list for sources, so we run through the sources and try to make
  1201. # them into SharedObject instances.
  1202. obj_list = []
  1203. for s in Flatten(sources):
  1204. if isinstance(s, str):
  1205. obj_list.append(env.SharedObject(s))
  1206. else:
  1207. obj_list.append(s)
  1208. return env.SharedLibrary(target=target,
  1209. source=obj_list,
  1210. parse_flags=parse_flags,
  1211. SHLIBVERSION=version)
  1212. def LibraryInstall(env, libdir, sources, version):
  1213. # note: osX lib name s/b libgps.VV.dylib
  1214. # where VV is libgps_version_current
  1215. inst = env.InstallVersionedLib(libdir, sources, SHLIBVERSION=version)
  1216. return inst
  1217. libgps_shared = Library(env=env,
  1218. target="gps",
  1219. sources=libgps_sources,
  1220. version=libgps_version,
  1221. parse_flags=rtlibs + libgps_flags)
  1222. env.Clean(libgps_shared, "gps_maskdump.c")
  1223. libgps_static = env.StaticLibrary("gps_static",
  1224. [env.StaticObject(s)
  1225. for s in libgps_sources], rtlibs)
  1226. static_gpsdlib = env.StaticLibrary(
  1227. target="gpsd",
  1228. source=[env.StaticObject(s, parse_flags=usbflags + bluezflags)
  1229. for s in libgpsd_sources],
  1230. parse_flags=usbflags + bluezflags)
  1231. libraries = [libgps_shared]
  1232. # Only attempt to create the qt library if we have shared turned on
  1233. # otherwise we have a mismash of objects in library
  1234. if qt_env:
  1235. qtobjects = []
  1236. qt_flags = qt_env['CFLAGS']
  1237. for c_only in ('-Wmissing-prototypes', '-Wstrict-prototypes'):
  1238. if c_only in qt_flags:
  1239. qt_flags.remove(c_only)
  1240. # Qt binding object files have to be renamed as they're built to avoid
  1241. # name clashes with the plain non-Qt object files. This prevents the
  1242. # infamous "Two environments with different actions were specified
  1243. # for the same target" error.
  1244. for src in libgps_sources:
  1245. if src not in ('ais_json.c', 'json.c', 'libgps_json.c',
  1246. 'rtcm2_json.c', 'rtcm3_json.c', 'shared_json.c'):
  1247. compile_with = qt_env['CXX']
  1248. compile_flags = qt_flags
  1249. else:
  1250. compile_with = qt_env['CC']
  1251. compile_flags = qt_env['CFLAGS']
  1252. qtobjects.append(qt_env.SharedObject(src,
  1253. CC=compile_with,
  1254. CFLAGS=compile_flags))
  1255. compiled_qgpsmmlib = Library(qt_env, "Qgpsmm", qtobjects, libgps_version)
  1256. libraries.append(compiled_qgpsmmlib)
  1257. # The libraries have dependencies on system libraries
  1258. # libdbus appears multiple times because the linker only does one pass.
  1259. gpsflags = mathlibs + rtlibs + dbusflags
  1260. gpsdflags = usbflags + bluezflags + gpsflags
  1261. # Source groups
  1262. gpsd_sources = [
  1263. 'dbusexport.c',
  1264. 'gpsd.c',
  1265. 'shmexport.c',
  1266. 'timehint.c'
  1267. ]
  1268. if env['systemd']:
  1269. gpsd_sources.append("sd_socket.c")
  1270. gpsmon_sources = [
  1271. 'gpsmon.c',
  1272. 'monitor_garmin.c',
  1273. 'monitor_italk.c',
  1274. 'monitor_nmea0183.c',
  1275. 'monitor_oncore.c',
  1276. 'monitor_sirf.c',
  1277. 'monitor_superstar2.c',
  1278. 'monitor_tnt.c',
  1279. 'monitor_ubx.c',
  1280. ]
  1281. # Production programs
  1282. gpsd = env.Program('gpsd', gpsd_sources,
  1283. LIBS=['gpsd', 'gps_static'],
  1284. parse_flags=gpsdflags + gpsflags)
  1285. gpsdecode = env.Program('gpsdecode', ['gpsdecode.c'],
  1286. LIBS=['gpsd', 'gps_static'],
  1287. parse_flags=gpsdflags + gpsflags)
  1288. gpsctl = env.Program('gpsctl', ['gpsctl.c'],
  1289. LIBS=['gpsd', 'gps_static'],
  1290. parse_flags=gpsdflags + gpsflags)
  1291. gpsmon = env.Program('gpsmon', gpsmon_sources,
  1292. LIBS=['gpsd', 'gps_static'],
  1293. parse_flags=gpsdflags + gpsflags + ncurseslibs)
  1294. gpsdctl = env.Program('gpsdctl', ['gpsdctl.c'],
  1295. LIBS=['gps_static'],
  1296. parse_flags=gpsflags)
  1297. gpspipe = env.Program('gpspipe', ['gpspipe.c'],
  1298. LIBS=['gps_static'],
  1299. parse_flags=gpsflags)
  1300. gpsrinex = env.Program('gpsrinex', ['gpsrinex.c'],
  1301. LIBS=['gps_static'],
  1302. parse_flags=gpsflags)
  1303. gps2udp = env.Program('gps2udp', ['gps2udp.c'],
  1304. LIBS=['gps_static'],
  1305. parse_flags=gpsflags)
  1306. gpxlogger = env.Program('gpxlogger', ['gpxlogger.c'],
  1307. LIBS=['gps_static'],
  1308. parse_flags=gpsflags)
  1309. lcdgps = env.Program('lcdgps', ['lcdgps.c'],
  1310. LIBS=['gps_static'],
  1311. parse_flags=gpsflags)
  1312. cgps = env.Program('cgps', ['cgps.c'],
  1313. LIBS=['gps_static'],
  1314. parse_flags=gpsflags + ncurseslibs)
  1315. ntpshmmon = env.Program('ntpshmmon', ['ntpshmmon.c'],
  1316. LIBS=['gpsd', 'gps_static'],
  1317. parse_flags=gpsflags)
  1318. ppscheck = env.Program('ppscheck', ['ppscheck.c'],
  1319. LIBS=['gps_static'],
  1320. parse_flags=gpsflags)
  1321. bin_binaries = []
  1322. sbin_binaries = []
  1323. if env["gpsd"]:
  1324. sbin_binaries += [gpsd]
  1325. if env["gpsdclients"]:
  1326. sbin_binaries += [gpsdctl]
  1327. bin_binaries += [
  1328. gps2udp,
  1329. gpsctl,
  1330. gpsdecode,
  1331. gpspipe,
  1332. gpsrinex,
  1333. gpxlogger,
  1334. lcdgps
  1335. ]
  1336. if env["timeservice"] or env["gpsdclients"]:
  1337. bin_binaries += [ntpshmmon]
  1338. if tiocmiwait:
  1339. bin_binaries += [ppscheck]
  1340. if env["ncurses"] and (env["timeservice"] or env["gpsdclients"]):
  1341. bin_binaries += [cgps, gpsmon]
  1342. else:
  1343. announce("WARNING: not building cgps or gpsmon")
  1344. # Test programs - always link locally and statically
  1345. test_bits = env.Program('tests/test_bits', ['tests/test_bits.c'],
  1346. LIBS=['gps_static'])
  1347. test_float = env.Program('tests/test_float', ['tests/test_float.c'])
  1348. test_geoid = env.Program('tests/test_geoid', ['tests/test_geoid.c'],
  1349. LIBS=['gpsd', 'gps_static'],
  1350. parse_flags=gpsdflags)
  1351. test_gpsdclient = env.Program('tests/test_gpsdclient',
  1352. ['tests/test_gpsdclient.c'],
  1353. LIBS=['gps_static', 'm'])
  1354. test_matrix = env.Program('tests/test_matrix', ['tests/test_matrix.c'],
  1355. LIBS=['gpsd', 'gps_static'],
  1356. parse_flags=gpsdflags)
  1357. test_mktime = env.Program('tests/test_mktime', ['tests/test_mktime.c'],
  1358. LIBS=['gps_static'], parse_flags=mathlibs + rtlibs)
  1359. test_packet = env.Program('tests/test_packet', ['tests/test_packet.c'],
  1360. LIBS=['gpsd', 'gps_static'],
  1361. parse_flags=gpsdflags)
  1362. test_timespec = env.Program('tests/test_timespec', ['tests/test_timespec.c'],
  1363. LIBS=['gpsd', 'gps_static'],
  1364. parse_flags=gpsdflags)
  1365. test_trig = env.Program('tests/test_trig', ['tests/test_trig.c'],
  1366. parse_flags=mathlibs)
  1367. # test_libgps for glibc older than 2.17
  1368. test_libgps = env.Program('tests/test_libgps', ['tests/test_libgps.c'],
  1369. LIBS=['gps_static'],
  1370. parse_flags=mathlibs + rtlibs + dbusflags)
  1371. if not env['socket_export']:
  1372. announce("test_json not building because socket_export is disabled")
  1373. test_json = None
  1374. else:
  1375. test_json = env.Program(
  1376. 'tests/test_json', ['tests/test_json.c'],
  1377. LIBS=['gps_static'],
  1378. parse_flags=mathlibs + rtlibs + usbflags + dbusflags)
  1379. # duplicate below?
  1380. test_gpsmm = env.Program('tests/test_gpsmm', ['tests/test_gpsmm.cpp'],
  1381. LIBS=['gps_static', 'gps'],
  1382. parse_flags=mathlibs + rtlibs + dbusflags)
  1383. testprogs = [test_bits,
  1384. test_float,
  1385. test_geoid,
  1386. test_gpsdclient,
  1387. test_libgps,
  1388. test_matrix,
  1389. test_mktime,
  1390. test_packet,
  1391. test_timespec,
  1392. test_trig]
  1393. if env['socket_export']:
  1394. testprogs.append(test_json)
  1395. if env["libgpsmm"]:
  1396. testprogs.append(test_gpsmm)
  1397. # Python programs
  1398. if not env['python']:
  1399. python_built_extensions = []
  1400. python_manpages = []
  1401. python_misc = []
  1402. python_progs = []
  1403. python_targets = []
  1404. else:
  1405. # installed python programs
  1406. python_progs = ["gegps", "gpscat", "gpsfake", "gpsprof", "ubxtool", "zerk"]
  1407. python_deps = {'gpscat': 'packet'}
  1408. # python misc helpers and stuff
  1409. python_misc = [
  1410. "gpscap.py",
  1411. "gpssim.py",
  1412. "jsongen.py",
  1413. "leapsecond.py",
  1414. "maskaudit.py",
  1415. "test_clienthelpers.py",
  1416. "test_misc.py",
  1417. "test_xgps_deps.py",
  1418. "valgrind-audit.py"
  1419. ]
  1420. python_manpages = {
  1421. "man/gegps.1": "man/gps.xml",
  1422. "man/gpscat.1": "man/gpscat.xml",
  1423. "man/gpsfake.1": "man/gpsfake.xml",
  1424. "man/gpsprof.1": "man/gpsprof.xml",
  1425. "man/ubxtool.1": "man/ubxtool.xml",
  1426. "man/zerk.1": "man/zerk.xml",
  1427. }
  1428. # aiogps is only available on Python >= 3.6
  1429. # FIXME check target_python, not current python
  1430. if sys.version_info < (3, 6):
  1431. env['aiogps'] = False
  1432. announce("WARNING: Python too old: "
  1433. "gps/aiogps.py will not be installed\n")
  1434. else:
  1435. env['aiogps'] = True
  1436. python_misc.extend(["example_aiogps.py", "example_aiogps_run"])
  1437. if env['xgps']:
  1438. # check for pycairo
  1439. try:
  1440. imp.find_module('cairo')
  1441. except ImportError:
  1442. # no pycairo, don't build xgps, xgpsspeed
  1443. announce("WARNING: Python module pycairo not found.")
  1444. env['xgps'] = False
  1445. # check for pygobject
  1446. try:
  1447. imp.find_module('gi')
  1448. except ImportError:
  1449. # no pygobject, don't build xgps, xgpsspeed
  1450. announce("WARNING: Python module pygobject not found.")
  1451. env['xgps'] = False
  1452. if env['xgps']:
  1453. python_progs.extend(["xgps", "xgpsspeed"])
  1454. python_manpages.update({
  1455. "man/xgps.1": "man/gps.xml",
  1456. "man/xgpsspeed.1": "man/gps.xml",
  1457. })
  1458. else:
  1459. announce("WARNING: xgps and xgpsspeed will not be installed")
  1460. # Glob() has to be run after all buildable objects defined
  1461. if env['aiogps']:
  1462. python_modules = Glob('gps/*.py', strings=True)
  1463. else:
  1464. python_modules = Glob('gps/*.py',strings=True, exclude="gps/aiogps.py")
  1465. # Build Python binding
  1466. #
  1467. python_extensions = {
  1468. "gps" + os.sep + "packet": ["crc24q.c",
  1469. "driver_greis_checksum.c",
  1470. "driver_rtcm2.c",
  1471. "gpspacket.c",
  1472. "hex.c",
  1473. "isgps.c",
  1474. "os_compat.c",
  1475. "packet.c",
  1476. ]
  1477. }
  1478. python_env = env.Clone()
  1479. # FIXME: build of python wrappers doesn't pickup flags set for coveraging,
  1480. # manually add them here
  1481. if env['coveraging']:
  1482. python_config['BASECFLAGS'] += ' -coverage'
  1483. python_config['LDFLAGS'] += ' -coverage'
  1484. python_config['LDSHARED'] += ' -coverage'
  1485. # in case CC/CXX was set to the scan-build wrapper,
  1486. # ensure that we build the python modules with scan-build, too
  1487. if env['CC'] is None or env['CC'].find('scan-build') < 0:
  1488. python_env['CC'] = python_config['CC']
  1489. # As we seem to be changing compilers we must assume that the
  1490. # CCFLAGS are incompatible with the new compiler. If we should
  1491. # use other flags, the variable or the variable for this
  1492. # should be predefined.
  1493. if python_config['CC'].split()[0] != env['CC']:
  1494. python_env['CCFLAGS'] = ''
  1495. else:
  1496. python_env['CC'] = (' '.join([env['CC']] +
  1497. python_config['CC'].split()[1:]))
  1498. if env['CXX'] is None or env['CXX'].find('scan-build') < 0:
  1499. python_env['CXX'] = python_config['CXX']
  1500. # As we seem to be changing compilers we must assume that the
  1501. # CCFLAGS or CXXFLAGS are incompatible with the new
  1502. # compiler. If we should use other flags, the variable or the
  1503. # variable for this should be predefined.
  1504. if python_config['CXX'].split()[0] != env['CXX']:
  1505. python_env['CCFLAGS'] = ''
  1506. python_env['CXXFLAGS'] = ''
  1507. else:
  1508. python_env['CXX'] = (' '.join([env['CXX']] +
  1509. python_config['CXX'].split()[1:]))
  1510. ldshared = python_config['LDSHARED']
  1511. ldshared = ldshared.replace('-fPIE', '')
  1512. ldshared = ldshared.replace('-pie', '')
  1513. python_env.Replace(SHLINKFLAGS=[],
  1514. LDFLAGS=python_config['LDFLAGS'],
  1515. LINK=ldshared,
  1516. SHLIBPREFIX="",
  1517. SHLIBSUFFIX=python_config['SO'],
  1518. CPPPATH=[python_config['INCLUDEPY']],
  1519. CPPFLAGS=python_config['OPT'],
  1520. CFLAGS=python_config['BASECFLAGS'],
  1521. CXXFLAGS=python_config['BASECFLAGS'])
  1522. python_objects = {}
  1523. python_compiled_libs = {}
  1524. for ext, sources in python_extensions.items():
  1525. python_objects[ext] = []
  1526. for src in sources:
  1527. python_objects[ext].append(
  1528. python_env.NoCache(
  1529. python_env.SharedObject(
  1530. src.split(".")[0] + '-py_' +
  1531. '_'.join(['%s' % (x) for x in sys.version_info]) +
  1532. python_config['SO'], src
  1533. )
  1534. )
  1535. )
  1536. python_compiled_libs[ext] = python_env.SharedLibrary(
  1537. ext, python_objects[ext])
  1538. # Make sure we know about compiled dependencies
  1539. for prog, dep in python_deps.items():
  1540. env.Depends(prog, python_compiled_libs['gps' + os.sep + dep])
  1541. # Make PEP 241 Metadata 1.0.
  1542. # Why not PEP 314 (V1.1) or PEP 345 (V1.2)?
  1543. # V1.2 and V1.2 require a Download-URL to an installable binary
  1544. python_egg_info_source = """Metadata-Version: 1.0
  1545. Name: gps
  1546. Version: %s
  1547. Summary: Python libraries for the gpsd service daemon
  1548. Home-page: %s
  1549. Author: the GPSD project
  1550. Author-email: %s
  1551. License: BSD
  1552. Keywords: GPS
  1553. Description: The gpsd service daemon can monitor one or more GPS devices \
  1554. connected to a host computer, making all data on the location and movements \
  1555. of the sensors available to be queried on TCP port 2947.
  1556. Platform: UNKNOWN
  1557. """ % (gpsd_version, website, devmail)
  1558. python_egg_info = python_env.Textfile(target="gps-%s.egg-info"
  1559. % (gpsd_version, ),
  1560. source=python_egg_info_source)
  1561. python_built_extensions = list(python_compiled_libs.values())
  1562. python_targets = python_built_extensions + [python_egg_info]
  1563. env.Command(target="packet_names.h", source="packet_states.h",
  1564. action="""
  1565. rm -f $TARGET &&\
  1566. sed -e '/^ *\\([A-Z][A-Z0-9_]*\\),/s// \"\\1\",/' <$SOURCE >$TARGET &&\
  1567. chmod a-w $TARGET""")
  1568. # timebase.h - always built in order to include current GPS week
  1569. def timebase_h(target, source, env):
  1570. f = open(target[0].abspath, 'w')
  1571. f.write(leapsecond.make_leapsecond_include(source[0].abspath))
  1572. f.close()
  1573. timebase = env.Command(target="timebase.h",
  1574. source=["leapseconds.cache"], action=timebase_h)
  1575. env.AlwaysBuild(timebase)
  1576. env.Textfile(target="gpsd_config.h", source=confdefs)
  1577. env.Command(target="gps_maskdump.c",
  1578. source=["maskaudit.py", "gps.h", "gpsd.h"],
  1579. action='''
  1580. rm -f $TARGET &&\
  1581. $SC_PYTHON $SOURCE -c $SRCDIR >$TARGET &&\
  1582. chmod a-w $TARGET''')
  1583. env.Command(target="ais_json.i", source="jsongen.py", action='''\
  1584. rm -f $TARGET &&\
  1585. $SC_PYTHON $SOURCE --ais --target=parser >$TARGET &&\
  1586. chmod a-w $TARGET''')
  1587. generated_sources = ['packet_names.h', 'timebase.h', "ais_json.i",
  1588. 'gps_maskdump.c', 'revision.h', 'gpsd.php',
  1589. 'gpsd_config.h']
  1590. # Helper functions for revision hackery
  1591. def GetMtime(file):
  1592. """Get mtime of given file, or 0."""
  1593. try:
  1594. return os.stat(file).st_mtime
  1595. except OSError:
  1596. return 0
  1597. def FileList(patterns, exclusions=None):
  1598. """Get list of files based on patterns, minus excluded files."""
  1599. files = functools.reduce(operator.add, map(glob.glob, patterns), [])
  1600. for file in exclusions:
  1601. try:
  1602. files.remove(file)
  1603. except ValueError:
  1604. pass
  1605. return files
  1606. # generate revision.h
  1607. if 'dev' in gpsd_version:
  1608. (st, rev) = _getstatusoutput('git describe --tags')
  1609. if st != 0:
  1610. # Use timestamp from latest relevant file
  1611. files = FileList(['*.c', '*.cpp', '*.h', '*.in', 'SConstruct'],
  1612. generated_sources)
  1613. timestamps = map(GetMtime, files)
  1614. if timestamps:
  1615. from datetime import datetime
  1616. latest = datetime.fromtimestamp(sorted(timestamps)[-1])
  1617. rev = '%s-%s' % (gpsd_version, latest.isoformat())
  1618. else:
  1619. rev = gpsd_version # Paranoia
  1620. else:
  1621. rev = gpsd_version
  1622. revision = '''/* Automatically generated file, do not edit */
  1623. #define REVISION "%s"
  1624. ''' % (polystr(rev.strip()),)
  1625. env.Textfile(target="revision.h", source=[revision])
  1626. # leapseconds.cache is a local cache for information on leapseconds issued
  1627. # by the U.S. Naval observatory. It gets kept in the repository so we can
  1628. # build without Internet access.
  1629. def leapseconds_cache_rebuild(target, source, env):
  1630. if not env["leapfetch"]:
  1631. sys.stdout.write("Leapsecond fetch suppressed by leapfetch=no.\n")
  1632. elif not leapsecond.conditional_leapsecond_fetch(target[0].abspath,
  1633. timeout=15):
  1634. sys.stdout.write("try building with leapfetch=no.\n")
  1635. if 'dev' in gpsd_version or not os.path.exists('leapseconds.cache'):
  1636. leapseconds_cache = env.Command(target="leapseconds.cache",
  1637. source="leapsecond.py",
  1638. action=leapseconds_cache_rebuild)
  1639. env.Clean(leapseconds_cache, "leapsecond.pyc")
  1640. env.NoClean(leapseconds_cache)
  1641. env.Precious(leapseconds_cache)
  1642. env.AlwaysBuild(leapseconds_cache)
  1643. if env['systemd']:
  1644. udevcommand = 'TAG+="systemd", ENV{SYSTEMD_WANTS}="gpsdctl@%k.service"'
  1645. else:
  1646. udevcommand = 'RUN+="%s/gpsd.hotplug"' % (env['udevdir'], )
  1647. # Instantiate some file templates. We'd like to use the Substfile builtin
  1648. # but it doesn't seem to work in scons 1.20
  1649. def substituter(target, source, env):
  1650. substmap = (
  1651. ('@ANNOUNCE@', annmail),
  1652. ('@BUGTRACKER@', bugtracker),
  1653. ('@CGIUPLOAD@', cgiupload),
  1654. ('@CLONEREPO@', clonerepo),
  1655. ('@DATE@', time.asctime()),
  1656. ('@DEVMAIL@', devmail),
  1657. ('@DOWNLOAD@', download),
  1658. ('@FORMSERVER@', formserver),
  1659. ('@GITREPO@', gitrepo),
  1660. ('@includedir@', installdir('includedir', add_destdir=False)),
  1661. ('@IRCCHAN@', ircchan),
  1662. ('@libdir@', installdir('libdir', add_destdir=False)),
  1663. ('@LIBGPSVERSION@', libgps_version),
  1664. ('@MAILMAN@', mailman),
  1665. ('@MAINPAGE@', mainpage),
  1666. ('@MASTER@', 'DO NOT HAND_HACK! THIS FILE IS GENERATED'),
  1667. ('@prefix@', env['prefix']),
  1668. ('@PROJECTPAGE@', projectpage),
  1669. ('@QTVERSIONED@', env['qt_versioned']),
  1670. ('@SCPUPLOAD@', scpupload),
  1671. ('@SITENAME@', sitename),
  1672. ('@SITESEARCH@', sitesearch),
  1673. ('@TIPLINK@', tiplink),
  1674. ('@TIPWIDGET@', tipwidget),
  1675. ('@udevcommand@', udevcommand),
  1676. ('@USERMAIL@', usermail),
  1677. ('@VERSION@', gpsd_version),
  1678. ('@WEBFORM@', webform),
  1679. ('@WEBSITE@', website),
  1680. )
  1681. sfp = open(str(source[0]))
  1682. content = sfp.read()
  1683. sfp.close()
  1684. for (s, t) in substmap:
  1685. content = content.replace(s, t)
  1686. m = re.search("@[A-Z]+@", content)
  1687. if m and m.group(0) not in map(lambda x: x[0], substmap):
  1688. print("Unknown subst token %s in %s." % (m.group(0), sfp.name),
  1689. file=sys.stderr)
  1690. tfp = open(str(target[0]), "w")
  1691. tfp.write(content)
  1692. tfp.close()
  1693. templated = glob.glob("*.in") + glob.glob("*/*.in") + glob.glob("*/*/*.in")
  1694. # ignore files in subfolder called 'debian' - the Debian packaging
  1695. # tools will handle them.
  1696. templated = [x for x in templated if not x.startswith('debian/')]
  1697. for fn in templated:
  1698. builder = env.Command(source=fn, target=fn[:-3], action=substituter)
  1699. env.AddPostAction(builder, 'chmod -w $TARGET')
  1700. if fn.endswith(".py.in"):
  1701. env.AddPostAction(builder, 'chmod +x $TARGET')
  1702. # Documentation
  1703. base_manpages = {
  1704. "man/cgps.1": "man/gps.xml",
  1705. "man/gps.1": "man/gps.xml",
  1706. "man/gps2udp.1": "man/gps2udp.xml",
  1707. "man/gpsctl.1": "man/gpsctl.xml",
  1708. "man/gpsd.8": "man/gpsd.xml",
  1709. "man/gpsdctl.8": "man/gpsdctl.xml",
  1710. "man/gpsdecode.1": "man/gpsdecode.xml",
  1711. "man/gpsd_json.5": "man/gpsd_json.xml",
  1712. "man/gpsinit.8": "man/gpsinit.xml",
  1713. "man/gpsmon.1": "man/gpsmon.xml",
  1714. "man/gpspipe.1": "man/gpspipe.xml",
  1715. "man/gpsrinex.1": "man/gpsrinex.xml",
  1716. "man/gpxlogger.1": "man/gpxlogger.xml",
  1717. "man/lcdgps.1": "man/gps.xml",
  1718. "man/libgps.3": "man/libgps.xml",
  1719. "man/libgpsmm.3": "man/libgpsmm.xml",
  1720. "man/libQgpsmm.3": "man/libgpsmm.xml",
  1721. "man/srec.5": "man/srec.xml",
  1722. }
  1723. if env["timeservice"] or env["gpsdclients"]:
  1724. base_manpages.update({
  1725. "man/ntpshmmon.1": "man/ntpshmmon.xml",
  1726. })
  1727. if tiocmiwait:
  1728. base_manpages.update({
  1729. "man/ppscheck.8": "man/ppscheck.xml",
  1730. })
  1731. all_manpages = list(base_manpages.keys())
  1732. other_manpages = [
  1733. "man/gegps.1",
  1734. "man/xgps.1",
  1735. "man/xgpsspeed.1",
  1736. ]
  1737. if python_manpages:
  1738. all_manpages += list(python_manpages.keys())
  1739. man_env = env.Clone()
  1740. if man_env.GetOption('silent'):
  1741. man_env['SPAWN'] = filtered_spawn # Suppress stderr chatter
  1742. manpage_targets = []
  1743. if manbuilder:
  1744. items = list(base_manpages.items())
  1745. if python_manpages:
  1746. items += list(python_manpages.items())
  1747. for (man, xml) in items:
  1748. manpage_targets.append(man_env.Man(source=xml, target=man))
  1749. # Where it all comes together
  1750. build = env.Alias('build',
  1751. [libraries, sbin_binaries, bin_binaries, python_targets,
  1752. "gpsd.php", manpage_targets,
  1753. "libgps.pc", "gpsd.rules"])
  1754. if qt_env:
  1755. # duplicate above?
  1756. test_qgpsmm = env.Program('tests/test_qgpsmm', ['tests/test_gpsmm.cpp'],
  1757. LIBPATH=['.'],
  1758. OBJPREFIX='qt-',
  1759. LIBS=['Qgpsmm', 'gps'])
  1760. build_qt = qt_env.Alias('build', [compiled_qgpsmmlib, test_qgpsmm])
  1761. qt_env.Default(*build_qt)
  1762. testprogs.append(test_qgpsmm)
  1763. if env['python']:
  1764. build_python = python_env.Alias('build', python_targets)
  1765. python_env.Default(*build_python)
  1766. # Installation and deinstallation
  1767. # Not here because too distro-specific: udev rules, desktop files, init scripts
  1768. # It's deliberate that we don't install gpsd.h. It's full of internals that
  1769. # third-party client programs should not see.
  1770. headerinstall = [env.Install(installdir('includedir'), x)
  1771. for x in ("libgpsmm.h", "gps.h")]
  1772. binaryinstall = []
  1773. binaryinstall.append(env.Install(installdir('sbindir'), sbin_binaries))
  1774. binaryinstall.append(env.Install(installdir('bindir'), bin_binaries))
  1775. binaryinstall.append(LibraryInstall(env, installdir('libdir'), libgps_shared,
  1776. libgps_version))
  1777. # Work around a minor bug in InstallSharedLib() link handling
  1778. env.AddPreAction(binaryinstall, 'rm -f %s/libgps.*' % (installdir('libdir'), ))
  1779. if qt_env:
  1780. binaryinstall.append(LibraryInstall(qt_env, installdir('libdir'),
  1781. compiled_qgpsmmlib, libgps_version))
  1782. if ((not env['debug'] and not env['profiling'] and not env['nostrip'] and
  1783. not sys.platform.startswith('darwin'))):
  1784. env.AddPostAction(binaryinstall, '$STRIP $TARGET')
  1785. if env['python']:
  1786. python_module_dir = str(python_libdir) + os.sep + 'gps'
  1787. python_extensions_install = python_env.Install(DESTDIR + python_module_dir,
  1788. python_built_extensions)
  1789. if ((not env['debug'] and not env['profiling'] and
  1790. not env['nostrip'] and not sys.platform.startswith('darwin'))):
  1791. python_env.AddPostAction(python_extensions_install, '$STRIP $TARGET')
  1792. python_modules_install = python_env.Install(DESTDIR + python_module_dir,
  1793. python_modules)
  1794. python_progs_install = python_env.Install(installdir('bindir'),
  1795. python_progs)
  1796. python_egg_info_install = python_env.Install(DESTDIR + str(python_libdir),
  1797. python_egg_info)
  1798. python_install = [python_extensions_install,
  1799. python_modules_install,
  1800. python_progs_install,
  1801. python_egg_info_install,
  1802. # We don't need the directory explicitly for the
  1803. # install, but we do need it for the uninstall
  1804. Dir(DESTDIR + python_module_dir)]
  1805. # Check that Python modules compile properly
  1806. python_all = python_misc + python_modules + python_progs + ['SConstruct']
  1807. check_compile = []
  1808. for p in python_all:
  1809. # split in two lines for readability
  1810. check_compile.append('cp %s tmp.py; %s -tt -m py_compile tmp.py;' %
  1811. (p, sys.executable))
  1812. check_compile.append('rm tmp.py*')
  1813. python_compilation_regress = Utility('python-compilation-regress',
  1814. python_all, check_compile)
  1815. # Sanity-check Python code.
  1816. # Bletch. We don't really want to suppress W0231 E0602 E0611 E1123,
  1817. # but Python 3 syntax confuses a pylint running under Python 2.
  1818. # There's an internal error in astroid that requires we disable some
  1819. # auditing. This is irritating as hell but there's no help for it short
  1820. # of an upstream fix.
  1821. python_lint = python_misc + python_modules + python_progs + ['SConstruct']
  1822. pylint = Utility(
  1823. "pylint", python_lint,
  1824. ['''pylint --rcfile=/dev/null --dummy-variables-rgx='^_' '''
  1825. '''--msg-template='''
  1826. '''"{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}" '''
  1827. '''--reports=n --disable=F0001,C0103,C0111,C1001,C0301,C0122,C0302,'''
  1828. '''C0322,C0324,C0323,C0321,C0330,C0411,C0413,E1136,R0201,R0204,'''
  1829. '''R0801,'''
  1830. '''R0902,R0903,R0904,R0911,R0912,R0913,R0914,R0915,W0110,W0201,'''
  1831. '''W0121,W0123,W0231,W0232,W0234,W0401,W0403,W0141,W0142,W0603,'''
  1832. '''W0614,W0640,W0621,W1504,E0602,E0611,E1101,E1102,E1103,E1123,'''
  1833. '''F0401,I0011 ''' + " ".join(python_lint)])
  1834. # Additional Python readability style checks
  1835. pep8 = Utility("pep8", python_lint,
  1836. ['pycodestyle --ignore=W602,E122,E241 ' +
  1837. " ".join(python_lint)])
  1838. flake8 = Utility("flake8", python_lint,
  1839. ['flake8 --ignore=E501,W602,E122,E241,E401 ' +
  1840. " ".join(python_lint)])
  1841. # get version from each python prog
  1842. # this ensures they can run and gps_versions match
  1843. vchk = ''
  1844. verenv = env['ENV'].copy()
  1845. verenv['DISPLAY'] = '' # Avoid launching X11 in X11 progs
  1846. pp = []
  1847. for p in python_progs:
  1848. pp.append("$PYTHON $SRCDIR/%s -V" % p)
  1849. python_versions = Utility('python-versions', python_progs, pp, ENV=verenv)
  1850. else:
  1851. python_install = []
  1852. python_compilation_regress = None
  1853. python_versions = None
  1854. pc_install = [env.Install(installdir('pkgconfig'), 'libgps.pc')]
  1855. if qt_env:
  1856. pc_install.append(qt_env.Install(installdir('pkgconfig'), 'Qgpsmm.pc'))
  1857. pc_install.append(qt_env.Install(installdir('libdir'), 'libQgpsmm.prl'))
  1858. maninstall = []
  1859. for manpage in all_manpages:
  1860. if not manbuilder and not os.path.exists(manpage):
  1861. continue
  1862. section = manpage.split(".")[1]
  1863. dest = os.path.join(installdir('mandir'), "man" + section,
  1864. os.path.basename(manpage))
  1865. maninstall.append(env.InstallAs(source=manpage, target=dest))
  1866. install = env.Alias('install', binaryinstall + maninstall + python_install +
  1867. pc_install + headerinstall)
  1868. def Uninstall(nodes):
  1869. deletes = []
  1870. for node in nodes:
  1871. if node.__class__ == install[0].__class__:
  1872. deletes.append(Uninstall(node.sources))
  1873. else:
  1874. deletes.append(Delete(str(node)))
  1875. return deletes
  1876. uninstall = env.Command('uninstall', '',
  1877. Flatten(Uninstall(Alias("install"))) or "")
  1878. env.AlwaysBuild(uninstall)
  1879. env.Precious(uninstall)
  1880. # Target selection for '.' is badly broken. This is a general scons problem,
  1881. # not a glitch in this particular recipe. Avoid triggering the bug.
  1882. def error_action(target, source, env):
  1883. raise SCons.Error.UserError("Target selection for '.' is broken.")
  1884. AlwaysBuild(Alias(".", [], error_action))
  1885. # Putting in all these -U flags speeds up cppcheck and allows it to look
  1886. # at configurations we actually care about.
  1887. Utility("cppcheck", ["gpsd.h", "packet_names.h"],
  1888. "cppcheck -U__UNUSED__ -UUSE_QT -U__COVERITY__ -U__future__ "
  1889. "-ULIMITED_MAX_CLIENTS -ULIMITED_MAX_DEVICES -UAF_UNSPEC -UINADDR_ANY "
  1890. "-U_WIN32 -U__CYGWIN__ "
  1891. "-UPATH_MAX -UHAVE_STRLCAT -UHAVE_STRLCPY -UIPTOS_LOWDELAY "
  1892. "-UIPV6_TCLASS -UTCP_NODELAY -UTIOCMIWAIT --template gcc "
  1893. "--enable=all --inline-suppr --suppress='*:driver_proto.c' "
  1894. "--force $SRCDIR")
  1895. # Check with clang analyzer
  1896. Utility("scan-build", ["gpsd.h", "packet_names.h"],
  1897. "scan-build scons")
  1898. # Check the documentation for bogons, too
  1899. Utility("xmllint", glob.glob("man/*.xml"),
  1900. "for xml in $SOURCES; do xmllint --nonet --noout --valid $$xml; done")
  1901. # Use deheader to remove headers not required. If the statistics line
  1902. # ends with other than '0 removed' there's work to be done.
  1903. Utility("deheader", generated_sources, [
  1904. 'deheader -x cpp -x contrib -x gpspacket.c '
  1905. '-x monitor_proto.c -i gpsd_config.h -i gpsd.h '
  1906. '-m "MORECFLAGS=\'-Werror -Wfatal-errors -DDEBUG \' scons -Q"',
  1907. ])
  1908. # Perform all local code-sanity checks (but not the Coverity scan).
  1909. audit = env.Alias('audit',
  1910. ['cppcheck',
  1911. 'pylint',
  1912. 'scan-build',
  1913. 'valgrind-audit',
  1914. 'xmllint',
  1915. ])
  1916. #
  1917. # Regression tests begin here
  1918. #
  1919. # Note that the *-makeregress targets re-create the *.log.chk source
  1920. # files from the *.log source files.
  1921. # Unit-test the bitfield extractor
  1922. bits_regress = Utility('bits-regress', [test_bits], [
  1923. '$SRCDIR/tests/test_bits --quiet'
  1924. ])
  1925. # Unit-test the deg_to_str() converter
  1926. bits_regress = Utility('deg-regress', [test_gpsdclient], [
  1927. '$SRCDIR/tests/test_gpsdclient'
  1928. ])
  1929. # Unit-test the bitfield extractor
  1930. matrix_regress = Utility('matrix-regress', [test_matrix], [
  1931. '$SRCDIR/tests/test_matrix --quiet'
  1932. ])
  1933. # using regress-drivers requires socket_export being enabled.
  1934. if not env['socket_export'] or not env['python']:
  1935. announce("GPS regression tests suppressed because socket_export "
  1936. "or python is off.")
  1937. gps_regress = None
  1938. gpsfake_tests = None
  1939. else:
  1940. # Regression-test the daemon.
  1941. # But first dump the platform and its delay parameters.
  1942. # The ":;" in this production and the later one forestalls an attempt by
  1943. # SCons to install up to date versions of gpsfake and gpsctl if it can
  1944. # find older versions of them in a directory on your $PATH.
  1945. gps_herald = Utility('gps-herald', [gpsd, gpsctl, python_built_extensions],
  1946. ':; $PYTHON $PYTHON_COVERAGE $SRCDIR/gpsfake -T')
  1947. gps_log_pattern = os.path.join('test', 'daemon', '*.log')
  1948. gps_logs = glob.glob(gps_log_pattern)
  1949. gps_names = [os.path.split(x)[-1][:-4] for x in gps_logs]
  1950. gps_tests = []
  1951. for gps_name, gps_log in zip(gps_names, gps_logs):
  1952. gps_tests.append(Utility(
  1953. 'gps-regress-' + gps_name, gps_herald,
  1954. '$SRCDIR/regress-driver -q -o -t $REGRESSOPTS ' + gps_log))
  1955. if GetOption('num_jobs') <= 1:
  1956. gps_regress = Utility('gps-regress', gps_herald,
  1957. '$SRCDIR/regress-driver $REGRESSOPTS %s'
  1958. % gps_log_pattern)
  1959. else:
  1960. gps_regress = env.Alias('gps-regress', gps_tests)
  1961. # Run the passthrough log in all transport modes for better coverage
  1962. gpsfake_log = os.path.join('test', 'daemon', 'passthrough.log')
  1963. gpsfake_tests = []
  1964. for name, opts in [['pty', ''], ['udp', '-u'], ['tcp', '-o -t']]:
  1965. gpsfake_tests.append(Utility('gpsfake-' + name, gps_herald,
  1966. '$SRCDIR/regress-driver'
  1967. ' $REGRESSOPTS -q %s %s'
  1968. % (opts, gpsfake_log)))
  1969. env.Alias('gpsfake-tests', gpsfake_tests)
  1970. # Build the regression tests for the daemon.
  1971. # Note: You'll have to do this whenever the default leap second
  1972. # changes in timebase.h. The problem is in the SiRF tests;
  1973. # that driver relies on the default until it gets the current
  1974. # offset from subframe data.
  1975. gps_rebuilds = []
  1976. for gps_name, gps_log in zip(gps_names, gps_logs):
  1977. gps_rebuilds.append(Utility('gps-makeregress-' + gps_name, gps_herald,
  1978. '$SRCDIR/regress-driver -bq -o -t '
  1979. '$REGRESSOPTS ' + gps_log))
  1980. if GetOption('num_jobs') <= 1:
  1981. Utility('gps-makeregress', gps_herald,
  1982. '$SRCDIR/regress-driver -b $REGRESSOPTS %s' % gps_log_pattern)
  1983. else:
  1984. env.Alias('gps-makeregress', gps_rebuilds)
  1985. # To build an individual test for a load named foo.log, put it in
  1986. # test/daemon and do this:
  1987. # regress-driver -b test/daemon/foo.log
  1988. # Regression-test the RTCM decoder.
  1989. if not env["rtcm104v2"]:
  1990. announce("RTCM2 regression tests suppressed because rtcm104v2 is off.")
  1991. rtcm_regress = None
  1992. else:
  1993. rtcm_regress = Utility('rtcm-regress', [gpsdecode], [
  1994. '@echo "Testing RTCM decoding..."',
  1995. '@for f in $SRCDIR/test/*.rtcm2; do '
  1996. ' echo "\tTesting $${f}..."; '
  1997. ' TMPFILE=`mktemp -t gpsd-test.chk-XXXXXXXXXXXXXX`; '
  1998. ' $SRCDIR/gpsdecode -u -j <$${f} >$${TMPFILE}; '
  1999. ' diff -ub $${f}.chk $${TMPFILE} || echo "Test FAILED!"; '
  2000. ' rm -f $${TMPFILE}; '
  2001. 'done;',
  2002. '@echo "Testing idempotency of JSON dump/decode for RTCM2"',
  2003. '@TMPFILE=`mktemp -t gpsd-test.chk-XXXXXXXXXXXXXX`; '
  2004. '$SRCDIR/gpsdecode -u -e -j <test/synthetic-rtcm2.json >$${TMPFILE}; '
  2005. ' grep -v "^#" test/synthetic-rtcm2.json | diff -ub - $${TMPFILE} '
  2006. ' || echo "Test FAILED!"; '
  2007. ' rm -f $${TMPFILE}; ',
  2008. ])
  2009. # Rebuild the RTCM regression tests.
  2010. Utility('rtcm-makeregress', [gpsdecode], [
  2011. 'for f in $SRCDIR/test/*.rtcm2; do '
  2012. ' $SRCDIR/gpsdecode -j <$${f} >$${f}.chk; '
  2013. 'done'
  2014. ])
  2015. # Regression-test the AIVDM decoder.
  2016. if not env["aivdm"]:
  2017. announce("AIVDM regression tests suppressed because aivdm is off.")
  2018. aivdm_regress = None
  2019. else:
  2020. # FIXME! Does not return a proper fail code
  2021. aivdm_regress = Utility('aivdm-regress', [gpsdecode], [
  2022. '@echo "Testing AIVDM decoding w/ CSV format..."',
  2023. '@for f in $SRCDIR/test/*.aivdm; do '
  2024. ' echo "\tTesting $${f}..."; '
  2025. ' TMPFILE=`mktemp -t gpsd-test.chk-XXXXXXXXXXXXXX`; '
  2026. ' $SRCDIR/gpsdecode -u -c <$${f} >$${TMPFILE}; '
  2027. ' diff -ub $${f}.chk $${TMPFILE} || echo "Test FAILED!"; '
  2028. ' rm -f $${TMPFILE}; '
  2029. 'done;',
  2030. '@echo "Testing AIVDM decoding w/ JSON unscaled format..."',
  2031. '@for f in $SRCDIR/test/*.aivdm; do '
  2032. ' echo "\tTesting $${f}..."; '
  2033. ' TMPFILE=`mktemp -t gpsd-test.chk-XXXXXXXXXXXXXX`; '
  2034. ' $SRCDIR/gpsdecode -u -j <$${f} >$${TMPFILE}; '
  2035. ' diff -ub $${f}.ju.chk $${TMPFILE} || echo "Test FAILED!"; '
  2036. ' rm -f $${TMPFILE}; '
  2037. 'done;',
  2038. '@echo "Testing AIVDM decoding w/ JSON scaled format..."',
  2039. '@for f in $SRCDIR/test/*.aivdm; do '
  2040. ' echo "\tTesting $${f}..."; '
  2041. ' TMPFILE=`mktemp -t gpsd-test.chk-XXXXXXXXXXXXXX`; '
  2042. ' $SRCDIR/gpsdecode -j <$${f} >$${TMPFILE}; '
  2043. ' diff -ub $${f}.js.chk $${TMPFILE} || echo "Test FAILED!"; '
  2044. ' rm -f $${TMPFILE}; '
  2045. 'done;',
  2046. '@echo "Testing idempotency of unscaled JSON dump/decode for AIS"',
  2047. '@TMPFILE=`mktemp -t gpsd-test.chk-XXXXXXXXXXXXXX`; '
  2048. '$SRCDIR/gpsdecode -u -e -j <$SRCDIR/test/sample.aivdm.ju.chk '
  2049. ' >$${TMPFILE}; '
  2050. ' grep -v "^#" $SRCDIR/test/sample.aivdm.ju.chk '
  2051. ' | diff -ub - $${TMPFILE} || echo "Test FAILED!"; '
  2052. ' rm -f $${TMPFILE}; ',
  2053. # Parse the unscaled json reference, dump it as scaled json,
  2054. # and finally compare it with the scaled json reference
  2055. '@echo "Testing idempotency of scaled JSON dump/decode for AIS"',
  2056. '@TMPFILE=`mktemp -t gpsd-test.chk-XXXXXXXXXXXXXX`; '
  2057. '$SRCDIR/gpsdecode -e -j <$SRCDIR/test/sample.aivdm.ju.chk '
  2058. ' >$${TMPFILE};'
  2059. ' grep -v "^#" $SRCDIR/test/sample.aivdm.js.chk '
  2060. ' | diff -ub - $${TMPFILE} || echo "Test FAILED!"; '
  2061. ' rm -f $${TMPFILE}; ',
  2062. ])
  2063. # Rebuild the AIVDM regression tests.
  2064. Utility('aivdm-makeregress', [gpsdecode], [
  2065. 'for f in $SRCDIR/test/*.aivdm; do '
  2066. ' $SRCDIR/gpsdecode -u -c <$${f} > $${f}.chk; '
  2067. ' $SRCDIR/gpsdecode -u -j <$${f} > $${f}.ju.chk; '
  2068. ' $SRCDIR/gpsdecode -j <$${f} > $${f}.js.chk; '
  2069. 'done', ])
  2070. # Regression-test the packet getter.
  2071. packet_regress = UtilityWithHerald(
  2072. 'Testing detection of invalid packets...',
  2073. 'packet-regress', [test_packet], [
  2074. '$SRCDIR/tests/test_packet | '
  2075. ' diff -u $SRCDIR/test/packet.test.chk -', ])
  2076. # Rebuild the packet-getter regression test
  2077. Utility('packet-makeregress', [test_packet], [
  2078. '$SRCDIR/tests/test_packet >$SRCDIR/test/packet.test.chk', ])
  2079. # Regression-test the geoid and variation tester.
  2080. geoid_regress = UtilityWithHerald(
  2081. 'Testing the geoid and variation models...',
  2082. 'geoid-regress', [test_geoid], ['$SRCDIR/tests/test_geoid'])
  2083. # Regression-test the calendar functions
  2084. time_regress = Utility('time-regress', [test_mktime], [
  2085. '$SRCDIR/tests/test_mktime'
  2086. ])
  2087. if not env['python']:
  2088. unpack_regress = None
  2089. misc_regress = None
  2090. else:
  2091. # Regression test the unpacking code in libgps
  2092. unpack_regress = UtilityWithHerald(
  2093. 'Testing the client-library sentence decoder...',
  2094. 'unpack-regress', [test_libgps], [
  2095. '$SRCDIR/regress-driver $REGRESSOPTS -c'
  2096. ' $SRCDIR/test/clientlib/*.log', ])
  2097. # Unit-test the bitfield extractor
  2098. misc_regress = Utility('misc-regress', [], [
  2099. '$SRCDIR/test_clienthelpers.py',
  2100. '$SRCDIR/test_misc.py'
  2101. ])
  2102. # Build the regression test for the sentence unpacker
  2103. Utility('unpack-makeregress', [test_libgps], [
  2104. '@echo "Rebuilding the client sentence-unpacker tests..."',
  2105. '$SRCDIR/regress-driver $REGRESSOPTS -c -b $SRCDIR/test/clientlib/*.log'
  2106. ])
  2107. # Unit-test the JSON parsing
  2108. if not env['socket_export']:
  2109. json_regress = None
  2110. else:
  2111. json_regress = Utility('json-regress', [test_json],
  2112. ['$SRCDIR/tests/test_json'])
  2113. # Unit-test timespec math
  2114. timespec_regress = Utility('timespec-regress', [test_timespec], [
  2115. '$SRCDIR/tests/test_timespec'
  2116. ])
  2117. # Unit-test float math
  2118. float_regress = Utility('float-regress', [test_float], [
  2119. '$SRCDIR/tests/test_float'
  2120. ])
  2121. # Unit-test trig math
  2122. trig_regress = Utility('trig-regress', [test_trig], [
  2123. '$SRCDIR/tests/test_trig'
  2124. ])
  2125. # consistency-check the driver methods
  2126. method_regress = UtilityWithHerald(
  2127. 'Consistency-checking driver methods...',
  2128. 'method-regress', [test_packet], [
  2129. '$SRCDIR/tests/test_packet -c >/dev/null', ])
  2130. # Test the xgps/xgpsspeed dependencies
  2131. if not env['python'] or not env['xgps']:
  2132. test_xgps_deps = None
  2133. else:
  2134. test_xgps_deps = UtilityWithHerald(
  2135. 'Testing xgps/xgpsspeed dependencies (since xgps=yes)...',
  2136. 'test-xgps-deps', [], [
  2137. '$PYTHON $SRCDIR/test_xgps_deps.py'])
  2138. # Run a valgrind audit on the daemon - not in normal tests
  2139. valgrind_audit = Utility('valgrind-audit', [
  2140. '$SRCDIR/valgrind-audit.py', python_built_extensions, gpsd],
  2141. '$PYTHON $SRCDIR/valgrind-audit.py'
  2142. )
  2143. # Run test builds on remote machines
  2144. flocktest = Utility("flocktest", [], "cd devtools; ./flocktest " + gitrepo)
  2145. # Run all normal regression tests
  2146. describe = UtilityWithHerald(
  2147. 'Run normal regression tests for %s...' % rev.strip(),
  2148. 'describe', [], [])
  2149. # Delete all test programs
  2150. test_exes = [str(p) for p in Flatten(testprogs)]
  2151. test_objs = [p + '.o' for p in test_exes]
  2152. testclean = Utility('testclean', [],
  2153. 'rm -f %s' % ' '.join(test_exes + test_objs))
  2154. test_nondaemon = [
  2155. aivdm_regress,
  2156. bits_regress,
  2157. describe,
  2158. float_regress,
  2159. geoid_regress,
  2160. json_regress,
  2161. matrix_regress,
  2162. method_regress,
  2163. misc_regress,
  2164. packet_regress,
  2165. python_compilation_regress,
  2166. python_versions,
  2167. rtcm_regress,
  2168. test_xgps_deps,
  2169. time_regress,
  2170. timespec_regress,
  2171. # trig_regress, # not ready
  2172. unpack_regress,
  2173. ]
  2174. test_quick = test_nondaemon + [gpsfake_tests]
  2175. test_noclean = test_quick + [gps_regress]
  2176. env.Alias('test-nondaemon', test_nondaemon)
  2177. env.Alias('test-quick', test_quick)
  2178. check = env.Alias('check', test_noclean)
  2179. env.Alias('testregress', check)
  2180. env.Alias('build-tests', testprogs)
  2181. build_all = env.Alias('build-all', build + testprogs)
  2182. # Remove all shared-memory segments. Normally only needs to be run
  2183. # when a segment size changes.
  2184. Utility('shmclean', [], ["ipcrm -M 0x4e545030;"
  2185. "ipcrm -M 0x4e545031;"
  2186. "ipcrm -M 0x4e545032;"
  2187. "ipcrm -M 0x4e545033;"
  2188. "ipcrm -M 0x4e545034;"
  2189. "ipcrm -M 0x4e545035;"
  2190. "ipcrm -M 0x4e545036;"
  2191. "ipcrm -M 0x47505345;"
  2192. ])
  2193. # The website directory
  2194. #
  2195. # None of these productions are fired by default.
  2196. # The content they handle is the GPSD website, not included in
  2197. # release tarballs.
  2198. # asciidoc documents
  2199. if env.WhereIs('asciidoc'):
  2200. adocfiles = ['AIVDM',
  2201. 'client-howto',
  2202. 'gpsd-time-service-howto',
  2203. 'NMEA',
  2204. 'ppp-howto',
  2205. 'protocol-evolution',
  2206. 'protocol-transition',
  2207. 'time-service-intro',
  2208. ]
  2209. asciidocs = ["www/" + stem + ".html" for stem in adocfiles] \
  2210. + ["www/installation.html"] + ["www/README.html"]
  2211. for stem in adocfiles:
  2212. env.Command('www/%s.html' % stem, 'www/%s.adoc' % stem,
  2213. ['asciidoc -b html5 -a toc -o www/%s.html www/%s.adoc'
  2214. % (stem, stem)])
  2215. env.Command("www/installation.html",
  2216. "INSTALL.adoc",
  2217. ["asciidoc -o www/installation.html INSTALL.adoc"])
  2218. env.Command("www/README.html",
  2219. "README.adoc",
  2220. ["asciidoc -o www/README.html README.adoc"])
  2221. else:
  2222. announce("Part of the website build requires asciidoc, not installed.")
  2223. asciidocs = []
  2224. # Non-asciidoc webpages only
  2225. htmlpages = Split('''
  2226. www/gps2udp.html
  2227. www/gpscat.html
  2228. www/gpsctl.html
  2229. www/gpsdctl.html
  2230. www/gpsdecode.html
  2231. www/gpsd.html
  2232. www/gpsd_json.html
  2233. www/gpsfake.html
  2234. www/gps.html
  2235. www/gpsinit.html
  2236. www/gpsmon.html
  2237. www/gpspipe.html
  2238. www/gpsprof.html
  2239. www/gpsrinex.html
  2240. www/gpxlogger.html
  2241. www/hardware.html
  2242. www/internals.html
  2243. www/libgps.html
  2244. www/libgpsmm.html
  2245. www/ntpshmmon.html
  2246. www/performance/performance.html
  2247. www/ppscheck.html
  2248. www/replacing-nmea.html
  2249. www/srec.html
  2250. www/ubxtool.html
  2251. www/writing-a-driver.html
  2252. www/zerk.html
  2253. ''')
  2254. webpages = htmlpages + asciidocs + list(map(lambda f: f[:-3],
  2255. glob.glob("www/*.in")))
  2256. www = env.Alias('www', webpages)
  2257. # Paste 'scons --quiet validation-list' to a batch validator such as
  2258. # http://htmlhelp.com/tools/validator/batch.html.en
  2259. def validation_list(target, source, env):
  2260. for page in glob.glob("www/*.html"):
  2261. if '-head' not in page:
  2262. fp = open(page)
  2263. if "Valid HTML" in fp.read():
  2264. print(os.path.join(website, os.path.basename(page)))
  2265. fp.close()
  2266. Utility("validation-list", [www], validation_list)
  2267. # How to update the website. Assumes a logal GitLab pages setup.
  2268. # See .gitlab-ci.yml
  2269. upload_web = Utility("website", [www],
  2270. ['rsync --exclude="*.in" -avz www/ ' +
  2271. os.environ.get('WEBSITE', '.public'),
  2272. 'cp TODO NEWS ' +
  2273. os.environ.get('WEBSITE', '.public')])
  2274. # When the URL declarations change, so must the generated web pages
  2275. for fn in glob.glob("www/*.in"):
  2276. env.Depends(fn[:-3], "SConstruct")
  2277. if htmlbuilder:
  2278. # Manual pages
  2279. for xml in glob.glob("man/*.xml"):
  2280. env.HTML('www/%s.html' % os.path.basename(xml[:-4]), xml)
  2281. # DocBook documents
  2282. for stem in ['writing-a-driver', 'performance/performance',
  2283. 'replacing-nmea']:
  2284. env.HTML('www/%s.html' % stem, 'www/%s.xml' % stem)
  2285. # The internals manual.
  2286. # Doesn't capture dependencies on the subpages
  2287. env.HTML('www/internals.html', '$SRCDIR/doc/internals.xml')
  2288. # The hardware page
  2289. env.Command('www/hardware.html', ['gpscap.py',
  2290. 'www/hardware-head.html',
  2291. 'gpscap.ini',
  2292. 'www/hardware-tail.html'],
  2293. ['(cat www/hardware-head.html && PYTHONIOENCODING=utf-8 '
  2294. '$SC_PYTHON gpscap.py && cat www/hardware-tail.html) '
  2295. '>www/hardware.html'])
  2296. # The diagram editor dia is required in order to edit the diagram masters
  2297. Utility("www/cycle.svg", ["www/cycle.dia"],
  2298. ["dia -e www/cycle.svg www/cycle.dia"])
  2299. # Experimenting with pydoc. Not yet fired by any other productions.
  2300. # scons www/ dies with this
  2301. # # if env['python']:
  2302. # # env.Alias('pydoc', "www/pydoc/index.html")
  2303. # #
  2304. # # # We need to run epydoc with the Python version the modules built for.
  2305. # # # So we define our own epydoc instead of using /usr/bin/epydoc
  2306. # # EPYDOC = "python -c 'from epydoc.cli import cli; cli()'"
  2307. # # env.Command('www/pydoc/index.html', python_progs + glob.glob("*.py")
  2308. # # + glob.glob("gps/*.py"), [
  2309. # # 'mkdir -p www/pydoc',
  2310. # # EPYDOC + " -v --html --graph all -n GPSD $SOURCES -o www/pydoc",
  2311. # # ])
  2312. # Productions for setting up and performing udev tests.
  2313. #
  2314. # Requires root. Do "udev-install", then "tail -f /var/log/syslog" in
  2315. # another window, then run 'scons udev-test', then plug and unplug the
  2316. # GPS ad libitum. All is well when you get fix reports each time a GPS
  2317. # is plugged in.
  2318. #
  2319. # In case you are a systemd user you might also need to watch the
  2320. # journalctl output. Instead of the hotplug script the gpsdctl@.service
  2321. # unit will handle hotplugging together with the udev rules.
  2322. #
  2323. # Note that a udev event can be triggered with an invocation like:
  2324. # udevadm trigger --sysname-match=ttyUSB0 --action add
  2325. if env['systemd']:
  2326. systemdinstall_target = [env.Install(DESTDIR + systemd_dir,
  2327. "systemd/%s" % (x,)) for x in
  2328. ("gpsdctl@.service", "gpsd.service",
  2329. "gpsd.socket")]
  2330. systemd_install = env.Alias('systemd_install', systemdinstall_target)
  2331. systemd_uninstall = env.Command(
  2332. 'systemd_uninstall', '',
  2333. Flatten(Uninstall(Alias("systemd_install"))) or "")
  2334. env.AlwaysBuild(systemd_uninstall)
  2335. env.Precious(systemd_uninstall)
  2336. hotplug_wrapper_install = []
  2337. else:
  2338. hotplug_wrapper_install = [
  2339. 'cp $SRCDIR/gpsd.hotplug ' + DESTDIR + env['udevdir'],
  2340. 'chmod a+x ' + DESTDIR + env['udevdir'] + '/gpsd.hotplug'
  2341. ]
  2342. udev_install = Utility('udev-install', 'install', [
  2343. 'mkdir -p ' + DESTDIR + env['udevdir'] + '/rules.d',
  2344. 'cp $SRCDIR/gpsd.rules ' + DESTDIR + env['udevdir'] +
  2345. '/rules.d/25-gpsd.rules', ] + hotplug_wrapper_install)
  2346. if env['systemd']:
  2347. env.Requires(udev_install, systemd_install)
  2348. if env['systemd'] and not env["sysroot"]:
  2349. systemctl_daemon_reload = Utility('systemctl-daemon-reload', '',
  2350. ['systemctl daemon-reload || true'])
  2351. env.AlwaysBuild(systemctl_daemon_reload)
  2352. env.Precious(systemctl_daemon_reload)
  2353. env.Requires(systemctl_daemon_reload, systemd_install)
  2354. env.Requires(udev_install, systemctl_daemon_reload)
  2355. Utility('udev-uninstall', '', [
  2356. 'rm -f %s/gpsd.hotplug' % env['udevdir'],
  2357. 'rm -f %s/rules.d/25-gpsd.rules' % env['udevdir'],
  2358. ])
  2359. Utility('udev-test', '', ['$SRCDIR/gpsd -N -n -F /var/run/gpsd.sock -D 5', ])
  2360. # Cleanup
  2361. # Dummy target for cleaning misc files
  2362. clean_misc = env.Alias('clean-misc')
  2363. # Since manpage targets are disabled in clean mode, we cover them here
  2364. env.Clean(clean_misc, all_manpages + other_manpages)
  2365. # Clean compiled Python
  2366. env.Clean(clean_misc,
  2367. glob.glob('*.pyc') + glob.glob('gps/*.pyc') +
  2368. glob.glob('gps/*.so') + ['gps/__pycache__'])
  2369. # Clean coverage and profiling files
  2370. env.Clean(clean_misc, glob.glob('*.gcno') + glob.glob('*.gcda'))
  2371. # Clean Python coverage files
  2372. env.Clean(clean_misc, glob.glob('.coverage*') + ['htmlcov/'])
  2373. # Clean Qt stuff
  2374. env.Clean(clean_misc, ['libQgpsmm.prl', 'Qgpsmm.pc'])
  2375. # Clean shared library files
  2376. env.Clean(clean_misc, glob.glob('*.so') + glob.glob('*.so.*'))
  2377. # Clean old location man page files
  2378. env.Clean(clean_misc, glob.glob('*.[0-8]'))
  2379. # Other misc items
  2380. env.Clean(clean_misc, ['config.log', 'contrib/ppscheck', 'contrib/clock_test',
  2381. 'TAGS'])
  2382. # Clean scons state files
  2383. env.Clean(clean_misc, ['.sconf_temp', '.scons-option-cache', 'config.log'])
  2384. # Nuke scons state files
  2385. sconsclean = Utility("sconsclean", '',
  2386. ["rm -fr .sconf_temp .scons-option-cache config.log"])
  2387. # Default targets
  2388. if cleaning:
  2389. env.Default(build_all, audit, clean_misc)
  2390. announce("You must manually remove {}".format(sconsign_file))
  2391. else:
  2392. env.Default(build)
  2393. # Tags for Emacs and vi
  2394. misc_sources = ['cgps.c',
  2395. 'gps2udp.c',
  2396. 'gpsctl.c',
  2397. 'gpsdctl.c',
  2398. 'gpsdecode.c',
  2399. 'gpspipe.c',
  2400. 'gpxlogger.c',
  2401. 'ntpshmmon.c',
  2402. 'ppscheck.c',
  2403. ]
  2404. sources = libgpsd_sources + libgps_sources + gpsd_sources + gpsmon_sources + \
  2405. misc_sources
  2406. env.Command('TAGS', sources, ['etags ' + " ".join(sources)])
  2407. # Release machinery begins here
  2408. #
  2409. # We need to be in the actual project repo (i.e. not doing a -Y build)
  2410. # for these productions to work.
  2411. if os.path.exists("gpsd.c") and os.path.exists(".gitignore"):
  2412. distfiles = _getoutput(r"git ls-files | grep -v '^www/'").split()
  2413. # for some reason distfiles is now a mix of byte strings and char strings
  2414. distfiles = [polystr(d) for d in distfiles]
  2415. if ".gitignore" in distfiles:
  2416. distfiles.remove(".gitignore")
  2417. distfiles += generated_sources
  2418. distfiles += all_manpages
  2419. if "packaging/rpm/gpsd.spec" not in distfiles:
  2420. distfiles.append("packaging/rpm/gpsd.spec")
  2421. # How to build a zip file.
  2422. # Perversely, if the zip exists, it is modified, not replaced.
  2423. # So delete it first.
  2424. dozip = env.Command('zip', distfiles, [
  2425. 'rm -f gpsd-${VERSION}.zip',
  2426. '@zip -ry gpsd-${VERSION}.zip $SOURCES -x contrib/ais-samples/\\*',
  2427. '@ls -l gpsd-${VERSION}.zip',
  2428. ])
  2429. env.Clean(dozip, ["gpsd-${VERSION}.zip", "packaging/rpm/gpsd.spec"])
  2430. # How to build a tarball.
  2431. # The command assume the non-portable GNU tar extension
  2432. # "--transform", and will thus fail if ${TAR} is not GNU tar.
  2433. # scons in theory has code to cope with this, but in practice this
  2434. # is not working. On BSD-derived systems, install GNU tar and
  2435. # pass TAR=gtar in the environment.
  2436. # make a .tar.gz and a .tar.xz
  2437. dist = env.Command('dist', distfiles, [
  2438. '@${TAR} --transform "s:^:gpsd-${VERSION}/:S" '
  2439. ' -czf gpsd-${VERSION}.tar.gz --exclude contrib/ais-samples $SOURCES',
  2440. '@${TAR} --transform "s:^:gpsd-${VERSION}/:S" '
  2441. ' -cJf gpsd-${VERSION}.tar.xz --exclude contrib/ais-samples $SOURCES',
  2442. '@ls -l gpsd-${VERSION}.tar.gz',
  2443. ])
  2444. env.Clean(dist, ["gpsd-${VERSION}.tar.gz", "packaging/rpm/gpsd.spec"])
  2445. # Make RPM from the specfile in packaging
  2446. Utility('dist-rpm', dist, 'rpmbuild -ta gpsd-${VERSION}.tar.gz')
  2447. # Make sure build-from-tarball works.
  2448. testbuild = Utility('testbuild', [dist], [
  2449. '${TAR} -xzvf gpsd-${VERSION}.tar.gz',
  2450. 'cd gpsd-${VERSION}; scons',
  2451. 'rm -fr gpsd-${VERSION}',
  2452. ])
  2453. releasecheck = env.Alias('releasecheck', [
  2454. testbuild,
  2455. check,
  2456. audit,
  2457. flocktest,
  2458. ])
  2459. # This is how to ship a release to the hosting site.
  2460. # The chmod copes with the fact that scp will give a
  2461. # replacement the permissions of the *original*...
  2462. upload_release = Utility('upload-release', [dist], [
  2463. 'rm -f gpsd-*tar*sig',
  2464. 'gpg -b gpsd-${VERSION}.tar.gz',
  2465. 'gpg -b gpsd-${VERSION}.tar.xz',
  2466. 'chmod ug=rw,o=r gpsd-${VERSION}.tar.*',
  2467. 'scp gpsd-${VERSION}.tar.* ' + scpupload,
  2468. ])
  2469. # How to tag a release
  2470. tag_release = Utility('tag-release', [], [
  2471. 'git tag -s -m "Tagged for external release ${VERSION}" \
  2472. release-${VERSION}'])
  2473. upload_tags = Utility('upload-tags', [], ['git push --tags'])
  2474. # Local release preparation. This production will require Internet access,
  2475. # but it doesn't do any uploads or public repo mods.
  2476. #
  2477. # Note that tag_release has to fire early, otherwise the value of REVISION
  2478. # won't be right when revision.h is generated for the tarball.
  2479. releaseprep = env.Alias("releaseprep",
  2480. [Utility("distclean", [], ["rm -f revision.h"]),
  2481. tag_release,
  2482. dist])
  2483. # Undo local release preparation
  2484. Utility("undoprep", [], ['rm -f gpsd-${VERSION}.tar.gz;',
  2485. 'git tag -d release-${VERSION};'])
  2486. # All a buildup to this.
  2487. env.Alias("release", [releaseprep,
  2488. upload_release,
  2489. upload_tags,
  2490. upload_web])
  2491. # Experimental release mechanics using shipper
  2492. # This will ship a freecode metadata update
  2493. Utility("ship", [dist, "control"],
  2494. ['shipper version=%s | sh -e -x' % gpsd_version])
  2495. # The following sets edit modes for GNU EMACS
  2496. # Local Variables:
  2497. # mode:python
  2498. # End:
  2499. # vim: set expandtab shiftwidth=4