generate_params.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/bin/env python
  2. # Copyright 2021 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.
  5. """generate_params.py processes input .sb seatbelt files and extracts
  6. parameter definitions of the form
  7. (define "sandbox-param-name")
  8. And generates C++ constants of the form
  9. kParamSandboxParamName
  10. Usage:
  11. generate_sandbox_params.py path/to/params policy1.sb policy2.sb...
  12. Where |path/to/params| specifies the file prefix for the generated .h
  13. and .cc files.
  14. """
  15. from __future__ import print_function
  16. import re
  17. import sys
  18. def generate_sandbox_params(argv):
  19. if len(argv) < 3:
  20. print('Usage: {} output_file_prefix file1.sb...'.format(argv[0]),
  21. file=sys.stderr)
  22. return 1
  23. h_contents = ''
  24. cc_contents = ''
  25. for (name, value) in _process_policy_files(argv[2:]):
  26. variable_name = 'kParam' + name.title().replace('-', '')
  27. h_contents += 'SANDBOX_POLICY_EXPORT extern const char {}[];\n'.format(
  28. variable_name)
  29. cc_contents += 'const char {}[] = "{}";\n'.format(variable_name, value)
  30. with open(argv[1] + '.h', 'w') as f:
  31. f.write(
  32. FILE_TEMPLATE.format(includes='#include "sandbox/policy/export.h"',
  33. contents=h_contents))
  34. with open(argv[1] + '.cc', 'w') as f:
  35. f.write(
  36. FILE_TEMPLATE.format(
  37. includes='#include "sandbox/policy/mac/params.h"',
  38. contents=cc_contents))
  39. return 0
  40. def _process_policy_files(files):
  41. """Iterates the files in |files|, parsing out parameter definitions, and
  42. yields the name-value pair.
  43. """
  44. for sb_file in files:
  45. with open(sb_file, 'r') as f:
  46. for line in f:
  47. comment_start = line.find(';')
  48. if comment_start != -1:
  49. line = line[:comment_start]
  50. match = DEFINE_RE.match(line)
  51. if match:
  52. groups = match.groups()
  53. yield (groups[0], groups[1])
  54. DEFINE_RE = re.compile(r'^\(define\s+([a-zA-Z0-9\-]+).*"(\w+)"\)')
  55. FILE_TEMPLATE = """// Generated by generate_params.py. Do not edit!!!
  56. {includes}
  57. namespace sandbox {{
  58. namespace policy {{
  59. {contents}
  60. }} // namespace policy
  61. }} // namespace sandbox
  62. """
  63. if __name__ == '__main__':
  64. sys.exit(generate_sandbox_params(sys.argv))