File: libraries.py

package info (click to toggle)
openmsx 0.10.1-2
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 16,628 kB
  • ctags: 19,723
  • sloc: cpp: 131,938; xml: 25,418; tcl: 15,394; python: 4,012; sh: 365; makefile: 26
file content (651 lines) | stat: -rw-r--r-- 19,129 bytes parent folder | download
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
# Some notes about static linking:
# There are two ways of linking to static library: using the -l command line
# option or specifying the full path to the library file as one of the inputs.
# When using the -l option, the library search paths will be searched for a
# dynamic version of the library, if that is not found, the search paths will
# be searched for a static version of the library. This means we cannot force
# static linking of a library this way. It is possible to force static linking
# of all libraries, but we want to control it per library.
# Conclusion: We have to specify the full path to each library that should be
#             linked statically.

from executils import captureStdout, shjoin

from os import listdir
from os.path import isdir, isfile
from os import environ

class Library(object):
	libName = None
	makeName = None
	header = None
	configScriptName = None
	dynamicLibsOption = '--libs'
	staticLibsOption = None
	function = None
	# TODO: A library can give an application compile time and run time
	#       dependencies on other libraries. For example SDL_ttf depends on
	#       FreeType only at run time, but depends on SDL both compile time
	#       and run time, since SDL is part of its interface and FreeType is
	#       only used by the implementation. As a result, it is possible to
	#       compile against SDL_ttf without having the FreeType headers
	#       installed. But our getCompileFlags() does not support this.
	#       In pkg-config these are called private dependencies.
	dependsOn = ()

	@classmethod
	def isSystemLibrary(cls, platform): # pylint: disable-msg=W0613
		'''Returns True iff this library is a system library on the given
		platform.
		A system library is a library that is available systemwide in the
		minimal installation of the OS.
		The default implementation returns False.
		'''
		return False

	@classmethod
	def getConfigScript( # pylint: disable-msg=W0613
		cls, platform, linkStatic, distroRoot
		):
		scriptName = cls.configScriptName
		if scriptName is None:
			return None
		elif platform == 'dingux' and cls.isSystemLibrary(platform):
			# TODO: A generic mechanism for locating config scripts in SDKs.
			#       Note that distroRoot is for non-system libs only.
			#       Trying a path relative to the compiler location would
			#       probably work well.
			return '/opt/a320-toolchain/usr/mipsel-a320-linux-uclibc/sysroot/usr/bin/%s' % scriptName
		elif distroRoot is None:
			return scriptName
		else:
			return '%s/bin/%s' % (distroRoot, scriptName)

	@classmethod
	def getHeaders(cls, platform): # pylint: disable-msg=W0613
		header = cls.header
		return header if hasattr(header, '__iter__') else (header, )

	@classmethod
	def getLibName(cls, platform): # pylint: disable-msg=W0613
		return cls.libName

	@classmethod
	def getCompileFlags(cls, platform, linkStatic, distroRoot):
		if platform == 'android':
			return environ['ANDROID_CXXFLAGS']
		configScript = cls.getConfigScript(platform, linkStatic, distroRoot)
		if configScript is not None:
			flags = [ '`%s --cflags`' % configScript ]
		elif distroRoot is None or cls.isSystemLibrary(platform):
			flags = []
		else:
			flags = [ '-I%s/include' % distroRoot ]
		dependentFlags = [
			librariesByName[name].getCompileFlags(
				platform, linkStatic, distroRoot
				)
			for name in cls.dependsOn
			]
		return ' '.join(flags + dependentFlags)

	@classmethod
	def getLinkFlags(cls, platform, linkStatic, distroRoot):
		if platform == 'android':
			return environ['ANDROID_LDFLAGS']
		configScript = cls.getConfigScript(platform, linkStatic, distroRoot)
		if configScript is not None:
			libsOption = (
				cls.dynamicLibsOption
				if not linkStatic or cls.isSystemLibrary(platform)
				else cls.staticLibsOption
				)
			if libsOption is not None:
				return '`%s %s`' % (configScript, libsOption)
		if distroRoot is None or cls.isSystemLibrary(platform):
			return '-l%s' % cls.getLibName(platform)
		else:
			flags = [
				'%s/lib/lib%s.a' % (distroRoot, cls.getLibName(platform))
				] if linkStatic else [
				'-L%s/lib -l%s' % (distroRoot, cls.getLibName(platform))
				]
			dependentFlags = [
				librariesByName[name].getLinkFlags(
					platform, linkStatic, distroRoot
					)
				for name in cls.dependsOn
				]
			systemDependentFlags = list(cls.getSystemDependentFlags(platform))
			return ' '.join(flags + dependentFlags + systemDependentFlags)

	@classmethod
	def getSystemDependentFlags(cls, platform):
		return ()

	@classmethod
	def getVersion(cls, platform, linkStatic, distroRoot):
		'''Returns the version of this library, "unknown" if there is no
		mechanism to retrieve the version, None if there is a mechanism
		to retrieve the version but it failed, or a callable that takes a
		CompileCommand and a log stream as its arguments and returns the
		version or None if retrieval failed.
		'''
		configScript = cls.getConfigScript(platform, linkStatic, distroRoot)
		if configScript is None:
			return 'unknown'
		else:
			return '`%s --version`' % configScript

