aboutsummaryrefslogtreecommitdiffstats
path: root/makewrappers
blob: 1166fe835642cb823bcba5504e872efbcbf3831e (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
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
#!/usr/bin/env python
'convert wrapfuncs.in to wrapper function stubs and tables'

import glob
import sys
import re
import os
import string
import datetime
import time
from string import Template

class SourceFile(object):
    "A template for creating a source file"

    def __init__(self, path):
	# default values...
	# no name or file yet
	self.name = ''
	self.sections = {}
	self.file = None
	self.path = None
	# open a new file for each function
	self.file_per_func = False

	# empty footer if none specified:
	self.sections['footer'] = []

	# lines appended to body by default
	self.sections['body'] = []
	current = self.sections['body']

        self.f = file(path, 'r')
	if not self.f:
	    return None
	for line in self.f:
	    line = line.rstrip()
	    if line.startswith('@'):
	        if ' ' in line:
	             leading, trailing = line.split(' ', 1)
	        else:
	             leading, trailing = line, None

	        if leading == '@name':
		    if not trailing:
		        raise Exception("@name requires a file name.")
	            self.path = trailing
		    if '$' in self.path:
		        self.file_per_func = True
	        else:
		    section = leading[1:]
		    if not section in self.sections:
		        self.sections[section] = []
		    current = self.sections[section]
	    else:
	        current.append(line)
	for section, data in self.sections.items():
	    self.sections[section] = Template("\n".join(data))

        # You need a file if this isn't a file-per-func
	if not self.file_per_func:
	    self.file = file(self.path, 'w')
	    if not self.file:
	        raise IOError("Couldn't open %s to read a template." % self.path)

    def __del__(self):
        if self.file:
	    self.file.close()

    def __repr__(self):
	strings = []
	if self.file_per_func:
            strings.append("path: %s (per func)" % self.path)
	else:
            strings.append("path: %s" % self.path)
	for name, data in self.sections.items():
	    strings.append("%s:" % name)
	    strings.append(data.safe_substitute({}))
	return "\n".join(strings)

    def emit(self, template, func = None):
	if self.file_per_func:
	    if not func:
	        # print "Must have a function to emit any part of a file-per-func template."
		return
	    path = Template(self.path).safe_substitute(func)
	    if os.path.exists(path):
	        # print "We don't overwrite existing files."
	        return
	    self.file = file(path, 'w')
	    if not self.file:
		print "Couldn't open '%s' (expanded from %s), not emitting '%s'." % (path, self.path, template)
	        return

	if template == "copyright":
	    # hey, at least it's not a global variable, amirite?
	    self.file.write(SourceFile.copyright)
	elif template in self.sections:
	    templ = self.sections[template]
	    self.file.write(templ.safe_substitute(func))
	    self.file.write("\n")
	else:
	    print "Warning: Unknown template '%s'." % template

	if self.file_per_func:
	    self.file.close()
	    self.file = None

class ArgumentList:
    "A (possibly empty) list of arguments"

    def __init__(self, text):
        "parse a comma-separated argument list (may contain function prototypes)"
        self.args = []
	self.variadic = False
	self.variadic_decl = ""
	self.variadic_start = ""
	self.variadic_end = ""
	self.prologue_call_real = "/* pass the call on to the underlying syscall */"
	# (void) is an empty list, not a list of a single argument which is void
	if text == "void":
	    return

        depth = 0
        accum = ''
        comma_sep = text.split(', ')
        # now, what if there was a comma embedded in an argument?
        for arg in comma_sep:
            lcount = arg.count('(')
            rcount = arg.count(')')
            depth = depth + lcount - rcount
            if (depth > 0):
                accum += arg + ', '
            else:
                self.args.append(C_Argument(accum + arg))
                accum = ''
        if depth != 0:
	    raise Exception("mismatched ()s while parsing '%s'" % text)
        if self.args[-1].vararg:
	    self.variadic = True
	    self.variadic_arg = self.args[-1]
	    self.last_fixed_arg = self.args[-2].name
	    self.variadic_decl = "va_list ap;\n"
	    self.variadic_start = "va_start(ap, %s);\n" % self.last_fixed_arg
	    if self.variadic_arg.vararg_wraps:
	        self.variadic_decl += "\t%s;\n" % self.variadic_arg.vararg_wraps.decl()
		self.variadic_start += "\t%s = va_arg(ap, %s);\n\tva_end(ap);\n" % (self.variadic_arg.name, self.variadic_arg.type)
	    else:
	        self.variadic_end = "va_end(ap);\n"
                self.prologue_call_real = '/* no way to pass a ... */\n\t\t\t\tassert(!"cannot chain to real versions of variadic functions");'

    def decl(self, **kw):
	if not self.args:
	    return "void"

	list = map(lambda x: x.decl(**kw), self.args)
        return ', '.join(list)

    def call(self):
        if not self.args:
	    return ""
	list = map(lambda x: x.call(), self.args)
	return ', '.join(list)

    def __repr__(self):
        if not self.args:
	    return "no arguments"
        else:
	    return '::'.join(map(lambda x:x.decl(), self.args))

    
class C_Argument:
    "A function argument such as 'char *path' or 'char (*foo)(void)'"
    def __init__(self, text):
        "get the type and name of a trivial C declaration"
	self.vararg = False
	self.function_pointer = False
	self.spacer = ''
	
	if text == 'void':
	    raise Exception("Tried to declare a nameless object of type void.")

	if text.startswith('...'):
	    self.vararg = True
	    if len(text) > 3:
		# we're a wrapper for something else, declared as
		# ...{real_decl}, as in the third argument to open(2)
		text = text[4:-1]
		# stash a copy of these values without the vararg flag, so we can
		# declare them prettily later
		self.vararg_wraps = C_Argument(text)
	    else:
		# nothing to do.
		self.vararg_wraps = None
	        self.type, self.name = None, None
		return
	else:
	    self.vararg = False

        # try for a function pointer
        match = re.match('(.*)\(\*([a-zA-Z0-9_]*)\)\((.*)\)', text)
        if match:
	    self.function_pointer = True
	    self.args = match.group(3)
            ret_type = match.group(1)
            args = match.group(3)
	    self.fulltype = "$ret_type(*)($args)"
	    self.name = match.group(2).rstrip(' ')
	    self.type = ret_type
	else:
            # plain declaration
            match = re.match('(.*[ *])\(?\*?([a-zA-Z0-9_]*)\)?', text)
            # there may not be a match, say in the special case where an arg is '...'
            if match:
	        self.type, self.name = match.group(1).rstrip(' '), match.group(2)
            else:
                self.type, self.name = None, None

	# spacing between type and name, needed if type ends with a character
	# which could be part of an identifier
	if re.match('[_a-zA-Z0-9]', self.type[-1]):
	    self.spacer = ' '

    def decl(self, **kw):
	comment = kw.get('comment', False)
	if self.function_pointer:
	    decl = "%s%s(*%s)(%s)" % (self.type, self.spacer, self.name, self.args)
	else:
            decl = "%s%s%s" % (self.type, self.spacer, self.name)

        if self.vararg:
	    if self.vararg_wraps:
	        if comment:
	            decl = "... { %s }" % decl
		else:
	            decl = "... /* %s */" % decl
	    else:
	        decl = "..."
	return decl

    def call(self):
	if self.type == 'void':
	    return ''

        if self.vararg and not self.vararg_wraps:
	    return "ap"

	return self.name

    def str(self):
        return self.decl()

    def __repr__(self):
        return self.decl()

class C_Function:
    "A function signature and additional data about how the function works"
    def __init__(self, line):
        # table of known default values:
        default_values = { 'gid_t': '0', 'uid_t': '0', 'int': '-1', 'long': '-1', 'ssize_t': '-1' }
    
        self.dirfd = 'AT_FDCWD'
        self.flags = '0'
        self.paths_to_munge = []
        # used for the copyright date when creating stub functions
        self.date = datetime.date.today().year
    
        function, comments = line.split(';')
        comment = re.search('/\* *(.*) *\*/', comments)
        if comment:
            self.comments = comment.group(1)
        else:
            self.comments = None
    
        bits = re.match('([^(]*)\((.*)\)', function)
	x = C_Argument(bits.group(1))
        self.type, self.name = x.type, x.name
	# it's convenient to have this declared here so we can use its .decl later
	if self.type != 'void':
	    self.rc = C_Argument("%s rc" % x.type)
    
        # Some args get special treatment:
        # * If the arg has a name ending in 'path', we will canonicalize it.
        # * If the arg is named 'dirfd' or 'flags', it becomes the default
        #   values for the dirfd and flags arguments when canonicalizing.
        # * Note that the "comments" field (/* ... */ after the decl) can
        #   override the dirfd/flags values.
        self.args = ArgumentList(bits.group(2))
        for arg in self.args.args:
	    # ignore varargs, they never get these special treatments
	    if arg.vararg:
	        pass
            elif arg.name == 'dirfd':
                self.dirfd = 'dirfd'
            elif arg.name == 'flags':
                self.flags = 'flags'
            elif arg.name[-4:] == 'path':
                self.paths_to_munge.append(arg.name)
    
	# pick default values
	if self.type == 'void':
	    self.default_value = ''
        elif self.type[-1:] == '*':
	    self.default_value = 'NULL'
	else:
	    try:
	        self.default_value = default_values[self.type]
            except KeyError:
	        raise Exception("Function %s has return type %s, for which there is no default value." % (self.name, self.type))

        # handle special comments, such as flags=AT_SYMLINK_NOFOLLOW
        if self.comments:
            modifiers = self.comments.split(', ')
            for mod in modifiers:
                key, value = mod.split('=')
                value = value.rstrip(' ')
                setattr(self, key, value)
    
    def comment(self):
        return self.decl(comment = True)
        
    def decl(self, **kw):
        if self.type[-1:] == '*':
	    spacer = ''
	else:
	    spacer = ' '
	return "%s%s%s(%s)" % (self.type, spacer, self.name, self.args.decl(**kw))

    def decl_args(self):
        return self.args.decl()

    def wrap_args(self):
        return self.args.decl(wrap = True)

    def call_args(self):
        return self.args.call()

    def alloc_paths(self):
        alloc_paths = []
	for p in self.paths_to_munge:
            alloc_paths.append("%s = pseudo_root_path(__func__, __LINE__, %s, %s, %s);" % (p, self.dirfd, p, self.flags))
	return "\n\t\t\t".join(alloc_paths);

    def free_paths(self):
        free_paths = []
	# the cast is here because free's argument isn't const qualified, but
	# the original path may have been -- but we only GET here if the path has
	# been overwritten.
	for p in self.paths_to_munge:
            free_paths.append("free((void *) %s);" % p)
	return "\n\t\t\t".join(free_paths);

    def rc_return(self):
        if self.type == 'void':
	    return "return;"
        else:
	    return "return rc;"

    def rc_decl(self):
        if self.type == 'void':
	    return ""
	else:
	    return "%s = %s;" % (self.rc.decl(), self.default_value)

    def rc_assign(self):
        if self.type == 'void':
	    return "(void)"
	else:
	    return "rc ="

    def def_return(self):
        if self.type == 'void':
	    return "return;"
	else:
	    return "return %s;" % self.default_value

    def __getitem__(self, key):
	"Make this object look like a dict for Templates to use"
	try:
            attr = getattr(self, key)
	except AttributeError:
	    # There's a few attributes that are handled inside the args object, so check there
	    # too...
	    attr = getattr(self.args, key)

	if callable(attr):
	    return attr()
	else:
	    return attr

    def __repr__(self):
        pretty = "%(name)s returns %(type)s and takes " % self
	pretty += repr(self.args)
        if self.comments:
            pretty += ' (%s)' % self.comments
	return pretty

files = {}

def main():
    funcs = []
    sources = []

    # error checking helpfully provided by the exception handler
    copyright_file = file('guts/COPYRIGHT', 'r')
    SourceFile.copyright = copyright_file.read()
    copyright_file.close()

    for path in glob.glob('templates/*'):
        try:
	    source = SourceFile(path)
	    source.emit('copyright')
	    source.emit('header')
	    sources.append(source)
	except IOError:
	    print "Invalid or malformed template %s.  Aborting." % path
	    exit(1)

    for filename in sys.argv[1:]:
        "parse the list of functions"
        sys.stdout.write("%s: " % filename)
        f = file(filename, 'r')
        for line in f:
            line = line.rstrip(" \r\n")
            if line.startswith('#') or line == "":
                continue
	    try:
                func = C_Function(line)
		funcs.append(func)
		sys.stdout.write(".")
	    except Exception as e:
		print "Parsing failed:", e
	    	exit(1)
        f.close()
	print ""

    # the per-function stuff
    print "Writing functions...",
    for func in funcs:
        "populate various tables and files with each function"
	for source in sources:
	    source.emit('body', func)
    print "done.  Cleaning up."
    
    for source in sources:
        "clean up files"
	source.emit('footer')
        del source

if __name__ == '__main__':
    main()