[go: up one dir, main page]

File: gen-autoargs.py

package info (click to toggle)
uftrace 0.17-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 5,264 kB
  • sloc: ansic: 49,132; python: 10,882; asm: 837; makefile: 760; cpp: 627; sh: 624; javascript: 191
file content (376 lines) | stat: -rwxr-xr-x 10,741 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python3

#
# Arguments / return type option tables generator for automatic value display
#
# Copyright (C) 2017, LG Electronics, Honggyu Kim <hong.gyu.kim@lge.com>
#
# Released under the GPL v2.
#

from __future__ import print_function

import re
import sys

# The syntax of C in Backus-Naur Form
#  https://cs.wmich.edu/~gupta/teaching/cs4850/sumII06/The%20syntax%20of%20C%20in%20Backus-Naur%20form.htm

# generated file name
argspec_file = "autoargs.h"

storage_class_specifier = ["auto", "register", "static", "extern", "typedef"]
type_qualifier = ["const", "volatile"]

type_specifier = ["void", "char", "short", "int", "long", "float", "double", \
                    "signed", "unsigned" ]

struct_or_union_specifier = ["struct", "union"]
enum_specifier = ["enum"]

typedef_name = [
        "size_t", "ssize_t", "pid_t", "uid_t", "off_t", "off64_t",
        "sigset_t", "socklen_t", "intptr_t", "nfds_t",
        "pthread_t", "pthread_once_t", "pthread_attr_t",
        "pthread_mutex_t", "pthread_mutexattr_t", "pthread_cond_t",
        "Lmid_t", "FILE", "in_addr_t",
    ]

artifitial_type = [ "funcptr_t", "oct_mode_t" ]

pointer = "*"
reference = "&"

type_specifier.extend(struct_or_union_specifier)
#type_specifier.extend(enum_specifier)
type_specifier.extend(typedef_name)
type_specifier.extend(["std::string"])
type_specifier.extend(artifitial_type)

header = """\
/*
 * Arguments / return type option tables for automatic value display
 *
 * This file is auto-generated by "gen-autoargs.py" based on prototypes.h
 */

"""

verbose = False

def parse_return_type(words):
    global storage_class_specifier
    global type_qualifier
    global struct_or_union_specifier
    global enum_specifier
    global pointer

    i = 0
    return_type = ""
    struct_or_union_flag = False
    for word in words:
        if word in storage_class_specifier:
            # skip <storage-class-specifier>
            pass
        elif word in type_qualifier:
            # skip <type-qualifier>
            pass
        elif word in struct_or_union_specifier:
            return_type = word
            struct_or_union_flag = True
        elif word in type_specifier:
            if return_type == "":
                return_type = word
            else:
                return_type += " " + word
        elif word == pointer:
            return_type += word
        elif word == reference:
            # skip reference
            pass
        elif struct_or_union_flag:
            return_type += " " + word
            struct_or_union_flag = False
        elif word == ",":
            pass
        else:
            break
        i += 1
    return (return_type, words[i:])


def parse_func_name(words):
    funcname = words[0]
    return (funcname, words[1:])


def parse_args(words):
    if words[0] != '(' and words[-1] != ')':
        return []   # fail

    arg_type = []
    enum_flag = False
    struct_or_union_flag = False
    for word in words[1:-1]:
        if word in type_qualifier:
            # skip <type-qualifier>
            pass
        elif word in struct_or_union_specifier:
            arg_type.append(word)
            struct_or_union_flag = True
        elif word in type_specifier:
            arg_type.append(word)
        elif word in enum_specifier:
            enum_flag = True
        elif word == pointer:
            arg_type[-1] += pointer
        elif word == reference:
            # skip reference
            pass
        elif struct_or_union_flag:
            struct_or_union_flag = False
            arg_type[-1] += " " + word
        elif enum_flag:
            enum_flag = False
            arg_type.append("enum " + word)
        elif word == ",":
            pass
        else:
            struct_or_union_flag = False
            enum_flag = False
    return arg_type


def parse_func_decl(func):
    chunks = re.split('[\s,;]+|([*()])', func)
    words = [x for x in chunks if x]
    (return_type, words) = parse_return_type(words)
    (funcname, words) = parse_func_name(words)
    args = parse_args(words)
    return (return_type, funcname, args)


DECL_TYPE_NONE = 0
DECL_TYPE_FUNC = 1
DECL_TYPE_ENUM = 2

def get_decl_type(line):
    # function should have parenthesis
    if line.find('(') >= 0:
        return DECL_TYPE_FUNC
    # or it should be enum
    if line.startswith('enum'):
        return DECL_TYPE_ENUM
    # error
    return DECL_TYPE_NONE

def make_uftrace_retval_format(ctype, funcname):
    retval_format = funcname + "@"

    if ctype == "void":
        retval_format = ""
        pass
    elif ctype == "int":
        retval_format += "retval/d32"
    elif ctype == "short":
        retval_format += "retval/d16"
    elif ctype == "char":
        retval_format += "retval/c"
    elif ctype == "float":
        retval_format += "retval/f32"
    elif ctype == "double":
        retval_format += "retval/f64"
    elif ctype == "char*":
        retval_format += "retval/s"
    elif ctype == "std::string":
        retval_format += "retval/S"
    elif ctype[-1] == "*":
        retval_format += "retval/p"
    elif ctype == "pid_t" or ctype == "uid_t":
        retval_format += "retval/i32"
    elif "unsigned" in ctype or ctype == "size_t":
        retval_format += "retval/u"
    elif ctype == "funcptr_t":
        retval_format += "retval/p"
    elif ctype == "oct_mode_t":
        retval_format += "retval/o"
    elif ctype == "off64_t":
        retval_format += "retval/d64"
    elif ctype.startswith('enum'):
        retval_format += "retval/e:%s" % ctype[5:]
    else:
        retval_format += "retval"

    return retval_format


