Exemplo n.º 1
0
int GptBootProgramList(HGPT hGPT)
    {
    int iErr;
    // Buffer for the 1st sector of programs in the chain
    char *pSect = (char *)NULL;
    EFI_MBR_HEADER *pMbr;
    EFI_BOOT_PROGRAM_HEADER *pOldProgram;
    //
    QWORD qwLBA;
    
    // Allocate buffers to access drive data.
    pSect = (char *)malloc(hGPT->iSectorSize);
    if (!pSect) GptBootProgramListFail(1);
    pMbr = (EFI_MBR_HEADER *)pSect;
    pOldProgram = (EFI_BOOT_PROGRAM_HEADER *)pSect;
    
    // Scan the chain
    printf("Boot program chain: ");
    
    iErr = GptBlockRead(hGPT, qwZero, 1, pSect);
    if (iErr) GptBootProgramListFail(2);

    if (   (memcmp(((char *)&(pMbr->Header.Signature))+3, "MBR32", 5))	// Unknown signature
        || (!CheckCrc(128, &(pMbr->Header)))				// invalid CRC
       ) GptBootProgramListFail(3);              // Invalid boot program chain
                
    qwLBA = pMbr->NextBootProg.StartingLBA;
    if (!qwLBA)					// The chain is empty so far
        {
        printf("Empty.");
        }
    else for (;;)				// Else scan the chain until the current boot menu or the end
        {
        printfx("LBA=0x%s ", qwLBA);
        
        iErr = GptBlockRead(hGPT, qwLBA, 1, pSect);
        if (iErr) GptBootProgramListFail(2);
                
        if (!CheckCrc(hGPT->iSectorSize, &(pOldProgram->Header))) GptBootProgramListFail(4);
        
        if (!pOldProgram->NextBootProg.StartingLBA)	// Reached the end of the chain!
            {
            printf("\n");
            break;
            }
                
        qwLBA = pOldProgram->NextBootProg.StartingLBA;
        }

bplist_return:
    free(pSect);
    
    return iErr;
    }
Exemplo n.º 2
0
// fast method to just read the UID of a tag (collission detection not supported)
//		*buf	should be large enough to fit the 64bit uid
// returns 1 if suceeded
int getUID(uint8_t *buf) {

	UsbCommand resp;
	UsbCommand c = {CMD_ISO_15693_COMMAND, {0, 1, 1}}; // len,speed,recv?

	c.d.asBytes[0] = ISO15_REQ_SUBCARRIER_SINGLE | ISO15_REQ_DATARATE_HIGH | ISO15_REQ_INVENTORY | ISO15_REQINV_SLOT1;
	c.d.asBytes[1] = ISO15_CMD_INVENTORY;
	c.d.asBytes[2] = 0; // mask length

	AddCrc(c.d.asBytes, 3);
	c.arg[0] = 5; // len

	uint8_t retry;
	
	// don't give up the at the first try			
	for (retry = 0; retry < 3; retry++) {

		clearCommandBuffer();
		SendCommand(&c);
		
		if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) {
			
			uint8_t resplen = resp.arg[0];
			if (resplen >= 12 && CheckCrc(resp.d.asBytes, 12)) {
			   memcpy(buf, resp.d.asBytes + 2, 8);
			   return 1;
			} 
		} 
	} // retry
	
	if ( retry >= 3 )
		PrintAndLogEx(WARNING, "timeout while waiting for reply.");
	
	return 0;
}
Exemplo n.º 3
0
void ArchExecutor::CheckFileIntagrity(Options* options)
{
	int filesCount = options->Files->GetCount();
	for(int i = 0; i < filesCount; i++)
	{
		char* path = options->Files->GetElement(i);
		FILE* file = fopen(path, "rb");
		if (IsCompressedFile(file) && !CheckCrc(file))
		{
			printf("arch: %s: invalid compressed data--crc error\n", GetName(path));
		}
		fclose(file);
	}
}
Exemplo n.º 4
0
/**
 * efi_main - The entry point for the OS loader image.
 * @image: firmware-allocated handle that identifies the image
 * @sys_table: EFI system table
 */
