void AT45D_FormatFS(void) { unsigned char buf[520]; int i; printf("AT45D_FormatFS()\r\n"); printf("\tcopying boot sector\r\n"); memcpy(buf, BootSector, sizeof(BootSector)); memset(buf + sizeof(BootSector), '\0', 512 - sizeof(BootSector)); buf[510] = 0x55; buf[511] = 0xAA; WriteSector(0, buf); printf("\tcopying FAT0\r\n"); memcpy(buf, FAT0, sizeof(FAT0)); memset(buf + sizeof(FAT0), '\0', 512 - sizeof(FAT0)); WriteSector(1, buf); memset(buf, '\0', 512); for (i = 2; i < (MDD_AT45D_FLASH_NUM_FAT_SECTORS + 1); i++) { WriteSector(i, buf); } printf("\tcopying root directory\r\n"); memcpy(buf, RootDirectory0, sizeof(RootDirectory0)); memset(buf + sizeof(RootDirectory0), '\0', 512 - sizeof(RootDirectory0)); WriteSector(MDD_AT45D_FLASH_NUM_FAT_SECTORS+1, buf); memset(buf, '\0', 512); for (i = (MDD_AT45D_FLASH_NUM_FAT_SECTORS+1+1); i < ((MDD_AT45D_FLASH_NUM_FAT_SECTORS+1) + MDD_AT45D_FLASH_NUM_ROOT_DIRECTORY_SECTORS); i++) { WriteSector(i, buf); } printf("AT45D_FormatFS() complete\r\n"); }
// recursively write the files and dirs void MakeImage::WriteFiles(Directory *root, ofstream &out) { char *sector = 0; sector = new char[SECTOR_SIZE]; ZeroMemory(sector, SECTOR_SIZE); root->CreatePathDescriptor(sector, false); WriteSector(out, root->GetBlock(), sector); delete [] sector; for(UINT i=0; i < root->mChildren.size(); ++i) { WriteFiles(root->mChildren[i], out); } for(UINT i=0; i < root->mFiles.size(); ++i) { File *curFile = root->mFiles[i]; int writeSector = curFile->GetBlock(); char filePath[MAX_PATH]; strcpy_s(filePath, MAX_PATH, "cd_root"); strcat_s(filePath, MAX_PATH, curFile->GetAbsolutePath()); ifstream in; in.open(filePath, ios_base::binary); do { sector = new char[SECTOR_SIZE]; ZeroMemory(sector, SECTOR_SIZE); in.read(sector, SECTOR_SIZE); WriteSector(out, writeSector, sector); delete [] sector; ++writeSector; } while(!in.eof()); in.close(); } }
void CCPCSystemDisc::WriteBlock(const unsigned char i_idBlock, const void* i_buffer) { unsigned int bloc = i_idBlock+9; unsigned char track1 = (bloc*2 - (bloc*2 % _geometry.dg_sectors)) / _geometry.dg_sectors; unsigned char sector1 = _geometry.dg_secbase+(bloc*2 % _geometry.dg_sectors); unsigned char track2 = ((bloc*2+1) - ((bloc*2+1) % _geometry.dg_sectors)) / _geometry.dg_sectors; unsigned char sector2 = _geometry.dg_secbase+((bloc*2+1) % _geometry.dg_sectors); WriteSector(track1,0,sector1,i_buffer); WriteSector(track2,0,sector2,(char*)i_buffer+_geometry.dg_secsize); }
//helper func for sync int sync() { inode_cache *n = first_inode; while (n!=NULL) { int inode_num = n->inode_num; if (n->dirty!=0) { n->dirty = 0; int block_num = inode_to_block(inode_num); block_cache *b = read_block(block_num); int idx = inode_num-(block_num-1)*(BLOCKSIZE/INODESIZE); memcpy((void*)(b->data+idx*INODESIZE),(void*)(&(n->data)),INODESIZE); b->dirty = 1; } n = n->next; } block_cache *t = first_block; while (t!=NULL) { if (t->dirty){ t->dirty = 0; if (WriteSector(t->block_num,(void*)(t->data))!=0) { perror("erro writing back dirty block!"); return -1; } } t = t->next; } return 0; }
inline void WriteFSInfo() { /*std::cout << "Updating FS Info! sector = " << bpb->clusterFSInfo << std::endl; std::cout << "nextFreeSector = " << fsInfo->nextFreeCluster << std::endl; std::cout << "freeSectors = " << fsInfo->freeClusterCount << std::endl;*/ WriteSector((char*)fsInfo, bpb->clusterFSInfo); }
int WriteBlock(int blk_num,char *ptr) { int sec_num,len=0; int j,k; char *dir; if(blk_num<0 || blk_num>max_block_num||ptr==NULL) return ERROR; dir=(char *) malloc(SECTORSIZE*sizeof(char)); sec_num=(blk_num*BLOCKSIZE)/SECTORSIZE; for(j=0;j<BLOCKSIZE/SECTORSIZE;j++) { for(k=0;k<(SECTORSIZE/sizeof(char));k++) { dir[k]=ptr[len++]; } WriteSector(sec_num,(void *)dir); sec_num++; } return (dir); return len; }
//============================================================================= // eFdd::AddFile //----------------------------------------------------------------------------- bool eFdd::AddFile(const byte* hdr, const byte* data) { eUdi::eTrack::eSector* s = GetSector(0, 0, 9); if(!s) return false; int len = hdr[13]; int pos = s->data[0xe4] * 0x10; eUdi::eTrack::eSector* dir = GetSector(0, 0, 1 + pos / 0x100); if(!dir) return false; if(SectorDataW(s, 0xe5) < len) //disk full return false; memcpy(dir->data + (pos & 0xff), hdr, 14); SectorDataW(dir, (pos & 0xff) + 14, SectorDataW(s, 0xe1)); UpdateCRC(dir); pos = s->data[0xe1] + 16 * s->data[0xe2]; s->data[0xe1] = (pos + len) & 0x0f, s->data[0xe2] = (pos + len) >> 4; s->data[0xe4]++; SectorDataW(s, 0xe5, SectorDataW(s, 0xe5) - len); UpdateCRC(s); // goto next track. s8 become invalid for(int i = 0; i < len; ++i, ++pos) { int cyl = pos / 32; int side = (pos / 16) & 1; if(!WriteSector(cyl, side, (pos & 0x0f) + 1, data + i * 0x100)) return false; } return true; }
/* * entry->cluster = last cluster (current EOF) * entry->sector = current FAT sector to read/write * entry->buffer = FAT buffer * cluster = new EOF cluster */ void UpdateFAT(FatEntry* entry, uint32_t cluster) { // Update old EOF to point to new cluster *(uint32_t*)(entry->buffer + GetFATOffset(entry->cluster)) = cluster; // Check if we need to load a new FAT sector if (entry->sector != GetFATSector(cluster)) { WriteSector(entry->buffer, entry->sector); entry->sector = GetFATSector(cluster); ReadSector(entry->buffer, entry->sector); } // Set new cluster to EOF *(uint32_t*)(entry->buffer + GetFATOffset(cluster)) = FAT_EOF; WriteSector(entry->buffer, entry->sector); // Update FS Info here? }
/****************************************************************************** * Function: BYTE SectorWrite(DWORD sector_addr, BYTE *buffer, BYTE allowWriteToZero) * * Input: sector_addr - Sector address, each sector contains 512-byte * buffer - Buffer where data will be read * allowWriteToZero - If true, writes to the MBR will be valid * * Output: Returns TRUE if write successful, FALSE otherwise * * Overview: SectorWrite sends 512 bytes of data from the location * pointed to by 'buffer' to the card starting * at the sector address specified by sector_addr. * * Note: The sample device expects the address field in the command packet * to be byte address. Therefore the sector_addr must first * be converted to byte address. This is accomplished by * shifting the address left 9 times. *****************************************************************************/ BYTE MDD_AT45D_SectorWrite(DWORD sector_addr, BYTE* buffer, BYTE allowWriteToZero) { // printf("MDD_AT45D_SectorWrite %u\r\n", (unsigned int)sector_addr); if (sector_addr >= MDD_AT45D_FLASH_TOTAL_DISK_SIZE) { return FALSE; } WriteSector((uint16_t)sector_addr, buffer); return TRUE; }
bool DeleteCluster(FatEntry* entry) { // Load FAT sector if needed - Update FatEntry sector if (entry->sector != GetFATSector(entry->cluster)) { WriteSector(entry->buffer, entry->sector); entry->sector = GetFATSector(entry->cluster); ReadSector(entry->buffer, entry->sector); } // Find a new cluster uint32_t tmpCluster = *(uint32_t*)(entry->buffer + GetFATOffset(entry->cluster)); *(uint32_t*)(entry->buffer + GetFATOffset(entry->cluster)) = FAT_FREE; entry->cluster = tmpCluster; WriteSector(entry->buffer, entry->sector); // Update FS Info if (tmpCluster < fsInfo->nextFreeCluster) fsInfo->nextFreeCluster = tmpCluster - 1; fsInfo->freeClusterCount++; return (tmpCluster < FAT_EOF); }
static DWORD __CtrlSectorWrite(__COMMON_OBJECT* lpDrv, __COMMON_OBJECT* lpDev, __DRCB* lpDrcb) { __PARTITION_EXTENSION* pPe = NULL; __DEVICE_OBJECT* pDevice = (__DEVICE_OBJECT*)lpDev; __SECTOR_INPUT_INFO* psii = NULL; DWORD dwStartSector = 0; DWORD dwSectorNum = 0; int nDiskNum = 0; DWORD i; DWORD dwFlags; //Parameter validity checking. if((NULL == lpDrcb->lpInputBuffer) || (0 == lpDrcb->dwInputLen)) { return 0; } psii = (__SECTOR_INPUT_INFO*)lpDrcb->lpInputBuffer; //Get start sector and sector number to read. __ENTER_CRITICAL_SECTION(NULL,dwFlags); pPe = (__PARTITION_EXTENSION*)pDevice->lpDevExtension; if(psii->dwBufferLen % pDevice->dwBlockSize) //Always integral block size times is valid. { __LEAVE_CRITICAL_SECTION(NULL,dwFlags); return 0; } dwSectorNum = psii->dwBufferLen / pDevice->dwBlockSize; //Check if the reading data exceed the device boundry. if((psii->dwStartSector + dwSectorNum) > (pPe->dwStartSector + pPe->dwSectorNum)) { __LEAVE_CRITICAL_SECTION(NULL,dwFlags); return 0; } dwStartSector = psii->dwStartSector + pPe->dwStartSector; nDiskNum = pPe->nDiskNum; __LEAVE_CRITICAL_SECTION(NULL,dwFlags); //Now issue the reading command. for(i = 0;i < dwSectorNum;i ++) { if(!WriteSector(nDiskNum,dwStartSector + i,1,((BYTE*)psii->lpBuffer) + 512*i)) { return FALSE; } } return TRUE; }
// ------------------------------------------------------------------------------------------------ int main(int argc, const char** argv) { // Parse arguments if (argc < 3) { Usage(); return EXIT_FAILURE; } const char* diskPath = argv[1]; const char* bootSectorPath = argv[2]; // Read boot loader char bootLoader[SECTOR_SIZE]; if (!ReadSector(bootSectorPath, bootLoader)) { fprintf(stderr, "Failed to read boot loader: %lu\n", GetLastError()); return EXIT_FAILURE; } // Read sector 0 char curSector[SECTOR_SIZE]; if (!ReadSector(diskPath, curSector)) { fprintf(stderr, "Failed to read current boot sector: %lu\n", GetLastError()); return EXIT_FAILURE; } // Prepare new boot sector preserving the bios parameter block char newSector[SECTOR_SIZE]; memcpy(newSector, bootLoader, SECTOR_SIZE); memcpy(newSector + JMP_CODE_SIZE, curSector + JMP_CODE_SIZE, BIOS_PARAM_BLOCK_SIZE - JMP_CODE_SIZE); // Write sector 0 if (!WriteSector(diskPath, newSector)) { fprintf(stderr, "Failed to write new boot sector: %lu\n", GetLastError()); return EXIT_FAILURE; } // Success! return EXIT_SUCCESS; }
bool WriteCluster(FatEntry* fatEntry, char* buffer) { // Load FAT sector if needed - Update FatEntry sector if (fatEntry->sector != GetFATSector(fatEntry->cluster)) { fatEntry->sector = GetFATSector(fatEntry->cluster); ReadSector(fatEntry->buffer, fatEntry->sector); } // Write that sector WriteSector(buffer, ClusterToSector(fatEntry->cluster)); // Find a new cluster uint32_t tmpCluster = FindFreeCluster(); UpdateFAT(fatEntry, tmpCluster); fatEntry->cluster = tmpCluster; fsInfo->nextFreeCluster = tmpCluster; fsInfo->freeClusterCount--; return true; }
int write_inode(int inode_num,struct inode *curr_inode) { int sec_num,res,i; struct inode *fs; //printf("\nInside Write_inode:Reached"); fs=(struct inode *)malloc(SECTORSIZE); if(fs==NULL) { printf("\nNot enough space in memory"); return ERROR; } sec_num=BLOCKSIZE/SECTORSIZE+((inode_num*INODESIZE)/SECTORSIZE); i=(inode_num*INODESIZE)%SECTORSIZE; i=i/INODESIZE; //printf("\nvalue of written inode is %d",i); res=ReadSector(sec_num,(void *)fs); if(!res) { memcpy((fs+i),curr_inode,INODESIZE); WriteSector(sec_num,(void *)fs); } else printf("\nReadSector Unsuccessful!"); free(fs); return 0; }
//insert or update a block in LRU cache void set_blockLRU(int block_num, block_cache* b) { block_cache* n = get_block(block_num); if (n!=NULL) { put_block(block_num, b); if (n!=last_block) { if (n==first_block) first_block = first_block->next; else n->prev->next = n->next; n->next->prev = n->prev; last_block->next = n; n->prev = last_block; n->next = NULL; last_block = n; } } else { if (block_cache_cnt>=BLOCK_CACHESIZE) { sync(); rm_block(first_block->block_num); //write back dirty block to disk if (first_block->dirty) { if (WriteSector(first_block->block_num,(void*)(first_block->data))!=0) perror("erro writing back dirty block!"); } block_cache* tmp = first_block; first_block = first_block->next; if (first_block!=NULL) first_block->prev = NULL; else last_block = NULL; block_cache_cnt--; free(tmp); } if (first_block==NULL || last_block==NULL) first_block = b; else last_block->next = b; b->prev = last_block; last_block = b; put_block(block_num, b); block_cache_cnt++; } }
exp bool Delete(const char* filename) { // Convert the filename into DOS8.3 format char* dosName = new char[12]; ToDos83Name(filename, dosName); // Find entry DirectoryEntry* entry = FindEntry(dosName, &directory); if (!entry) { LastError("Delete", "Failed to find file"); return false; } if (!(entry->attrib & ATTRIB_ARCHIVE) || (entry->attrib & ATTRIB_DIRECTORY)) { LastError("Delete", "This is not a file"); return false; } entry->name[0] = (char)ATTRIB_DELETED; DirectoryWrite(&directory); //WriteSector(directoryBuffer + ((((char*)entry - directoryBuffer) / 512) * 512),directorySector + (((char*)entry - directoryBuffer) / 512)); // Unlink all clusters FatEntry fatEntry; fatEntry.buffer = new char[bpb->bytesPerSector]; fatEntry.cluster = GetClusterFromEntry(entry); fatEntry.sector = GetFATSector(fatEntry.cluster); ReadSector(fatEntry.buffer, fatEntry.sector); while (DeleteCluster(&fatEntry)) Sleep(1); WriteSector(fatEntry.buffer, fatEntry.sector); delete[] fatEntry.buffer; return false; }
//A testing routine used to create hard disk partition table. static VOID CreatePartition() { BYTE Buff[512]; __PARTITION_TABLE_ENTRY* pTableEntry = NULL; pTableEntry = (__PARTITION_TABLE_ENTRY*)(Buff + 0x1BE); pTableEntry->IfActive = 0x00; pTableEntry->PartitionType = PARTITION_TYPE_NTFS; pTableEntry->dwStartSector = 16065; pTableEntry->dwTotalSector = 65535; pTableEntry ++; pTableEntry->IfActive = 0x00; pTableEntry->PartitionType = PARTITION_TYPE_NTFS; pTableEntry->dwStartSector = 81600; pTableEntry->dwTotalSector = 65535; pTableEntry ++; pTableEntry->IfActive = 0x00; pTableEntry->PartitionType = PARTITION_TYPE_NTFS; pTableEntry->dwStartSector = 147135; pTableEntry->dwTotalSector = 65535; pTableEntry ++; pTableEntry->IfActive = 0x00; pTableEntry->PartitionType = PARTITION_TYPE_NTFS; pTableEntry->dwStartSector = 212670; pTableEntry->dwTotalSector = 65535; pTableEntry ++; //Set the terminate flag. Buff[510] = (BYTE)0xAA; Buff[511] = (BYTE)0x55; WriteSector(0,0,1,Buff); }
void _CRTAPI1 main( int ArgC, char *ArgS[] ) { HANDLE handle; ULONG bytesRead; ULONG lsn; int i; int j; int lines; char c; char lastCmd; char currentDrive[12]; PPTE partitionTable; BOOLEAN modify = FALSE; BOOLEAN more = FALSE; // Disable hard-error popups. SetErrorMode(TRUE); // See if we are connected to CON Batch = (BOOLEAN)(!isatty(0)); switch (ArgC) { case 2: // Nothing to do for level 2 break; case 3: if (strcmp(_strupr(ArgS[2]), "/E") == 0) { modify = TRUE; fprintf(stderr, "Warning: Opening drive %s for write access!\n", ArgS[1]); break; } else { fprintf(stderr, "%s: Invalid option '%s'\n", ArgS[0], ArgS[2]); } // Note fall through to default: (usage case) default: if (ArgC > 3) fprintf(stderr, "%s: Too many arguments\n", ArgS[0]); fprintf(stderr, "usage: %s diskno [/e]\n", ArgS[0]); // Re-enable harderror popups. SetErrorMode(FALSE); exit(-1); break; } sprintf(currentDrive, "%s", ArgS[1]); if (!OpenFile(currentDrive, &handle)) { fprintf(stderr, "%s: Unable to open %s\n", ArgS[0], currentDrive); // Re-enable harderror popups. SetErrorMode(FALSE); exit(1); } // check if we want to do writes with dasd if (modify) { // This is a drive, and we want to modify it, so we need // to lock it. if (!LockVolume(handle)) { printf("Unable to lock volume.\n"); // Re-enable harderror popups. SetErrorMode(FALSE); exit(1); } } // default to sector 0 lsn = 0; while (1) { PromptUsr(); if (fgets(Command, sizeof(Command), stdin) == NULL) break; if ((i = sscanf(Command, "%c %li", &c, &lsn)) > 1) { if ((c != 'c') && (c != 'C')) { /* * The user entered a lsn as well as an lsn based command, * convert it to byte seek pos */ lsn *= SECSIZE; } } more = FALSE; c = (char)tolower((int)c); // pre process command if (c == 'q') break; if (c == '\n') c = lastCmd; switch (c) { case 'b': if (i == 1 && lastCmd == c) { // same command with no new lsn, use the next one on disk lsn -= bytesRead; } break; case 'c': // change drives. if (i != 2) { fprintf(stderr, "You must specify a drive number to change drives.\n"); continue; } CloseFile(handle); sprintf(currentDrive, "%d", lsn); if (!OpenFile(currentDrive, &handle)) { fprintf(stderr, "%s: Unable to open %s\n", ArgS[0], currentDrive); // Re-enable harderror popups. SetErrorMode(FALSE); exit(1); } // check if we want to do writes with dasd if (modify) { // This is a drive, and we want to modify it, so we need // to lock it. if (!LockVolume(handle)) { printf("Unable to lock volume.\n"); // Re-enable harderror popups. SetErrorMode(FALSE); exit(1); } } // default to sector 0 lsn = 0; continue; case 'g': { DISK_GEOMETRY diskGeometry; IO_STATUS_BLOCK statusBlock; NTSTATUS status; // Get and display drive geometry from system. status = NtDeviceIoControlFile(handle, 0, NULL, NULL, &statusBlock, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &diskGeometry, sizeof(DISK_GEOMETRY)); if (NT_SUCCESS(status)) { printf("BytesPerSector: %d\n", diskGeometry.BytesPerSector); printf("SectorsPerTrack: %d\n", diskGeometry.SectorsPerTrack); printf("TracksPerCylinder: %d\n", diskGeometry.TracksPerCylinder); printf("NumberOfCylinders: %d\n", diskGeometry.Cylinders); } else { fprintf(stderr, "Could not get geometry %x\n", status); } continue; } case 'm': case 'd': case 'e': case 'p': if (i == 1 && lastCmd == c) { // same command with no new lsn, use the next one on disk lsn += bytesRead; } break; default: fprintf(stderr,"Unknown command '%c'\n", c); case 'h': case '?': fprintf(stderr," d [####]\tDump sector ####\n"); fprintf(stderr," e [####]\tEdit sector ####\n"); fprintf(stderr," m [####]\tDump sector with 'MORE'\n"); fprintf(stderr," b [####]\tSame as 'd' but defaults to" " previous sector\n"); fprintf(stderr," c [##]\tChange harddisk number\n"); fprintf(stderr," p [####]\tDump partition table on sector ###\n"); fprintf(stderr," q \tquit the program"); fprintf(stderr,"\n" "\n If no new sector is given and the command is the same, the next" "\n sector on the disk is used. If no sector is given but the command" "\n is different from the previous command, the sector used in the" "\n last command will be used again.\n" ); continue; } // remember last command lastCmd = c; bytesRead = 0; if(!ReadSector(handle, lsn, Sector, &bytesRead)) { printf("Unable to read sector %lx\n", lsn); } else { printf("\n lsn:0x%lX bytes read:%d\n", lsn / SECSIZE, bytesRead); switch (c) { case 'm': /* * More */ more = TRUE; // fall through to Dump case 'd': case 'b': /* * Dump */ lines = 0; HexLine[0] = '\0'; CharLine[0] = '\0'; i = 0; sprintf(HexLine, "%04X ", i); for (i = 0; i < (int)bytesRead; i++) { sprintf(HexLine, "%s%2x ", HexLine, Sector[i]); sprintf(CharLine, "%s%c", CharLine, (isprint(Sector[i])) ? Sector[i] : '.'); if ((i != 0) && ((i % 16) == 15)) { printf("%s *%s*\n", HexLine, CharLine); HexLine[0] = '\0'; sprintf(HexLine, "%04X ", i + 1); CharLine[0] = '\0'; lines++; } if (more && (lines == 20)) { printf("\n--MORE--"); MyGetChr(); printf("\r"); lines = 0; } } putchar('\n'); break; case 'p': /* * dump partition table */ if (LoadWORD(&Sector[SIGNATURE_OFFSET]) == 0xaa55) { partitionTable = ((PBOOTSECTOR)Sector)->PartitionTable; for (i = 0; i < 4; i++) { printf("\nEntry #%u:\n",i); printf(" Boot flag : %u\n", partitionTable[i].BootIndicator); printf(" System ID : %u\n", partitionTable[i].SysID); printf(" Relative sectors: %u (0x%x)\n", LoadDWORD(&partitionTable[i].Relative0), LoadDWORD(&partitionTable[i].Relative0)); printf(" Sector count : %u (0x%x) [%u MB]\n", LoadDWORD(&partitionTable[i].SectorCount0), LoadDWORD(&partitionTable[i].SectorCount0), (LoadDWORD(&partitionTable[i].SectorCount0) * SECSIZE) / (1024*1024)); printf(" Start CHS : %u %u %u\n", partitionTable[i].StartCylinder | ((partitionTable[i].StartSector & 0xc0) << 2), partitionTable[i].StartHead, partitionTable[i].StartSector & 0x3f); printf(" End CHS : %u %u %u\n", partitionTable[i].EndCylinder | ((partitionTable[i].EndSector & 0xc0) << 2), partitionTable[i].EndHead, partitionTable[i].EndSector & 0x3f); } } else { printf("\nSector %u is not a valid master boot sector.\n", lsn/SECSIZE); } break; case 'e': /* * Edit */ if (!modify) { printf("Can not edit, restart with /e option\n"); } else { for (i = 0; i < (int)bytesRead; i++) { if ((i % CB_INPUTLINE) == 0) { // print line header printf("\n%04X\t", i); } printf("%02X.", (BYTE)Sector[i]); if (MyGetInput(&j, &c )) { Sector[i] = (BYTE)j; } else { printf("%02X", (BYTE)Sector[i]); } if (c == '\r') break; putchar('\t'); } printf("\nWrite new data to sector? (Y/N)"); c = (char)MyGetChr(); if ((c = (char)toupper(c)) == 'Y') { // User wants to save the data printf("Yes...."); if (!WriteSector(handle, lsn, Sector)) { fprintf(stderr, "Write failed\n"); } else { // indicate success printf("\t[Done]\n"); } } else { // user chickened out printf("No....\t[Nothing written]\n"); } } break; } } } // if this was a dasd open, then unlock the drive if (modify) { UnlockVolume(handle); } CloseFile(handle); // Re-enable harderror popups. SetErrorMode(FALSE); exit(0); }
BOOL DLL_EXPORT DeletePartition(DWORD dwStartSector, BYTE btHardDisk, CREATE_PAR_FLAG flags, PINT pnError) { int nErrorCode; int nIndex; LARGE_INTEGER lnStartByte; DISK_GEOMETRY dg; DRIVE_LAYOUT DriveLayout; BIOS_DRIVE_PARAM bdp; //standard mbr BYTE stdMBR[512] = {0x33,0xc0,0x8e,0xd0,0xbc,0x0 ,0x7c,0xfb,0x50,0x7 , 0x50,0x1f,0xfc,0xbe,0x1b,0x7c,0xbf,0x1b,0x6 ,0x50, 0x57,0xb9,0xe5,0x1 ,0xf3,0xa4,0xcb,0xbe,0xbe,0x7 , 0xb1,0x4 ,0x38,0x2c,0x7c,0x9 ,0x75,0x15,0x83,0xc6, 0x10,0xe2,0xf5,0xcd,0x18,0x8b,0x14,0x8b,0xee,0x83, 0xc6,0x10,0x49,0x74,0x16,0x38,0x2c,0x74,0xf6,0xbe, 0x10,0x7 ,0x4e,0xac,0x3c,0x0 ,0x74,0xfa,0xbb,0x7 , 0x0 ,0xb4,0xe ,0xcd,0x10,0xeb,0xf2,0x89,0x46,0x25, 0x96,0x8a,0x46,0x4 ,0xb4,0x6 ,0x3c,0xe ,0x74,0x11, 0xb4,0xb ,0x3c,0xc ,0x74,0x5 ,0x3a,0xc4,0x75,0x2b, 0x40,0xc6,0x46,0x25,0x6 ,0x75,0x24,0xbb,0xaa,0x55, 0x50,0xb4,0x41,0xcd,0x13,0x58,0x72,0x16,0x81,0xfb, 0x55,0xaa,0x75,0x10,0xf6,0xc1,0x1 ,0x74,0xb ,0x8a, 0xe0,0x88,0x56,0x24,0xc7,0x6 ,0xa1,0x6 ,0xeb,0x1e, 0x88,0x66,0x4 ,0xbf,0xa ,0x0 ,0xb8,0x1 ,0x2 ,0x8b, 0xdc,0x33,0xc9,0x83,0xff,0x5 ,0x7f,0x3 ,0x8b,0x4e, 0x25,0x3 ,0x4e,0x2 ,0xcd,0x13,0x72,0x29,0xbe,0x46, 0x7 ,0x81,0x3e,0xfe,0x7d,0x55,0xaa,0x74,0x5a,0x83, 0xef,0x5 ,0x7f,0xda,0x85,0xf6,0x75,0x83,0xbe,0x27, 0x7 ,0xeb,0x8a,0x98,0x91,0x52,0x99,0x3 ,0x46,0x8 , 0x13,0x56,0xa ,0xe8,0x12,0x0 ,0x5a,0xeb,0xd5,0x4f, 0x74,0xe4,0x33,0xc0,0xcd,0x13,0xeb,0xb8,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x56,0x33,0xf6,0x56,0x56,0x52, 0x50,0x6 ,0x53,0x51,0xbe,0x10,0x0 ,0x56,0x8b,0xf4, 0x50,0x52,0xb8,0x0 ,0x42,0x8a,0x56,0x24,0xcd,0x13, 0x5a,0x58,0x8d,0x64,0x10,0x72,0xa ,0x40,0x75,0x1 , 0x42,0x80,0xc7,0x2 ,0xe2,0xf7,0xf8,0x5e,0xc3,0xeb, 0x74,0x49,0x6e,0x76,0x61,0x6c,0x69,0x64,0x20,0x70, 0x61,0x72,0x74,0x69,0x74,0x69,0x6f,0x6e,0x20,0x74, 0x61,0x62,0x6c,0x65,0x0 ,0x45,0x72,0x72,0x6f,0x72, 0x20,0x6c,0x6f,0x61,0x64,0x69,0x6e,0x67,0x20,0x6f, 0x70,0x65,0x72,0x61,0x74,0x69,0x6e,0x67,0x20,0x73, 0x79,0x73,0x74,0x65,0x6d,0x0 ,0x4d,0x69,0x73,0x73, 0x69,0x6e,0x67,0x20,0x6f,0x70,0x65,0x72,0x61,0x74, 0x69,0x6e,0x67,0x20,0x73,0x79,0x73,0x74,0x65,0x6d, 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x8b,0xfc,0x1e, 0x57,0x8b,0xf5,0xcb,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 ,0x0 , 0x55,0xaa}; btHardDisk &= 0x7f; //Get disk geometry and layout information *pnError = nErrorCode = ERR_PARMAN_PARAM; // 102 indicate false if ( GetDiskGeometry(btHardDisk,&dg)) return FALSE; if ( GetDriveLayout(btHardDisk, &DriveLayout)) return FALSE; //found the partition lnStartByte.QuadPart = (__int64)dg.BytesPerSector * dwStartSector; for( nIndex = DriveLayout.dli.PartitionCount -1 ; nIndex >=0 ; nIndex-- ) { if(DriveLayout.dli.PartitionEntry[nIndex].StartingOffset.QuadPart == lnStartByte.QuadPart) break; } //usb disk if((DriveLayout.dli.PartitionCount == 1)&&(nIndex == 0)) { GetDriveParam(btHardDisk,&bdp); WriteSector(6,1,stdMBR,btHardDisk,&bdp); return WriteSector(0,1,stdMBR,btHardDisk,&bdp); } //if found do delete if(nIndex >= 0) { switch( GetPartitionType(&DriveLayout, nIndex) ) { case DISKMAN_PAR_UNUSED: nErrorCode = ERR_PARMAN_PARAM; break; case DISKMAN_PAR_EXTENDED_MBR: if ( flags.Extended ) { //delete first logical if( DeleteLogical(&DriveLayout,4) ) nErrorCode = ERR_PARMAN_PARAM; else nErrorCode = 0; break; }//else consider as primary case DISKMAN_PAR_PRIMARY_MBR: if( DeletePrimary(&DriveLayout,nIndex) ) nErrorCode = ERR_PARMAN_PARAM; else nErrorCode = 0; break; case DISKMAN_PAR_EXTENDED_EMBR: nIndex +=3; case DISKMAN_PAR_LOGICAL_EMBR: if( DeleteLogical(&DriveLayout,nIndex) ) nErrorCode = ERR_PARMAN_PARAM; else nErrorCode = 0; break; } //if success, nErrorCode == 0 //write the layout information back if( !nErrorCode ) nErrorCode = SetDriveLayout(btHardDisk, &DriveLayout); } *pnError = nErrorCode; // nErrorCode == 0, return TRUE; return !nErrorCode; }
void DirectoryWrite(Directory* dir) { for (uint32_t i = 0; i < dir->count; i++) WriteSector(dir->sectors[i]->buffer, dir->sectors[i]->sector); }
/******************************************************************************* * Function Name : MainTrim * Description : STC3115 internal register configuration function * This function has to be called at stable battery voltage during the application magnufacturing * This function is checking itself the propper configuration of the device. *******************************************************************************/ int MainTrim(struct i2c_client *client) { unsigned char IDCode; int ii,error,testnbr; if (client) sav_client = client; else return STC_CONFIG_CLIENT_FAIL; //Check the cut v ersion I2C_ReadByte(0xE0,0x18,&IDCode,1); //read IDcode if(IDCode == 0x13) { return STC_CONFIG_IDCODE_NOTMATCH; } ReadRAM(); //Enter test mode ReadSector(0, Sector0); //read sector 0 ExitTest(); //exit test mode if ( (Sector0[1] & 0x01) == 0 ) { testnbr=0; do { ReadRAM(); //Enter test mode ReadSector(0, Sector0); //read sector 0 ExitTest(); //exit test mode Sector0 [1] = Sector0[1] | 0x01 ; PreWriteNVN(0x40); //Enter test mode WriteSector(6,Sector0);//write sector 0 in 6 ExitTest(); ReadRAM(); //Enter test mode ReadSector(6, Sector6); //read sector 6 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector6[ii]) error++; } testnbr++; } while(error > 0 && testnbr < 5); if (testnbr >= 3) return STC_CONFIG_TEST_FAIL; testnbr=0; do { PreWriteNVN(0x01); //Enter test mode WriteSector(0,Sector6);//write sector 0 in 0 ExitTest(); ReadRAM(); //Enter test mode ReadSector(0, Sector0); //read sector 0 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector6[ii]) error++; } testnbr++; } while(error > 0 && testnbr < 5); } //Check sector 6 status #if defined (CONFIG_MACH_HENDRIX) || \ defined (CONFIG_MACH_LT02) || \ defined (CONFIG_MACH_COCOA7) Sector3 [ 0 ]=0x82 ; Sector3 [ 1 ]=0x8C ; Sector3 [ 2 ]=0xA0 ; Sector3 [ 3 ]=0xB4 ; Sector3 [ 4 ]=0xC8 ; Sector3 [ 5 ]=0x70 ; Sector3 [ 6 ]=0x17 ; Sector3 [ 7 ]=0x27 ; Sector4 [ 0 ]=0x19 ; Sector4 [ 1 ]=0xB2 ; Sector4 [ 2 ]=0x19 ; Sector4 [ 3 ]=0xFA ; Sector4 [ 4 ]=0x19 ; Sector4 [ 5 ]=0x3E ; Sector4 [ 6 ]=0x1A ; Sector4 [ 7 ]=0x6D ; Sector5 [ 0 ]=0x1A ; Sector5 [ 1 ]=0x9D ; Sector5 [ 2 ]=0x1A ; Sector5 [ 3 ]=0xB7 ; Sector5 [ 4 ]=0x1A ; Sector5 [ 5 ]=0xD5 ; Sector5 [ 6 ]=0x1A ; Sector5 [ 7 ]=0x01 ; Sector6 [ 0 ]=0x1B ; Sector6 [ 1 ]=0x6F ; Sector6 [ 2 ]=0x1B ; Sector6 [ 3 ]=0xB1 ; Sector6 [ 4 ]=0x1B ; Sector6 [ 5 ]=0xE7 ; Sector6 [ 6 ]=0x1B ; Sector6 [ 7 ]=0x59 ; ReadRAM(); //Enter test mode ReadSector(7, Sector0); //read sector 7 ReadSector(7, Sector7); //read sector 7 ExitTest(); //exit test mode Sector7 [ 0 ]=0x1C ; Sector7 [ 1 ]=0xF3 ; Sector7 [ 2 ]=0x1C ; Sector7 [ 3 ]=0xA8 ; Sector7 [ 4 ]=0x1D ; error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector7[ii]) error++; } testnbr=0; while(error > 0 && testnbr < 5) { PreWriteNVN(0x80); //Enter test mode WriteSector(7,Sector7);//write sector 7 in 7 ExitTest(); ReadRAM(); //Enter test mode ReadSector(7, Sector0); //read sector 7 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector7[ii] != Sector0[ii]) error++; } testnbr++; } //write sector 3 in 3 ReadRAM(); //Enter test mode ReadSector(3, Sector0); //read sector 3 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector3[ii]) error++; } testnbr=0; while(error > 0 && testnbr < 5) { PreWriteNVN(0x08); //Enter test mode WriteSector(3,Sector3);//write sector 3 in 3 ExitTest(); ReadRAM(); //Enter test mode ReadSector(3, Sector0); //read sector 3 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector3[ii] != Sector0[ii]) error++; } testnbr++; } //write sector 4 in 4 ReadRAM(); //Enter test mode ReadSector(4, Sector0); //read sector 4 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector4[ii]) error++; } testnbr=0; while(error > 0 && testnbr < 5) { PreWriteNVN(0x10); //Enter test mode WriteSector(4,Sector4);//write sector 4 in 4 ExitTest(); ReadRAM(); //Enter test mode ReadSector(4, Sector0); //read sector 4 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector4[ii] != Sector0[ii]) error++; } testnbr++; } //write sector 5 in 5 ReadRAM(); //Enter test mode ReadSector(5, Sector0); //read sector 5 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector5[ii]) error++; } testnbr=0; while(error > 0 && testnbr < 5) { PreWriteNVN(0x20); //Enter test mode WriteSector(5,Sector5);//write sector 5 in 5 ExitTest(); ReadRAM(); //Enter test mode ReadSector(5, Sector0); //read sector 5 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector5[ii] != Sector0[ii]) error++; } testnbr++; } //write sector 6 in 6 ReadRAM(); //Enter test mode ReadSector(6, Sector0); //read sector 6 ExitTest(); //exit test mode #else Sector6 [ 0 ]=0x1B ; Sector6 [ 1 ]=0xCD ; Sector6 [ 2 ]=0x1B ; Sector6 [ 3 ]=0x13 ; Sector6 [ 4 ]=0x1C ; Sector6 [ 5 ]=0x57 ; Sector6 [ 6 ]=0x1C ; Sector6 [ 7 ]=0x09 ; ReadRAM(); //Enter test mode ReadSector(6, Sector0); //read sector 0 ExitTest(); //exit test mode #endif error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector6[ii]) error++; } testnbr=0; while(error > 0 && testnbr < 5) { PreWriteNVN(0x40); //Enter test mode WriteSector(6,Sector6);//write sector 6 in 6 ExitTest(); ReadRAM(); //Enter test mode ReadSector(6, Sector0); //read sector 0 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector6[ii]) error++; } testnbr++; } return -1; }
void _CRTAPI1 main( int cArgs, char *szArg[] ) { HANDLE Handle; int i, j, k; BOOLEAN fMore = FALSE; ULONG cbRead; char c, chLastCmd; ULONG lsn; BOOLEAN fModify = FALSE; ULONG AlignmentMask; /* See if we are connected to CON */ fBatch = !isatty( 0 ); switch( cArgs ) { case 2: /* Nothing to do for level 2 */ break; case 3: if( strcmp( _strupr(szArg[2]), "/E" ) == 0 ) { fModify = TRUE; fprintf( stderr, "Warning: Opening drive %s for write access!\n", szArg[1] ); break; } else { fprintf(stderr, "%s: Invalid option '%s'\n", szArg[0], szArg[2]); } /* Note fall through to default: (usage case) */ default: if( cArgs > 3 ) fprintf( stderr, "%s: Too many arguments\n", szArg[0] ); fprintf( stderr, "usage: %s drive_or_file [/e]\n", szArg[0] ); exit(-1); break; } if( !OpenFile( szArg[1], &Handle ) ){ fprintf( stderr, "%s: Unable to open %s\n", szArg[0], szArg[1] ); exit(1); } if( !QueryVolumeInformation( Handle, &AlignmentMask, &SectorSize ) ) { fprintf( stderr, "Cannot determine volume information.\n" ); exit(1); } // Allocate a buffer to read and write sectors. Note that this // buffer has to satisfy the device's alignment restrictions. DataBuffer = (PBYTE)malloc( SectorSize + AlignmentMask ); if( DataBuffer == NULL ) { fprintf( stderr, "Out of memory.\n" ); exit(1); } SectorData = (PBYTE)(((ULONG)(DataBuffer) + AlignmentMask) & ~AlignmentMask); // /* check if we want to do writes with dasd */ if( fModify && szArg[1][1] == '\\' && szArg[1][2] == ':' ) { // This is a drive, and we want to modify it, so we need // to lock it. if( !LockVolume( Handle ) ) { printf( "Unable to lock volume.\n" ); exit(1); } } /* default to sector 0 */ lsn = 0; PromptUsr(); while( fgets(szCommand, sizeof( szCommand ), stdin) ){ if( (i = sscanf( szCommand, "%c %li", &c, &lsn )) > 1 ) { /* * The user entered a lsn as well as a command, * convert it to byte seek pos */ lsn *= SectorSize; } fMore = FALSE; c = (char)tolower( (int)c ); /* pre process command */ if( c == 'q' ) break; switch( c ) { case 'b': if( i == 1 && chLastCmd == c ) { /* same command with no new lsn, use the next one on disk */ lsn -= cbRead; } break; case 'm': case 'd': case 'e': if( i == 1 && chLastCmd == c ) { /* same command with no new lsn, use the next one on disk */ lsn += cbRead; } break; default: fprintf(stderr,"Unknown command '%c'\n", c ); fprintf(stderr," d [####]\tDump sector ####\n" ); fprintf(stderr," e [####]\tEdit sector ####\n" ); fprintf(stderr," m [####]\tDump sector with 'MORE'\n"); fprintf(stderr," b [####]\tSame as 'd' but defaults to" " previous sector\n"); fprintf(stderr," q \tquit the program" ); fprintf(stderr,"\n" "\n If no new sector is given and the command is the same, the next" "\n sector on the disk is used. If no sector is given but the command" "\n is different from the previous command, the sector used in the" "\n last command will be used again.\n" ); PromptUsr(); continue; } /* remember last command */ chLastCmd = c; cbRead = 0; if( !ReadSector( Handle, lsn, SectorData, &cbRead ) ) { printf( "Unable to read sector %lx\n", lsn ); } else { printf( "\n lsn:0x%lX bytes read:%d\n", lsn / SectorSize, cbRead ); switch( c ) { case 'm': /* * More */ fMore = TRUE; /* fall through to Dump */ case 'd': case 'b': /* * Dump */ k = 0; for( i = 0; i < cbRead; i += CB_LINE ) { if( fMore && k++ == 20 ) { printf( "\n--MORE--" ); MyGetChr(); printf( "\r" ); k = 0; } printf("\n%04X ", i ); for( j = 0; j < CB_LINE && (j + i) < cbRead; j++ ) { printf( "%02X ", (BYTE)SectorData[i + j] ); } printf( " " ); for( j = 0; j < CB_LINE && (j + i) < cbRead; j++ ) { if( (c = SectorData[i + j]) >= ' ' && c <= '\177' ) putchar( c ); else putchar( '.' ); } } putchar( '\n' ); break; case 'e': /* * Edit */ if( !fModify ) { printf( "Can not edit, restart with /e option\n" ); } else { for( i = 0; i < cbRead; i++ ) { if( (i % CB_INPUTLINE) == 0 ) { /* print line header */ printf("\n%04X\t", i ); } printf( "%02X.", (BYTE)SectorData[i] ); if( MyGetInput( &j, &c ) ) { SectorData[i] = (BYTE)j; } else { printf( "%02X", (BYTE)SectorData[i] ); } if( c == '\r' ) break; putchar( '\t' ); } printf( "\nWrite new data to sector? (Y/N)" ); c = (char)MyGetChr(); if( (c = (char)toupper( c )) == 'Y' ) { /* User wants to save the data */ printf( "Yes...." ); if( !WriteSector( Handle, lsn, SectorData ) ) { fprintf( stderr, "Write failed\n" ); } else { /* indicate success */ printf( "\t[Done]\n" ); } } else { /* user chickened out */ printf( "No....\t[Nothing written]\n" ); } } break; } } PromptUsr(); } /* if this was a dasd open, then unlock the drive */ if( fModify ) { UnlockVolume( Handle ); } CloseFile( Handle ); exit(0); }
void WriteSectors(char* buffer, size_t sec, size_t count) { for (size_t i = 0; i < count; i++) WriteSector((char*)(buffer + (i * 512)), sec + i); }
void MakeImage::Build(Directory *root, const char *filename, int totalBlocks) { mRootDir = root; ofstream outFile; outFile.open(filename, ios_base::binary | ios_base::trunc); char *sector = 0; int pathTableSize = 0; char *rootPathEntry = 0; //======================= // write path table PathTable *table = new PathTable(mRootDir); sector = new char[SECTOR_SIZE]; // create char array ZeroMemory(sector, SECTOR_SIZE); // clear to 0 table->MakeTable(sector, PathTable::TYPE_L); // make type L path table WriteSector(outFile, mLPathSector, sector); // write it to file delete [] sector; // delete char array sector = new char[SECTOR_SIZE]; // create char array ZeroMemory(sector, SECTOR_SIZE); // clear to 0 table->MakeTable(sector, PathTable::TYPE_M); // make type M path table WriteSector(outFile, mMPathSector, sector); // write it to file delete [] sector; // delete char array pathTableSize = table->GetSize(); delete table; //======================= //======================= // write primary volume descriptor sector = new char[SECTOR_SIZE]; // create char array ZeroMemory(sector, SECTOR_SIZE); // clear to 0 MakePrimaryVolumeDescriptor(sector, totalBlocks, pathTableSize); WriteSector(outFile, mPrimaryVolSector, sector); // write it to file delete [] sector; // delete char array //======================= //======================= // write boot volume descriptor sector = new char[SECTOR_SIZE]; // create char array ZeroMemory(sector, SECTOR_SIZE); // clear to 0 MakeBootVolumeDescriptor(sector); // make boot volume descriptor WriteSector(outFile, mBootVolSector, sector); // write it to file delete [] sector; // delete char array //======================= //======================= // write terminator volume descriptor sector = new char[SECTOR_SIZE]; // create char array ZeroMemory(sector, SECTOR_SIZE); // clear to 0 MakeTerminatorVolumeDescriptor(sector); // make terminator volume descriptor WriteSector(outFile, mTermVolSector, sector); // write it to file delete [] sector; // delete char array //======================= //======================= // write boot catalog sector = new char[SECTOR_SIZE]; // create char array ZeroMemory(sector, SECTOR_SIZE); // clear to 0 MakeBootCatalog(sector); // make boot catalog WriteSector(outFile, mBootCatSector, sector); // write it to file delete [] sector; // delete char array //======================= //======================= // write boot sector sector = new char[SECTOR_SIZE]; // create char array ZeroMemory(sector, SECTOR_SIZE); // clear to 0 MakeBootSector(sector); // make boot sector WriteSector(outFile, mBootSector, sector); // write it to file delete [] sector; // delete char array //======================= WriteFiles(mRootDir, outFile); outFile.close(); mRootDir = 0; }
static BOOL WriteSector1 (U32 sect, U8 *buf, U32 cnt) { return (WriteSector (1, sect, buf, cnt)); }
BOOL WriteSecsWithBuf(DWORD dwStart,DWORD dwSize,BYTE btDisk,BYTE *pBuf,BOOL bVerify) { DWORD i,j,k; int nTry; BYTE *pCompBuf; BIOS_DRIVE_PARAM DriveParam; pCompBuf = NULL; if(bVerify) { pCompBuf = (BYTE *) _fmalloc(DATA_BUFFER_SIZE); if(!pBuf) { ErrorMessageBox(NO_MEMORY); return FALSE; } } if(!GetDriveParam(btDisk,&DriveParam)) { if(pCompBuf) free(pCompBuf); ErrorMessageBox(GET_DISK_PARAM_FAIL); return FALSE; } i = dwSize / DATA_BUFFER_SECTOR; j = dwSize % DATA_BUFFER_SECTOR; for (k=0; k<i ; k++) { nTry = 0; TRY_WRITE_LAB1: if(!WriteSector(dwStart+k*DATA_BUFFER_SECTOR,DATA_BUFFER_SECTOR,pBuf,btDisk,&DriveParam)) { if (g_nMaxTry == 0) ErrorMessageBox("Write sector fail."); if (nTry < g_nMaxTry) { nTry ++; SaveVerifyLog(g_chLogDrive,dwStart+k*DATA_BUFFER_SECTOR,DATA_BUFFER_SECTOR,TRUE); goto TRY_WRITE_LAB1; } } else { if(bVerify) { ReadSector(dwStart+k*DATA_BUFFER_SECTOR,DATA_BUFFER_SECTOR,pCompBuf,btDisk,&DriveParam); if(memcmp(pBuf,pCompBuf,DATA_BUFFER_SIZE)) { SaveVerifyLog(g_chLogDrive,dwStart+k*DATA_BUFFER_SECTOR,DATA_BUFFER_SECTOR,FALSE); } } } g_dDeletedSize += DATA_BUFFER_SECTOR; FlushProgressInfo(); } if (j) { nTry = 0; TRY_WRITE_LAB2: if(!WriteSector(dwStart+i*DATA_BUFFER_SECTOR,(WORD)j,pBuf,btDisk,&DriveParam)) { if (g_nMaxTry == 0) ErrorMessageBox("Write sector fail."); if (nTry < g_nMaxTry) { nTry ++; SaveVerifyLog(g_chLogDrive,dwStart+i*DATA_BUFFER_SECTOR,j,TRUE); goto TRY_WRITE_LAB2; } } else { if(bVerify) { ReadSector(dwStart+i*DATA_BUFFER_SECTOR,(WORD)j,pCompBuf,btDisk,&DriveParam); if(memcmp(pBuf,pCompBuf,(int)j*512)) { SaveVerifyLog(g_chLogDrive,dwStart+i*DATA_BUFFER_SECTOR,j,FALSE); } } } g_dDeletedSize += j; FlushProgressInfo(); } if(pCompBuf) free(pCompBuf); return TRUE; }
/******************************************************************************* * Function Name : MainTrim * Description : STC3115 internal register configuration function * This function has to be called at stable battery voltage during the application magnufacturing * This function is checking itself the propper configuration of the device. *******************************************************************************/ int MainTrim(struct i2c_client *client) { unsigned char IDCode,RAMBuffer[16]; int ii,error,testnbr; if (client) sav_client = client; else return STC_CONFIG_CLIENT_FAIL; //Check the cut v ersion I2C_ReadByte(0xE0,0x18,&IDCode,1); //read IDcode if(IDCode == 0x13) { return STC_CONFIG_IDCODE_NOTMATCH; } I2C_ReadByte(0xE0,0x20,RAMBuffer,16); //read RAM memory content ReadRAM(); //Enter test mode ReadSector(0, Sector0); //read sector 0 ExitTest(); //exit test mode if ( (Sector0[1] & 0x01) == 0 ) { testnbr=0; do { ReadRAM(); //Enter test mode ReadSector(0, Sector0); //read sector 0 ExitTest(); //exit test mode Sector0 [1] = Sector0[1] | 0x01 ; PreWriteNVN(0x40); //Enter test mode WriteSector(6,Sector0);//write sector 0 in 6 ExitTest(); ReadRAM(); //Enter test mode ReadSector(6, Sector6); //read sector 6 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector6[ii]) error++; } testnbr++; } while(error > 0 && testnbr < 5); if (testnbr >= 3) { I2C_WriteByte(0xE0,0x20,RAMBuffer,16);//restore RAM memory content return STC_CONFIG_TEST_FAIL; } testnbr=0; do { PreWriteNVN(0x01); //Enter test mode WriteSector(0,Sector6);//write sector 0 in 0 ExitTest(); ReadRAM(); //Enter test mode ReadSector(0, Sector0); //read sector 0 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector6[ii]) error++; } testnbr++; } while(error > 0 && testnbr < 5); } //Check sector 6 status Sector6 [ 0 ]=0x1B ; Sector6 [ 1 ]=0xCD ; Sector6 [ 2 ]=0x1B ; Sector6 [ 3 ]=0x13 ; Sector6 [ 4 ]=0x1C ; Sector6 [ 5 ]=0x57 ; Sector6 [ 6 ]=0x1C ; Sector6 [ 7 ]=0x09 ; ReadRAM(); //Enter test mode ReadSector(6, Sector0); //read sector 7 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector6[ii]) error++; } testnbr=0; while(error > 0 && testnbr < 5) { PreWriteNVN(0x40); //Enter test mode WriteSector(6,Sector6);//write sector 7 in 7 ExitTest(); ReadRAM(); //Enter test mode ReadSector(6, Sector0); //read sector 7 ExitTest(); //exit test mode error=0; for(ii=0;ii<8;ii++) { if(Sector0[ii] != Sector6[ii]) error++; } testnbr++; } I2C_WriteByte(0xE0,0x20,RAMBuffer,16);//restore RAM memory content return -1; }
BOOL WriteFlashNK(UINT32 address, UINT32 size) { BOOL rc = FALSE; HANDLE hFMD; FlashInfo flashInfo; SectorInfo sectorInfo; BOOL ok = FALSE; BLOCK_ID block; //ROMHDR *pTOC; UINT32 *pInfo, count, sector; UINT32 blockSize, sectorSize, sectorsPerBlock; UINT8 *pData; OALMSG(OAL_INFO, (L"OEMWriteFlash: Writing NK image to flash\r\n")); // We need to know sector/block size if ((hFMD = FMD_Init(NULL, NULL, NULL)) == NULL) { OALMSG(OAL_ERROR, (L"ERROR: OEMWriteFlash: " L"FMD_Init call failed\r\n" )); goto cleanUp; } // Get flash info if (!FMD_GetInfo(&flashInfo)) { OALMSG(OAL_ERROR, (L"ERROR: EBOOT!OEMWriteFlash: " L"FMD_GetInfo call failed!\r\n" )); FMD_Deinit(hFMD); goto cleanUp; } // We don't need access to FMD library FMD_Deinit(hFMD); OALMSG(OAL_INFO, (L"OEMWriteFlash: " L"Flash has %d blocks, %d bytes/block, %d sectors/block\r\n", flashInfo.dwNumBlocks, flashInfo.dwBytesPerBlock, flashInfo.wSectorsPerBlock )); // Make block & sector size ready blockSize = flashInfo.dwBytesPerBlock; sectorSize = flashInfo.wDataBytesPerSector; sectorsPerBlock = flashInfo.wSectorsPerBlock; // Get data location pData = OEMMapMemAddr(address, address); // Verify that we get CE image. pInfo = (UINT32*)(pData + ROM_SIGNATURE_OFFSET); if (*pInfo++ != ROM_SIGNATURE) { OALMSG(OAL_ERROR, (L"ERROR: OEMWriteFlash: " L"Image Signature not found\r\n" )); goto cleanUp; } pInfo++; // Skip reserved blocks block = 0; while (block < flashInfo.dwNumBlocks) { if ((FMD_GetBlockStatus(block) & BLOCK_STATUS_BAD) != 0) { OALMSG(OAL_WARN, (L"WARN: EBOOT!OEMWriteFlash: " L"Skip bad block %d\r\n", block )); block++; continue; } if ((FMD_GetBlockStatus(block) & BLOCK_STATUS_RESERVED) == 0) break; block++; } OALMSG(OAL_INFO, (L"OEMWriteFlash: " L"NK image starts at block %d\r\n", block )); // Write image count = 0; while (count < size && block < flashInfo.dwNumBlocks) { // If block is bad, we have to offset it if ((FMD_GetBlockStatus(block) & BLOCK_STATUS_BAD) != 0) { block++; OALMSG(OAL_WARN, (L"WARN: EBOOT!OEMWriteFlash: " L"Skip bad block %d\r\n", block )); continue; } // Erase block if (!EraseBlock(block)) { FMD_SetBlockStatus(block, BLOCK_STATUS_BAD); block++; OALMSG(OAL_WARN, (L"WARN: EBOOT!OEMWriteFlash: " L"Block %d erase failed, mark block as bad\r\n", block )); continue; } // Now write sectors sector = 0; while (sector < sectorsPerBlock && count < size) { // Prepare sector info memset(§orInfo, 0xFF, sizeof(sectorInfo)); sectorInfo.dwReserved1 = 0; sectorInfo.wReserved2 = 0; // Write sector if (!(ok = WriteSector( block * sectorsPerBlock + sector, pData + count, §orInfo ))) break; // Move to next sector count += sectorSize; sector++; } // When sector write failed, mark block as bad and move back if (!ok) { OALMSG(OAL_WARN, (L"WARN: EBOOT!OEMWriteFlash: " L"Block %d sector %d write failed, mark block as bad\r\n", block, sector )); // First move back count -= sector * flashInfo.wDataBytesPerSector; // Mark block as bad FMD_SetBlockStatus(block, BLOCK_STATUS_BAD); } // We are done with block block++; } // Erase rest of media while (block < flashInfo.dwNumBlocks) { // If block is bad, we have to offset it if ((FMD_GetBlockStatus(block) & BLOCK_STATUS_BAD) != 0) { block++; OALMSG(OAL_WARN, (L"WARN: EBOOT!OEMWriteFlash: " L"Skip bad block %d\r\n", block )); continue; } // When erase failed, mark block as bad and skip it if (!EraseBlock(block)) { FMD_SetBlockStatus(block, BLOCK_STATUS_BAD); block++; OALMSG(OAL_WARN, (L"WARN: EBOOT!OEMWriteFlash: " L"Block %d erase failed, mark block as bad\r\n", block )); continue; } // Move to next block block++; } // Close FMD driver FMD_Deinit(hFMD); hFMD = NULL; OALMSG(OAL_INFO, (L"OEMWriteFlash: NK written\r\n")); // Done rc = TRUE; cleanUp: if (hFMD != NULL) FMD_Deinit(hFMD); return rc; }
int FormatNoFs (HWND hwndDlg, unsigned __int64 startSector, __int64 num_sectors, void * dev, PCRYPTO_INFO cryptoInfo, BOOL quickFormat) { int write_buf_cnt = 0; char sector[TC_MAX_VOLUME_SECTOR_SIZE], *write_buf; unsigned __int64 nSecNo = startSector; int retVal = 0; DWORD err; char temporaryKey[MASTER_KEYDATA_SIZE]; char originalK2[MASTER_KEYDATA_SIZE]; LARGE_INTEGER startOffset; LARGE_INTEGER newOffset; // Seek to start sector startOffset.QuadPart = startSector * FormatSectorSize; if (!SetFilePointerEx ((HANDLE) dev, startOffset, &newOffset, FILE_BEGIN) || newOffset.QuadPart != startOffset.QuadPart) { return ERR_OS_ERROR; } write_buf = (char *)TCalloc (FormatWriteBufferSize); if (!write_buf) return ERR_OUTOFMEMORY; VirtualLock (temporaryKey, sizeof (temporaryKey)); VirtualLock (originalK2, sizeof (originalK2)); memset (sector, 0, sizeof (sector)); // Remember the original secondary key (XTS mode) before generating a temporary one memcpy (originalK2, cryptoInfo->k2, sizeof (cryptoInfo->k2)); /* Fill the rest of the data area with random data */ if(!quickFormat) { /* Generate a random temporary key set to be used for "dummy" encryption that will fill the free disk space (data area) with random data. This is necessary for plausible deniability of hidden volumes. */ // Temporary master key if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (cryptoInfo->ea), FALSE)) goto fail; // Temporary secondary key (XTS mode) if (!RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof cryptoInfo->k2, FALSE)) goto fail; retVal = EAInit (cryptoInfo->ea, temporaryKey, cryptoInfo->ks); if (retVal != ERR_SUCCESS) goto fail; if (!EAInitMode (cryptoInfo)) { retVal = ERR_MODE_INIT_FAILED; goto fail; } while (num_sectors--) { if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo) == FALSE) goto fail; } if (!FlushFormatWriteBuffer (dev, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo)) goto fail; } else nSecNo = num_sectors; UpdateProgressBar (nSecNo * FormatSectorSize); // Restore the original secondary key (XTS mode) in case NTFS format fails and the user wants to try FAT immediately memcpy (cryptoInfo->k2, originalK2, sizeof (cryptoInfo->k2)); // Reinitialize the encryption algorithm and mode in case NTFS format fails and the user wants to try FAT immediately retVal = EAInit (cryptoInfo->ea, cryptoInfo->master_keydata, cryptoInfo->ks); if (retVal != ERR_SUCCESS) goto fail; if (!EAInitMode (cryptoInfo)) { retVal = ERR_MODE_INIT_FAILED; goto fail; } burn (temporaryKey, sizeof(temporaryKey)); burn (originalK2, sizeof(originalK2)); VirtualUnlock (temporaryKey, sizeof (temporaryKey)); VirtualUnlock (originalK2, sizeof (originalK2)); TCfree (write_buf); return 0; fail: err = GetLastError(); burn (temporaryKey, sizeof(temporaryKey)); burn (originalK2, sizeof(originalK2)); VirtualUnlock (temporaryKey, sizeof (temporaryKey)); VirtualUnlock (originalK2, sizeof (originalK2)); TCfree (write_buf); SetLastError (err); return (retVal ? retVal : ERR_OS_ERROR); }
// ------------------------------------------------------------------------------------------------ int main(int argc, const char** argv) { // Parse arguments if (argc < 3) { Usage(); return EXIT_FAILURE; } const char* diskPath = argv[1]; const char* dumpPath = argv[2]; // Read sector 0 char curSector[SECTOR_SIZE]; if (!ReadSector(diskPath, curSector)) { fprintf(stderr, "Failed to read current boot sector: %lu\n", GetLastError()); return EXIT_FAILURE; } // Dump sector 0 if (!WriteSector(dumpPath, curSector)) { fprintf(stderr, "Failed to dump boot sector: %lu\n", GetLastError()); return EXIT_FAILURE; } // Output parameter block BiosParamBlock* bpb = (BiosParamBlock *)curSector; char oem[9]; char volumeLabel[12]; char fileSystem[9]; memcpy(oem, bpb->oem, sizeof(bpb->oem)); memcpy(volumeLabel, bpb->volumeLabel, sizeof(bpb->volumeLabel)); memcpy(fileSystem, bpb->fileSystem, sizeof(bpb->fileSystem)); oem[8] = '\0'; volumeLabel[11] = '\0'; fileSystem[8] = '\0'; fprintf(stdout, "OEM = %s\n", oem); fprintf(stdout, "Bytes Per Sector = %d\n", bpb->bytesPerSector); fprintf(stdout, "Sectors Per Cluster = %d\n", bpb->sectorsPerCluster); fprintf(stdout, "Reserved Sector Count = %d\n", bpb->reservedSectorCount); fprintf(stdout, "FAT Count = %d\n", bpb->fatCount); fprintf(stdout, "Root Entry Count = %d\n", bpb->rootEntryCount); fprintf(stdout, "Sector Count = %d\n", bpb->sectorCount); fprintf(stdout, "Media Type = 0x%x\n", bpb->mediaType); fprintf(stdout, "Sectors Per FAT = %d\n", bpb->sectorsPerFat); fprintf(stdout, "Sectors Per Track = %d\n", bpb->sectorsPerTrack); fprintf(stdout, "Head Count = %d\n", bpb->headCount); fprintf(stdout, "Hidden Sector Count = %d\n", bpb->hiddenSectorCount); fprintf(stdout, "Large Sector Count = %d\n", bpb->largeSectorCount); fprintf(stdout, "Drive Number = %d\n", bpb->driveNumber); fprintf(stdout, "Flags = %d\n", bpb->flags); fprintf(stdout, "Signature = %d\n", bpb->signature); fprintf(stdout, "Volume ID = 0x%8x\n", bpb->volumeId); fprintf(stdout, "Volume Label = %s\n", volumeLabel); fprintf(stdout, "File System = %s\n", fileSystem); // Success! return EXIT_SUCCESS; }