PrelinkedKext.c 24.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/** @file
  Copyright (C) 2019, vit9696. All rights reserved.

  All rights reserved.

  This program and the accompanying materials
  are licensed and made available under the terms and conditions of the BSD License
  which accompanies this distribution.  The full text of the license may be found at
  http://opensource.org/licenses/bsd-license.php

  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/

15
#include <Base.h>
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

#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/OcAppleKernelLib.h>
#include <Library/OcMachoLib.h>
#include <Library/OcXmlLib.h>

#include "PrelinkedInternal.h"

/**
  Creates new uncached PRELINKED_KEXT from pool.

  @param[in] Prelinked  Initialises PRELINKED_KEXT from prelinked buffer.
  @param[in] KextPlist  Plist root node with Kext Information.
  @param[in] Identifier Abort on CFBundleIdentifier mismatch.

  @return allocated PRELINKED_KEXT or NULL.
**/
STATIC
PRELINKED_KEXT *
InternalCreatePrelinkedKext (
  IN OUT PRELINKED_CONTEXT  *Prelinked OPTIONAL,
  IN XML_NODE               *KextPlist,
  IN CONST CHAR8            *Identifier OPTIONAL
  )
{
  PRELINKED_KEXT  *NewKext;
  UINT32          FieldIndex;
  UINT32          FieldCount;
  CONST CHAR8     *KextPlistKey;
  XML_NODE        *KextPlistValue;
  CONST CHAR8     *KextIdentifier;
  XML_NODE        *BundleLibraries;
51
  XML_NODE        *BundleLibraries64;
52 53 54 55 56 57 58 59 60 61
  CONST CHAR8     *CompatibleVersion;
  UINT64          VirtualBase;
  UINT64          VirtualKmod;
  UINT64          SourceBase;
  UINT64          SourceSize;
  UINT64          SourceEnd;
  BOOLEAN         Found;

  KextIdentifier    = NULL;
  BundleLibraries   = NULL;
62
  BundleLibraries64 = NULL;
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
  CompatibleVersion = NULL;
  VirtualBase       = 0;
  VirtualKmod       = 0;
  SourceBase        = 0;
  SourceSize        = 0;

  Found       = Identifier == NULL;

  FieldCount = PlistDictChildren (KextPlist);
  for (FieldIndex = 0; FieldIndex < FieldCount; ++FieldIndex) {
    KextPlistKey = PlistKeyValue (PlistDictChild (KextPlist, FieldIndex, &KextPlistValue));
    if (KextPlistKey == NULL) {
      continue;
    }

    if (KextIdentifier == NULL && AsciiStrCmp (KextPlistKey, INFO_BUNDLE_IDENTIFIER_KEY) == 0) {
      KextIdentifier = XmlNodeContent (KextPlistValue);
      if (PlistNodeCast (KextPlistValue, PLIST_NODE_TYPE_STRING) == NULL || KextIdentifier == NULL) {
        break;
      }
      if (!Found && AsciiStrCmp (KextIdentifier, Identifier) == 0) {
        Found = TRUE;
      }
    } else if (BundleLibraries == NULL && AsciiStrCmp (KextPlistKey, INFO_BUNDLE_LIBRARIES_KEY) == 0) {
      if (PlistNodeCast (KextPlistValue, PLIST_NODE_TYPE_DICT) == NULL) {
        break;
      }
      BundleLibraries = KextPlistValue;
91 92 93 94 95
    } else if (BundleLibraries64 == NULL && AsciiStrCmp (KextPlistKey, INFO_BUNDLE_LIBRARIES_64_KEY) == 0) {
      if (PlistNodeCast (KextPlistValue, PLIST_NODE_TYPE_DICT) == NULL) {
        break;
      }
      BundleLibraries64 = BundleLibraries = KextPlistValue;
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
    } else if (CompatibleVersion == NULL && AsciiStrCmp (KextPlistKey, INFO_BUNDLE_COMPATIBLE_VERSION_KEY) == 0) {
      if (PlistNodeCast (KextPlistValue, PLIST_NODE_TYPE_STRING) == NULL) {
        break;
      }
      CompatibleVersion = XmlNodeContent (KextPlistValue);
      if (CompatibleVersion == NULL) {
        break;
      }
    } else if (Prelinked != NULL && VirtualBase == 0 && AsciiStrCmp (KextPlistKey, PRELINK_INFO_EXECUTABLE_LOAD_ADDR_KEY) == 0) {
      if (!PlistIntegerValue (KextPlistValue, &VirtualBase, sizeof (VirtualBase), TRUE)) {
        break;
      }
    } else if (Prelinked != NULL && VirtualKmod == 0 && AsciiStrCmp (KextPlistKey, PRELINK_INFO_KMOD_INFO_KEY) == 0) {
      if (!PlistIntegerValue (KextPlistValue, &VirtualKmod, sizeof (VirtualKmod), TRUE)) {
        break;
      }
    } else if (Prelinked != NULL && SourceBase == 0 && AsciiStrCmp (KextPlistKey, PRELINK_INFO_EXECUTABLE_SOURCE_ADDR_KEY) == 0) {
      if (!PlistIntegerValue (KextPlistValue, &SourceBase, sizeof (SourceBase), TRUE)) {
        break;
      }
    } else if (Prelinked != NULL && SourceSize == 0 && AsciiStrCmp (KextPlistKey, PRELINK_INFO_EXECUTABLE_SIZE_KEY) == 0) {
      if (!PlistIntegerValue (KextPlistValue, &SourceSize, sizeof (SourceSize), TRUE)) {
        break;
      }
    }

122
    if (KextIdentifier != NULL && BundleLibraries64 != NULL && CompatibleVersion != NULL
123 124 125 126 127 128 129 130 131
      && (Prelinked == NULL || (Prelinked != NULL && VirtualBase != 0 && VirtualKmod != 0 && SourceBase != 0 && SourceSize != 0))) {
      break;
    }
  }

  //
  // BundleLibraries, CompatibleVersion, and KmodInfo are optional and thus not checked.
  //
  if (!Found || KextIdentifier == NULL || SourceBase < VirtualBase
132
    || (Prelinked != NULL && (VirtualBase == 0 || SourceBase == 0 || SourceSize == 0 || SourceSize > MAX_UINT32))) {
133 134 135 136 137 138 139 140 141 142 143 144
    return NULL;
  }

  if (Prelinked != NULL) {
    SourceBase -= Prelinked->PrelinkedTextSegment->VirtualAddress;
    if (OcOverflowAddU64 (SourceBase, Prelinked->PrelinkedTextSegment->FileOffset, &SourceBase) ||
      OcOverflowAddU64 (SourceBase, SourceSize, &SourceEnd) ||
      SourceEnd > Prelinked->PrelinkedSize) {
      return NULL;
    }
  }

V
vit9696 已提交
145 146 147
  //
  // Important to ZeroPool for dependency cleanup.
  //
148 149 150 151 152 153
  NewKext = AllocateZeroPool (sizeof (*NewKext));
  if (NewKext == NULL) {
    return NULL;
  }

  if (Prelinked != NULL
154
    && !MachoInitializeContext (&NewKext->Context.MachContext, &Prelinked->Prelinked[SourceBase], (UINT32)SourceSize)) {
155 156 157 158 159 160 161 162 163 164 165 166 167 168
    FreePool (NewKext);
    return NULL;
  }

  NewKext->Signature            = PRELINKED_KEXT_SIGNATURE;
  NewKext->Identifier           = KextIdentifier;
  NewKext->BundleLibraries      = BundleLibraries;
  NewKext->CompatibleVersion    = CompatibleVersion;
  NewKext->Context.VirtualBase  = VirtualBase;
  NewKext->Context.VirtualKmod  = VirtualKmod;

  return NewKext;
}