EFI_STATUS
efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *_table)
{
	WCHAR *error_buf;
	EFI_STATUS err;
	EFI_LOADED_IMAGE *info;
	CHAR16 *name, *options;
	UINT32 options_size;
	char *cmdline;

	InitializeLib(image, _table);
	sys_table = _table;
	boot = sys_table->BootServices;
	runtime = sys_table->RuntimeServices;

	if (CheckCrc(sys_table->Hdr.HeaderSize, &sys_table->Hdr) != TRUE)
		return EFI_LOAD_ERROR;

	Print(banner, EFILINUX_VERSION_MAJOR, EFILINUX_VERSION_MINOR);

	err = fs_init();
	if (err != EFI_SUCCESS)
		goto failed;

	err = handle_protocol(image, &LoadedImageProtocol, (void **)&info);
	if (err != EFI_SUCCESS)
		goto fs_deinit;

	if (!read_config_file(info, &options, &options_size)) {
		int i;

		options = info->LoadOptions;
		options_size = info->LoadOptionsSize;

		/*
		 * Skip the first word, that's probably our name. Stop
		 * when we hit a word delimiter (' ') or the start of an
		 * efilinux argument ('-').
		 */
		i = 0;
		while (i < options_size) {
			if (options[i] == ' ' || options[i] == '-')
				break;
			i++;
		}

		options = &options[i];
		options_size -= i;
	}

	if (options && options_size != 0) {
		err = parse_args(options, options_size, &name, &cmdline);

		/* We print the usage message in case of invalid args */
		if (err == EFI_INVALID_PARAMETER) {
			fs_exit();
			return EFI_SUCCESS;
		}

		if (err != EFI_SUCCESS)
			goto fs_deinit;
	}

	err = load_image(image, name, cmdline);
	if (err != EFI_SUCCESS)
		goto free_args;

	return EFI_SUCCESS;

free_args:
	free(cmdline);
	free(name);
fs_deinit:
	fs_exit();
failed:
	/*
	 * We need to be careful not to trash 'err' here. If we fail
	 * to allocate enough memory to hold the error string fallback
	 * to returning 'err'.
	 */
	if (allocate_pool(EfiLoaderData, ERROR_STRING_LENGTH,
			  (void **)&error_buf) != EFI_SUCCESS) {
		Print(L"Couldn't allocate pages for error string\n");
		return err;
	}

	StatusToString(error_buf, err);
	Print(L": %s\n", error_buf);
	return exit(image, err, ERROR_STRING_LENGTH, error_buf);
}
Exemplo n.º 5
0
// Reads all memory pages
// need to write to file
int CmdHF15Dump(const char*Cmd) {
	
	uint8_t fileNameLen = 0;
	char filename[FILE_PATH_SIZE] = {0};
	char * fptr = filename;
	bool errors = false;
	uint8_t cmdp = 0;
	uint8_t uid[8] = {0,0,0,0,0,0,0,0};	
	
	while(param_getchar(Cmd, cmdp) != 0x00 && !errors) {
		switch(param_getchar(Cmd, cmdp)) {
		case 'h':
		case 'H':
			return usage_15_dump();
		case 'f':
		case 'F':
			fileNameLen = param_getstr(Cmd, cmdp+1, filename, FILE_PATH_SIZE); 
			cmdp += 2;
			break;
		default:
			PrintAndLogEx(WARNING, "Unknown parameter '%c'\n", param_getchar(Cmd, cmdp));
			errors = true;
			break;
		}
	}

	//Validations
	if (errors) return usage_15_dump();
	
	if (fileNameLen < 1) {

		PrintAndLogEx(INFO, "Using UID as filename");

		if (!getUID(uid)) {
			PrintAndLogEx(WARNING, "No tag found.");
			return 1;
		}
		
		fptr += sprintf(fptr, "hf-15-"); 
		FillFileNameByUID(fptr,uid,"-dump",sizeof(uid));

	}	
	// detect blocksize from card :)
	
	PrintAndLogEx(NORMAL, "Reading memory from tag UID %s", sprintUID(NULL, uid));

	int blocknum = 0;
	uint8_t *recv = NULL;

	// memory.
	t15memory mem[256];
	
	uint8_t data[256*4] = {0};
	memset(data, 0, sizeof(data));

	UsbCommand resp;
	UsbCommand c = {CMD_ISO_15693_COMMAND, {0, 1, 1}}; // len,speed,recv?
	uint8_t *req = c.d.asBytes;
	req[0] = ISO15_REQ_SUBCARRIER_SINGLE | ISO15_REQ_DATARATE_HIGH | ISO15_REQ_NONINVENTORY | ISO15_REQ_ADDRESS;
	req[1] = ISO15_CMD_READ;

	// copy uid to read command
	memcpy(req+2, uid, sizeof(uid));
	
	for (int retry = 0; retry < 5; retry++) {
	
		req[10] = blocknum;
		AddCrc(req, 11);
		c.arg[0] = 13;
	
		clearCommandBuffer();
		SendCommand(&c);
				
		if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) {

			uint8_t len = resp.arg[0];
			if ( len < 2 ) {
				PrintAndLogEx(FAILED, "iso15693 card select failed");
				continue;		
			}
			
			recv = resp.d.asBytes;
			
			if ( !CheckCrc(recv, len) ) {
				PrintAndLogEx(FAILED, "crc fail");
				continue;
			}

			if (recv[0] & ISO15_RES_ERROR) {
				PrintAndLogEx(FAILED, "Tag returned Error %i: %s", recv[1], TagErrorStr(recv[1]) ); 
				break;
			}
								
			mem[blocknum].lock = resp.d.asBytes[0];
			memcpy(mem[blocknum].block, resp.d.asBytes + 1, 4);					
			memcpy(data + (blocknum * 4), resp.d.asBytes + 1, 4);
			
			retry = 0;
			blocknum++;
			
			printf("."); fflush(stdout);
		} 
	}
	PrintAndLogEx(NORMAL, "\n");

	PrintAndLogEx(NORMAL, "block#   | data         |lck| ascii");
	PrintAndLogEx(NORMAL, "---------+--------------+---+----------");	
	for (int i = 0; i < blocknum; i++) {
		PrintAndLogEx(NORMAL, "%3d/0x%02X | %s | %d | %s", i, i, sprint_hex(mem[i].block, 4 ), mem[i].lock, sprint_ascii(mem[i].block, 4) );
	}
	PrintAndLogEx(NORMAL, "\n");

	size_t datalen = blocknum * 4;
	saveFileEML(filename, "eml", data, datalen, 4);	
	saveFile(filename, "bin", data, datalen);
	return 0;
}
Exemplo n.º 6
0
int
main(
     int  argc,
     char **argv
) {
     FILE *fp;
     char *game_file;
     int  level     = 0;
     int  old_level = 0;

     (void) printf(&title_msg[WHAT_OFFSET]);

     /*lint -e506 Ignore constat boolean */
     assert(sizeof(SAVED_GAME) == SAVED_GAME_SIZE);
     /*lint +e506 Ignore constat boolean */

     if (argc != 3) {
          (void) printf("Usage: SetLevel (saved game) (level)\n");
          (void) printf("          1 - Rookie\n");
          (void) printf("          2 - Amateur\n");
          (void) printf("          3 - Semi-Pro\n");
          (void) printf("          4 - Pro\n");
          (void) printf("          5 - Ace\n");
          return -1;
     }

     game_file = argv[1];
     level = atoi(argv[2]);

     if (level < 1 || level > 5) {
          (void) printf("SetLevel: The level value should be between 1 and 5.\n");
          return -1;
     }
     --level;

     if ((fp = fopen(game_file, "rb+")) == NULL) {
          (void) printf("SetLevel: Unable to open saved game file called '%s'\n", game_file);
          return -1;
     }

     if (fread(&game, sizeof(game), 1, fp) != 1) {
          (void) printf("SetLevel: Unable to read from saved game file called '%s'\n", game_file);
          return -1;
     }

     if (!CheckCrc(&game, sizeof(game), game.crc1, game.crc2)) {
          (void) printf("SetLevel: '%s' doesn't appear to be a valid saved game file.\n", game_file);
          return -1;
     }

     /*
     ** Update level and recalculate CRC.
     */
     old_level = game.data[LEVEL_OFFSET];
     game.data[LEVEL_OFFSET] = (unsigned char) level;
     CalcCrc(&game, sizeof(game), &game.crc1, &game.crc2);

     (void) fseek(fp, 0L, SEEK_SET);
     if (fwrite(&game, sizeof(game), 1, fp) != 1) {
          (void) printf("SetLevel: Unable to write to saved game file called '%s'\n", game_file);
          return -1;
     }

     (void) printf("Updated saved game '%s' from '%s' to '%s'\n", game_file, level_txt[old_level], level_txt[level]);

     (void) fclose(fp);

     return 0;
}
Exemplo n.º 7
0
int GptBootProgramAdd(HGPT hGPT, char *pNewSect)
    {
    int iErr;
    // Buffer for the 1st sector of the new boot program
    EFI_BOOT_PROGRAM_HEADER *pNewProgram = (EFI_BOOT_PROGRAM_HEADER *)pNewSect;
    // Buffer for the 1st sector of other programs in the chain
    char *pSect = (char *)NULL;
    EFI_MBR_HEADER *pMbr;
    EFI_BOOT_PROGRAM_HEADER *pOldProgram;
    //
    QWORD qwLBA, qwLastLBA;
#ifdef _DEBUG
    char szQwordBuf[20];
#endif
    QWORD qwNewLBA = pNewProgram->Partition.StartingLBA;
    EFI_GUID guidNew = pNewProgram->Partition.PartitionTypeGUID;
    
#ifdef _DEBUG
    if (iDebug) printf("GptBootProgramAdd(hBlockDev=%p, lba=%s)\n", hGPT->hBlockDev, qwtox(qwNewLBA, szQwordBuf));
#endif

    // Allocate buffers to access drive data.
    pSect = (char *)malloc(hGPT->iSectorSize);
    if (!pSect) GptBootProgramAddFail(1);
    pMbr = (EFI_MBR_HEADER *)pSect;
    pOldProgram = (EFI_BOOT_PROGRAM_HEADER *)pSect;

    // Update the boot program chain
    iErr = GptBlockRead(hGPT, qwZero, 1, pSect);
    if (iErr) GptBootProgramAddFail(2);

    if (   (memcmp(((char *)&(pMbr->Header.Signature))+3, "MBR32", 5))	// Unknown signature
        || (!CheckCrc(128, &(pMbr->Header)))				// invalid CRC
       ) GptBootProgramAddFail(3);              // Invalid boot program chain
                
    qwLBA = pMbr->NextBootProg.StartingLBA;
    qwLastLBA = 0;
    if (!qwLBA)					// The chain is empty so far
        {
        pMbr->NextBootProg.StartingLBA = qwNewLBA;	// Start the chain with this boot program.
        }
    else if (GUIDCMP(guidNew, guidBootMenu))	// It's not empty, but Anything else than boot menus is inserted ahead of the chain.
        {
        pMbr->NextBootProg.StartingLBA = qwNewLBA;	// Start the chain with this new boot program.

        pNewProgram->NextBootProg.StartingLBA = qwLBA;	// And link this new boot program to the previous chain.
        }
    else for (;;)				// Else scan the chain until the current boot menu or the end
        {
        iErr = GptBlockRead(hGPT, qwLBA, 1, pSect);
        if (iErr) GptBootProgramAddFail(2);
                
        if (!CheckCrc(hGPT->iSectorSize, &(pOldProgram->Header))) GptBootProgramAddFail(3);
                
	if (!GUIDCMP(pOldProgram->Partition.PartitionTypeGUID, guidBootMenu))
            {  // There's already one boot menu in the chain!
            // Back-up to the previous boot program.
            qwLBA = qwLastLBA;
            iErr = GptBlockRead(hGPT, qwLBA, 1, pSect);
	    if (iErr) GptBootProgramAddFail(2);
            if (!qwLBA)
                pMbr->NextBootProg.StartingLBA = qwNewLBA;	// Start the chain with this boot menu.
            else
                pOldProgram->NextBootProg.StartingLBA = qwNewLBA;// Append this boot menu to the chain
            break;
            }
                    
        qwLastLBA = qwLBA;
        
        if (!pOldProgram->NextBootProg.StartingLBA)	// Reached the end of the chain!
            {
            pOldProgram->NextBootProg.StartingLBA = qwNewLBA;	// Append this boot menu to the chain
            break;
            }
                
        qwLBA = pOldProgram->NextBootProg.StartingLBA;
        }

    SetCrc(&pNewProgram->Header);			// Update the CRC.
    iErr = GptBlockWrite(hGPT, qwNewLBA, 1, pNewSect);
    if (iErr) GptBootProgramAddFail(2);

    SetCrc(&pOldProgram->Header);			// Update the CRC.
    iErr = GptBlockWrite(hGPT, qwLastLBA, 1, pSect);
    if (iErr) GptBootProgramAddFail(2);

bpadd_return:
    free(pSect);
    
    return iErr;
    }
