-
Notifications
You must be signed in to change notification settings - Fork 1
/
disk_image.c
68 lines (55 loc) · 1.77 KB
/
disk_image.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdlib.h>
#include "disk_image.h"
#include "general.h"
DISK_IMG *ImgOpen(const char *pszPath)
{
HANDLE FileHandle = CreateFileA(pszPath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(FileHandle == INVALID_HANDLE_VALUE)
return NULL;
DISK_IMG *pImg = MxfsAlloc(sizeof(DISK_IMG));
if(!pImg)
return NULL;
pImg->FileHandle = FileHandle;
InitializeCriticalSection(&pImg->Lock);
return pImg;
}
void ImgClose(DISK_IMG *pImg)
{
if(!pImg) return;
CloseHandle(pImg->FileHandle);
MxfsFree(pImg);
}
int ImgRead(DISK_IMG *pImg, unsigned uOffset, unsigned cBytes, PVOID pBuf)
{
DWORD dwBytesRead;
BOOL bSuccess;
EnterCriticalSection(&pImg->Lock);
SetFilePointer(pImg->FileHandle, uOffset, NULL, FILE_BEGIN);
bSuccess = ReadFile(pImg->FileHandle, pBuf, cBytes, &dwBytesRead, NULL);
LeaveCriticalSection(&pImg->Lock);
if(!bSuccess || dwBytesRead != cBytes)
return -ERROR_READ_FAULT;
return 0;
}
int ImgWrite(DISK_IMG *pImg, unsigned uOffset, unsigned cBytes, PVOID pBuf)
{
DWORD dwBytesWritten = 0;
BOOL bSuccess = FALSE;
EnterCriticalSection(&pImg->Lock);
if(uOffset + cBytes <= GetFileSize(pImg->FileHandle, NULL))
{
SetFilePointer(pImg->FileHandle, uOffset, NULL, FILE_BEGIN);
bSuccess = WriteFile(pImg->FileHandle, pBuf, cBytes, &dwBytesWritten, NULL);
}
LeaveCriticalSection(&pImg->Lock);
if(!bSuccess || dwBytesWritten != cBytes)
return -ERROR_WRITE_FAULT;
return 0;
}
unsigned ImgGetSize(DISK_IMG *pImg)
{
EnterCriticalSection(&pImg->Lock);
unsigned uSize = GetFileSize(pImg->FileHandle, NULL);
LeaveCriticalSection(&pImg->Lock);
return uSize;
}