169
STATIC
170 171
VOID
InternalScanCurrentPrelinkedKextLinkInfo (
172 173 174 175 176 177 178 179 180 181
  IN OUT PRELINKED_KEXT  *Kext
  )
{
  if (Kext->LinkEditSegment == NULL) {
    Kext->LinkEditSegment = MachoGetSegmentByName64 (
      &Kext->Context.MachContext,
      "__LINKEDIT"
      );
  }

V
vit9696 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194
  if (Kext->SymbolTable == NULL) {
    Kext->NumberOfSymbols = MachoGetSymbolTable (
                   &Kext->Context.MachContext,
                   &Kext->SymbolTable,
                   &Kext->StringTable,
                   NULL,
                   NULL,
                   NULL,
                   NULL,
                   NULL,
                   NULL
                   );
  }
195 196
}

V
vit9696 已提交
197
STATIC
198
EFI_STATUS
V
vit9696 已提交
199
InternalScanBuildLinkedSymbolTable (
200 201
  IN OUT PRELINKED_KEXT     *Kext,
  IN     PRELINKED_CONTEXT  *Context
V
vit9696 已提交
202 203
  )
{
204 205
  CONST MACH_HEADER_64  *MachHeader;
  BOOLEAN               ResolveSymbols;
D
Download-Fritz 已提交
206 207 208 209
  PRELINKED_KEXT_SYMBOL *SymbolTable;
  PRELINKED_KEXT_SYMBOL *WalkerBottom;
  PRELINKED_KEXT_SYMBOL *WalkerTop;
  UINT32                NumCxxSymbols;
210
  UINT32                NumDiscardedSyms;
D
Download-Fritz 已提交
211 212
  UINT32                Index;
  CONST MACH_NLIST_64   *Symbol;
213 214
  MACH_NLIST_64         SymbolScratch;
  CONST PRELINKED_KEXT_SYMBOL *ResolvedSymbol;
D
Download-Fritz 已提交
215 216 217
  CONST CHAR8           *Name;
  BOOLEAN               Result;

V
vit9696 已提交
218
  if (Kext->LinkedSymbolTable != NULL) {
219
    return EFI_SUCCESS;
V
vit9696 已提交
220 221
  }

D
Download-Fritz 已提交
222 223
  SymbolTable = AllocatePool (Kext->NumberOfSymbols * sizeof (*SymbolTable));
  if (SymbolTable == NULL) {
224
    return EFI_OUT_OF_RESOURCES;
D
Download-Fritz 已提交
225 226
  }

227 228 229 230 231 232 233 234
  MachHeader = MachoGetMachHeader64 (&Kext->Context.MachContext);
  ASSERT (MachHeader != NULL);
  //
  // KPIs declare undefined and indirect symbols even in prelinkedkernel.
  //
  ResolveSymbols = ((MachHeader->Flags & MACH_HEADER_FLAG_NO_UNDEFINED_REFERENCES) == 0);
  NumDiscardedSyms = 0;

D
Download-Fritz 已提交
235 236 237 238 239 240 241
  WalkerBottom = &SymbolTable[0];
  WalkerTop    = &SymbolTable[Kext->NumberOfSymbols - 1];

  NumCxxSymbols = 0;

  for (Index = 0; Index < Kext->NumberOfSymbols; ++Index) {
    Symbol = &Kext->SymbolTable[Index];
242 243 244 245 246
    if ((Symbol->Type & MACH_N_TYPE_STAB) != 0) {
      ++NumDiscardedSyms;
      continue;
    }

D
Download-Fritz 已提交
247 248 249
    Name   = MachoGetSymbolName64 (&Kext->Context.MachContext, Symbol);
    Result = MachoSymbolNameIsCxx (Name);

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    if (ResolveSymbols) {
      //
      // Undefined symbols will be resolved via the KPI's dependencies and
      // hence do not need to be included (again).
      //
      if ((Symbol->Type & MACH_N_TYPE_TYPE) == MACH_N_TYPE_UNDF) {
        ++NumDiscardedSyms;
        continue;
      }
      //
      // Resolve indirect symbols via the KPI's dependencies (kernel).
      //
      if ((Symbol->Type & MACH_N_TYPE_TYPE) == MACH_N_TYPE_INDR) {
        Name = MachoGetIndirectSymbolName64 (&Kext->Context.MachContext, Symbol);
        if (Name == NULL) {
265
          FreePool (SymbolTable);
266
          return EFI_LOAD_ERROR;
267 268 269
        }

        CopyMem (&SymbolScratch, Symbol, sizeof (SymbolScratch));
270
        ResolvedSymbol = InternalOcGetSymbolName (
271 272
                           Context,
                           Kext,
273
                           Name,
274 275 276
                           OcGetSymbolFirstLevel
                           );
        if (ResolvedSymbol == NULL) {
277
          FreePool (SymbolTable);
278
          return EFI_NOT_FOUND;
279 280 281 282 283 284
        }
        SymbolScratch.Value = ResolvedSymbol->Value;
        Symbol = &SymbolScratch;
      }
    }

D
Download-Fritz 已提交
285
    if (!Result) {
286 287
      WalkerBottom->Value  = Symbol->Value;
      WalkerBottom->Name   = Kext->StringTable + Symbol->UnifiedName.StringIndex;
288
      WalkerBottom->Length = (UINT32)AsciiStrLen (WalkerBottom->Name);
D
Download-Fritz 已提交
289 290
      ++WalkerBottom;
    } else {
291
      WalkerTop->Value  = Symbol->Value;
292
      WalkerTop->Name   = Kext->StringTable + Symbol->UnifiedName.StringIndex;
293
      WalkerTop->Length = (UINT32)AsciiStrLen (WalkerTop->Name);
D
Download-Fritz 已提交
294 295 296 297 298
      --WalkerTop;

      ++NumCxxSymbols;
    }
  }
299 300 301 302 303 304 305 306 307 308 309 310
  //
  // Move the C++ symbols to the actual end of the non-C++ symbols as undefined
  // symbols got discarded.
  //
  if (NumDiscardedSyms > 0) {
    CopyMem (
      &SymbolTable[Kext->NumberOfSymbols - NumCxxSymbols - NumDiscardedSyms],
      &SymbolTable[Kext->NumberOfSymbols - NumCxxSymbols],
      (NumCxxSymbols * sizeof (*SymbolTable))
      );
    Kext->NumberOfSymbols -= NumDiscardedSyms;
  }
D
Download-Fritz 已提交
311 312

  Kext->NumberOfCxxSymbols = NumCxxSymbols;
313
  Kext->LinkedSymbolTable  = SymbolTable;
D
Download-Fritz 已提交
314

315
  return EFI_SUCCESS;
V
vit9696 已提交
316 317
}