class Expat(Library):
	libName = 'expat'
	makeName = 'EXPAT'
	header = '<expat.h>'
	function = 'XML_ParserCreate'

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android', 'dingux')

	@classmethod
	def getVersion(cls, platform, linkStatic, distroRoot):
		def execute(cmd, log):
			versionTuple = cmd.expand(
				log,
				cls.getHeaders(platform),
				'XML_MAJOR_VERSION', 'XML_MINOR_VERSION', 'XML_MICRO_VERSION'
				)
			return None if versionTuple is None else '.'.join(versionTuple)
		return execute

class FreeType(Library):
	libName = 'freetype'
	makeName = 'FREETYPE'
	header = ('<ft2build.h>', 'FT_FREETYPE_H')
	configScriptName = 'freetype-config'
	function = 'FT_Open_Face'

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android', 'dingux')

	@classmethod
	def getConfigScript(cls, platform, linkStatic, distroRoot):
		if platform in ('netbsd', 'openbsd'):
			if distroRoot == '/usr/local':
				# FreeType is located in the X11 tree, not the ports tree.
				distroRoot = '/usr/X11R6'
		return super(FreeType, cls).getConfigScript(
			platform, linkStatic, distroRoot
			)

	@classmethod
	def getVersion(cls, platform, linkStatic, distroRoot):
		configScript = cls.getConfigScript(platform, linkStatic, distroRoot)
		return '`%s --ftversion`' % configScript

class GL(Library):
	libName = 'GL'
	makeName = 'GL'
	function = 'glGenTextures'

	@classmethod
	def isSystemLibrary(cls, platform):
		# On *BSD, OpenGL is in ports, not in the base system.
		return not platform.endswith('bsd')

	@classmethod
	def getHeaders(cls, platform):
		if platform == 'darwin':
			return ('<OpenGL/gl.h>', )
		else:
			return ('<GL/gl.h>', )

	@classmethod
	def getCompileFlags(cls, platform, linkStatic, distroRoot):
		if platform in ('netbsd', 'openbsd'):
			return '-I/usr/X11R6/include -I/usr/X11R7/include'
		else:
			return super(GL, cls).getCompileFlags(
				platform, linkStatic, distroRoot
				)

	@classmethod
	def getLinkFlags(cls, platform, linkStatic, distroRoot):
		if platform == 'darwin':
			return '-framework OpenGL'
		elif platform == 'mingw32':
			return '-lopengl32'
		elif platform in ('netbsd', 'openbsd'):
			return '-L/usr/X11R6/lib -L/usr/X11R7/lib -lGL'
		else:
			return super(GL, cls).getLinkFlags(platform, linkStatic, distroRoot)

	@classmethod
	def getVersion(cls, platform, linkStatic, distroRoot):
		def execute(cmd, log):
			versionPairs = tuple(
				( major, minor )
				for major in range(1, 10)
				for minor in range(0, 10)
				)
			version = cmd.expand(log, cls.getHeaders(platform), *(
				'GL_VERSION_%d_%d' % pair for pair in versionPairs
				))
			try:
				return '%d.%d' % max(
					ver
					for ver, exp in zip(versionPairs, version)
					if exp is not None
					)
			except ValueError:
				return None
		return execute

