forked from JonathanDotCel/NOTPSXSerial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PCDrv.cs
548 lines (396 loc) · 18.3 KB
/
PCDrv.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
class PCDrv {
public static TargetDataPort serial => Program.activeSerial;
public enum PCDrvCodes { unknown, PCINIT_101 = 0x101, PCCREAT_102 = 0x102, PCOPEN_103 = 0x103, PCCLOSE_104 = 0x104, PCREAD_105 = 0x105, PCWRITE_106 = 0x106, PCSEEK_107 = 0x107 };
public enum PCFileMode { READONLY, WRITEONLY, READWRITE };
/// <summary>
/// Grab the filename over sio
/// Reads up to 255 chars or till it hits a null terminator
/// </summary>
/// <returns></returns>
private static string GetFilename() {
string fileName = "";
while ( true ) {
if ( serial.BytesToRead > 0 ) {
char inChar = (char)serial.ReadChar();
if ( inChar == 0 ) {
return fileName;
} else {
fileName += inChar;
}
if ( fileName.Length > 255 ) {
Utils.Error( "Filename overflow!" );
return "";
}
} // bytesToRead
} // while
} // local GetFileName
/// <summary>
/// To keep track of the stuff we've opened, closed, etc
/// </summary>
class PCFile {
public FileStream fileStream;
public string fileName;
public UInt32 handle;
public bool hasBeenClosed = false;
// Much cleaner handling this here than in the .NET FileStreams
public PCFileMode fileMode = PCFileMode.READWRITE;
public override string ToString() {
return $"PCFile: name={fileName}, handle={handle}, hasClosed={hasBeenClosed}, mode={fileMode}";
}
}
private static List<PCFile> activeFiles = new List<PCFile>();
/// <summary>
/// Dumps some info related to known/tracked files
/// </summary>
public static void DumpTrackedFiles() {
Log.WriteLine( "Tracked files: " );
for ( int i = 0; i < activeFiles.Count; i++ ) {
if ( activeFiles[ i ] != null ) Log.WriteLine( $"File {i} = {activeFiles[ i ]}" );
}
}
/// <summary>
/// Get a tracked file by filename,
/// excludes files we've closed.
/// </summary>
/// <param name="inFile">the path</param>
/// <returns>a <see cref="PCFile"/> reference</returns>
// Leaving these plain C style (vs linq) for readability
private static PCFile GetOpenFile( string inFile ) {
for ( int i = 0; i < activeFiles.Count; i++ ) {
// not recycling handles
if ( activeFiles[ i ].hasBeenClosed ) continue;
if ( activeFiles[ i ].fileName.ToLowerInvariant() == inFile.ToLowerInvariant() ) {
return activeFiles[ i ];
}
}
return null;
}
/// <summary>
/// Get a tracked file by handle
/// excludes files we've closed
/// </summary>
/// <param name="inHandle">a file opened via PCOpen/PCCreat</param>
/// <returns>a <see cref="PCFile"/> reference</returns>
private static PCFile GetOpenFile( UInt32 inHandle ) {
for ( int i = 0; i < activeFiles.Count; i++ ) {
// not recycling handles
if ( activeFiles[ i ].hasBeenClosed ) continue;
if ( activeFiles[ i ].handle == inHandle ) {
return activeFiles[ i ];
}
}
return null;
}
/// <summary>
/// Close the file stream and mark it closed
/// handles are consecutive and will not be recycled
/// </summary>
/// <param name="inHandle"></param>
/// <returns></returns>
private static bool ClosePCFile( UInt32 inHandle ) {
for ( int i = 0; i < activeFiles.Count; i++ ) {
// not recycling handles
if ( activeFiles[ i ].hasBeenClosed ) continue;
if ( activeFiles[ i ].handle == inHandle ) {
activeFiles[ i ].hasBeenClosed = true;
activeFiles[ i ].fileStream.Close();
activeFiles[ i ].fileStream.Dispose();
return true;
}
}
Log.WriteLine( $"No active file with handle {inHandle} to close!" );
return false;
}
/// <summary>
/// Connect a file handle, filename and file stream
/// </summary>
/// <param name="inFile">the file name</param>
/// <param name="inHandle">the handle</param>
/// <param name="inStream">the stream opened via PCCreate/PCOpen"/></param>
private static void TrackFile( string inFile, UInt32 inHandle, FileStream inStream, PCFileMode inMode ) {
// It's already tracked, open
if ( GetOpenFile( inFile ) != null ) return;
Log.WriteLine( $"Assigned file {inFile} with handle {inHandle}..." );
PCFile p = new PCFile() {
fileName = inFile,
handle = inHandle,
fileStream = inStream,
fileMode = inMode
};
activeFiles.Add( p );
}
/// <summary>
/// Grab a sequential handle, 1-indexed
/// </summary>
/// <returns>the next free handle</returns>
private static UInt32 NextHandle() {
return (UInt32)activeFiles.Count + 1;
}
/// <summary>
/// The monitor recieved 0x00, 'p' ...
/// Read the command ID bytes following that and process them.
/// </summary>
public static bool ReadCommand() {
Log.WriteLine( "Got PCDRV ..." );
// Wait till we get the PCDrv function code
while ( serial.BytesToRead == 0 ) { }
PCDrvCodes funcCode = (PCDrvCodes)TransferLogic.read32();
Log.WriteLine( "Got function code: " + funcCode );
// TODO: split these off into discrete functions?
// PCInit
if ( funcCode == PCDrvCodes.PCINIT_101 ) {
serial.Write( "OKAY" );
serial.Write( new byte[] { 0 }, 0, 1 );
return true;
}
// PCCreat
if ( funcCode == PCDrvCodes.PCCREAT_102 ) {
// tell unirom to start with the filename, etc
serial.Write( "OKAY" );
string fileName = GetFilename();
if ( fileName == "" ) {
return false;
}
UInt32 parameters = TransferLogic.read32();
bool isDir = ((parameters & 16) != 0);
Log.WriteLine( $"PCCreat( {fileName}, {parameters} )" );
PCFile pcFile = GetOpenFile( fileName );
if ( pcFile != null ) {
// We're already tracking this file, just return it's handle
Log.WriteLine( "File already open, handle=" + pcFile.handle );
serial.Write( "OKAY" );
serial.Write( BitConverter.GetBytes( pcFile.handle ), 0, 4 );
return true;
}
FileStream fStream;
try {
if ( isDir ) {
throw new Exception( "Directories are not supported!" );
} else {
if ( !File.Exists( fileName ) ) {
FileStream tempStream = File.Create( fileName );
tempStream.Flush();
tempStream.Close();
tempStream.Dispose();
} else {
Log.WriteLine( $"File {fileName} already exists, using that..." );
}
fStream = new FileStream( fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite );
}
// open it read/write until otherwise specified via PCOpen
UInt32 handle = NextHandle();
TrackFile( fileName, handle, fStream, PCFileMode.READWRITE );
serial.Write( "OKAY" );
serial.Write( BitConverter.GetBytes( handle ), 0, 4 );
return true;
} catch ( Exception e ) {
Log.WriteLine( $"Error creating file '{fileName}', ex={e}" );
serial.Write( "NOPE" );
return false;
}
} // PCCREAT_102
// PCOpen
if ( funcCode == PCDrvCodes.PCOPEN_103 ) {
serial.Write( "OKAY" );
string fileName = GetFilename();
if ( fileName == "" ) {
return false;
}
PCFileMode fileModeParams = (PCFileMode)TransferLogic.read32();
Log.WriteLine( $"PCOpen( {fileName}, {fileModeParams} )" );
PCFile f = GetOpenFile( fileName );
if ( f != null ) {
// just return the handle for this file...
if ( f.fileMode != fileModeParams ) {
Log.WriteLine( $"File {f.handle} already open, switching params to {fileModeParams}" );
f.fileMode = fileModeParams;
} else {
Log.WriteLine( "File already open, handle=" + f.handle );
}
serial.Write( "OKAY" );
serial.Write( BitConverter.GetBytes( f.handle ), 0, 4 );
return true;
}
if ( !File.Exists( fileName ) ) {
Log.WriteLine( "File doesn't exist!" );
goto nope;
}
FileStream fs = null;
try {
fs = File.Open( fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite );
} catch ( Exception e ) {
Log.WriteLine( $"Error opening file '{fileName}', ex={e}" );
goto nope;
}
UInt32 handle = NextHandle();
TrackFile( fileName, handle, fs, fileModeParams );
Log.WriteLine( "Returning file, handle=" + handle );
serial.Write( "OKAY" );
serial.Write( BitConverter.GetBytes( handle ), 0, 4 );
return true;
nope:;
Log.WriteLine( "Failed.." );
serial.Write( "NOPE" );
return false;
} // PCOPEN_103
// PCClose
if ( funcCode == PCDrvCodes.PCCLOSE_104 ) {
serial.Write( "OKAY" );
// unirom sends extra params to save kernel
// space by grouping similar commands together.
UInt32 handle = TransferLogic.read32();
UInt32 unused1 = TransferLogic.read32();
UInt32 unused2 = TransferLogic.read32();
Log.WriteLine( $"PCClose( {handle} ) unusedParams: {unused1},{unused2}" );
PCFile f = GetOpenFile( handle );
try {
if ( f == null ) {
Log.WriteLine( "No such file... great success!" );
serial.Write( "OKAY" ); // v0
serial.Write( BitConverter.GetBytes( 0 ), 0, 4 ); // v1
return true;
} else {
Log.WriteLine( $"Closing file {f.fileName} with handle {f.handle}..." );
serial.Write( "OKAY" ); // v0
serial.Write( BitConverter.GetBytes( f.handle ), 0, 4 ); // v1 let the garbage collector deal with it
ClosePCFile( f.handle );
return true;
}
} catch ( Exception e ) {
Log.WriteLine( "Error closing file..." + e );
serial.Write( "NOPE" ); // v0
// don't need to send v1
return false;
}
} // PCCLOSE_104
// PCRead
if ( funcCode == PCDrvCodes.PCREAD_105 ) {
serial.Write( "OKAY" );
// unirom sends extra params to save kernel
// space by grouping similar commands together,
// so 'memaddr' is for debugging only.
// PCRead() takes (handle, buff*, len )
// but interally passes it to _SN_Read as
// ( 0, handle, len, buff* ), essentially
// shuffling regs A0,A1,A2 into A1,A3,A2.
// or just ( handle, len, buff* ). lol.
UInt32 handle = TransferLogic.read32();
int inLength = (int)TransferLogic.read32();
UInt32 memaddr = TransferLogic.read32(); // not used, debugging only
//Log.WriteLine( $"PCRead( {handle}, len={inLength}, dbg=0x{memaddr.ToString("X")} )" );
PCFile pcFile = GetOpenFile( handle );
Log.WriteLine( $"PCRead( {handle}, len=0x{inLength.ToString( "X" )} ); MemAddr=0x{memaddr.ToString( "X" )}, File={pcFile}" );
if ( pcFile == null ) {
Log.WriteLine( $"No file with handle 0x{handle.ToString( "X" )}, returning!" );
serial.Write( "NOPE" ); // v0
// don't need to send v1
return false;
} else {
Log.WriteLine( "Reading file " + pcFile.fileName );
}
long streamLength = 0;
try {
FileStream fs = pcFile.fileStream;
streamLength = fs.Length;
byte[] bytes = new byte[ inLength ];
int bytesRead = fs.Read( bytes, 0, inLength );
if ( bytesRead <= 0 ) {
//throw new Exception( "Read 0 bytes from the file.." );
Log.WriteLine( "Warning - no bytes were read from the file - returning zeros..." );
}
// if we returned fewer bytes than requested, no biggie, the byte array is already set
serial.Write( "OKAY" ); // v0
serial.Write( BitConverter.GetBytes( bytes.Length ), 0, 4 ); // v1
// Then
UInt32 check = TransferLogic.CalculateChecksum( bytes, false );
serial.Write( BitConverter.GetBytes( check ), 0, 4 );
TransferLogic.WriteBytes( bytes, false, true );
// again the weird order reflects a desire to save space within the psx kernel
// and reuse some functions
} catch ( Exception e ) {
Log.WriteLine( $"Error reading file {pcFile.fileName} at pos={pcFile.fileStream.Position}, streamLength={streamLength} e={e}" );
serial.Write( "NOPE" );
return false;
}
} // PCREAD_105
// PCWrite
if ( funcCode == PCDrvCodes.PCWRITE_106 ) {
serial.Write( "OKAY" );
// PCWrite() takes (handle, buff*, len )
// but interally passes it to _SN_Write as
// ( 0, handle, len, buff* ), essentially
// shuffling regs A0,A1,A2 into A1,A3,A2.
// or just ( handle, len, buff* ). lol.
UInt32 handle = TransferLogic.read32();
int inLength = (int)TransferLogic.read32();
UInt32 memaddr = TransferLogic.read32(); // not used, debugging only
PCFile pcFile = GetOpenFile( handle );
if ( pcFile == null ) {
Log.WriteLine( $"No file with handle 0x{handle.ToString( "X" )}, returning!" );
serial.Write( "NOPE" ); // v0
// don't need to send v1
return false;
}
Log.WriteLine( $"PCWrite( {handle}, len={inLength} ); fileName={pcFile.fileName} SourceAddr={memaddr.ToString( "X" )}, File={pcFile}" );
if ( pcFile.fileMode == PCFileMode.READONLY ) {
Log.WriteLine( "Error: File is readonly!" );
serial.Write( "NOPE" );
return false;
}
serial.Write( "OKAY" );
try {
FileStream fs = pcFile.fileStream;
byte[] bytes = new byte[ inLength ];
bool didRead = TransferLogic.ReadBytes_Raw( (UInt32)inLength, bytes );
if ( !didRead ) {
throw new Exception( "there was an error reading the stream from the psx!" );
}
Log.WriteLine( $"Read {inLength} bytes, flushing to {pcFile.fileName}..." );
fs.Write( bytes, 0, inLength );
fs.Flush( true );
serial.Write( "OKAY" ); // v0
serial.Write( BitConverter.GetBytes( bytes.Length ), 0, 4 ); // v1
// again the weird order reflects a desire to save space within the psx kernel
// and reuse some functions
} catch ( Exception e ) {
Log.WriteLine( $"Error writing file {pcFile.fileName}, streamLength={inLength} e={e}" );
serial.Write( "NOPE" );
return false;
}
return true;
} //PCWRITE 106
if ( funcCode == PCDrvCodes.PCSEEK_107 ) {
serial.Write( "OKAY" );
UInt32 handle = TransferLogic.read32();
int seekPos = (int)TransferLogic.read32();
SeekOrigin seekOrigin = (SeekOrigin)TransferLogic.read32();
PCFile pcFile = GetOpenFile( handle );
string fileName = pcFile != null ? pcFile.fileName : "";
Log.WriteLine( $"PCSeek file {handle} to {seekPos}, type={seekOrigin}, fileName={fileName}" );
if ( pcFile == null ) {
Log.WriteLine( "Error: There is no file with handle 0x" + handle.ToString( "X" ) );
serial.Write( "NOPE" );
return false;
}
// Let's actually open the file and seek it to see if we bump into any issues
try {
FileStream fs = pcFile.fileStream;
//fs.Seek( pcFile.filePointer, pcFile.seekMode );
fs.Seek( seekPos, seekOrigin );
Log.WriteLine( "Seeked position " + fs.Position );
serial.Write( "OKAY" );
serial.Write( BitConverter.GetBytes( fs.Position ), 0, 4 );
} catch ( System.Exception e ) {
Log.WriteLine( $"Exception when seeking file {handle}, e={e}" );
serial.Write( "NOPE" );
return false;
}
} //PCSEEK_107
return true;
}
}