File: check-ast-context.py

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (444 lines) | stat: -rwxr-xr-x 14,886 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
#!/usr/bin/env python

import sys
import subprocess
import os
import os.path
import argparse
import json
import hashlib


class Hasher(object):

    @classmethod
    def from_file(cls, file):
        hl = hashlib.md5()
        hl.update(file.read())
        return hl.hexdigest()


class IncludePath(object):

    def __init__(self, path):
        self.path = path

    def to_arg(self):
        return ['-I', self.path]


class Macro(object):

    def __init__(self, macro):
        self.macro = macro

    def to_arg(self):
        return ['-D%s' % self.macro]


class SDKRoot(object):

    def __init__(self, root):
        self.root = root

    def to_arg(self):
        return ['-isysroot', self.root]


class CPP11(object):

    def __init__(self):
        pass

    def to_arg(self):
        return ['-x', 'c++', '-std=c++11']


class Parser(object):

    def __init__(self, parser):
        self.parser = parser
        self.cursor = self.parser.cursor

    def find_if_impl(self, cursor, f):
        results = []
        if f(cursor):
            results.append(cursor)
        for c in cursor.get_children():
            results += self.find_if_impl(c, f)
        return results

    def find_if(self, f):
        return self.find_if_impl(self.cursor, f)

    def diagnostics(self):
      return self.parser.diagnostics

class Index(object):

    def __init__(self):
        self.index = clang.cindex.Index(
            clang.cindex.conf.lib.clang_createIndex(
                False, True))

    def parse(self, file, options):
        opts = []
        for opt in options:
            opts += opt.to_arg()
        return Parser(self.index.parse(file, opts))


def get_args():
    parser = argparse.ArgumentParser(
        description="Validate that methods of LLDB SwiftASTContext have proper VALID_OR_RETURN macros in place before accessing the underlying swift::ASTContext object (which is unsafe to touch in the face of fatal errors)\n" +
        "The expected pattern for methods in SwiftASTContext is usually of the form:\n" +
        "int SwiftASTContext::GetMagicThing(bool doit) {\n" +
        "  VALID_OR_RETURN(0);\n" +
        "  return GetASTContext()->getMagicThing(doit);\n"
        "}\n" +
        "and a missing VALID_OR_RETURN for methods that do access the AST context can be a source of debugger crashes.\n" +
        "The script is able to automatically figure out if a method is doing operations that require validation, as well as discern VALID_OR_RETURN vs. VALID_OR_RETURN_VOID as the macro to insert\n"+
        "For the obvious reason, the script will only validate instance methods of SwiftASTContext as located in SwiftASTContext.h or SwiftASTContext.cpp, so please don't split methods across files without adjusting this script first\n" +
        "The first run of this script may take up to a minute. Subsequent runs against an unmodified SwiftASTContext.cpp are instantaneous. This is done by storing the MD5 hash of SwiftASTContext.cpp inside check-ast-context.md5 in the build products directory. A missing MD5 file, or any changes in SwiftASTContext.cpp will trigger a full validation.",
        epilog="For reference to how to pass proper arguments to the script, one should refer to the LLDB Xcode project, namely to the 'Check AST Context' build phase of lldb-core.\n" +
        "This script is meant to cause the build process of LLDB to fail if it detects missing checks where it expects one. The script is usually right, but sometimes can trigger on a path that is inherently safe, but deciding that requires human smarts. In order to override the automated detection, you should add the name of the method you know to be safe to the whitelist variable in this file.\n" +
        "This script tries to be smart about the location of build products and sources (for CMake vs. Xcode builds mostly), but any changes to the layout of an LLDB checkout might and probably will require changes here\n" +
        "Also, keep in mind that this script is only tested to run on macOS. This was deemed a safe tradeoff as nothing in the AST context validation should be platform-specific. If it needs to run on Linux, changes may be required",
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        '--file',
        type=str,
        help='path to SwiftASTContext.cpp',
        required=True)
    parser.add_argument(
        '--llvmbuild',
        type=str,
        help='location of the LLVM build tree',
        required=True)
    parser.add_argument(
        '--llvmbarch',
        type=str,
        help='LLVM build directory architecture',
        default=None)
    parser.add_argument(
        '--lldbbuild',
        type=str,
        help='location of the LLDB build tree',
        required=True)
    parser.add_argument(
        '--swiftbuild',
        type=str,
        help='location of the Swift build tree',
        required=True)
    parser.add_argument(
        '--sdk',
        type=str,
        help='location of the SDK root',
        default=None)
    parser.add_argument('--verbose', type=bool, help='verbose output')

    return parser.parse_args(sys.argv[1:])


