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