1# Copyright (C) 2020 The Android Open Source Project 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15from __future__ import absolute_import 16 17import os 18import subprocess 19import tempfile 20 21from google.protobuf import descriptor, descriptor_pb2, message_factory, descriptor_pool 22from google.protobuf import reflection, text_format 23 24 25ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 26 27 28def create_message_factory(descriptor_file_paths, proto_type): 29 pool = descriptor_pool.DescriptorPool() 30 for file_path in descriptor_file_paths: 31 descriptor = read_descriptor(file_path) 32 for file in descriptor.file: 33 pool.Add(file) 34 35 return message_factory.MessageFactory().GetPrototype( 36 pool.FindMessageTypeByName(proto_type)) 37 38 39def read_descriptor(file_name): 40 with open(file_name, 'rb') as f: 41 contents = f.read() 42 43 descriptor = descriptor_pb2.FileDescriptorSet() 44 descriptor.MergeFromString(contents) 45 46 return descriptor 47 48 49def serialize_textproto_trace(trace_descriptor_path, extension_descriptor_paths, 50 text_proto_path, out_stream): 51 proto = create_message_factory([trace_descriptor_path] + 52 extension_descriptor_paths, 53 'perfetto.protos.Trace')() 54 55 with open(text_proto_path, 'r') as text_proto_file: 56 text_format.Merge(text_proto_file.read(), proto) 57 out_stream.write(proto.SerializeToString()) 58 out_stream.flush() 59 60 61def serialize_python_trace(trace_descriptor_path, python_trace_path, 62 out_stream): 63 python_cmd = [ 64 'python3', 65 python_trace_path, 66 trace_descriptor_path, 67 ] 68 69 # Add the test dir to the PYTHONPATH to allow synth_common to be found. 70 env = os.environ.copy() 71 if 'PYTHONPATH' in env: 72 env['PYTHONPATH'] = "{}:{}".format( 73 os.path.join(ROOT_DIR, 'test'), env['PYTHONPATH']) 74 else: 75 env['PYTHONPATH'] = os.path.join(ROOT_DIR, 'test') 76 subprocess.check_call(python_cmd, env=env, stdout=out_stream) 77