forked from JonathanDotCel/NOTPSXSerial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bridge.cs
370 lines (265 loc) · 12.1 KB
/
Bridge.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// GDB TCP->SIO bridge for Unirom 8
//
// NOTE!
//
// While all of the basic debug functionality is present, the GDB
// bridge is still very much a work in progress!
//
using System;
using System.Text;
using System.IO.Ports;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public enum MonitorMode {
// serial is monitored for printf, pcdrv, halt events, etc
MONITOR_OR_PCDRV,
// as MONITOR_OR_PCDRV, but also forwarded to a socket
SERIALBRIDGE,
// as MONITOR_OR_PCDRV, but for GDB
GDB
};
/// <summary>
/// Monitor data over the target connection and optionally
/// listens on a socket in bridge mode or gdb mode
/// </summary>
public class Bridge {
// TODO: could do to document some of these a bit better.
public static bool enabled = false;
public static TargetDataPort serial => Program.activeSerial;
public static Socket socket;
// default monitor mode, no external socket/gdb
public static MonitorMode activeBridgeMode = MonitorMode.MONITOR_OR_PCDRV;
public const int socketBufferSize = 512;
public static byte[] socketBuffer = new byte[ socketBufferSize ];
public static StringBuilder sb = new StringBuilder();
public static string socketString; // oh boy, this will be nuts on the GC
public static Socket replySocket;
private static IPEndPoint localEndpoint;
public static void Init( MonitorMode inMode, UInt32 localPort, string localIP = "" ) {
activeBridgeMode = inMode;
InitListenServer( localPort, localIP );
if ( inMode == MonitorMode.GDB ) {
GDBServer.Init();
Log.WriteLine( $"Monitoring psx and accepting GDB connections on {localIP}:{localPort}" );
}
// Shared function
MonitorSerial();
}
// Called when a connection has been accepted
public static void AcceptCallback( IAsyncResult result ) {
Socket whichSocket = (Socket)result.AsyncState;
Socket newSocket = socket.EndAccept( result );
Log.WriteLine( "Remote connection to local socket accepted: " + newSocket.LocalEndPoint );
replySocket = newSocket;
// on the new socket or it'll moan. I don't like this setup.
newSocket.BeginReceive( socketBuffer, 0, socketBufferSize, 0, new AsyncCallback( ReceiveCallback ), newSocket );
}
/// <summary>
/// Received data over a socket:
/// - in bridge mode
/// - from GDB
/// </summary>
/// <param name="ar">A <see cref="Socket" var./></param>
private static void ReceiveCallback( IAsyncResult ar ) {
//Console.WriteLine( "SOCKET: RCB " + ar.AsyncState );
Socket recvSocket = (Socket)ar.AsyncState;
//Console.WriteLine( "SOCKET RCB 1 " + recvSocket );
int numBytesRead = recvSocket.EndReceive( ar, out SocketError errorCode );
if( errorCode != SocketError.Success ) {
if(errorCode == SocketError.ConnectionReset ) {
Log.WriteLine( "Remote connection closed, restarting listen server", LogType.Warning );
Log.WriteLine( "CTRL-C to exit" );
RestartListenServer( );
}
Log.WriteLine( "errorCode: " + errorCode.ToString(), LogType.Debug );
return;
}
//Console.WriteLine( "SOCKET RCB 2 " + numBytesRead );
if ( numBytesRead > 0 ) {
// copy the bytes (from the buffer specificed in BeginRecieve), into the stringbuilder
string thisPacket = ASCIIEncoding.ASCII.GetString( socketBuffer, 0, numBytesRead );
sb.Append( thisPacket );
socketString = sb.ToString();
//Console.WriteLine( "\rSOCKET: rec: " + thisPacket );
if ( socketString.IndexOf( "<EOF>" ) > -1 ) {
//Console.WriteLine( "Read {0} bytes, done!: {1}", numBytesRead, socketString );
} else {
if ( activeBridgeMode == MonitorMode.GDB ) {
GDBServer.ProcessData( socketString );
sb.Clear();
} else
if ( activeBridgeMode == MonitorMode.SERIALBRIDGE ) {
// To echo it back:
//Send( recvSocket, thisPacket );
// Send the incoming socket data over sio
TransferLogic.activeSerial.Write( socketBuffer, 0, numBytesRead );
}
//Console.WriteLine( "SOCKET: Grabbing more data" );
try {
recvSocket.BeginReceive( socketBuffer, 0, socketBufferSize, 0, new AsyncCallback( ReceiveCallback ), recvSocket );
} catch ( Exception ex ) {
Log.WriteLine( "SOCKET: RCB EXCEPTION: " + ex.Message, LogType.Error );
}
}
} else {
//Console.WriteLine( "Read 0 bytes" );
RestartListenServer( );
}
}
public static void RestartListenServer( ) {
Log.WriteLine( "Restarting listen server" );
socket.Close();
StartListenServer( );
if ( activeBridgeMode == MonitorMode.GDB ) {
GDBServer.ResetConnection();
}
}
public static void StartListenServer( ) {
socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
socket.Bind( localEndpoint );
socket.Listen( 2 );
socket.BeginAccept( new AsyncCallback( AcceptCallback ), socket );
}
public static void Send( string inData ) {
Send( replySocket, inData );
}
public static void Send( Socket inSocket, string inData ) {
// TODO: we could probs check if there's
// any sort of connection long before it
// reaches this point.
if ( inSocket == null ) {
return;
}
byte[] bytes = ASCIIEncoding.ASCII.GetBytes( inData );
inSocket.BeginSend( bytes, 0, bytes.Length, 0, out SocketError errorCode, new AsyncCallback( SendCallback ), inSocket );
if ( errorCode != SocketError.Success ) {
if ( errorCode == SocketError.ConnectionReset ) {
Log.WriteLine( "Error sending, restarting listen server", LogType.Warning );
Log.WriteLine( "CTRL-C to exit" );
RestartListenServer();
}
Log.WriteLine( "errorCode: " + errorCode.ToString(), LogType.Debug );
return;
}
}
// Send() succeeded
private static void SendCallback( IAsyncResult ar ) {
Socket whichSocket = (Socket)ar.AsyncState;
int bytesSent = whichSocket.EndSend( ar );
}
//
// Listens on the given IP and port
// Shared by bridge and gdb modes
//
private static void InitListenServer( UInt32 inPort, string localIP = "" ) {
IPAddress ip;
if ( string.IsNullOrEmpty( localIP ) ) {
ip = IPAddress.Parse( "127.0.0.1" );
} else {
Log.WriteLine( "Binding IP " + localIP );
ip = IPAddress.Parse( localIP );
}
Log.WriteLine( "Opening a listen server on " + ip + ":" + inPort );
localEndpoint = new IPEndPoint( ip, (int)inPort );
StartListenServer();
}
/// <summary>
/// Monitor serial data from the psx
///
/// 1: printfs() over serial
/// 2: PCDRV
/// 3: `HALT` (break/exception/etc)
///
/// + In bridge mode:
/// 4: forwards serial traffic over a TCP socket (because mono hasn't implemented SIO callbacks)
///
/// + In GDB mode:
/// 5: forwards HALT etc to GDB
///
/// </summary>
// TODO: move somewhere appropriate
public static void MonitorSerial() {
const int ESCAPECHAR = 0x00;
// Old mode (unescaped): when this reads HLTD, kdebug has halted the playstation.
char[] last4ResponseChars = new char[] { 'x', 'x', 'x', 'x' };
// 10kb buffer?
byte[] responseBytes = new byte[ 2048 * 10 ];
int bytesInBuffer = 0;
bool lastByteWasEscaped = false;
while ( true ) {
// Ensure that socket threads aren't trying
// to e.g. read/write memory at the same time
lock( SerialTarget.serialLock ) {
while ( serial.BytesToRead > 0 && bytesInBuffer < responseBytes.Length ) {
int thisByte = (byte)serial.ReadByte();
bool thisByteIsEscapeChar = (thisByte == ESCAPECHAR);
//Console.WriteLine( $"Got val {thisByte.ToString( "X" )} escaped={thisByteIsEscapeChar} lastWasEscapeChar={lastByteWasEscaped}" );
// The byte before this one was an escape sequence...
if ( lastByteWasEscaped ) {
// 2x escape cars = just print that char
if ( thisByteIsEscapeChar ) {
// a properly escaped doublet can go in the buffer.
responseBytes[ bytesInBuffer++ ] = ESCAPECHAR;
Log.Write( ((char)thisByte).ToString(), LogType.Stream );
} else {
if ( thisByte == 'p' ) {
PCDrv.ReadCommand();
}
}
// whether we're printing an escaped char or acting on
// a sequence, reset things back to normal.
lastByteWasEscaped = false;
continue; // next inner loop
}
// Any non-escape char: print it, dump it, send it, etc
if ( !thisByteIsEscapeChar ) {
responseBytes[ bytesInBuffer++ ] = (byte)thisByte;
Log.Write( ((char)thisByte).ToString(), LogType.Stream );
// TODO: remove this unescaped method after a few versions
// Clunky way to do it, but there's no unboxing or reallocation
last4ResponseChars[ 0 ] = last4ResponseChars[ 1 ];
last4ResponseChars[ 1 ] = last4ResponseChars[ 2 ];
last4ResponseChars[ 2 ] = last4ResponseChars[ 3 ];
last4ResponseChars[ 3 ] = (char)thisByte;
if (
last4ResponseChars[ 0 ] == 'H' && last4ResponseChars[ 1 ] == 'L'
&& last4ResponseChars[ 2 ] == 'T' && last4ResponseChars[ 3 ] == 'D'
) {
Log.WriteLine( "PSX may have halted (<8.0.I)!", LogType.Warning );
CPU.GetRegs();
CPU.DumpRegs();
if ( CPU.IsStepBreakSet ) {
CPU.StepBreakCallback();
}
GDBServer.SetHaltStateInternal( CPU.HaltState.HALT, true );
}
}
lastByteWasEscaped = thisByteIsEscapeChar;
} // bytestoread > 0
if ( !GDBServer.IsEnabled ) {
// Send the buffer back in a big chunk if we're not waiting
// on an escaped byte resolving
if ( bytesInBuffer > 0 && !lastByteWasEscaped ) {
// send it baaahk
if ( replySocket != null ) {
replySocket.Send( responseBytes, 0, bytesInBuffer, SocketFlags.None, out SocketError errorCode );
}
bytesInBuffer = 0;
}
if ( Console.KeyAvailable ) {
ConsoleKeyInfo keyVal = Console.ReadKey( true );
serial.Write( new byte[] { (byte)keyVal.KeyChar }, 0, 1 );
Log.Write( (keyVal.KeyChar).ToString(), LogType.Stream );
}
}
} // serial lock object
// Yield the thread
Thread.Sleep( 1 );
} // while
}
}