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