Loading...
  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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
 *
 * Copyright (c) 2014 Apple Inc. All rights reserved.
 *
 * @APPLE_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. 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_LICENSE_HEADER_END@
 */

#include <TargetConditionals.h>

#if !TARGET_OS_EXCLAVEKIT

#include "SwiftVisitor.h"

#if SUPPORT_VM_LAYOUT
#include "MachOAnalyzer.h"
#endif

#include <assert.h>

using namespace metadata_visitor;
using mach_o::Header;

//
// MARK: --- SwiftVisitor methods ---
//

void SwiftVisitor::forEachProtocolConformance(void (^callback)(const SwiftConformance& swiftConformance,
                                                               bool& stopConformance)) const
{
    SwiftConformanceList swiftConformanceList = this->getSwiftConformances();

    for ( uint32_t i = 0, e = swiftConformanceList.numConformances(); i != e; ++i ) {
        SwiftConformance swiftConformance = swiftConformanceList.getConformance(*this, i);

        bool stop = false;
        callback(swiftConformance, stop);
        if ( stop )
            break;
    }
}

SwiftConformanceList SwiftVisitor::getSwiftConformances() const
{
    std::optional<SectionContent> protoListSection = findTextSection("__swift5_proto");
    if ( !protoListSection.has_value() )
        return SwiftConformanceList(std::nullopt, 0);

    assert((protoListSection->sectSize % 4) == 0);
    uint64_t numElements = protoListSection->sectSize / 4;
    const ResolvedValue& sectionValue = protoListSection->sectionBase;
    return SwiftConformanceList(sectionValue, (uint32_t)numElements);
}

std::optional<SwiftVisitor::SectionContent> SwiftVisitor::findSection(const char* segmentName, const char *sectionName) const
{
#if SUPPORT_VM_LAYOUT
    const dyld3::MachOFile* mf = this->dylibMA;
#else
    const dyld3::MachOFile* mf = this->dylibMF;
#endif

    __block std::optional<SwiftVisitor::SectionContent> sectionContent;
    ((const Header*)mf)->forEachSection(^(const Header::SegmentInfo& segInfo, const Header::SectionInfo& sectInfo, bool& stop) {
        if ( sectInfo.segmentName != segmentName )
            return;
        if ( sectInfo.sectionName != sectionName )
            return;

#if SUPPORT_VM_LAYOUT
        const void* targetValue = (const void*)(sectInfo.address + this->dylibMA->getSlide());
        ResolvedValue target(targetValue, VMAddress(sectInfo.address));
#else
        VMOffset offsetInSegment(sectInfo.address - segInfo.vmaddr);
        ResolvedValue target(this->segments[sectInfo.segIndex], offsetInSegment);
#endif
        sectionContent.emplace(std::move(target));
        sectionContent->sectSize       = sectInfo.size;

        stop = true;
    });
    return sectionContent;
}

#if BUILDING_CACHE_BUILDER || BUILDING_CACHE_BUILDER_UNIT_TESTS
void SwiftVisitor::forEachPointerHashTable(Diagnostics &diag, void(^callback)(ResolvedValue sectionBase, size_t tableIndex, uint8_t* tableStart, size_t numEntries)) const
{
    std::optional<SectionContent> sect = findPointerHashTableSection();
    if ( !sect )
        return;

    if ( sect->sectSize < sizeof(uint64_t) )
        return;

    // Pointer hash table section consists of:
    // struct PointerHashTable {
    //   size_t count;
    //   struct PointerHashTableEntry entries[];
    // };
    // struct PointerHashTableEntry {
    //   struct PointerHashTableKey *key;
    //   void *value;
    // };

    const size_t sizeTySize = this->pointerSize;
    uint8_t* const sectBase = (uint8_t*)sect->sectionBase.value();
    uint8_t* const sectEnd = (uint8_t*)sectBase + sect->sectSize;
    uint8_t* pos = sectBase;
    size_t   tableIndex = 0;
    while ( pos < sectEnd ) {
        if ( (sectEnd-pos) < sizeof(sizeTySize) ) {
            diag.error("Bad hash table section, missing count");
            return;
        }

        const uint64_t count = sizeTySize == 4 ? *(uint32_t*)pos : *(uint64_t*)pos;
        const size_t headerSize = sizeTySize;
        const size_t entrySize = this->pointerSize * 2;
        const size_t minSize = (entrySize * count) + headerSize;
        if ( (sectEnd-pos) < minSize ) {
            diag.error("Bad hash table section, found count: %llu, expected section size: %lu, actual size: %llu", count, minSize, sect->sectSize);
            return;
        }

        callback(sect->sectionBase, tableIndex, pos, count);
        pos = pos + minSize;
        ++tableIndex;
    }
}

