summaryrefslogtreecommitdiff
path: root/utils/xbox/xbox_loader/xbox_fileCopy.cpp
blob: 39d0c6574a6fc01aaf8c30e9489e2cbe573d1903 (plain) (blame)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//========= Copyright Valve Corporation, All rights reserved. ============//
//
//	Copies a file using overlapped async IO.
//
//	Stub executeable
//=====================================================================================//
#include "xbox_loader.h"

#define BUFFER_SIZE			(1*1024*1024)
#define NUM_BUFFERS			4
#define ALIGN(x,y)			(((x)+(y)-1) & ~((y)-1))

struct CopyFile_t
{
	// source file
	HANDLE				m_hSrcFile;
	DWORD				m_srcFileSize;
	int					m_readBufferSize;
	unsigned int		m_numReadCycles;

	// target file
	HANDLE				m_hDstFile;
	DWORD				m_dstFileSize;

	// source file gets decompressed
	bool				m_bInflate;
	unsigned char		*m_pInflateBuffer;
	int					m_inflateBufferSize;

	bool				m_bCopyError;
	CopyStats_t			*m_pCopyStats;
};

struct Buffer_t
{
	unsigned char	*pData;
	DWORD			dwSize;
	Buffer_t*		pNext;
	int				id;
};

Buffer_t	*g_pReadBuffers = NULL;
Buffer_t	*g_pWriteBuffers = NULL;

CRITICAL_SECTION	g_criticalSection;
HANDLE				g_hReadEvent;
HANDLE				g_hWriteEvent;
DWORD				*g_pNumReadBuffers;
DWORD				*g_pNumWriteBuffers;

//-----------------------------------------------------------------------------
// CreateFilePath
//
// Create full path to specified file.
//-----------------------------------------------------------------------------
bool CreateFilePath( const char *inPath )
{
	char*	ptr;
	char	dirPath[MAX_PATH];
	BOOL	bSuccess;

	// prime and skip to first seperator after the drive path
	strcpy( dirPath, inPath );
	ptr = strchr( dirPath, '\\' );
	while ( ptr )
	{		
		ptr = strchr( ptr+1, '\\' );
		if ( ptr )
		{
			*ptr = '\0';
			bSuccess = ::CreateDirectory( dirPath, NULL );
			*ptr = '\\';
		}
	}

	// ensure read-only is cleared
	SetFileAttributes( inPath, FILE_ATTRIBUTE_NORMAL );

	return true;
}

//-----------------------------------------------------------------------------
// LockBufferForRead
//
//-----------------------------------------------------------------------------
Buffer_t *LockBufferForRead()
{
	if ( !g_pReadBuffers )
	{
		// out of data, wait for it
		WaitForSingleObject( g_hReadEvent, INFINITE );
	}
	else
	{
		ResetEvent( g_hReadEvent );
	}

	EnterCriticalSection( &g_criticalSection );

	Buffer_t *pBuffer = g_pReadBuffers;
	g_pReadBuffers = pBuffer->pNext;

	(*g_pNumReadBuffers)--;

	LeaveCriticalSection( &g_criticalSection );

	return pBuffer;
}

//-----------------------------------------------------------------------------
// LockBufferForWrite
//
//-----------------------------------------------------------------------------
Buffer_t* LockBufferForWrite()
{
	if ( !g_pWriteBuffers )
	{
		// out of data, wait for more
		WaitForSingleObject( g_hWriteEvent, INFINITE );
	}
	else
	{
		ResetEvent( g_hWriteEvent );
	}

	EnterCriticalSection( &g_criticalSection );

	Buffer_t *pBuffer = g_pWriteBuffers;
	g_pWriteBuffers = pBuffer->pNext;

	(*g_pNumWriteBuffers)--;

	LeaveCriticalSection( &g_criticalSection );

	return pBuffer;
}

//-----------------------------------------------------------------------------
// AddBufferForRead
//
//-----------------------------------------------------------------------------
void AddBufferForRead( Buffer_t *pBuffer )
{
	EnterCriticalSection( &g_criticalSection );

	// add to end of list
	Buffer_t *pCurrent = g_pReadBuffers;
	while ( pCurrent && pCurrent->pNext )
	{
		pCurrent = pCurrent->pNext;
	}
	if ( pCurrent )
	{
		pBuffer->pNext  = pCurrent->pNext;
		pCurrent->pNext = pBuffer;
	}
	else
	{
		pBuffer->pNext = NULL;
		g_pReadBuffers = pBuffer;
	}
	
	(*g_pNumReadBuffers)++;

	LeaveCriticalSection( &g_criticalSection );

	SetEvent( g_hReadEvent );
}

