logging: Issue 6615: Changed handler prepend to append.
[python.git] / Lib / distutils / emxccompiler.py
bloba5a2ef88fe0690e80d0bbbcc8e46471ffbe4facd
1 """distutils.emxccompiler
3 Provides the EMXCCompiler class, a subclass of UnixCCompiler that
4 handles the EMX port of the GNU C compiler to OS/2.
5 """
7 # issues:
9 # * OS/2 insists that DLLs can have names no longer than 8 characters
10 # We put export_symbols in a def-file, as though the DLL can have
11 # an arbitrary length name, but truncate the output filename.
13 # * only use OMF objects and use LINK386 as the linker (-Zomf)
15 # * always build for multithreading (-Zmt) as the accompanying OS/2 port
16 # of Python is only distributed with threads enabled.
18 # tested configurations:
20 # * EMX gcc 2.81/EMX 0.9d fix03
22 __revision__ = "$Id$"
24 import os, sys, copy
25 from warnings import warn
27 from distutils.ccompiler import gen_preprocess_options, gen_lib_options
28 from distutils.unixccompiler import UnixCCompiler
29 from distutils.file_util import write_file
30 from distutils.errors import DistutilsExecError, CompileError, UnknownFileError
31 from distutils import log
32 from distutils.util import get_compiler_versions
34 class EMXCCompiler (UnixCCompiler):
36 compiler_type = 'emx'
37 obj_extension = ".obj"
38 static_lib_extension = ".lib"
39 shared_lib_extension = ".dll"
40 static_lib_format = "%s%s"
41 shared_lib_format = "%s%s"
42 res_extension = ".res" # compiled resource file
43 exe_extension = ".exe"
45 def __init__ (self,
46 verbose=0,
47 dry_run=0,
48 force=0):
50 UnixCCompiler.__init__ (self, verbose, dry_run, force)
52 (status, details) = check_config_h()
53 self.debug_print("Python's GCC status: %s (details: %s)" %
54 (status, details))
55 if status is not CONFIG_H_OK:
56 self.warn(
57 "Python's pyconfig.h doesn't seem to support your compiler. " +
58 ("Reason: %s." % details) +
59 "Compiling may fail because of undefined preprocessor macros.")
61 gcc_version, ld_version, dllwrap_version = get_compiler_versions()
62 self.gcc_version, self.ld_version = gcc_version, ld_version
63 self.debug_print(self.compiler_type + ": gcc %s, ld %s\n" %
64 (self.gcc_version,
65 self.ld_version) )
67 # Hard-code GCC because that's what this is all about.
68 # XXX optimization, warnings etc. should be customizable.
69 self.set_executables(compiler='gcc -Zomf -Zmt -O3 -fomit-frame-pointer -mprobe -Wall',
70 compiler_so='gcc -Zomf -Zmt -O3 -fomit-frame-pointer -mprobe -Wall',
71 linker_exe='gcc -Zomf -Zmt -Zcrtdll',
72 linker_so='gcc -Zomf -Zmt -Zcrtdll -Zdll')
74 # want the gcc library statically linked (so that we don't have
75 # to distribute a version dependent on the compiler we have)
76 self.dll_libraries=["gcc"]
78 # __init__ ()
80 def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
81 if ext == '.rc':
82 # gcc requires '.rc' compiled to binary ('.res') files !!!
83 try:
84 self.spawn(["rc", "-r", src])
85 except DistutilsExecError, msg:
86 raise CompileError, msg
87 else: # for other files use the C-compiler
88 try:
89 self.spawn(self.compiler_so + cc_args + [src, '-o', obj] +
90 extra_postargs)
91 except DistutilsExecError, msg:
92 raise CompileError, msg
94 def link (self,
95 target_desc,
96 objects,
97 output_filename,
98 output_dir=None,
99 libraries=None,
100 library_dirs=None,
101 runtime_library_dirs=None,
102 export_symbols=None,
103 debug=0,
104 extra_preargs=None,
105 extra_postargs=None,
106 build_temp=None,
107 target_lang=None):
109 # use separate copies, so we can modify the lists
110 extra_preargs = copy.copy(extra_preargs or [])
111 libraries = copy.copy(libraries or [])
112 objects = copy.copy(objects or [])
114 # Additional libraries
115 libraries.extend(self.dll_libraries)
117 # handle export symbols by creating a def-file
118 # with executables this only works with gcc/ld as linker
119 if ((export_symbols is not None) and
120 (target_desc != self.EXECUTABLE)):
121 # (The linker doesn't do anything if output is up-to-date.
122 # So it would probably better to check if we really need this,
123 # but for this we had to insert some unchanged parts of
124 # UnixCCompiler, and this is not what we want.)
126 # we want to put some files in the same directory as the
127 # object files are, build_temp doesn't help much
128 # where are the object files
129 temp_dir = os.path.dirname(objects[0])
130 # name of dll to give the helper files the same base name
131 (dll_name, dll_extension) = os.path.splitext(
132 os.path.basename(output_filename))
134 # generate the filenames for these files
135 def_file = os.path.join(temp_dir, dll_name + ".def")
137 # Generate .def file
138 contents = [
139 "LIBRARY %s INITINSTANCE TERMINSTANCE" % \
140 os.path.splitext(os.path.basename(output_filename))[0],
141 "DATA MULTIPLE NONSHARED",
142 "EXPORTS"]
143 for sym in export_symbols:
144 contents.append(' "%s"' % sym)
145 self.execute(write_file, (def_file, contents),
146 "writing %s" % def_file)
148 # next add options for def-file and to creating import libraries
149 # for gcc/ld the def-file is specified as any other object files
150 objects.append(def_file)
152 #end: if ((export_symbols is not None) and
153 # (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
155 # who wants symbols and a many times larger output file
156 # should explicitly switch the debug mode on
157 # otherwise we let dllwrap/ld strip the output file
158 # (On my machine: 10KB < stripped_file < ??100KB
159 # unstripped_file = stripped_file + XXX KB
160 # ( XXX=254 for a typical python extension))
161 if not debug:
162 extra_preargs.append("-s")
164 UnixCCompiler.link(self,
165 target_desc,
166 objects,
167 output_filename,
168 output_dir,
169 libraries,
170 library_dirs,
171 runtime_library_dirs,
172 None, # export_symbols, we do this in our def-file
173 debug,
174 extra_preargs,
175 extra_postargs,
176 build_temp,
177 target_lang)
179 # link ()
181 # -- Miscellaneous methods -----------------------------------------
183 # override the object_filenames method from CCompiler to
184 # support rc and res-files
185 def object_filenames (self,
186 source_filenames,
187 strip_dir=0,
188 output_dir=''):
189 if output_dir is None: output_dir = ''
190 obj_names = []
191 for src_name in source_filenames:
192 # use normcase to make sure '.rc' is really '.rc' and not '.RC'
193 (base, ext) = os.path.splitext (os.path.normcase(src_name))
194 if ext not in (self.src_extensions + ['.rc']):
195 raise UnknownFileError, \
196 "unknown file type '%s' (from '%s')" % \
197 (ext, src_name)
198 if strip_dir:
199 base = os.path.basename (base)
200 if ext == '.rc':
201 # these need to be compiled to object files
202 obj_names.append (os.path.join (output_dir,
203 base + self.res_extension))
204 else:
205 obj_names.append (os.path.join (output_dir,
206 base + self.obj_extension))
207 return obj_names
209 # object_filenames ()
211 # override the find_library_file method from UnixCCompiler
212 # to deal with file naming/searching differences
213 def find_library_file(self, dirs, lib, debug=0):
214 shortlib = '%s.lib' % lib
215 longlib = 'lib%s.lib' % lib # this form very rare
217 # get EMX's default library directory search path
218 try:
219 emx_dirs = os.environ['LIBRARY_PATH'].split(';')
220 except KeyError:
221 emx_dirs = []
223 for dir in dirs + emx_dirs:
224 shortlibp = os.path.join(dir, shortlib)
225 longlibp = os.path.join(dir, longlib)
226 if os.path.exists(shortlibp):
227 return shortlibp
228 elif os.path.exists(longlibp):
229 return longlibp
231 # Oops, didn't find it in *any* of 'dirs'
232 return None
234 # class EMXCCompiler
237 # Because these compilers aren't configured in Python's pyconfig.h file by
238 # default, we should at least warn the user if he is using a unmodified
239 # version.
241 CONFIG_H_OK = "ok"
242 CONFIG_H_NOTOK = "not ok"
243 CONFIG_H_UNCERTAIN = "uncertain"
245 def check_config_h():
247 """Check if the current Python installation (specifically, pyconfig.h)
248 appears amenable to building extensions with GCC. Returns a tuple
249 (status, details), where 'status' is one of the following constants:
250 CONFIG_H_OK
251 all is well, go ahead and compile
252 CONFIG_H_NOTOK
253 doesn't look good
254 CONFIG_H_UNCERTAIN
255 not sure -- unable to read pyconfig.h
256 'details' is a human-readable string explaining the situation.
258 Note there are two ways to conclude "OK": either 'sys.version' contains
259 the string "GCC" (implying that this Python was built with GCC), or the
260 installed "pyconfig.h" contains the string "__GNUC__".
263 # XXX since this function also checks sys.version, it's not strictly a
264 # "pyconfig.h" check -- should probably be renamed...
266 from distutils import sysconfig
267 import string
268 # if sys.version contains GCC then python was compiled with
269 # GCC, and the pyconfig.h file should be OK
270 if string.find(sys.version,"GCC") >= 0:
271 return (CONFIG_H_OK, "sys.version mentions 'GCC'")
273 fn = sysconfig.get_config_h_filename()
274 try:
275 # It would probably better to read single lines to search.
276 # But we do this only once, and it is fast enough
277 f = open(fn)
278 s = f.read()
279 f.close()
281 except IOError, exc:
282 # if we can't read this file, we cannot say it is wrong
283 # the compiler will complain later about this file as missing
284 return (CONFIG_H_UNCERTAIN,
285 "couldn't read '%s': %s" % (fn, exc.strerror))
287 else:
288 # "pyconfig.h" contains an "#ifdef __GNUC__" or something similar
289 if string.find(s,"__GNUC__") >= 0:
290 return (CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn)
291 else:
292 return (CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn)
295 def get_versions():
296 """ Try to find out the versions of gcc and ld.
297 If not possible it returns None for it.
299 warn("'distutils.emxccompiler.get_versions' is deprecated "
300 "use 'distutils.util.get_compiler_versions' instead",
301 DeprecationWarning)
303 # EMX ld has no way of reporting version number, and we use GCC
304 # anyway - so we can link OMF DLLs
305 gcc_version, ld_version, dllwrap_version = get_compiler_versions()
306 return gcc_version, None