Debian Codegraph @

src/device_trezor/trezor/tools/pb2cpp.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # Converts Google's protobuf python definitions of TREZOR wire messages
3 # to plain-python objects as used in TREZOR Core and python-trezor
4
5 import argparse
6 import logging
7 import os
8 import re
9 import shutil
10 import subprocess
11 import glob
12 import hashlib
13
14 try:
15 from tempfile import TemporaryDirectory
16 except:
17 # Py2 backward compatibility, using bundled sources.
18 # Original source: pip install backports.tempfile
19 try:
20 # Try bundled python version
21 import sys
22 sys.path.append(os.path.dirname(__file__))
23 from py2backports.tempfile import TemporaryDirectory
24
25 except:
26 raise EnvironmentError('Python 2.7+ or 3.4+ is required. '
27 'TemporaryDirectory is not available in Python 2.'
28 'Try to specify python to use, e.g.: "export TREZOR_PYTHON=`which python3`"')
29
30
31 AUTO_HEADER = "# Automatically generated by pb2cpp\n"
32
33 # Fixing GCC7 compilation error
34 UNDEF_STATEMENT = """
35 #ifdef minor
36 #undef minor
37 #endif
38 """
39
40 PROTOC = None
41 PROTOC_INCLUDE = None
42
43
44 def which(pgm):
45 path = os.getenv('PATH')
46 for p in path.split(os.path.pathsep):
47 p = os.path.join(p, pgm)
48 if os.path.exists(p) and os.access(p, os.X_OK):
49 return p
50
51
52 def namespace_file(fpath, package):
53 """Adds / replaces package name. Simple regex parsing, may use https://github.com/ph4r05/plyprotobuf later"""
54 with open(fpath) as fh:
55 fdata = fh.read()
56
57 re_syntax = re.compile(r"^syntax\s*=")
58 re_package = re.compile(r"^package\s+([^;]+?)\s*;\s*$")
59 lines = fdata.split("\n")
60
61 line_syntax = None
62 line_package = None
63 for idx, line in enumerate(lines):
64 if line_syntax is None and re_syntax.match(line):
65 line_syntax = idx
66 if line_package is None and re_package.match(line):
67 line_package = idx
68
69 if package is None:
70 if line_package is None:
71 return
72 else:
73 lines.pop(line_package)
74
75 else:
76 new_package = "package %s;" % package
77 if line_package is None:
78 lines.insert(line_syntax + 1 if line_syntax is not None else 0, new_package)
79 else:
80 lines[line_package] = new_package
81
82 new_fdat = "\n".join(lines)
83 with open(fpath, "w+") as fh:
84 fh.write(new_fdat)
85 return new_fdat
86
87
88 def protoc(files, out_dir, additional_includes=(), package=None, force=False):
89 """Compile code with protoc and return the data."""
90
91 include_dirs = set()
92 include_dirs.add(PROTOC_INCLUDE)
93 if additional_includes:
94 include_dirs.update(additional_includes)
95
96 with TemporaryDirectory() as tmpdir_protob, TemporaryDirectory() as tmpdir_out:
97 include_dirs.add(tmpdir_protob)
98
99 new_files = []
100 for file in files:
101 bname = os.path.basename(file)
102 tmp_file = os.path.join(tmpdir_protob, bname)
103
104 shutil.copy(file, tmp_file)
105 if package is not None:
106 namespace_file(tmp_file, package)
107 new_files.append(tmp_file)
108
109 protoc_includes = ["-I" + dir for dir in include_dirs if dir]
110
111 exec_args = (
112 [
113 PROTOC,
114 "--cpp_out",
115 tmpdir_out,
116 ]
117 + protoc_includes
118 + new_files
119 )
120
121 subprocess.check_call(exec_args)
122
123 # Fixing gcc compilation and clashes with "minor" field name
124 add_undef(tmpdir_out)
125
126 # Scan output dir, check file differences
127 update_message_files(tmpdir_out, out_dir, force)
128
129
130 def update_message_files(tmpdir_out, out_dir, force=False):
131 files = glob.glob(os.path.join(tmpdir_out, '*.pb.*'))
132 for fname in files:
133 bname = os.path.basename(fname)
134 dest_file = os.path.join(out_dir, bname)
135 if not force and os.path.exists(dest_file):
136 data = open(fname, 'rb').read()
137 data_hash = hashlib.sha256(data).digest()
138 data_dest = open(dest_file, 'rb').read()
139 data_dest_hash = hashlib.sha256(data_dest).digest()
140 if data_hash == data_dest_hash:
141 continue
142
143 shutil.copy(fname, dest_file)
144
145
146 def add_undef(out_dir):
147 files = glob.glob(os.path.join(out_dir, '*.pb.*'))
148 for fname in files:
149 with open(fname) as fh:
150 lines = fh.readlines()
151
152 idx_insertion = None
153 for idx in range(len(lines)):
154 if '@@protoc_insertion_point(includes)' in lines[idx]:
155 idx_insertion = idx
156 break
157
158 if idx_insertion is None:
159 pass
160
161 lines.insert(idx_insertion + 1, UNDEF_STATEMENT)
162 with open(fname, 'w') as fh:
163 fh.write("".join(lines))
164
165
166 def strip_leader(s, prefix):
167 """Remove given prefix from underscored name."""
168 leader = prefix + "_"
169 if s.startswith(leader):
170 return s[len(leader) :]
171 else:
172 return s
173
174
175 def main():
176 global PROTOC, PROTOC_INCLUDE
177 logging.basicConfig(level=logging.DEBUG)
178
179 parser = argparse.ArgumentParser()
180 # fmt: off
181 parser.add_argument("proto", nargs="+", help="Protobuf definition files")
182 parser.add_argument("-o", "--out-dir", help="Directory for generated source code")
183 parser.add_argument("-n", "--namespace", default=None, help="Message namespace")
184 parser.add_argument("-I", "--protoc-include", action="append", help="protoc include path")
185 parser.add_argument("-P", "--protobuf-module", default="protobuf", help="Name of protobuf module")
186 parser.add_argument("-f", "--force", default=False, help="Overwrite existing files")
187 # fmt: on
188 args = parser.parse_args()
189
190 protoc_includes = args.protoc_include or (os.environ.get("PROTOC_INCLUDE"),)
191
192 PROTOBUF_INCLUDE_DIRS = os.getenv("PROTOBUF_INCLUDE_DIRS", None)
193 PROTOBUF_PROTOC_EXECUTABLE = os.getenv("PROTOBUF_PROTOC_EXECUTABLE", None)
194
195 if PROTOBUF_PROTOC_EXECUTABLE and not os.path.exists(PROTOBUF_PROTOC_EXECUTABLE):
196 raise ValueError("PROTOBUF_PROTOC_EXECUTABLE set but not found: %s" % PROTOBUF_PROTOC_EXECUTABLE)
197
198 elif PROTOBUF_PROTOC_EXECUTABLE:
199 PROTOC = PROTOBUF_PROTOC_EXECUTABLE
200
201 else:
202 if os.name == "nt":
203 PROTOC = which("protoc.exe")
204 else:
205 PROTOC = which("protoc")
206
207 if not PROTOC:
208 raise ValueError("protoc command not found. Set PROTOBUF_PROTOC_EXECUTABLE env var to the protoc binary and optionally PROTOBUF_INCLUDE_DIRS")
209
210 PROTOC_PREFIX = os.path.dirname(os.path.dirname(PROTOC))
211 PROTOC_INCLUDE = PROTOBUF_INCLUDE_DIRS if PROTOBUF_INCLUDE_DIRS else os.path.join(PROTOC_PREFIX, "include")
212
213 protoc(
214 args.proto, args.out_dir, protoc_includes, package=args.namespace, force=args.force
215 )
216
217
218 if __name__ == "__main__":
219 main()