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