1#!/usr/bin/env python 2 3# Copyright 2019 the V8 project authors. All rights reserved. 4# Use of this source code is governed by a BSD-style license that can be found 5# in the LICENSE file. 6 7import argparse 8import io 9import sys 10 11from wasm import * 12 13FUNCTION_SECTION_ID = 3 14 15def parse_args(): 16 parser = argparse.ArgumentParser(\ 17 description="Inject compilation hints into a Wasm module.") 18 parser.add_argument("-i", "--in-wasm-file", \ 19 type=str, \ 20 help="original wasm module") 21 parser.add_argument("-o", "--out-wasm-file", \ 22 type=str, \ 23 help="wasm module with injected hints") 24 parser.add_argument("-x", "--hints-file", \ 25 type=str, required=True, \ 26 help="binary hints file to be injected as a custom section " + \ 27 "'compilationHints'") 28 return parser.parse_args() 29 30if __name__ == "__main__": 31 args = parse_args() 32 in_wasm_file = args.in_wasm_file if args.in_wasm_file else sys.stdin.fileno() 33 out_wasm_file = args.out_wasm_file if args.out_wasm_file else sys.stdout.fileno() 34 hints_bs = open(args.hints_file, "rb").read() 35 with io.open(in_wasm_file, "rb") as fin: 36 with io.open(out_wasm_file, "wb") as fout: 37 magic_number, bs = read_magic_number(fin); 38 fout.write(bs) 39 version, bs = read_version(fin); 40 fout.write(bs) 41 num_declared_functions = None 42 while True: 43 id, bs = read_varuintN(fin) 44 fout.write(bs) 45 if id == None: 46 break 47 payload_length, bs = read_varuintN(fin) 48 fout.write(bs) 49 50 # Peek into function section for upcoming validity check. 51 if id == FUNCTION_SECTION_ID: 52 num_declared_functions, bs = peek_varuintN(fin) 53 54 bs = fin.read(payload_length) 55 fout.write(bs) 56 57 # Instert hint section after function section. 58 if id == FUNCTION_SECTION_ID: 59 assert len(hints_bs) == num_declared_functions, "unexpected number of hints" 60 write_compilation_hints_section(fout, hints_bs) 61