//-----------------------------------------------------------------------------
// AddBufferForWrite
//
//-----------------------------------------------------------------------------
void AddBufferForWrite( Buffer_t *pBuffer )
{
	EnterCriticalSection( &g_criticalSection );

	// add to end of list
	Buffer_t* pCurrent = g_pWriteBuffers;
	while ( pCurrent && pCurrent->pNext )
	{
		pCurrent = pCurrent->pNext;
	}
	if ( pCurrent )
	{
		pBuffer->pNext  = pCurrent->pNext;
		pCurrent->pNext = pBuffer;
	}
	else
	{
		pBuffer->pNext = NULL;
		g_pWriteBuffers = pBuffer;
	}

	(*g_pNumWriteBuffers)++;

	LeaveCriticalSection( &g_criticalSection );

	SetEvent( g_hWriteEvent );
}

//-----------------------------------------------------------------------------
// ReadFileThread
//
//-----------------------------------------------------------------------------
DWORD WINAPI ReadFileThread( LPVOID lParam )
{
	CopyFile_t		*pCopyFile;
	OVERLAPPED		overlappedRead = {0};
	DWORD			startTime;
	DWORD			dwBytesRead;
	DWORD			dwError;
	BOOL			bResult;
	Buffer_t		*pBuffer;

	pCopyFile = (CopyFile_t*)lParam;

	// Copy from the buffer to the Hard Drive
	for ( unsigned int readCycle = 0; readCycle < pCopyFile->m_numReadCycles; ++readCycle )
	{
		pBuffer = LockBufferForRead();

		startTime = GetTickCount();
		dwBytesRead = 0;

		int numAttempts = 0;
retry:
		// read file from DVD
		bResult = ReadFile( pCopyFile->m_hSrcFile, pBuffer->pData, pCopyFile->m_readBufferSize, NULL, &overlappedRead );
		dwError = GetLastError();
		if ( !bResult && dwError != ERROR_IO_PENDING )
		{
			if ( dwError == ERROR_HANDLE_EOF )
			{
				// nothing more to read
				break;
			}

			numAttempts++;
			if ( numAttempts == 3 )
			{
				// error
				pCopyFile->m_bCopyError = true;
				break;
			}
			else
			{
				goto retry;
			}
		}
		else
		{
			// Wait for the operation to finish
			GetOverlappedResult( pCopyFile->m_hSrcFile, &overlappedRead, &dwBytesRead, TRUE );
			overlappedRead.Offset += dwBytesRead;
		}

		if ( !dwBytesRead  )
		{
			pCopyFile->m_bCopyError = true;
			break;
		}

		pCopyFile->m_pCopyStats->m_bufferReadSize = dwBytesRead;
		pCopyFile->m_pCopyStats->m_bufferReadTime = GetTickCount() - startTime;
		pCopyFile->m_pCopyStats->m_totalReadSize += pCopyFile->m_pCopyStats->m_bufferReadSize;
		pCopyFile->m_pCopyStats->m_totalReadTime += pCopyFile->m_pCopyStats->m_bufferReadTime;

		pBuffer->dwSize = dwBytesRead;
		AddBufferForWrite( pBuffer );
	}

	return 0;
}

