package_sb_file.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python
  2. # Copyright 2017 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. from __future__ import print_function
  6. import os
  7. import sys
  8. """Pack MacOS sandbox seatbelt .sb files as C-style strings, escaping
  9. quotes and backslashes as needed.
  10. """
  11. header = '// Generated by package_sb_file.py. Do not edit !!!\n\n'
  12. namespace = 'namespace sandbox {\nnamespace policy{\n\n'
  13. namespace_end = '\n} // namespace policy\n} // namespace sandbox\n'
  14. h_include = '#include "sandbox/policy/export.h"\n'
  15. h_definition = ('SANDBOX_POLICY_EXPORT\n' +
  16. 'extern const char kSeatbeltPolicyString_%s[];\n\n')
  17. cc_include = '#include "sandbox/policy/mac/%s.sb.h"\n'
  18. cc_definition = 'const char kSeatbeltPolicyString_%s[] = \n'
  19. cc_definition_end = '"";\n' # Add "" so the definition has some content
  20. # (the empty string) if the sb file is empty.
  21. def escape_for_c(line):
  22. if line and line[0] == ';':
  23. return ''
  24. return line.replace('\\', '\\\\').replace('\"', '\\\"')
  25. def pack_file(argv):
  26. if len(argv) != 2:
  27. print >> sys.stderr, 'usage: package_sb_file.py input_filename output_dir'
  28. return 1
  29. input_filename = argv[0]
  30. output_directory = argv[1]
  31. input_basename = os.path.basename(input_filename)
  32. (module_name, module_ext) = os.path.splitext(input_basename)
  33. output_h_file = output_directory + '/' + input_basename + '.h'
  34. output_cc_file = output_directory + '/' + input_basename + '.cc'
  35. try:
  36. with open(input_filename, 'r') as infile:
  37. with open(output_h_file, 'w') as outfile:
  38. outfile.write(header)
  39. outfile.write(h_include)
  40. outfile.write(namespace)
  41. outfile.write(h_definition % module_name)
  42. outfile.write(namespace_end)
  43. with open(output_cc_file, 'w') as outfile:
  44. outfile.write(header)
  45. outfile.write(cc_include % module_name)
  46. outfile.write(namespace)
  47. outfile.write(cc_definition % module_name)
  48. for line in infile:
  49. escaped_line = escape_for_c(line.rstrip())
  50. if escaped_line:
  51. outfile.write(' "' + escaped_line + '\\n"\n')
  52. outfile.write(cc_definition_end)
  53. outfile.write(namespace_end)
  54. except IOError:
  55. print('Failed to process %s' % input_filename, file=sys.stderr)
  56. return 1
  57. return 0
  58. if __name__ == '__main__':
  59. sys.exit(pack_file(sys.argv[1:]))