yocto: Use tools from sysroot before system PATH
[platform/upstream/iotivity.git] / build_common / SConscript
1 # -*- mode: python; python-indent-offset: 4; indent-tabs-mode: nil -*-
2 ##
3 # This script includes generic build options:
4 #    release/debug, target os, target arch, cross toolchain, build environment etc
5 ##
6 import os
7 import platform
8
9 project_version = '1.2.0'
10
11 # Map of host os and allowed target os (host: allowed target os)
12 host_target_map = {
13                 'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'],
14                 'windows': ['windows', 'android', 'arduino'],
15                 'darwin': ['darwin', 'ios', 'android', 'arduino'],
16                 'msys_nt' :['msys_nt'],
17                 }
18
19 # Map of os and allowed archs (os: allowed archs)
20 os_arch_map = {
21                 'linux': ['x86', 'x86_64', 'arm', 'arm-v7a', 'arm64'],
22                 'tizen': ['x86', 'x86_64', 'arm', 'arm-v7a', 'armeabi-v7a', 'arm64'],
23                 'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
24                 'windows': ['x86', 'amd64', 'arm'],
25                 'msys_nt':['x86', 'x86_64'],
26                 'darwin': ['i386', 'x86_64'],
27                 'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
28                 'arduino': ['avr', 'arm'],
29                 'yocto': ['i586', 'x86_64', 'arm', 'powerpc', 'powerpc64', 'mips', 'mipsel'],
30                 }
31
32 host = platform.system().lower()
33
34 # the host string contains version of windows. 6.3, 6.4, 10.0 which is 8.0, 8.1, and 10 respectively.
35 # Let's canonicalize the msys_nt-XX.X system name by stripping version off.
36 if 'msys_nt' in host:
37         host = 'msys_nt'
38
39 if not host_target_map.has_key(host):
40         print "\nError: Current system (%s) isn't supported\n" % host
41         Exit(1)
42
43 ######################################################################
44 # Get build options (the optins from command line)
45 ######################################################################
46 target_os = ARGUMENTS.get('TARGET_OS', host).lower() # target os
47
48 if target_os not in host_target_map[host]:
49         print "\nError: Unknown target os: %s (Allow values: %s)\n" % (target_os, host_target_map[host])
50         Exit(1)
51
52 if target_os == 'android':
53         default_arch = 'x86'
54 else:
55         default_arch = platform.machine()
56
57 if default_arch not in os_arch_map[target_os]:
58         default_arch = os_arch_map[target_os][0].lower()
59
60 target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # target arch
61
62 # True if binary needs to be installed on board. (Might need root permissions)
63 # set to 'no', 'false' or 0 for only compilation
64 require_upload = ARGUMENTS.get('UPLOAD', False)
65
66 # Get the device name. This name can be used as network display name wherever possible
67 device_name = ARGUMENTS.get('DEVICE_NAME', "OIC-DEVICE")
68
69 default_with_upstream_libcoap = 0
70
71 if ARGUMENTS.get('TEST'):
72         logging_default = False
73 else:
74         release_mode = False
75         if ARGUMENTS.get('RELEASE', True) in ['y', 'yes', 'true', 't', '1', 'on', 'all', True]:
76                 release_mode = True
77         logging_default = (release_mode == False)
78
79
80 ######################################################################
81 # Common build options (release, target os, target arch)
82 ######################################################################
83 targets_disallow_multitransport = ['arduino']
84
85 help_vars = Variables()
86 help_vars.Add(BoolVariable('VERBOSE', 'Show compilation', False))
87 help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
88 help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
89
90
91 help_vars.Add(BoolVariable('WITH_RA', 'Build with Remote Access module', False))
92 help_vars.Add(BoolVariable('WITH_TCP', 'Build with TCP adapter', False))
93 help_vars.Add(BoolVariable('WITH_PROXY', 'Build with CoAP-HTTP Proxy', False))
94 help_vars.Add(ListVariable('WITH_MQ', 'Build with MQ publisher/broker', 'OFF', ['OFF', 'SUB', 'PUB', 'BROKER']))
95 help_vars.Add(BoolVariable('WITH_CLOUD', 'Build including AccountManager class and Cloud Client sample', False))
96 help_vars.Add(ListVariable('RD_MODE', 'Resource Directory build mode', 'CLIENT', ['CLIENT', 'SERVER']))
97
98 help_vars.Add(BoolVariable('SIMULATOR', 'Build with simulator module', False))
99
100 help_vars.Add(BoolVariable('WITH_RA_IBB', 'Build with Remote Access module(workssys)', False))
101
102
103 if target_os in targets_disallow_multitransport:
104         help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'IP', ['BT', 'BLE', 'IP', 'NFC']))
105 else:
106         help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP', 'NFC']))
107
108 help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
109 help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
110 help_vars.Add(EnumVariable('DTLS_WITH_X509', 'DTLS with X.509 support', '0', allowed_values=('0', '1')))
111 help_vars.Add(EnumVariable('TEST', 'Run unit tests', '0', allowed_values=('0', '1')))
112 help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', logging_default))
113 help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
114 help_vars.Add(EnumVariable('ROUTING', 'Enable routing', 'EP', allowed_values=('GW', 'EP')))
115 help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
116 help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device (For Arduino)', device_name, None, None),)
117 help_vars.Add(PathVariable('ANDROID_NDK', 'Android NDK path', None, PathVariable.PathAccept))
118 help_vars.Add(PathVariable('ANDROID_HOME', 'Android SDK path', None, PathVariable.PathAccept))
119 help_vars.Add(PathVariable('ANDROID_GRADLE', 'Gradle binary file', None, PathVariable.PathIsFile))
120 help_vars.Add(EnumVariable('WITH_UPSTREAM_LIBCOAP', 'Use latest stable version of LibCoAP downloaded from github', default_with_upstream_libcoap, allowed_values=('0','1')))
121
122 AddOption('--prefix',
123                   dest='prefix',
124                   type='string',
125                   nargs=1,
126                   action='store',
127                   metavar='DIR',
128                   help='installation prefix')
129
130 ######################################################################
131 # Platform(build target) specific options: SDK/NDK & toolchain
132 ######################################################################
133 targets_support_cc = ['linux', 'arduino', 'tizen']
134
135 if target_os in targets_support_cc:
136         # Set cross compile toolchain
137         help_vars.Add('TC_PREFIX', "Toolchain prefix (Generally only be required for cross-compiling)", os.environ.get('TC_PREFIX'))
138         help_vars.Add(PathVariable('TC_PATH',
139                         'Toolchain path (Generally only be required for cross-compiling)',
140                         os.environ.get('TC_PATH')))
141
142 if target_os in ['android', 'arduino']: # Android/Arduino always uses GNU compiler regardless of the host
143         env = Environment(variables = help_vars,
144                         tools = ['gnulink', 'gcc', 'g++', 'ar', 'as', 'textfile']
145                         )
146 else:
147         env = Environment(variables = help_vars, tools = ['default', 'textfile'],
148                         TARGET_ARCH = target_arch, TARGET_OS = target_os,
149                         PREFIX = GetOption('prefix'),
150                         LIB_INSTALL_DIR = ARGUMENTS.get('LIB_INSTALL_DIR') #for 64bit build
151                         )
152 Help(help_vars.GenerateHelpText(env))
153
154 tc_set_msg = '''
155 ************************************ Warning **********************************
156 *   Enviornment variable TC_PREFIX/TC_PATH is set. It will change the default *
157 * toolchain, if it isn't what you expect you should unset it, otherwise it may*
158 * cause inexplicable errors.                                                  *
159 *******************************************************************************
160 '''
161 if env.get('VERBOSE') == False:
162         env['CCCOMSTR'] = "Compiling $TARGET"
163         env['SHCCCOMSTR'] = "Compiling $TARGET"
164         env['CXXCOMSTR'] = "Compiling $TARGET"
165         env['SHCXXCOMSTR'] = "Compiling $TARGET"
166         env['LINKCOMSTR'] = "Linking $TARGET"
167         env['SHLINKCOMSTR'] = "Linking $TARGET"
168         env['ARCOMSTR'] = "Archiving $TARGET"
169         env['RANLIBCOMSTR'] = "Indexing Archive $TARGET"
170
171 if target_os in targets_support_cc:
172         prefix = env.get('TC_PREFIX')
173         tc_path = env.get('TC_PATH')
174         if prefix:
175                 env.Replace(CC = prefix + env.get('CC', 'gcc'))
176                 env.Replace(CXX = prefix + env.get('CXX', 'g++'))
177                 env.Replace(AR = prefix + env.get('AR', 'ar'))
178                 env.Replace(AS = prefix + env.get('AS', 'as'))
179                 env.Replace(RANLIB = prefix + env.get('RANLIB', 'ranlib'))
180
181         if tc_path:
182                 env.PrependENVPath('PATH', tc_path)
183                 sys_root = os.path.abspath(tc_path + '/../')
184                 env.AppendUnique(CCFLAGS = ['--sysroot=' + sys_root])
185                 env.AppendUnique(LINKFLAGS = ['--sysroot=' + sys_root])
186
187         if prefix or tc_path:
188                 print tc_set_msg
189
190 # Import env variables only if reproductibility is ensured
191 if target_os in ['yocto']:
192     env['CONFIG_ENVIRONMENT_IMPORT'] = True
193 else:
194     env['CONFIG_ENVIRONMENT_IMPORT'] = False
195
196 if env['CONFIG_ENVIRONMENT_IMPORT'] == True:
197     print "warning: importing some environment variables for OS: %s" % target_os
198     for ev in ['PATH', 'PKG_CONFIG', 'PKG_CONFIG_PATH', 'PKG_CONFIG_SYSROOT_DIR']:
199         if os.environ.get(ev) != None:
200             env['ENV'][ev] = os.environ.get(ev)
201     if os.environ['LDFLAGS'] != None:
202         env.AppendUnique(LINKFLAGS = Split(os.environ['LDFLAGS']))
203
204 # Ensure scons be able to change its working directory
205 env.SConscriptChdir(1)
206
207 # Set the source directory and build directory
208 #   Source directory: 'dir'
209 #   Build directory: 'dir'/out/<target_os>/<target_arch>/<release or debug>/
210 #
211 # You can get the directory as following:
212 #   env.get('SRC_DIR')
213 #   env.get('BUILD_DIR')
214
215 def __set_dir(env, dir):
216         if not os.path.exists(dir + '/SConstruct'):
217                 print '''
218 *************************************** Error *********************************
219 * The directory(%s) seems isn't a source code directory, no SConstruct file is
220 * found. *
221 *******************************************************************************
222 ''' % dir
223                 Exit(1)
224
225         if env.get('RELEASE'):
226                 build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
227         else:
228                 build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
229         env.VariantDir(build_dir, dir, duplicate=0)
230
231         env.Replace(BUILD_DIR = build_dir)
232         env.Replace(SRC_DIR = dir)
233
234 def __src_to_obj(env, src, home = ''):
235         obj = env.get('BUILD_DIR') + src.replace(home, '')
236         if env.get('OBJSUFFIX'):
237                 obj += env.get('OBJSUFFIX')
238         return env.Object(obj, src)
239
240 def __install(ienv, targets, name):
241         i_n = ienv.Install(env.get('BUILD_DIR'), targets)
242         Alias(name, i_n)
243         env.AppendUnique(TS = [name])
244
245 def __installlib(ienv, targets, name):
246         user_prefix = env.get('PREFIX')
247         if user_prefix:
248                 user_lib = env.get('LIB_INSTALL_DIR')
249                 if user_lib:
250                         i_n = ienv.Install(user_lib, targets)
251                 else:
252                         i_n = ienv.Install(user_prefix + '/lib', targets)
253                 ienv.Alias("install", i_n)
254         else:
255                 i_n = ienv.Install(env.get('BUILD_DIR'), targets)
256         ienv.Alias("install", i_n)
257
258 def __installbin(ienv, targets, name):
259         user_prefix = env.get('PREFIX')
260         if user_prefix:
261                 i_n = ienv.Install(user_prefix + '/bin', targets)
262                 ienv.Alias("install", i_n)
263
264 def __installheader(ienv, targets, dir, name):
265         user_prefix = env.get('PREFIX')
266         if user_prefix:
267                 i_n = ienv.Install(user_prefix + '/include/' + dir ,targets)
268         else:
269                 i_n = ienv.Install(os.path.join(env.get('BUILD_DIR'), 'include', dir), targets)
270         ienv.Alias("install", i_n)
271
272 def __installpcfile(ienv, targets, name):
273         user_prefix = env.get('PREFIX')
274         if user_prefix:
275                 user_lib = env.get('LIB_INSTALL_DIR')
276                 if user_lib:
277                         i_n = ienv.Install(user_lib + '/pkgconfig', targets)
278                 else:
279                         i_n = ienv.Install(user_prefix + '/lib/pkgconfig', targets)
280         else:
281                 i_n = ienv.Install(env.get('BUILD_DIR') + 'lib/pkgconfig', targets)
282         ienv.Alias("install", i_n)
283
284 def __append_target(ienv, name, targets = None):
285         if targets:
286                 env.Alias(name, targets)
287         env.AppendUnique(TS = [name])
288
289 def __print_targets(env):
290         Help('''
291 ===============================================================================
292 Targets:\n    ''')
293         for t in env.get('TS'):
294                 Help(t + ' ')
295         Help('''
296 \nDefault all targets will be built. You can specify the target to build:
297
298     $ scons [options] [target]
299 ===============================================================================
300 ''')
301
302 env.AddMethod(__set_dir, 'SetDir')
303 env.AddMethod(__print_targets, 'PrintTargets')
304 env.AddMethod(__src_to_obj, 'SrcToObj')
305 env.AddMethod(__append_target, 'AppendTarget')
306 env.AddMethod(__install, 'InstallTarget')
307 env.AddMethod(__installlib, 'UserInstallTargetLib')
308 env.AddMethod(__installbin, 'UserInstallTargetBin')
309 env.AddMethod(__installheader, 'UserInstallTargetHeader')
310 env.AddMethod(__installpcfile, 'UserInstallTargetPCFile')
311 env.SetDir(env.GetLaunchDir())
312 env['ROOT_DIR']=env.GetLaunchDir()+'/..'
313
314 Export('env')
315
316 ######################################################################
317 # Scons to generate the iotivity.pc file from iotivity.pc.in file
318 ######################################################################
319 pc_file = env.get('SRC_DIR') + '/iotivity.pc.in'
320
321 user_prefix = env.get('PREFIX')
322 user_lib = env.get('LIB_INSTALL_DIR')
323
324 if not user_prefix:
325     user_prefix = env.get('BUILD_DIR').encode('string_escape')
326
327 if not user_lib:
328     user_lib = '$${prefix}/lib'
329
330 defines = []
331 if env.get('LOGGING'):
332     defines.append('-DTB_LOG=1')
333
334 if env.get('ROUTING') == 'GW':
335     defines.append('-DROUTING_GATEWAY=1')
336 elif env.get('ROUTING') == 'EP':
337     defines.append('-DROUTING_EP=1')
338
339 pc_vars = {
340     '\@VERSION\@': project_version,
341     '\@PREFIX\@': user_prefix,
342     '\@EXEC_PREFIX\@': user_prefix,
343     '\@LIB_INSTALL_DIR\@': user_lib,
344     '\@DEFINES\@': " ".join(defines)
345 }
346
347 env.Substfile(pc_file, SUBST_DICT = pc_vars)
348
349 ######################################################################
350 # Link scons to Yocto cross-toolchain ONLY when target_os is yocto
351 ######################################################################
352 if target_os == "yocto":
353     '''
354     This code injects Yocto cross-compilation tools+flags into scons'
355     build environment in order to invoke the relevant tools while
356     performing a build.
357     '''
358     import os.path
359     try:
360         CC = os.environ['CC']
361         target_prefix = CC.split()[0]
362         target_prefix = target_prefix[:len(target_prefix)-3]
363         tools = {"CC" : target_prefix+"gcc",
364                 "CXX" : target_prefix+"g++",
365                 "AS" : target_prefix+"as",
366                 "LD" : target_prefix+"ld",
367                 "GDB" : target_prefix+"gdb",
368                 "STRIP" : target_prefix+"strip",
369                 "RANLIB" : target_prefix+"ranlib",
370                 "OBJCOPY" : target_prefix+"objcopy",
371                 "OBJDUMP" : target_prefix+"objdump",
372                 "AR" : target_prefix+"ar",
373                 "NM" : target_prefix+"nm",
374                 "M4" : "m4",
375                 "STRINGS": target_prefix+"strings"}
376         PATH = os.environ['PATH'].split(os.pathsep)
377         for tool in tools:
378             if tool in os.environ:
379                 for path in PATH:
380                     if os.path.isfile(os.path.join(path, tools[tool])):
381                         env[tool] = os.path.join(path, os.environ[tool])
382                         break
383         env['CROSS_COMPILE'] = target_prefix[:len(target_prefix) - 1]
384     except:
385         print "ERROR in Yocto cross-toolchain environment"
386         Exit(1)
387     '''
388     Now reset TARGET_OS to linux so that all linux specific build configurations
389     hereupon apply for the entirety of the build process.
390     '''
391     env['TARGET_OS'] = 'linux'
392     '''
393     We want to preserve debug symbols to allow BitBake to generate both DEBUG and
394     RELEASE packages for OIC.
395     '''
396     env.AppendUnique(CCFLAGS = ['-g'])
397     '''
398     Additional flags to pass to the Yocto toolchain.
399     '''
400     if env.get('RELEASE'):
401         env.AppendUnique(CPPDEFINES = ['NDEBUG'])
402     if env.get('LOGGING'):
403         env.AppendUnique(CPPDEFINES = ['TB_LOG'])
404     env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__', '_GNU_SOURCE'])
405     env.AppendUnique(CFLAGS = ['-std=gnu99'])
406     env.AppendUnique(CCFLAGS = ['-Wall', '-Wextra', '-fPIC'])
407     env.AppendUnique(LIBS = ['dl', 'pthread', 'uuid'])
408     Export('env')
409 else:
410     '''
411     If target_os is not Yocto, continue with the regular build process
412     '''
413     # Load config of target os
414     env.SConscript(target_os + '/SConscript')
415
416 # Delete the temp files of configuration
417 if env.GetOption('clean'):
418         dir = env.get('SRC_DIR')
419
420         if os.path.exists(dir + '/config.log'):
421                 Execute(Delete(dir + '/config.log'))
422         if os.path.exists(dir + '/.sconsign.dblite'):
423                 Execute(Delete(dir + '/.sconsign.dblite'))
424         if os.path.exists(dir + '/.sconf_temp'):
425                 Execute(Delete(dir + '/.sconf_temp'))
426
427 ######################################################################
428 # Check for PThreads support
429 ######################################################################
430 import iotivityconfig
431 from iotivityconfig import *
432
433 conf = Configure(env,
434         custom_tests =
435         {
436             'CheckPThreadsSupport' : iotivityconfig.check_pthreads
437         } )
438
439 # Identify whether we have pthreads support, which is necessary for
440 # threading and mutexes.  This will set the environment variable
441 # POSIX_SUPPORTED, 1 if it is supported, 0 otherwise
442 conf.CheckPThreadsSupport()
443
444 env = conf.Finish()
445 ######################################################################
446
447 env.SConscript('external_libs.scons')
448 Return('env')