summaryrefslogtreecommitdiffstats
path: root/Tools/freeze/nfreeze.py
blob: 3706e734e5a9850ead9177c9883c6c43a45effcc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#! /usr/local/bin/python

# "Freeze" a Python script into a binary.
# Usage: see variable usage_msg below (before the imports!)

# This version builds the frozen binary in a temporary directory;
# courtesy Jaap Vermeulen.  Use the -l option to get the functionality
# of the standard version.

# HINTS:
# - Edit the lines marked XXX below to localize.
# - You must have done "make inclinstall libainstall" in the Python
#   build directory.
# - The script should not use dynamically loaded modules
#   (*.so on most systems).


# Usage message

usage_msg = """
usage: freeze [-p prefix] [-e extension] [-l] ... script [module] ...

-p prefix:    This is the prefix used when you ran
              'Make inclinstall libainstall' in the Python build directory.
              (If you never ran this, freeze won't work.)
              The default is /usr/local.

-e extension: A directory containing additional .o files that
              may be used to resolve modules.  This directory
              should also have a Setup file describing the .o files.
              More than one -e option may be given.

-l:           Local compilation. Instead of using a temporary directory
              that is removed after succesful compilation, the current
              directory is used and temporary files are not removed.

script:       The Python script to be executed by the resulting binary.

module ...:   Additional Python modules (referenced by pathname)
              that will be included in the resulting binary.  These
              may be .py or .pyc files.
"""


# XXX Change the following line to point to your Tools/freeze directory
PACK = '/ufs/guido/src/python/Tools/freeze'

# XXX Change the following line to point to your install prefix
PREFIX = '/usr/local'

# XXX Change the following line to point to your favority temporary  directory
TMPDIR = '/usr/tmp'


# Import standard modules

import cmp
import getopt
import os
import string
import sys
import addpack


# Set the directory to look for the freeze-private modules

dir = os.path.dirname(sys.argv[0])
if dir:
	pack = dir
else:
	pack = PACK
addpack.addpack(pack)


# Establish temporary directory name

tmpdir = os.path.join(TMPDIR, 'freeze.' + `os.getpid()`)


# Import the freeze-private modules

import checkextensions
import findmodules
import makeconfig
import makefreeze
import makemakefile
import parsesetup


# Main program

