[IOT-1089] Change Android build system to accomodate both Android and Generic Java...
[contrib/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                 }
14
15 # Map of os and allowed archs (os: allowed archs)
16 os_arch_map = {
17                 'linux': ['x86', 'x86_64', 'arm', 'arm64'],
18                 'tizen': ['x86', 'x86_64', 'arm', 'arm64', 'armeabi-v7a'],
19                 'android': ['x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'armeabi-v7a-hard', 'arm64-v8a'],
20                 'windows': ['x86', 'amd64', 'arm'],
21                 'winrt': ['arm'],
22                 'darwin': ['i386', 'x86_64'],
23                 'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
24                 'arduino': ['avr', 'arm'],
25                 'yocto': ['i586', 'x86_64', 'arm', 'powerpc', 'powerpc64', 'mips', 'mipsel'],
26                 }
27
28 host = platform.system().lower()
29
30 if not host_target_map.has_key(host):
31         print "\nError: Current system (%s) isn't supported\n" % host
32         Exit(1)
33
34 ######################################################################
35 # Get build options (the optins from command line)
36 ######################################################################
37 target_os = ARGUMENTS.get('TARGET_OS', host).lower() # target os
38
39 if target_os not in host_target_map[host]:
40         print "\nError: Unknown target os: %s (Allow values: %s)\n" % (target_os, host_target_map[host])
41         Exit(1)
42
43 if target_os == 'android':
44         default_arch = 'x86'
45 else:
46         default_arch = platform.machine()
47
48 if default_arch not in os_arch_map[target_os]:
49         default_arch = os_arch_map[target_os][0].lower()
50
51 target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # target arch
52
53 # True if binary needs to be installed on board. (Might need root permissions)
54 # set to 'no', 'false' or 0 for only compilation
55 require_upload = ARGUMENTS.get('UPLOAD', False)
56
57 # Get the device name. This name can be used as network display name wherever possible
58 device_name = ARGUMENTS.get('DEVICE_NAME', "OIC-DEVICE")
59
60 if ARGUMENTS.get('TEST'):
61         logging_default = False
62 else:
63         release_mode = False
64         if ARGUMENTS.get('RELEASE', True) in ['y', 'yes', 'true', 't', '1', 'on', 'all', True]:
65                 release_mode = True
66         logging_default = (release_mode == False)
67
68
69
70 ######################################################################
71 # Common build options (release, target os, target arch)
72 ######################################################################
73 targets_disallow_multitransport = ['arduino']
74
75 help_vars = Variables()
76 help_vars.Add(BoolVariable('VERBOSE', 'Show compilation', False))
77 help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
78 help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
79
80
81 help_vars.Add(BoolVariable('WITH_RA', 'Build with Remote Access module', False))
82 help_vars.Add(BoolVariable('WITH_TCP', 'Build with TCP adapter', False))
83 help_vars.Add(EnumVariable('WITH_RD', 'Build including Resource Directory', '0', allowed_values=('0', '1')))
84 help_vars.Add(BoolVariable('WITH_CLOUD', 'Build including Cloud client sample', False))
85
86 help_vars.Add(BoolVariable('SIMULATOR', 'Build with simulator module', False))
87
88 help_vars.Add(BoolVariable('WITH_RA_IBB', 'Build with Remote Access module(workssys)', False))
89
90
91 if target_os in targets_disallow_multitransport:
92         help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'IP', ['BT', 'BLE', 'IP', 'NFC']))
93 else:
94         help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP', 'NFC']))
95
96 help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
97 help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
98 help_vars.Add(EnumVariable('DTLS_WITH_X509', 'DTLS with X.509 support', '0', allowed_values=('0', '1')))
99 help_vars.Add(EnumVariable('TEST', 'Run unit tests', '0', allowed_values=('0', '1')))
100 help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', logging_default))
101 help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
102 help_vars.Add(EnumVariable('ROUTING', 'Enable routing', 'EP', allowed_values=('GW', 'EP')))
103 help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
104 help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device (For Arduino)', device_name, None, None),)
105 help_vars.Add(PathVariable('ANDROID_NDK', 'Android NDK path', None, PathVariable.PathAccept))
106 help_vars.Add(PathVariable('ANDROID_HOME', 'Android SDK path', None, PathVariable.PathAccept))
107 help_vars.Add(PathVariable('ANDROID_GRADLE', 'Gradle binary file', None, PathVariable.PathIsFile))
108 #ES_TARGET_ENROLLEE is for specifying what is our target enrollee (Arduino or rest of platforms which support Multicast)
109 help_vars.Add(EnumVariable('ES_TARGET_ENROLLEE', 'Target Enrollee', 'arduino', allowed_values=('arduino', 'tizen', 'linux')))
110 #ES_ROLE is for specifying the role (Enrollee or Mediator) for which scons is being executed
111 help_vars.Add(EnumVariable('ES_ROLE', 'Target build mode', 'mediator', allowed_values=('mediator', 'enrollee')))
112 #ES_SOFT_MODE is for specifying MODE (Mode 1 : Enrollee with  Soft AP or Mode 2  : Mediator with Soft AP)
113 help_vars.Add(EnumVariable('ES_SOFTAP_MODE', 'Target build mode', 'ENROLLEE_SOFTAP', allowed_values=('ENROLLEE_SOFTAP', 'MEDIATOR_SOFTAP')))
114
115 help_vars.Add(EnumVariable('BUILD_JAVA', 'Build Java bindings', 'OFF', allowed_values=('ON', 'OFF')))
116 help_vars.Add(PathVariable('JAVA_HOME', 'JDK directory', os.environ.get('JAVA_HOME'), PathVariable.PathAccept))
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 # Ensure scons be able to change its working directory
187 env.SConscriptChdir(1)
188
189 # Set the source directory and build directory
190 #   Source directory: 'dir'
191 #   Build directory: 'dir'/out/<target_os>/<target_arch>/<release or debug>/
192 #
193 # You can get the directory as following:
194 #   env.get('SRC_DIR')
195 #   env.get('BUILD_DIR')
196
197 def __set_dir(env, dir):
198         if not os.path.exists(dir + '/SConstruct'):
199                 print '''
200 *************************************** Error *********************************
201 * The directory(%s) seems isn't a source code directory, no SConstruct file is
202 * found. *
203 *******************************************************************************
204 ''' % dir
205                 Exit(1)
206
207         if env.get('RELEASE'):
208                 build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
209         else:
210                 build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
211         env.VariantDir(build_dir, dir, duplicate=0)
212
213         env.Replace(BUILD_DIR = build_dir)
214         env.Replace(SRC_DIR = dir)
215
216 def __src_to_obj(env, src, home = ''):
217         obj = env.get('BUILD_DIR') + src.replace(home, '')
218         if env.get('OBJSUFFIX'):
219                 obj += env.get('OBJSUFFIX')
220         return env.Object(obj, src)
221
222 def __install(ienv, targets, name):
223         i_n = ienv.Install(env.get('BUILD_DIR'), targets)
224         Alias(name, i_n)
225         env.AppendUnique(TS = [name])
226
227 def __installlib(ienv, targets, name):
228         user_prefix = env.get('PREFIX')
229         if user_prefix:
230                 user_lib = env.get('LIB_INSTALL_DIR')
231                 if user_lib:
232                         i_n = ienv.Install(user_lib, targets)
233                 else:
234                         i_n = ienv.Install(user_prefix + '/lib', targets)
235                 ienv.Alias("install", i_n)
236
237 def __installbin(ienv, targets, name):
238         user_prefix = env.get('PREFIX')
239         if user_prefix:
240                 i_n = ienv.Install(user_prefix + '/bin', targets)
241                 ienv.Alias("install", i_n)
242
243 def __installheader(ienv, targets, dir, name):
244         user_prefix = env.get('PREFIX')
245         if user_prefix:
246                 i_n = ienv.Install(user_prefix + '/include/' + dir ,targets)
247                 ienv.Alias("install", i_n)
248
249 def __installpcfile(ienv, targets, name):
250         user_prefix = env.get('PREFIX')
251         if user_prefix:
252                 user_lib = env.get('LIB_INSTALL_DIR')
253                 if user_lib:
254                         i_n = ienv.Install(user_lib + '/pkgconfig', targets)
255                 else:
256                         i_n = ienv.Install(user_prefix + '/lib/pkgconfig', targets)
257                 ienv.Alias("install", i_n)
258
259 def __append_target(ienv, name, targets = None):
260         if targets:
261                 env.Alias(name, targets)
262         env.AppendUnique(TS = [name])
263
264 def __print_targets(env):
265         Help('''
266 ===============================================================================
267 Targets:\n    ''')
268         for t in env.get('TS'):
269                 Help(t + ' ')
270         Help('''
271 \nDefault all targets will be built. You can specify the target to build:
272
273     $ scons [options] [target]
274 ===============================================================================
275 ''')
276
277 env.AddMethod(__set_dir, 'SetDir')
278 env.AddMethod(__print_targets, 'PrintTargets')
279 env.AddMethod(__src_to_obj, 'SrcToObj')
280 env.AddMethod(__append_target, 'AppendTarget')
281 env.AddMethod(__install, 'InstallTarget')
282 env.AddMethod(__installlib, 'UserInstallTargetLib')
283 env.AddMethod(__installbin, 'UserInstallTargetBin')
284 env.AddMethod(__installheader, 'UserInstallTargetHeader')
285 env.AddMethod(__installpcfile, 'UserInstallTargetPCFile')
286 env.SetDir(env.GetLaunchDir())
287 env['ROOT_DIR']=env.GetLaunchDir()+'/..'
288
289 Export('env')
290
291 ######################################################################
292 # Scons to generate the iotivity.pc file from iotivity.pc.in file
293 ######################################################################
294 pc_file = env.get('SRC_DIR') + '/iotivity.pc.in'
295
296 if env.get('ROUTING') == 'GW':
297         routing_define = 'ROUTING_GATEWAY'
298 elif env.get('ROUTING') == 'EP':
299         routing_define = 'ROUTING_EP'
300
301 user_prefix = env.get('PREFIX')
302 user_lib = env.get('LIB_INSTALL_DIR')
303 if not user_lib:
304         user_lib = '$${prefix}/lib'
305
306 if user_prefix:
307         pc_vars = {'\@PREFIX\@': user_prefix,
308                                 '\@EXEC_PREFIX\@':user_prefix,
309                                 '\@VERSION\@': '1.0.1',
310                                 '\@LIB_INSTALL_DIR\@': user_lib,
311                                 '\@ROUTING_DEFINE\@': routing_define
312                                 }
313 else:
314         pc_vars = {'\@PREFIX\@': env.get('BUILD_DIR'),
315                                 '\@EXEC_PREFIX\@': env.get('BUILD_DIR'),
316                                 '\@VERSION\@': '1.0.1',
317                                 '\@LIB_INSTALL_DIR\@': user_lib,
318                                 '\@ROUTING_DEFINE\@': routing_define
319                                 }
320
321 env.Substfile(pc_file, SUBST_DICT = pc_vars)
322
323 ######################################################################
324 # Link scons to Yocto cross-toolchain ONLY when target_os is yocto
325 ######################################################################
326 if target_os == "yocto":
327     '''
328     This code injects Yocto cross-compilation tools+flags into scons'
329     build environment in order to invoke the relevant tools while
330     performing a build.
331     '''
332     import os.path
333     try:
334         CC = os.environ['CC']
335         target_prefix = CC.split()[0]
336         target_prefix = target_prefix[:len(target_prefix)-3]
337         tools = {"CC" : target_prefix+"gcc",
338                 "CXX" : target_prefix+"g++",
339                 "AS" : target_prefix+"as",
340                 "LD" : target_prefix+"ld",
341                 "GDB" : target_prefix+"gdb",
342                 "STRIP" : target_prefix+"strip",
343                 "RANLIB" : target_prefix+"ranlib",
344                 "OBJCOPY" : target_prefix+"objcopy",
345                 "OBJDUMP" : target_prefix+"objdump",
346                 "AR" : target_prefix+"ar",
347                 "NM" : target_prefix+"nm",
348                 "M4" : "m4",
349                 "STRINGS": target_prefix+"strings"}
350         PATH = os.environ['PATH'].split(os.pathsep)
351         for tool in tools:
352             if tool in os.environ:
353                 for path in PATH:
354                     if os.path.isfile(os.path.join(path, tools[tool])):
355                         env[tool] = os.path.join(path, os.environ[tool])
356                         break
357         env['CROSS_COMPILE'] = target_prefix[:len(target_prefix) - 1]
358     except:
359         print "ERROR in Yocto cross-toolchain environment"
360         Exit(1)
361     '''
362     Now reset TARGET_OS to linux so that all linux specific build configurations
363     hereupon apply for the entirety of the build process.
364     '''
365     env['TARGET_OS'] = 'linux'
366     '''
367     We want to preserve debug symbols to allow BitBake to generate both DEBUG and
368     RELEASE packages for OIC.
369     '''
370     env.AppendUnique(CCFLAGS = ['-g'])
371     '''
372     Additional flags to pass to the Yocto toolchain.
373     '''
374     if env.get('RELEASE'):
375         env.AppendUnique(CPPDEFINES = ['NDEBUG'])
376     if env.get('LOGGING'):
377         env.AppendUnique(CPPDEFINES = ['TB_LOG'])
378     env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__', '_GNU_SOURCE'])
379     env.AppendUnique(CFLAGS = ['-std=gnu99'])
380     env.AppendUnique(CCFLAGS = ['-Wall', '-Wextra', '-fPIC'])
381     env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread'])
382     env.AppendUnique(LIBS = ['uuid'])
383     Export('env')
384 else:
385     '''
386     If target_os is not Yocto, continue with the regular build process
387     '''
388     # Load config of target os
389     env.SConscript(target_os + '/SConscript')
390
391 # Delete the temp files of configuration
392 if env.GetOption('clean'):
393         dir = env.get('SRC_DIR')
394
395         if os.path.exists(dir + '/config.log'):
396                 Execute(Delete(dir + '/config.log'))
397         if os.path.exists(dir + '/.sconsign.dblite'):
398                 Execute(Delete(dir + '/.sconsign.dblite'))
399         if os.path.exists(dir + '/.sconf_temp'):
400                 Execute(Delete(dir + '/.sconf_temp'))
401
402 ######################################################################
403 # Check for PThreads support
404 ######################################################################
405 import iotivityconfig
406 from iotivityconfig import *
407
408 conf = Configure(env,
409         custom_tests =
410         {
411             'CheckPThreadsSupport' : iotivityconfig.check_pthreads
412         } )
413
414 # Identify whether we have pthreads support, which is necessary for
415 # threading and mutexes.  This will set the environment variable
416 # POSIX_SUPPORTED, 1 if it is supported, 0 otherwise
417 conf.CheckPThreadsSupport()
418
419 env = conf.Finish()
420 ######################################################################
421
422 env.SConscript('external_libs.scons')
423 Return('env')