//-----------------------------------------------------------------------------
// WriteFileThread
//
//-----------------------------------------------------------------------------
DWORD WINAPI WriteFileThread( LPVOID lParam )
{
	CopyFile_t		*pCopyFile;
	OVERLAPPED		overlappedWrite = {0};
	DWORD			startTime;
	DWORD			dwBytesWrite;
	DWORD			dwWriteSize;
	DWORD			dwError;
	BOOL			bResult;
	Buffer_t		*pBuffer;
	unsigned char	*pWriteBuffer;

	pCopyFile = (CopyFile_t*)lParam;

	while ( overlappedWrite.Offset < pCopyFile->m_dstFileSize )
	{
		// wait for wake-up event
		pBuffer = LockBufferForWrite();

		if ( pCopyFile->m_bInflate )
		{
			startTime = GetTickCount();

			DWORD dwSkip = overlappedWrite.Offset ? 0 : sizeof( xCompressHeader );
			dwWriteSize = JCALG1_Decompress_Formatted_Buffer( pBuffer->dwSize - dwSkip, pBuffer->pData + dwSkip, pCopyFile->m_inflateBufferSize, pCopyFile->m_pInflateBuffer );
			if ( dwWriteSize == (DWORD)-1 )
			{
				pCopyFile->m_bCopyError = true;
				break;
			}

			pCopyFile->m_pCopyStats->m_inflateSize = dwWriteSize;
			pCopyFile->m_pCopyStats->m_inflateTime = GetTickCount() - startTime;

			pWriteBuffer = pCopyFile->m_pInflateBuffer;
		}
		else
		{
			// straight copy
			dwWriteSize  = pBuffer->dwSize;
			pWriteBuffer = pBuffer->pData;
		}

		if ( overlappedWrite.Offset + dwWriteSize >= pCopyFile->m_dstFileSize )
		{
			// last buffer, ensure all data is written
			dwWriteSize = ALIGN( dwWriteSize, 512 );
		}

		startTime = GetTickCount();
		dwBytesWrite = 0;
	
		int numAttempts = 0;
retry:
		// write file to HDD
		bResult = WriteFile( pCopyFile->m_hDstFile, pWriteBuffer, (dwWriteSize/512) * 512, NULL, &overlappedWrite );
		dwError = GetLastError();
		if ( !bResult && dwError != ERROR_IO_PENDING )
		{
			numAttempts++;
			if ( numAttempts == 3 )
			{
				// error
				pCopyFile->m_bCopyError = true;
				break;
			}
			else
			{
				goto retry;
			}
		}
		else
		{
			// Wait for the operation to finish
			GetOverlappedResult( pCopyFile->m_hDstFile, &overlappedWrite, &dwBytesWrite, TRUE );
			overlappedWrite.Offset += dwBytesWrite;
		}

		if ( dwBytesWrite  )
		{
			// track expected size
			pCopyFile->m_pCopyStats->m_bytesCopied += dwBytesWrite;
			pCopyFile->m_pCopyStats->m_writeSize += dwBytesWrite;
		}
		else
		{
			pCopyFile->m_bCopyError = true;
			break;
		}

		pCopyFile->m_pCopyStats->m_bufferWriteSize = dwBytesWrite;
		pCopyFile->m_pCopyStats->m_bufferWriteTime = GetTickCount() - startTime;
		pCopyFile->m_pCopyStats->m_totalWriteSize += pCopyFile->m_pCopyStats->m_bufferWriteSize;
		pCopyFile->m_pCopyStats->m_totalWriteTime += pCopyFile->m_pCopyStats->m_bufferWriteTime;

		AddBufferForRead( pBuffer );
	}

	return 0;
}

//-----------------------------------------------------------------------------
// CopyFileInit
//
//-----------------------------------------------------------------------------
void CopyFileInit()
{
	static bool init = false;
	if ( !init )
	{
		InitializeCriticalSection( &g_criticalSection );
		g_hReadEvent  = CreateEvent( NULL, FALSE, FALSE, NULL );
		g_hWriteEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
		init = true;
	}
	else
	{
		// expected startup state
		ResetEvent( g_hReadEvent );
		ResetEvent( g_hWriteEvent );

		g_pReadBuffers  = NULL;
		g_pWriteBuffers = NULL;
	}
}