class GLEW(Library):
	makeName = 'GLEW'
	header = '<GL/glew.h>'
	function = 'glewInit'
	dependsOn = ('GL', )

	@classmethod
	def getLibName(cls, platform):
		if platform == 'mingw32':
			return 'glew32'
		else:
			return 'GLEW'

	@classmethod
	def getCompileFlags(cls, platform, linkStatic, distroRoot):
		flags = super(GLEW, cls).getCompileFlags(
			platform, linkStatic, distroRoot
			)
		if platform == 'mingw32' and linkStatic:
			return '%s -DGLEW_STATIC' % flags
		else:
			return flags

class LibAO(Library):
	libName = 'ao'
	makeName = 'AO'
	header = '<ao/ao.h>'
	function = 'ao_open_live'

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android', 'dingux')

	@classmethod
	def getSystemDependentFlags(cls, platform):
		if platform in ('linux', 'dingux'):
			return ('-ldl', )
		elif platform == 'mingw32':
			return ('-lwinmm', )
		else:
			return ()

class LibPNG(Library):
	libName = 'png12'
	makeName = 'PNG'
	header = '<png.h>'
	configScriptName = 'libpng-config'
	dynamicLibsOption = '--ldflags'
	function = 'png_write_image'
	dependsOn = ('ZLIB', )

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android', 'dingux')

class LibXML2(Library):
	libName = 'xml2'
	makeName = 'XML'
	header = '<libxml/parser.h>'
	configScriptName = 'xml2-config'
	function = 'xmlParseDocument'
	dependsOn = ('ZLIB', )

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android',)

	@classmethod
	def getCompileFlags(cls, platform, linkStatic, distroRoot):
		flags = super(LibXML2, cls).getCompileFlags(
			platform, linkStatic, distroRoot
			)
		if not linkStatic or cls.isSystemLibrary(platform):
			return flags
		else:
			return flags + ' -DLIBXML_STATIC'

class OGG(Library):
	libName = 'ogg'
	makeName = 'OGG'
	header = '<ogg/ogg.h>'
	function = 'ogg_stream_init'

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android', 'dingux')

class SDL(Library):
	libName = 'SDL'
	makeName = 'SDL'
	header = '<SDL.h>'
	configScriptName = 'sdl-config'
	staticLibsOption = '--static-libs'
	function = 'SDL_Init'

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android', 'dingux')

class SDL_ttf(Library):
	libName = 'SDL_ttf'
	makeName = 'SDL_TTF'
	header = '<SDL_ttf.h>'
	function = 'TTF_OpenFont'
	dependsOn = ('SDL', 'FREETYPE')

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android', 'dingux')

	@classmethod
	def getVersion(cls, platform, linkStatic, distroRoot):
		def execute(cmd, log):
			version = cmd.expand(log, cls.getHeaders(platform),
				'SDL_TTF_MAJOR_VERSION',
				'SDL_TTF_MINOR_VERSION',
				'SDL_TTF_PATCHLEVEL',
				)
			return None if None in version else '%s.%s.%s' % version
		return execute

class SQLite(Library):
	libName = 'sqlite3'
	makeName = 'SQLITE'
	header = '<sqlite3.h>'
	function = 'sqlite3_prepare_v2'

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android', 'dingux')

	@classmethod
	def getVersion(cls, platform, linkStatic, distroRoot):
		def execute(cmd, log):
			version = cmd.expand(
				log, cls.getHeaders(platform), 'SQLITE_VERSION'
				)
			return None if version is None else version.strip('"')
		return execute