Exemplo n.º 8
0
int GptAllocFileCopy(HGPT hGPT, char *pszFileName, EFI_PARTITION_ENTRY *pNewEntry)
    {
    int i;
    int iPartition;
    QWORD qwLBA;
    int iErr;
    // To be cleaned up before return
    char *pSect = (char *)NULL;
    // End of clean-up zone
    int nSect;
    FILE *hf = NULL;
    
    // Compute the number of partition entries per sector.
    // int iEntryPerSect = hGPT->iSectorSize / sizeof(EFI_PARTITION_ENTRY);

    // Allocate a buffer to access drive data.
    pSect = (char *)malloc(hGPT->iSectorSize);
    if (!pSect) GptAllocFileCopyFail(-4);
    	
    // Open the partition image file
    hf = fopen(pszFileName, "rb");
    if (!hf) GptAllocFileCopyFail(-10);
    // Compute the number of sectors necessary.
    nSect = (int)((_filelength(_fileno(hf)) + hGPT->iSectorSize - 1) / hGPT->iSectorSize);

    // Search the smallest contiguous block of free sectors large enough.
    pNewEntry->EndingLBA = nSect;
    iPartition = GptAllocSectors(hGPT, pNewEntry);  // Side effect: pNewEntry->PartitionTypeGUID = 0;
    if (iPartition < 0) GptAllocFileCopyFail(iPartition);

#ifdef _DEBUG
    if (iVerbose)
        {
        printf("Allocating partition entry #%d for copying from file %s\n", iPartition, pszFileName);
        }
#endif
	    
    // Write the partition contents
    for (i=0, qwLBA=pNewEntry->StartingLBA; i<nSect; i++, qwLBA++)
        {
        size_t stRead;
	        
        stRead = fread(pSect, 1, hGPT->iSectorSize, hf);
        if (stRead < (size_t)(hGPT->iSectorSize)) memset(pSect+stRead, 0, hGPT->iSectorSize-stRead);
	        
	// ~~jfl 2001/12/19 Use the partition type GUID specified in the file, if any.
	if (i==0)
	    {
	    EFI_BOOT_PROGRAM_HEADER *pHdr = (EFI_BOOT_PROGRAM_HEADER *)pSect;
	    if (CheckCrc(hGPT->iSectorSize, &(pHdr->Header)))
		{
		if (!memcmp(((char *)&(pHdr->Header.Signature))+3, "MBR32", 5))
		    {
		    pNewEntry->PartitionTypeGUID = guidMbrBackup;   // If it's inside the GPT, then it's the backup!
		    }
		else	// Assume it's a relay or a boot program (Including the boot menu).
		    {	// Both have a partition entry behind the header.
		    pNewEntry->PartitionTypeGUID = pHdr->Partition.PartitionTypeGUID;
		    }
		}
	    else if (   (!memcmp(((char *)&(pHdr->Header.Signature))+3, "Relay", 5))
		     && (!uuidcmp(&(pHdr->Partition.PartitionTypeGUID), &guidRelay))
		    )	// It's a relay, but with the header incomplete (CRC not set yet).
		{
		pNewEntry->PartitionTypeGUID = guidRelay;
		// ~~jfl 2002/01/03 Update the partition header while we have it.
		uuid_create((uuid_t *)&(pHdr->Partition.UniquePartitionGUID));	// Generate a new GUID
		SetCrc(&(pHdr->Header));
		}
	    else if (IsMBR(pSect))	// Master Boot Record. Assume it's a hard disk.
		{
		pNewEntry->PartitionTypeGUID = guidHardDiskImage;
		}
	    if (IsNullUuid((uuid_t*)&(pNewEntry->PartitionTypeGUID)))	// Assume anything else is a floppy.
		{
		pNewEntry->PartitionTypeGUID = guidFloppyImage;
		}
	    }

	iErr = GptBlockWrite(hGPT, qwLBA, 1, pSect);
	if (iErr) GptAllocFileCopyFail(-3);
        }

copy_return:
    // Cleanup
    fclose(hf);
    free(pSect);
    
    return iPartition;    
    }
