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