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.

3346 lines
121 KiB

# scons file. Only meant to be run from SContruct.
# This file is Copyright 2010 by the GPSD project
# SPDX-License-Identifier: BSD-2-clause
# This code runs compatibly under Python 2 and 3.x for x >= 2.
# Preserve this property!
from __future__ import print_function
import ast
import atexit # for atexit.register()
import functools
import glob
import operator
import os
import pickle
import re
# replacement for functions from the commands module, which is deprecated.
import subprocess
import sys
import time
from distutils import sysconfig
import SCons
# scons does not like targets that come and go (if cleaning, if python,
# etc). All targets are needed for proper cleaning. If a target should
# not be built (if not python), then do not include the target in the
# next layer sources.
# scons gets confused by targets that are not a real file (shmclean, etc.).
# Set them Pseudo (like in a Makefile) and use an Alias() for them.
# Facilitate debugging with pdb.
# At pdb startup, the environment is such that setting breakpoints in
# SConstruct requires specifying its full absolute path, which is incovenient.
# Stopping here at an automatic breakpoint makes this easier. Note that this
# code has no effect unless pdb is loaded.
# To use this, run with pdb and continue from the initial pdb prompt.
pdb_module = sys.modules.get('pdb')
if pdb_module:
pass # Breakpoint default file is now SConscript
# gpsd needs Scons version at least 2.3
EnsureSConsVersion(2, 3, 0)
# gpsd needs Python version at least 2.6
EnsurePythonVersion(2, 6)
# By user choice, or due to system-dependent availability, the scons
# executable may be called using names other than plain "scons",
# e.g. "scons-3" on CentOS 8.
scons_executable_name = os.path.basename(sys.argv[0]) or 'scons'
# Have scons rebuild an existing target when the source(s) MD5 changes
# Do not use time to prevent rebuilding when sources, like gpsd_config.h,
# are rebuilt, but with no changes.
# Put .sconsign*dblite and .scons-options-cache in variantdir for
# one-touch cleaning
# support building with various Python versions.
sconsign_file = '.sconsign.{}.dblite'.format(pickle.HIGHEST_PROTOCOL)
SConsignFile(os.getcwd() + os.path.sep + sconsign_file)
# Start by reading configuration variables from the cache
opts = Variables('.scons-option-cache')
# ugly hack from
# handle python2/3 strings
def polystr(o):
if bytes is str: # Python 2
return str(o)
# python 3.
if isinstance(o, str):
return o
if isinstance(o, (bytes, bytearray)):
return str(o, encoding='latin1')
if isinstance(o, int):
return str(o)
raise ValueError
# Helper functions for revision hackery
def GetMtime(file):
"""Get mtime of given file, or 0."""
return os.stat(file).st_mtime
except OSError:
return 0
def FileList(patterns, exclusion=None):
"""Get list of files based on patterns, minus excluded path."""
files = functools.reduce(operator.add, map(glob.glob, patterns), [])
for file in files:
if file.find(exclusion):
return files
# FIXME: replace with TryAction()
def _getstatusoutput(cmd, nput=None, shell=True, cwd=None, env=None):
pipe = subprocess.Popen(cmd, shell=shell, cwd=cwd, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(output, errout) = pipe.communicate(input=nput)
status = pipe.returncode
return (status, output)
# Workaround for old SCons bug that couldn't overwrite existing symlinks
# This was fixed in 2.3.2, but we allow 2.3.0 (e.g., on Ubuntu 14)
# In the troublesome versions, we monkey-patch os.symlink to bully it through
standard_os_symlink = os.symlink
def _forced_symlink(source, link_name):
standard_os_symlink(source, link_name)
except OSError:
# Out of paranoia, only do this when the target is a symlink
if os.path.islink(link_name):
standard_os_symlink(source, link_name)
if SCons.__version__ in ['2.3.0', '2.3.1']:
os.symlink = _forced_symlink
# SCons 2.3.0 is also missing the Psuedo method. See the workaround after
# the initial 'env' setup.
# TODO: this list is missing stuff.
# built man pages found in all_manpages
generated_sources = [
generated_www = [
# All installed python programs
# All are templated
python_clients = [
python_progs = python_clients + [
# All man pages. Always build them all.
all_manpages = {
"man/cgps.1": "man/gps.xml",
"man/gegps.1": "man/gps.xml",
"man/gps.1": "man/gps.xml",
"man/gps2udp.1": "man/gps2udp.xml",
"man/gpscsv.1": "man/gpscsv.xml",
"man/gpscat.1": "man/gpscat.xml",
"man/gpsctl.1": "man/gpsctl.xml",
"man/gpsd.8": "man/gpsd.xml",
"man/gpsdctl.8": "man/gpsdctl.xml",
"man/gpsdecode.1": "man/gpsdecode.xml",
"man/gpsd_json.5": "man/gpsd_json.xml",
"man/gpsfake.1": "man/gpsfake.xml",
"man/gpsinit.8": "man/gpsinit.xml",
"man/gpsmon.1": "man/gpsmon.xml",
"man/gpspipe.1": "man/gpspipe.xml",
"man/gpsplot.1": "man/gpsplot.xml",
"man/gpsprof.1": "man/gpsprof.xml",
"man/gpsrinex.1": "man/gpsrinex.xml",
"man/gpssubframe.1": "man/gpssubframe.xml",
"man/gpxlogger.1": "man/gpxlogger.xml",
"man/lcdgps.1": "man/gps.xml",
"man/libgps.3": "man/libgps.xml",
"man/libgpsmm.3": "man/libgpsmm.xml",
"man/libQgpsmm.3": "man/libgpsmm.xml",
"man/ntpshmmon.1": "man/ntpshmmon.xml",
"man/ppscheck.8": "man/ppscheck.xml",
"man/ubxtool.1": "man/ubxtool.xml",
"man/xgps.1": "man/xgps.xml",
"man/xgpsspeed.1": "man/xgps.xml",
"man/zerk.1": "man/zerk.xml",
# doc files to install in share/gpsd/doc
doc_files = [
# doc files to install in share/gpsd/doc
icon_files = [
# gpsd_version, and variantdir, from SConstruct
# Create a fixed-name symlink to the build tree, for scripts and symlinks.
# FIXME: Make this work with Execute()
vdir_parent = os.path.dirname(os.path.abspath(os.path.dirname(variantdir)))
os.symlink(variantdir, os.path.join(vdir_parent, 'buildtmp'))
except OSError:
pass # May already exist
# API (JSON) version
api_version_major = 3
api_version_minor = 14
# client library version
libgps_version_current = 28
libgps_version_revision = 0
libgps_version_age = 0
libgps_version = "%d.%d.%d" % (libgps_version_current, libgps_version_age,
# Release identification ends here
# Hosting information (mainly used for templating web pages) begins here
# Each variable foo has a corresponding @FOO@ expanded in .in files.
# There are no project-dependent URLs or references to the hosting site
# anywhere else in the distribution; preserve this property!
annmail = ""
bugtracker = ""
cgiupload = ""
clonerepo = ""
devmail = ""
download = ""
formserver = ""
gitrepo = ""
ircchan = "irc://"
mailman = ""
mainpage = ""
projectpage = ""
scpupload = ""
sitename = "GPSD"
sitesearch = ""
tiplink = "<a href=''>" \
"leave a remittance at Patreon</a>"
tipwidget = '<p><a href="">' \
'Donate here to support continuing development.</a></p>'
usermail = ""
webform = ""
website = ""
# Hosting information ends here
PYTHON_SYSCONFIG_IMPORT = 'from distutils import sysconfig'
# Utility productions
def Utility(target, source, action, **kwargs):
targ = env.Command(target=target, source=source, action=action, **kwargs)
# why always build? wasteful?
# when gpsdecode is the source this rebuilds the entire daemon!
# env.AlwaysBuild(targ)
# Why precious?
# Is pseudo really needed (didn't used to be)?
# Alias to make name work without variantdir prefix
env.Alias(target, targ)
return targ
def UtilityWithHerald(herald, target, source, action, **kwargs):
if not env.GetOption('silent'):
action = ['@echo "%s"' % herald] + action
return Utility(target=target, source=source, action=action, **kwargs)
# Spawn replacement that suppresses non-error stderr
def filtered_spawn(sh, escape, cmd, args, env):
proc = subprocess.Popen([sh, '-c', ' '.join(args)],
env=env, close_fds=True, stderr=subprocess.PIPE)
_, stderr = proc.communicate()
if proc.returncode:
return proc.returncode
# Build-control options
# guess systemd defaults
systemd_dir = '/lib/systemd/system'
systemd = os.path.exists(systemd_dir)
# Set distribution-specific defaults here
imloads = True
boolopts = (
# GPS protocols
("ashtech", True, "Ashtech support"),
("earthmate", True, "DeLorme EarthMate Zodiac support"),
("evermore", True, "EverMore binary support"),
("fury", True, "Jackson Labs Fury and Firefly support"),
("fv18", True, "San Jose Navigation FV-18 support"),
("garmin", True, "Garmin kernel driver support"),
("garmintxt", True, "Garmin Simple Text support"),
("geostar", True, "Geostar Protocol support"),
("greis", True, "Javad GREIS support"),
("itrax", True, "iTrax hardware support"),
("mtk3301", True, "MTK-3301 support"),
("navcom", True, "Navcom NCT support"),
("nmea0183", True, "NMEA0183 support"),
("nmea2000", True, "NMEA2000/CAN support"),
("oncore", True, "Motorola OnCore chipset support"),
("sirf", True, "SiRF chipset support"),
("skytraq", True, "Skytraq chipset support"),
("superstar2", True, "Novatel SuperStarII chipset support"),
("tnt", True, "True North Technologies support"),
("tripmate", True, "DeLorme TripMate support"),
("tsip", True, "Trimble TSIP support"),
("ublox", True, "u-blox Protocol support"),
# Non-GPS protocols
("aivdm", True, "AIVDM support"),
("gpsclock", True, "GPSClock support"),
("isync", True, "Spectratime iSync LNRClok/GRCLOK support"),
("ntrip", True, "NTRIP support"),
("oceanserver", True, "OceanServer support"),
("passthrough", True, "build support for passing through JSON"),
("rtcm104v2", True, "rtcm104v2 support"),
("rtcm104v3", True, "rtcm104v3 support"),
# Time service
("oscillator", True, "Disciplined oscillator support"),
# Export methods
("dbus_export", True, "enable DBUS export support"),
("shm_export", True, "export via shared memory"),
("socket_export", True, "data export over sockets"),
# Communication
("bluez", True, "BlueZ support for Bluetooth devices"),
("netfeed", True, "build support for handling TCP/IP data sources"),
('usb', True, "libusb support for USB devices"),
# Other daemon options
("control_socket", True, "control socket for hotplug notifications"),
("systemd", systemd, "systemd socket activation"),
# Client-side options
("clientdebug", True, "client debugging support"),
("libgpsmm", True, "build C++ bindings"),
("ncurses", True, "build with ncurses"),
("qt", True, "build Qt bindings"),
# Daemon options
("squelch", False, "squelch gpsd_log/gpsd_hexdump to save cpu"),
# Build control
("coveraging", False, "build with code coveraging enabled"),
("debug", False, "add debug information to build, unoptimized"),
("debug_opt", False, "add debug information to build, optimized"),
("gpsdclients", True, "gspd client programs"),
("gpsd", True, "gpsd itself"),
("implicit_link", imloads, "implicit linkage is supported in shared libs"),
("magic_hat", sys.platform.startswith('linux'),
"special Linux PPS hack for Raspberry Pi et al"),
("manbuild", True, "build help in man and HTML formats"),
("minimal", False, "turn off every option not set on the command line"),
("nostrip", False, "don't symbol-strip binaries at link time"),
("profiling", False, "build with profiling enabled"),
("python", True, "build Python support and modules."),
("shared", True, "build shared libraries, not static"),
("timeservice", False, "time-service configuration"),
("xgps", True, "include xgps and xgpsspeed."),
# Test control
("slow", False, "run tests with realistic (slow) delays"),
# now step on the boolopts just read from '.scons-option-cache'
# Otherwise if no cache, then no boolopts.
for (name, default, helpd) in boolopts:
opts.Add(BoolVariable(name, helpd, default))
def_target_python = "python"
def_python_shebang = "/usr/bin/env %s" % def_target_python
# Gentoo, Fedora, openSUSE systems use uucp for ttyS* and ttyUSB*
if os.path.exists("/etc/gentoo-release"):
def_group = "uucp"
def_group = "dialout"
# darwin and BSDs do not have /run, maybe others.
if os.path.exists("/run"):
rundir = "/run"
rundir = "/var/run"
nonboolopts = (
("gpsd_group", def_group, "privilege revocation group"),
("gpsd_user", "nobody", "privilege revocation user",),
("max_clients", '64', "maximum allowed clients"),
("max_devices", '4', "maximum allowed devices"),
("prefix", "/usr/local", "installation directory prefix"),
("python_coverage", "coverage run", "coverage command for Python progs"),
("python_libdir", "", "Python module directory prefix"),
("python_shebang", def_python_shebang, "Python shebang"),
("qt_versioned", "", "version for versioned Qt"),
("release", "", "Suffix for gpsd version"),
("rundir", rundir, "Directory for run-time variable data"),
("sysroot", "",
"Logical root directory for headers and libraries.\n"
"For cross-compiling, or building with multiple local toolchains.\n"
"See gcc and ld man pages for more details."),
("target", "",
"Prefix to the binary tools to use (gcc, ld, etc.)\n"
"For cross-compiling, or building with multiple local toolchains.\n"
("target_python", def_target_python, "target Python version as command"),
# now step on the non boolopts just read from '.scons-option-cache'
# why?
for (name, default, helpd) in nonboolopts:
opts.Add(name, helpd, default)
pathopts = (
("bindir", "bin", "application binaries directory"),
("docdir", "share/gpsd/doc", "documents directory"),
("icondir", "share/gpsd/icons", "icon directory"),
("includedir", "include", "header file directory"),
("libdir", "lib", "system libraries"),
("mandir", "share/man", "manual pages directory"),
("pkgconfig", "$libdir/pkgconfig", "pkgconfig file directory"),
("sbindir", "sbin", "system binaries directory"),
("sharedir", "share/gpsd", "share directory"),
("sysconfdir", "etc", "system configuration directory"),
("udevdir", "/lib/udev", "udev rules directory"),
("unitdir", systemd_dir, "Directory for systemd unit files"),
# now step on the path options just read from '.scons-option-cache'
for (name, default, helpd) in pathopts:
opts.Add(PathVariable(name, helpd, default, PathVariable.PathAccept))
# Environment creation
import_env = (
# Variables used by programs invoked during the build
"DISPLAY", # Required for dia to run under scons
"GROUPS", # Required by gpg
"HOME", # Required by gpg
"LANG", # To avoid Gtk warnings with Python >=3.7
"LOGNAME", # LOGNAME is required for the flocktest production.
'PATH', # Required for ccache and Coverity scan-build
'CCACHE_DIR', # Required for ccache
'CCACHE_RECACHE', # Required for ccache (probably there are more)
# pkg-config (required for crossbuilds at least, and probably pkgsrc)
# Variables for specific packaging/build systems
"MACOSX_DEPLOYMENT_TARGET", # MacOSX 10.4 (and probably earlier)
'STAGING_DIR', # OpenWRT and CeroWrt
'STAGING_PREFIX', # OpenWRT and CeroWrt
# Variables used in testing
'WRITE_PAD', # So we can test WRITE_PAD values on the fly.
envs = {}
for var in import_env:
if var in os.environ:
envs[var] = os.environ[var]
envs["GPSD_HOME"] = os.getcwd() + os.sep + 'gpsd'
env = Environment(tools=["default", "tar", "textfile"], options=opts, ENV=envs)
# Release identification begins here.
# Actual releases follow the normal X.Y or X.Y.Z scheme. The version
# number in git between releases has the form X.Y~dev, when it is
# expected that X.Y will be the next actual release. As an example,
# when 3.20 is the last release, and 3.20.1 is the expected next
# release, the version in git will be 3.20.1~dev. Note that ~ is used,
# because there is some precedent, ~ is an allowed version number in
# the Debian version rules, and it does not cause confusion with
# whether - separates components of the package name, separates the
# name from the version, or separates version components.
if 'dev' in gpsd_version:
(st, gpsd_revision) = _getstatusoutput('git describe --tags')
if st != 0:
# Only if git describe failed
# Use timestamp from latest relevant file,
# ignoring generated files (../$variantdir)
# from root, not from $variantdir
files = FileList(['../*.c', '../*/*.c', '../*.cpp', '../*/*.cpp',
'../include/*.h', '../*.in', '../*/*.in',
'../SConstruct', '../SConscript'],
'../%s' % variantdir)
timestamps = map(GetMtime, files)
if timestamps:
from datetime import datetime
latest = datetime.fromtimestamp(sorted(timestamps)[-1])
gpsd_revision = '%s-%s' % (gpsd_version, latest.isoformat())
gpsd_revision = gpsd_version # Paranoia
gpsd_revision = gpsd_version
gpsd_revision = polystr(gpsd_revision.strip())
# Distros like to add a suffix to the version. Fedora, and others,
# call it the "rele4ase". It often looks like: r1
if env['release']:
gpsd_revision += "-" + polystr(env['release'])
# SCons 2.3.0 lacks the Pseudo method. If it's missing here, make it a
# dummy and hope for the best.
except AttributeError:
env.Pseudo = lambda x: None
# Minimal build turns off every option not set on the command line,
if ARGUMENTS.get('minimal'):
for (name, default, helpd) in boolopts:
# Ensure gpsd and gpsdclients are always enabled unless explicitly
# turned off.
if ((default is True and
not ARGUMENTS.get(name) and
name not in ("gpsd", "gpsdclients"))):
env[name] = False
# Time-service build = stripped-down with some diagnostic tools
if ARGUMENTS.get('timeservice'):
timerelated = ("gpsd",
"mtk3301", # For the Adafruit HAT
"nmea0183", # For generic hats of unknown type.
"ublox", # For the Uputronics board
for (name, default, helpd) in boolopts:
if ((default is True and
not ARGUMENTS.get(name) and
name not in timerelated)):
env[name] = False
# Many drivers require NMEA0183 - in case we select timeserver/minimal
# followed by one of these.
for driver in ('ashtech',
'tripmate', ):
if env[driver]:
env['nmea0183'] = True
# iSync uses ublox underneath, so we force to enable it
if env['isync']:
env['ublox'] = True
opts.Save('.scons-option-cache', env)
for (name, default, helpd) in pathopts:
env[name] = env.subst(env[name])
env['VERSION'] = gpsd_version
env['SC_PYTHON'] = sys.executable # Path to SCons Python
# Set defaults from environment. Note that scons doesn't cope well
# with multi-word CPPFLAGS/LDFLAGS/SHLINKFLAGS values; you'll have to
# explicitly quote them or (better yet) use the "=" form of GNU option
# settings.
# Scons also uses different internal names than most other build-systems.
# So we rely on MergeFlags/ParseFlags to do the right thing for us.
env['STRIP'] = "strip"
env['PKG_CONFIG'] = "pkg-config"
for i in ["AR", # linker for static libs, usually "ar"
# "LD", # scons does not use LD, usually "ld"
"SHLINK", # linker for shared libs, usually "gcc" or "g++", NOT "ld"
if i in os.environ:
env[i] = os.getenv(i)
for i in ["ARFLAGS",
if i in os.environ:
# Keep scan-build options in the environment
for key, value in os.environ.items():
if key.startswith('CCC_'):
env.Append(ENV={key: value})
# Placeholder so we can kluge together something like VPATH builds.
# $SRCDIR replaces occurrences for $(srcdir) in the autotools build.
# scons can get confused if this is not a full path
# FIXME: could get variantdir from SRCDIR
env['SRCDIR'] = os.getcwd()
# We may need to force slow regression tests to get around race
# conditions in the pty layer, especially on a loaded machine.
if env["slow"]:
env['REGRESSOPTS'] = "-S"
env['REGRESSOPTS'] = ""
if env.GetOption("silent"):
env['REGRESSOPTS'] += " -Q"
def announce(msg, end=False):
if not env.GetOption("silent"):
if end:
# duplicate message at exit
atexit.register(lambda: print(msg))
announce("scons version: %s" % SCons.__version__)
announce("scons is running under Python version: %s" %
".".join(map(str, sys.version_info)))
announce("gpsd version: %s" % polystr(gpsd_revision))
# DESTDIR environment variable means user prefix the installation root.
DESTDIR = os.environ.get('DESTDIR', '')
def installdir(idir, add_destdir=True):
# use os.path.join to handle absolute paths properly.
wrapped = os.path.join(env['prefix'], env[idir])
if add_destdir:
wrapped = os.path.normpath(DESTDIR + os.path.sep + wrapped)
wrapped.replace("/usr/etc", "/etc")
wrapped.replace("/usr/lib/systemd", "/lib/systemd")
return wrapped
# Honor the specified installation prefix in link paths.
if env["sysroot"]:
env.Prepend(LIBPATH=[env["sysroot"] + installdir('libdir',
# Give deheader a way to set compiler flags
if 'MORECFLAGS' in os.environ:
# Don't change CCFLAGS if already set by environment.
if 'CCFLAGS' in os.environ:
announce('Warning: CCFLAGS from environment overriding scons settings')
# Should we build with profiling?
if env['profiling']:
# Should we build with coveraging?
if env['coveraging']:
# Should we build with debug symbols?
if env['debug'] or env['debug_opt']:
# Should we build with optimisation?
if env['debug'] or env['coveraging']:
# Cross-development
devenv = (("ADDR2LINE", "addr2line"),
("AR", "ar"),
("AS", "as"),
("CC", "gcc"),
("CPP", "cpp"),
("CXX", "c++"),
("CXXFILT", "c++filt"),
("GCCBUG", "gccbug"),
("GCOV", "gcov"),
("GPROF", "gprof"),
("GXX", "g++"),
# ("LD", "ld"), # scons does not use LD
("NM", "nm"),
("OBJCOPY", "objcopy"),
("OBJDUMP", "objdump"),
("RANLIB", "ranlib"),
("READELF", "readelf"),
("SIZE", "size"),
("STRINGS", "strings"),
("STRIP", "strip"),
if env['target']:
for (name, toolname) in devenv:
env[name] = env['target'] + '-' + toolname
if env['sysroot']:
env.MergeFlags({"CFLAGS": ["--sysroot=%s" % env['sysroot']]})
env.MergeFlags({"LINKFLAGS": ["--sysroot=%s" % env['sysroot']]})
# Build help
def cmp(a, b):
return (a > b) - (a < b)
# FIXME: include __doc__ in help
Help("""Arguments may be a mixture of switches and targets in any order.
Switches apply to the entire build regardless of where they are in the order.
Important switches include:
prefix=/usr probably what packagers want
Options are cached in a file named .scons-option-cache and persist to later
invocations. The file is editable. Delete it to start fresh. Current option
values can be listed with 'scons -h'.
""" + opts.GenerateHelpText(env, sort=cmp))
# Configuration
def CheckPKG(context, name):
context.Message('Checking pkg-config for %s... ' % name)
ret = context.TryAction('%s --exists \'%s\''
% (context.env['PKG_CONFIG'], name))[0]
return ret
# Stylesheet URLs for making HTML and man pages from DocBook XML.
docbook_url_stem = ''
docbook_man_uri = docbook_url_stem + 'manpages/docbook.xsl'
docbook_html_uri = docbook_url_stem + 'html/docbook.xsl'
def CheckXsltproc(context):
context.Message('Checking that xsltproc can make man pages... ')
# open() happens in variantdir
ofp = open("xmltest.xml", "w")
<refentry id="foo.1">
<refmiscinfo class='date'>9 Aug 2004</refmiscinfo>
<refnamediv id='name'>
<refpurpose>check man page generation from docbook source</refpurpose>
probe = ("xsltproc --encoding UTF-8 --output %s/man/foo.1 --nonet "
"--noout '%s' %s/xmltest.xml" %
(variantdir, docbook_man_uri, variantdir))
(ret, out) = context.TryAction(probe)
# out should be empty, don't bother to test.
# next 3 lines happen in variantdir
if os.path.exists("man/foo.1"):
# don't fail due to missing output file
# scons may return cached result, instead of running the probe
return ret
def CheckTime_t(context):
context.Message('Checking if sizeof(time_t) is 64 bits... ')
ret = context.TryLink("""
#include <time.h>
int main(int argc, char **argv) {
static int test_array[1 - 2 * ((long int) sizeof(time_t) < 8 )];
test_array[0] = 0;
(void) argc; (void) argv;
return 0;
""", '.c')
return ret
def CheckCompilerOption(context, option):
context.Message('Checking if compiler accepts %s... ' % (option,))
old_CFLAGS = context.env['CFLAGS'][:] # Get a *copy* of the old list
ret = context.TryLink("""
int main(int argc, char **argv) {
(void) argc; (void) argv;
return 0;
""", '.c')
if not ret:
return ret
# Check if this compiler is C11 or better
def CheckC11(context):
context.Message('Checking if compiler is C11... ')
ret = context.TryLink("""
#if (__STDC_VERSION__ < 201112L)
#error Not C11
int main(int argc, char **argv) {
(void) argc; (void) argv;
return 0;
""", '.c')
return ret
def GetPythonValue(context, name, imp, expr, brief=False):
"""Get a value from the target python, not the running one."""
context.Message('Checking Python %s... ' % name)
if context.env['target_python']:
command = (context.env['target_python'] + " $SOURCE > $TARGET")
text = "%s; print(%s)" % (imp, expr)
# TryAction returns (1, outputStr), or (0, '') on fail
(status, value) = context.TryAction(command, text, '.py')
# do not disable python because this failed
# maybe testing for newer python feature
# FIXME: this ignores imp
status = 1
value = str(eval(expr))
if 1 == status:
# we could convert to str(), but caching turns it into bytes anyway
value = value.strip()
if brief is True:
context.did_show_result = 1
# return value
return value
def GetLoadPath(context):
context.Message("Getting system load path... ")
cleaning = env.GetOption('clean')
helping = env.GetOption('help')
# Always set up LIBPATH so that cleaning works properly.
# from scons 3.0.5, any changes to env after this, until after
# config.Finish(), will be lost. Use config.env until then.
config = Configure(env, custom_tests={
'CheckC11': CheckC11,
'CheckCompilerOption': CheckCompilerOption,
'CheckPKG': CheckPKG,
'CheckXsltproc': CheckXsltproc,
'CheckTime_t': CheckTime_t,
'GetPythonValue': GetPythonValue,
# Use print, rather than announce, so we see it in -s mode.
print("This system is: %s" % sys.platform)
libgps_flags = []
rtlibs = []
bluezflags = []
confdefs = []
dbusflags = []
htmlbuilder = False
manbuilder = False
ncurseslibs = []
mathlibs = []
xtlibs = []
tiocmiwait = True # For cleaning, which works on any OS
usbflags = []
have_dia = False
have_coverage = False
have_cppcheck = False
have_flake8 = False
have_pycodestyle = False
have_pylint = False
have_scan_build = False
have_tar = False
have_valgrind = False
have_xmllint = False
# skip config part if cleaning or helping.
# per SCons 4.0.1 doc: Section 23.9. Not Configuring When Cleaning Targets
if not cleaning and not helping:
# OS X aliases gcc to clang
# clang accepts -pthread, then warns it is unused.
if not config.CheckCC():
announce("ERROR: CC doesn't work")
if ((config.CheckCompilerOption("-pthread") and
not sys.platform.startswith('darwin'))):
confdefs = ["/* gpsd_config.h generated by scons, do not hand-hack. */\n"]
confdefs.append('#ifndef GPSD_CONFIG_H\n')
confdefs.append('#define VERSION "%s"' % gpsd_version)
confdefs.append('#define REVISION "%s"' % gpsd_revision)
confdefs.append('#define GPSD_PROTO_VERSION_MAJOR %u' % api_version_major)
confdefs.append('#define GPSD_PROTO_VERSION_MINOR %u' % api_version_minor)
confdefs.append('#define GPSD_URL "%s"\n' % website)
# TODO: Move these into an if block only on systems with glibc.
# needed for isfinite(), pselect(), etc.
# for strnlen() before glibc 2.10
# glibc 2.10+ needs 200908L (or XOPEN 700+) for strnlen()
# on newer glibc _DEFAULT_SOURCE resets _POSIX_C_SOURCE
# we set it just in case
confdefs.append('#if !defined(_POSIX_C_SOURCE)')
confdefs.append('#define _POSIX_C_SOURCE 200809L')
# for daemon(), cfmakeraw(), strsep() and setgroups()
# on glibc 2.19+
# may also be added by pkg_config
# on linux this eventually sets _USE_XOPEN
confdefs.append('#if !defined(_DEFAULT_SOURCE)')
confdefs.append('#define _DEFAULT_SOURCE')
# sys/un.h, and more, needs __USE_MISC with glibc and osX
# TODO: Many of these are now specified by POSIX. Check if
# defining _XOPEN_SOURCE is necessary, and limit to systems where
# it is.
# 500 means X/Open 1995
# getsid(), isascii(), nice(), putenv(), strdup(), sys/ipc.h need 500
# 600 means X/Open 2004
# Ubuntu and OpenBSD isfinite() needs 600
# 700 means X/Open 2008
# glibc 2.10+ needs 700+ for strnlen()
# Python.h wants 600 or 700
# removed 2 Jul 2019 to see if anything breaks...
# confdefs.append('#if !defined(_XOPEN_SOURCE)')
# confdefs.append('#define _XOPEN_SOURCE 700')
# confdefs.append('#endif\n')
# Reinstated for FreeBSD (below) 16-Aug-2019
if sys.platform.startswith('linux'):
# for cfmakeraw(), strsep(), etc. on CentOS 7
# glibc 2.19 and before
# sets __USE_MISC
confdefs.append('#if !defined(_BSD_SOURCE)')
confdefs.append('#define _BSD_SOURCE')
# for strnlen() and struct ifreq
# glibc before 2.10, deprecated in 2.10+
confdefs.append('#if !defined(_GNU_SOURCE)')
confdefs.append('#define _GNU_SOURCE 1')
elif sys.platform.startswith('darwin'):
# strlcpy() and SIGWINCH need _DARWIN_C_SOURCE
confdefs.append('#if !defined(_DARWIN_C_SOURCE)')
confdefs.append('#define _DARWIN_C_SOURCE 1\n')
# vsnprintf() needs __DARWIN_C_LEVEL >= 200112L
# snprintf() needs __DARWIN_C_LEVEL >= 200112L
# _DARWIN_C_SOURCE forces __DARWIN_C_LEVEL to 900000L
# see <sys/cdefs.h>
# set internal lib versions at link time.
libgps_flags = ["-Wl,-current_version,%s" % libgps_version,
"-Wl,-compatibility_version,%s" % libgps_version,
"-Wl,-install_name,%s/$TARGET.srcpath" %
installdir('libdir', add_destdir=False)]
elif sys.platform.startswith('freebsd'):
# for isascii(), putenv(), nice(), strptime()
confdefs.append('#if !defined(_XOPEN_SOURCE)')
confdefs.append('#define _XOPEN_SOURCE 700')
# required to define u_int in sys/time.h
confdefs.append('#if !defined(_BSD_SOURCE)')
confdefs.append("#define _BSD_SOURCE 1\n")
# required to get strlcpy(), and more, from string.h
confdefs.append('#if !defined(__BSD_VISIBLE)')
confdefs.append("#define __BSD_VISIBLE 1\n")
elif sys.platform.startswith('openbsd'):
# required to define u_int in sys/time.h
confdefs.append('#if !defined(_BSD_SOURCE)')
confdefs.append("#define _BSD_SOURCE 1\n")
# required to get strlcpy(), and more, from string.h
confdefs.append('#if !defined(__BSD_VISIBLE)')
confdefs.append("#define __BSD_VISIBLE 1\n")
elif sys.platform.startswith('netbsd'):
# required to get strlcpy(), and more, from string.h
confdefs.append('#if !defined(_NETBSD_SOURCE)')
confdefs.append("#define _NETBSD_SOURCE 1\n")
elif sys.platform.startswith('sunos5'):
# tested with gcc-5.5 on slowlaris 10
# required to get isascii(), and more, from ctype.h
confdefs.append('#if !defined(__XPG4_CHAR_CLASS__)')
confdefs.append("#define __XPG4_CHAR_CLASS__ 1\n")
confdefs.append('#if !defined(__XPG6)')
confdefs.append('#define _XPG6\n')
# for things like strlcat(), strlcpy)
confdefs.append('#if !defined(__EXTENSIONS__)')
confdefs.append('#define __EXTENSIONS__\n')
cxx = config.CheckCXX()
if not cxx:
announce("C++ doesn't work, suppressing libgpsmm and Qt build.")
config.env["libgpsmm"] = False
config.env["qt"] = False
# define a helper function for pkg-config - we need to pass
# --static for static linking, too.
# Using "--libs-only-L --libs-only-l" instead of "--libs" avoids
# a superfluous "-rpath" option in some FreeBSD cases, and the resulting
# scons crash.
# However, it produces incorrect results for Qt5Network in OSX, so
# it can't be used unconditionally.
def pkg_config(pkg, shared=env['shared'], rpath_hack=False):
libs = '--libs-only-L --libs-only-l' if rpath_hack else '--libs'
if not shared:
libs += ' --static'
return ['!%s --cflags %s %s' % (env['PKG_CONFIG'], libs, pkg)]
# The actual distinction here is whether the platform has ncurses in the
# base system or not. If it does, pkg-config is not likely to tell us
# anything useful. FreeBSD does, Linux doesn't. Most likely other BSDs
# are like FreeBSD.
ncurseslibs = []
if config.env['ncurses']:
if not config.CheckHeader(["curses.h"]):
announce('Turning off ncurses support, curses.h not found.')
config.env['ncurses'] = False
elif config.CheckPKG('ncurses'):
ncurseslibs = pkg_config('ncurses', rpath_hack=True)
if config.CheckPKG('tinfo'):
ncurseslibs += pkg_config('tinfo', rpath_hack=True)
# It's not yet known whether rpath_hack is appropriate for
# ncurses5-config.
elif WhereIs('ncurses5-config'):
ncurseslibs = ['!ncurses5-config --libs --cflags']
elif WhereIs('ncursesw5-config'):
ncurseslibs = ['!ncursesw5-config --libs --cflags']
elif sys.platform.startswith('freebsd'):
ncurseslibs = ['-lncurses']
elif (sys.platform.startswith('darwin') or
sys.platform.startswith('openbsd') or
ncurseslibs = ['-lcurses']
announce('Turning off ncurses support, library not found.')
config.env['ncurses'] = False
if config.env['usb']:
# In FreeBSD except version 7, USB libraries are in the base system
if config.CheckPKG('libusb-1.0'):
confdefs.append("#define HAVE_LIBUSB 1\n")
usbflags = pkg_config('libusb-1.0')
except OSError:
announce("pkg_config is confused about the state "
"of libusb-1.0.")
usbflags = []
elif sys.platform.startswith("freebsd"):
confdefs.append("#define HAVE_LIBUSB 1\n")
usbflags = ["-lusb"]
confdefs.append("/* #undef HAVE_LIBUSB */\n")
usbflags = []
confdefs.append("/* #undef HAVE_LIBUSB */\n")
usbflags = []
config.env["usb"] = False
if config.CheckLib('librt'):
confdefs.append("#define HAVE_LIBRT 1\n")
# System library - no special flags
rtlibs = ["-lrt"]
confdefs.append("/* #undef HAVE_LIBRT */\n")
# for slowlaris socket(), bind(), etc.
if config.CheckLib('libnsl'):
confdefs.append("#define HAVE_LIBNSL\n")
# System library - no special flags
rtlibs += ["-lnsl"]
confdefs.append("/* #undef HAVE_LIBNSL */\n")
# for slowlaris socket(), bind(), etc.
if config.CheckLib('libsocket'):
confdefs.append("#define HAVE_LIBSOCKET\n")
# System library - no special flags
rtlibs += ["-lsocket"]
confdefs.append("/* #undef HAVE_LIBNSOCKET */\n")
# The main reason we check for libm explicitly is to set up the config
# environment for CheckFunc for sincos(). But it doesn't hurt to omit
# the '-lm' when it isn't appropriate.
if config.CheckLib('libm'):
mathlibs = ['-lm']
mathlibs = []
# FreeBSD uses -lthr for pthreads
if config.CheckLib('libthr'):
confdefs.append("#define HAVE_LIBTHR 1\n")
# System library - no special flags
rtlibs += ["-lthr"]
confdefs.append("/* #undef HAVE_LIBTHR */\n")
if config.env['dbus_export'] and config.CheckPKG('dbus-1'):
confdefs.append("#define HAVE_DBUS 1\n")
dbusflags = pkg_config("dbus-1")
confdefs.append("/* #undef HAVE_DBUS */\n")
dbusflags = []
if config.env["dbus_export"]:
announce("Turning off dbus-export support, library not found.")
config.env["dbus_export"] = False
if config.env['bluez'] and config.CheckPKG('bluez'):
confdefs.append("#define ENABLE_BLUEZ 1\n")
bluezflags = pkg_config('bluez')
confdefs.append("/* #undef ENABLE_BLUEZ */\n")
bluezflags = []
if config.env["bluez"]:
announce("Turning off Bluetooth support, library not found.")
config.env["bluez"] = False
# in_port_t is not defined on Android
if not config.CheckType("in_port_t", "#include <netinet/in.h>"):
announce("Did not find in_port_t typedef, assuming unsigned short int")
confdefs.append("typedef unsigned short int in_port_t;\n")
# SUN_LEN is not defined on Android
if ((not config.CheckDeclaration("SUN_LEN", "#include <sys/un.h>") and
not config.CheckDeclaration("SUN_LEN", "#include <linux/un.h>"))):
announce("SUN_LEN is not system-defined, using local definition")
confdefs.append("#ifndef SUN_LEN\n")
confdefs.append("#define SUN_LEN(ptr) "
"((size_t) (((struct sockaddr_un *) 0)->sun_path) "
"+ strlen((ptr)->sun_path))\n")
confdefs.append("#endif /* SUN_LEN */\n")
if config.CheckHeader(["linux/can.h"]):
confdefs.append("#define HAVE_LINUX_CAN_H 1\n")
announce("You have kernel CANbus available.")
confdefs.append("/* #undef HAVE_LINUX_CAN_H */\n")
announce("You do not have kernel CANbus available.")
config.env["nmea2000"] = False
# check for C11 or better, and __STDC__NO_ATOMICS__ is not defined
# before looking for stdatomic.h
if ((config.CheckC11() and
not config.CheckDeclaration("__STDC_NO_ATOMICS__") and
confdefs.append("#define HAVE_STDATOMIC_H 1\n")
confdefs.append("/* #undef HAVE_STDATOMIC_H */\n")
if config.CheckHeader("libkern/OSAtomic.h"):
confdefs.append("#define HAVE_OSATOMIC_H 1\n")
confdefs.append("/* #undef HAVE_OSATOMIC_H */\n")
announce("No memory barriers - SHM export and time hinting "
"may not be reliable.")
# endian.h is required for rtcm104v2 unless the compiler defines
if ((config.CheckDeclaration("__ORDER_BIG_ENDIAN__") and
config.CheckDeclaration("__ORDER_LITTLE_ENDIAN__") and
confdefs.append("#define HAVE_BUILTIN_ENDIANNESS 1\n")
confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
announce("Your compiler has built-in endianness support.")
confdefs.append("/* #undef HAVE_BUILTIN_ENDIANNESS\n */")
if config.CheckHeader("endian.h"):
confdefs.append("#define HAVE_ENDIAN_H 1\n")
confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
confdefs.append("/* #undef HAVE_MACHINE_ENDIAN_H */\n")
elif config.CheckHeader("sys/endian.h"):
confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
confdefs.append("#define HAVE_SYS_ENDIAN_H 1\n")
confdefs.append("/* #undef HAVE_MACHINE_ENDIAN_H */\n")
elif config.CheckHeader("machine/endian.h"):
confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
confdefs.append("#define HAVE_MACHINE_ENDIAN_H 1\n")
confdefs.append("/* #undef HAVE_ENDIAN_H */\n")
confdefs.append("/* #undef HAVE_SYS_ENDIAN_H */\n")
confdefs.append("/* #undef HAVE_MACHINE_ENDIAN_H */\n")
announce("You do not have the endian.h header file. "
"RTCM V2 support disabled.")
config.env["rtcm104v2"] = False
for hdr in ("arpa/inet",
"sys/sysmacros", # for major(), on linux
if config.CheckHeader(hdr + ".h"):
confdefs.append("#define HAVE_%s_H 1\n"
% hdr.replace("/", "_").upper())
elif "termios" == hdr:
announce("ERROR: %s.h not found" % hdr)
confdefs.append("/* #undef HAVE_%s_H */\n"
% hdr.replace("/", "_").upper())
if 0 == config.CheckTime_t():
announce("WARNING: time_t is too small. It will fail in 2038")
sizeof_time_t = 4
sizeof_time_t = 8
confdefs.append("#define SIZEOF_TIME_T %s\n" % sizeof_time_t)
# check function after libraries, because some function require libraries
# for example clock_gettime() require librt on Linux glibc < 2.17
for f in ("cfmakeraw", "clock_gettime", "daemon", "fcntl", "fork",
"gmtime_r", "inet_ntop", "strlcat", "strlcpy", "strptime"):
if config.CheckFunc(f):
confdefs.append("#define HAVE_%s 1\n" % f.upper())
confdefs.append("/* #undef HAVE_%s */\n" % f.upper())
# Apple may supply sincos() as __sincos(), or not at all
if config.CheckFunc('sincos'):
confdefs.append('#define HAVE_SINCOS\n')
elif config.CheckFunc('__sincos'):
confdefs.append('#define sincos __sincos\n#define HAVE_SINCOS\n')
confdefs.append('/* #undef HAVE_SINCOS */\n')
if config.CheckHeader(["sys/types.h", "sys/time.h", "sys/timepps.h"]):
confdefs.append("#define HAVE_SYS_TIMEPPS_H 1\n")
kpps = True
kpps = False
if config.env["magic_hat"]:
announce("Forcing magic_hat=no since RFC2783 API is unavailable")
config.env["magic_hat"] = False
tiocmiwait = config.CheckDeclaration("TIOCMIWAIT",
"#include <sys/ioctl.h>")
if not tiocmiwait and not kpps:
announce("WARNING: Neither TIOCMIWAIT (PPS) nor RFC2783 API (KPPS) "
"is available.", end=True)
if config.env["timeservice"]:
announce("ERROR: timeservice specified, but no PPS available")
# Map options to libraries required to support them that might be absent.
optionrequires = {
"bluez": ["libbluetooth"],
"dbus_export": ["libdbus-1"],
keys = list(map(lambda x: (x[0], x[2]), boolopts)) \
+ list(map(lambda x: (x[0], x[2]), nonboolopts)) \
+ list(map(lambda x: (x[0], x[2]), pathopts))
for (key, helpd) in keys:
value = config.env[key]
if value and key in optionrequires:
for required in optionrequires[key]:
if not config.CheckLib(required):
announce("%s not found, %s cannot be enabled."
% (required, key))
value = False
confdefs.append("/* %s */" % helpd)
if isinstance(value, bool):
if value:
confdefs.append("#define %s_ENABLE 1\n" % key.upper())
confdefs.append("/* #undef %s_ENABLE */\n" % key.upper())
elif value in (0, "", "(undefined)"):
confdefs.append("/* #undef %s */\n" % key.upper())
if value.isdigit():
confdefs.append("#define %s %s\n" % (key.upper(), value))
confdefs.append("#define %s \"%s\"\n" % (key.upper(), value))
# Simplifies life on hackerboards like the Raspberry Pi
if config.env['magic_hat']:
/* Magic device which, if present, means to grab a static /dev/pps0 for KPPS */
#define MAGIC_HAT_GPS "/dev/ttyAMA0"
/* Generic device which, if present, means: */
/* to grab a static /dev/pps0 for KPPS */
#define MAGIC_LINK_GPS "/dev/gpsd0"
#endif /* GPSD_CONFIG_H */
manbuilder = htmlbuilder = None
if config.env['manbuild']:
if config.CheckXsltproc():
build = ("xsltproc --encoding UTF-8 --output $TARGET"
" --nonet %s $SOURCE")
htmlbuilder = build % docbook_html_uri
manbuilder = build % docbook_man_uri
elif WhereIs("xmlto"):
xmlto = "xmlto -o `dirname $TARGET` %s $SOURCE"
htmlbuilder = xmlto % "html-nochunks"
manbuilder = xmlto % "man"
announce("Neither xsltproc nor xmlto found, documentation "
"cannot be built.")
announce("Build of man and HTML documentation is disabled.")
if manbuilder:
# 18.2. Attaching a Builder to a Construction Environment
config.env.Append(BUILDERS={"Man": Builder(action=manbuilder,
config.env.Append(BUILDERS={"HTML": Builder(action=htmlbuilder,
# Determine if Qt network libraries are present, and
# if not, force qt to off
if config.env["qt"]:
qt_net_name = 'Qt%sNetwork' % config.env["qt_versioned"]
qt_network = config.CheckPKG(qt_net_name)
if not qt_network:
config.env["qt"] = False
announce('Turning off Qt support, library not found.')
# If supported by the compiler, enable all warnings except uninitialized
# and missing-field-initializers, which we can't help triggering because
# of the way some of the JSON-parsing code is generated.
# Also not including -Wcast-qual and -Wimplicit-function-declaration,
# because we can't seem to keep scons from passing these to g++.
# Do this after the other config checks, to keep warnings out of them.
for option in ('-Wall',
# -Wimplicit-fallthrough same as
# -Wimplicit-fallthrough=3, except osX hates the
# second flavor
if option not in config.env['CFLAGS']:
# check for misc audit programs
have_coverage = config.CheckProg('coverage')
have_cppcheck = config.CheckProg('cppcheck')
have_dia = config.CheckProg('dia')
have_flake8 = config.CheckProg('flake8')
have_pycodestyle = config.CheckProg('pycodestyle')
have_pylint = config.CheckProg('pylint')
have_scan_build = config.CheckProg('scan-build')
have_tar = config.CheckProg(env['TAR'])
have_valgrind = config.CheckProg('valgrind')
have_xmllint = config.CheckProg('xmllint')
except AttributeError:
# scons versions before Sep 2015 (2.4.0) don't have CheckProg
# gpsd only asks for 2.3.0 or higher
announce("scons CheckProg() failed..")
if not have_coverage:
announce("Program coverage not found -- skipping Python coverage")
if not have_cppcheck:
announce("Program cppcheck not found -- skipping cppcheck checks")
if not have_dia:
announce("Program dia not found -- not rebuiding cycle.svg.")
if not have_flake8:
announce("Program flake8 not found -- skipping flake8 checks")
if not have_pycodestyle:
announce("Program pycodestyle not found -- "
"skipping pycodestyle checks")
if not have_pylint:
announce("Program pylint not found -- skipping pylint checks")
if not have_scan_build:
announce("Program scan-build not found -- skipping scan-build checks")
if not have_tar:
announce('WARNING: %s not found. Can not build tar files.' %
if not have_valgrind:
announce("Program valgrind not found -- skipping valgrind checks")
if not have_xmllint:
announce("Program xmllint not found -- skipping xmllint checks")
# Set up configuration for target Python
PYTHON_LIBDIR_CALL = 'sysconfig.get_python_lib()'
PYTHON_CONFIG_NAMES = ['SO'] # Now a fairly degenerate list
PYTHON_CONFIG_CALL = ('sysconfig.get_config_vars(%s)'
# flag that we have xgps* dependencies, so xgps* should run OK
config.env['xgps_deps'] = False
python_config = {} # Dummy for all non-Python-build cases
target_python_path = ''
py_config_text = str(eval(PYTHON_CONFIG_CALL))
python_libdir = str(eval(PYTHON_LIBDIR_CALL))
config.env['xgps_deps'] = False
if not cleaning and not helping and config.env['python']:
if config.env['target_python']:
except AttributeError:
# scons versions before Nov 2015 (2.4.1) don't have CheckProg
# gpsd only asks for 2.3.0 or higher
target_python_path = config.env['target_python']
target_python_path = config.CheckProg(config.env['target_python'])
if not target_python_path:
announce("Target Python doesn't exist - disabling Python.")
config.env['python'] = False
if config.env['python']:
if not target_python_path:
# Avoid double testing for target_python_path
# Maximize consistency by using the reported sys.executable
target_python_path = config.GetPythonValue('exe path',
'import sys',
target_python_path = polystr(target_python_path)
# python module directory
if config.env['python_libdir']:
python_libdir = config.env['python_libdir']
python_libdir = config.GetPythonValue('lib dir',
# follow FHS, put in /usr/local/libXX, not /usr/libXX
# may be lib, lib32 or lib64
python_libdir = polystr(python_libdir)
python_libdir = python_libdir.replace("/usr/lib",
python_module_dir = str(python_libdir) + os.sep
# Many systems can have a problem with the Python path
if 'PYTHONPATH' in os.environ:
announce("System PYTHONPATH='%s'" % os.environ['PYTHONPATH'])
announce("System PYTHONPATH is empty")
announce("Ensure your PYTHONPATH includes %s" % python_module_dir,
python_module_dir += 'gps'
py_config_text = config.GetPythonValue('config vars',
py_config_text = polystr(py_config_text)
py_config_vars = ast.literal_eval(py_config_text)
py_config_vars = [[] if x is None else x for x in py_config_vars]
python_config = dict(zip(PYTHON_CONFIG_NAMES, py_config_vars))
# debug
# announce(python_config)
# aiogps is only available on Python >= 3.6
sysver = config.GetPythonValue('target version',
'import sys',
'"%d.%d" % sys.version_info[0:2]')
if 3 > int(sysver[0]) or 6 > int(sysver[2]):
config.env['aiogps'] = False
announce("WARNING: Python%s too old (need 3.6): "
"gps/ will not be installed" %
(sysver), end=True)
config.env['aiogps'] = True
# check for pyserial
if not config.GetPythonValue('module serial (pyserial)',
'import serial', '"found"'):
# no pyserial, used by ubxtool and zerk
announce("WARNING: ubxtool and zerk are missing optional "
"runtime module serial", end=True)
config.env['xgps_deps'] = True
# check for pycairo
if not config.GetPythonValue('module cairo (pycairo)',
'import cairo', '"found"'):
# no pycairo, used by xgps, xgpsspeed
config.env['xgps_deps'] = False
announce("WARNING: Python module cairo (pycairo) not found.")
# check for pygobject
if not config.GetPythonValue('module gi (pygobject)',
'import gi', '"found"'):
# no pygobject, used by xgps, xgpsspeed
config.env['xgps_deps'] = False
announce("WARNING: Python module gi (pygobject) not found.")
# gtk+ needed by pygobject
if not config.CheckPKG('gtk+-3.0'):
config.env['xgps_deps'] = False
announce("WARNING: gtk+-3.0 not found.")
if not config.env['xgps_deps']:
announce("WARNING: xgps and xgpsspeed are missing runtime "
"dependencies", end=True)
if not env['xgps']:
# xgps* turned off by option
config.env['xgps_deps'] = False
# check for matplotlib
if not config.GetPythonValue('module matplotlib',
'import matplotlib', '"found"'):
# no matplotlib, used by gpsplot
announce("WARNING: gpsplot is missing required "
"runtime module matplotlib", end=True)
config.env['PYTHON'] = target_python_path
# For regress-driver
config.env['ENV']['PYTHON'] = target_python_path
# get a list of the files from git, so they can go in distribution zip/tar
distfiles = config.TryAction("git ls-files > $TARGET")[1]
distfiles = polystr(distfiles).split()
env = config.Finish()
# All configuration should be finished. env can now be modified.
qt_env = None
if not (cleaning or helping):
# Be explicit about what we're doing.
changelatch = False
for (name, default, helpd) in boolopts + nonboolopts + pathopts:
if env[name] != env.subst(default):
if not changelatch:
announce("Altered configuration variables:")
changelatch = True
announce("%s = %s (default %s): %s"
% (name, env[name], env.subst(default), helpd))
if not changelatch:
announce("All configuration flags are defaulted.")
# Should we build the Qt binding?
if env["qt"] and env["shared"]:
qt_env = env.Clone()
except OSError:
announce("pkg_config is confused about the state of %s."
% qt_net_name)
qt_env = None
# Set up for Python coveraging if needed
pycov_path = None
if have_coverage and env['coveraging'] and env['python_coverage']:
pycov_default = opts.options[opts.keys().index('python_coverage')].default
pycov_current = env['python_coverage']
pycov_list = pycov_current.split()
if env.GetOption('num_jobs') > 1 and pycov_current == pycov_default:
# May need absolute path to coveraging tool if 'PythonXX' is prefixed
pycov_path = env.WhereIs(pycov_list[0])
if pycov_path:
pycov_list[0] = pycov_path
env['PYTHON_COVERAGE'] = ' '.join(pycov_list)
env['ENV']['PYTHON_COVERAGE'] = ' '.join(pycov_list)
env['python_coverage'] = '' # So we see it in the options
# Two shared libraries provide most of the code for the C programs
# gpsd client library
libgps_sources = [
"libgps/gps_maskdump.c", # generated
# Client sources not to be built as C++ when building the Qt library.
libgps_c_only = set([
if env['libgpsmm']:
# gpsd server library
libgpsd_sources = [
# Build ffi binding
packet_ffi_extension = [
if env["shared"]:
def GPSLibrary(env, target, source, version, parse_flags=None):
# Note: We have a possibility of getting either Object or file
# list for sources, so we run through the sources and try to make
# them into SharedObject instances.
obj_list = []
for s in Flatten(source):
if isinstance(s, str):
return env.SharedLibrary(target=target,
def GPSLibraryInstall(env, libdir, source, version):
# note: osX lib name s/b libgps.VV.dylib
# where VV is libgps_version_current
inst = env.InstallVersionedLib(libdir, source, SHLIBVERSION=version)
return inst
def GPSLibrary(env, target, source, version, parse_flags=None):
return env.StaticLibrary(target,
[env.StaticObject(s) for s in source],
def GPSLibraryInstall(env, libdir, source, version):
return env.Install(libdir, source)
libgps_shared = GPSLibrary(env=env,
parse_flags=rtlibs + libgps_flags)
libgps_static = env.StaticLibrary(
source=[env.StaticObject(s) for s in libgps_sources],
libgpsd_static = env.StaticLibrary(
source=[env.StaticObject(s, parse_flags=usbflags + bluezflags)
for s in libgpsd_sources],
parse_flags=usbflags + bluezflags)
# FFI library must always be shared, even with shared=no.
packet_ffi_objects = [env.SharedObject(s) for s in packet_ffi_extension]
packet_ffi_shared = env.SharedLibrary(target="gpsdpacket",
parse_flags=rtlibs + libgps_flags)
libraries = [libgps_shared, packet_ffi_shared]
# Only attempt to create the qt library if we have shared turned on
# otherwise we have a mismash of objects in library
if qt_env:
qtobjects = []
qt_flags = qt_env['CFLAGS']
for c_only in ('-Wmissing-prototypes', '-Wstrict-prototypes',
if c_only in qt_flags:
# Qt binding object files have to be renamed as they're built to avoid
# name clashes with the plain non-Qt object files. This prevents the
# infamous "Two environments with different actions were specified
# for the same target" error.
for src in libgps_sources:
if src not in libgps_c_only:
compile_with = qt_env['CXX']
compile_flags = qt_flags
compile_with = qt_env['CC']
compile_flags = qt_env['CFLAGS']
compiled_qgpsmmlib = GPSLibrary(env=qt_env,
# The libraries have dependencies on system libraries
# libdbus appears multiple times because the linker only does one pass.
gpsflags = mathlibs + rtlibs + dbusflags
gpsdflags = usbflags + bluezflags + gpsflags
# Source groups
gpsd_sources = [
if env['systemd']:
gpsmon_sources = [
# Python dependencies
# For generated dependencies, this causes them to be generated as needed.
# For non-generated dependencies, it causes them to be duplicated into
# the build tree as needed.
# Symlink creator for uplevel access to the 'gps' package
def PylibLink(target, source, env):
_ = source, env
os.symlink('../gps', target[0].get_path())
# Import dependencies
# Update these whenever the imports change
# Internal imports within 'gps' package
env.Depends('gps/', ['gps/', 'gps/'])
env.Depends('gps/', ['gps/', 'gps/', 'gps/'])
env.Depends('gps/', ['gps/', 'gps/'])
['gps/', 'gps/', 'gps/'])
env.Depends('gps/', 'gps/')
env.Depends('gps/', 'gps/')
# All Python programs import the 'gps' package
env.Depends(python_progs, 'gps/')
# Additional specific import cases
env.Depends('clients/gpscat', ['gps/', 'gps/'])
env.Depends('clients/gpsplot', 'gps/')
env.Depends('clients/gpsprof', 'gps/')
env.Depends('clients/ubxtool', 'gps/')
env.Depends('clients/xgps', 'gps/')
env.Depends('clients/xgpsspeed', 'gps/')
env.Depends('clients/zerk', 'gps/')
env.Depends('gpsfake', ['gps/', 'gps/'])
# Symlink for the clients to find the 'gps' package in the build tree
env.Depends(python_clients, env.Command('clients/gps', '', PylibLink))
# Non-import dependencies
# Dependency on program
env.Depends('regress-driver', 'gpsfake')
# Dependency on FFI packet library
env.Depends('gps/', packet_ffi_shared)
# Production programs
gpsd = env.Program('gpsd/gpsd', gpsd_sources,
LIBS=[libgpsd_static, libgps_static],
parse_flags=gpsdflags + gpsflags)
gpsdecode = env.Program('clients/gpsdecode', ['clients/gpsdecode.c'],
LIBS=[libgpsd_static, libgps_static],
parse_flags=gpsdflags + gpsflags)
gpsctl = env.Program('gpsctl', ['gpsctl.c'],
LIBS=[libgpsd_static, libgps_static],
parse_flags=gpsdflags + gpsflags)
# FIXME: gpsmon should not link to gpsd server sources!
gpsmon = env.Program('gpsmon/gpsmon', gpsmon_sources,
LIBS=[libgpsd_static, libgps_static],
parse_flags=gpsdflags + gpsflags + ncurseslibs)
gpsdctl = env.Program('clients/gpsdctl', ['clients/gpsdctl.c'],
gpspipe = env.Program('clients/gpspipe', ['clients/gpspipe.c'],
gpsrinex = env.Program('clients/gpsrinex', ['clients/gpsrinex.c'],
gps2udp = env.Program('clients/gps2udp', ['clients/gps2udp.c'],
gpxlogger = env.Program('clients/gpxlogger', ['clients/gpxlogger.c'],
lcdgps = env.Program('clients/lcdgps', ['clients/lcdgps.c'],
cgps = env.Program('clients/cgps', ['clients/cgps.c'],
parse_flags=gpsflags + ncurseslibs)
ntpshmmon = env.Program('clients/ntpshmmon', ['clients/ntpshmmon.c'],
LIBS=[libgpsd_static, libgps_static],
ppscheck = env.Program('clients/ppscheck', ['clients/ppscheck.c'],
bin_binaries = []
sbin_binaries = []
if env["gpsd"]:
sbin_binaries += [gpsd]
if env["gpsdclients"]:
sbin_binaries += [gpsdctl]
bin_binaries += [
if env["timeservice"] or env["gpsdclients"]:
bin_binaries += [ntpshmmon]
if tiocmiwait:
bin_binaries += [ppscheck]
if env["ncurses"]:
bin_binaries += [cgps, gpsmon]
announce("WARNING: ncurses not found, not building cgps or gpsmon.",
# Test programs - always link locally and statically
test_bits = env.Program('tests/test_bits', ['tests/test_bits.c'],
test_float = env.Program('tests/test_float', ['tests/test_float.c'])
test_geoid = env.Program('tests/test_geoid', ['tests/test_geoid.c'],
LIBS=[libgpsd_static, libgps_static],
test_gpsdclient = env.Program('tests/test_gpsdclient',
LIBS=[libgps_static, 'm'])
test_matrix = env.Program('tests/test_matrix', ['tests/test_matrix.c'],
LIBS=[libgpsd_static, libgps_static],
test_mktime = env.Program('tests/test_mktime', ['tests/test_mktime.c'],
LIBS=[libgps_static], parse_flags=mathlibs + rtlibs)
test_packet = env.Program('tests/test_packet',
LIBS=[libgpsd_static, libgps_static],
test_timespec = env.Program('tests/test_timespec', ['tests/test_timespec.c'],
LIBS=[libgpsd_static, libgps_static],
test_trig = env.Program('tests/test_trig', ['tests/test_trig.c'],
# test_libgps for glibc older than 2.17
test_libgps = env.Program('tests/test_libgps', ['tests/test_libgps.c'],
parse_flags=mathlibs + rtlibs + dbusflags)
if env['socket_export']:
test_json = env.Program(
'tests/test_json', ['tests/test_json.c'],
parse_flags=mathlibs + rtlibs + usbflags + dbusflags)
announce("test_json not building because socket_export is disabled")
test_json = None
# duplicate below?
test_gpsmm = env.Program('tests/test_gpsmm', ['tests/test_gpsmm.cpp'],
parse_flags=mathlibs + rtlibs + dbusflags)
testprogs = [test_bits,
if env['socket_export'] or cleaning:
if env["libgpsmm"] or cleaning:
# Python programs
# python misc helpers and stuff, not to be installed
python_misc = [
# Dependencies for imports in test programs
['gps/', 'gps/', 'gps/'])
env.Depends('tests/', ['gps/', 'gps/'])
env.Depends('', ['gps/', 'gps/'])
# Symlink for the programs to find the 'gps' package in the build tree
env.Depends(['tests/', 'tests/'],
env.Command('tests/gps', '', PylibLink))
# Glob() has to be run after all buildable objects defined
# FIXME: confirm this is true here.
python_modules = Glob('gps/*.py', strings=True) + ['gps/',
# Remove the aiogps module if not configured
# Don't use Glob's exclude option, since it may not be available
if 'aiogps' in env and env['aiogps']:
python_misc.extend(["", "example_aiogps_run"])
except ValueError:
# Make PEP 241 Metadata 1.0.
# Why not PEP 314 (V1.1) or PEP 345 (V1.2)?
# V1.1 and V1.2 require a Download-URL to an installable binary
python_egg_info_source = """Metadata-Version: 1.0
Name: gps
Version: %s
Summary: Python libraries for the gpsd service daemon
Home-page: %s
Author: the GPSD project
Author-email: %s
License: BSD
Keywords: GPS
Description: The gpsd service daemon can monitor one or more GPS devices \
connected to a host computer, making all data on the location and movements \
of the sensors available to be queried on TCP port 2947.
Platform: UNKNOWN
""" % (gpsd_version, website, devmail)
python_egg_info = env.Textfile(target="gps-%s.egg-info" % (gpsd_version, ),
python_targets = ([python_egg_info] + python_progs + python_modules)
env.Command(target="include/packet_names.h", source="include/packet_states.h",
rm -f $TARGET &&\
sed -e '/^ *\\([A-Z][A-Z0-9_]*\\),/s// \"\\1\",/' <$SOURCE >$TARGET &&\
chmod a-w $TARGET""")
env.Textfile(target="include/gpsd_config.h", source=confdefs)
source=["", "include/gps.h", "include/gpsd.h"],
rm -f $TARGET &&\
chmod a-w $TARGET''')
env.Command(target="libgps/ais_json.i", source="libgps/",
rm -f $TARGET &&\
$SC_PYTHON $SOURCE --ais --target=parser >$TARGET &&\
chmod a-w $TARGET''')
if env['systemd']:
udevcommand = 'TAG+="systemd", ENV{SYSTEMD_WANTS}="gpsdctl@%k.service"'
udevcommand = 'RUN+="%s/gpsd.hotplug"' % (env['udevdir'], )
# FIXME: why do this every time scons is called?
# $variantdir may not exist when this is run.
pythonize_header_match = re.compile(r'\s*#define\s+(\w+)\s+(\w+)\s*.*$[^\\]')
pythonized_header = ''
with open(env['SRCDIR'] + '/../include/gpsd.h') as sfp:
for content in sfp:
_match3 = pythonize_header_match.match(content)
if _match3:
if 'LOG' in content or 'PACKET' in content:
pythonized_header += ('%s = %s\n' %
if ((env['python'] and
not cleaning and
not helping and
def_target_python != env['target_python'])):
# non-default target python.
if def_python_shebang == env['python_shebang']:
# default python shebang, update to match target python
if os.sep == env['target_python'][0]:
# full path, no need for env
env['python_shebang'] = env['target_python']
# partial path, need env
env['python_shebang'] = "/usr/bin/env %s" % env['target_python']
announce("Setting python_shebang to %s" % env['python_shebang'])
# tuples for Substfile. To convert .in files to generated files.
substmap = (
('@ANNOUNCE@', annmail),
('@BUGTRACKER@', bugtracker),
('@CGIUPLOAD@', cgiupload),
('@CLONEREPO@', clonerepo),
('@DEVMAIL@', devmail),
('@DOWNLOAD@', download),
('@FORMSERVER@', formserver),
('@GENERATED@', "This code is generated by scons. Do not hand-hack it!"),
('@GITREPO@', gitrepo),
('@GPSAPIVERMAJ@', api_version_major),
('@GPSAPIVERMIN@', api_version_minor),
('@GPSPACKET@', packet_ffi_shared[0].get_path()),
('@ICONPATH@', installdir('icondir', add_destdir=False)),
('@INCLUDEDIR@', installdir('includedir', add_destdir=False)),
('@IRCCHAN@', ircchan),
('@ISSUES@', ''),
('@LIBDIR@', installdir('libdir', add_destdir=False)),
('@LIBGPSVERSION@', libgps_version),
('@MAILMAN@', mailman),
('@MAINPAGE@', mainpage),
('@PREFIX@', env['prefix']),
('@PROJECTPAGE@', projectpage),
# PEP 394 and 397 python shebang
('@PYSHEBANG@', env['python_shebang']),
('@PYPACKETH@', pythonized_header),
('@QTVERSIONED@', env['qt_versioned']),
('@RUNDIR@', env['rundir']),
('@SBINDIR@', installdir('sbindir', add_destdir=False)),
('@SCPUPLOAD@', scpupload),
('@SHAREPATH@', installdir('sharedir', add_destdir=False)),
('@SITENAME@', sitename),
('@SITESEARCH@', sitesearch),
('@SUPPORT@', ''),
('@TIPLINK@', tiplink),
('@TIPWIDGET@', tipwidget),
('@UDEVCOMMAND@', udevcommand),
('@USERMAIL@', usermail),
('@VERSION@', gpsd_version),
('@WEBSITE@', website),
# Keep time-dependent version separate
# FIXME: Come up with a better approach with reproducible builds
substmap_dated = substmap + (('@DATE@', time.asctime()),)
# explicit templated files
templated = {
"android/gpsd_config": "android/",
"clients/gegps": "clients/",
"clients/gpscat": "clients/",
"clients/gpscsv": "clients/",
"clients/gpsd.php": "clients/",
"clients/gpsplot": "clients/",
"clients/gpsprof": "clients/",
"clients/gpssubframe": "clients/",
"clients/ubxtool": "clients/",
"clients/xgps": "clients/",
"clients/xgpsspeed": "clients/",
"clients/zerk": "clients/",
"contrib/ntpshmviz": "contrib/",
"contrib/": "contrib/",
"contrib/webgps": "contrib/",
"control": "",
"gpsd.rules": "",
"gpsfake": "",
"gps/": "gps/",
"gps/": "gps/",
"gps/": "gps/",
"libgps.pc": "",
"libQgpsmm.prl": "",
"packaging/deb/etc_default_gpsd": "packaging/deb/",
"packaging/deb/etc_init.d_gpsd": "packaging/deb/",
"packaging/": "packaging/",
"packaging/rpm/gpsd.init": "packaging/rpm/",
"packaging/rpm/gpsd.spec": "packaging/rpm/",
"packaging/X11/xgps.desktop": "packaging/X11/",
"packaging/X11/xgpsspeed.desktop": "packaging/X11/",
"Qgpsmm.pc": "",
"systemd/gpsdctl@.service": "systemd/",
"systemd/gpsd.service": "systemd/",
"systemd/gpsd.socket": "systemd/",
"www/faq.html": "www/",
"www/gps_report.cgi": "www/",
"www/": "www/",
"www/hacking.html": "www/",
"www/hardware-head.html": "www/",
"www/index.html": "www/",
"www/troubleshooting.html": "www/",
for (tgt, src) in templated.items():
iswww = tgt.startswith('www/')
# Only www pages need @DATE@ expansion, which forces rebuild every time
subst = substmap_dated if iswww else substmap
# use scons built-in Substfile()
builder = env.Substfile(target=tgt, source=src, SUBST_DICT=subst)
# default to building all built targets, except www
# FIXME: Render this unnecessary
if not iswww:
# set read-only to alert people trying to edit the files.
env.AddPostAction(builder, 'chmod -w $TARGET')
if ((src.endswith("") or
tgt in python_progs or
tgt in ['contrib/ntpshmviz', 'contrib/webgps'])):
# set python files to executable
env.AddPostAction(builder, 'chmod +x $TARGET')
# When the URL declarations change, so must the generated web pages
for fn in glob.glob("www/*.in"):
env.Depends(fn[:-3], ["SConstruct", "SConscript"])
man_env = env.Clone()
if man_env.GetOption('silent'):
man_env['SPAWN'] = filtered_spawn # Suppress stderr chatter
manpage_targets = []
if manbuilder:
for (man, xml) in all_manpages.items():
manpage_targets.append(man_env.Man(source=xml, target=man))
# The hardware page