Fix cross compile link error
[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                 }
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', 'android']
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 if target_os in targets_disallow_multitransport:
81     help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'IP', ['BT', 'BLE', 'IP']))
82 else:
83     help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP']))
84
85 help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
86 help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
87 help_vars.Add(EnumVariable('TEST', 'Run unit tests', '0', allowed_values=('0', '1')))
88 help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', logging_default))
89 help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
90 help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
91 help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device (For Arduino)', device_name, None, None),)
92
93 ######################################################################
94 # Platform(build target) specific options: SDK/NDK & toolchain
95 ######################################################################
96 targets_support_cc = ['linux', 'arduino', 'tizen']
97
98 if target_os in targets_support_cc:
99         # Set cross compile toolchain
100         help_vars.Add('TC_PREFIX', "Toolchain prefix (Generally only be required for cross-compiling)", os.environ.get('TC_PREFIX'))
101         help_vars.Add(PathVariable('TC_PATH',
102                         'Toolchain path (Generally only be required for cross-compiling)',
103                         os.environ.get('TC_PATH')))
104
105 if target_os in ['android', 'arduino']: # Android/Arduino always uses GNU compiler regardless of the host
106         env = Environment(variables = help_vars,
107                         tools = ['gnulink', 'gcc', 'g++', 'ar', 'as']
108                         )
109 else:
110         env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os)
111
112 Help(help_vars.GenerateHelpText(env))
113
114 tc_set_msg = '''
115 ************************************ Warning **********************************
116 *   Enviornment variable TC_PREFIX/TC_PATH is set. It will change the default *
117 * toolchain, if it isn't what you expect you should unset it, otherwise it may*
118 * cause inexplicable errors.                                                  *
119 *******************************************************************************
120 '''
121 if env.get('VERBOSE') == False:
122         env['CCCOMSTR'] = "Compiling $TARGET"
123         env['SHCCCOMSTR'] = "Compiling $TARGET"
124         env['CXXCOMSTR'] = "Compiling $TARGET"
125         env['SHCXXCOMSTR'] = "Compiling $TARGET"
126         env['LINKCOMSTR'] = "Linking $TARGET"
127         env['SHLINKCOMSTR'] = "Linking $TARGET"
128         env['ARCOMSTR'] = "Archiving $TARGET"
129         env['RANLIBCOMSTR'] = "Indexing Archive $TARGET"
130
131 if target_os in targets_support_cc:
132         prefix = env.get('TC_PREFIX')
133         tc_path = env.get('TC_PATH')
134         if prefix:
135                 env.Replace(CC = prefix + env.get('CC', 'gcc'))
136                 env.Replace(CXX = prefix + env.get('CXX', 'g++'))
137                 env.Replace(AR = prefix + env.get('AR', 'ar'))
138                 env.Replace(AS = prefix + env.get('AS', 'as'))
139                 env.Replace(RANLIB = prefix + env.get('RANLIB', 'ranlib'))
140
141         if tc_path:
142                 env.PrependENVPath('PATH', tc_path)
143                 sys_root = os.path.abspath(tc_path + '/../')
144                 env.AppendUnique(CCFLAGS = ['--sysroot=' + sys_root])
145                 env.AppendUnique(LINKFLAGS = ['--sysroot=' + sys_root])
146
147         if prefix or tc_path:
148                 print tc_set_msg
149
150 # Ensure scons be able to change its working directory
151 env.SConscriptChdir(1)
152
153 # Set the source directory and build directory
154 #   Source directory: 'dir'
155 #   Build directory: 'dir'/out/<target_os>/<target_arch>/<release or debug>/
156 #
157 # You can get the directory as following:
158 #   env.get('SRC_DIR')
159 #   env.get('BUILD_DIR')
160
161 def __set_dir(env, dir):
162         if not os.path.exists(dir + '/SConstruct'):
163                 print '''
164 *************************************** Error *********************************
165 * The directory(%s) seems isn't a source code directory, no SConstruct file is
166 * found. *
167 *******************************************************************************
168 ''' % dir
169                 Exit(1)
170
171         if env.get('RELEASE'):
172                 build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/'
173         else:
174                 build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/'
175         env.VariantDir(build_dir, dir, duplicate=0)
176
177         env.Replace(BUILD_DIR = build_dir)
178         env.Replace(SRC_DIR = dir)
179
180 def __src_to_obj(env, src, home = ''):
181         obj = env.get('BUILD_DIR') + src.replace(home, '')
182         if env.get('OBJSUFFIX'):
183                 obj += env.get('OBJSUFFIX')
184         return env.Object(obj, src)
185
186 def __install(ienv, targets, name):
187         i_n = ienv.Install(env.get('BUILD_DIR'), targets)
188         Alias(name, i_n)
189         env.AppendUnique(TS = [name])
190
191 def __append_target(ienv, name, targets = None):
192         if targets:
193                 env.Alias(name, targets)
194         env.AppendUnique(TS = [name])
195
196 def __print_targets(env):
197         Help('''
198 ===============================================================================
199 Targets:\n    ''')
200         for t in env.get('TS'):
201                 Help(t + ' ')
202         Help('''
203 \nDefault all targets will be built. You can specify the target to build:
204
205     $ scons [options] [target]
206 ===============================================================================
207 ''')
208
209 env.AddMethod(__set_dir, 'SetDir')
210 env.AddMethod(__print_targets, 'PrintTargets')
211 env.AddMethod(__src_to_obj, 'SrcToObj')
212 env.AddMethod(__append_target, 'AppendTarget')
213 env.AddMethod(__install, 'InstallTarget')
214 env.SetDir(env.GetLaunchDir())
215 env['ROOT_DIR']=env.GetLaunchDir()+'/..'
216
217 Export('env')
218
219 ######################################################################
220 # Link scons to Yocto cross-toolchain ONLY when target_os is yocto
221 ######################################################################
222 if target_os == "yocto":
223     '''
224     This code injects Yocto cross-compilation tools+flags into scons'
225     build environment in order to invoke the relevant tools while
226     performing a build.
227     '''
228     import os.path
229     try:
230         CC = os.environ['CC']
231         target_prefix = CC.split()[0]
232         target_prefix = target_prefix[:len(target_prefix)-3]
233         tools = {"CC" : target_prefix+"gcc",
234                 "CXX" : target_prefix+"g++",
235                 "AS" : target_prefix+"as",
236                 "LD" : target_prefix+"ld",
237                 "GDB" : target_prefix+"gdb",
238                 "STRIP" : target_prefix+"strip",
239                 "RANLIB" : target_prefix+"ranlib",
240                 "OBJCOPY" : target_prefix+"objcopy",
241                 "OBJDUMP" : target_prefix+"objdump",
242                 "AR" : target_prefix+"ar",
243                 "NM" : target_prefix+"nm",
244                 "M4" : "m4",
245                 "STRINGS": target_prefix+"strings"}
246         PATH = os.environ['PATH'].split(os.pathsep)
247         for tool in tools:
248             if tool in os.environ:
249                 for path in PATH:
250                     if os.path.isfile(os.path.join(path, tools[tool])):
251                         env[tool] = os.path.join(path, os.environ[tool])
252                         break
253         env['CROSS_COMPILE'] = target_prefix[:len(target_prefix) - 1]
254     except:
255         print "ERROR in Yocto cross-toolchain environment"
256         Exit(1)
257     '''
258     Now reset TARGET_OS to linux so that all linux specific build configurations
259     hereupon apply for the entirety of the build process.
260     '''
261     env['TARGET_OS'] = 'linux'
262     '''
263     We want to preserve debug symbols to allow BitBake to generate both DEBUG and
264     RELEASE packages for OIC.
265     '''
266     env.AppendUnique(CCFLAGS = ['-g'])
267     '''
268     Additional flags to pass to the Yocto toolchain.
269     '''
270     if env.get('RELEASE'):
271         env.AppendUnique(CPPDEFINES = ['NDEBUG'])
272     if env.get('LOGGING'):
273         env.AppendUnique(CPPDEFINES = ['TB_LOG'])
274     env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__', '_GNU_SOURCE'])
275     env.AppendUnique(CFLAGS = ['-std=gnu99'])
276     env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
277     env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread'])
278     env.AppendUnique(LIBS = ['uuid'])
279     Export('env')
280 else:
281     '''
282     If target_os is not Yocto, continue with the regular build process
283     '''
284     # Load config of target os
285     env.SConscript(target_os + '/SConscript')
286
287 # Delete the temp files of configuration
288 if env.GetOption('clean'):
289         dir = env.get('SRC_DIR')
290
291         if os.path.exists(dir + '/config.log'):
292                 Execute(Delete(dir + '/config.log'))
293         if os.path.exists(dir + '/.sconsign.dblite'):
294                 Execute(Delete(dir + '/.sconsign.dblite'))
295         if os.path.exists(dir + '/.sconf_temp'):
296                 Execute(Delete(dir + '/.sconf_temp'))
297
298 ######################################################################
299 # Check for PThreads support
300 ######################################################################
301 import iotivityconfig
302 from iotivityconfig import *
303
304 conf = Configure(env,
305         custom_tests =
306         {
307             'CheckPThreadsSupport' : iotivityconfig.check_pthreads
308         } )
309
310 # Identify whether we have pthreads support, which is necessary for
311 # threading and mutexes.  This will set the environment variable
312 # POSIX_SUPPORTED, 1 if it is supported, 0 otherwise
313 conf.CheckPThreadsSupport()
314
315 env = conf.Finish()
316 ######################################################################
317
318 env.SConscript('external_libs.scons')
319 Return('env')