class TCL(Library):
	libName = 'tcl'
	makeName = 'TCL'
	header = '<tcl.h>'
	function = 'Tcl_CreateInterp'

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android',)

	@classmethod
	def getTclConfig(cls, platform, distroRoot):
		'''Tcl has a config script that is unlike the typical lib-config script.
		Information is gathered by sourcing the config script, instead of
		executing it and capturing the queried value from stdout. This script
		is located in a library directory, not in a directory in the PATH.
		Also, it does not have the executable bit set.
		This method returns the location of the Tcl config script, or None if
		it could not be found.
		'''
		if hasattr(cls, 'tclConfig'):
			# Return cached value.
			return cls.tclConfig

		def iterLocations():
			if platform == 'android':
				# Under Android, the tcl set-up apparently differs from
				# other cross-platform setups. the search algorithm to find the
				# directory that will contain the tclConfig.sh script and the shared libs
				# is not applicable to Android. Instead, immediately return the correct
				# subdirectories to the routine that invokes iterLocations()
				sdl_android_port_path = environ['SDL_ANDROID_PORT_PATH']
				libpath = sdl_android_port_path + '/project/libs/armeabi'
				yield libpath
				tclpath = sdl_android_port_path + '/project/jni/tcl8.5/unix'
				yield tclpath
			else:
				if distroRoot is None or cls.isSystemLibrary(platform):
					roots = ('/usr/local', '/usr')
				else:
					roots = (distroRoot, )
				for root in roots:
					if isdir(root):
						for libdir in ('lib', 'lib64', 'lib/tcl'):
							libpath = root + '/' + libdir
							if isdir(libpath):
								yield libpath
								for entry in listdir(libpath):
									if entry.startswith('tcl8.'):
										tclpath = libpath + '/' + entry
										if isdir(tclpath):
											yield tclpath

		tclConfigs = {}
		log = open('derived/tcl-search.log', 'w')
		print >> log, 'Looking for Tcl...'
		try:
			for location in iterLocations():
				path = location + '/tclConfig.sh'
				if isfile(path):
					print >> log, 'Config script:', path
					text = captureStdout(
						log,
						"sh -c '. %s && echo %s'" % (
							path, '$TCL_MAJOR_VERSION $TCL_MINOR_VERSION'
							)
						)
					if text is not None:
						try:
							# pylint: disable-msg=E1103
							major, minor = text.split()
							version = int(major), int(minor)
						except ValueError:
							pass
						else:
							print >> log, 'Found: version %d.%d' % version
							tclConfigs[path] = version
			try:
				# Minimum required version is 8.5.
				# Pick the oldest possible version to minimize the risk of
				# running into incompatible changes.
				tclConfig = min(
					( version, path )
					for path, version in tclConfigs.iteritems()
					if version >= (8, 5)
					)[1]
			except ValueError:
				tclConfig = None
				print >> log, 'No suitable versions found.'
			else:
				print >> log, 'Selected:', tclConfig
		finally:
			log.close()

		cls.tclConfig = tclConfig
		return tclConfig

	@classmethod
	def evalTclConfigExpr(cls, platform, distroRoot, expr, description):
		tclConfig = cls.getTclConfig(platform, distroRoot)
		if tclConfig is None:
			return None
		log = open('derived/tcl-search.log', 'a')
		try:
			print >> log, 'Getting Tcl %s...' % description
			text = captureStdout(
				log,
				shjoin([
					'sh', '-c',
						'. %s && eval "echo \\"%s\\""' % (tclConfig, expr)
					])
				)
			if text is not None:
				print >> log, 'Result: %s' % text.strip()
		finally:
			log.close()
		return None if text is None else text.strip()

	@classmethod
	def getCompileFlags(cls, platform, linkStatic, distroRoot):
		if platform == 'android':
			# Use the current ANDROID cross-compilation flags and not the TCL flags. Otherwise, the
			# wrong version of libstdc++ will end-up on the include path; the minimal Android NDK
			# version instead of the more complete GNU version. This is because TCL for Android has
			# been configured with the minimal libstdc++ on the include path in the C(XX) flags and
			# not with the more complete GNU version
			return environ['ANDROID_CXXFLAGS']
		wantShared = not linkStatic or cls.isSystemLibrary(platform)
		# The -DSTATIC_BUILD is a hack to avoid including the complete
		# TCL_DEFS (see 9f1dbddda2) but still being able to link on
		# MinGW (tcl.h depends on this being defined properly).
		return cls.evalTclConfigExpr(
			platform,
			distroRoot,
			'${TCL_INCLUDE_SPEC}' + ('' if wantShared else ' -DSTATIC_BUILD'),
			'compile flags'
			)

	@classmethod
	def getLinkFlags(cls, platform, linkStatic, distroRoot):
		if platform == 'android':
			# Use the current ANDROID cross-compilation flags and not the TCL flags to
			# prevent issues with libstdc++ version. See also getCompileFlags()
			return environ['ANDROID_LDFLAGS']
		# Tcl can be built as a shared or as a static library, but not both.
		# Check whether the library type of Tcl matches the one we want.
		wantShared = not linkStatic or cls.isSystemLibrary(platform)
		tclShared = cls.evalTclConfigExpr(
			platform,
			distroRoot,
			'${TCL_SHARED_BUILD}',
			'library type (shared/static)'
			)
		log = open('derived/tcl-search.log', 'a')
		try:
			if tclShared == '0':
				if wantShared:
					print >> log, (
						'Dynamic linking requested, but Tcl installation has '
						'static library.'
						)
					return None
			elif tclShared == '1':
				if not wantShared:
					print >> log, (
						'Static linking requested, but Tcl installation has '
						'dynamic library.'
						)
					return None
			else:
				print >> log, (
					'Unable to determine whether Tcl installation has '
					'shared or static library.'
					)
				return None
		finally:
			log.close()

		# Now get the link flags.
		if wantShared:
			return cls.evalTclConfigExpr(
				platform,
				distroRoot,
				'${TCL_LIB_SPEC}',
				'dynamic link flags'
				)
		else:
			return cls.evalTclConfigExpr(
				platform,
				distroRoot,
				'${TCL_EXEC_PREFIX}/lib/${TCL_LIB_FILE} ${TCL_LIBS}',
				'static link flags'
				)

	@classmethod
	def getVersion(cls, platform, linkStatic, distroRoot):
		return cls.evalTclConfigExpr(
			platform,
			distroRoot,
			'${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_PATCH_LEVEL}',
			'version'
			)