Exemplo n.º 9
0
HGPT GptOpen(HANDLE hBlockDev)
    {
    int iErr;
    // To be cleaned up eventually
    GPTREF *hGPT;
    // End of clean-up zone
    
#ifdef _DEBUG
    if (iDebug) printf("GptOpen(hBlockDev=%p)\n", hBlockDev);
#endif

    // Create a new GPTREF object
    hGPT = NEW(GPTREF);
    if (!hGPT) return 0;
    memset(hGPT, 0, sizeof(GPTREF));		// Clear everything
    hGPT->hBlockDev = hBlockDev;

    // Manage logical sectors that may be different from physical sectors in the case of image files.
    hGPT->iSectorSize = BlockSize(hGPT->hBlockDev);	// Sector size. 1 for files; 512 for disks.
    hGPT->iSectPerSect = 1;	    // Number of logical sectors per physical sector
    if (BlockType(hBlockDev) == 0)  // If it's a file image of a GPT...
	{			    // ... Force all file accesses per 512-byte blocks
	hGPT->iSectPerSect = 512 / hGPT->iSectorSize;	// Logical sectors per physical sector
	hGPT->iSectorSize = 512;			// New logical sector size
	}

    // Allocate buffers to access drive data.
    hGPT->pGptHdr = (EFI_PARTITION_TABLE_HEADER *)malloc(hGPT->iSectorSize);
    if (!hGPT->pGptHdr) GptOpenFail();
    	
    // Get the GPT header.
    iErr = GptBlockRead(hGPT, qwOne, 1, hGPT->pGptHdr);
    if (iErr) GptOpenFail();
    
    // Debug. TO BE REMOVED.
    CheckCrc(hGPT->iSectorSize, &(hGPT->pGptHdr->Header));
    CheckCrcAltSize(hGPT->iSectorSize, 0x5C, &(hGPT->pGptHdr->Header));
    CheckCrcAltSize(hGPT->iSectorSize, 0x58, &(hGPT->pGptHdr->Header));
    if (!strncmp((char *)&(hGPT->pGptHdr->Header.Signature), "TRAP IFE", 8))
        {
        strncpy((char *)&(hGPT->pGptHdr->Header.Signature), EFI_PTAB_HEADER_ID, 8);
        }
//    DumpBuf(&(hGPT->pGptHdr->Header), 0, hGPT->pGptHdr->Header.HeaderSize);
    CheckCrc(hGPT->iSectorSize, &(hGPT->pGptHdr->Header));
    CheckCrcAltSize(hGPT->iSectorSize, 0x5C, &(hGPT->pGptHdr->Header));
    CheckCrcAltSize(hGPT->iSectorSize, 0x58, &(hGPT->pGptHdr->Header));
    hGPT->pGptHdr->PartitionEntryArrayCRC32 = 0;
    CheckCrc(hGPT->iSectorSize, &(hGPT->pGptHdr->Header));
    CheckCrcAltSize(hGPT->iSectorSize, 0x5C, &(hGPT->pGptHdr->Header));
    CheckCrcAltSize(hGPT->iSectorSize, 0x58, &(hGPT->pGptHdr->Header));
        
    // Check if the header is valid
    if ((   strncmp((char *)&(hGPT->pGptHdr->Header.Signature), EFI_PTAB_HEADER_ID, 8)
	 && strncmp((char *)&(hGPT->pGptHdr->Header.Signature), "TRAP IFE", 8))
//	|| (!CheckCrc(hGPT->iSectorSize, &(hGPT->pGptHdr->Header)))
       ) GptOpenFail();

    // Success
    return hGPT;	// HGPT is same type as GPTREF*
    
open_return:
    GptClose(hGPT);
    
    return (HGPT)NULL;
    }
