-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathrtos-rtthread.ts
More file actions
380 lines (345 loc) · 13.8 KB
/
Copy pathrtos-rtthread.ts
File metadata and controls
380 lines (345 loc) · 13.8 KB
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
/* eslint-disable @typescript-eslint/naming-convention */
import * as vscode from 'vscode';
import { DebugProtocol } from '@vscode/debugprotocol';
import * as RTOSCommon from './rtos-common';
type ThreadState =
| 'INITIALIZED'
| 'CLOSED'
| 'READY'
| 'RUNNING'
| 'SUSPENDED'
| 'SUSPENDED (KILLABLE)'
| 'SUSPENDED (UNINTERRUPTIBLE)'
| 'UNKNOWN';
const ThreadTableItems: { [key: string]: RTOSCommon.DisplayColumnItem } = {
name: {
width: 2,
headerRow1: 'Thread',
headerRow2: 'Name',
},
address: {
width: 2,
headerRow1: '',
headerRow2: 'Address',
},
state: {
width: 2,
headerRow1: '',
headerRow2: 'State',
},
priority: {
width: 1,
headerRow1: 'Priority',
headerRow2: 'Current / Init',
colType: RTOSCommon.ColTypeEnum.colTypeNumeric,
},
tick: {
width: 1,
headerRow1: 'Time Slice',
headerRow2: 'Remain / Init',
colType: RTOSCommon.ColTypeEnum.colTypeNumeric,
},
error: {
width: 1,
headerRow1: '',
headerRow2: 'Error',
colType: RTOSCommon.ColTypeEnum.colTypeNumeric,
colGapAfter: 1,
},
stack: {
width: 4,
headerRow1: 'Stack',
headerRow2: 'Current Usage',
colType: RTOSCommon.ColTypeEnum.colTypePercentage,
},
stackPeak: {
width: 4,
headerRow1: 'Stack',
headerRow2: 'Peak Usage',
colType: RTOSCommon.ColTypeEnum.colTypePercentage,
},
};
const ThreadTableItemNames = Object.keys(ThreadTableItems);
/**
* RT-Thread thread view.
*
* Threads are discovered through the kernel object container instead of a
* firmware-side helper table. Member offsets are resolved by the debugger,
* so the provider follows the exact layout described by the ELF debug info.
*/
export class RTOSRTThread extends RTOSCommon.RTOSBase {
private static readonly MAX_THREADS = 256;
private static readonly MAX_STACK_READ = 16 * 1024 * 1024;
private containerSymbol = '';
private hasSchedulerContext = true;
private listHead: RTOSCommon.RTOSVarHelperMaybe;
private objectListOffset: RTOSCommon.RTOSVarHelperMaybe;
private currentThread: RTOSCommon.RTOSVarHelperMaybe;
private threads: RTOSCommon.RTOSThreadInfo[] = [];
private timeInfo = '';
constructor(public session: vscode.DebugSession) {
super(session, 'RT-Thread');
}
public async tryDetect(useFrameId: number): Promise<RTOSCommon.RTOSBase> {
this.progStatus = 'stopped';
try {
if (this.status !== 'none') {
return this;
}
const modernListHead = await this.getVarIfEmpty(
undefined,
useFrameId,
'&_object_container[0].object_list',
true,
);
if (modernListHead) {
this.containerSymbol = '_object_container';
this.listHead = modernListHead;
} else {
const legacyListHead = await this.getVarIfEmpty(
undefined,
useFrameId,
'&rt_object_container[0].object_list',
true,
);
if (!legacyListHead) {
throw new Error('RT-Thread object container was not found');
}
this.containerSymbol = 'rt_object_container';
this.listHead = legacyListHead;
}
this.objectListOffset = await this.getVarIfEmpty(
this.objectListOffset,
useFrameId,
'(unsigned long)&((struct rt_thread *)0)->parent.list',
false,
);
const schedulerContext = await this.getVarIfEmpty(
undefined,
useFrameId,
'&((struct rt_thread *)0)->sched_thread_ctx.stat',
true,
);
this.hasSchedulerContext = schedulerContext !== null;
this.currentThread = await this.getVarIfEmpty(
this.currentThread,
useFrameId,
'_cpu.current_thread',
true,
);
if (!this.currentThread) {
this.currentThread = await this.getVarIfEmpty(
this.currentThread,
useFrameId,
'_cpus[0].current_thread',
true,
);
}
if (!this.currentThread) {
this.currentThread = await this.getVarIfEmpty(
this.currentThread,
useFrameId,
'rt_current_thread',
true,
);
}
this.status = 'initialized';
} catch (e) {
if (e instanceof RTOSCommon.ShouldRetry) {
console.error(e.message);
} else {
this.status = 'failed';
this.failedWhy = e;
console.error('RTOSRTThread.tryDetect() failed: ', e);
}
}
return this;
}
public async refresh(frameId: number): Promise<void> {
if (this.progStatus !== 'stopped' || !this.listHead || !this.objectListOffset || !this.containerSymbol) {
return;
}
try {
const headAddress = this.parseNumber(await this.listHead.getValue(frameId));
const listOffset = this.parseNumber(await this.objectListOffset.getValue(frameId));
const container = `${this.containerSymbol}[0]`;
let nodeAddress = this.parseNumber(await this.getExprVal(`${container}.object_list.next`, frameId));
const currentAddress = this.currentThread
? this.parseNumber(await this.currentThread.getValue(frameId))
: undefined;
if (headAddress === undefined || listOffset === undefined || nodeAddress === undefined) {
throw new Error('Unable to read the RT-Thread object list');
}
const found: RTOSCommon.RTOSThreadInfo[] = [];
const visited = new Set<number>();
while (
nodeAddress !== headAddress &&
nodeAddress !== 0 &&
!visited.has(nodeAddress) &&
found.length < RTOSRTThread.MAX_THREADS
) {
visited.add(nodeAddress);
const threadAddress = nodeAddress - listOffset;
found.push(await this.readThread(threadAddress, currentAddress, frameId));
nodeAddress = this.parseNumber(
await this.getExprVal(
`((struct rt_thread *)${RTOSCommon.hexFormat(threadAddress)})->parent.list.next`,
frameId,
),
);
if (nodeAddress === undefined) {
throw new Error('Unable to read the next RT-Thread object list node');
}
}
this.threads = found;
this.timeInfo = new Date().toLocaleTimeString();
} catch (e) {
console.error('RTOSRTThread.refresh() failed: ', e);
}
}
public getHTML(): RTOSCommon.HtmlInfo {
if (this.threads.length === 0) {
return {
html: `
<div>
<div><strong>RT-Thread threads not found</strong></div>
<div>
No thread objects are currently present. The kernel may not have reached
<code>rtthread_startup()</code> yet.
</div>
</div>`,
css: '',
};
}
return this.getHTMLThreads(ThreadTableItemNames, ThreadTableItems, this.threads, this.timeInfo);
}
private async readThread(
threadAddress: number,
currentAddress: number | undefined,
frameId: number,
): Promise<RTOSCommon.RTOSThreadInfo> {
const ptr = `((struct rt_thread *)${RTOSCommon.hexFormat(threadAddress)})`;
const scheduler = this.hasSchedulerContext ? 'sched_thread_ctx.' : '';
const schedulerPrivate = this.hasSchedulerContext
? 'sched_thread_ctx.sched_thread_priv.'
: '';
const [nameValue, stateValue, currentPriority, initPriority, remainingTick, initTick, errorValue] =
await Promise.all([
this.getExprVal(`(char *)&${ptr}->parent.name`, frameId),
this.getExprVal(`(unsigned int)${ptr}->${scheduler}stat`, frameId),
this.getExprVal(`(unsigned int)${ptr}->${schedulerPrivate}current_priority`, frameId),
this.getExprVal(`(unsigned int)${ptr}->${schedulerPrivate}init_priority`, frameId),
this.getExprVal(`(unsigned long)${ptr}->${schedulerPrivate}remaining_tick`, frameId),
this.getExprVal(`(unsigned long)${ptr}->${schedulerPrivate}init_tick`, frameId),
this.getExprVal(`(long)${ptr}->error`, frameId),
]);
const rawState = this.parseNumber(stateValue) ?? 0xff;
const running = currentAddress !== undefined
? threadAddress === currentAddress
: (rawState & 0x07) === 0x03;
const stackInfo = await this.readStackInfo(ptr, frameId);
const stackUsage = this.formatStackUsage(stackInfo.stackUsed, stackInfo.stackSize);
const stackPeak = RTOSCommon.RTOSBase.disableStackPeaks
? { text: '----', value: undefined }
: this.formatStackUsage(stackInfo.stackPeak, stackInfo.stackSize);
return {
display: {
name: { text: this.stringFromGdb(nameValue) },
address: { text: RTOSCommon.hexFormat(threadAddress) },
state: { text: this.threadState(rawState) },
priority: { text: `${currentPriority ?? '?'} / ${initPriority ?? '?'}` },
tick: { text: `${remainingTick ?? '?'} / ${initTick ?? '?'}` },
error: { text: errorValue ?? '?' },
stack: stackUsage,
stackPeak,
},
stackInfo,
running,
};
}
private async readStackInfo(ptr: string, frameId: number): Promise<RTOSCommon.RTOSStackInfo> {
const [stackAddressValue, stackSizeValue, stackPointerValue] = await Promise.all([
this.getExprVal(`(unsigned long)${ptr}->stack_addr`, frameId),
this.getExprVal(`(unsigned long)${ptr}->stack_size`, frameId),
this.getExprVal(`(unsigned long)${ptr}->sp`, frameId),
]);
const stackStart = this.parseNumber(stackAddressValue) ?? 0;
const stackSize = this.parseNumber(stackSizeValue);
const stackTop = this.parseNumber(stackPointerValue);
const stackInfo: RTOSCommon.RTOSStackInfo = { stackStart, stackTop, stackSize };
if (stackSize === undefined || stackSize <= 0) {
return stackInfo;
}
stackInfo.stackEnd = stackStart + stackSize;
if (stackTop !== undefined) {
stackInfo.stackUsed = Math.max(0, Math.min(stackSize, stackInfo.stackEnd - stackTop));
stackInfo.stackFree = stackSize - stackInfo.stackUsed;
}
if (!RTOSCommon.RTOSBase.disableStackPeaks && stackSize <= RTOSRTThread.MAX_STACK_READ) {
try {
const memArg: DebugProtocol.ReadMemoryArguments = {
memoryReference: RTOSCommon.hexFormat(stackStart),
count: stackSize,
};
const stackData = await this.session.customRequest('readMemory', memArg);
const buf = Buffer.from(stackData.data, 'base64');
if (buf.length !== stackSize || (stackData.unreadableBytes ?? 0) !== 0) {
return stackInfo;
}
stackInfo.bytes = new Uint8Array(buf);
let unusedBytes = 0;
while (unusedBytes < stackInfo.bytes.length && stackInfo.bytes[unusedBytes] === 0x23) {
unusedBytes++;
}
stackInfo.stackPeak = stackSize - unusedBytes;
} catch (e) {
console.log('RTOSRTThread: stack peak read failed', e);
}
}
return stackInfo;
}
private formatStackUsage(used: number | undefined, size: number | undefined): RTOSCommon.DisplayRowItem {
if (used === undefined || size === undefined || size <= 0) {
return { text: '?', value: undefined };
}
const percent = Math.max(0, Math.min(100, Math.round((used / size) * 100)));
return { text: `${percent} % (${used} / ${size})`, value: percent };
}
private threadState(rawState: number): ThreadState {
switch (rawState & 0x07) {
case 0x00:
return 'INITIALIZED';
case 0x01:
return 'CLOSED';
case 0x02:
return 'READY';
case 0x03:
return 'RUNNING';
case 0x04:
return 'SUSPENDED';
case 0x06:
return 'SUSPENDED (KILLABLE)';
case 0x07:
return 'SUSPENDED (UNINTERRUPTIBLE)';
default:
return 'UNKNOWN';
}
}
private parseNumber(value: string | undefined): number | undefined {
if (!value) {
return undefined;
}
const hex = value.match(/-?0x[0-9a-f]+/i)?.[0];
if (hex) {
return Number.parseInt(hex, 16);
}
const decimal = value.match(/-?\d+/)?.[0];
return decimal === undefined ? undefined : Number.parseInt(decimal, 10);
}
private stringFromGdb(value: string | undefined): string {
if (!value) {
return '?';
}
return value.match(/"((?:\\.|[^"\\])*)"/)?.[1] ?? '?';
}
}