Devuan fork of gpsd
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SConstruct 105 KiB

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