318
STATIC
319
EFI_STATUS
320 321 322 323 324
InternalScanBuildLinkedVtables (
  IN OUT PRELINKED_KEXT     *Kext,
  IN     PRELINKED_CONTEXT  *Context
  )
{
325 326 327 328 329 330 331 332 333 334 335
  OC_PRELINKED_VTABLE_LOOKUP_ENTRY *VtableLookups;
  UINT32                           MaxSize;
  BOOLEAN                          Result;
  UINT32                           NumVtables;
  UINT32                           NumEntries;
  UINT32                           NumEntriesTemp;
  UINT32                           Index;
  UINT32                           VtableMaxSize;
  CONST UINT64                     *VtableData;
  PRELINKED_VTABLE                 *LinkedVtables;

336 337
  VOID                             *Tmp;

338
  if (Kext->LinkedVtables != NULL) {
339
    return EFI_SUCCESS;
340 341
  }

342
  VtableLookups = Context->LinkBuffer;
343
  MaxSize       = Context->LinkBufferSize;
344 345

  Result = InternalPrepareCreateVtablesPrelinked64 (
346
             Kext,
347 348
             MaxSize,
             &NumVtables,
349
             VtableLookups
350 351
             );
  if (!Result) {
352
    return EFI_UNSUPPORTED;
353 354
  }

355
  NumEntries = 0;
356

357
  for (Index = 0; Index < NumVtables; ++Index) {
358 359 360 361 362
    //
    // NOTE: KXLD locates the section via MACH_NLIST_64.Section. However, as we
    //       need to abort anyway when the value is out of its bounds, we can
    //       just locate it by address in the first place.
    //
363 364 365 366 367 368
    Tmp = MachoGetFilePointerByAddress64 (
            &Kext->Context.MachContext,
            VtableLookups[Index].Vtable.Value,
            &VtableMaxSize
            );
    if (Tmp == NULL || !OC_TYPE_ALIGNED (UINT64, Tmp)) {
369
      return EFI_UNSUPPORTED;
370
    }
371
    VtableData = (UINT64 *)Tmp;
372

373 374
    Result = InternalGetVtableEntries64 (
               VtableData,
375 376
               VtableMaxSize,
               &NumEntriesTemp
377 378
               );
    if (!Result) {
379
      return EFI_UNSUPPORTED;
380 381
    }

382 383
    VtableLookups[Index].Vtable.Data = VtableData;

384
    NumEntries += NumEntriesTemp;
385 386
  }

387 388 389 390 391
  LinkedVtables = AllocatePool (
                    (NumVtables * sizeof (*LinkedVtables))
                      + (NumEntries * sizeof (*LinkedVtables->Entries))
                    );
  if (LinkedVtables == NULL) {
392
    return EFI_OUT_OF_RESOURCES;
393 394
  }

V
vit9696 已提交
395
  InternalCreateVtablesPrelinked64 (
396 397 398
             Context,
             Kext,
             NumVtables,
399
             VtableLookups,
400 401
             LinkedVtables
             );
402

403
  Kext->NumberOfVtables = NumVtables;
404
  Kext->LinkedVtables   = LinkedVtables;
405

406
  return EFI_SUCCESS;
407 408
}

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
STATIC
UINT32
InternalGetLinkBufferSize (
  IN OUT PRELINKED_KEXT  *Kext
  )
{
  UINT32 Size;
  //
  // LinkBuffer must be able to hold all symbols and for KEXTs to be prelinked
  // also the __LINKEDIT segment (however not both simultaneously/separately).
  //
  Size = Kext->NumberOfSymbols * sizeof (MACH_NLIST_64);
  
  if (Kext->LinkEditSegment != NULL) {
    Size = MAX ((UINT32) Kext->LinkEditSegment->FileSize, Size);
  }

  return Size;
}

