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