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