forked from apple/darwin-xnu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kcdata_core.m
468 lines (416 loc) · 13.9 KB
/
kcdata_core.m
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#include <kcdata.h>
#import <Foundation/Foundation.h>
#import "kdd.h"
#import "KCDBasicTypeDescription.h"
#import "KCDStructTypeDescription.h"
#import "KCDEmbeddedBufferDescription.h"
#define LIB_KCD_ERR_DOMAIN @"KCDataError"
#define GEN_ERROR(code, msg) gen_error(__LINE__, code, @msg)
#define GEN_ERRORF(code, msg, ...) gen_error(__LINE__, code, [NSString stringWithFormat:@msg, __VA_ARGS__])
#define MAX_KCDATATYPE_BUFFER_SIZE 2048
extern struct kcdata_type_definition * kcdata_get_typedescription(unsigned type_id, uint8_t * buffer, uint32_t buffer_size);
BOOL setKCDataTypeForID(uint32_t newTypeID, KCDataType *newTypeObj);
static NSError *
gen_error(int line, NSInteger code, NSString *message)
{
return [NSError errorWithDomain:LIB_KCD_ERR_DOMAIN
code:code
userInfo:@{ @"line": @(line), @"message": message }];
}
static BOOL
mergedict(NSMutableDictionary * container, NSDictionary * object, NSError ** error)
{
for (id key in object) {
id existing = container[key];
id new = object[key];
if (existing) {
if ([existing isKindOfClass:[NSMutableArray class]] && [new isKindOfClass:[ NSArray class ]]) {
[existing addObjectsFromArray:new];
} else {
if (error) {
*error = GEN_ERRORF(KERN_INVALID_OBJECT, "repeated key: %@", key);
}
return FALSE;
}
} else {
[container setValue:new forKey:key];
}
}
return TRUE;
}
/*!
* @function getTypeFromTypeDef
*
* @abstract
* Build a KCDataType from a type definition.
*
* @param typeDef
* A pointer to kcdata_type_definition_t that specifies the type fields and has subtype definitions
* in the memory immediately following the type_definition.
*
* @return KCDataType * type object which can be used to parse data into dictionaries.
* This may return nil if it finds the data to be invalid.
*
* @discussion
* This routine tries to decode the typeDef structure and create either a basic type (KCDBasicTypeDescription)
* or a struct type.
*/
static KCDataType * getTypeFromTypeDef(struct kcdata_type_definition * typeDef);
static KCDataType *
getTypeFromTypeDef(struct kcdata_type_definition * typeDef)
{
if (typeDef == NULL) {
return nil;
}
NSString * kct_name = [NSString stringWithFormat:@"%s", typeDef->kct_name];
if (typeDef->kct_num_elements == 1 && !(typeDef->kct_elements[0].kcs_flags & KCS_SUBTYPE_FLAGS_STRUCT)) {
KCDBasicTypeDescription * retval = [[KCDBasicTypeDescription alloc] initWithKCTypeDesc:&typeDef->kct_elements[0]];
return retval;
} else {
KCDStructTypeDescription * retval =
[[KCDStructTypeDescription alloc] initWithType:typeDef->kct_type_identifier withName:kct_name];
/* need to do work here to get the array of elements setup here */
KCDBasicTypeDescription * curField = nil;
for (unsigned int i = 0; i < typeDef->kct_num_elements; i++) {
curField = [[KCDBasicTypeDescription alloc] initWithKCTypeDesc:&typeDef->kct_elements[i]];
[retval addFieldBasicType:curField];
if (typeDef->kct_elements[i].kcs_flags & KCS_SUBTYPE_FLAGS_MERGE) {
[retval setFlagsRequestedMerge];
}
}
return retval;
}
return nil;
}
static dispatch_once_t onceToken;
static NSMutableDictionary * knownTypes = nil;
KCDataType *
getKCDataTypeForID(uint32_t typeID)
{
dispatch_once(&onceToken, ^{
if (!knownTypes) {
knownTypes = [[NSMutableDictionary alloc] init];
}
});
NSNumber * type = [NSNumber numberWithUnsignedInt:typeID];
if (!knownTypes[type]) {
if (typeID == KCDATA_TYPE_NESTED_KCDATA) {
knownTypes[type] = [[KCDEmbeddedBufferDescription alloc] init];
return knownTypes[type];
}
/* code to query system for type information */
uint8_t buffer[MAX_KCDATATYPE_BUFFER_SIZE];
struct kcdata_type_definition * sys_def = kcdata_get_typedescription(typeID, buffer, MAX_KCDATATYPE_BUFFER_SIZE);
if (sys_def == NULL) {
knownTypes[type] = [[KCDBasicTypeDescription alloc] createDefaultForType:typeID];
} else {
knownTypes[type] = getTypeFromTypeDef(sys_def);
}
}
assert(knownTypes[type] != nil);
return knownTypes[type];
}
BOOL
setKCDataTypeForID(uint32_t newTypeID, KCDataType *newTypeObj) {
if (newTypeObj == NULL || newTypeID == 0) {
return FALSE;
}
dispatch_once(&onceToken, ^{
if (!knownTypes) {
knownTypes = [[NSMutableDictionary alloc] init];
}
});
NSNumber * type = [NSNumber numberWithUnsignedInt:newTypeID];
if (!knownTypes[type]) {
knownTypes[type] = newTypeObj;
return TRUE;
}
return FALSE;
}
NSString *
KCDataTypeNameForID(uint32_t typeID)
{
NSString * retval = [NSString stringWithFormat:@"%u", typeID];
KCDataType * t = getKCDataTypeForID(typeID);
if (![[t name] containsString:@"Type_"]) {
retval = [t name];
}
return retval;
}
NSMutableDictionary *
parseKCDataArray(kcdata_iter_t iter, NSError **error)
{
if (!kcdata_iter_array_valid(iter)) {
if (error)
*error = GEN_ERROR(KERN_INVALID_OBJECT, "invalid array");
return NULL;
}
uint32_t typeID = kcdata_iter_array_elem_type(iter);
uint32_t count = kcdata_iter_array_elem_count(iter);
uint32_t size = kcdata_iter_array_elem_size(iter);
uint8_t * buffer = (uint8_t *)kcdata_iter_payload(iter);
KCDataType * datatype = getKCDataTypeForID(typeID);
NSMutableDictionary * retval = [[NSMutableDictionary alloc] initWithCapacity:1];
NSMutableArray * arr = [[NSMutableArray alloc] initWithCapacity:count];
retval[[datatype name]] = arr;
NSDictionary * tmpdict = NULL;
for (uint32_t i = 0; i < count; i++) {
tmpdict = [datatype parseData:(void *)&buffer[i * size] ofLength:size];
if (!tmpdict) {
if (error)
*error = GEN_ERRORF(KERN_INVALID_OBJECT, "failed to parse array element. type=0x%x", (int)typeID);
return NULL;
}
if ([datatype shouldMergeData]) {
assert([tmpdict count] == 1);
[arr addObject: [tmpdict allValues][0]];
} else {
[arr addObject:tmpdict];
}
}
return retval;
}
NSMutableDictionary *
parseKCDataContainer(kcdata_iter_t *iter_p, NSError **error)
{
kcdata_iter_t iter = *iter_p;
if (!kcdata_iter_container_valid(iter)) {
if (error)
*error = GEN_ERROR(KERN_INVALID_OBJECT, "invalid container");
return NULL;
}
uint64_t containerID = kcdata_iter_container_id(iter);
/* setup collection object for sub containers */
NSMutableDictionary * sub_containers = [[NSMutableDictionary alloc] init];
NSMutableDictionary * retval = [[NSMutableDictionary alloc] init];
NSMutableDictionary * container = [[NSMutableDictionary alloc] init];
KCDataType * tmptype;
uint32_t _t;
void * _d;
BOOL ok;
NSDictionary * tmpdict;
BOOL found_end = FALSE;
retval[KCDataTypeNameForID(kcdata_iter_container_type(iter))] = container;
iter = kcdata_iter_next(iter);
KCDATA_ITER_FOREACH(iter)
{
_t = kcdata_iter_type(iter);
_d = kcdata_iter_payload(iter);
if (_t == KCDATA_TYPE_CONTAINER_END) {
if (kcdata_iter_container_id(iter) != containerID) {
if (error)
*error = GEN_ERROR(KERN_INVALID_ARGUMENT, "container marker mismatch");
return NULL;
}
found_end = TRUE;
break;
}
if (_t == KCDATA_TYPE_ARRAY) {
tmpdict = parseKCDataArray(iter, error);
if (!tmpdict)
return NULL;
ok = mergedict(container, tmpdict, error);
if (!ok)
return NULL;
continue;
}
if (_t == KCDATA_TYPE_CONTAINER_BEGIN) {
NSString * subcontainerID = [NSString stringWithFormat:@"%llu", kcdata_iter_container_id(iter)];
tmpdict = parseKCDataContainer(&iter, error);
if (!tmpdict)
return NULL;
assert([tmpdict count] == 1);
for (NSString * k in [tmpdict keyEnumerator]) {
if (sub_containers[k] == nil) {
sub_containers[k] = [[NSMutableDictionary alloc] init];
}
if (sub_containers[k][subcontainerID] != nil) {
if (error)
*error = GEN_ERRORF(KERN_INVALID_OBJECT, "repeated container id: %@", subcontainerID);
return NULL;
}
sub_containers[k][subcontainerID] = tmpdict[k];
}
continue;
}
tmptype = getKCDataTypeForID(_t);
tmpdict = [tmptype parseData:_d ofLength:kcdata_iter_size(iter)];
if (!tmpdict) {
if (error)
*error = GEN_ERRORF(KERN_INVALID_OBJECT, "failed to parse. type=0x%x", (int)_t);
return NULL;
}
if (![tmptype shouldMergeData]) {
tmpdict = @{[tmptype name] : tmpdict};
}
ok = mergedict(container, tmpdict, error);
if (!ok)
return NULL;
}
if (!found_end) {
if (error)
*error = GEN_ERROR(KERN_INVALID_ARGUMENT, "missing container end");
return NULL;
}
ok = mergedict(container, sub_containers, error);
if (!ok)
return NULL;
*iter_p = iter;
return retval;
}
NSDictionary *
parseKCDataBuffer(void * dataBuffer, uint32_t size, NSError ** error)
{
if (dataBuffer == NULL) {
if (error)
*error = GEN_ERROR(KERN_INVALID_ARGUMENT, "buffer is null");
return NULL;
}
uint32_t _type = (size >= sizeof(uint32_t)) ? *(uint32_t*)dataBuffer : 0;
uint32_t _size = 0;
uint64_t _flags = 0;
void * _datap = NULL;
KCDataType * kcd_type = NULL;
NSString * rootKey = NULL;
uint32_t rootType = _type;
BOOL ok;
/* validate begin tag and get root key */
switch (_type) {
case KCDATA_BUFFER_BEGIN_CRASHINFO:
rootKey = @"kcdata_crashinfo";
break;
case KCDATA_BUFFER_BEGIN_STACKSHOT:
rootKey = @"kcdata_stackshot";
break;
case KCDATA_BUFFER_BEGIN_DELTA_STACKSHOT:
rootKey = @"kcdata_delta_stackshot";
break;
case KCDATA_BUFFER_BEGIN_OS_REASON:
rootKey = @"kcdata_reason";
break;
case KCDATA_BUFFER_BEGIN_XNUPOST_CONFIG:
rootKey = @"xnupost_testconfig";
break;
default: {
if (error)
*error = GEN_ERROR(KERN_INVALID_VALUE, "invalid magic number");
return NULL;
break;
}
}
assert(rootKey != NULL);
kcdata_iter_t iter = kcdata_iter(dataBuffer, size);
if (!kcdata_iter_valid(iter)) {
if (error) {
*error = GEN_ERROR(KERN_INVALID_OBJECT, "initial item is invalid");
}
return NULL;
}
NSMutableDictionary * rootObject = [NSMutableDictionary dictionary];
NSDictionary * retval = [NSMutableDictionary dictionaryWithObject:rootObject forKey:rootKey];
/* iterate over each kcdata item */
KCDATA_ITER_FOREACH(iter)
{
_type = kcdata_iter_type(iter);
_size = kcdata_iter_size(iter);
_flags = kcdata_iter_flags(iter);
_datap = kcdata_iter_payload(iter);
if (_type == rootType)
continue;
if (_type == KCDATA_TYPE_ARRAY) {
NSDictionary * dict = parseKCDataArray(iter, error);
if (!dict)
return nil;
ok = mergedict(rootObject, dict, error);
if (!ok)
return NULL;
continue;
}
if (_type == KCDATA_TYPE_CONTAINER_BEGIN) {
NSString * containerID = [NSString stringWithFormat:@"%llu", kcdata_iter_container_id(iter)];
NSMutableDictionary *container = parseKCDataContainer(&iter, error);
if (!container)
return nil;
assert([container count] == 1);
for (NSString * k in [container keyEnumerator]) {
if (rootObject[k] == nil) {
rootObject[k] = [[NSMutableDictionary alloc] init];
}
if (rootObject[k][containerID] != nil) {
if (error)
*error = GEN_ERRORF(KERN_INVALID_OBJECT, "repeated container id: %@", containerID);
return NULL;
}
rootObject[k][containerID] = container[k];
}
continue;
}
if (_type == KCDATA_TYPE_TYPEDEFINTION) {
KCDataType *new_type = getTypeFromTypeDef((struct kcdata_type_definition *)_datap);
if (new_type != NULL) {
setKCDataTypeForID([new_type typeID], new_type);
kcd_type = getKCDataTypeForID(_type);
NSDictionary * tmpdict = [kcd_type parseData:_datap ofLength:_size];
if (!tmpdict) {
if (error)
*error = GEN_ERRORF(KERN_INVALID_OBJECT, "failed to parse. type=0x%x", (int)_type);
return NULL;
}
NSString *k = [NSString stringWithFormat:@"typedef[%@]", [new_type name]];
rootObject[k] = tmpdict;
}else {
if (error)
*error = GEN_ERRORF(KERN_INVALID_OBJECT, "Failed to parse type definition for type %u", _type);
return NULL;
}
continue;
}
kcd_type = getKCDataTypeForID(_type);
NSDictionary * tmpdict = [kcd_type parseData:_datap ofLength:_size];
if (!tmpdict) {
if (error)
*error = GEN_ERRORF(KERN_INVALID_OBJECT, "failed to parse. type=0x%x", (int)_type);
return NULL;
}
if (![kcd_type shouldMergeData]) {
tmpdict = @{[kcd_type name] : tmpdict};
}
ok = mergedict(rootObject, tmpdict, error);
if (!ok)
return NULL;
}
if (KCDATA_ITER_FOREACH_FAILED(iter)) {
retval = nil;
if (error) {
*error = GEN_ERROR(KERN_INVALID_OBJECT, "invalid item or missing buffer end marker");
}
}
return retval;
}