size_t SwiftVisitor::numPointerHashTables(Diagnostics& diag) const
{
    __block size_t res = 0;
    forEachPointerHashTable(diag, ^(ResolvedValue sectionBase, size_t tableIndex, uint8_t *tableStart, size_t numEntries) {
        ++res;
    });
    return res;
}

std::optional<ResolvedValue> SwiftVisitor::forEachPointerHashTableRelativeEntry(Diagnostics& diag, uint8_t* tableStart,
                                                                                VMAddress sharedCacheBaseAddr,
                                                                                void(^callback)(size_t index, std::span<uint64_t> cacheOffsetKeys, uint64_t cacheOffsetValue)) const
{
    std::optional<SectionContent> sect = findPointerHashTableSection();
    if ( !sect )
        return {};

    if ( sect->sectSize < sizeof(uint64_t) )
        return {};

    std::vector<ResolvedValue> res;
    uint8_t* const sectBase = (uint8_t*)sect->sectionBase.value();
    uint8_t* const sectEnd = (uint8_t*)sectBase + sect->sectSize;
    if ( tableStart < sectBase || tableStart >= sectEnd ) {
        assert(false && "invalid pointer table addr");
        return std::nullopt;
    }

    const size_t sizeTySize = pointerSize;
    if ( (sectEnd-tableStart) < sizeTySize ) {
        diag.error("Bad hash table section, missing count");
        return {};
    }

    const uint64_t count = sizeTySize == 4 ? *(uint32_t*)tableStart : *(uint64_t*)tableStart;
    const size_t headerSize = sizeTySize;
    const size_t ptrSize = this->pointerSize;
    const size_t entrySize = ptrSize * 2;
    const size_t minSize = (entrySize * count) + headerSize;
    if ( (sectEnd-tableStart) < minSize ) {
        diag.error("Bad hash table section, found count: %llu, expected section size: %lu, actual size: %llu", count, minSize, sect->sectSize);
        return {};
    }

    // Entry and key layout are:
    //
    // struct PointerHashTableEntry {
    //     struct PointerHashTableKey *key;
    //     void *value;
    // };
    // struct PointerHashTableKey {
    //     size_t  count;
    //     void *pointers[];
    // };
    uint8_t* entry = (uint8_t*)(tableStart + headerSize);
    std::vector<uint64_t> keysBuffer;
    for ( size_t i = 0; i < count; ++i ) {
        ResolvedValue keyPtrResolved = resolveRebase(getField(sect->sectionBase, entry));
        entry += ptrSize;

        bool wasBind;
        ResolvedValue valueResolved = resolveBindOrRebase(getField(sect->sectionBase, entry), wasBind);
        entry += ptrSize;

        uint8_t* keyPtr = (uint8_t*)keyPtrResolved.value();
        const uint64_t numKeys = sizeTySize == 4 ? *(uint32_t*)keyPtr : *(uint64_t*)keyPtr;
        keyPtr += sizeTySize;

        keysBuffer.clear();
        for ( uint64_t k = 0; k < numKeys; ++k ) {
            ResolvedValue key = resolveBindOrRebase(getField(keyPtrResolved, keyPtr), wasBind);
            keyPtr += ptrSize;

            keysBuffer.push_back((key.vmAddress()-sharedCacheBaseAddr).rawValue());
        }

        callback(i, keysBuffer, (valueResolved.vmAddress()-sharedCacheBaseAddr).rawValue());
    }
    assert((uint8_t*)entry == (tableStart+minSize));
    return getField(sect->sectionBase, tableStart);
}
#endif

//
// MARK: --- SwiftConformanceList methods ---
//