class Theora(Library):
	libName = 'theoradec'
	makeName = 'THEORA'
	header = '<theora/theoradec.h>'
	function = 'th_decode_ycbcr_out'
	dependsOn = ('OGG', )

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android', 'dingux')

class Vorbis(Library):
	libName = 'vorbis'
	makeName = 'VORBIS'
	header = '<vorbis/codec.h>'
	function = 'vorbis_synthesis_pcmout'
	dependsOn = ('OGG', )

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android', 'dingux')

class ZLib(Library):
	libName = 'z'
	makeName = 'ZLIB'
	header = '<zlib.h>'
	function = 'inflate'

	@classmethod
	def isSystemLibrary(cls, platform):
		return platform in ('android', 'dingux')

	@classmethod
	def getVersion(cls, platform, linkStatic, distroRoot):
		def execute(cmd, log):
			version = cmd.expand(log, cls.getHeaders(platform), 'ZLIB_VERSION')
			return None if version is None else version.strip('"')
		return execute

# Build a dictionary of libraries using introspection.
def _discoverLibraries(localObjects):
	for obj in localObjects:
		if isinstance(obj, type) and issubclass(obj, Library):
			if not (obj is Library):
				yield obj.makeName, obj
librariesByName = dict(_discoverLibraries(locals().itervalues()))

def allDependencies(makeNames):
	'''Compute the set of all directly and indirectly required libraries to
	build and use the given set of libraries.
	Returns the make names of the required libraries.
	'''
	# Compute the reflexive-transitive closure.
	transLibs = set()
	newLibs = set(makeNames)
	while newLibs:
		transLibs.update(newLibs)
		newLibs = set(
			depMakeName
			for makeName in newLibs
			for depMakeName in librariesByName[makeName].dependsOn
			if depMakeName not in transLibs
			)
	return transLibs