460054ca473535c57f1faa2de1d62ee5de879452
[gnome.gobject-introspection] / giscanner / dumper.py
1 # -*- Mode: Python -*-
2 # GObject-Introspection - a framework for introspecting GObject libraries
3 # Copyright (C) 2008 Colin Walters
4 # Copyright (C) 2008 Johan Dahlin
5 #
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.
10 #
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.
15 #
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.
20 #
21
22 import os
23 import subprocess
24 import tempfile
25
26 from .glibtransformer import IntrospectionBinary
27 from .utils import get_libtool_command
28
29 # bugzilla.gnome.org/558436
30 # Compile a binary program which is then linked to a library
31 # we want to introspect, in order to call its get_type functions.
32
33 _PROGRAM_TEMPLATE = """/* This file is generated, do not edit */
34 #include <glib.h>
35 #include <girepository.h>
36 #include <string.h>
37
38 static GOptionEntry entries[] =
39 {
40   { NULL }
41 };
42
43 int
44 main(int argc, char **argv)
45 {
46   GOptionContext *context;
47   GError *error = NULL;
48
49   if (!g_thread_supported ()) g_thread_init (NULL);
50   g_type_init ();
51
52   %(init_sections)s
53
54   context = g_option_context_new ("");
55   g_option_context_add_main_entries (context, entries, "girepository-1.0");
56   g_option_context_add_group (context, g_irepository_get_option_group ());
57   if (!g_option_context_parse (context, &argc, &argv, &error))
58     {
59       g_printerr ("introspect failed (%%d,%%d): %%s\\n",
60                   error->domain, error->code,
61                   error->message);
62       return 1;
63     }
64   return 0;
65 }
66 """
67
68
69 class CompilerError(Exception):
70     pass
71
72
73 class LinkerError(Exception):
74     pass
75
76
77 class DumpCompiler(object):
78
79     def __init__(self, options, get_type_functions):
80         self._options = options
81         self._get_type_functions = get_type_functions
82         # We have to use the current directory to work around Unix
83         # sysadmins who mount /tmp noexec
84         self._tmpdir = tempfile.mkdtemp('', 'tmp-introspect', dir=os.getcwd())
85
86         self._compiler_cmd = os.environ.get('CC', 'gcc')
87         self._linker_cmd = os.environ.get('CC', self._compiler_cmd)
88         self._pkgconfig_cmd = os.environ.get('PKG_CONFIG', 'pkg-config')
89
90         self._uninst_srcdir = os.environ.get(
91             'UNINSTALLED_INTROSPECTION_SRCDIR')
92         self._packages = ['gio-2.0 gthread-2.0']
93         if not self._uninst_srcdir:
94             self._packages.append('gobject-introspection-1.0')
95
96     # Public API
97
98     def run(self):
99         tpl_args = {}
100         tpl_args['init_sections'] = "\n".join(self._options.init_sections)
101
102         c_path = self._generate_tempfile('.c')
103         f = open(c_path, 'w')
104         f.write(_PROGRAM_TEMPLATE % tpl_args)
105
106         # We need to reference our get_type functions to make sure they are
107         # pulled in at the linking stage if the library is a static library
108         # rather than a shared library.
109         if len(self._get_type_functions) > 0:
110             for func in self._get_type_functions:
111                 f.write("extern GType " + func + "(void);\n")
112             f.write("GType (*GI_GET_TYPE_FUNCS_[])(void) = {\n")
113             first = True
114             for func in self._get_type_functions:
115                 if first:
116                     first = False
117                 else:
118                     f.write(",\n")
119                 f.write("  " + func)
120             f.write("\n};\n")
121         f.close()
122
123         o_path = self._generate_tempfile('.o')
124         bin_path = self._generate_tempfile()
125
126         try:
127             self._compile(o_path, c_path)
128         except CompilerError, e:
129             raise SystemExit('ERROR: ' + str(e))
130
131         try:
132             self._link(bin_path, o_path)
133         except LinkerError, e:
134             raise SystemExit('ERROR: ' + str(e))
135
136         os.unlink(c_path)
137
138         return IntrospectionBinary([bin_path], self._tmpdir)
139
140     # Private API
141
142     def _generate_tempfile(self, suffix=''):
143         tmpl = '%s-%s%s' % (self._options.namespace_name,
144                             self._options.namespace_version, suffix)
145         return os.path.join(self._tmpdir, tmpl)
146
147     def _run_pkgconfig(self, flag):
148         proc = subprocess.Popen(
149             [self._pkgconfig_cmd, flag] + self._packages,
150             stdout=subprocess.PIPE)
151         return proc.communicate()[0].split()
152
153     def _compile(self, output, *sources):
154         # Not strictly speaking correct, but easier than parsing shell
155         args = self._compiler_cmd.split()
156         # Do not add -Wall when using init code as we do not include any
157         # header of the library being introspected
158         if self._compiler_cmd == 'gcc' and not self._options.init_sections:
159             args.append('-Wall')
160         pkgconfig_flags = self._run_pkgconfig('--cflags')
161         if self._uninst_srcdir:
162             args.append('-I' + os.path.join(self._uninst_srcdir,
163                                                'girepository'))
164         args.extend(pkgconfig_flags)
165         cflags = os.environ.get('CFLAGS')
166         if (cflags):
167             for iflag in cflags.split():
168                 args.append(iflag)
169         for include in self._options.cpp_includes:
170             args.append('-I' + include)
171         args.extend(['-c', '-o', output])
172         for source in sources:
173             if not os.path.exists(source):
174                 raise CompilerError(
175                     "Could not find c source file: %s" % (source, ))
176         args.extend(list(sources))
177         subprocess.check_call(args)
178
179     def _link(self, output, *sources):
180         args = []
181         libtool = get_libtool_command(self._options)
182         if libtool:
183             args.extend(libtool)
184             args.append('--mode=link')
185             args.append('--tag=CC')
186             args.append('--silent')
187
188         args.extend([self._linker_cmd, '-o', output])
189
190         cflags = os.environ.get('CFLAGS')
191         if (cflags):
192             for iflag in cflags.split():
193                 args.append(iflag)
194
195         # Make sure to list the library to be introspected first since it's
196         # likely to be uninstalled yet and we want the uninstalled RPATHs have
197         # priority (or we might run with installed library that is older)
198
199         # Search the current directory first
200         args.append('-L.')
201
202         uninst_builddir = os.environ.get('UNINSTALLED_INTROSPECTION_BUILDDIR')
203         # hack for building GIRepository.gir, skip -lgirepository-1.0 since
204         # libgirepository-1.0.la is not in current directory and we refer to it
205         # explicitly below anyway
206         for library in self._options.libraries:
207             if (uninst_builddir and
208                 self._options.libraries[0] == 'girepository-1.0'):
209                 continue
210             if library.endswith(".la"): # explicitly specified libtool library
211                 args.append(library)
212             else:
213                 args.append('-l' + library)
214
215         # hack for building gobject-introspection itself
216         if uninst_builddir:
217             path = os.path.join(uninst_builddir, 'girepository',
218                                 'libgirepository-1.0.la')
219             args.append(path)
220
221         args.extend(self._run_pkgconfig('--libs'))
222         for source in sources:
223             if not os.path.exists(source):
224                 raise CompilerError(
225                     "Could not find object file: %s" % (source, ))
226         args.extend(list(sources))
227
228         subprocess.check_call(args)
229
230
231 def compile_introspection_binary(options, get_type_functions):
232     dc = DumpCompiler(options, get_type_functions)
233     return dc.run()