SwiftConformance SwiftConformanceList::getConformance(const Visitor &swiftVisitor, uint32_t i) const
{
    // Protocol conformances are a 32-bit offset from the list entry
    const uint8_t* fieldPos = (const uint8_t*)this->conformanceListPos->value() + (i * sizeof(int32_t));

    int64_t relativeOffsetFromField = (int64_t)*(int32_t*)fieldPos;
    VMOffset relativeOffsetFromList((uint64_t)relativeOffsetFromField + (i * 4));

    VMAddress listVMAddr = this->conformanceListPos->vmAddress();
    VMAddress conformanceVMAddr = listVMAddr + relativeOffsetFromList;

    ResolvedValue conformanceValue = swiftVisitor.getValueFor(conformanceVMAddr);
    return SwiftConformance(conformanceValue);
}

uint32_t SwiftConformanceList::numConformances() const
{
    return this->numElements;
}

//
// MARK: --- SwiftConformance methods ---
//

std::optional<VMAddress> SwiftConformance::getProtocolVMAddr(const SwiftVisitor& swiftVisitor) const
{
    const conformance_t* rawConformance = (const conformance_t*)this->getLocation();

    // The protocol is found via the relative pointer
    const relative_pointer_t* relativePtr = &rawConformance->protocolRelativePointer;
    ResolvedValue relativePtrField = swiftVisitor.getField(this->conformancePos, relativePtr);
    return SwiftRelativePointer(relativePtrField).getTargetVMAddr(swiftVisitor);
}

SwiftPointer SwiftConformance::getProtocolPointer(const SwiftVisitor& swiftVisitor) const
{
    const conformance_t* rawConformance = (const conformance_t*)this->getLocation();

    // The protocol is found via the relative pointer
    const relative_pointer_t* relativePtr = &rawConformance->protocolRelativePointer;
    ResolvedValue relativePtrField = swiftVisitor.getField(this->conformancePos, relativePtr);
    return SwiftRelativePointer(relativePtrField).getTargetPointer(swiftVisitor);
}

SwiftConformance::SwiftProtocolConformanceFlags
SwiftConformance::getProtocolConformanceFlags(const SwiftVisitor& swiftVisitor) const
{
    const conformance_t* rawConformance = (const conformance_t*)this->getLocation();

    const protocol_conformance_flags_t* flagsPtr = &rawConformance->flags;
    ResolvedValue flagsField = swiftVisitor.getField(this->conformancePos, flagsPtr);
    return SwiftProtocolConformanceFlags(flagsField);
}

SwiftConformance::SwiftTypeRefPointer
SwiftConformance::getTypeRef(const SwiftVisitor& swiftVisitor) const
{
    const conformance_t* rawConformance = (const conformance_t*)this->getLocation();

    // The typeref is found via the relative pointer
    const typeref_pointer_t* relativePtr = &rawConformance->typeRef;
    ResolvedValue relativePtrField = swiftVisitor.getField(this->conformancePos, relativePtr);

    auto kind = getProtocolConformanceFlags(swiftVisitor).typeReferenceKind();
    return SwiftTypeRefPointer(relativePtrField, kind);
}

bool SwiftConformance::isNull() const
{
    const conformance_t* rawConformance = (const conformance_t*)this->getLocation();
    uint8_t emptyConformance[sizeof(conformance_t)] = { 0 };
    return memcmp(rawConformance, emptyConformance, sizeof(conformance_t)) == 0;
}

VMAddress SwiftConformance::getVMAddress() const
{
    return this->conformancePos.vmAddress();
}

const void* SwiftConformance::getLocation() const
{
    return this->conformancePos.value();
}

//
// MARK: --- SwiftConformance::SwiftRelativePointer methods ---
//

std::optional<VMAddress> SwiftConformance::SwiftRelativePointer::getTargetVMAddr(const SwiftVisitor &swiftVisitor) const
{
    const relative_pointer_t* relativePtr = (const relative_pointer_t*)this->pos.value();
    int32_t relativeOffset = relativePtr->relativeOffset;
    if ( (relativeOffset & 0x1) == 0 ) {
        // Relative offset directly to the target value
        int64_t offset64 = (int64_t)relativeOffset;
        VMAddress targetVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);
        return targetVMAddr;
    } else {
        // Relative offset to a pointer.  The pointer contains the target value
        int32_t offset = relativeOffset & ~0x1ULL;
        int64_t offset64 = (int64_t)offset;
        VMAddress pointerVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);
        ResolvedValue pointerValue = swiftVisitor.getValueFor(pointerVMAddr);

        // Dereference the pointer to get the final target
        return swiftVisitor.resolveOptionalRebaseToVMAddress(pointerValue);
    }
}

