File size: 6,557 Bytes
b09157d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { maskCNonCode } from './cSyntaxHighlight.js';
// Clang's AST supplies statement boundaries and lexical scopes. The inserted
// hooks execute in the compiled program; source text is never interpreted as C.
const prefix = '__reachy_dbg_';
export const debugHeader = `
__attribute__((import_module("debug"), import_name("reset"))) void ${prefix}reset(void);
__attribute__((import_module("debug"), import_name("value"))) void ${prefix}value(const char*, const char*, const void*, unsigned);
__attribute__((import_module("debug"), import_name("pause"))) void ${prefix}pause(int, int, int, const char*);
static int ${prefix}depth;
static void ${prefix}leave(int *unused) { (void)unused; --${prefix}depth; }
`;

export function instrumentC(source, ast) {
  if (source.includes(prefix)) throw new Error('The __reachy_dbg_ prefix is reserved for the debugger.');
  const clean = maskCNonCode(source);
  const offsets = []; let byte = 0;
  for (let i = 0; i < source.length;) {
    const char = String.fromCodePoint(source.codePointAt(i));
    offsets[byte] = i; byte += new TextEncoder().encode(char).length; i += char.length;
  }
  offsets[byte] = source.length;
  const position = loc => offsets[(loc?.expansionLoc || loc)?.offset];
  const begin = node => position(node?.range?.begin);
  const end = node => {
    const loc = node?.range?.end?.expansionLoc || node?.range?.end;
    let at = offsets[loc?.offset + loc?.tokLen];
    // An expansion location names the macro, not its argument list.
    if (node?.range?.end?.expansionLoc) {
      const spaces = clean.slice(at).match(/^\s*/)[0].length;
      if (clean[at + spaces] === '(') {
        at += spaces; let balance = 0;
        do { if (clean[at] === '(') balance++; if (clean[at] === ')') balance--; at++; } while (at < clean.length && balance);
      }
    }
    return at;
  };
  const edits = new Map(), lines = new Set(); let site = 0;
  const insert = (at, text) => { if (!Number.isInteger(at)) throw new Error('Unsupported debug source location.'); edits.set(at, (edits.get(at) || '') + text); };
  const lineAt = at => source.slice(0, at).split('\n').length;
  const declarations = node => (node?.inner || []).filter(n => n.kind === 'VarDecl');
  const visible = vars => [...new Map(vars.filter(v => v.name).map(v => [v.name, v])).values()];
  const hook = (at, vars, fn) => {
    const line = lineAt(at); lines.add(line);
    const values = visible(vars).filter(v => v.storageClass !== 'register' && !/\[\]/.test(v.type?.qualType || '')).map(v => {
      const type = v.type.desugaredQualType || v.type.qualType;
      return `${prefix}value(${JSON.stringify(v.name)},${JSON.stringify(type)},(const void*)&${v.name},sizeof(${v.name}))`;
    });
    return `(${prefix}reset(),${values.length ? values.join(',') + ',' : ''}${prefix}pause(${line},${++site},${prefix}depth,${JSON.stringify(fn)}))`;
  };
  const expression = (node, vars, fn) => {
    if (!node?.kind) return;
    insert(begin(node), `(${hook(begin(node), vars, fn)},(`); insert(end(node), '))');
  };
  const statementEnd = node => {
    let at = end(node);
    // AST expression/return ranges omit the semicolon. Control-statement ranges
    // end at their last child; include that child's semicolon as well.
    if (source[at - 1] !== ';' && source[at - 1] !== '}') {
      const tail = source.slice(at).match(/^(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*;/);
      if (tail) at += tail[0].length;
    }
    return at;
  };
  function visit(node, vars, fn, wrap = false) {
    if (!node?.kind) return;
    const children = node.inner || [], at = begin(node);
    if (node.range?.begin?.expansionLoc) {
      insert(at, `${wrap ? '{' : ''}${hook(at, vars, fn)};`);
      if (wrap) insert(statementEnd(node), '}');
      return;
    }
    if (node.kind === 'CompoundStmt') {
      const locals = [...vars];
      for (const child of children) {
        visit(child, locals, fn);
        if (child.kind === 'DeclStmt') locals.push(...declarations(child));
      }
      insert(position(node.range.end), `${hook(position(node.range.end), locals, fn)};`);
      return;
    }
    if (['CaseStmt', 'DefaultStmt', 'LabelStmt'].includes(node.kind)) {
      visit(children.at(-1), vars, fn); return;
    }
    if (wrap) insert(at, '{');
    insert(at, `${hook(at, vars, fn)};`);
    if (node.kind === 'ForStmt') {
      const scope = [...vars, ...declarations(children[0])];
      expression(children[2], scope, fn);
      // for (;;) has no condition: insert a hook followed by true.
      if (!children[2]?.kind) {
        const from = children[0]?.kind ? end(children[0]) : source.indexOf('(', at) + 1;
        const separator = source.indexOf(';', source[from - 1] === ';' ? from : source.indexOf(';', from) + 1);
        insert(separator, `(${hook(at, scope, fn)},1)`);
      }
      visit(children.at(-1), scope, fn, true);
    } else if (node.kind === 'WhileStmt') {
      expression(children[0], vars, fn); visit(children.at(-1), vars, fn, true);
    } else if (node.kind === 'DoStmt') {
      visit(children[0], vars, fn, true); expression(children.at(-1), vars, fn);
    } else if (node.kind === 'IfStmt') {
      visit(children[1], vars, fn, true);
      if (children[2]) visit(children[2], vars, fn, true);
    } else if (node.kind === 'SwitchStmt') visit(children.at(-1), vars, fn, true);
    if (wrap) insert(statementEnd(node), '}');
  }
  const globals = [];
  for (const node of ast.inner || []) {
    if (node.loc?.includedFrom || node.loc?.file && !node.loc.file.endsWith('main.c')) continue;
    const at = position(node.loc);
    if (at === undefined || source.slice(at, at + (node.name?.length || 0)) !== node.name) continue;
    if (node.kind === 'VarDecl') globals.push(node);
    if (node.kind !== 'FunctionDecl') continue;
    const body = node.inner?.find(n => n.kind === 'CompoundStmt');
    if (!body) continue;
    if (body.range.begin.expansionLoc) throw new Error('Debugging a complete function body generated by a macro is not supported.');
    insert(begin(body) + 1, `int ${prefix}guard __attribute__((cleanup(${prefix}leave))) = ++${prefix}depth; (void)${prefix}guard;`);
    visit(body, [...globals, ...node.inner.filter(n => n.kind === 'ParmVarDecl')], node.name);
  }
  if (!site) throw new Error('No C function available for debugging.');
  let result = source;
  for (const [at, text] of [...edits].sort((a, b) => b[0] - a[0])) result = result.slice(0, at) + text + result.slice(at);
  return { source: debugHeader + '\n#line 1 "main.c"\n' + result, lines: [...lines].sort((a, b) => a - b) };
}