2 # Copyright 2014 The Chromium 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 # pylint: disable=W0104,W0106,F0401,R0201
16 return os.path.dirname(os.path.abspath(__file__))
19 def _GetDirAbove(dirname):
20 """Returns the directory "above" this file containing |dirname| (which must
21 also be "above" this file)."""
24 path, tail = os.path.split(path)
30 def _AddThirdPartyImportPath():
31 sys.path.append(os.path.join(_GetDirAbove('mojo'), 'third_party'))
34 _AddThirdPartyImportPath()
37 loader = jinja2.FileSystemLoader(_ScriptDir())
38 jinja_env = jinja2.Environment(loader=loader, keep_trailing_newline=True)
41 # Accumulate lines of code with varying levels of indentation.
42 class CodeWriter(object):
46 self._margin_stack = []
48 def __lshift__(self, line):
49 self._lines.append((self._margin + line).rstrip())
52 self._margin_stack.append(self._margin)
56 self._margin = self._margin_stack.pop()
59 return '\n'.join(self._lines).rstrip() + '\n'
65 # Context handler that automatically indents and dedents a CodeWriter
67 def __init__(self, writer):
71 self._writer.PushMargin()
73 def __exit__(self, type_, value, traceback):
74 self._writer.PopMargin()
77 def TemplateFile(name):
78 return os.path.join(os.path.dirname(__file__), name)
81 # Wraps comma separated lists as needed.
82 def Wrap(pre, items, post):
83 complete = pre + ', '.join(items) + post
84 if len(complete) <= 80:
88 for i, item in enumerate(items):
89 if i < len(items) - 1:
90 lines.append(indent + item + ',')
92 lines.append(indent + item + post)
96 def GeneratorWarning():
97 return ('// WARNING this file was generated by %s\n// Do not edit by hand.' %
98 os.path.basename(__file__))
101 # Untrusted library implementing the public Mojo API.
102 def GenerateLibMojo(functions, out):
103 template = jinja_env.get_template('libmojo.cc.tmpl')
108 for line in Wrap('%s %s(' % (f.return_type, f.name), f.ParamList(), ') {'):
111 # 2 extra parameters: message ID and return value.
112 num_params = len(f.params) + 2
115 code << 'uint32_t params[%d];' % num_params
116 return_type = f.result_param.base_type
117 if return_type == 'MojoResult':
118 default = 'MOJO_RESULT_INVALID_ARGUMENT'
119 elif return_type == 'MojoTimeTicks':
122 raise Exception('Unhandled return type: ' + return_type)
123 code << '%s %s = %s;' % (return_type, f.result_param.name, default)
126 code << 'params[0] = %d;' % f.uid
128 cast_template = 'params[%d] = reinterpret_cast<uint32_t>(%s);'
131 if p.IsPassedByValue():
133 code << cast_template % (p.uid + 1, ptr)
134 # Return value pointer
135 code << cast_template % (num_params - 1, '&' + f.result_param.name)
137 code << 'DoMojoCall(params, sizeof(params));'
138 code << 'return %s;' % f.result_param.name
143 body = code.GetValue()
144 text = template.render(
145 generator_warning=GeneratorWarning(),
150 # Parameters passed into trusted code are handled differently depending on
151 # details of the parameter. ParamImpl instances encapsulate these differences
152 # and are used to generate the code that transfers parameters across the
153 # untrusted/trusted boundary.
154 class ParamImpl(object):
155 def __init__(self, param):
158 # Declare whatever variables are needed to handle this particular parameter.
159 def DeclareVars(self, code):
160 raise NotImplementedError()
162 # Convert the untrusted representation of the parameter into a trusted
163 # representation, such as a scalar value or a trusted pointer into the
164 # untrusted address space.
165 def ConvertParam(self):
166 raise NotImplementedError()
168 # For this particular parameter, what expression should be passed when
169 # invoking the trusted Mojo API function?
171 raise NotImplementedError()
173 # After invoking the trusted Mojo API function, transfer data back into
174 # untrusted memory. Overriden for Out and InOut parameters.
175 def CopyOut(self, code):
178 # Converting array parameters needs to be defered until after the scalar
179 # parameter containing the size of the array has itself been converted.
184 class ScalarInputImpl(ParamImpl):
185 def DeclareVars(self, code):
186 code << '%s %s_value;' % (self.param.base_type, self.param.name)
188 def ConvertParam(self):
190 return ('ConvertScalarInput(nap, params[%d], &%s_value)' %
194 return '%s_value' % self.param.name
197 class ScalarOutputImpl(ParamImpl):
198 def DeclareVars(self, code):
199 code << '%s volatile* %s_ptr;' % (self.param.base_type, self.param.name)
200 code << '%s %s_value;' % (self.param.base_type, self.param.name)
202 def ConvertParam(self):
204 return 'ConvertScalarOutput(nap, params[%d], &%s_ptr)' % (p.uid + 1, p.name)
207 return '&%s_value' % self.param.name
209 def CopyOut(self, code):
210 name = self.param.name
211 code << '*%s_ptr = %s_value;' % (name, name)
214 class ScalarInOutImpl(ParamImpl):
215 def DeclareVars(self, code):
216 code << '%s volatile* %s_ptr;' % (self.param.base_type, self.param.name)
217 code << '%s %s_value;' % (self.param.base_type, self.param.name)
219 def ConvertParam(self):
221 return ('ConvertScalarInOut(nap, params[%d], %s, &%s_value, &%s_ptr)' %
222 (p.uid + 1, CBool(p.is_optional), p.name, p.name))
225 name = self.param.name
226 expr = '&%s_value' % name
227 if self.param.is_optional:
228 expr = '%s_ptr ? %s : NULL' % (name, expr)
231 def CopyOut(self, code):
232 name = self.param.name
233 if self.param.is_optional:
234 code << 'if (%s_ptr != NULL) {' % (name)
236 code << '*%s_ptr = %s_value;' % (name, name)
239 code << '*%s_ptr = %s_value;' % (name, name)
242 class ArrayImpl(ParamImpl):
243 def DeclareVars(self, code):
244 code << '%s %s;' % (self.param.param_type, self.param.name)
246 def ConvertParam(self):
248 if p.base_type == 'void':
251 element_size = 'sizeof(*%s)' % p.name
253 return ('ConvertArray(nap, params[%d], %s, %s, %s, &%s)' %
254 (p.uid + 1, p.size + '_value', element_size, CBool(p.is_optional),
258 return self.param.name
264 class StructInputImpl(ParamImpl):
265 def DeclareVars(self, code):
266 code << '%s %s;' % (self.param.param_type, self.param.name)
268 def ConvertParam(self):
270 return ('ConvertStruct(nap, params[%d], %s, &%s)' %
271 (p.uid + 1, CBool(p.is_optional), p.name))
274 return self.param.name
281 return ScalarInOutImpl(p)
283 return ScalarOutputImpl(p)
285 return ScalarInputImpl(p)
289 return StructInputImpl(p)
295 return 'true' if value else 'false'
298 # A trusted wrapper that validates the arguments passed from untrusted code
299 # before passing them to the underlying public Mojo API.
300 def GenerateMojoSyscall(functions, out):
301 template = jinja_env.get_template('mojo_syscall.cc.tmpl')
307 impls = [ImplForParam(p) for p in f.params]
308 impls.append(ImplForParam(f.result_param))
310 code << 'case %d:' % f.uid
317 num_params = len(f.params) + 2
318 code << 'if (num_params != %d) {' % num_params
323 # Declare temporaries.
325 impl.DeclareVars(code)
327 def ConvertParam(code, impl):
328 code << 'if (!%s) {' % impl.ConvertParam()
335 code << 'ScopedCopyLock copy_lock(nap);'
336 # Convert and validate pointers in two passes.
337 # Arrays cannot be validated until the size parameter has been
340 if not impl.IsArray():
341 ConvertParam(code, impl)
344 ConvertParam(code, impl)
349 getParams = [impl.CallParam() for impl in impls[:-1]]
350 code << 'result_value = %s(%s);' % (f.name, ', '.join(getParams))
356 code << 'ScopedCopyLock copy_lock(nap);'
367 body = code.GetValue()
368 text = template.render(
369 generator_warning=GeneratorWarning(),
374 def OutFile(dir_path, name):
375 if not os.path.exists(dir_path):
376 os.makedirs(dir_path)
377 return open(os.path.join(dir_path, name), 'w')
381 usage = 'usage: %prog [options]'
382 parser = optparse.OptionParser(usage=usage)
387 help='output generated code into directory DIR')
388 options, args = parser.parse_args(args=args)
389 if not options.out_dir:
390 parser.error('-d is required')
392 parser.error('unexpected positional arguments: %s' % ' '.join(args))
394 mojo = interface.MakeInterface()
396 out = OutFile(options.out_dir, 'libmojo.cc')
397 GenerateLibMojo(mojo.functions, out)
399 out = OutFile(options.out_dir, 'mojo_syscall.cc')
400 GenerateMojoSyscall(mojo.functions, out)
403 if __name__ == '__main__':