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