Exemplo n.º 10
0
int GptBootProgramDelete(HGPT hGPT, QWORD qwFirst)
    {
    int iErr;
    // Buffer for the 1st sector of other programs in the chain
    char *pSect = (char *)NULL;
    EFI_MBR_HEADER *pMbr;
    EFI_BOOT_PROGRAM_HEADER *pBootProgram;
    // Buffer for the 2nd sector of other programs in the chain
    char *pSect2 = (char *)NULL;
    EFI_BOOT_PROGRAM_HEADER *pDeletedProgram;
    //
    QWORD qwLBA, qwLastLBA;
#ifdef _DEBUG
    char szQwordBuf[20];
#endif
    
#ifdef _DEBUG
    if (iDebug) printf("GptBootProgramDelete(hBlockDev=%p, lba=%s)\n", hGPT->hBlockDev, qwtox(qwFirst, szQwordBuf));
#endif
    if (!qwFirst) return 0;	// Prevent problems

    // Allocate buffers to access drive data.
    pSect = (char *)malloc(hGPT->iSectorSize);
    if (!pSect) GptBootProgramDeleteFail(1);
    pMbr = (EFI_MBR_HEADER *)pSect;
    pBootProgram = (EFI_BOOT_PROGRAM_HEADER *)pSect;

    pSect2 = (char *)malloc(hGPT->iSectorSize);
    if (!pSect2) GptBootProgramDeleteFail(1);
    pDeletedProgram = (EFI_BOOT_PROGRAM_HEADER *)pSect2;

    // Update the boot program chain
    iErr = GptBlockRead(hGPT, qwZero, 1, pSect);
    if (iErr) GptBootProgramDeleteFail(2);

    if (   (memcmp(((char *)&(pMbr->Header.Signature))+3, "MBR32", 5))	// Unknown signature
        || (!CheckCrc(128, &(pMbr->Header)))				// invalid CRC
       ) GptBootProgramDeleteFail(3);              // Invalid boot program chain
                
    qwLBA = pMbr->NextBootProg.StartingLBA;
    qwLastLBA = 0;
    if (!qwLBA)					// The chain is empty so far
        {
        goto bpdel_return;				// Requested boot program NOT in the chain!
        }
    else while (qwLBA != qwFirst)			// Else scan the chain until the end
        {
        iErr = GptBlockRead(hGPT, qwLBA, 1, pSect);
        if (iErr) GptBootProgramDeleteFail(2);
                
        if (!CheckCrc(hGPT->iSectorSize, &(pBootProgram->Header))) GptBootProgramDeleteFail(3);
                
        qwLastLBA = qwLBA;
        
        if (!pBootProgram->NextBootProg.StartingLBA)	// Reached the end of the chain!
            {
            goto bpdel_return;				// Requested boot program NOT in the chain!Done.
            }
                
        qwLBA = pBootProgram->NextBootProg.StartingLBA;
        }

    iErr = GptBlockRead(hGPT, qwFirst, 1, pSect2);
    if (iErr) GptBootProgramDeleteFail(2);

    if (!CheckCrc(hGPT->iSectorSize, &(pDeletedProgram->Header))) GptBootProgramDeleteFail(3);
                
    qwLBA = pDeletedProgram->NextBootProg.StartingLBA;	// The boot program that was to follow de deleted one
    if (!qwLastLBA)
        pMbr->NextBootProg.StartingLBA = qwLBA;
    else
        pBootProgram->NextBootProg.StartingLBA = qwLBA;	// And link this new boot program to the previous chain.

    SetCrc(&pBootProgram->Header);			// Update the CRC.
    iErr = GptBlockWrite(hGPT, qwLastLBA, 1, pSect);
    if (iErr) GptBootProgramDeleteFail(2);

bpdel_return:
    free(pSect);
    free(pSect2);
    
    return iErr;
    }