SwiftPointer SwiftConformance::SwiftRelativePointer::getTargetPointer(const SwiftVisitor &swiftVisitor) const
{
    const relative_pointer_t* relativePtr = (const relative_pointer_t*)this->pos.value();
    int32_t relativeOffset = relativePtr->relativeOffset;
    if ( (relativeOffset & 0x1) == 0 ) {
        // Relative offset directly to the target value
        int64_t offset64 = (int64_t)relativeOffset;
        VMAddress targetVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);
        return { true, swiftVisitor.getValueFor(targetVMAddr) };
    } else {
        // Relative offset to a pointer.  The pointer contains the target value
        int32_t offset = relativeOffset & ~0x1ULL;
        int64_t offset64 = (int64_t)offset;
        VMAddress pointerVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);
        return { false, swiftVisitor.getValueFor(pointerVMAddr) };
    }
}

//
// MARK: --- SwiftConformance::SwiftProtocolConformanceFlags methods ---
//

SwiftConformance::SwiftProtocolConformanceFlags::TypeReferenceKind
SwiftConformance::SwiftProtocolConformanceFlags::typeReferenceKind() const
{
    const protocol_conformance_flags_t* flagsPtr = (const protocol_conformance_flags_t*)this->pos.value();
    uint32_t flags = flagsPtr->flags;
    return (TypeReferenceKind)((flags & (uint32_t)TypeMetadataKind::mask) >> (uint32_t)TypeMetadataKind::shift);
}

//
// MARK: --- SwiftConformance::SwiftProtocolConformanceFlags methods ---
//

std::optional<ResolvedValue>
SwiftConformance::SwiftTypeRefPointer::getTypeDescriptor(const SwiftVisitor &swiftVisitor) const
{
    assert((this->kind == SwiftProtocolConformanceFlags::TypeReferenceKind::directTypeDescriptor)
           || (this->kind == SwiftProtocolConformanceFlags::TypeReferenceKind::indirectTypeDescriptor));

    if ( this->kind == SwiftProtocolConformanceFlags::TypeReferenceKind::directTypeDescriptor ) {
        // Relative offset directly to the target value
        int32_t relativeOffset = *(int32_t*)this->pos.value();
        int64_t offset64 = (int64_t)relativeOffset;
        VMAddress pointerVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);

        return swiftVisitor.getValueFor(pointerVMAddr);
    }

    if ( this->kind == SwiftProtocolConformanceFlags::TypeReferenceKind::indirectTypeDescriptor ) {
        // Relative offset to a pointer.  The pointer contains the target value
        int32_t relativeOffset = *(int32_t*)this->pos.value();
        int32_t offset = relativeOffset & ~0x1ULL;
        int64_t offset64 = (int64_t)offset;
        VMAddress pointerVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);
        ResolvedValue pointerValue = swiftVisitor.getValueFor(pointerVMAddr);

        // Dereference the pointer to get the final target
        return swiftVisitor.resolveOptionalRebase(pointerValue);
    }
    return { };
}

const char*
SwiftConformance::SwiftTypeRefPointer::getClassName(const SwiftVisitor &swiftVisitor) const
{
    assert(this->kind == SwiftProtocolConformanceFlags::TypeReferenceKind::directObjCClassName);

    // Relative offset directly to the class name string
    int32_t relativeOffset = *(int32_t*)this->pos.value();
    int64_t offset64 = (int64_t)relativeOffset;
    VMAddress pointerVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);

    ResolvedValue pointerValue = swiftVisitor.getValueFor(pointerVMAddr);
    return (const char*)pointerValue.value();
}