429
STATIC
430
EFI_STATUS
431 432 433 434 435
InternalUpdateLinkBuffer (
  IN OUT PRELINKED_KEXT     *Kext,
  IN OUT PRELINKED_CONTEXT  *Context
  )
{
436 437
  UINT32 BufferSize;

438 439 440 441
  ASSERT (Kext != NULL);
  ASSERT (Context != NULL);

  if (Context->LinkBuffer == NULL) {
442 443 444 445 446 447
    //
    // Context->LinkBufferSize was updated recursively during initial dependency
    // walk to save reallocations.
    //
    ASSERT (Context->LinkBufferSize >= InternalGetLinkBufferSize (Kext));

448 449
    Context->LinkBuffer = AllocatePool (Context->LinkBufferSize);
    if (Context->LinkBuffer == NULL) {
450
      return EFI_OUT_OF_RESOURCES;
451
    }
452 453
  } else {
    BufferSize = InternalGetLinkBufferSize (Kext);
454

455 456 457 458 459 460 461 462
    if (Context->LinkBufferSize < BufferSize) {
      FreePool (Context->LinkBuffer);

      Context->LinkBufferSize = BufferSize;
      Context->LinkBuffer     = AllocatePool (Context->LinkBufferSize);
      if (Context->LinkBuffer == NULL) {
        return EFI_OUT_OF_RESOURCES;
      }
463 464 465
    }
  }

466
  return EFI_SUCCESS;
467 468
}

