2 # GObject-Introspection - a framework for introspecting GObject libraries
3 # Copyright (C) 2008 Colin Walters
4 # Copyright (C) 2008 Johan Dahlin
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2 of the License, or (at your option) any later version.
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # Lesser General Public License for more details.
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the
18 # Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 # Boston, MA 02111-1307, USA.
28 from .gdumpparser import IntrospectionBinary
31 # bugzilla.gnome.org/558436
32 # Compile a binary program which is then linked to a library
33 # we want to introspect, in order to call its get_type functions.
35 _PROGRAM_TEMPLATE = """/* This file is generated, do not edit */
43 main(int argc, char **argv)
46 const char *introspect_dump_prefix = "--introspect-dump=";
48 #if !GLIB_CHECK_VERSION(2,35,0)
54 if (argc != 2 || !g_str_has_prefix (argv[1], introspect_dump_prefix))
56 g_printerr ("Usage: %%s --introspect-dump=input,output", argv[0]);
60 if (!dump_irepository (argv[1] + strlen(introspect_dump_prefix), &error))
62 g_printerr ("%%s\\n", error->message);
70 class CompilerError(Exception):
74 class LinkerError(Exception):
78 class DumpCompiler(object):
80 def __init__(self, options, get_type_functions, error_quark_functions):
81 self._options = options
82 self._get_type_functions = get_type_functions
83 self._error_quark_functions = error_quark_functions
85 self._compiler_cmd = os.environ.get('CC', 'gcc')
86 self._linker_cmd = os.environ.get('CC', self._compiler_cmd)
87 self._pkgconfig_cmd = os.environ.get('PKG_CONFIG', 'pkg-config')
88 self._pkgconfig_msvc_flags = ''
89 # Enable the --msvc-syntax pkg-config flag when
90 # the Microsoft compiler is used
91 # (This is the other way to check whether Visual C++ is used subsequently)
92 if 'cl' in self._compiler_cmd:
93 self._pkgconfig_msvc_flags = '--msvc-syntax'
94 self._uninst_srcdir = os.environ.get(
95 'UNINSTALLED_INTROSPECTION_SRCDIR')
96 self._packages = ['gio-2.0 gmodule-2.0']
97 self._packages.extend(options.packages)
102 # We have to use the current directory to work around Unix
103 # sysadmins who mount /tmp noexec
104 tmpdir = tempfile.mkdtemp('', 'tmp-introspect', dir=os.getcwd())
107 if self._uninst_srcdir is not None:
108 gdump_path = os.path.join(self._uninst_srcdir, 'girepository', 'gdump.c')
110 gdump_path = os.path.join(os.path.join(DATADIR), 'gobject-introspection-1.0',
112 if not os.path.isfile(gdump_path):
113 raise SystemExit("Couldn't find %r" % (gdump_path, ))
114 gdump_file = open(gdump_path)
115 gdump_contents = gdump_file.read()
117 tpl_args['gdump_include'] = gdump_contents
118 tpl_args['init_sections'] = "\n".join(self._options.init_sections)
120 c_path = self._generate_tempfile(tmpdir, '.c')
121 f = open(c_path, 'w')
122 f.write(_PROGRAM_TEMPLATE % tpl_args)
124 # We need to reference our get_type and error_quark functions
125 # to make sure they are pulled in at the linking stage if the
126 # library is a static library rather than a shared library.
127 if len(self._get_type_functions) > 0:
128 for func in self._get_type_functions:
129 f.write("extern GType " + func + "(void);\n")
130 f.write("GType (*GI_GET_TYPE_FUNCS_[])(void) = {\n")
132 for func in self._get_type_functions:
139 if len(self._error_quark_functions) > 0:
140 for func in self._error_quark_functions:
141 f.write("extern GQuark " + func + "(void);\n")
142 f.write("GQuark (*GI_ERROR_QUARK_FUNCS_[])(void) = {\n")
144 for func in self._error_quark_functions:
153 # Microsoft compilers generate intermediate .obj files
154 # during compilation, unlike .o files like GCC and others
155 if self._pkgconfig_msvc_flags:
156 o_path = self._generate_tempfile(tmpdir, '.obj')
158 o_path = self._generate_tempfile(tmpdir, '.o')
165 bin_path = self._generate_tempfile(tmpdir, ext)
168 self._compile(o_path, c_path)
169 except CompilerError, e:
170 if not utils.have_debug_flag('save-temps'):
171 shutil.rmtree(tmpdir)
172 raise SystemExit('compilation of temporary binary failed:' + str(e))
175 self._link(bin_path, o_path)
176 except LinkerError, e:
177 if not utils.have_debug_flag('save-temps'):
178 shutil.rmtree(tmpdir)
179 raise SystemExit('linking of temporary binary failed: ' + str(e))
181 return IntrospectionBinary([bin_path], tmpdir)
185 def _generate_tempfile(self, tmpdir, suffix=''):
186 tmpl = '%s-%s%s' % (self._options.namespace_name,
187 self._options.namespace_version, suffix)
188 return os.path.join(tmpdir, tmpl)
190 def _run_pkgconfig(self, flag):
191 # Enable the --msvc-syntax pkg-config flag when
192 # the Microsoft compiler is used
193 if self._pkgconfig_msvc_flags:
194 cmd = [self._pkgconfig_cmd, self._pkgconfig_msvc_flags, flag]
196 cmd = [self._pkgconfig_cmd, flag]
197 proc = subprocess.Popen(
198 cmd + self._packages,
199 stdout=subprocess.PIPE)
200 return proc.communicate()[0].split()
202 def _compile(self, output, *sources):
203 # Not strictly speaking correct, but easier than parsing shell
204 args = self._compiler_cmd.split()
205 # Do not add -Wall when using init code as we do not include any
206 # header of the library being introspected
207 if self._compiler_cmd == 'gcc' and not self._options.init_sections:
209 pkgconfig_flags = self._run_pkgconfig('--cflags')
210 args.extend(pkgconfig_flags)
211 cflags = os.environ.get('CFLAGS', '')
212 for cflag in cflags.split():
214 for include in self._options.cpp_includes:
215 args.append('-I' + include)
216 # The Microsoft compiler uses different option flags for
217 # compilation result output
218 if self._pkgconfig_msvc_flags:
219 args.extend(['-c', '-Fe'+output, '-Fo'+output])
221 args.extend(['-c', '-o', output])
222 for source in sources:
223 if not os.path.exists(source):
225 "Could not find c source file: %s" % (source, ))
226 args.extend(list(sources))
227 if not self._options.quiet:
228 print "g-ir-scanner: compile: %s" % (
229 subprocess.list2cmdline(args), )
232 subprocess.check_call(args)
233 except subprocess.CalledProcessError, e:
234 raise CompilerError(e)
236 def _link(self, output, *sources):
238 libtool = utils.get_libtool_command(self._options)
241 args.append('--mode=link')
242 args.append('--tag=CC')
243 if self._options.quiet:
244 args.append('--silent')
246 args.extend(self._linker_cmd.split())
247 # We can use -o for the Microsoft compiler/linker,
248 # but it is considered deprecated usage with that
249 if self._pkgconfig_msvc_flags:
250 args.extend(['-Fe'+output])
252 args.extend(['-o', output])
255 args.append('-export-all-symbols')
257 args.append('-export-dynamic')
259 cflags = os.environ.get('CFLAGS', '')
260 for cflag in cflags.split():
262 ldflags = os.environ.get('LDFLAGS', '')
263 for ldflag in ldflags.split():
266 # Make sure to list the library to be introspected first since it's
267 # likely to be uninstalled yet and we want the uninstalled RPATHs have
268 # priority (or we might run with installed library that is older)
270 for source in sources:
271 if not os.path.exists(source):
273 "Could not find object file: %s" % (source, ))
274 args.extend(list(sources))
276 if not self._options.external_library:
277 self._add_link_internal_args(args, libtool)
279 self._add_link_external_args(args)
281 if not self._options.quiet:
282 print "g-ir-scanner: link: %s" % (
283 subprocess.list2cmdline(args), )
286 subprocess.check_call(args)
287 except subprocess.CalledProcessError, e:
290 def _add_link_internal_args(self, args, libtool):
291 # An "internal" link is where the library to be introspected
292 # is being built in the current directory.
294 # Search the current directory first
295 # (This flag is not supported nor needed for Visual C++)
296 if self._pkgconfig_msvc_flags == '':
299 # https://bugzilla.gnome.org/show_bug.cgi?id=625195
301 # We don't have -Wl,-rpath for Visual C++, and that's
302 # going to cause a problem. Instead, link to internal
303 # libraries by deducing the .lib file name using
304 # the namespace name and version
305 if self._pkgconfig_msvc_flags:
306 if self._options.namespace_version:
307 args.append(str.lower(self._options.namespace_name) +
309 self._options.namespace_version+'.lib')
311 args.append(str.lower(self._options.namespace_name)+'.lib')
313 args.append('-Wl,-rpath=.')
315 for library in self._options.libraries:
316 # Visual C++: We have the needed .lib files now, and we need to link
317 # to .lib files, not the .dll as the --library option specifies the
318 # .dll(s) the .gir file refers to
319 if self._pkgconfig_msvc_flags == '':
320 if library.endswith(".la"): # explicitly specified libtool library
323 args.append('-l' + library)
325 for library_path in self._options.library_paths:
326 # Not used/needed on Visual C++, and -Wl,-rpath options
328 if self._pkgconfig_msvc_flags == '':
329 args.append('-L' + library_path)
330 if os.path.isabs(library_path):
332 args.append('-rpath')
333 args.append(library_path)
335 args.append('-Wl,-rpath=' + library_path)
337 args.extend(self._run_pkgconfig('--libs'))
339 def _add_link_external_args(self, args):
340 # An "external" link is where the library to be introspected
341 # is installed on the system; this case is used for the scanning
342 # of GLib in gobject-introspection itself.
344 args.extend(self._run_pkgconfig('--libs'))
345 for library in self._options.libraries:
346 # The --library option on Windows pass in the .dll file(s) the
347 # .gir files refer to, so don't link to them on Visual C++
348 if self._pkgconfig_msvc_flags == '':
349 if library.endswith(".la"): # explicitly specified libtool library
352 args.append('-l' + library)
354 def compile_introspection_binary(options, get_type_functions,
355 error_quark_functions):
356 dc = DumpCompiler(options, get_type_functions, error_quark_functions)