Merge "Merge remote-tracking branch 'origin/master' into notification-service" into...
[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', '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 if ARGUMENTS.get('TEST'):
70         logging_default = False
71 else:
72         release_mode = False
73         if ARGUMENTS.get('RELEASE', True) in ['y', 'yes', 'true', 't', '1', 'on', 'all', True]:
74                 release_mode = True
75         logging_default = (release_mode == False)
76
77
78 ######################################################################
79 # Common build options (release, target os, target arch)
80 ######################################################################
81 targets_disallow_multitransport = ['arduino']
82
83 help_vars = Variables()
84 help_vars.Add(BoolVariable('VERBOSE', 'Show compilation', False))
85 help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
86 help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
87
88
89 help_vars.Add(BoolVariable('WITH_RA', 'Build with Remote Access module', False))
90 help_vars.Add(BoolVariable('WITH_TCP', 'Build with TCP adapter', False))
91 help_vars.Add(ListVariable('WITH_MQ', 'Build with MQ publisher/broker', 'OFF', ['OFF', 'SUB', 'PUB', 'BROKER']))
92 help_vars.Add(BoolVariable('WITH_CLOUD', 'Build including AccountManager class and Cloud Client sample', False))
93 help_vars.Add(ListVariable('RD_MODE', 'Resource Directory build mode', 'CLIENT', ['CLIENT', 'SERVER']))
94
95 help_vars.Add(BoolVariable('SIMULATOR', 'Build with simulator module', False))
96
97 help_vars.Add(BoolVariable('WITH_RA_IBB', 'Build with Remote Access module(workssys)', False))
98
99
100 if target_os in targets_disallow_multitransport:
101         help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'IP', ['BT', 'BLE', 'IP', 'NFC']))
102 else:
103         help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP', 'NFC']))
104
105 help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
106 help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
107 help_vars.Add(EnumVariable('DTLS_WITH_X509', 'DTLS with X.509 support', '0', allowed_values=('0', '1')))
108 help_vars.Add(EnumVariable('TEST', 'Run unit tests', '0', allowed_values=('0', '1')))
109 help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', logging_default))
110 help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
111 help_vars.Add(EnumVariable('ROUTING', 'Enable routing', 'EP', allowed_values=('GW', 'EP')))
112 help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
113 help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device (For Arduino)', device_name, None, None),)
114 help_vars.Add(PathVariable('ANDROID_NDK', 'Android NDK path', None, PathVariable.PathAccept))
115 help_vars.Add(PathVariable('ANDROID_HOME', 'Android SDK path', None, PathVariable.PathAccept))
116 help_vars.Add(PathVariable('ANDROID_GRADLE', 'Gradle binary file', None, PathVariable.PathIsFile))
117
118 AddOption('--prefix',
119                   dest='prefix',
120                   type='string',
121                   nargs=1,
122                   action='store',
123                   metavar='DIR',
124                   help='installation prefix')
125
126 ######################################################################
127 # Platform(build target) specific options: SDK/NDK & toolchain
128 ######################################################################
129 targets_support_cc = ['linux', 'arduino', 'tizen']
130
131 if target_os in targets_support_cc:
132         # Set cross compile toolchain
133         help_vars.Add('TC_PREFIX', "Toolchain prefix (Generally only be required for cross-compiling)", os.environ.get('TC_PREFIX'))
134         help_vars.Add(PathVariable('TC_PATH',
135                         'Toolchain path (Generally only be required for cross-compiling)',
136                         os.environ.get('TC_PATH')))
137
138 if target_os in ['android', 'arduino']: # Android/Arduino always uses GNU compiler regardless of the host
139         env = Environment(variables = help_vars,
140                         tools = ['gnulink', 'gcc', 'g++', 'ar', 'as', 'textfile']
141                         )
142 else:
143         env = Environment(variables = help_vars, tools = ['default', 'textfile'],
144                         TARGET_ARCH = target_arch, TARGET_OS = target_os,
145                         PREFIX = GetOption('prefix'),
146                         LIB_INSTALL_DIR = ARGUMENTS.get('LIB_INSTALL_DIR') #for 64bit build
147                         )
148 Help(help_vars.GenerateHelpText(env))
149
150 tc_set_msg = '''
151 ************************************ Warning **********************************
152 *   Enviornment variable TC_PREFIX/TC_PATH is set. It will change the default *
153 * toolchain, if it isn't what you expect you should unset it, otherwise it may*
154 * cause inexplicable errors.                                                  *
155 *******************************************************************************
156 '''
157 if env.get('VERBOSE') == False:
158         env['CCCOMSTR'] = "Compiling $TARGET"
159         env['SHCCCOMSTR'] = "Compiling $TARGET"
160         env['CXXCOMSTR'] = "Compiling $TARGET"
161         env['SHCXXCOMSTR'] = "Compiling $TARGET"
162         env['LINKCOMSTR'] = "Linking $TARGET"
163         env['SHLINKCOMSTR'] = "Linking $TARGET"
164         env['ARCOMSTR'] = "Archiving $TARGET"
165         env['RANLIBCOMSTR'] = "Indexing Archive $TARGET"
166
167 if target_os in targets_support_cc:
168         prefix = env.get('TC_PREFIX')
169         tc_path = env.get('TC_PATH')
170         if prefix:
171                 env.Replace(CC = prefix + env.get('CC', 'gcc'))
172                 env.Replace(CXX = prefix + env.get('CXX', 'g++'))
173                 env.Replace(AR = prefix + env.get('AR', 'ar'))
174                 env.Replace(AS = prefix + env.get('AS', 'as'))
175                 env.Replace(RANLIB = prefix + env.get('RANLIB', 'ranlib'))
176
177         if tc_path:
178                 env.PrependENVPath('PATH', tc_path)
179                 sys_root = os.path.abspath(tc_path + '/../')
180                 env.AppendUnique(CCFLAGS = ['--sysroot=' + sys_root])
181                 env.AppendUnique(LINKFLAGS = ['--sysroot=' + sys_root])
182
183         if prefix or tc_path:
184                 print tc_set_msg
185
186 # If cross-compiling, honor environment settings for toolchain to avoid picking up native tools
187 if os.environ.get('PKG_CONFIG') != None:
188         env["ENV"]["PKG_CONFIG"] = os.environ.get("PKG_CONFIG")
189 if os.environ.get('PKG_CONFIG_PATH') != None:
190         env["ENV"]["PKG_CONFIG_PATH"] = os.environ.get("PKG_CONFIG_PATH")
191 if os.environ.get('PKG_CONFIG_SYSROOT_DIR') != None:
192         env["ENV"]["PKG_CONFIG_SYSROOT_DIR"] = os.environ.get("PKG_CONFIG_SYSROOT_DIR")
193
194 # Ensure scons be able to change its working directory
195 env.SConscriptChdir(1)
196
197 # Set the source directory and build directory
198 #   Source directory: 'dir'
199 #   Build directory: 'dir'/out/<target_os>/<target_arch>/<release or debug>/
200 #
201 # You can get the directory as following:
202 #   env.get('SRC_DIR')
203 #   env.get('BUILD_DIR')
204
205 def __set_dir(env, dir):
206         if not os.path.exists(dir + '/SConstruct'):
207                 print '''
208 *************************************** Error *********************************
209 * The directory(%s) seems isn't a source code directory, no SConstruct file is
210 * found. *
211 *******************************************************************************
212 ''' % dir
213                 Exit(1)
214
215         if env.get('RELEASE'):
216                 build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
217         else:
218                 build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
219         env.VariantDir(build_dir, dir, duplicate=0)
220
221         env.Replace(BUILD_DIR = build_dir)
222         env.Replace(SRC_DIR = dir)
223
224 def __src_to_obj(env, src, home = ''):
225         obj = env.get('BUILD_DIR') + src.replace(home, '')
226         if env.get('OBJSUFFIX'):
227                 obj += env.get('OBJSUFFIX')
228         return env.Object(obj, src)
229
230 def __install(ienv, targets, name):
231         i_n = ienv.Install(env.get('BUILD_DIR'), targets)
232         Alias(name, i_n)
233         env.AppendUnique(TS = [name])
234
235 def __installlib(ienv, targets, name):
236         user_prefix = env.get('PREFIX')
237         if user_prefix:
238                 user_lib = env.get('LIB_INSTALL_DIR')
239                 if user_lib:
240                         i_n = ienv.Install(user_lib, targets)
241                 else:
242                         i_n = ienv.Install(user_prefix + '/lib', targets)
243                 ienv.Alias("install", i_n)
244         else:
245                 i_n = ienv.Install(env.get('BUILD_DIR'), targets)
246         ienv.Alias("install", i_n)
247
248 def __installbin(ienv, targets, name):
249         user_prefix = env.get('PREFIX')
250         if user_prefix:
251                 i_n = ienv.Install(user_prefix + '/bin', targets)
252                 ienv.Alias("install", i_n)
253
254 def __installheader(ienv, targets, dir, name):
255         user_prefix = env.get('PREFIX')
256         if user_prefix:
257                 i_n = ienv.Install(user_prefix + '/include/' + dir ,targets)
258         else:
259                 i_n = ienv.Install(os.path.join(env.get('BUILD_DIR'), 'include', dir), targets)
260         ienv.Alias("install", i_n)
261
262 def __installpcfile(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 + '/pkgconfig', targets)
268                 else:
269                         i_n = ienv.Install(user_prefix + '/lib/pkgconfig', targets)
270         else:
271                 i_n = ienv.Install(env.get('BUILD_DIR') + 'lib/pkgconfig', targets)
272         ienv.Alias("install", i_n)
273
274 def __append_target(ienv, name, targets = None):
275         if targets:
276                 env.Alias(name, targets)
277         env.AppendUnique(TS = [name])
278
279 def __print_targets(env):
280         Help('''
281 ===============================================================================
282 Targets:\n    ''')
283         for t in env.get('TS'):
284                 Help(t + ' ')
285         Help('''
286 \nDefault all targets will be built. You can specify the target to build:
287
288     $ scons [options] [target]
289 ===============================================================================
290 ''')
291
292 env.AddMethod(__set_dir, 'SetDir')
293 env.AddMethod(__print_targets, 'PrintTargets')
294 env.AddMethod(__src_to_obj, 'SrcToObj')
295 env.AddMethod(__append_target, 'AppendTarget')
296 env.AddMethod(__install, 'InstallTarget')
297 env.AddMethod(__installlib, 'UserInstallTargetLib')
298 env.AddMethod(__installbin, 'UserInstallTargetBin')
299 env.AddMethod(__installheader, 'UserInstallTargetHeader')
300 env.AddMethod(__installpcfile, 'UserInstallTargetPCFile')
301 env.SetDir(env.GetLaunchDir())
302 env['ROOT_DIR']=env.GetLaunchDir()+'/..'
303
304 Export('env')
305
306 ######################################################################
307 # Scons to generate the iotivity.pc file from iotivity.pc.in file
308 ######################################################################
309 pc_file = env.get('SRC_DIR') + '/iotivity.pc.in'
310
311 user_prefix = env.get('PREFIX')
312 user_lib = env.get('LIB_INSTALL_DIR')
313
314 if not user_prefix:
315     user_prefix = env.get('BUILD_DIR').encode('string_escape')
316
317 if not user_lib:
318     user_lib = '$${prefix}/lib'
319
320 defines = []
321 if env.get('LOGGING'):
322     defines.append('-DTB_LOG=1')
323
324 if env.get('ROUTING') == 'GW':
325     defines.append('-DROUTING_GATEWAY=1')
326 elif env.get('ROUTING') == 'EP':
327     defines.append('-DROUTING_EP=1')
328
329 pc_vars = {
330     '\@VERSION\@': project_version,
331     '\@PREFIX\@': user_prefix,
332     '\@EXEC_PREFIX\@': user_prefix,
333     '\@LIB_INSTALL_DIR\@': user_lib,
334     '\@DEFINES\@': " ".join(defines)
335 }
336
337 env.Substfile(pc_file, SUBST_DICT = pc_vars)
338
339 ######################################################################
340 # Link scons to Yocto cross-toolchain ONLY when target_os is yocto
341 ######################################################################
342 if target_os == "yocto":
343     '''
344     This code injects Yocto cross-compilation tools+flags into scons'
345     build environment in order to invoke the relevant tools while
346     performing a build.
347     '''
348     import os.path
349     try:
350         CC = os.environ['CC']
351         target_prefix = CC.split()[0]
352         target_prefix = target_prefix[:len(target_prefix)-3]
353         tools = {"CC" : target_prefix+"gcc",
354                 "CXX" : target_prefix+"g++",
355                 "AS" : target_prefix+"as",
356                 "LD" : target_prefix+"ld",
357                 "GDB" : target_prefix+"gdb",
358                 "STRIP" : target_prefix+"strip",
359                 "RANLIB" : target_prefix+"ranlib",
360                 "OBJCOPY" : target_prefix+"objcopy",
361                 "OBJDUMP" : target_prefix+"objdump",
362                 "AR" : target_prefix+"ar",
363                 "NM" : target_prefix+"nm",
364                 "M4" : "m4",
365                 "STRINGS": target_prefix+"strings"}
366         PATH = os.environ['PATH'].split(os.pathsep)
367         for tool in tools:
368             if tool in os.environ:
369                 for path in PATH:
370                     if os.path.isfile(os.path.join(path, tools[tool])):
371                         env[tool] = os.path.join(path, os.environ[tool])
372                         break
373         env['CROSS_COMPILE'] = target_prefix[:len(target_prefix) - 1]
374         if os.environ['LDFLAGS'] != None:
375             env.AppendUnique(LINKFLAGS = Split(os.environ['LDFLAGS']))
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')