469
STATIC
470
EFI_STATUS
471 472 473 474 475 476 477
InternalInsertPrelinkedKextDependency (
  IN OUT PRELINKED_KEXT     *Kext,
  IN OUT PRELINKED_CONTEXT  *Context,
  IN     UINT32             DependencyIndex,
  IN OUT PRELINKED_KEXT     *DependencyKext
  )
{
478
  EFI_STATUS  Status;
479 480

  if (DependencyIndex >= ARRAY_SIZE (Kext->Dependencies)) {
V
vit9696 已提交
481
    DEBUG ((DEBUG_INFO, "OCAK: Kext %a has more than %u or more dependencies!", Kext->Identifier, DependencyIndex));
482
    return EFI_OUT_OF_RESOURCES;
483 484
  }

485
  Status = InternalScanPrelinkedKext (DependencyKext, Context, TRUE);
486
  if (EFI_ERROR (Status)) {
487 488 489 490 491
    return Status;
  }

  Kext->Dependencies[DependencyIndex] = DependencyKext;

492
  return EFI_SUCCESS;
493 494
}

495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
PRELINKED_KEXT *
InternalNewPrelinkedKext (
  IN OC_MACHO_CONTEXT       *Context,
  IN XML_NODE               *KextPlist
  )
{
  PRELINKED_KEXT  *NewKext;

  NewKext = InternalCreatePrelinkedKext (NULL, KextPlist, NULL);
  if (NewKext == NULL) {
    return NULL;
  }

  CopyMem (&NewKext->Context.MachContext, Context, sizeof (NewKext->Context.MachContext));
  return NewKext;
}

