aboutsummaryrefslogtreecommitdiff
path: root/SrcShared/EmROMTransfer.cpp
blob: feb0c5aad48bcd08d0a58a234c5e216850bb1865 (plain)
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
/* -*- mode: C++; tab-width: 4 -*- */
/* ===================================================================== *\
	Copyright (c) 1999-2001 Palm, Inc. or its subsidiaries.
	All rights reserved.

	This file is part of the Palm OS Emulator.

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.
\* ===================================================================== */

#include "EmCommon.h"
#include "EmROMTransfer.h"

#include "EmDlg.h"					// DoTransferROM
#include "EmStreamFile.h"			// EmStreamFile
#include "EmTransport.h"			// EmTransport
#include "EmTransportSerial.h"		// EmTransportSerial
#include "ErrorHandling.h"			// Errors::ThrowIfError
#include "Platform.h"				// Platform::GetMilliseconds
#include "Strings.r.h"				// kStr_Waiting


/*
	Notes on the XModem/YModem implementation used in this file:

	Basic XModem is dead simple:

		1. Sender waits for NAK from receiver.
		2. Sender sends SOH, block#, complement of block#
		3. Sender sends 128 bytes of data.
		3. Sender sends one-byte sum of those 128 bytes as checksum.
		4. Receiver sends ACK or NAK.
		5. If NAK, go back to step 2.
		6. If ACK, increment block# and go back to step 2.
		7. At end of file, sender sends EOT.
		8. Receiver acknowledges EOT with ACK.

	There is an XModem variant called Ymodem that sends an additional block at
	the start of the protocol - this block contains the file name and size,
	among other things.
*/


const int	kXModemBlockSize	= 1024;	// 1k-XModem variant
const int	kXModemBufferSize	= 1029;	// 1k-XModem variant
const char	kXModemSoh			= 1;	// start of block header
const char	kXModemEof			= 4;	// end of file signal
const char	kXModemAck			= 6;	// acknowledge
const char	kXModemNak			= 21;	// negative acknowledge (resend packet)
const char	kXModemCan			= 24;	// cancel
const char	kXModemNakCrc		= 'C';	// used instead of NAK for initial block


enum
{
	kWaitingForTransport,	// Waiting for transprt to come online
	kOpen					// Transport ready, first NakCrc sent
};


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::ROMTransfer
 *
 * DESCRIPTION:	Handle the entire process of downloading a ROM, from
 *				asking them for port/baud, to showing the progress
 *				dialog, to downloading the ROM, to saving it, and to
 *				handling the Cancel button.
 *
 * PARAMETERS:	None
 *
 * RETURNED:	Nothing
 *
 ***********************************************************************/