def detect_source_layout(args):
    args.lldb = os.path.abspath(
        os.path.join(
            os.path.dirname(
                args.file),
            '..',
            '..'))
    args.header = os.path.join(
        args.lldb,
        'include',
        'lldb',
        'Symbol',
        'SwiftASTContext.h')
    if not(
        os.path.exists(
            os.path.join(
            args.llvmbuild,
            'lib',
            'libclang.dylib'))):
        if os.path.exists(
            os.path.join(
                args.llvmbuild,
                args.llvmbarch,
                'lib',
                'libclang.dylib')):
            args.llvmbuild = os.path.join(args.llvmbuild, args.llvmbarch)
    if not(os.path.exists(args.swiftbuild)):
      args.swiftbuild = os.path.abspath(os.path.join(args.llvmbuild,'..',args.llvmbarch.replace('llvm','swift')))
      if not(os.path.exists(args.swiftbuild)):
        return False
    if os.path.isdir(
        os.path.join(
            args.lldb,
            'llvm')) and os.path.isdir(
            os.path.join(
                args.lldb,
                'llvm',
                'tools',
                'clang')) and os.path.isdir(
                    os.path.join(
                        args.lldb,
                        'llvm',
                        'tools',
                        'swift')):
        args.source = args.lldb
        args.llvm = os.path.join(args.source, 'llvm')
        args.clang = os.path.join(args.source, 'llvm', 'tools', 'clang')
        args.swift = os.path.join(args.source, 'llvm', 'tools', 'swift')
        return True
    args.parent = os.path.abspath(os.path.join(args.lldb, '..'))
    if os.path.isdir(os.path.join(args.parent, 'lldb')) and \
       os.path.isdir(os.path.join(args.parent, 'swift')) and \
       os.path.isdir(os.path.join(args.parent, 'clang')) and \
       os.path.isdir(os.path.join(args.parent, 'llvm')):
        args.source = args.parent
        args.swift = os.path.join(args.source, 'swift')
        args.clang = os.path.join(args.source, 'clang')
        args.llvm = os.path.join(args.source, 'llvm')
        return True
    if args.verbose:
        print('arg dictionary = %s' % args)
    return False


def makehashes(args):
    hashes = {}
    with open(args.file) as f:
        hashes['cpp'] = Hasher.from_file(f)
    with open(args.header) as f:
        hashes['h'] = Hasher.from_file(f)
    return hashes


def readhashes(args):
    try:
        p = os.path.join(args.lldbbuild, 'check-ast-context.md5')
        if os.path.exists(p):
            with open(p, 'r') as f:
                return json.load(f)
    finally:
        pass
    return None


def comparehashes(args):
    made = makehashes(args)
    read = readhashes(args)
    if read is None:
        return False
    made_cpp = made.get('cpp')
    read_cpp = read.get('cpp')
    if made_cpp is None or read_cpp is None:
        return False
    if made_cpp != read_cpp:
        return False
    made_h = made.get('h')
    read_h = read.get('h')
    if made_h is None or read_h is None:
        return False
    if made_h != read_h:
        return False
    return True


def writehashes(args):
    try:
        hashes = makehashes(args)
        p = os.path.join(args.lldbbuild, 'check-ast-context.md5')
        with open(p, 'w') as f:
            json.dump(hashes, f)
    finally:
        pass


def init_libclang(src_path, lib_path):
    def look_for_node(cursor, f):
        if not cursor:
            return None
        if not f:
            return None
        if f(cursor):
            return cursor
        for c in cursor.get_children():
            w = look_for_node(c, f)
            if w:
                return w
        return None

    def printtree(node, depth=0):
        d = '  ' * depth
        print('%s%s (%s)') % (d, node.pretty_print(), node.kind)
        for c in node.get_children():
            printtree(c, depth + 1)

    try:
        globals()['clang'] = __import__('clang')
        globals()['clang.cindex'] = __import__('clang.cindex')
    except:
        sys.path.insert(1, src_path)
        try:
            globals()['clang'] = __import__('clang')
            globals()['clang.cindex'] = __import__('clang.cindex')
        except:
            return False
    clang.cindex.Config.set_library_path(lib_path)
    clang.cindex.Cursor.pretty_print = lambda self: (
        self.spelling or self.displayname or self.mangled_name)
    clang.cindex.Cursor.search = look_for_node
    clang.cindex.Cursor.dump = lambda self: printtree(self, depth=0)
    return True

def compute_libcpp_include_path():
    clang = subprocess.check_output(['xcrun', '-f', 'clang']).strip()
    # Remove /bin/clang
    base = os.path.dirname(os.path.dirname(clang))
    return os.path.join(base, "include", "c++", "v1")