def main():
	# module variable
	global tmpdir

	# overridable context
	prefix = PREFIX			# settable with -p option
	extensions = []
	path = sys.path

	# output files
	frozen_c = 'frozen.c'
	config_c = 'config.c'
	target = 'a.out'		# normally derived from script name
	makefile = 'Makefile'

	# parse command line
	try:
		opts, args = getopt.getopt(sys.argv[1:], 'e:p:l')
	except getopt.error, msg:
		usage('getopt error: ' + str(msg))

	# proces option arguments
	for o, a in opts:
		if o == '-e':
			extensions.append(a)
		if o == '-l':
			tmpdir = None
		if o == '-p':
			prefix = a

	# locations derived from options
	binlib = os.path.join(prefix, 'lib/python/lib')
	incldir = os.path.join(prefix, 'include/Py')
	config_c_in = os.path.join(binlib, 'config.c.in')
	frozenmain_c = os.path.join(binlib, 'frozenmain.c')
	makefile_in = os.path.join(binlib, 'Makefile')
	defines = ['-DHAVE_CONFIG_H', '-DUSE_FROZEN', '-DNO_MAIN',
		   '-DPYTHONPATH=\\"$(PYTHONPATH)\\"']
	includes = ['-I' + incldir, '-I' + binlib]

	# sanity check of directories and files
	for dir in [prefix, binlib, incldir] + extensions:
		if not os.path.exists(dir):
			usage('needed directory %s not found' % dir)
		if not os.path.isdir(dir):
			usage('%s: not a directory' % dir)
	for file in config_c_in, makefile_in, frozenmain_c:
		if not os.path.exists(file):
			usage('needed file %s not found' % file)
		if not os.path.isfile(file):
			usage('%s: not a plain file' % file)
	for dir in extensions:
		setup = os.path.join(dir, 'Setup')
		if not os.path.exists(setup):
			usage('needed file %s not found' % setup)
		if not os.path.isfile(setup):
			usage('%s: not a plain file' % setup)

	# check that enough arguments are passed
	if not args:
		usage('at least one filename argument required')

	# check that file arguments exist
	for arg in args:
		if not os.path.exists(arg):
			usage('argument %s not found' % arg)
		if not os.path.isfile(arg):
			usage('%s: not a plain file' % arg)

	# process non-option arguments
	scriptfile = args[0]
	modules = args[1:]

	# derive target name from script name
	base = os.path.basename(scriptfile)
	base, ext = os.path.splitext(base)
	if base:
		if base != scriptfile:
			target = base
		else:
			target = base + '.bin'

	# use temporary directory
	if tmpdir:
		try: os.mkdir(tmpdir, 0700)
		except os.error, errmsg:
			sys.stderr.write('mkdir: (%s) %s\n' % errmsg)
			sys.stderr.write('Error: cannot create temporary directory: %s\n' % (tmpdir,))
			sys.exit(2)
		frozen_c = os.path.join(tmpdir, frozen_c)
		config_c = os.path.join(tmpdir, config_c)
		makefile = os.path.join(tmpdir, makefile)

	dict = findmodules.findmodules(scriptfile, modules, path)

	# Actual work starts here...

	backup = frozen_c + '~'
	try:
		os.rename(frozen_c, backup)
	except os.error:
		backup = None
	outfp = open(frozen_c, 'w')
	try:
		makefreeze.makefreeze(outfp, dict)
	finally:
		outfp.close()
	if backup:
		if cmp.cmp(backup, frozen_c):
			sys.stderr.write('%s not changed, not written\n' %
					 frozen_c)
			os.rename(backup, frozen_c)

	builtins = []
	unknown = []
	mods = dict.keys()
	mods.sort()
	for mod in mods:
		if dict[mod] == '<builtin>':
			builtins.append(mod)
		elif dict[mod] == '<unknown>':
			unknown.append(mod)

	addfiles = []
	if unknown:
		addfiles, addmods = \
			  checkextensions.checkextensions(unknown, extensions)
		for mod in addmods:
			unknown.remove(mod)
		builtins = builtins + addmods
	if unknown:
		sys.stderr.write('Warning: unknown modules remain: %s\n' %
				 string.join(unknown))

	builtins.sort()
	infp = open(config_c_in)
	backup = config_c + '~'
	try:
		os.rename(config_c, backup)
	except os.error:
		backup = None
	outfp = open(config_c, 'w')
	try:
		makeconfig.makeconfig(infp, outfp, builtins)
	finally:
		outfp.close()
	infp.close()
	if backup:
		if cmp.cmp(backup, config_c):
			sys.stderr.write('%s not changed, not written\n' %
					 config_c)
			os.rename(backup, config_c)

	cflags = defines + includes + ['$(OPT)']
	libs = []
	for n in 'Modules', 'Python', 'Objects', 'Parser':
		n = 'lib%s.a' % n
		n = os.path.join(binlib, n)
		libs.append(n)

	makevars = parsesetup.getmakevars(makefile_in)
	somevars = {}
	for key in makevars.keys():
		somevars[key] = makevars[key]

	somevars['CFLAGS'] = string.join(cflags) # override
	files = ['$(OPT)', config_c, frozen_c, frozenmain_c] + \
		addfiles + libs + \
		['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)']

	backup = makefile + '~'
	try:
		os.rename(makefile, backup)
	except os.error:
		backup = None
	outfp = open(makefile, 'w')
	try:
		makemakefile.makemakefile(outfp, somevars, files, target)
	finally:
		outfp.close()
	if backup:
		if not cmp.cmp(backup, makefile):
			print 'previous Makefile saved as', backup

	# Done!

	if tmpdir:
		# Run make
		curdir = os.getcwd()
		os.chdir(tmpdir)
		status = os.system('make > /dev/null')
		os.chdir(curdir)

		if status:
			sys.stderr.write('Compilation failed. Files left in %s\n' % 
	 (tmpdir,))
		else:
			tmptarget = os.path.join(tmpdir, target)
			try: os.rename(tmptarget, target)
			except os.error:
				os.system('cp %s %s' % (tmptarget, target))
			os.system('rm -rf %s' % (tmpdir,))
			print 'Frozen target:', target
		tmpdir = None
	else:
		print 'Now run make to build the target:', target


# Print usage message and exit

def usage(msg = None):
	if msg:
		sys.stderr.write(str(msg) + '\n')
	sys.stderr.write(usage_msg)
	sys.exit(2)


try: main()
finally:
	if tmpdir:
		os.system('rm -rf %s' % (tmpdir,))