V
vit9696 已提交
512 513 514 515 516
VOID
InternalFreePrelinkedKext (
  IN PRELINKED_KEXT  *Kext
  )
{
V
vit9696 已提交
517 518 519
  if (Kext->LinkedSymbolTable != NULL) {
    FreePool (Kext->LinkedSymbolTable);
    Kext->LinkedSymbolTable = NULL;
520 521 522 523 524
  }

  if (Kext->LinkedVtables != NULL) {
    FreePool (Kext->LinkedVtables);
    Kext->LinkedVtables = NULL;
V
vit9696 已提交
525 526
  }

V
vit9696 已提交
527 528 529
  FreePool (Kext);
}

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
PRELINKED_KEXT *
InternalCachedPrelinkedKext (
  IN OUT PRELINKED_CONTEXT  *Prelinked,
  IN     CONST CHAR8        *Identifier
  )
{
  PRELINKED_KEXT  *NewKext;
  LIST_ENTRY      *Kext;
  UINT32          Index;
  UINT32          KextCount;
  XML_NODE        *KextPlist;

  //
  // Find cached entry if any.
  //
  Kext = GetFirstNode (&Prelinked->PrelinkedKexts);
  while (!IsNull (&Prelinked->PrelinkedKexts, Kext)) {
    if (AsciiStrCmp (Identifier, GET_PRELINKED_KEXT_FROM_LINK (Kext)->Identifier) == 0) {
      return GET_PRELINKED_KEXT_FROM_LINK (Kext);
    }

    Kext = GetNextNode (&Prelinked->PrelinkedKexts, Kext);
  }

  //
  // Try with real entry.
  //
  NewKext   = NULL;
  KextCount = XmlNodeChildren (Prelinked->KextList);
  for (Index = 0; Index < KextCount; ++Index) {
    KextPlist = PlistNodeCast (XmlNodeChild (Prelinked->KextList, Index), PLIST_NODE_TYPE_DICT);

    if (KextPlist == NULL) {
      continue;
    }

    NewKext = InternalCreatePrelinkedKext (Prelinked, KextPlist, Identifier);
    if (NewKext != NULL) {
      break;
    }
  }

  if (NewKext == NULL) {
    return NULL;
  }

  InsertTailList (&Prelinked->PrelinkedKexts, &NewKext->Link);

  return NewKext;
}

581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
PRELINKED_KEXT *
InternalCachedPrelinkedKernel (
  IN OUT PRELINKED_CONTEXT  *Prelinked
  )
{
  LIST_ENTRY               *Kext;
  PRELINKED_KEXT           *NewKext;
  MACH_SEGMENT_COMMAND_64  *Segment;

  //
  // First entry is prelinked kernel.
  //
  Kext = GetFirstNode (&Prelinked->PrelinkedKexts);
  if (!IsNull (&Prelinked->PrelinkedKexts, Kext)) {
    return GET_PRELINKED_KEXT_FROM_LINK (Kext);
  }

  NewKext = AllocateZeroPool (sizeof (*NewKext));
  if (NewKext == NULL) {
    return NULL;
  }

603 604 605
  ASSERT (Prelinked->Prelinked != NULL);
  ASSERT (Prelinked->PrelinkedSize > 0);

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
  if (!MachoInitializeContext (&NewKext->Context.MachContext, &Prelinked->Prelinked[0], Prelinked->PrelinkedSize)) {
    FreePool (NewKext);
    return NULL;
  }

  Segment = MachoGetSegmentByName64 (
    &NewKext->Context.MachContext,
    "__TEXT"
    );
  if (Segment == NULL || Segment->VirtualAddress < Segment->FileOffset) {
    FreePool (NewKext);
    return NULL;
  }

  NewKext->Signature            = PRELINKED_KEXT_SIGNATURE;
  NewKext->Identifier           = PRELINK_KERNEL_IDENTIFIER;
  NewKext->BundleLibraries      = NULL;
  NewKext->CompatibleVersion    = "0";
  NewKext->Context.VirtualBase  = Segment->VirtualAddress - Segment->FileOffset;
  NewKext->Context.VirtualKmod  = 0;

  InsertTailList (&Prelinked->PrelinkedKexts, &NewKext->Link);

  return NewKext;
}

632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
PRELINKED_KEXT *
InternalGetQuirkDependencyKext (
  IN     CONST CHAR8        *DependencyId,
  IN OUT PRELINKED_CONTEXT  *Context
  )
{
  PRELINKED_KEXT *DependencyKext;

  ASSERT (DependencyId != NULL);
  ASSERT (Context != NULL);

  DependencyKext = NULL;
  //
  // Some kexts, notably VoodooPS2 forks, link against IOHIDSystem.kext, which is a plist-only
  // dummy, macOS does not add to the prelinkedkernel. This cannot succeed as /S/L/E directory
  // is not accessible (and can be encrypted). Normally kext's Info.plist is to be fixed, but
  // we also put a hack here to let some common kexts work.
  //
  if (AsciiStrCmp (DependencyId, "com.apple.iokit.IOHIDSystem") == 0) {
    DependencyKext = InternalCachedPrelinkedKext (Context, "com.apple.iokit.IOHIDFamily");
    DEBUG ((
      DEBUG_WARN,
      "Dependency %a fallback to %a %a. Please fix your kext!\n",
      DependencyId,
656
      "com.apple.iokit.IOHIDFamily",
657 658 659 660 661 662 663
      DependencyKext != NULL ? "succeeded" : "failed"
      ));
  }

  return DependencyKext;
}