Exemplo n.º 11
0
int
main(
     int  argc,
     char **argv
) {
     FILE *ifp;
     FILE *ofp;
     char *name_file;
     char *game_file;

     (void) printf(&title_msg[WHAT_OFFSET]);

     /*lint -e506 Ignore constat boolean */
     assert(sizeof(SAVED_GAME) == SAVED_GAME_SIZE);
     /*lint +e506 Ignore constat boolean */

     if (argc != 3) {
          (void) printf("Usage: SetNames (name file) (saved game)\n");
          return -1;
     }

     name_file = argv[1];
     game_file = argv[2];

     if ((ifp = fopen(name_file, "rb")) == NULL) {
          (void) printf("SetNames: Unable to open names file called '%s'\n", name_file);
          return -1;
     }

     if ((ofp = fopen(game_file, "rb+")) == NULL) {
          (void) printf("SetNames: Unable to open saved game file called '%s'\n", game_file);
          return -1;
     }

     if (fread(&names, sizeof(names), 1, ifp) != 1) {
          (void) printf("SetNames: Unable to read from names file called '%s'\n", name_file);
          return -1;
     }

     if (!CheckCrc(&names, sizeof(names), names.crc1, names.crc2)) {
          (void) printf("SetNames: '%s' doesn't appear to be a valid names file.\n", name_file);
          return -1;
     }

     if (fread(&game, sizeof(game), 1, ofp) != 1) {
          (void) printf("SetNames: Unable to read from saved game file called '%s'\n", game_file);
          return -1;
     }

     if (!CheckCrc(&game, sizeof(game), game.crc1, game.crc2)) {
          (void) printf("SetNames: '%s' doesn't appear to be a valid saved game file.\n", name_file);
          return -1;
     }

     /*
     ** Copy names and recalculate CRC.
     */
     (void) memcpy(&game.names, &names, sizeof(game.names) - CRC_SIZE);
     CalcCrc(&game, sizeof(game), &game.crc1, &game.crc2);

     (void) fseek(ofp, 0L, SEEK_SET);
     if (fwrite(&game, sizeof(game), 1, ofp) != 1) {
          (void) printf("SetNames: Unable to write to saved game file called '%s'\n", name_file);
          return -1;
     }

     (void) printf("Updated saved game '%s' with names from '%s'\n", game_file, name_file);

     (void) fclose(ifp);
     (void) fclose(ofp);

     return 0;
}
Exemplo n.º 12
0
/**
 * efi_main - The entry point for the OS loader image.
 * @image: firmware-allocated handle that identifies the image
 * @sys_table: EFI system table
 */
