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