std::optional<ResolvedValue>
SwiftConformance::SwiftTypeRefPointer::getClass(const SwiftVisitor &swiftVisitor) const
{
    assert(this->kind == SwiftProtocolConformanceFlags::TypeReferenceKind::indirectObjCClass);

    // Relative offset to a pointer.  The pointer contains the target value
    int32_t relativeOffset = *(int32_t*)this->pos.value();
    int32_t offset = relativeOffset & ~0x1ULL;
    int64_t offset64 = (int64_t)offset;
    VMAddress pointerVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);
    ResolvedValue pointerValue = swiftVisitor.getValueFor(pointerVMAddr);

    // Dereference the pointer to get the final target
    return swiftVisitor.resolveOptionalRebase(pointerValue);
}

SwiftPointer SwiftConformance::SwiftTypeRefPointer::getTargetPointer(const SwiftVisitor &swiftVisitor) const
{
    switch ( this->kind ) {
        case SwiftProtocolConformanceFlags::TypeReferenceKind::directTypeDescriptor: {
            // Relative offset directly to the target value
            int32_t relativeOffset = *(int32_t*)this->pos.value();
            int64_t offset64 = (int64_t)relativeOffset;
            VMAddress pointerVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);
            return { true, swiftVisitor.getValueFor(pointerVMAddr) };
        }
        case SwiftProtocolConformanceFlags::TypeReferenceKind::indirectTypeDescriptor: {
            // Relative offset to a pointer.  The pointer contains the target value
            int32_t relativeOffset = *(int32_t*)this->pos.value();
            int32_t offset = relativeOffset & ~0x1ULL;
            int64_t offset64 = (int64_t)offset;
            VMAddress pointerVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);
            return { false, swiftVisitor.getValueFor(pointerVMAddr) };
        }
        case SwiftProtocolConformanceFlags::TypeReferenceKind::directObjCClassName: {
            // Relative offset directly to the class name string
            int32_t relativeOffset = *(int32_t*)this->pos.value();
            int64_t offset64 = (int64_t)relativeOffset;
            VMAddress pointerVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);
            return { true, swiftVisitor.getValueFor(pointerVMAddr) };
        }
        case SwiftProtocolConformanceFlags::TypeReferenceKind::indirectObjCClass: {
            // Relative offset to a pointer.  The pointer contains the target value
            int32_t relativeOffset = *(int32_t*)this->pos.value();
            int32_t offset = relativeOffset & ~0x1ULL;
            int64_t offset64 = (int64_t)offset;
            VMAddress pointerVMAddr = this->pos.vmAddress() + VMOffset((uint64_t)offset64);
            return { false, swiftVisitor.getValueFor(pointerVMAddr) };
        }
    }
}

//
// MARK: --- SwiftConformance::TypeContextDescriptor methods ---
//

// The most significant two bytes of the flags word, which can have
// kind-specific meaning.
uint16_t SwiftConformance::TypeContextDescriptor::getKindSpecificFlags() const {
    const type_context_descriptor_t* context = (type_context_descriptor_t*)this->pos.value();
    return (context->flags >> 16u) & 0xFFFFu;
}

bool SwiftConformance::TypeContextDescriptor::isForeignMetadata() const
{
    // The botton 2 bits have the flags
    return (this->getKindSpecificFlags() & 0x3) == ForeignMetadataInitialization;
}

bool SwiftConformance::TypeContextDescriptor::hasImportInfo() const
{
    // Bit 2 tells us if we have import info, ie, a name containing NULLs
    return (this->getKindSpecificFlags() & (1 << 2)) != 0;
}

ResolvedValue SwiftConformance::TypeContextDescriptor::getName(const SwiftVisitor& swiftVisitor) const
{
    // The name is found via a relative offset
    const type_context_descriptor_t* context = (type_context_descriptor_t*)this->pos.value();
    ResolvedValue nameField = swiftVisitor.getField(this->pos, &context->name.relativeOffset);

    // Add the offset to the field to get the target value
    int32_t nameOffset = *(int32_t*)nameField.value();
    int64_t nameOffset64 = (int64_t)nameOffset;
    VMOffset offsetFromNameField((uint64_t)nameOffset64);
    VMAddress targetVMAddr = nameField.vmAddress() + offsetFromNameField;
    return swiftVisitor.getValueFor(targetVMAddr);
}

#endif // !TARGET_OS_EXCLAVEKIT