//-----------------------------------------------------------------------------
// CopyFileOverlapped
//
//-----------------------------------------------------------------------------
bool CopyFileOverlapped( const char *pSrcFilename, const char *pDstFilename, xCompressHeader *pxcHeader, CopyStats_t *pCopyStats )
{
	CopyFile_t	copyFile = {0};
	Buffer_t	buffers[NUM_BUFFERS] = {0};
	HANDLE		hReadThread = NULL;
	HANDLE		hWriteThread = NULL;
	bool		bSuccess = false;
	DWORD		startCopyTime;
	DWORD		dwResult;
	int			i;

	startCopyTime = GetTickCount();

	CopyFileInit();

	g_pNumReadBuffers  = &pCopyStats->m_numReadBuffers;
	g_pNumWriteBuffers = &pCopyStats->m_numWriteBuffers;

	strcpy( pCopyStats->m_srcFilename, pSrcFilename );
	strcpy( pCopyStats->m_dstFilename, pDstFilename );

	copyFile.m_hSrcFile   = INVALID_HANDLE_VALUE;
	copyFile.m_hDstFile   = INVALID_HANDLE_VALUE;
	copyFile.m_pCopyStats = pCopyStats;
	copyFile.m_bCopyError = false;

	// validate the source file
	copyFile.m_hSrcFile = CreateFile( pSrcFilename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED|FILE_FLAG_NO_BUFFERING, NULL );
	if ( copyFile.m_hSrcFile == INVALID_HANDLE_VALUE )
	{
		// failure
		goto cleanUp;
	}

	copyFile.m_srcFileSize = GetFileSize( copyFile.m_hSrcFile, NULL );
	if ( copyFile.m_srcFileSize == (DWORD)-1 )
	{
		// failure
		goto cleanUp;
	}

	// ensure the target file path exists
	CreateFilePath( pDstFilename );

	// validate the target file
	copyFile.m_hDstFile = CreateFile( pDstFilename, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_FLAG_OVERLAPPED|FILE_FLAG_NO_BUFFERING, NULL );
	if ( copyFile.m_hDstFile == INVALID_HANDLE_VALUE )
	{
		// failure
		goto cleanUp;
	}
	
	pCopyStats->m_readSize  = copyFile.m_srcFileSize;
	pCopyStats->m_writeSize = 0;

	if ( pxcHeader )
	{
		// read in chunks of compressed blocks
		copyFile.m_readBufferSize = pxcHeader->nReadBlockSize;
		copyFile.m_dstFileSize = pxcHeader->nUncompressedFileSize;
	}
	else
	{
		// setup for copy
		copyFile.m_readBufferSize = BUFFER_SIZE;
		copyFile.m_dstFileSize = copyFile.m_srcFileSize;
	}

	// setup read buffers
	for ( i=0; i<NUM_BUFFERS; i++)
	{
		buffers[i].pData  = new unsigned char[copyFile.m_readBufferSize];
		buffers[i].dwSize = 0;
		buffers[i].pNext  = NULL;
		AddBufferForRead( &buffers[i] );
	}
	copyFile.m_numReadCycles = (copyFile.m_srcFileSize + copyFile.m_readBufferSize - 1)/copyFile.m_readBufferSize;

	// setup write buffer
	if ( pxcHeader )
	{
		copyFile.m_pInflateBuffer = new unsigned char[pxcHeader->nDecompressionBufferSize];
		copyFile.m_inflateBufferSize = pxcHeader->nDecompressionBufferSize;
		copyFile.m_bInflate = true;
	}
	else
	{
		copyFile.m_bInflate = false;
	}

	// pre-size the target file in aligned buffers
	DWORD dwAligned = ALIGN( copyFile.m_dstFileSize, 512 );
	dwResult = SetFilePointer( copyFile.m_hDstFile, dwAligned, NULL, FILE_BEGIN );
	if ( dwResult == INVALID_SET_FILE_POINTER )
	{
		// failure
		goto cleanUp;
	}
	SetEndOfFile( copyFile.m_hDstFile );

	// start the read thread
	hReadThread = CreateThread( 0, 0, &ReadFileThread, &copyFile, 0, 0 );
	if ( !hReadThread )
	{
		// failure
		goto cleanUp;
	}

	// wait for buffers to populate

	// start the write thread
	hWriteThread = CreateThread( 0, 0, &WriteFileThread, &copyFile, 0, 0 );
	if ( !hWriteThread )
	{
		// failure
		goto cleanUp;
	}

	// wait for write thread to finish
	WaitForSingleObject( hWriteThread, INFINITE );
	WaitForSingleObject( hReadThread, INFINITE );

	if ( copyFile.m_bCopyError )
	{
		goto cleanUp;
	}

	// Fixup the file size
	CloseHandle( copyFile.m_hDstFile );
	copyFile.m_hDstFile = INVALID_HANDLE_VALUE;

	if ( copyFile.m_dstFileSize % 512 )
	{
		// re-open file as non-buffered to adjust to correct file size
		HANDLE hFile = CreateFile( pDstFilename, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
		SetFilePointer( hFile, copyFile.m_dstFileSize, NULL, FILE_BEGIN );
		SetEndOfFile( hFile );
		CloseHandle( hFile );
	}

	// finished
	bSuccess = true;

cleanUp:
	if ( copyFile.m_hSrcFile != INVALID_HANDLE_VALUE )
	{
		CloseHandle( copyFile.m_hSrcFile );
	}

	if ( copyFile.m_hDstFile != INVALID_HANDLE_VALUE )
	{
		CloseHandle( copyFile.m_hDstFile );
	}

	if ( hReadThread )
	{
		CloseHandle( hReadThread );
	}

	if ( hWriteThread )
	{
		CloseHandle( hWriteThread );
	}

	for ( i=0; i<NUM_BUFFERS; i++ )
	{
		if ( buffers[i].pData )
		{
			delete [] buffers[i].pData;
		}
	}

	if ( copyFile.m_pInflateBuffer )
	{
		delete [] copyFile.m_pInflateBuffer;
	}

	if ( !bSuccess )
	{
		pCopyStats->m_copyErrors++;
	}

	pCopyStats->m_copyTime = GetTickCount() - startCopyTime;

	return bSuccess;
}