1# Copyright 2017 The TensorFlow Authors. All Rights Reserved. 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# ============================================================================== 15 16"""create_def_file.py - tool to create a windows def file. 17 18The def file can be used to export symbols from the tensorflow dll to enable 19tf.load_library(). 20 21Because the linker allows only 64K symbols to be exported per dll 22we filter the symbols down to the essentials. The regular expressions 23we use for this are specific to tensorflow. 24 25TODO: this works fine but there is an issue with exporting 26'const char * const' and importing it from a user_ops. The problem is 27on the importing end and using __declspec(dllimport) works around it. 28""" 29from __future__ import absolute_import 30from __future__ import division 31from __future__ import print_function 32 33import argparse 34import codecs 35import os 36import re 37import subprocess 38import sys 39import tempfile 40 41# External tools we use that come with visual studio sdk and 42# we assume that the caller has the correct PATH to the sdk 43UNDNAME = "undname.exe" 44DUMPBIN = "dumpbin.exe" 45 46# Exclude if matched 47EXCLUDE_RE = re.compile(r"RTTI|deleting destructor|::internal::|Internal|" 48 r"python_op_gen_internal|grappler") 49 50# Include if matched before exclude 51INCLUDEPRE_RE = re.compile(r"google::protobuf::internal::ExplicitlyConstructed|" 52 r"tensorflow::internal::LogMessage|" 53 r"tensorflow::internal::LogString|" 54 r"tensorflow::internal::CheckOpMessageBuilder|" 55 r"tensorflow::internal::PickUnusedPortOrDie|" 56 r"tensorflow::internal::ValidateDevice|" 57 r"tensorflow::ops::internal::Enter|" 58 r"tensorflow::strings::internal::AppendPieces|" 59 r"tensorflow::strings::internal::CatPieces|" 60 r"tensorflow::errors::Internal|" 61 r"tensorflow::Tensor::CopyFromInternal|" 62 r"tensorflow::kernel_factory::" 63 r"OpKernelRegistrar::InitInternal|" 64 r"tensorflow::io::internal::JoinPathImpl") 65 66# Include if matched after exclude 67INCLUDE_RE = re.compile(r"^(TF_\w*)$|" 68 r"^(TFE_\w*)$|" 69 r"tensorflow::|" 70 r"functor::|" 71 r"\?nsync_|" 72 r"stream_executor::") 73 74# We want to identify data members explicitly in the DEF file, so that no one 75# can implicitly link against the DLL if they use one of the variables exported 76# from the DLL and the header they use does not decorate the symbol with 77# __declspec(dllimport). It is easier to detect what a data symbol does 78# NOT look like, so doing it with the below regex. 79DATA_EXCLUDE_RE = re.compile(r"[)(]|" 80 r"vftable|" 81 r"vbtable|" 82 r"vcall|" 83 r"RTTI|" 84 r"protobuf::internal::ExplicitlyConstructed") 85 86def get_args(): 87 """Parse command line.""" 88 filename_list = lambda x: x.split(";") 89 parser = argparse.ArgumentParser() 90 parser.add_argument("--input", type=filename_list, 91 help="paths to input libraries separated by semicolons", 92 required=True) 93 parser.add_argument("--output", help="output deffile", required=True) 94 parser.add_argument("--target", help="name of the target", required=True) 95 parser.add_argument("--bitness", help="build target bitness", required=True) 96 args = parser.parse_args() 97 return args 98 99 100def main(): 101 """main.""" 102 args = get_args() 103 104 # Pipe dumpbin to extract all linkable symbols from libs. 105 # Good symbols are collected in candidates and also written to 106 # a temp file. 107 candidates = [] 108 tmpfile = tempfile.NamedTemporaryFile(mode="w", delete=False) 109 for lib_path in args.input: 110 proc = subprocess.Popen([DUMPBIN, "/nologo", "/linkermember:1", lib_path], 111 stdout=subprocess.PIPE) 112 for line in codecs.getreader("utf-8")(proc.stdout): 113 cols = line.split() 114 if len(cols) < 2: 115 continue 116 sym = cols[1] 117 tmpfile.file.write(sym + "\n") 118 candidates.append(sym) 119 exit_code = proc.wait() 120 if exit_code != 0: 121 print("{} failed, exit={}".format(DUMPBIN, exit_code)) 122 return exit_code 123 tmpfile.file.close() 124 125 # Run the symbols through undname to get their undecorated name 126 # so we can filter on something readable. 127 with open(args.output, "w") as def_fp: 128 # track dupes 129 taken = set() 130 131 # Header for the def file. 132 def_fp.write("LIBRARY " + args.target + "\n") 133 def_fp.write("EXPORTS\n") 134 if args.bitness == "64": 135 def_fp.write("\t??1OpDef@tensorflow@@UEAA@XZ\n") 136 else: 137 def_fp.write("\t??1OpDef@tensorflow@@UAE@XZ\n") 138 139 # Each symbols returned by undname matches the same position in candidates. 140 # We compare on undname but use the decorated name from candidates. 141 dupes = 0 142 proc = subprocess.Popen([UNDNAME, tmpfile.name], stdout=subprocess.PIPE) 143 for idx, line in enumerate(codecs.getreader("utf-8")(proc.stdout)): 144 decorated = candidates[idx] 145 if decorated in taken: 146 # Symbol is already in output, done. 147 dupes += 1 148 continue 149 150 if not INCLUDEPRE_RE.search(line): 151 if EXCLUDE_RE.search(line): 152 continue 153 if not INCLUDE_RE.search(line): 154 continue 155 156 if "deleting destructor" in line: 157 # Some of the symbols convered by INCLUDEPRE_RE export deleting 158 # destructor symbols, which is a bad idea. 159 # So we filter out such symbols here. 160 continue 161 162 if DATA_EXCLUDE_RE.search(line): 163 def_fp.write("\t" + decorated + "\n") 164 else: 165 def_fp.write("\t" + decorated + " DATA\n") 166 taken.add(decorated) 167 exit_code = proc.wait() 168 if exit_code != 0: 169 print("{} failed, exit={}".format(UNDNAME, exit_code)) 170 return exit_code 171 172 os.unlink(tmpfile.name) 173 174 print("symbols={}, taken={}, dupes={}" 175 .format(len(candidates), len(taken), dupes)) 176 return 0 177 178 179if __name__ == "__main__": 180 sys.exit(main()) 181