664
EFI_STATUS
665 666
InternalScanPrelinkedKext (
  IN OUT PRELINKED_KEXT     *Kext,
667 668
  IN OUT PRELINKED_CONTEXT  *Context,
  IN     BOOLEAN            Dependency
669 670
  )
{
671
  EFI_STATUS      Status;
672 673 674 675 676
  UINT32          FieldCount;
  UINT32          FieldIndex;
  UINT32          DependencyIndex;
  CONST CHAR8     *DependencyId;
  PRELINKED_KEXT  *DependencyKext;
677
  //
678 679
  // __LINKEDIT may validly not be present, as seen for 10.7.5's
  // com.apple.kpi.unsupported.
680
  //
681 682 683 684 685 686 687 688 689 690 691
  InternalScanCurrentPrelinkedKextLinkInfo (Kext);
  //
  // Find the biggest LinkBuffer size down the first dependency tree walk to
  // possibly save a few re-allocations.
  //
  if (Context->LinkBuffer == NULL) {
    Context->LinkBufferSize = MAX (
                                InternalGetLinkBufferSize (Kext),
                                Context->LinkBufferSize
                                );
  }
V
vit9696 已提交
692

693 694 695 696 697 698 699
  //
  // Always add kernel dependency.
  //
  DependencyKext = InternalCachedPrelinkedKernel (Context);
  if (DependencyKext == NULL) {
    return EFI_NOT_FOUND;
  }
700

701 702 703 704
  if (DependencyKext != Kext) {
    Status = InternalInsertPrelinkedKextDependency (Kext, Context, 0, DependencyKext);
    if (EFI_ERROR (Status)) {
      return Status;
705
    }
706
  }
707

708 709 710
  if (Kext->BundleLibraries != NULL) {
    DependencyIndex = 1;
    FieldCount = PlistDictChildren (Kext->BundleLibraries);
711

712 713 714 715 716
    for (FieldIndex = 0; FieldIndex < FieldCount; ++FieldIndex) {
      DependencyId = PlistKeyValue (PlistDictChild (Kext->BundleLibraries, FieldIndex, NULL));
      if (DependencyId == NULL) {
        continue;
      }
717

718 719 720 721 722
      //
      // We still need to add KPI dependencies, as they may have indirect symbols,
      // which are not present in kernel (e.g. _IOLockLock).
      //
      DependencyKext = InternalCachedPrelinkedKext (Context, DependencyId);
723
      if (DependencyKext == NULL) {
V
vit9696 已提交
724
        DEBUG ((DEBUG_INFO, "OCAK: Dependency %a was not found for kext %a\n", DependencyId, Kext->Identifier));
725

726
        DependencyKext = InternalGetQuirkDependencyKext (DependencyId, Context);
727
        if (DependencyKext == NULL) {
728 729 730 731 732 733 734
          //
          // Skip missing dependencies.  PLIST-only dependencies, such as used
          // in macOS Catalina, will not be found in prelinkedkernel and are
          // assumed to be safe to ignore.  Any actual problems will be found
          // during linking.
          //
          continue;
735
        }
736 737
      }

738
      Status = InternalInsertPrelinkedKextDependency (Kext, Context, DependencyIndex, DependencyKext);
739
      if (EFI_ERROR (Status)) {
740 741 742
        return Status;
      }

743
      ++DependencyIndex;
V
vit9696 已提交
744 745
    }

746 747 748 749 750
    //
    // We do not need this anymore.
    // Additionally it may point to invalid memory on prelinked kexts.
    //
    Kext->BundleLibraries = NULL;
751 752
  }

753 754 755 756 757 758 759 760 761 762 763 764
  //
  // Extend or allocate LinkBuffer in case there are no dependencies (kernel).
  //
  Status = InternalUpdateLinkBuffer (Kext, Context);
  if (EFI_ERROR (Status)) {
    return Status;
  }
  //
  // Collect data to enable linking against this KEXT.
  //
  if (Dependency) {
    Status = InternalScanBuildLinkedSymbolTable (Kext, Context);
765
    if (EFI_ERROR (Status)) {
766 767 768
      return Status;
    }

769 770 771
    Status = InternalScanBuildLinkedVtables (Kext, Context);
    if (EFI_ERROR (Status)) {
      return Status;
772
    }
773
  }
774

775
  return EFI_SUCCESS;
776
}
777

