summaryrefslogtreecommitdiffstats
path: root/chromium/sandbox/policy/mac/package_sb_file.py
blob: 934fd2261b5d3bf5970829cdb1ccfd569cf32d94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os
import sys

"""Pack MacOS sandbox seatbelt .sb files as C-style strings, escaping
quotes and backslashes as needed.
"""

header = '// Generated by package_sb_file.py. Do not edit !!!\n\n'
namespace = 'namespace sandbox {\nnamespace policy{\n\n'
namespace_end = '\n}  // namespace policy\n}  // namespace sandbox\n'
h_include = '#include "sandbox/policy/export.h"\n'
h_definition = ('SANDBOX_POLICY_EXPORT\n' +
                'extern const char kSeatbeltPolicyString_%s[];\n\n')
cc_include = '#include "sandbox/policy/mac/%s.sb.h"\n'
cc_definition = 'const char kSeatbeltPolicyString_%s[] = \n'
cc_definition_end = '"";\n'  # Add "" so the definition has some content
                             # (the empty string) if the sb file is empty.

def escape_for_c(line):
  if line and line[0] == ';':
    return ''
  return line.replace('\\', '\\\\').replace('\"', '\\\"')

def pack_file(argv):
  if len(argv) != 2:
    print >> sys.stderr, 'usage: package_sb_file.py input_filename output_dir'
    return 1
  input_filename = argv[0]
  output_directory = argv[1]
  input_basename = os.path.basename(input_filename)
  (module_name, module_ext) = os.path.splitext(input_basename)
  output_h_file = output_directory + '/' + input_basename + '.h'
  output_cc_file = output_directory + '/' + input_basename + '.cc'
  try:
    with open(input_filename, 'rb') as infile:
      with open(output_h_file, 'wb') as outfile:
        outfile.write(header)
        outfile.write(h_include)
        outfile.write(namespace)
        outfile.write(h_definition % module_name)
        outfile.write(namespace_end)
      with open(output_cc_file, 'wb') as outfile:
        outfile.write(header)
        outfile.write(cc_include % module_name)
        outfile.write(namespace)
        outfile.write(cc_definition % module_name)
        for line in infile:
          escaped_line = escape_for_c(line.rstrip())
          if escaped_line:
            outfile.write('    "' + escaped_line + '\\n"\n')
        outfile.write(cc_definition_end)
        outfile.write(namespace_end)
  except IOError:
    print >> sys.stderr, 'Failed to process %s' % input_filename
    return 1
  return 0

if __name__ == '__main__':
  sys.exit(pack_file(sys.argv[1:]))