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