EFI_STATUS
efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *_table)
{
	WCHAR *error_buf;
	EFI_STATUS err;
	EFI_LOADED_IMAGE *info;
	CHAR16 *name = NULL;
	CHAR16 *options;
	BOOLEAN options_from_conf_file = FALSE;
	UINT32 options_size;
	CHAR8 *cmdline = NULL;
	struct bootimg_hooks hooks;

	main_image_handle = image;
	InitializeLib(image, _table);
	sys_table = _table;
	boot = sys_table->BootServices;
	runtime = sys_table->RuntimeServices;

	if (CheckCrc(ST->Hdr.HeaderSize, &ST->Hdr) != TRUE)
		return EFI_LOAD_ERROR;

	log_init();

	info(banner, EFILINUX_VERSION_MAJOR, EFILINUX_VERSION_MINOR,
		EFILINUX_BUILD_STRING, EFILINUX_VERSION_STRING,
		EFILINUX_VERSION_DATE);

	store_osloader_version(EFILINUX_BUILD_STRING);

	err = fs_init();
	if (err != EFI_SUCCESS)
		error(L"fs_init failed, DnX mode ?\n");

	err = handle_protocol(image, &LoadedImageProtocol, (void **)&info);
	if (err != EFI_SUCCESS)
		goto fs_deinit;

	efilinux_image_base = info->ImageBase;
	efilinux_image = info->DeviceHandle;

	if (!read_config_file(info, &options, &options_size)) {
		int i;

		options = info->LoadOptions;
		options_size = info->LoadOptionsSize;

		/* Skip the first word, that's our name. */
		for (i = 0; i < options_size && options[i] != ' '; i++)
			;
		options = &options[i];
		options_size -= i;
	} else
		options_from_conf_file = TRUE;

	err = init_platform_functions();
	if (EFI_ERROR(err)) {
		error(L"Failed to initialize platform: %r\n", err);
		goto fs_deinit;
	}

	CHAR16 type = '\0';
	if (options && options_size != 0) {
		err = parse_args(options, options_size, &type, &name, &cmdline);

		if (options_from_conf_file)
			free(options);

		/* We print the usage message in case of invalid args */
		if (err == EFI_INVALID_PARAMETER) {
			fs_exit();
			return EFI_SUCCESS;
		}

		if (err != EFI_SUCCESS)
			goto fs_deinit;
	}

	hooks.before_exit = loader_ops.hook_before_exit;
	hooks.before_jump = loader_ops.hook_before_jump;
	hooks.watchdog = tco_start_watchdog;

	debug(L"shell cmdline=%a\n", cmdline);
	switch(type) {
	case 'f':
		if (!name) {
			error(L"No file name specified or name is empty\n");
			goto free_args;
		}
		info(L"Starting file %s\n", name);
		err = android_image_start_file(info->DeviceHandle, name, cmdline, &hooks);
		break;
	case 't': {
		enum targets target;
		if ((err = name_to_target(name, &target)) != EFI_SUCCESS) {
			error(L"Unknown target name %s\n", name);
			goto free_args;
		}
		info(L"Starting target %s\n", name);
		loader_ops.load_target(target, cmdline);
		break;
	}
	case 'p': {
		EFI_GUID part_guid;
		if ((err = name_to_guid(name, &part_guid)) != EFI_SUCCESS) {
			error(L"Unknown target name %s\n", name);
			goto free_args;
		}
		info(L"Starting partition %s\n", name);
		err = android_image_start_partition(&part_guid, cmdline, &hooks);
		break;
	}
	case 'c': {
		int i;
		for (i = 0 ; i < sizeof(commands) / sizeof(*commands); i++)
			if (!StrCmp(commands[i].name, name))
				commands[i].func();
		err = EFI_SUCCESS;
	}
		break;
	case 'a':
	{
		CHAR16 *endptr;
		VOID * addr = (VOID *)strtoul16(name, &endptr, 0);
		if ((name[0] == '\0' || *endptr != '\0')) {
			error(L"Failed to convert %s into address\n", name);
			goto free_args;
		}
		debug(L"Loading android image at 0x%x\n", addr);
		err = android_image_start_buffer(addr, cmdline, &hooks);
		break;
	}
	default:
		debug(L"type=0x%x, starting bootlogic\n", type);
		err = start_boot_logic(cmdline);
		if (EFI_ERROR(err)) {
			error(L"Boot logic failed: %r\n", err);
			goto free_args;
		}
	}

free_args:
	if (cmdline)
		free(cmdline);
	if (name)
		free(name);
fs_deinit:
	fs_exit();
	/*
	 * We need to be careful not to trash 'err' here. If we fail
	 * to allocate enough memory to hold the error string fallback
	 * to returning 'err'.
	 */

	error_buf = AllocatePool(ERROR_STRING_LENGTH);
	if (!error_buf) {
		error(L"Couldn't allocate pages for error string\n");
		return EFI_OUT_OF_RESOURCES;
	}

	StatusToString(error_buf, err);
	error(L": %s\n", error_buf);

	loader_ops.hook_before_exit();

	return exit(image, err, ERROR_STRING_LENGTH, error_buf);
}