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