def main():
    args = get_args()
    if not args.sdk:
        args.sdk = subprocess.check_output(
            'xcrun --sdk macosx --show-sdk-path', shell=True).strip()
    detect_source_layout(args)
    if comparehashes(args):
        if args.verbose:
            print('MD5 matches; skipping check')
        return 0
    src_path = os.path.join(args.clang, 'bindings', 'python')
    lib_path = os.path.join(args.llvmbuild, 'lib')
    if not init_libclang(src_path, lib_path):
        print('libclang initialization failed - please try again')

    index = Index()

    macros = [
        Macro(x) for x in [
            '__STDC_CONSTANT_MACROS',
            '__STDC_LIMIT_MACROS']]
    includes = [IncludePath(x) for x in [
        os.path.join(os.path.abspath(args.llvm), 'include'),
        os.path.join(os.path.abspath(args.clang), 'include'),
        os.path.join(os.path.abspath(args.swift), 'include'),
        os.path.join(os.path.abspath(args.lldb), 'include'),
        os.path.join(os.path.abspath(args.lldb), 'source'),
        os.path.join(os.path.abspath(args.llvmbuild), 'include'),
        os.path.join(os.path.abspath(args.llvmbuild), 'tools', 'clang', 'include'),
        os.path.join(os.path.abspath(args.swiftbuild), 'include'),
        compute_libcpp_include_path(),
    ]]
    lang = [CPP11()]
    sdk = [SDKRoot(args.sdk)]
    parser = index.parse(
        args.file,
        macros + lang + sdk + includes)

    failed = False

    for diag in parser.diagnostics():
      if diag.severity < clang.cindex.Diagnostic.Error:
        if args.verbose:
          print(str(diag))
      else:
        print(str(diag))
        failed = True
    if failed:
      sys.exit(1)

    def search_lambda(cursor):
        try:
            if not (cursor.kind == clang.cindex.CursorKind.CXX_METHOD):
                return False
            parent = cursor.semantic_parent
            if not ((parent.spelling or parent.displayname)
                    == 'SwiftASTContext'):
                return False
            if not (cursor.is_definition()):
                return False
            if (cursor.is_static_method()):
                return False
            return True
        except:
            return False

    methods = parser.find_if(search_lambda)

    FAIL = 0

    def emit_fail(method):
        print(
            '%s:%s:%s: error: %s not found on method \'%s\'; consider adding (or whitelisting if necessary, --help for further information)' %
            (os.path.basename(
                method.location.file.name),
                method.location.line,
                method.location.column,
                ('VALID_OR_RETURN_VOID' if method.result_type.kind == clang.cindex.TypeKind.VOID else 'VALID_OR_RETURN'),
                method.pretty_print()))

    def scan(method):
        look_for_COMPOUND_STMT = lambda c: c.kind == clang.cindex.CursorKind.COMPOUND_STMT
        look_for_DO_STMT = lambda c: c.kind == clang.cindex.CursorKind.DO_STMT
        look_for_CALL_EXPR = lambda c: c.kind == clang.cindex.CursorKind.CALL_EXPR
        look_for_MEMBER_REF_EXPR = lambda c: c.kind == clang.cindex.CursorKind.MEMBER_REF_EXPR
        compound_stmt = method.search(look_for_COMPOUND_STMT)
        if not compound_stmt:
            return False
        do_stmt = compound_stmt.search(look_for_DO_STMT)
        if not do_stmt:
            return False
        call_expr = do_stmt.search(look_for_CALL_EXPR)
        if not call_expr:
            return False
        member_ref_expr = call_expr.search(look_for_MEMBER_REF_EXPR)
        if not member_ref_expr:
            return False
        if member_ref_expr.pretty_print() == 'HasFatalErrors':
            return True
        return False

    def is_safe(method):
        def look_for_IVAR(c):
            if c.kind == clang.cindex.CursorKind.MEMBER_REF_EXPR:
                if c.pretty_print() == 'm_ast_context_ap':
                    return True
            return False

        def look_for_METHOD(c):
            if c.kind == clang.cindex.CursorKind.CALL_EXPR:
                if c.pretty_print() == 'GetASTContext':
                    return True
            return False
        unsafe = method.search(
            lambda c: look_for_IVAR(c) or look_for_METHOD(c))
        return (unsafe is None)

    whitelist = [
        'GetPluginName',
        'HasFatalErrors',
        'GetFatalErrors',
        'PrintDiagnostics',
        'GetASTContext',
        'SetTriple',
        'LogConfiguration'
    ]

    for method in methods:
        if method.pretty_print() in whitelist:
            continue
        try:
            if not scan(method) and not is_safe(method):
                emit_fail(method)
                FAIL += 1
        except Exception as e:
            print(e)
            emit_fail(method)
            FAIL += 1

    if FAIL == 0:
        writehashes(args)
    return FAIL

if main() > 0:
    sys.exit(1)