2 # Copyright (c) 2012 The Native Client Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 # IMPORTANT NOTE: If you make local mods to this file, you must run:
7 # % pnacl/build.sh driver
8 # in order for them to take effect in the scons build. This command
9 # updates the copy in the toolchain/ tree.
11 # Global environment and expression parsing for the PNaCl driver
14 # This dictionary initializes a shell-like environment.
15 # Shell escaping and ${} substitution are provided.
16 # See "class Environment" defined later for the implementation.
18 from driver_log import Log, DriverExit
19 from shelltools import shell
24 'DRIVER_PATH' : '', # Absolute path to this driver invocation
25 'DRIVER_BIN' : '', # PNaCl driver bin/ directory
26 'DRIVER_REV_FILE' : '${DRIVER_BIN}/REV',
28 'BASE_NACL' : '${@FindBaseNaCl}', # Absolute path of native_client/
29 'BASE_TOOLCHAIN' : '${@FindBaseToolchain}', # Absolute path to toolchain/
30 'BASE' : '${@FindBasePNaCl}', # Absolute path to PNaCl
31 'BUILD_OS' : '${@GetBuildOS}', # "linux", "darwin" or "windows"
32 'BUILD_ARCH' : '${@GetBuildArch}', # "x86_64" or "i686" or "i386"
35 'BPREFIXES' : '', # Prefixes specified using the -B flag.
36 'BASE_LLVM' : '${@FindBaseHost:clang}',
37 'BASE_BINUTILS' : '${@FindBaseHost:le32-nacl-ar}',
39 'BASE_LIB_NATIVE' : '${BASE}/lib-',
41 'BASE_USR' : '${BASE}/usr',
42 'BASE_SDK' : '${BASE}/sdk',
43 'BASE_LIB' : '${BASE}/lib',
44 'BASE_USR_ARCH' : '${BASE_USR_%BCLIB_ARCH%}',
45 'BASE_USR_X8664' : '${BASE}/usr-bc-x86-64',
46 'BASE_LIB_ARCH' : '${BASE_LIB_%BCLIB_ARCH%}',
47 'BASE_LIB_X8664' : '${BASE}/lib-bc-x86-64',
49 'BASE_LLVM_BIN' : '${BASE_LLVM}/bin',
51 '${BASE_TOOLCHAIN}/pnacl_translator/${STANDARD_ARCH}/bin',
53 # TODO(pdox): Unify this with ARCH.
54 'STANDARD_ARCH' : '${STANDARD_ARCH_%ARCH%}',
55 'STANDARD_ARCH_X8632' : 'i686',
56 'STANDARD_ARCH_X8664' : 'x86_64',
57 'STANDARD_ARCH_ARM' : 'armv7',
58 'STANDARD_ARCH_MIPS32': 'mips32',
60 'SCONS_OUT' : '${BASE_NACL}/scons-out',
63 'ARCH' : '', # Target architecture
64 'BIAS' : 'NONE', # This can be 'NONE', 'ARM', 'MIPS32', 'X8632' or
66 # When not set to none, this causes the front-end to
67 # act like a target-specific compiler. This bias is
68 # currently needed while compiling newlib,
69 # and some scons tests.
71 'SAVE_TEMPS' : '0', # Do not clean up temporary files
72 'SANDBOXED' : '0', # Use sandboxed toolchain for this arch. (main switch)
73 'HAS_FRONTEND': '', # Set by ReadConfig(). '1' if the driver install
74 # has support for front-end bitcode tools, or '0'
75 # if it only has the backend translator.
78 'USE_BOOTSTRAP' : '${BUILD_OS==linux ? 1 : 0}',
79 # Args passed from one driver invocation to another
80 'INHERITED_DRIVER_ARGS' : '',
84 'LOG_VERBOSE' : '0', # Log to stdout (--pnacl-driver-verbose)
87 'SO_EXT' : '${SO_EXT_%BUILD_OS%}',
88 'SO_EXT_darwin' : '.dylib',
89 'SO_EXT_linux' : '.so',
90 'SO_EXT_windows' : '.dll',
92 'SO_DIR' : '${SO_DIR_%BUILD_OS%}',
93 'SO_DIR_darwin' : 'lib',
94 'SO_DIR_linux' : 'lib',
95 'SO_DIR_windows' : 'bin', # On Windows, DLLs are placed in bin/
96 # because the dynamic loader searches %PATH%
98 'EXEC_EXT' : '${EXEC_EXT_%BUILD_OS%}',
99 'EXEC_EXT_darwin' : '',
100 'EXEC_EXT_linux' : '',
101 'EXEC_EXT_windows': '.exe',
103 'SCONS_OS' : '${SCONS_OS_%BUILD_OS%}',
104 'SCONS_OS_linux' : 'linux',
105 'SCONS_OS_darwin' : 'mac',
106 'SCONS_OS_windows' : 'win',
109 'GOLD_PLUGIN_SO' : '${BASE_LLVM}/${SO_DIR}/LLVMgold${SO_EXT}',
111 'SCONS_STAGING' : '${SCONS_STAGING_%ARCH%}',
112 'SCONS_STAGING_X8632' : '${SCONS_OUT}/opt-${SCONS_OS}-x86-32/staging',
113 'SCONS_STAGING_X8664' : '${SCONS_OUT}/opt-${SCONS_OS}-x86-64/staging',
114 'SCONS_STAGING_ARM' : '${SCONS_OUT}/opt-${SCONS_OS}-arm/staging',
115 'SCONS_STAGING_MIPS32': '${SCONS_OUT}/opt-${SCONS_OS}-mips32/staging',
117 'SEL_UNIVERSAL_PREFIX': '${USE_EMULATOR ? ${EMULATOR}}',
118 'SEL_UNIVERSAL' : '${SCONS_STAGING}/sel_universal${EXEC_EXT}',
119 # NOTE: -Q skips sel_ldr qualification tests, -c -c skips validation
120 # NOTE: We are not using -B to load the IRT, since the translators do not
122 'SEL_UNIVERSAL_FLAGS' : '--abort_on_error ' +
123 '--uses_reverse_service ' +
124 '${USE_EMULATOR ? -Q -c -c --command_prefix ${EMULATOR}}',
126 'EMULATOR' : '${EMULATOR_%ARCH%}',
127 'EMULATOR_X8632' : '',
128 'EMULATOR_X8664' : '',
129 # NOTE: this is currently the only dependency on the arm trusted TC
131 '${BASE_NACL}/toolchain/linux_arm-trusted/run_under_qemu_arm',
133 '${BASE_NACL}/toolchain/linux_mips-trusted/run_under_qemu_mips32',
135 'SEL_LDR' : '${SCONS_STAGING}/sel_ldr${EXEC_EXT}',
136 'BOOTSTRAP_LDR' : '${SCONS_STAGING}/nacl_helper_bootstrap${EXEC_EXT}',
138 # sandboxed llvm backend
139 'LLC_SB' : '${TRANSLATOR_BIN}/pnacl-llc.nexe',
140 # sandboxed linker (gold based)
141 'LD_SB' : '${TRANSLATOR_BIN}/ld.nexe',
144 'CLANG' : '${BASE_LLVM_BIN}/clang${EXEC_EXT}',
145 # 'clang++' doesn't work on Windows (outside of Cygwin),
146 # because it is a symlink. '-ccc-cxx' enables C++ mode.
147 'CLANGXX' : '${BASE_LLVM_BIN}/clang${EXEC_EXT} -ccc-cxx',
148 'LLVM_OPT' : '${BASE_LLVM_BIN}/opt${EXEC_EXT}',
149 'LLVM_DIS' : '${BASE_LLVM_BIN}/llvm-dis${EXEC_EXT}',
150 'LLVM_NM' : '${BASE_LLVM_BIN}/llvm-nm${EXEC_EXT}',
151 # llvm-as compiles llvm assembly (.ll) to bitcode (.bc/.po)
152 'LLVM_AS' : '${BASE_LLVM_BIN}/llvm-as${EXEC_EXT}',
153 'PNACL_ABICHECK': '${BASE_LLVM_BIN}/pnacl-abicheck${EXEC_EXT}',
154 'PNACL_COMPRESS': '${BASE_LLVM_BIN}/pnacl-bccompress${EXEC_EXT}',
157 'LLVM_PNACL_LLC': '${BASE_LLVM_BIN}/pnacl-llc${EXEC_EXT}',
158 # llvm-mc is llvm's native assembler
159 'LLVM_MC' : '${BASE_LLVM_BIN}/llvm-mc${EXEC_EXT}',
162 'BINUTILS_BASE' : '${BASE_BINUTILS}/bin/le32-nacl-',
163 'OBJDUMP' : '${BINUTILS_BASE}objdump${EXEC_EXT}',
164 'NM' : '${BINUTILS_BASE}nm${EXEC_EXT}',
165 'AR' : '${BINUTILS_BASE}ar${EXEC_EXT}',
166 'RANLIB' : '${BINUTILS_BASE}ranlib${EXEC_EXT}',
167 'READELF' : '${BINUTILS_BASE}readelf${EXEC_EXT}',
168 'STRIP' : '${BINUTILS_BASE}strip${EXEC_EXT}',
169 # linker (used for both bitcode and ELF linking)
170 'LD' : '${BINUTILS_BASE}ld.gold${EXEC_EXT}',
172 # Use the default command line arguments to the sandboxed translator.
173 'USE_DEFAULT_CMD_LINE': '1',
176 ######################################################################
180 ######################################################################
182 def ParseError(s, leftpos, rightpos, msg):
183 Log.Error("Parse Error: %s", msg)
185 Log.Error(' ' + (' '*leftpos) + ('^'*(rightpos - leftpos + 1)))
188 # Find the leftmost position in "s" which begins a substring
189 # in "strset", starting at "pos".
191 # FindFirst('hello world', 0, ['h','o']) = ('h', 0)
192 # FindFirst('hello world', 1, ['h','o']) = ('o', 4)
193 # FindFirst('hello world', 0, ['x']) = (None,11)
194 def FindFirst(s, pos, strset):
197 m[s.find(ss, pos)] = ss
201 return (None, len(s))
205 class Environment(object):
209 def register(cls, func):
210 """ Register a function for use in the evaluator """
211 cls.functions[func.__name__] = func
219 self.data = dict(INITIAL_ENV)
221 def update(self, extra):
222 self.data.update(extra)
225 for (k,v) in self.data.iteritems():
226 print '%s == %s' % (k,v)
229 self.stack.append(self.data)
230 self.data = dict(self.data) # Make a copy
233 self.data = self.stack.pop()
235 def has(self, varname):
236 return varname in self.data
238 def getraw(self, varname):
239 return self.eval(self.data[varname])
241 # Evaluate a variable from the environment.
242 # Returns a list of terms.
243 def get(self, varname):
244 return shell.split(self.getraw(varname))
246 # Retrieve a variable from the environment which
247 # is a single term. Returns a string.
248 def getone(self, varname):
249 return shell.unescape(self.getraw(varname))
251 def getbool(self, varname):
252 return bool(int(self.getone(varname)))
254 def setbool(self, varname, val):
256 self.set(varname, '1')
258 self.set(varname, '0')
260 # Set a variable in the environment without shell-escape
261 def setraw(self, varname, val):
262 self.data[varname] = val
264 # Set one or more variables using named arguments
265 def setmany(self, **kwargs):
266 for k,v in kwargs.iteritems():
267 if isinstance(v, types.StringTypes):
269 elif isinstance(v, types.ListType):
272 Log.Fatal('env.setmany given a non-string and non-list value')
274 def clear(self, varname):
275 self.data[varname] = ''
277 # Set a variable to one or more terms, applying shell-escape.
278 def set(self, varname, *vals):
280 self.append(varname, *vals)
282 # Append one or more terms to a variable in the
283 # environment, applying shell-escape.
284 def append(self, varname, *vals):
285 escaped = [ shell.escape(v) for v in vals ]
286 if len(self.data[varname]) > 0:
287 self.data[varname] += ' '
288 self.data[varname] += ' '.join(escaped)
290 # Evaluate an expression s
292 (result, i) = self.eval_expr(s, 0, [])
296 ######################################################################
297 # EXPRESSION EVALUATION CODE
298 # Context Free Grammar:
300 # str = empty | string literal
301 # expr = str | expr '$' '{' bracket_expr '}' expr
302 # bracket_expr = varname | boolexpr ? expr | boolexpr ? expr : expr | @call
303 # boolexpr = boolval | boolval '&&' boolexpr | boolval '||' boolexpr
304 # boolval = varname | !varname | #varname | !#varname | varname '==' str
305 # varname = str | varname '%' bracket_expr '%' varname
306 # call = func | func ':' arglist
308 # arglist = empty | arg ':' arglist
310 # Do not call these functions outside of this class.
311 # The env.eval method is the external interface to the evaluator.
312 ######################################################################
314 # Evaluate a string literal
315 def eval_str(self, s, pos, terminators):
316 (_,i) = FindFirst(s, pos, terminators)
319 # Evaluate %var% substitutions inside a variable name.
320 # Returns (the_actual_variable_name, endpos)
321 # Terminated by } character
322 def eval_varname(self, s, pos, terminators):
323 (_,i) = FindFirst(s, pos, ['%'] + terminators)
324 leftpart = s[pos:i].strip(' ')
325 if i == len(s) or s[i] in terminators:
328 (middlepart, j) = self.eval_bracket_expr(s, i+1, ['%'])
329 if j == len(s) or s[j] != '%':
330 ParseError(s, i, j, "Unterminated %")
332 (rightpart, k) = self.eval_varname(s, j+1, terminators)
334 fullname = leftpart + middlepart + rightpart
335 fullname = fullname.strip()
339 def eval_whitespace(self, s, pos):
341 while i < len(s) and s[i] == ' ':
345 def eval_bool_val(self, s, pos, terminators):
346 (_,i) = self.eval_whitespace(s, pos)
354 (_,i) = self.eval_whitespace(s, i)
362 (varname, j) = self.eval_varname(s, i, ['=']+terminators)
364 # This is an error condition one level up. Don't evaluate anything.
367 if varname not in self.data:
368 ParseError(s, i, j, "Undefined variable '%s'" % varname)
369 vardata = self.data[varname]
371 contents = self.eval(vardata)
374 # String equality test
375 if j+1 == len(s) or s[j+1] != '=':
376 ParseError(s, j, j, "Unexpected token")
378 ParseError(s, j, j, "Cannot combine == and #")
379 (_,j) = self.eval_whitespace(s, j+2)
380 (literal_str,j) = self.eval_str(s, j, [' ']+terminators)
381 (_,j) = self.eval_whitespace(s, j)
383 return (False, j) # Error one level up
388 val = (len(contents) != 0)
389 elif literal_str is not None:
390 val = (contents == literal_str)
392 if contents not in ('0','1'):
394 "%s evaluated to %s, which is not a boolean!" % (varname, contents))
395 val = bool(int(contents))
396 return (negated ^ val, j)
398 # Evaluate a boolexpr
399 def eval_bool_expr(self, s, pos, terminators):
400 (boolval1, i) = self.eval_bool_val(s, pos, ['&','|']+terminators)
402 # This is an error condition one level up. Don't evaluate anything.
405 if s[i] in ('&','|'):
407 if i+1 == len(s) or s[i+1] != s[i]:
408 ParseError(s, i, i, "Unexpected token")
409 is_and = (s[i] == '&')
411 (boolval2, j) = self.eval_bool_expr(s, i+2, terminators)
413 # This is an error condition one level up.
417 return (boolval1 and boolval2, j)
419 return (boolval1 or boolval2, j)
423 # Evaluate the inside of a ${} or %%.
424 # Returns the (the_evaluated_string, endpos)
425 def eval_bracket_expr(self, s, pos, terminators):
426 (_,pos) = self.eval_whitespace(s, pos)
429 # Function call: ${@func}
430 # or possibly : ${@func:arg1:arg2...}
431 (_,i) = FindFirst(s, pos, [':']+terminators)
433 return ('', i) # Error one level up
434 funcname = s[pos+1:i]
440 (_,j) = FindFirst(s, i+1, terminators)
442 return ('', j) # Error one level up
443 args = s[i+1:j].split(':')
445 val = self.functions[funcname](*args)
446 contents = self.eval(val)
449 (m,_) = FindFirst(s, pos, ['?']+terminators)
451 # Regular variable substitution
452 (varname,i) = self.eval_varname(s, pos, terminators)
454 return ('', i) # Error one level up
455 if varname not in self.data:
456 ParseError(s, pos, i, "Undefined variable '%s'" % varname)
457 vardata = self.data[varname]
458 contents = self.eval(vardata)
462 (is_cond_true,i) = self.eval_bool_expr(s, pos, ['?']+terminators)
463 assert(i < len(s) and s[i] == '?')
465 (if_true_expr, j) = self.eval_expr(s, i+1, [' : ']+terminators)
467 return ('', j) # Error one level up
469 if s[j:j+3] == ' : ':
470 (if_false_expr,j) = self.eval_expr(s, j+3, terminators)
472 # This is an error condition one level up.
478 contents = if_true_expr.strip()
480 contents = if_false_expr.strip()
484 # Evaluate an expression with ${} in string s, starting at pos.
485 # Returns (the_evaluated_expression, endpos)
486 def eval_expr(self, s, pos, terminators):
487 (m,i) = FindFirst(s, pos, ['${'] + terminators)
489 if i == len(s) or m in terminators:
492 (middlepart, j) = self.eval_bracket_expr(s, i+2, ['}'])
493 if j == len(s) or s[j] != '}':
494 ParseError(s, i, j, 'Unterminated ${')
496 (rightpart, k) = self.eval_expr(s, j+1, terminators)
497 return (leftpart + middlepart + rightpart, k)
502 def override_env(meth_name, func):
503 """Override a method in the global |env|, given the method name
504 and the new function.
507 setattr(env, meth_name, types.MethodType(func, env, Environment))