void EmROMTransfer::ROMTransfer (void)
{
	// Run the dialog that sets up the download process.

	EmTransport::Config*	cfg;
	if (EmDlg::DoROMTransferQuery (cfg) == kDlgItemCancel)
		return;

	EmAssert (cfg != NULL);

	EmTransport*	oldTransport = NULL;
	EmTransport*	transport = NULL;

	try
	{
		// Close whatever might be on the selected port already.

		oldTransport = cfg->GetTransport ();
		if (oldTransport)
			Errors::ThrowIfError (oldTransport->Close ());

		// Open the port we want to use for downloading the ROM.

		transport = cfg->NewTransport ();
		Errors::ThrowIfError (transport->Open());

		// Create the ROM transfer object with this transport.

		EmROMTransfer	transferer (transport);

		// Run the progress window.

		EmDlgItemID	result = EmDlg::DoROMTransferProgress (transferer);

		if (result != kDlgItemCancel && transferer.HaveEntireROM ())
		{
			// Ask what name to save the ROM image to.

			EmFileRef		ref;
			EmFileTypeList	typeList (1, kFileTypeROM);
			if (EmDlg::DoPutFile (ref, "", "", typeList, "") == kDlgItemOK)
			{
				// Save the ROM image.

				EmStreamFile	stream (ref, kCreateOrEraseForUpdate,
										kFileCreatorEmulator, kFileTypeROM);

				stream.PutBytes (transferer.Data (), transferer.Size ());
			}
		}

		ResetSerialPort (oldTransport, transport);
	}
	catch (ErrCode errCode)
	{
		ResetSerialPort (oldTransport, transport);
		Errors::ReportIfError (kStr_CmdTransferROM, errCode, 0, false);
	}
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer c'tor
 *
 * DESCRIPTION:	Create the object.  Initialize all data members.
 *
 * PARAMETERS:	transport - transport object for low-level communications.
 *					We do not own it; the client deletes it.
 *
 * RETURNED:	Nothing
 *
 ***********************************************************************/

EmROMTransfer::EmROMTransfer (EmTransport* transport) :
	fState (kWaitingForTransport),
	fTransport (transport),
	fROMSize (0),
	fROMRead (0),
	fROMBuffer (),
	fHaveFirstBlock (false),
	fHaveLastBlock (false),
	fLastValidBlock ((uint8) -1),
	fProgressCaption (-1),
	fProgressValue (-1),
	fProgressMax (-1),
	fProgressLastUpdate (0),
//	fTempBuffer (),
	fTempBufferOffset (0)
{
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer d'tor
 *
 * DESCRIPTION:	Destroy the object.  Delete all data members.
 *
 * PARAMETERS:	None
 *
 * RETURNED:	Nothing
 *
 ***********************************************************************/

EmROMTransfer::~EmROMTransfer (void)
{
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::Continue
 *
 * DESCRIPTION:	Continually called to incrementally download a ROM.
 *
 * PARAMETERS:	dlg - reference to the progress dialog
 *
 * RETURNED:	True to continue downloading, false if done.
 *
 ***********************************************************************/

Bool EmROMTransfer::Continue (EmDlgRef dlg)
{
	switch (fState)
	{
		case kWaitingForTransport:
			return this->WaitForTransport (dlg);

		case kOpen:
			return this->ReadSomeData (dlg);
	}

	return false;	// Don't continue
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::Abort
 *
 * DESCRIPTION:	Abort the download.  Called when the user clicks on
 *				the Cancel button.
 *
 * PARAMETERS:	dlg - reference to the progress dialog
 *
 * RETURNED:	Nothing
 *
 ***********************************************************************/

void EmROMTransfer::Abort (EmDlgRef)
{
	// Nothing to do.  All memory is reclaimed in the destructor, and
	// the transport is closed and called by EmROMTransfer::ROMTransfer.
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::Size
 *
 * DESCRIPTION:	Return the size of the ROM.  Valid only if the ROM has
 *				been successfully downloaded (that is, Continue had
 *				been called until it finally returned false).
 *
 * PARAMETERS:	None
 *
 * RETURNED:	Size of the ROM in bytes.
 *
 ***********************************************************************/

long EmROMTransfer::Size (void)
{
	return fROMSize;
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::Data
 *
 * DESCRIPTION:	Return a pointer to the ROM.  Valid only if the ROM has
 *				been successfully downloaded (that is, Continue had
 *				been called until it finally returned false).
 *
 * PARAMETERS:	None
 *
 * RETURNED:	Pointer to the ROM image.
 *
 ***********************************************************************/

void* EmROMTransfer::Data (void)
{
	return fROMBuffer.Get();
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::WaitForTransport
 *
 * DESCRIPTION:	Called while waiting for the transport object to
 *				indicate that the transport is ready for sending
 *				data.  Until it is, we idle the progress indicator.
 *				When the transport is ready, prepare our state
 *				variables for downloading the ROM.
 *
 * PARAMETERS:	dlg - reference to the progress dialog
 *
 * RETURNED:	True to indicate that the Continue function should
 *				still be called.
 *
 ***********************************************************************/

Bool EmROMTransfer::WaitForTransport (EmDlgRef dlg)
{
	// Update the progress indicator.

	this->UpdateProgress (dlg, kStr_Waiting, 0, 0);

	if (fTransport->CanRead ())
	{
		// Start the transfer by sending kXModemNakCrc.

		this->SendByte (kXModemNakCrc);

		// Initialize our download state

		fROMSize			= 0;
		fROMRead			= 0;
		fHaveFirstBlock		= false;
		fHaveLastBlock		= false;
		fLastValidBlock		= (uint8) -1;
		fTimeoutBase		= Platform::GetMilliseconds ();
		fTempBufferOffset	= 0;

		// Switch over to the engine state

		fState = kOpen;
	}

	return true;
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::ReadSomeData
 *
 * DESCRIPTION:	Called to incrementally download a ROM.  Reads data
 *				until we have enough for an XModem packet.  Examines
 *				the packet. If valid, adds it to our full ROM image and
 *				acks the packet.  If invalid, requests a resend.
 *
 * PARAMETERS:	dlg - reference to the progress dialog
 *
 * RETURNED:	True to indicate that the Continue function should
 *				still be called.  False if the entire ROM has now
 *				been downloaded.
 *
 ***********************************************************************/

Bool EmROMTransfer::ReadSomeData (EmDlgRef dlg)
{
	this->BufferPendingData ();

	uint8	ackChar;

	// If we have an entire new valid block by now, process it.

	if (this->HaveValidBlock ())
	{
		ackChar = this->HandleNewBlock ();
	}

	// EOF signal.

	else if (fTempBufferOffset > 0 && fTempBuffer[0] == kXModemEof)
	{
		ackChar = kXModemAck;
		fHaveLastBlock = true;
	}

	// Check for timeouts.

	else
	{
		// Returns:
		//
		//		kXModemNak		If timeout in middle of transfer
		//		kXModemNakCrc	If timeout and haven't started transfer, yet
		//		0				If no timeout

		ackChar = this->CheckForTimeouts ();
	}

	// Send the ack char and reset our timeout counter.

	if (ackChar)
	{
		this->SendByte (ackChar);
	}

	// Update the progress indicator.

	if (fHaveFirstBlock)
	{
		this->UpdateProgress (dlg, kStr_Transferring, fROMRead, fROMSize);
	}

	return !this->HaveEntireROM ();
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::HandleNewBlock
 *
 * DESCRIPTION:	A new ROM block has been downloaded and verified as
 *				valid.  Add it to our incrementally built ROM image
 *				and prepare for the next block.
 *
 * PARAMETERS:	None
 *
 * RETURNED:	The character with which to acknowledge the packet.
 *
 ***********************************************************************/

uint8 EmROMTransfer::HandleNewBlock (void)
{
	// If this is the first block, skip past the "file name" and
	// get the file (ROM) size.  Allocate a buffer to hold the image.

	uint8	receivedBlock = fTempBuffer[1];

	EmAssert (
		!fHaveFirstBlock ||
		fLastValidBlock == receivedBlock ||
		fLastValidBlock == (uint8) (receivedBlock - 1));

	if (!fHaveFirstBlock)
	{
		char* p = (char*) &fTempBuffer[3];
		p += strlen (p) + 1;
		fROMSize = atoi (p);
		fROMBuffer.Adopt ((char*) Platform::AllocateMemory (fROMSize));

		fHaveFirstBlock = true;
	}

	// Got a good block of data. Copy it into the ROM image.

	else if (fLastValidBlock != receivedBlock)
	{
		memcpy (fROMBuffer.Get () + fROMRead, &fTempBuffer[3], kXModemBlockSize);
		fROMRead += kXModemBlockSize;

#ifndef NDEBUG
		int	blocksRead = fROMRead / kXModemBlockSize;
		EmAssert ((blocksRead % 256) == receivedBlock);
		EmAssert (fROMRead <= fROMSize);
#endif
	}

	fLastValidBlock = receivedBlock;

	// Prepare the read buffer for the next block of data.

	fTempBufferOffset = 0;

	// Acknowledge this packet as good.

	return kXModemAck;
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::CheckForTimeouts
 *
 * DESCRIPTION:	Check to see if a certain amount of time has elapsed
 *				since we received a valid packet.  If it has, indicate
 *				that the sender resend the previous packet.
 *
 * PARAMETERS:	ackChar - the current ackChar the caller is considering
 *					sending back to the client.
 *
 * RETURNED:	The ackChar to *really* send back to the client.  If
 *				the timeout hasn't occurred, just send back what the
 *				caller sent us.  If it has timed out, return an ackChar
 *				based on whether we're in the middle of a download or
 *				just starting up.
 *
 ***********************************************************************/

uint8 EmROMTransfer::CheckForTimeouts (void)
{
	if (Platform::GetMilliseconds () - fTimeoutBase > kTimeout)
	{
		// We haven't received a good packet in some time.  Probably a dropped
		// character, or we're just starting the protocol.  If just starting, nak
		// with kXModemNakCrc 'C', else just use regular nak '\025'.

		fTempBufferOffset = 0;
		return fROMRead > 0 ? kXModemNak : kXModemNakCrc;
	}
	
	return 0;	// No timeout
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::BufferPendingData
 *
 * DESCRIPTION:	Transfer any data in the transport's buffer into our
 *				own private little buffer used to hold a single packet.
 *
 * PARAMETERS:	None
 *
 * RETURNED:	Nothing
 *
 ***********************************************************************/

void EmROMTransfer::BufferPendingData (void)
{
	// Get some data.  Read as much as we can, but don't overflow
	// our local buffer.

	long	bytesInPort = fTransport->BytesInBuffer (kXModemBufferSize);

	if (bytesInPort > 0)
	{
		long	bytesToRead = min (bytesInPort, kBufferSize - fTempBufferOffset);
		ErrCode	err = fTransport->Read (bytesToRead, &fTempBuffer[fTempBufferOffset]);
		Errors::ThrowIfError (err);
		fTempBufferOffset += bytesToRead;
	}
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::HaveValidBlock
 *
 * DESCRIPTION:	Check to see if our little packet buffer now contains
 *				a full and valid packet
 *
 * PARAMETERS:	None
 *
 * RETURNED:	True if so.
 *
 ***********************************************************************/

Bool EmROMTransfer::HaveValidBlock (void)
{
	// Check to see whether we have enough data for a full block, and
	// that the block is valid, and it's the block number we're expecting

	Bool	haveEnoughData = fTempBufferOffset >= kXModemBufferSize;
	Bool	checksumValid = haveEnoughData && this->ValidXModemBlock (fTempBuffer);

	return haveEnoughData && checksumValid;
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::HaveEntireROM
 *
 * DESCRIPTION:	Return whether or now we have downloaded the entire ROM.
 *
 * PARAMETERS:	None
 *
 * RETURNED:	True if so.
 *
 ***********************************************************************/

Bool EmROMTransfer::HaveEntireROM (void)
{
	return fHaveLastBlock;
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::ValidXModemBlock
 *
 * DESCRIPTION:	Validate a packet by doing a checksum and comparing it
 *				to the checksum that came with the packet.
 *
 * PARAMETERS:	block - the packet to checksum
 *
 * RETURNED:	True if valid.
 *
 ***********************************************************************/

Bool EmROMTransfer::ValidXModemBlock (const uint8* block)
{
	/*
	 * XModem-1k block layout is as follows:
	 *
	 * +--------------+
	 * | SOH = '\002' |
	 * +--------------+
	 * | Block number |
	 * +--------------+
	 * | Block compl. | Complement of block number
	 * +--------------+
	 * | 1024 bytes   |
	 * | of data	  |
	 * .	  . 	  .
	 * .	  . 	  .
	 * +--------------+
	 * | CRC hi byte  | CRC-16 of preceding 1024 bytes of data,
	 * +--------------+ plus two zero bytes
	 * | CRC lo byte  |
	 * +--------------+
	 */

	if (block[0] != kXModemSoh)
	{
		return false;
	}

	if ((block[1] ^ block[2]) != 0xFF)
	{
		return false;
	}

	uint16	calculatedCRC = Crc16CalcBlock ((void*) &block[3], kXModemBlockSize, 0);

	uint8	zeros[2] = {0, 0};
	calculatedCRC = Crc16CalcBlock (zeros, 2, calculatedCRC);

	uint16	xmittedCRC = (((uint16) (block[3 + kXModemBlockSize])) << 8) |
						block[3 + kXModemBlockSize + 1];

	return xmittedCRC == calculatedCRC;
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::SendByte
 *
 * DESCRIPTION:	Send a single byte to the client.
 *
 * PARAMETERS:	byte - the byte to send.
 *
 * RETURNED:	Nothing
 *
 ***********************************************************************/

#define CORRUPT_SENDS 0

#if CORRUPT_SENDS
static UInt32 PrvRange (UInt32 maxValue)
{
	static int initialized;
	if (!initialized)
	{
		initialized = true;
		srand (1);
	}

	return (rand () * maxValue) / (1UL + RAND_MAX);
}
#endif


void EmROMTransfer::SendByte (uint8 byte)
{
#if CORRUPT_SENDS
	// Drop a character.
	if (::PrvRange (100) < 5)
	{
		LogAppendMsg ("CORRUPTOR: dropping a character");
		fTimeoutBase = Platform::GetMilliseconds ();
		return;
	}

	// Corrupt a character.
	if (::PrvRange (100) < 5)
	{
		LogAppendMsg ("CORRUPTOR: changing a character");
		byte++;
	}
#endif

	long	len = 1;
	/*ErrCode	err =*/ fTransport->Write (len, &byte);

	// Any errors will just cause the retry/timeout mechanisms to kick in.
//	Errors::ThrowIfError (err);

	fTimeoutBase = Platform::GetMilliseconds ();
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::UpdateProgress
 *
 * DESCRIPTION:	Update the progress bar according to whether or not we
 *				have started the download process and, if so, how far
 *				along we are.  The progress information is updated only
 *				incrementally and only when it's been changed.
 *
 * PARAMETERS:	dlg - reference to progress dialog.
 *				caption - StrID of string for caption.
 *				value - number indicating how much of the ROM has been
 *					downloaded.
 *				max - number indicating how large the ROM image is.
 *
 * RETURNED:	Nothing
 *
 ***********************************************************************/

void EmROMTransfer::UpdateProgress (EmDlgRef dlg, long caption, long value, long maxValue)
{
	if (fProgressCaption != caption)
	{
		fProgressCaption = caption;
		EmDlg::SetItemText (dlg, kDlgItemDlpMessage, caption);
	}

	uint32	now = Platform::GetMilliseconds ();
	uint32	delta = now - fProgressLastUpdate;
	bool	timeout = delta > kProgressTimeout;

	if (timeout)
	{
		// Divide values by 1024, since the Windows control deals only
		// with 16-bit values.  (This is fixed in later versions of
		// the progress control, but those aren't shipped with stock
		// Windows installations, yet.)

		if (fProgressMax != maxValue)
		{
			fProgressMax = maxValue;
			EmDlg::SetItemMax (dlg, kDlgItemDlpProgress, max (1L, maxValue / 1024));
		}

		if (fProgressValue != value)
		{
			fProgressValue = value;
			EmDlg::SetItemValue (dlg, kDlgItemDlpProgress, value / 1024);
		}

		fProgressLastUpdate = now;
	}
}


/***********************************************************************
 *
 * FUNCTION:	EmROMTransfer::ResetSerialPort
 *
 * DESCRIPTION:	We're done downloading the ROM (either successfully, or
 *				after an error or after the user Cancels).  Close up
 *				the transport object we were using and, if needed,
 *				restore the old transport object.
 *
 * PARAMETERS:	oldTransport - the transport object that was using the
 *					connection medium before we came along and usurped
 *					it.  Usually a serial port.
 *
 *				curTransport - the transport object used to download
 *					the ROM and that now needs to be closed.
 *
 * RETURNED:	Nothing
 *
 ***********************************************************************/

void EmROMTransfer::ResetSerialPort (EmTransport* oldTransport, EmTransport* curTransport)
{
	// Close our stream.

	if (curTransport)
	{
		curTransport->Close ();
		delete curTransport;
	}

	// Reopen the stream used before we got in the way.

	if (oldTransport)
	{
		oldTransport->Open ();
	}
}