V
vit9696 已提交
778 779 780 781 782 783 784 785 786 787 788 789 790 791
VOID
InternalUnlockContextKexts (
  IN PRELINKED_CONTEXT                *Context
  )
{
  LIST_ENTRY  *Kext;

  Kext = GetFirstNode (&Context->PrelinkedKexts);
  while (!IsNull (&Context->PrelinkedKexts, Kext)) {
    GET_PRELINKED_KEXT_FROM_LINK (Kext)->Processed = FALSE;
    Kext = GetNextNode (&Context->PrelinkedKexts, Kext);
  }
}

792 793 794 795 796 797
PRELINKED_KEXT *
InternalLinkPrelinkedKext (
  IN OUT PRELINKED_CONTEXT  *Context,
  IN OUT OC_MACHO_CONTEXT   *Executable,
  IN     XML_NODE           *PlistRoot,
  IN     UINT64             LoadAddress,
798
  IN     UINT64             KmodAddress
799 800
  )
{
801
  EFI_STATUS      Status;
802
  PRELINKED_KEXT  *Kext;
803 804 805 806 807 808

  Kext = InternalNewPrelinkedKext (Executable, PlistRoot);
  if (Kext == NULL) {
    return NULL;
  }

809
  Status = InternalScanPrelinkedKext (Kext, Context, FALSE);
810
  if (EFI_ERROR (Status)) {
811 812 813 814 815 816 817 818 819 820 821 822 823
    InternalFreePrelinkedKext (Kext);
    return NULL;
  }

  //
  // Detach Identifier from temporary memory location.
  //
  Kext->Identifier = AllocateCopyPool (AsciiStrSize (Kext->Identifier), Kext->Identifier);
  if (Kext->Identifier == NULL) {
    InternalFreePrelinkedKext (Kext);
    return NULL;
  }

824
  Status = PrelinkedDependencyInsert (Context, (VOID *)Kext->Identifier);
825
  if (EFI_ERROR (Status)) {
826
    FreePool ((VOID *)Kext->Identifier);
827 828 829 830 831 832 833 834 835 836 837 838 839
    InternalFreePrelinkedKext (Kext);
    return NULL;
  }
  //
  // Also detach bundle compatible version if any.
  //
  if (Kext->CompatibleVersion != NULL) {
    Kext->CompatibleVersion = AllocateCopyPool (AsciiStrSize (Kext->CompatibleVersion), Kext->CompatibleVersion);
    if (Kext->CompatibleVersion == NULL) {
      InternalFreePrelinkedKext (Kext);
      return NULL;
    }

840
    Status = PrelinkedDependencyInsert (Context, (VOID *)Kext->CompatibleVersion);
841
    if (EFI_ERROR (Status)) {
842
      FreePool ((VOID *)Kext->CompatibleVersion);
843 844 845 846 847 848 849 850 851 852 853 854
      InternalFreePrelinkedKext (Kext);
      return NULL;
    }
  }
  //
  // Set virtual addresses.
  //
  Kext->Context.VirtualBase = LoadAddress;
  Kext->Context.VirtualKmod = KmodAddress;

  Status = InternalPrelinkKext64 (Context, Kext, LoadAddress);

855
  if (EFI_ERROR (Status)) {
856 857 858 859
    InternalFreePrelinkedKext (Kext);
    return NULL;
  }

860 861 862
  Kext->SymbolTable     = NULL;
  Kext->StringTable     = NULL;
  Kext->NumberOfSymbols = 0;
863
  //
V
vit9696 已提交
864 865 866 867 868 869
  // TODO: VTable and entry names are not updated after relocating StringTable,
  // which means that to avoid linkage issues for plugins we must either continue
  // re-constructing VTables (as done below) or implement some optimisations.
  // For example, we could recalculate addresses after linking has finished.
  // We could also store the name's offset and access via a StringTable pointer,
  // yet it was prone to errors and was already removed once.
870 871 872 873 874 875
  //
  if (Kext->LinkedVtables != NULL) {
    FreePool (Kext->LinkedVtables);
    Kext->LinkedVtables   = NULL;
    Kext->NumberOfVtables = 0;
  }
876

877 878
  return Kext;
}