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