def make_uftrace_args_format(args, funcname):
    args_format = funcname + "@"

    i = 0
    f = 1
    for arg in args:
        i += 1
        if (i > 1):
            args_format += ","
        if arg == "void":
            args_format = ""
            break
        elif arg == "int":
            args_format += "arg%d/d32" % i
        elif arg == "short":
            args_format += "arg%d/d16" % i
        elif arg == "char":
            args_format += "arg%d/c" % i
        elif arg == "float":
            args_format += "fparg%d/32" % f
            f += 1
            i -= 1
        elif arg == "double":
            args_format += "fparg%d/64" % f
            f += 1
            i -= 1
        elif arg == "char*":
            args_format += "arg%d/s" % i
        elif arg == "std::string":
            args_format += "arg%d/S" % i
        elif arg[-1] == "*":
            args_format += "arg%d/p" % i
        elif arg == "pid_t" or arg == "uid_t":
            args_format += "arg%d/i32" % i
        elif "unsigned" in arg or arg == "size_t":
            args_format += "arg%d/u" % i
        elif arg == "funcptr_t":
            args_format += "arg%d/p" % i
        elif arg == "oct_mode_t":
            args_format += "arg%d/o" % i
        elif arg == "off64_t":
            args_format += "arg%d/d64" % i
        elif arg.startswith('enum'):
            args_format += "arg%d/e:%s" % (i, arg[5:])
        else:
            args_format += "arg%d" % i

    return args_format


def parse_enum(line):
    # is this the final line (including semi-colon)
    if line.find(';') >= 0:
        return (DECL_TYPE_NONE, ' '.join(line.split()))

    # continue to parse next line
    return (DECL_TYPE_ENUM, ' '.join(line.split()))


def parse_argument():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input-file", dest='infile', default="prototypes.h",
                        help="input prototype header file (default: prototypes.h")
    parser.add_argument("-o", "--output-file", dest='outfile', default="autoargs.h",
                        help="output uftrace argspec file (default: autoargs.h)")
    parser.add_argument("-v", "--verbose", dest='verbose', action='store_true',
                        help="show internal command and result for debugging")

    return parser.parse_args()


if __name__ == "__main__":
    arg = parse_argument()
    if arg.verbose:
        print(arg)

    argspec_file = arg.outfile
    prototype_file = arg.infile
    verbose = arg.verbose

    enum_list = ""
    args_list = ""
    retvals_list = ""

    # operator new and delete and their variations
    args_list     = '\t\"_Znwm@arg1/u;\"\n'   \
                  + '\t\"_Znam@arg1/u;\"\n'   \
                  + '\t\"_ZdlPv@arg1/x;\"\n'  \
                  + '\t\"_ZdaPv@arg1/x;\"\n'

    # operator new and its variations
    retvals_list  = '\t\"_Znwm@retval/x;\"\n' \
                  + '\t\"_Znam@retval/x;\"\n'

    t = DECL_TYPE_NONE
    with open(prototype_file) as fin:
        for line in fin:
            if len(line) <= 1 or line[0] == '#' or line[0:2] == "//" \
                    or line[0:7] == "typedef":
                continue

            if verbose:
                print(line, end='')

            if t == DECL_TYPE_ENUM:
                (t, curr) = parse_enum(line)
                enum_format += curr
                if t == DECL_TYPE_NONE:
                    enum_list += '\t"' + enum_format + '"\n'
                continue

            t = get_decl_type(line)
            if t == DECL_TYPE_NONE:
                continue
            if t == DECL_TYPE_ENUM:
                (t, enum_format) = parse_enum(line)
                if t == DECL_TYPE_NONE:
                    enum_list += '\t"' + enum_format + '"\n'
                continue

            (return_type, funcname, args) = parse_func_decl(line)
            if verbose:
                print(args)

            retval_format = make_uftrace_retval_format(return_type, funcname)
            args_format = make_uftrace_args_format(args, funcname)

            if verbose:
                print("ret : " + retval_format)
                print("arg : " + args_format)
                print("")

            if retval_format:
                retvals_list += '\t"' + retval_format + ';"\n'
            if args_format:
                args_list += '\t"' + args_format + ';"\n'

    if verbose:
        print(enum_list)
        print(args_list)
        print(retvals_list)

    if argspec_file == "-":
        fout = sys.stdout
    else:
        fout = open(argspec_file, "w")

    fout.write(header)

    if len(enum_list) == 0:
        enum_list="\"\""

    fout.write("/* clang-format off */\n\n")
    fout.write("static char *auto_enum_list =\n")
    fout.write(enum_list)
    fout.write(";\n\n")

    fout.write("static char *auto_args_list =\n")
    fout.write(args_list)
    fout.write(";\n\n")

    fout.write("static char *auto_retvals_list =\n")
    fout.write(retvals_list)
    fout.write(";\n\n")
    fout.write("/* clang-format on */\n")

    if argspec_file != "-":
        fout.close()