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