bool ApplyEnsemblePatch(const CString old_file, const CString patch_file, const CString new_file) { BYTE* old_buffer = NULL ; BYTE* patch_buffer = NULL; DWORD dwOld; DWORD dwPatch; if (!ReadFileToBuffer(old_file, old_buffer, &dwOld)) return false; if (!ReadFileToBuffer(patch_file, patch_buffer, &dwPatch)) return false; courgette::SourceStream old_stream; courgette::SourceStream patch_stream; old_stream.Init(old_buffer, dwOld); patch_stream.Init(patch_buffer, dwPatch); courgette::SinkStream new_stream; courgette::Status status = courgette::ApplyEnsemblePatch(&old_stream, &patch_stream, &new_stream); if (status != courgette::C_OK) return false; return WriteBufferToFile(new_file, reinterpret_cast<const BYTE*>(new_stream.Buffer()), new_stream.Length()); }
static CFURLRef FindJnlpURLInFile(char* fileName) { XMLNode* doc = NULL; CFURLRef returnValue = NULL; char* jnlbuffer = NULL; /* Parse XML document. */ if (!ReadFileToBuffer(fileName, &jnlbuffer)) { return NULL; } doc = ParseXMLDocument(jnlbuffer); if (doc != NULL) { XMLNode* node = NULL; char *codebase = NULL; char *href = NULL; CFStringRef baseURLString = NULL; CFStringRef hrefString = NULL; CFMutableStringRef fullURL = NULL; node = FindXMLChild(doc, "jnlp"); require(node != NULL, bail); codebase = FindXMLAttribute(node->_attributes, "codebase"); require(codebase != NULL, bail); href = FindXMLAttribute(node->_attributes, "href"); require(href != NULL, bail); baseURLString = CFStringCreateWithCString(NULL, codebase, kCFStringEncodingUTF8); require(baseURLString != NULL, bail); fullURL = CFStringCreateMutableCopy(NULL, 0, baseURLString); hrefString = CFStringCreateWithCString(NULL, href, kCFStringEncodingUTF8); require(hrefString != NULL, bail); // a relative JNLP path needs a URL that starts at the specificed codebase if (!CFStringHasSuffix(fullURL, CFSTR("/"))) CFStringAppend(fullURL, CFSTR("/")); CFStringAppend(fullURL, hrefString); returnValue = CFURLCreateWithString(NULL, fullURL, NULL); bail: if (baseURLString != NULL) CFRelease(baseURLString); if (hrefString != NULL) CFRelease(hrefString); if (fullURL != NULL) CFRelease(fullURL); FreeXMLDocument(doc); } free(jnlbuffer); return returnValue; }
/* * Parses a property file. Returns NULL if file not found or it is empty */ PropertyFileEntry* parsePropertyFile(char *filename, PropertyFileEntry* head) { PropertyFileEntry* entry = NULL; char* buffer; int size; /* Read contents of file into memory */ size = ReadFileToBuffer(filename, &buffer); /* File not found? */ if (buffer == NULL) return head; entry = parsePropertyStream(buffer, head); free(buffer); return entry; }
/** Dump capsule information @param[in] CapsuleName The name of the capsule image. @retval EFI_SUCCESS The capsule information is dumped. @retval EFI_UNSUPPORTED Input parameter is not valid. **/ EFI_STATUS DumpCapsule ( IN CHAR16 *CapsuleName ) { VOID *Buffer; UINTN FileSize; EFI_CAPSULE_HEADER *CapsuleHeader; EFI_STATUS Status; Buffer = NULL; Status = ReadFileToBuffer(CapsuleName, &FileSize, &Buffer); if (EFI_ERROR(Status)) { Print(L"CapsuleApp: Capsule (%s) is not found.\n", CapsuleName); goto Done; } if (!IsValidCapsuleHeader (Buffer, FileSize)) { Print(L"CapsuleApp: Capsule image (%s) is not a valid capsule.\n", CapsuleName); Status = EFI_INVALID_PARAMETER; goto Done; } CapsuleHeader = Buffer; if (CompareGuid(&CapsuleHeader->CapsuleGuid, &gWindowsUxCapsuleGuid)) { DumpUxCapsule(CapsuleHeader); Status = EFI_SUCCESS; goto Done; } if (CompareGuid(&CapsuleHeader->CapsuleGuid, &gEfiFmpCapsuleGuid)) { DumpFmpCapsule(CapsuleHeader); } if (IsNestedFmpCapsule(CapsuleHeader)) { Print(L"[NestedCapusule]\n"); Print(L"CapsuleHeader:\n"); Print(L" CapsuleGuid - %g\n", &CapsuleHeader->CapsuleGuid); Print(L" HeaderSize - 0x%x\n", CapsuleHeader->HeaderSize); Print(L" Flags - 0x%x\n", CapsuleHeader->Flags); Print(L" CapsuleImageSize - 0x%x\n", CapsuleHeader->CapsuleImageSize); DumpFmpCapsule((EFI_CAPSULE_HEADER *)((UINTN)CapsuleHeader + CapsuleHeader->HeaderSize)); } Done: if (Buffer != NULL) { FreePool(Buffer); } return Status; }
// main function to do the spkg decrypt/unpackage int do_spp_decrypt(char* pInPath, char* pOutPath, char* pKeyName) { u8* pMySpp = NULL; u64 dec_size = 0; u64 hdr_len = 0; uint32_t dwBytesRead = 0; sce_header_t* pSceHdr = NULL; int retval = -1; // validate input params if ( (pInPath == NULL) || (pOutPath == NULL) ) goto exit; // read the spp file into a buffer (alloc a new buffer) if ( ReadFileToBuffer(pInPath,(uint8_t**)&pMySpp, 0x00, &dwBytesRead, TRUE) != STATUS_SUCCESS ) { printf("failed to read in file:%s, exiting...\n", pInPath); goto exit; } /// Unpackage the "PKG" types /// if ( decrypt_spp(pMySpp, &dec_size, pKeyName) != STATUS_SUCCESS ) { printf("\n!!ERROR!! FAILED to decrypt SPP file:%s\n\n", pInPath); goto exit; } // setup the SCE header pSceHdr = (sce_header_t*)pMySpp;//SIZE_SPKG_HDR wbe64((u8*)&hdr_len, pSceHdr->header_len); // write the decrypted file to disk if ( WriteBufferToFile(pOutPath, (pMySpp+hdr_len), (uint32_t)dec_size, FALSE, 0, NULL) != STATUS_SUCCESS ) { printf("failed to write to file:%s, exiting...\n", pOutPath); goto exit; } // status success retval = STATUS_SUCCESS; exit: // free the alloc'd memory if (pMySpp != NULL) free(pMySpp); return retval; }
int _tmain(int argc, _TCHAR* argv[]) { CMyHttpManager http_mgr ; HTTP_REQUEST_HEADER h (HTTP_REQUEST_HEADER::VERB_TYPE_POST_MULTIPART) ; // your url h.m_url = L"http://www.you_url.com" ; // add string param h.AddMultipartFormData ("param1", "value of param1") ; h.AddMultipartFormData ("param2", "value of param2") ; // add post file, read file into buf std::vector<BYTE> file_buf ; ReadFileToBuffer (L"c:\\1.jpg", file_buf) ; if (file_buf.size()) { h.AddMultipartFormData ("param3", &file_buf[0], file_buf.size(), "123.jpg") ; } // add end flag h.EndMultipartFormData() ; http_mgr.AddRequest (h) ; // wait result MSG msg ; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg) ; DispatchMessage(&msg) ; } return 0 ; }
SECStatus AddCertificateFromFile(const char* basePath, const char* filename) { char buf[16384] = { 0 }; SECStatus rv = ReadFileToBuffer(basePath, filename, buf); if (rv != SECSuccess) { return rv; } SECItem certDER; rv = CERT_DecodeCertPackage(buf, strlen(buf), DecodeCertCallback, &certDER); if (rv != SECSuccess) { PrintPRError("CERT_DecodeCertPackage failed"); return rv; } ScopedCERTCertificate cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &certDER, nullptr, false, true)); PORT_Free(certDER.data); if (!cert) { PrintPRError("CERT_NewTempCertificate failed"); return SECFailure; } ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot()); if (!slot) { PrintPRError("PK11_GetInternalKeySlot failed"); return SECFailure; } // The nickname is the filename without '.pem'. std::string nickname(filename, strlen(filename) - 4); rv = PK11_ImportCert(slot, cert, CK_INVALID_HANDLE, nickname.c_str(), false); if (rv != SECSuccess) { PrintPRError("PK11_ImportCert failed"); return rv; } return SECSuccess; }
/** Update Capsule image. @param[in] ImageHandle The image handle. @param[in] SystemTable The system table. @retval EFI_SUCCESS Command completed successfully. @retval EFI_UNSUPPORTED Command usage unsupported. @retval EFI_INVALID_PARAMETER Command usage invalid. @retval EFI_NOT_FOUND The input file can't be found. **/ EFI_STATUS EFIAPI UefiMain ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; RETURN_STATUS RStatus; UINTN FileSize[MAX_CAPSULE_NUM]; VOID *CapsuleBuffer[MAX_CAPSULE_NUM]; EFI_CAPSULE_BLOCK_DESCRIPTOR *BlockDescriptors; EFI_CAPSULE_HEADER *CapsuleHeaderArray[MAX_CAPSULE_NUM + 1]; UINT64 MaxCapsuleSize; EFI_RESET_TYPE ResetType; BOOLEAN NeedReset; BOOLEAN NoReset; CHAR16 *CapsuleName; UINTN CapsuleNum; UINTN Index; Status = GetArg(); if (EFI_ERROR(Status)) { Print(L"Please use UEFI SHELL to run this application!\n", Status); return Status; } if (Argc < 2) { PrintUsage(); return EFI_UNSUPPORTED; } if (StrCmp(Argv[1], L"-D") == 0) { if (Argc != 3) { Print(L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } Status = DumpCapsule(Argv[2]); return Status; } if (StrCmp(Argv[1], L"-G") == 0) { Status = CreateBmpFmp(); return Status; } if (StrCmp(Argv[1], L"-N") == 0) { Status = CreateNestedFmp(); return Status; } if (StrCmp(Argv[1], L"-S") == 0) { Status = DmpCapsuleStatusVariable(); return EFI_SUCCESS; } if (StrCmp(Argv[1], L"-C") == 0) { Status = ClearCapsuleStatusVariable(); return Status; } if (StrCmp(Argv[1], L"-P") == 0) { if (Argc == 2) { DumpFmpData(); } if (Argc >= 3) { if (StrCmp(Argv[2], L"GET") != 0) { Print(L"CapsuleApp: Unrecognized option(%s).\n", Argv[2]); return EFI_UNSUPPORTED; } else { if (Argc != 7) { Print(L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } EFI_GUID ImageTypeId; UINTN ImageIndex; // // FMP->GetImage() // RStatus = StrToGuid (Argv[3], &ImageTypeId); if (RETURN_ERROR (RStatus) || (Argv[3][GUID_STRING_LENGTH] != L'\0')) { Print (L"Invalid ImageTypeId - %s\n", Argv[3]); return EFI_INVALID_PARAMETER; } ImageIndex = StrDecimalToUintn(Argv[4]); if (StrCmp(Argv[5], L"-O") != 0) { Print(L"CapsuleApp: NO output file name.\n"); return EFI_UNSUPPORTED; } DumpFmpImage(&ImageTypeId, ImageIndex, Argv[6]); } } return EFI_SUCCESS; } if (StrCmp(Argv[1], L"-E") == 0) { DumpEsrtData(); return EFI_SUCCESS; } if (Argv[1][0] == L'-') { Print(L"CapsuleApp: Unrecognized option(%s).\n", Argv[1]); return EFI_UNSUPPORTED; } CapsuleFirstIndex = 1; NoReset = FALSE; if ((Argc > 1) && (StrCmp(Argv[Argc - 1], L"-NR") == 0)) { NoReset = TRUE; CapsuleLastIndex = Argc - 2; } else { CapsuleLastIndex = Argc - 1; } CapsuleNum = CapsuleLastIndex - CapsuleFirstIndex + 1; if (CapsuleFirstIndex > CapsuleLastIndex) { Print(L"CapsuleApp: NO capsule image.\n"); return EFI_UNSUPPORTED; } if (CapsuleNum > MAX_CAPSULE_NUM) { Print(L"CapsuleApp: Too many capsule images.\n"); return EFI_UNSUPPORTED; } ZeroMem(&CapsuleBuffer, sizeof(CapsuleBuffer)); ZeroMem(&FileSize, sizeof(FileSize)); BlockDescriptors = NULL; for (Index = 0; Index < CapsuleNum; Index++) { CapsuleName = Argv[CapsuleFirstIndex + Index]; Status = ReadFileToBuffer(CapsuleName, &FileSize[Index], &CapsuleBuffer[Index]); if (EFI_ERROR(Status)) { Print(L"CapsuleApp: capsule image (%s) is not found.\n", CapsuleName); goto Done; } if (!IsValidCapsuleHeader (CapsuleBuffer[Index], FileSize[Index])) { Print(L"CapsuleApp: Capsule image (%s) is not a valid capsule.\n", CapsuleName); return EFI_INVALID_PARAMETER; } } // // Every capsule use 2 descriptor 1 for data 1 for end // Status = BuildGatherList(CapsuleBuffer, FileSize, CapsuleNum, &BlockDescriptors); if (EFI_ERROR(Status)) { goto Done; } // // Call the runtime service capsule. // NeedReset = FALSE; for (Index = 0; Index < CapsuleNum; Index++) { CapsuleHeaderArray[Index] = (EFI_CAPSULE_HEADER *) CapsuleBuffer[Index]; if ((CapsuleHeaderArray[Index]->Flags & CAPSULE_FLAGS_PERSIST_ACROSS_RESET) != 0) { NeedReset = TRUE; } } CapsuleHeaderArray[CapsuleNum] = NULL; // // Inquire platform capability of UpdateCapsule. // Status = gRT->QueryCapsuleCapabilities (CapsuleHeaderArray, CapsuleNum, &MaxCapsuleSize, &ResetType); if (EFI_ERROR(Status)) { Print (L"CapsuleApp: failed to query capsule capability - %r\n", Status); goto Done; } for (Index = 0; Index < CapsuleNum; Index++) { if (FileSize[Index] > MaxCapsuleSize) { Print (L"CapsuleApp: capsule is too large to update, %ld is allowed\n", MaxCapsuleSize); Status = EFI_UNSUPPORTED; goto Done; } } // // Check whether the input capsule image has the flag of persist across system reset. // if (NeedReset) { Status = gRT->UpdateCapsule(CapsuleHeaderArray,CapsuleNum,(UINTN) BlockDescriptors); if (Status != EFI_SUCCESS) { Print (L"CapsuleApp: failed to update capsule - %r\n", Status); goto Done; } // // For capsule with CAPSULE_FLAGS_PERSIST_ACROSS_RESET + CAPSULE_FLAGS_INITIATE_RESET, // a system reset should have been triggered by gRT->UpdateCapsule() calling above. // // For capsule with CAPSULE_FLAGS_PERSIST_ACROSS_RESET and without CAPSULE_FLAGS_INITIATE_RESET, // check if -NR (no-reset) has been specified or not. // if (!NoReset) { // // For capsule who has reset flag and no -NR (no-reset) has been specified, after calling UpdateCapsule service, // trigger a system reset to process capsule persist across a system reset. // gRT->ResetSystem (ResetType, EFI_SUCCESS, 0, NULL); } } else { // // For capsule who has no reset flag, only call UpdateCapsule Service without a // system reset. The service will process the capsule immediately. // Status = gRT->UpdateCapsule (CapsuleHeaderArray,CapsuleNum,(UINTN) BlockDescriptors); if (Status != EFI_SUCCESS) { Print (L"CapsuleApp: failed to update capsule - %r\n", Status); } } Status = EFI_SUCCESS; Done: for (Index = 0; Index < CapsuleNum; Index++) { if (CapsuleBuffer[Index] != NULL) { FreePool (CapsuleBuffer[Index]); } } CleanGatherList(BlockDescriptors, CapsuleNum); return Status; }
/** Append a capsule header on top of current image. This function follows Windows UEFI Firmware Update Platform document. @retval EFI_SUCCESS The capsule header is appended. @retval EFI_UNSUPPORTED Input parameter is not valid. @retval EFI_OUT_OF_RESOURCES No enough resource to append capsule header. **/ EFI_STATUS CreateNestedFmp ( VOID ) { CHAR16 *OutputCapsuleName; VOID *CapsuleBuffer; UINTN FileSize; CHAR16 *CapsuleName; UINT8 *FullCapsuleBuffer; UINTN FullCapsuleBufferSize; EFI_CAPSULE_HEADER *NestedCapsuleHeader; EFI_GUID *ImageTypeId; UINT32 FwType; EFI_STATUS Status; if (Argc != 5) { Print(L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } if (StrCmp(Argv[3], L"-O") != 0) { Print(L"CapsuleApp: NO output capsule name.\n"); return EFI_UNSUPPORTED; } OutputCapsuleName = Argv[4]; CapsuleBuffer = NULL; FileSize = 0; FullCapsuleBuffer = NULL; CapsuleName = Argv[2]; Status = ReadFileToBuffer(CapsuleName, &FileSize, &CapsuleBuffer); if (EFI_ERROR(Status)) { Print(L"CapsuleApp: Capsule image (%s) is not found.\n", CapsuleName); goto Done; } ImageTypeId = GetCapsuleImageTypeId(CapsuleBuffer); if (ImageTypeId == NULL) { Print(L"CapsuleApp: Capsule ImageTypeId is not found.\n"); goto Done; } FwType = GetEsrtFwType(ImageTypeId); if ((FwType != ESRT_FW_TYPE_SYSTEMFIRMWARE) && (FwType != ESRT_FW_TYPE_DEVICEFIRMWARE)) { Print(L"CapsuleApp: Capsule FwType is invalid.\n"); goto Done; } FullCapsuleBufferSize = NESTED_CAPSULE_HEADER_SIZE + FileSize; FullCapsuleBuffer = AllocatePool(FullCapsuleBufferSize); if (FullCapsuleBuffer == NULL) { Print(L"CapsuleApp: Capsule Buffer size (0x%x) too big.\n", FullCapsuleBufferSize); Status = EFI_OUT_OF_RESOURCES; goto Done; } NestedCapsuleHeader = (EFI_CAPSULE_HEADER *)FullCapsuleBuffer; ZeroMem(NestedCapsuleHeader, NESTED_CAPSULE_HEADER_SIZE); CopyGuid(&NestedCapsuleHeader->CapsuleGuid, ImageTypeId); NestedCapsuleHeader->HeaderSize = NESTED_CAPSULE_HEADER_SIZE; NestedCapsuleHeader->Flags = (FwType == ESRT_FW_TYPE_SYSTEMFIRMWARE) ? SYSTEM_FIRMWARE_FLAG : DEVICE_FIRMWARE_FLAG; NestedCapsuleHeader->CapsuleImageSize = (UINT32)FullCapsuleBufferSize; CopyMem((UINT8 *)NestedCapsuleHeader + NestedCapsuleHeader->HeaderSize, CapsuleBuffer, FileSize); Status = WriteFileFromBuffer(OutputCapsuleName, FullCapsuleBufferSize, FullCapsuleBuffer); Print(L"CapsuleApp: Write %s %r\n", OutputCapsuleName, Status); Done: if (CapsuleBuffer != NULL) { FreePool(CapsuleBuffer); } if (FullCapsuleBuffer != NULL) { FreePool(FullCapsuleBuffer); } return Status; }
/** Create UX capsule. @retval EFI_SUCCESS The capsule header is appended. @retval EFI_UNSUPPORTED Input parameter is not valid. @retval EFI_OUT_OF_RESOURCES No enough resource to create UX capsule. **/ EFI_STATUS CreateBmpFmp ( VOID ) { CHAR16 *OutputCapsuleName; VOID *BmpBuffer; UINTN FileSize; CHAR16 *BmpName; UINT8 *FullCapsuleBuffer; UINTN FullCapsuleBufferSize; EFI_DISPLAY_CAPSULE *DisplayCapsule; EFI_STATUS Status; EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop; EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info; EFI_GRAPHICS_OUTPUT_BLT_PIXEL *GopBlt; UINTN GopBltSize; UINTN Height; UINTN Width; Status = gBS->LocateProtocol(&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&Gop); if (EFI_ERROR(Status)) { Print(L"CapsuleApp: NO GOP is found.\n"); return EFI_UNSUPPORTED; } Info = Gop->Mode->Info; Print(L"Current GOP: Mode - %d, ", Gop->Mode->Mode); Print(L"HorizontalResolution - %d, ", Info->HorizontalResolution); Print(L"VerticalResolution - %d\n", Info->VerticalResolution); // HorizontalResolution >= BMP_IMAGE_HEADER.PixelWidth // VerticalResolution >= BMP_IMAGE_HEADER.PixelHeight if (Argc != 5) { Print(L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } if (StrCmp(Argv[3], L"-O") != 0) { Print(L"CapsuleApp: NO output capsule name.\n"); return EFI_UNSUPPORTED; } OutputCapsuleName = Argv[4]; BmpBuffer = NULL; FileSize = 0; FullCapsuleBuffer = NULL; BmpName = Argv[2]; Status = ReadFileToBuffer(BmpName, &FileSize, &BmpBuffer); if (EFI_ERROR(Status)) { Print(L"CapsuleApp: BMP image (%s) is not found.\n", BmpName); goto Done; } GopBlt = NULL; Status = TranslateBmpToGopBlt ( BmpBuffer, FileSize, &GopBlt, &GopBltSize, &Height, &Width ); if (EFI_ERROR(Status)) { Print(L"CapsuleApp: BMP image (%s) is not valid.\n", BmpName); goto Done; } if (GopBlt != NULL) { FreePool (GopBlt); } Print(L"BMP image (%s), Width - %d, Height - %d\n", BmpName, Width, Height); if (Height > Info->VerticalResolution) { Status = EFI_INVALID_PARAMETER; Print(L"CapsuleApp: BMP image (%s) height is larger than current resolution.\n", BmpName); goto Done; } if (Width > Info->HorizontalResolution) { Status = EFI_INVALID_PARAMETER; Print(L"CapsuleApp: BMP image (%s) width is larger than current resolution.\n", BmpName); goto Done; } FullCapsuleBufferSize = sizeof(EFI_DISPLAY_CAPSULE) + FileSize; FullCapsuleBuffer = AllocatePool(FullCapsuleBufferSize); if (FullCapsuleBuffer == NULL) { Print(L"CapsuleApp: Capsule Buffer size (0x%x) too big.\n", FullCapsuleBufferSize); Status = EFI_OUT_OF_RESOURCES; goto Done; } DisplayCapsule = (EFI_DISPLAY_CAPSULE *)FullCapsuleBuffer; CopyGuid(&DisplayCapsule->CapsuleHeader.CapsuleGuid, &gWindowsUxCapsuleGuid); DisplayCapsule->CapsuleHeader.HeaderSize = sizeof(DisplayCapsule->CapsuleHeader); DisplayCapsule->CapsuleHeader.Flags = CAPSULE_FLAGS_PERSIST_ACROSS_RESET; DisplayCapsule->CapsuleHeader.CapsuleImageSize = (UINT32)FullCapsuleBufferSize; DisplayCapsule->ImagePayload.Version = 1; DisplayCapsule->ImagePayload.Checksum = 0; DisplayCapsule->ImagePayload.ImageType = 0; // BMP DisplayCapsule->ImagePayload.Reserved = 0; DisplayCapsule->ImagePayload.Mode = Gop->Mode->Mode; // // Center the bitmap horizontally // DisplayCapsule->ImagePayload.OffsetX = (UINT32)((Info->HorizontalResolution - Width) / 2); // // Put bitmap 3/4 down the display. If bitmap is too tall, then align bottom // of bitmap at bottom of display. // DisplayCapsule->ImagePayload.OffsetY = MIN ( (UINT32)(Info->VerticalResolution - Height), (UINT32)(((3 * Info->VerticalResolution) - (2 * Height)) / 4) ); Print(L"BMP image (%s), OffsetX - %d, OffsetY - %d\n", BmpName, DisplayCapsule->ImagePayload.OffsetX, DisplayCapsule->ImagePayload.OffsetY ); CopyMem((DisplayCapsule + 1), BmpBuffer, FileSize); DisplayCapsule->ImagePayload.Checksum = CalculateCheckSum8(FullCapsuleBuffer, FullCapsuleBufferSize); Status = WriteFileFromBuffer(OutputCapsuleName, FullCapsuleBufferSize, FullCapsuleBuffer); Print(L"CapsuleApp: Write %s %r\n", OutputCapsuleName, Status); Done: if (BmpBuffer != NULL) { FreePool(BmpBuffer); } if (FullCapsuleBuffer != NULL) { FreePool(FullCapsuleBuffer); } return Status; }
EFI_STATUS GetProtocolAssertion ( IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, IN CHAR16 *FilePath, OUT UINT32 *PassNumber, OUT UINT32 *WarnNumber, OUT UINT32 *FailNumber ) /*++ Routine Description: Get the assertion number of a protocol or service. Arguments: DevicePath - Device path of the key files. FilePath - Path of the key files. PassNumber - The number of passed assertions. WarnNumber - The number of warning assertions. FailNumber - The number of failed assertions. Returns: EFI_SUCCESS - Get instance assertion number successfully. --*/ { EFI_STATUS Status; EFI_HANDLE DeviceHandle; EFI_FILE_HANDLE RootDir; EFI_FILE_HANDLE LogDir; UINTN FileInfoSize; EFI_FILE_INFO *FileInfo; EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Vol; EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; UINTN BufferSize; CHAR16 *Buffer; CHAR16 *FileName; CHAR16 *LogName; CHAR16 *TempName; CHAR16 *CaseIndexStr; CHAR16 *CaseIterationStr; // // Check parameters // if ((DevicePath == NULL) || (FilePath == NULL) || (PassNumber == NULL) || (WarnNumber == NULL) || (FailNumber == NULL)) { return EFI_INVALID_PARAMETER; } // // Locate the device handle // RemainingDevicePath = DevicePath; Status = BS->LocateDevicePath ( &gEfiSimpleFileSystemProtocolGuid, &RemainingDevicePath, &DeviceHandle ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Locate device path - %r", Status)); return Status; } // // Locate the simple file system // Status = BS->HandleProtocol ( DeviceHandle, &gEfiSimpleFileSystemProtocolGuid, &Vol ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Handle protocol - %r", Status)); return Status; } // // Open the root directory // Status = Vol->OpenVolume (Vol, &RootDir); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Open volume - %r", Status)); return Status; } // // Open the log directory // Status = RootDir->Open ( RootDir, &LogDir, FilePath, EFI_FILE_MODE_READ, EFI_FILE_DIRECTORY ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Open directory - %r", Status)); RootDir->Close (RootDir); return Status; } RootDir->Close (RootDir); // // Allocate memory for the entries in the directory // FileInfoSize = sizeof(EFI_FILE_INFO) + 1024; Status = BS->AllocatePool ( EfiBootServicesData, FileInfoSize, &FileInfo ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Allocate pool - %r", Status)); LogDir->Close (LogDir); return Status; } // // Walk through each file in the directory // while (TRUE) { // // Read a file entry // FileInfoSize = sizeof(EFI_FILE_INFO) + 1024; Status = LogDir->Read ( LogDir, &FileInfoSize, FileInfo ); if (EFI_ERROR (Status) || (FileInfoSize == 0)) { break; } if ((FileInfo->Attribute & EFI_FILE_DIRECTORY) == 0) { // // This is a file // // // Only deal with the EFI key file // if (!SctStrEndWith (FileInfo->FileName, L".ekl")) { continue; } // // Read the file to a buffer // FileName = PoolPrint (L"%s\\%s", FilePath, FileInfo->FileName); if (FileName == NULL) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"PoolPrint: Out of resources")); return EFI_OUT_OF_RESOURCES; } Status = ReadFileToBuffer ( DevicePath, FileName, &BufferSize, &Buffer ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_DEBUG, L"Read file to buffer - %r", Status)); BS->FreePool (FileName); continue; } BS->FreePool (FileName); // // Get the index and iteration from the file name // TempName = StrDuplicate (FileInfo->FileName); // // The following function didn't allocate memory for CaseIndexStr and // CaseIterationStr. So DON'T free the TempName before these two strings // are still used. // Status = GetIndexFromFileName ( TempName, &CaseIndexStr, &CaseIterationStr ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_DEBUG, L"Get index from file name - %r", Status)); BS->FreePool (TempName); continue; } // // Load the buffer to the report information structure // LogName = SctStrEndReplace (FileInfo->FileName, L"log"); Status = LoadReportInfor ( CaseIndexStr, CaseIterationStr, Buffer, LogName ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_DEBUG, L"Load report infor - %r", Status)); BS->FreePool (TempName); BS->FreePool (LogName); BS->FreePool (Buffer); continue; } BS->FreePool (TempName); BS->FreePool (LogName); BS->FreePool (Buffer); // // Get the assertion number (free the GUID assertion table) // Status = GetAssertionNumber (PassNumber, WarnNumber, FailNumber); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_DEBUG, L"Get assertion number - %r", Status)); continue; } } else { // // This is a directory // // // Skip the '.' and '..' dir // if ((StrCmp (FileInfo->FileName, L".") == 0) || (StrCmp (FileInfo->FileName, L"..") == 0)) { continue; } // // Get the report information from the sub directories // FileName = PoolPrint (L"%s\\%s", FilePath, FileInfo->FileName); if (FileName == NULL) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"PoolPrint: Out of resources")); return EFI_OUT_OF_RESOURCES; } Status = GetProtocolAssertion ( DevicePath, FileName, PassNumber, WarnNumber, FailNumber ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_DEBUG, L"Get protocol assertion - %r", Status)); BS->FreePool (FileName); continue; } BS->FreePool (FileName); } } // // Free resources // BS->FreePool (FileInfo); LogDir->Close (LogDir); // // Done // return EFI_SUCCESS; }
EFI_STATUS LoadGuidDatabase ( IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, IN CHAR16 *FileName ) /*++ Routine Description: Load the GUID database from a file. --*/ { EFI_STATUS Status; UINTN BufferSize; CHAR16 *Buffer; CHAR16 *LineBuffer; CHAR16 *GuidStr; CHAR16 *TitleStr; CHAR16 *IndexStr; // // Check parameters // if ((DevicePath == NULL) || (FileName == NULL)) { return EFI_INVALID_PARAMETER; } // // Read the database file // Status = ReadFileToBuffer ( DevicePath, FileName, &BufferSize, (VOID **)&Buffer ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Read file to buffer - %r", Status)); return Status; } // // Skip the first unicode char 0xFEFF // if (Buffer[0] != 0xFEFF) { EFI_SCT_DEBUG ((EFI_SCT_D_DEBUG, L"Unsupported GUID database file")); BS->FreePool (Buffer); return EFI_SUCCESS; } LineBuffer = StrTokenLine (Buffer + 1, L"\n\r"); // // Walk through the GUID database file // while (LineBuffer != NULL) { if (LineBuffer[0] == L'#') { LineBuffer = StrTokenLine (NULL, L"\n\r"); continue; } // // Get the GUID string // GuidStr = LineBuffer; // // Get the Title string // TitleStr = StrTokenLine (NULL, L"\n\r"); if (TitleStr == NULL) { LineBuffer = StrTokenLine (NULL, L"\n\r"); continue; } // // Get the Index string // IndexStr = StrTokenLine (NULL, L"\n\r"); if (IndexStr == NULL) { LineBuffer = StrTokenLine (NULL, L"\n\r"); continue; } // // Insert the entry into the GUID database // Status = InsertGuidDatabase (GuidStr, TitleStr, IndexStr); if (EFI_ERROR (Status)) { break; } // // Next line // LineBuffer = StrTokenLine (NULL, L"\n\r"); } BS->FreePool (Buffer); return EFI_SUCCESS; }
//----------------------------------------------------------------------------- // Generate a tree containing files from a reslist. Returns TRUE if successful. //----------------------------------------------------------------------------- bool LoadReslist( const char *pReslistName, CUtlRBTree< CUtlString, int > *pTree ) { CUtlBuffer buffer; if ( !scriptlib->ReadFileToBuffer( pReslistName, buffer, true ) ) { return false; } char szBasename[MAX_PATH]; V_FileBase( pReslistName, szBasename, sizeof( szBasename ) ); characterset_t breakSet; CharacterSetBuild( &breakSet, "" ); // parse reslist char szToken[MAX_PATH]; char szBspName[MAX_PATH]; szBspName[0] = '\0'; for ( ;; ) { int nTokenSize = buffer.ParseToken( &breakSet, szToken, sizeof( szToken ) ); if ( nTokenSize <= 0 ) { break; } // reslists are pc built, filenames can be sloppy V_strlower( szToken ); V_FixSlashes( szToken ); V_RemoveDotSlashes( szToken ); // can safely cull filetypes that are ignored by queued loader at runtime bool bKeep = false; const char *pExt = V_GetFileExtension( szToken ); if ( !pExt ) { // unknown continue; } else if ( !V_stricmp( pExt, "vmt" ) || !V_stricmp( pExt, "vhv" ) || !V_stricmp( pExt, "mdl" ) || !V_stricmp( pExt, "raw" ) || !V_stricmp( pExt, "wav" ) ) { bKeep = true; } else if ( !V_stricmp( pExt, "mp3" ) ) { // change to .wav V_SetExtension( szToken, ".wav", sizeof( szToken ) ); bKeep = true; } else if ( !V_stricmp( pExt, "bsp" ) ) { // reslists erroneously have multiple bsps if ( !V_stristr( szToken, szBasename ) ) { // wrong one, cull it continue; } else { // right one, save it strcpy( szBspName, szToken ); bKeep = true; } } if ( bKeep ) { FindOrAddFileToResourceList( szToken, pTree ); } } if ( !szBspName[0] ) { // reslist is not bsp derived, nothing more to do return true; } CUtlVector< CUtlString > bspList; bool bOK = GetDependants_BSP( szBspName, &bspList ); if ( !bOK ) { return false; } // add all the bsp dependants to the resource list for ( int i=0; i<bspList.Count(); i++ ) { FindOrAddFileToResourceList( bspList[i].String(), pTree ); } // iterate all the models in the resource list, get all their dependents CUtlVector< CUtlString > modelList; for ( int i = pTree->FirstInorder(); i != pTree->InvalidIndex(); i = pTree->NextInorder( i ) ) { const char *pExt = V_GetFileExtension( pTree->Element( i ).String() ); if ( !pExt || V_stricmp( pExt, "mdl" ) ) { continue; } if ( !GetDependants_MDL( pTree->Element( i ).String(), &modelList ) ) { return false; } } // add all the model dependents to the resource list for ( int i=0; i<modelList.Count(); i++ ) { FindOrAddFileToResourceList( modelList[i].String(), pTree ); } // check for optional commentary, include wav dependencies char szCommentaryName[MAX_PATH]; V_ComposeFileName( g_szGamePath, szBspName, szCommentaryName, sizeof( szCommentaryName ) ); V_StripExtension( szCommentaryName, szCommentaryName, sizeof( szCommentaryName ) ); V_strncat( szCommentaryName, "_commentary.txt", sizeof( szCommentaryName ) ); CUtlBuffer commentaryBuffer; if ( ReadFileToBuffer( szCommentaryName, commentaryBuffer, true, true ) ) { // any single token may be quite large to due to text char szCommentaryToken[8192]; for ( ;; ) { int nTokenSize = commentaryBuffer.ParseToken( &breakSet, szCommentaryToken, sizeof( szCommentaryToken ) ); if ( nTokenSize < 0 ) { break; } if ( nTokenSize > 0 && !V_stricmp( szCommentaryToken, "commentaryfile" ) ) { // get the commentary file nTokenSize = commentaryBuffer.ParseToken( &breakSet, szCommentaryToken, sizeof( szCommentaryToken ) ); if ( nTokenSize > 0 ) { // skip past sound chars char *pName = szCommentaryToken; while ( *pName && IsSoundChar( *pName ) ) { pName++; } char szWavFile[MAX_PATH]; V_snprintf( szWavFile, sizeof( szWavFile ), "sound/%s", pName ); FindOrAddFileToResourceList( szWavFile, pTree ); } } } } // check for optional blacklist char szBlacklist[MAX_PATH]; V_ComposeFileName( g_szGamePath, "reslistfixes_xbox.xsc", szBlacklist, sizeof( szBlacklist ) ); CUtlBuffer blacklistBuffer; if ( ReadFileToBuffer( szBlacklist, blacklistBuffer, true, true ) ) { for ( ;; ) { int nTokenSize = blacklistBuffer.ParseToken( &breakSet, szToken, sizeof( szToken ) ); if ( nTokenSize <= 0 ) { break; } bool bAdd; if ( !V_stricmp( szToken, "-" ) ) { bAdd = false; } else if ( !V_stricmp( szToken, "+" ) ) { bAdd = true; } else { // bad syntax, skip line Msg( "Bad Syntax, expecting '+' or '-' as first token in reslist fixup file '%s'.\n", szBlacklist ); continue; } // get entry nTokenSize = blacklistBuffer.ParseToken( &breakSet, szToken, sizeof( szToken ) ); if ( nTokenSize <= 0 ) { break; } if ( bAdd ) { FindOrAddFileToResourceList( szToken, pTree ); } else { RemoveFileFromResourceList( szToken, pTree ); } } } return true; }
int main(int argc, char *argv[]) { // These should be set by command switches but aren't at the moment PRBool bSearchForUnicodeProgIDs = PR_FALSE; PRBool bSearchForUnicodeLibraries = PR_FALSE; if (argc != 2) { fprintf(stderr, "Usage: dumpdeps <mozbindirectory>\n"); return 1; } std::string sBinDirPath = argv[1]; nsIServiceManager *mServiceManager; nsILocalFile *pBinDirPath = nsnull; nsresult res = NS_NewLocalFile(sBinDirPath.c_str(), &pBinDirPath); // Initialise XPCOM if (pBinDirPath == nsnull) { fprintf(stderr, "Error: Could not create object to represent mozbindirectory - is the path correct?\n"); return 1; } NS_InitXPCOM(&mServiceManager, pBinDirPath); NS_RELEASE(pBinDirPath); // Read the component registry to fill the arrays with CLSIDs ReadComponentRegistry(); // Locate all libraries and add them to the components list // BEGIN WINDOWS SPECIFIC for (int n = 0; n < 2; n++) { // Windows specific paths std::string sFolder; if (n == 0) { sFolder = sBinDirPath + "\\"; } else if (n == 1) { sFolder = sBinDirPath + "\\components\\"; } std::string sPattern = sFolder + "*.dll"; WIN32_FIND_DATA findData; HANDLE h = FindFirstFile(sPattern.c_str(), &findData); if (h) { do { std::string fullPath = sFolder + findData.cFileName; listComponents.push_back(library(fullPath.c_str(), findData.cFileName)); } while (FindNextFile(h, &findData)); } FindClose(h); } // END WINDOWS SPECIFIC // Enumerate through all libraries looking for dependencies std::vector<library>::const_iterator i; for (i = listComponents.begin(); i != listComponents.end(); i++) { char *pszBuffer = NULL; long nBufferSize = 0; if (ReadFileToBuffer((*i).mFullPath.c_str(), &pszBuffer, &nBufferSize)) { printf("Library \"%s\"\n", (*i).mFullPath.c_str()); // Print out implements printf(" Implements:\n"); // Search for CIDs implemented by this library std::vector<factory>::const_iterator j; for (j = listCLSIDs.begin(); j != listCLSIDs.end(); j++) { if (LibraryImplementsCID((*i).mFile.c_str(), (*j).mCID)) { OutputCID((*j).mCID); } } // Print out references printf(" References:\n"); // Search for CIDs not implemented by this library but referenced for (j = listCLSIDs.begin(); j != listCLSIDs.end(); j++) { if (!LibraryImplementsCID((*i).mFile.c_str(), (*j).mCID) && ScanBuffer(pszBuffer, nBufferSize, &(*j).mCID, sizeof((*j).mCID)) == 1) { OutputCID((*j).mCID); } } // Search for ProgIds wchar_t szWTmp[1024]; std::vector<progid2cid>::const_iterator k; for (k = listProgIDs.begin(); k != listProgIDs.end(); k++) { // Skip ProgIds that the library implements if (LibraryImplementsCID((*i).mFile.c_str(), (*k).mCID)) { continue; } // Search for ANSI strings const char *szA = (*k).mProgID.c_str(); int nLength = (*k).mProgID.length(); if (ScanBuffer(pszBuffer, nBufferSize, szA, nLength) == 1) { OutputProgId(szA); continue; } if (bSearchForUnicodeProgIDs) { // Search for Unicode strings wchar_t *szW = A2W((*k).mProgID.c_str(), szWTmp, sizeof(szWTmp) / sizeof(szWTmp[0])); if (ScanBuffer(pszBuffer, nBufferSize, szW, nLength * sizeof(wchar_t)) == 1) { printf("UNICODE Progid\n"); OutputProgId(szA); continue; } } } printf(" Statically linked to:\n"); std::vector<library>::const_iterator l; for (l = listComponents.begin(); l != listComponents.end(); l++) { // Skip when the full path and the component point to the same thing if (i == l) { continue; } // Search for ANSI strings const char *szA = (*l).mFile.c_str(); int nLength = (*l).mFile.length(); if (ScanBuffer(pszBuffer, nBufferSize, szA, nLength) == 1) { OutputLibrary(szA); continue; } if (bSearchForUnicodeLibraries) { // Search for Unicode strings wchar_t *szW = A2W((*l).mFile.c_str(), szWTmp, sizeof(szWTmp) / sizeof(szWTmp[0])); if (ScanBuffer(pszBuffer, nBufferSize, szW, nLength * sizeof(wchar_t)) == 1) { printf("UNICODE library\n"); OutputLibrary(szA); continue; } } } delete []pszBuffer; } } return 0; }
/** Create UX capsule. @retval EFI_SUCCESS The capsule header is appended. @retval EFI_UNSUPPORTED Input parameter is not valid. @retval EFI_OUT_OF_RESOURCES No enough resource to create UX capsule. **/ EFI_STATUS CreateBmpFmp ( VOID ) { CHAR16 *OutputCapsuleName; VOID *BmpBuffer; UINTN FileSize; CHAR16 *BmpName; UINT8 *FullCapsuleBuffer; UINTN FullCapsuleBufferSize; EFI_DISPLAY_CAPSULE *DisplayCapsule; EFI_STATUS Status; EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop; Status = gBS->LocateProtocol(&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&Gop); if (EFI_ERROR(Status)) { Print(L"CapsuleApp: NO GOP is found.\n"); return EFI_UNSUPPORTED; } Print(L"Current GOP: Mode - %d, ", Gop->Mode->Mode); Print(L"HorizontalResolution - %d, ", Gop->Mode->Info->HorizontalResolution); Print(L"VerticalResolution - %d\n", Gop->Mode->Info->VerticalResolution); // HorizontalResolution >= BMP_IMAGE_HEADER.PixelWidth // VerticalResolution >= BMP_IMAGE_HEADER.PixelHeight if (Argc != 5) { Print(L"CapsuleApp: Invalid Parameter.\n"); return EFI_UNSUPPORTED; } if (StrCmp(Argv[3], L"-O") != 0) { Print(L"CapsuleApp: NO output capsule name.\n"); return EFI_UNSUPPORTED; } OutputCapsuleName = Argv[4]; BmpBuffer = NULL; FileSize = 0; FullCapsuleBuffer = NULL; BmpName = Argv[2]; Status = ReadFileToBuffer(BmpName, &FileSize, &BmpBuffer); if (EFI_ERROR(Status)) { Print(L"CapsuleApp: BMP image (%s) is not found.\n", BmpName); goto Done; } FullCapsuleBufferSize = sizeof(EFI_DISPLAY_CAPSULE) + FileSize; FullCapsuleBuffer = AllocatePool(FullCapsuleBufferSize); if (FullCapsuleBuffer == NULL) { Print(L"CapsuleApp: Capsule Buffer size (0x%x) too big.\n", FullCapsuleBufferSize); Status = EFI_OUT_OF_RESOURCES; goto Done; } DisplayCapsule = (EFI_DISPLAY_CAPSULE *)FullCapsuleBuffer; CopyGuid(&DisplayCapsule->CapsuleHeader.CapsuleGuid, &gWindowsUxCapsuleGuid); DisplayCapsule->CapsuleHeader.HeaderSize = sizeof(DisplayCapsule->CapsuleHeader); DisplayCapsule->CapsuleHeader.Flags = CAPSULE_FLAGS_PERSIST_ACROSS_RESET; DisplayCapsule->CapsuleHeader.CapsuleImageSize = (UINT32)FullCapsuleBufferSize; DisplayCapsule->ImagePayload.Version = 1; DisplayCapsule->ImagePayload.Checksum = 0; DisplayCapsule->ImagePayload.ImageType = 0; // BMP DisplayCapsule->ImagePayload.Reserved = 0; DisplayCapsule->ImagePayload.Mode = Gop->Mode->Mode; DisplayCapsule->ImagePayload.OffsetX = 0; DisplayCapsule->ImagePayload.OffsetY = 0; CopyMem((DisplayCapsule + 1), BmpBuffer, FileSize); DisplayCapsule->ImagePayload.Checksum = CalculateCheckSum8(FullCapsuleBuffer, FullCapsuleBufferSize); Status = WriteFileFromBuffer(OutputCapsuleName, FullCapsuleBufferSize, FullCapsuleBuffer); Print(L"CapsuleApp: Write %s %r\n", OutputCapsuleName, Status); Done: if (BmpBuffer != NULL) { FreePool(BmpBuffer); } if (FullCapsuleBuffer != NULL) { FreePool(FullCapsuleBuffer); } return Status; }
bool Workspace::Load(const char* relativePath, bool bForce) { BEHAVIAC_ASSERT(behaviac::StringUtils::FindExtension(relativePath) == 0, "no extention to specify"); BEHAVIAC_ASSERT(IsValidPath(relativePath)); BehaviorTree* pBT = 0; BehaviorTrees_t::iterator it = ms_behaviortrees.find(relativePath); if (it != ms_behaviortrees.end()) { if (!bForce) { return true; } pBT = it->second; } behaviac::string fullPath = ms_workspace_export_path; fullPath += relativePath; Workspace::EFileFormat f = Workspace::GetFileFormat(); switch (f) { case EFF_default: { // try to load the behavior in xml behaviac::string path = fullPath + ".xml"; if (CFileManager::GetInstance()->FileExists(path.c_str())) { f = EFF_xml; fullPath = path; } else { // try to load the behavior in bson path = fullPath + ".bson.bytes"; if (CFileManager::GetInstance()->FileExists(path.c_str())) { f = EFF_bson; fullPath = path; } // try to load the behavior in cpp else { f = EFF_cpp; } } } break; case EFF_xml: fullPath += ".xml"; break; case EFF_bson: fullPath += ".bson.bytes"; break; case EFF_cpp: break; default: BEHAVIAC_ASSERT(0); break; } bool bLoadResult = false; bool bNewly = false; if (!pBT) { //in case of circular referencebehavior bNewly = true; pBT = BEHAVIAC_NEW BehaviorTree(); ms_behaviortrees[relativePath] = pBT; } BEHAVIAC_ASSERT(pBT); bool bCleared = false; if (f == EFF_xml || f == EFF_bson) { char* pBuffer = ReadFileToBuffer(fullPath.c_str()); if (pBuffer) { //if forced to reload if (!bNewly) { bCleared = true; pBT->Clear(); } if (f == EFF_xml) { bLoadResult = pBT->load_xml(pBuffer); } else { bLoadResult = pBT->load_bson(pBuffer); } PopFileFromBuffer(pBuffer); } else { BEHAVIAC_LOGWARNING("Workspace::Load:FileNotOpen %s", fullPath.c_str()); } } else if (f == EFF_cpp) { if (!bNewly) { bCleared = true; pBT->Clear(); } if (ms_behaviortreeCreators && ms_behaviortreeCreators->find(relativePath) != ms_behaviortreeCreators->end()) { BehaviorTreeCreator_t btCreator = (*ms_behaviortreeCreators)[relativePath]; bLoadResult = (*btCreator)(pBT); } else { BEHAVIAC_ASSERT(0); BEHAVIAC_LOGWARNING("The generated_behaviors.cpp file should be included by the app."); } } else { BEHAVIAC_ASSERT(0); } if (bLoadResult) { BEHAVIAC_ASSERT(pBT->GetName() == relativePath); if (!bNewly) { BEHAVIAC_ASSERT(ms_behaviortrees[pBT->GetName()] == pBT); } } else { if (bNewly) { //if it is forced to reload ms_behaviortrees.erase(relativePath); BEHAVIAC_DELETE(pBT); } else if (bCleared) { //it has been cleared but failed to load, to remove it ms_behaviortrees.erase(relativePath); } BEHAVIAC_LOGWARNING("BehaviorTree %s not loaded!\n", fullPath.c_str()); } return bLoadResult; }
/** * 응용프로그램의 C 언어 엔트리 포인트 */ int Main( char* pcArgument ) { QWORD qwWindowID; int iX; int iY; int iWidth; int iHeight; TEXTINFO stInfo; int iMoveLine; EVENT stReceivedEvent; KEYEVENT* pstKeyEvent; WINDOWEVENT* pstWindowEvent; DWORD dwFileOffset; RECT stScreenArea; //-------------------------------------------------------------------------- // 그래픽 모드 판단 //-------------------------------------------------------------------------- // MINT64 OS가 그래픽 모드로 시작했는지 확인 if( IsGraphicMode() == FALSE ) { // MINT64 OS가 그래픽 모드로 시작하지 않았다면 실패 printf( "This task can run only GUI mode~!!!\n" ); return -1; } //-------------------------------------------------------------------------- // 파일의 내용을 파일 버퍼에 저장하고 라인 별 파일 오프셋 저장용 버퍼를 생성 //-------------------------------------------------------------------------- // 인자에 아무것도 전달되지 않으면 실패 if( strlen( pcArgument ) == 0 ) { printf( "ex) exec textviwer.elf abc.txt\n" ); return 0; } // 파일을 디렉터리에서 찾은 뒤에 파일의 크기만큼 메모리를 할당하여 파일을 저장 // 라인 별 파일 오프셋을 저장할 버퍼도 같이 생성 if( ReadFileToBuffer( pcArgument, &stInfo ) == FALSE ) { printf( "%s file is not found\n", pcArgument ); return 0; } //-------------------------------------------------------------------------- // 윈도우와 라인 인덱스를 생성한 뒤 첫 번째 라인부터 화면에 출력 //-------------------------------------------------------------------------- // 윈도우를 화면 가운데에 가로 500 픽셀 X 세로 500 픽셀로 생성 GetScreenArea( &stScreenArea ); iWidth = 500; iHeight = 500; iX = ( GetRectangleWidth( &stScreenArea ) - iWidth ) / 2; iY = ( GetRectangleHeight( &stScreenArea ) - iHeight ) / 2; qwWindowID = CreateWindow(iX, iY, iWidth, iHeight, WINDOW_FLAGS_DEFAULT | WINDOW_FLAGS_RESIZABLE, "Text Viewer" ); // 라인 별 파일 오프셋을 계산하고 현재 화면에 출력하는 라인 인덱스를 0으로 설정 CalculateFileOffsetOfLine( iWidth, iHeight, &stInfo ); stInfo.iCurrentLineIndex = 0; // 현재 라인부터 화면 전체 크기만큼을 표시 DrawTextBuffer( qwWindowID, &stInfo ); //-------------------------------------------------------------------------- // GUI 태스크의 이벤트 처리 루프 //-------------------------------------------------------------------------- while( 1 ) { // 이벤트 큐에서 이벤트를 수신 if( ReceiveEventFromWindowQueue( qwWindowID, &stReceivedEvent ) == FALSE ) { Sleep( 10 ); continue; } // 수신된 이벤트를 타입에 따라 나누어 처리 switch( stReceivedEvent.qwType ) { // 키 눌림 처리 case EVENT_KEY_DOWN: pstKeyEvent = &( stReceivedEvent.stKeyEvent ); if( pstKeyEvent->bFlags & KEY_FLAGS_DOWN ) { // 키 값에 따른 현재 라인 변경 값 설정 switch( pstKeyEvent->bASCIICode ) { // Page Up 키와 Page Down 키는 화면에 출력 가능한 라인 단위로 이동 case KEY_PAGEUP: iMoveLine = -stInfo.iRowCount; break; case KEY_PAGEDOWN: iMoveLine = stInfo.iRowCount; break; // Up 키와 Down 키는 한 라인 단위로 이동 case KEY_UP: iMoveLine = -1; break; case KEY_DOWN: iMoveLine = 1; break; // 기타 키이거나 현재 위치에서 움직일 필요가 없으면 종료 default: iMoveLine = 0; break; } // 최대 최소 라인 범위를 벗어나면 현재 라인 인덱스를 조정 if( stInfo.iCurrentLineIndex + iMoveLine < 0 ) { iMoveLine = -stInfo.iCurrentLineIndex; } else if( stInfo.iCurrentLineIndex + iMoveLine >= stInfo.iMaxLineCount ) { iMoveLine = stInfo.iMaxLineCount - stInfo.iCurrentLineIndex - 1; } // 기타 키이거나 움직일 필요가 없으면 종료 if( iMoveLine == 0 ) { break; } // 현재 라인의 인덱스를 변경하고 화면에 출력 stInfo.iCurrentLineIndex += iMoveLine; DrawTextBuffer( qwWindowID, &stInfo ); } break; // 윈도우 크기 변경 처리 case EVENT_WINDOW_RESIZE: pstWindowEvent = &( stReceivedEvent.stWindowEvent ); iWidth = GetRectangleWidth( &( pstWindowEvent->stArea ) ); iHeight = GetRectangleHeight( &( pstWindowEvent->stArea ) ); // 현재 라인이 있는 파일 오프셋을 저장 dwFileOffset = stInfo.pdwFileOffsetOfLine[ stInfo.iCurrentLineIndex ]; // 변경된 화면 크기로 다시 라인 수와 라인 당 문자 수, 그리고 파일 오프셋을 // 계산하고 이 값과 이전에 저장한 파일 오프셋을 이용하여 현재 라인을 다시 계산 CalculateFileOffsetOfLine( iWidth, iHeight, &stInfo ); stInfo.iCurrentLineIndex = dwFileOffset / stInfo.iColumnCount; // 현재 라인부터 화면에 출력 DrawTextBuffer( qwWindowID, &stInfo ); break; // 윈도우 닫기 버튼 처리 case EVENT_WINDOW_CLOSE: // 윈도우를 삭제하고 메모리를 해제 DeleteWindow( qwWindowID ); free( stInfo.pbFileBuffer ); free( stInfo.pdwFileOffsetOfLine ); return 0; break; // 그 외 정보 default: break; } } return 0; }
EFI_STATUS GetInstanceAssertion ( IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, IN CHAR16 *MetaName, OUT EFI_SCT_LOG_STATE *FileState, OUT UINT32 *Index, OUT UINT32 *Iteration, OUT UINT32 *PassNumber, OUT UINT32 *WarnNumber, OUT UINT32 *FailNumber ) /*++ Routine Description: Get the assertion number of a instance. Arguments: DevicePath - Device path of the key files. MetaName - Meta name of the key files. FileState - The log state. Index - The index of the instance. Interation - The index of the iteration. PassNumber - The number of passed assertions. WarnNumber - The number of warning assertions. FailNumber - The number of failed assertions. Returns: EFI_SUCCESS - Get instance assertion number successfully. --*/ { EFI_STATUS Status; CHAR16 *FileName; UINT32 InstanceIndex; UINT32 IterationIndex; UINTN BufferSize; CHAR16 *Buffer; // // Check parameters // if ((DevicePath == NULL) || (MetaName == NULL) || (FileState == NULL) || (Index == NULL) || (Iteration == NULL) || (PassNumber == NULL) || (WarnNumber == NULL) || (FailNumber == NULL)) { return EFI_INVALID_PARAMETER; } // // Initialize // *FileState = EFI_SCT_LOG_STATE_UNKNOWN; *Index = 0; *Iteration = 0; *PassNumber = 0; *WarnNumber = 0; *FailNumber = 0; InstanceIndex = 0; IterationIndex = 0; // // Found the maximum index of instance and iteration // for (InstanceIndex = 0; TRUE; InstanceIndex ++) { for (IterationIndex = 0; TRUE; IterationIndex ++) { FileName = PoolPrint (MetaName, InstanceIndex, IterationIndex); if (FileName == NULL) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"PoolPrint: Out of resources")); return EFI_OUT_OF_RESOURCES; } if (!FileExist (DevicePath, FileName)) { // // File does not exist // if (IterationIndex != 0) { *Index = InstanceIndex; *Iteration = IterationIndex - 1; } BS->FreePool (FileName); break; } BS->FreePool (FileName); } if (IterationIndex == 0) { break; } } // // No instance file is found // if ((InstanceIndex == 0) && (IterationIndex == 0)) { *FileState = EFI_SCT_LOG_STATE_EMPTY; *Index = 0; *Iteration = 0; return EFI_SUCCESS; } // // The maximum instance index is found // FileName = PoolPrint (MetaName, *Index, *Iteration); if (FileName == NULL) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"PoolPrint: Out of resources")); return EFI_OUT_OF_RESOURCES; } // // Read the file to a buffer // Status = ReadFileToBuffer ( DevicePath, FileName, &BufferSize, &Buffer ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Read file to buffer - %r", Status)); BS->FreePool (FileName); return Status; } BS->FreePool (FileName); // // Load the buffer to the GUID assertion table with duplicate // Status = LoadGuidAssertion (Buffer, TRUE, FileState); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Load GUID assertion - %r", Status)); BS->FreePool (Buffer); return Status; } BS->FreePool (Buffer); // // Get the assertion number (free the GUID assertion table) // Status = GetAssertionNumber (PassNumber, WarnNumber, FailNumber); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"Get assertion number - %r", Status)); return Status; } // // Done // return EFI_SUCCESS; }
SECStatus AddKeyFromFile(const char* basePath, const char* filename) { const char* PRIVATE_KEY_HEADER = "-----BEGIN PRIVATE KEY-----"; const char* PRIVATE_KEY_FOOTER = "-----END PRIVATE KEY-----"; char buf[16384] = { 0 }; SECStatus rv = ReadFileToBuffer(basePath, filename, buf); if (rv != SECSuccess) { return rv; } if (strncmp(buf, PRIVATE_KEY_HEADER, strlen(PRIVATE_KEY_HEADER)) != 0) { PR_fprintf(PR_STDERR, "invalid key - not importing\n"); return SECFailure; } const char* bufPtr = buf + strlen(PRIVATE_KEY_HEADER); size_t bufLen = strlen(buf); char base64[16384] = { 0 }; char* base64Ptr = base64; while (bufPtr < buf + bufLen) { if (strncmp(bufPtr, PRIVATE_KEY_FOOTER, strlen(PRIVATE_KEY_FOOTER)) == 0) { break; } if (*bufPtr != '\r' && *bufPtr != '\n') { *base64Ptr = *bufPtr; base64Ptr++; } bufPtr++; } unsigned int binLength; UniquePORTString bin( reinterpret_cast<char*>(ATOB_AsciiToData(base64, &binLength))); if (!bin || binLength == 0) { PrintPRError("ATOB_AsciiToData failed"); return SECFailure; } ScopedSECItem secitem(::SECITEM_AllocItem(nullptr, nullptr, binLength)); if (!secitem) { PrintPRError("SECITEM_AllocItem failed"); return SECFailure; } PORT_Memcpy(secitem->data, bin.get(), binLength); ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot()); if (!slot) { PrintPRError("PK11_GetInternalKeySlot failed"); return SECFailure; } if (PK11_NeedUserInit(slot)) { if (PK11_InitPin(slot, nullptr, nullptr) != SECSuccess) { PrintPRError("PK11_InitPin failed"); return SECFailure; } } SECKEYPrivateKey* privateKey; if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot, secitem, nullptr, nullptr, true, false, KU_ALL, &privateKey, nullptr) != SECSuccess) { PrintPRError("PK11_ImportDERPrivateKeyInfoAndReturnKey failed"); return SECFailure; } SECKEY_DestroyPrivateKey(privateKey); return SECSuccess; }
///////////////////////////////////////////////////////////////////////////////////////////////////// // // For Vista/2008, 32bit // Last mod: 2008.10.30 // BOOL CThemeFileInfo::GetPatchInfoVista32( LPTSTR pszTargetFile, // In, file name PPatchInfo pInfo // Out, Patch info ) { // The magic sign UCHAR szSignChar[] = {0x8B, 0x33, 0x8B, 0xFF, 0x55, 0x8B, 0xEC}; UCHAR szSignIndex[] = {0, 16, 23, 1, 2, 3 , 4}; ULONG ulSignMagicIndex= 5; ULONG ulLenSignChar = sizeof(szSignChar); // The Cracked char, we need to patch file to this UCHAR szPatchChar[] = {0x33, 0xC0, 0xC9, 0xC2, 0x04, 0x00}; ULONG ulLenPatchChar = sizeof(szPatchChar); // define the range to search ULONG ulFileReadStart = 0x2000; ULONG ulFileReadEnd = 0x50000; // // Begin of stable Code // BOOL bRet = FALSE; DWORD dwMatch = 0; // The count of matched sign DWORD dwPatchOffset = 0; // Sign offset in the file PATCH_STATUS_CLASS PatchStatus = PATCH_UNKNOWN; PVOID pBuffer = NULL; // Pointer to File buffer DWORD dwBufferSize = 0; // File buffer size PUCHAR pData = 0; // pointer to the data ULONG i = 0; ULONG k = 0; // Try to open file pBuffer = ReadFileToBuffer(pszTargetFile, &ulFileReadStart, &ulFileReadEnd, &dwBufferSize); if (NULL == pBuffer) { // Fail to open file return FALSE; } pData = (PUCHAR)pBuffer; for (i = 0; i < (dwBufferSize - 64); i++) { if ( (*(PUCHAR)(pData + i) == szSignChar[0]) && (*(PUCHAR)(pData + i + szSignIndex[1]) == szSignChar[1]) ) { for (k = 2; k < ulLenSignChar; k++) { // if sign not match, then break if ( *(PUCHAR)(pData + i + szSignIndex[k]) != szSignChar[k] ) break; } // before win7 M1 if ( (k == ulLenSignChar) && (*(PUCHAR)(pData + i + 33) == 0xF6) && (*(PUCHAR)(pData + i + 34) == 0xD8) ) { //TRACEF(_T("Windows 7 M1, and before\n"), dwPatchOffset); // patched version if ( (*(PUCHAR)(pData + i + ulSignMagicIndex) == 0x33) && (*(PUCHAR)(pData + i + ulSignMagicIndex + 1)== 0xC0) ) { PatchStatus = PATCH_YES; // get the real patch offset in the file dwPatchOffset = ulFileReadStart + ( i + ulSignMagicIndex); dwMatch ++; } else if ( (*(PUCHAR)(pData + i + ulSignMagicIndex) == 0x81) && (*(PUCHAR)(pData + i + ulSignMagicIndex + 1) == 0xEC) ) // not patched { // not patched PatchStatus = PATCH_NO; // get the real patch offset in the file dwPatchOffset = ulFileReadStart + ( i + ulSignMagicIndex); dwMatch ++; } //TRACEF(_T("Get the right magic offset: 0x%08x\n"), dwPatchOffset); } // all char match, before win7 M1 else if ( (k == ulLenSignChar) && (*(PUCHAR)(pData + i + 33) == 0x0F) && (*(PUCHAR)(pData + i + 36) == 0xF7) ) { // win 7 M3 //TRACEF(_T("Windows 7 M3, and later\n"), dwPatchOffset); // patched version if ( (*(PUCHAR)(pData + i + ulSignMagicIndex) == 0x33) && (*(PUCHAR)(pData + i + ulSignMagicIndex + 1)== 0xC0) ) { PatchStatus = PATCH_YES; // get the real patch offset in the file dwPatchOffset = ulFileReadStart + ( i + ulSignMagicIndex); dwMatch ++; } else if ( (*(PUCHAR)(pData + i + ulSignMagicIndex) == 0x81) && (*(PUCHAR)(pData + i + ulSignMagicIndex + 1) == 0xEC) ) // not patched { // not patched PatchStatus = PATCH_NO; // get the real patch offset in the file dwPatchOffset = ulFileReadStart + ( i + ulSignMagicIndex); dwMatch ++; } //TRACEF(_T("Get the right magic offset: 0x%08x\n"), dwPatchOffset); } // all char match, after win7 M3 } // first 2 char match } // for i // Important! free memory if (NULL != pBuffer) FREE(pBuffer); // if match count is 1, we are sure it's the correct offset. if (dwMatch == 1) { pInfo->PatchOffset = dwPatchOffset; pInfo->PatchStatus = PatchStatus; pInfo->PatchCharLength = ulLenPatchChar; CopyMemory(pInfo->PatchChar, szPatchChar, ulLenPatchChar); } else { // match count is 0, or more than 1, so it's unknown pInfo->PatchOffset = 0; pInfo->PatchStatus = PATCH_UNKNOWN; pInfo->PatchCharLength = 0; } pInfo->MatchingCount = dwMatch; return TRUE; } // GetPatchInfoVista32
EFI_STATUS SctReportConfig ( OUT UINTN *BufferSize, OUT VOID **Buffer ) /*++ Routine Description: Report the system configuration via shell commands. --*/ { EFI_STATUS Status; UINTN Index; CHAR16 *CmdLine; CHAR16 *FileName; CHAR16 *CmdList[] = { L"map -v", L"memmap", L"pci", L"ver", L"dh -v", L"" }; // // Record an empty line to a file via shell command // CmdLine = PoolPrint ( L"ECHO \" \" >a %s", EFI_SCT_FILE_CFG ); if (CmdLine == NULL) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"PoolPrint: Out of resources")); return EFI_OUT_OF_RESOURCES; } Status = ShellExecute ( gFT->ImageHandle, CmdLine, FALSE ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"ShellExecute: %s - %r", CmdLine, Status)); BS->FreePool (CmdLine); return Status; } BS->FreePool (CmdLine); // // For each shell command // for (Index = 0; CmdList[Index][0] != L'\0'; Index++) { // // Record the command to a file via shell command // CmdLine = PoolPrint ( L"ECHO \"%s\" >>a %s", CmdList[Index], EFI_SCT_FILE_CFG ); if (CmdLine == NULL) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"PoolPrint: Out of resources")); return EFI_OUT_OF_RESOURCES; } Status = ShellExecute ( gFT->ImageHandle, CmdLine, FALSE ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"ShellExecute: %s - %r", CmdLine, Status)); BS->FreePool (CmdLine); return Status; } BS->FreePool (CmdLine); // // Get the system configuration to a file via shell command // CmdLine = PoolPrint ( L"%s >>a %s", CmdList[Index], EFI_SCT_FILE_CFG ); if (CmdLine == NULL) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"PoolPrint: Out of resources")); return EFI_OUT_OF_RESOURCES; } Status = ShellExecute ( gFT->ImageHandle, CmdLine, FALSE ); if (EFI_ERROR (Status)) { // // Just record as a debug info. It is acceptable for this command return // an error status // EFI_SCT_DEBUG ((EFI_SCT_D_DEBUG, L"ShellExecute: %s - %r", CmdLine, Status)); } BS->FreePool (CmdLine); } // // Get the system configuration from the file // FileName = PoolPrint ( L"%s\\%s", gFT->FilePath, EFI_SCT_FILE_CFG ); if (FileName == NULL) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"PoolPrint: Out of resources")); return EFI_OUT_OF_RESOURCES; } Status = ReadFileToBuffer ( gFT->DevicePath, FileName, BufferSize, (VOID **)Buffer ); if (EFI_ERROR (Status)) { EFI_SCT_DEBUG ((EFI_SCT_D_ERROR, L"ReadFileToBuffer: %s - %r", FileName, Status)); BS->FreePool (FileName); return Status; } BS->FreePool (FileName); // // Done // return EFI_SUCCESS; }
///////////////////////////////////////////////////////////////////////////////////////////////////// // // For Vista/2008, 64bit // Last mod: 2009.04.07 // 2009.04.07: Modified PATCH_YES比较条件, 去除&& (*(PUCHAR)(chbuf+i+9)== 0xDB),兼容其它补丁 // 2009.03.30: Modified ulPointEnd 0x50000 -> 0x70000, support windows 7 x64 7068 // BOOL CThemeFileInfo::GetPatchInfoVista64( LPTSTR pszTargetFile, // In, file name PPatchInfo pInfo // Out, Patch info ) { // The magic sign UCHAR szSignChar[] = {0x48, 0x8B, 0x48, 0x89, 0x55, 0x56, 0x57, 0x48, 0x08, 0x8B, 0xF9}; UCHAR szSignIndex[] = {0, 16, 33, 1, 5, 6 , 7, 22, 39, 34 , 35}; ULONG ulSignMagicIndex= 8; ULONG ulLenSignChar = sizeof(szSignChar); // The Cracked char, we need to patch file to this UCHAR szPatchChar[] = {0x33, 0xDB, 0x8B, 0xC3, 0x5F, 0x5E, 0x5D, 0xC3}; ULONG ulLenPatchChar = sizeof(szPatchChar); // define the range to search ULONG ulFileReadStart = 0x2000; ULONG ulFileReadEnd = 0x80000; // // Begin of stable Code // BOOL bRet = FALSE; DWORD dwMatch = 0; // The count of matched sign DWORD dwPatchOffset = 0; // Sign offset in the file PATCH_STATUS_CLASS PatchStatus = PATCH_UNKNOWN; PVOID pBuffer = NULL; // Pointer to File buffer DWORD dwBufferSize = 0; // File buffer size PUCHAR pData = 0; // pointer to the data ULONG i = 0; ULONG k = 0; // Try to open file pBuffer = ReadFileToBuffer(pszTargetFile, &ulFileReadStart, &ulFileReadEnd, &dwBufferSize); if (NULL == pBuffer) { // Fail to open file return FALSE; } pData = (PUCHAR)pBuffer; for (i = 0; i < (dwBufferSize - 64); i++) { if ( (*(PUCHAR)(pData + i) == szSignChar[0]) && (*(PUCHAR)(pData + i + szSignIndex[1]) == szSignChar[1]) ) { for (k = 2; k < ulLenSignChar; k++) { // if sign not match, then break if ( *(PUCHAR)(pData + i + szSignIndex[k]) != szSignChar[k] ) break; } if (k == ulLenSignChar) { // patched version if ( (*(PUCHAR)(pData + i + ulSignMagicIndex) == 0x33) && (*(PUCHAR)(pData + i + 15) == 0xC3) ) { PatchStatus = PATCH_YES; // get the real patch offset in the file dwPatchOffset = ulFileReadStart + ( i + ulSignMagicIndex); dwMatch ++; } else if ( (*(PUCHAR)(pData + i + ulSignMagicIndex) == 0x48) && (*(PUCHAR)(pData + i + ulSignMagicIndex + 1) == 0x81) && (*(PUCHAR)(pData + i + 15) == 0x48)) // not patched { // not patched PatchStatus = PATCH_NO; // get the real patch offset in the file dwPatchOffset = ulFileReadStart + ( i + ulSignMagicIndex); dwMatch ++; } else if (*(PUCHAR)(pData + i + ulSignMagicIndex) == 0x33) // not sure { // 2009.04.06, not sure status PatchStatus = PATCH_UNSURE; // get the real patch offset in the file dwPatchOffset = ulFileReadStart + ( i + ulSignMagicIndex); //LimitedValue = *(PUCHAR)(chbuf+i+8); dwMatch ++; } //TRACEF(_T("Get the right magic offset: 0x%08x\n"), dwPatchOffset); } // all char match } // first 2 char match } // for i // Important! free memory if (NULL != pBuffer) FREE(pBuffer); // if match count is 1, we are sure it's the correct offset. if (dwMatch == 1) { pInfo->PatchOffset = dwPatchOffset; pInfo->PatchStatus = PatchStatus; pInfo->PatchCharLength = ulLenPatchChar; CopyMemory(pInfo->PatchChar, szPatchChar, ulLenPatchChar); } else { // match count is 0, or more than 1, so it's unknown pInfo->PatchOffset = 0; pInfo->PatchStatus = PATCH_UNKNOWN; pInfo->PatchCharLength = 0; } pInfo->MatchingCount = dwMatch; return TRUE; } // GetPatchInfoVista64
//----------------------------------------------------------------------------- // Rebuilds all of a MDL's components. //----------------------------------------------------------------------------- static bool GenerateModelFiles( const char *pMdlFilename ) { CUtlBuffer tempBuffer; int fileSize; int paddedSize; int swappedSize; // .mdl CUtlBuffer mdlBuffer; if ( !scriptlib->ReadFileToBuffer( pMdlFilename, mdlBuffer ) ) { return false; } if ( !Studio_ConvertStudioHdrToNewVersion( (studiohdr_t *)mdlBuffer.Base() )) { Msg("%s needs to be recompiled\n", pMdlFilename ); } // .vtx char szVtxFilename[MAX_PATH]; V_StripExtension( pMdlFilename, szVtxFilename, sizeof( szVtxFilename ) ); V_strncat( szVtxFilename, ".dx90.vtx", sizeof( szVtxFilename ) ); CUtlBuffer vtxBuffer; bool bHasVtx = ReadFileToBuffer( szVtxFilename, vtxBuffer, false, true ); // .vvd char szVvdFilename[MAX_PATH]; V_StripExtension( pMdlFilename, szVvdFilename, sizeof( szVvdFilename ) ); V_strncat( szVvdFilename, ".vvd", sizeof( szVvdFilename ) ); CUtlBuffer vvdBuffer; bool bHasVvd = ReadFileToBuffer( szVvdFilename, vvdBuffer, false, true ); if ( bHasVtx != bHasVvd ) { // paired resources, either mandates the other return false; } // a .mdl file that has .vtx/.vvd gets re-processed to cull lod data if ( bHasVtx && bHasVvd ) { // cull lod if needed IMdlStripInfo *pStripInfo = NULL; bool bResult = mdllib->StripModelBuffers( mdlBuffer, vvdBuffer, vtxBuffer, &pStripInfo ); if ( !bResult ) { return false; } if ( pStripInfo ) { // .vsi CUtlBuffer vsiBuffer; pStripInfo->Serialize( vsiBuffer ); pStripInfo->DeleteThis(); // save strip info for later processing char szVsiFilename[MAX_PATH]; V_StripExtension( pMdlFilename, szVsiFilename, sizeof( szVsiFilename ) ); V_strncat( szVsiFilename, ".vsi", sizeof( szVsiFilename ) ); WriteBufferToFile( szVsiFilename, vsiBuffer, false, WRITE_TO_DISK_ALWAYS ); } } // .ani processing may further update .mdl buffer char szAniFilename[MAX_PATH]; V_StripExtension( pMdlFilename, szAniFilename, sizeof( szAniFilename ) ); V_strncat( szAniFilename, ".ani", sizeof( szAniFilename ) ); CUtlBuffer aniBuffer; bool bHasAni = ReadFileToBuffer( szAniFilename, aniBuffer, false, true ); if ( bHasAni ) { // Some vestigal .ani files exist in the tree, only process valid .ani if ( ((studiohdr_t*)mdlBuffer.Base())->numanimblocks != 0 ) { // .ani processing modifies .mdl buffer fileSize = aniBuffer.TellPut(); paddedSize = fileSize + BYTESWAP_ALIGNMENT_PADDING; aniBuffer.EnsureCapacity( paddedSize ); tempBuffer.EnsureCapacity( paddedSize ); V_StripExtension( pMdlFilename, szAniFilename, sizeof( szAniFilename ) ); V_strncat( szAniFilename, ".360.ani", sizeof( szAniFilename ) ); swappedSize = StudioByteSwap::ByteswapStudioFile( szAniFilename, tempBuffer.Base(), aniBuffer.PeekGet(), fileSize, (studiohdr_t*)mdlBuffer.Base(), CompressFunc ); if ( swappedSize > 0 ) { // .ani buffer is replaced with swapped data aniBuffer.Purge(); aniBuffer.Put( tempBuffer.Base(), swappedSize ); WriteBufferToFile( szAniFilename, aniBuffer, false, WRITE_TO_DISK_ALWAYS ); } else { return false; } } } // .phy char szPhyFilename[MAX_PATH]; V_StripExtension( pMdlFilename, szPhyFilename, sizeof( szPhyFilename ) ); V_strncat( szPhyFilename, ".phy", sizeof( szPhyFilename ) ); CUtlBuffer phyBuffer; bool bHasPhy = ReadFileToBuffer( szPhyFilename, phyBuffer, false, true ); if ( bHasPhy ) { fileSize = phyBuffer.TellPut(); paddedSize = fileSize + BYTESWAP_ALIGNMENT_PADDING; phyBuffer.EnsureCapacity( paddedSize ); tempBuffer.EnsureCapacity( paddedSize ); V_StripExtension( pMdlFilename, szPhyFilename, sizeof( szPhyFilename ) ); V_strncat( szPhyFilename, ".360.phy", sizeof( szPhyFilename ) ); swappedSize = StudioByteSwap::ByteswapStudioFile( szPhyFilename, tempBuffer.Base(), phyBuffer.PeekGet(), fileSize, (studiohdr_t*)mdlBuffer.Base(), CompressFunc ); if ( swappedSize > 0 ) { // .phy buffer is replaced with swapped data phyBuffer.Purge(); phyBuffer.Put( tempBuffer.Base(), swappedSize ); WriteBufferToFile( szPhyFilename, phyBuffer, false, WRITE_TO_DISK_ALWAYS ); } else { return false; } } if ( bHasVtx ) { fileSize = vtxBuffer.TellPut(); paddedSize = fileSize + BYTESWAP_ALIGNMENT_PADDING; vtxBuffer.EnsureCapacity( paddedSize ); tempBuffer.EnsureCapacity( paddedSize ); V_StripExtension( pMdlFilename, szVtxFilename, sizeof( szVtxFilename ) ); V_strncat( szVtxFilename, ".dx90.360.vtx", sizeof( szVtxFilename ) ); swappedSize = StudioByteSwap::ByteswapStudioFile( szVtxFilename, tempBuffer.Base(), vtxBuffer.PeekGet(), fileSize, (studiohdr_t*)mdlBuffer.Base(), CompressFunc ); if ( swappedSize > 0 ) { // .vtx buffer is replaced with swapped data vtxBuffer.Purge(); vtxBuffer.Put( tempBuffer.Base(), swappedSize ); WriteBufferToFile( szVtxFilename, vtxBuffer, false, WRITE_TO_DISK_ALWAYS ); } else { return false; } } if ( bHasVvd ) { fileSize = vvdBuffer.TellPut(); paddedSize = fileSize + BYTESWAP_ALIGNMENT_PADDING; vvdBuffer.EnsureCapacity( paddedSize ); tempBuffer.EnsureCapacity( paddedSize ); V_StripExtension( pMdlFilename, szVvdFilename, sizeof( szVvdFilename ) ); V_strncat( szVvdFilename, ".360.vvd", sizeof( szVvdFilename ) ); swappedSize = StudioByteSwap::ByteswapStudioFile( szVvdFilename, tempBuffer.Base(), vvdBuffer.PeekGet(), fileSize, (studiohdr_t*)mdlBuffer.Base(), CompressFunc ); if ( swappedSize > 0 ) { // .vvd buffer is replaced with swapped data vvdBuffer.Purge(); vvdBuffer.Put( tempBuffer.Base(), swappedSize ); WriteBufferToFile( szVvdFilename, vvdBuffer, false, WRITE_TO_DISK_ALWAYS ); } else { return false; } } // swap and write final .mdl fileSize = mdlBuffer.TellPut(); paddedSize = fileSize + BYTESWAP_ALIGNMENT_PADDING; mdlBuffer.EnsureCapacity( paddedSize ); tempBuffer.EnsureCapacity( paddedSize ); char szMdlFilename[MAX_PATH]; V_StripExtension( pMdlFilename, szMdlFilename, sizeof( szMdlFilename ) ); V_strncat( szMdlFilename, ".360.mdl", sizeof( szMdlFilename ) ); swappedSize = StudioByteSwap::ByteswapStudioFile( szMdlFilename, tempBuffer.Base(), mdlBuffer.PeekGet(), fileSize, NULL, CompressFunc ); if ( swappedSize > 0 ) { // .mdl buffer is replaced with swapped data mdlBuffer.Purge(); mdlBuffer.Put( tempBuffer.Base(), swappedSize ); WriteBufferToFile( szMdlFilename, mdlBuffer, false, WRITE_TO_DISK_ALWAYS ); } else { return false; } return true; }
bool Workspace::Load(const char* relativePath, bool bForce) { bool bOk = this->TryInit(); if (!bOk) { //not init correctly return false; } //BEHAVIAC_ASSERT(behaviac::StringUtils::FindExtension(relativePath) == 0, "no extention to specify"); BEHAVIAC_ASSERT(IsValidPath(relativePath)); BehaviorTree* pBT = 0; BehaviorTrees_t::iterator it = m_behaviortrees.find(relativePath); if (it != m_behaviortrees.end()) { if (!bForce) { return true; } pBT = it->second; } behaviac::string fullPath = StringUtils::CombineDir(this->GetFilePath(), relativePath); Workspace::EFileFormat f = this->GetFileFormat(); switch (f) { case EFF_default: { // try to load the behavior in xml behaviac::string path = fullPath + ".xml"; if (behaviac::CFileManager::GetInstance()->FileExists(path.c_str())) { f = EFF_xml; fullPath = path; } else { // try to load the behavior in bson path = fullPath + ".bson.bytes"; if (behaviac::CFileManager::GetInstance()->FileExists(path.c_str())) { f = EFF_bson; fullPath = path; } // try to load the behavior in cpp else { f = EFF_cpp; } } } break; case EFF_xml: fullPath += ".xml"; break; case EFF_bson: fullPath += ".bson.bytes"; break; case EFF_cpp: break; default: BEHAVIAC_ASSERT(0); break; } bool bLoadResult = false; bool bNewly = false; if (!pBT) { //in case of circular referencebehavior bNewly = true; pBT = BEHAVIAC_NEW BehaviorTree(); m_behaviortrees[relativePath] = pBT; } BEHAVIAC_ASSERT(pBT); bool bCleared = false; if (f == EFF_xml || f == EFF_bson) { char* pBuffer = ReadFileToBuffer(fullPath.c_str()); if (pBuffer) { //if forced to reload if (!bNewly) { bCleared = true; pBT->Clear(); } if (f == EFF_xml) { bLoadResult = pBT->load_xml(pBuffer); } else { bLoadResult = pBT->load_bson(pBuffer); } PopFileFromBuffer(pBuffer); } else { BEHAVIAC_LOGERROR("'%s' doesn't exist!, Please check the file name or override Workspace and its GetFilePath()\n", fullPath.c_str()); BEHAVIAC_ASSERT(false); } } else if (f == EFF_cpp) { if (!bNewly) { bCleared = true; pBT->Clear(); } if (m_behaviortreeCreators && m_behaviortreeCreators->find(relativePath) != m_behaviortreeCreators->end()) { BehaviorTreeCreator_t btCreator = (*m_behaviortreeCreators)[relativePath]; bLoadResult = (*btCreator)(pBT); } else { BEHAVIAC_ASSERT(0); BEHAVIAC_LOGWARNING("The behaviac_generated/behaviors/generated_behaviors.h should be included by one of your apps."); } } else { BEHAVIAC_ASSERT(0); } if (bLoadResult) { BEHAVIAC_ASSERT(pBT->GetName() == relativePath); if (!bNewly) { BEHAVIAC_ASSERT(m_behaviortrees[pBT->GetName()] == pBT); } } else { if (bNewly) { //if it is forced to reload m_behaviortrees.erase(relativePath); BEHAVIAC_DELETE(pBT); } else if (bCleared) { //it has been cleared but failed to load, to remove it m_behaviortrees.erase(relativePath); } BEHAVIAC_LOGWARNING("'%s' is not loaded!\n", fullPath.c_str()); } return bLoadResult; }
char* Workspace::ReadFileToBuffer(const char* file, const char* ext) { char path[1024]; sprintf(path, "%s%s", file, ext); return ReadFileToBuffer(path); }
// main function to do the pkg decrypt/unpackage int do_spp_encrypt(char* pInPath, char* pOutPath, char* pType, char* pKeyName) { u8* pMySpp = NULL; u8* pMyContent = NULL; sce_header_t sce_hdr = {0}; SPP_META_HDR meta_hdr = {0}; u64 content_size_original = 0; u32 dwBytesRead = 0; u64 spp_size = 0; struct keylist* pMyKeyList = NULL; struct key MyKey = {0}; int retval = -1; // validate input params if ( (pInPath == NULL) || (pOutPath == NULL) || (pType == NULL) ) goto exit; // read in the 'input' (unencrypted) spp file (alloc a buffer) if ( ReadFileToBuffer(pInPath, (uint8_t**)&pMyContent, 0x00, &dwBytesRead, TRUE) != STATUS_SUCCESS) { printf("failed to read in file:%s, exiting...\n", pInPath); goto exit; } // assign the read-in size content_size_original = (u32)dwBytesRead; // build the SCE & META headers if ( build_spp_sce_hdr(&sce_hdr, content_size_original) != STATUS_SUCCESS ) goto exit; ///////////////// KEYS LOADING ////////////////////////////////////////// // // If we are OVERRIDING the default key from the 'keys' file, then // attempt to find it, first from the new 'keys' file, and if not, // manually by the exact 'keyname' specified if ( b_DefaultKeyListOverride == TRUE ) { if ( load_singlekey_by_name(pKeyName, &pMyKeyList) != STATUS_SUCCESS ) { // failed to find the 'override' key in 'KEYS' file, // so try 'old-style' keys printf("Error: Failed to find override SPP key(%s) in new \"KEYS\" file, trying old style keys...\n", pKeyName); if ( key_get_old(KEY_SPP, pKeyName, &MyKey) == STATUS_SUCCESS ) { if ( load_keylist_from_key(&pMyKeyList, &MyKey) != STATUS_SUCCESS ) { printf("Error: Unexpected failure loading single 'keylist' from 'key' structure....exiting....\n"); goto exit; } } else { printf("key_get() for SPP key failed"); goto exit; } } } // end if (KeyListOverride....) else { // try to get keys via the new 'keys' format first, if not, // failover to the old keys style if ( key_get_new(sce_hdr.key_revision, sce_hdr.header_type, &MyKey) != STATUS_SUCCESS ) { printf("Failed to find SPP key in new \"KEYS\" file, exiting!\n"); goto exit; } } // //////////////////////////////////////////////////////////////////////////////// // build the 'metadata' headers if ( build_spp_meta_hdr(&meta_hdr, content_size_original) != STATUS_SUCCESS ) goto exit; // build the SPP file spp_size = build_spp(&sce_hdr, &meta_hdr, &pMySpp, pMyContent, content_size_original); if (spp_size == 0) goto exit; // hash/sha1 the pkg data if ( hash_spp(pMySpp, content_size_original) != STATUS_SUCCESS ) goto exit; // ECDSA sign the pkg if ( sign_spp(pMySpp) != STATUS_SUCCESS ) goto exit; // encrypt the data if ( sce_encrypt_data_pkgtool(pMySpp) != STATUS_SUCCESS ) goto exit; // encrypt the hdrs if (sce_encrypt_header_pkgtool(pMySpp, &MyKey) != STATUS_SUCCESS ) goto exit; // write out the final .pkg file if (WriteBufferToFile(pOutPath, pMySpp, (uint32_t)spp_size, FALSE, 0, NULL) != STATUS_SUCCESS) { printf("failed to write to file:%s, exiting...\n", pOutPath); goto exit; } // status success retval = STATUS_SUCCESS; exit: // free the alloc'd memory if (pMyContent != NULL) free(pMyContent); // free the alloc'd memory if (pMySpp != NULL) free(pMySpp); // return the status return retval; }