File: EmPatchMgr.cpp

package info (click to toggle)
pose 3.5-1
  • links: PTS
  • area: contrib
  • in suites: woody
  • size: 13,108 kB
  • ctags: 29,485
  • sloc: cpp: 93,990; ansic: 62,838; sh: 1,970; perl: 1,891; python: 1,242; makefile: 616
file content (1203 lines) | stat: -rw-r--r-- 30,233 bytes parent folder | download | duplicates (3)
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
/* -*- mode: C++; tab-width: 4 -*- */
/* ===================================================================== *\
	Copyright (c) 1998-2001 Palm, Inc. or its subsidiaries.
	Copyright (c) 2001 PocketPyro, Inc.
	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 "EmPatchMgr.h"

#include "EmPatchModule.h"
#include "EmPatchModuleMap.h"
#include "EmPatchState.h"
#include "EmPatchLoader.h"

#include "CGremlinsStubs.h" 	// StubAppEnqueueKey
#include "DebugMgr.h"			// Debug::ConnectedToTCPDebugger
#include "EmEventPlayback.h"	// EmEventPlayback::ReplayingEvents
#include "EmHAL.h"				// EmHAL::GetLineDriverState
#include "EmLowMem.h"			// EmLowMem::GetEvtMgrIdle, EmLowMem::TrapExists, EmLowMem_SetGlobal, EmLowMem_GetGlobal
#include "EmPalmFunction.h"		// IsSystemTrap
#include "EmRPC.h"				// RPC::SignalWaiters
#include "EmSession.h"			// GetDevice
#include "Hordes.h"				// Hordes::IsOn, Hordes::PostFakeEvent, Hordes::CanSwitchToApp
#include "Logging.h"			// LogEvtAddEventToQueue, etc.
#include "MetaMemory.h" 		// MetaMemory mark functions
#include "PreferenceMgr.h"		// Preference (kPrefKeyUserName)
#include "Profiling.h"			// StDisableAllProfiling
#include "ROMStubs.h"			// FtrSet, FtrUnregister, EvtWakeup, ...
#include "SessionFile.h"		// SessionFile
#include "UAE.h"				// gRegs, m68k_dreg, etc.


#pragma mark -

// ===========================================================================
//		 EmPatchMgr
// ===========================================================================

// ======================================================================
//	Global Interfaces
// ======================================================================


//Interface to THE collection of all patch modules:

extern IEmPatchModuleMap*	gPatchMapIP;
extern IEmPatchLoader*		gTheLoaderIP;


// ======================================================================
//	Private globals and constants
// ======================================================================

//Table of currently Patched shared libraries
//
static PatchedLibIndex		gPatchedLibs;

//Table of currently installed tail patches
//
static TailPatchIndex		gInstalledTailpatches;


// Magic number used to identify Htal patch
//	See comments in HtalLibSendReply.
//
const UInt16	kMagicRefNum = 0x666;	



// ======================================================================
//	Private functions
// ======================================================================

void 		PrvAutoload			(void);
void 		PrvSetCurrentDate	(void);


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::Initialize
 *
 * DESCRIPTION: Standard initialization function.  Responsible for
 *				initializing this sub-system when a new session is
 *				created.  Will be followed by at least one call to
 *				Reset or Load.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::Initialize (void)
{
	EmAssert (gSession);
	
	gTheLoaderIP->InitializePL ();
	gTheLoaderIP->LoadAllModules ();

	gSession->AddInstructionBreakHandlers (
		InstallInstructionBreaks,
		RemoveInstructionBreaks,
		HandleInstructionBreak);

	if (gPatchMapIP != NULL)
	{
		gPatchMapIP->ClearAll ();
		gPatchMapIP->LoadAll ();
	}

	EmPatchState::Initialize ();
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::Reset
 *
 * DESCRIPTION:	Standard reset function.  Sets the sub-system to a
 *				default state.	This occurs not only on a Reset (as
 *				from the menu item), but also when the sub-system
 *				is first initialized (Reset is called after Initialize)
 *				as well as when the system is re-loaded from an
 *				insufficient session file.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::Reset (void)
{
	gInstalledTailpatches.clear ();

	// Clear the installed lib patches (for "loaded" libraries)
	//
	gPatchedLibs.clear ();

	EmPatchState::Reset ();
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::Save
 *
 * DESCRIPTION:	Standard save function.  Saves any sub-system state to
 *				the given session file.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::Save (SessionFile& f)
{
	const long	kCurrentVersion = 5;

	Chunk			chunk;
	EmStreamChunk	s (chunk);

	s << kCurrentVersion;

	EmPatchState::Save (s, kCurrentVersion, EmPatchState::PSPersistStep1);

//	s << gSysPatchModule;
//	s << gNetLibPatchModule;
//	s << gPatchedLibs;

	s << (long) gInstalledTailpatches.size ();

	TailPatchIndex::iterator	iter2;
	for (iter2 = gInstalledTailpatches.begin (); iter2 != gInstalledTailpatches.end (); ++iter2)
	{
		s << iter2->fContext.fDestPC1;	// !!! Need to support fDestPC2, too.  But since only fNextPC seems to be used, it doesn't really matter.
		s << iter2->fContext.fExtra;
		s << iter2->fContext.fNextPC;
		s << iter2->fContext.fPC;
		s << iter2->fContext.fTrapIndex;
		s << iter2->fContext.fTrapWord;
		s << iter2->fCount;
//		s << iter2->fTailpatch; // Patched up in ::Load
	}

	EmPatchState::Save (s, kCurrentVersion, EmPatchState::PSPersistStep2);

	f.WritePatchInfo (chunk);
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::Load
 *
 * DESCRIPTION:	Standard load function.  Loads any sub-system state
 *				from the given session file.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::Load (SessionFile& f)
{
	Chunk	chunk;
	if (f.ReadPatchInfo (chunk))
	{
		long			version;
		EmStreamChunk	s (chunk);

		s >> version;

		if (version >= 1)
		{
			EmPatchState::Load (s, version, EmPatchState::PSPersistStep1);

			gPatchedLibs.clear ();
			gInstalledTailpatches.clear ();


			long	numTailpatches;
			s >> numTailpatches;

			int ii;
			for (ii = 0; ii < numTailpatches; ++ii)
			{
				TailpatchType	patch;

				s >> patch.fContext.fDestPC1;	// !!! Need to support fDestPC2, too.  But since only fNextPC seems to be used, it doesn't really matter.
				patch.fContext.fDestPC2 = patch.fContext.fDestPC1;
				s >> patch.fContext.fExtra;
				s >> patch.fContext.fNextPC;
				s >> patch.fContext.fPC;
				s >> patch.fContext.fTrapIndex;
				s >> patch.fContext.fTrapWord;
				s >> patch.fCount;

				// Patch up the tailpatch proc.

				HeadpatchProc	dummy;
				GetPatches (patch.fContext, dummy, patch.fTailpatch);

				gInstalledTailpatches.push_back (patch);
			}
		}
		
		EmPatchState::Load (s, version, EmPatchState::PSPersistStep2);
	}
	else
	{
		f.SetCanReload (false);
	}
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::Dispose
 *
 * DESCRIPTION:	Standard dispose function.	Completely release any
 *				resources acquired or allocated in Initialize and/or
 *				Load.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::Dispose (void)
{
	gInstalledTailpatches.clear ();
	gPatchedLibs.clear ();

	EmPatchState::Dispose ();

	if (gPatchMapIP != NULL)
	{
		gPatchMapIP->ClearAll ();
	}

	if (gTheLoaderIP)
	{
		gTheLoaderIP->ClearPL ();
	}
}


Err EmPatchMgr::GetGlobalMemBanks (void** membanksPP)
{
	if (membanksPP != NULL)
		*membanksPP = gEmMemBanks;

	return 0;
}

Err EmPatchMgr::GetGlobalRegs (void** regsPP)
{
	if (regsPP != NULL)
		*regsPP = &gRegs;
	
	return 0;
}



/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::PostLoad
 *
 * DESCRIPTION:	Do some stuff that is normally taken care of during the
 *				process of resetting the device (autoloading
 *				applications, setting the device date, installing the
 *				HotSync user-name, and setting the 'gdbS' feature).
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::PostLoad (void)
{
	if (EmPatchState::UIInitialized ())
	{
		// If we're listening on a socket, install the 'gdbS' feature.	The
		// existance of this feature causes programs written with the prc tools
		// to enter the debugger when they're launched.

		if (Debug::ConnectedToTCPDebugger ())
		{
			FtrSet ('gdbS', 0, 0x12BEEF34);
		}
		else
		{
			FtrUnregister ('gdbS', 0);
		}

		// Reconfirm the strict intl checks setting, whether on or off.

		Preference<Bool> intlPref (kPrefKeyReportStrictIntlChecks);

		if (EmPatchMgr::IntlMgrAvailable ())
		{
			::IntlSetStrictChecks (*intlPref);
		}

		// Reconfirm the overlay checks setting, whether on or off.

		Preference<Bool> overlayPref (kPrefKeyReportOverlayErrors);
		(void) ::FtrSet (omFtrCreator, omFtrShowErrorsFlag, *overlayPref);

		// Install the HotSync user-name.

		// Actually, let's not do that.  From Scott Maxwell:
		//
		//	Would it be possible to save the HotSync user name with each session? This
		//	would be very convenient for working on multiple projects because each
		//	session could have a different user name.
		//
		// To which I said:
		//	I think that what you're seeing is Poser (re-)establishing the user preference
		//	from the Properties/Preferences dialog box after the session is reloaded.  I
		//	could see this way of working as being valuable, too, so I'm not sure which way
		//	to go: keep things the way they are or change them.
		//
		// To which he said:
		//
		//	How about having the preferences dialog grab the name from the Palm RAM?
		//	That way you could easily maintain it per session.
		//
		// Sounds good to me...

//		Preference<string>	userNamePref (kPrefKeyUserName);
//		::SetHotSyncUserName (userNamePref->c_str ());

		CEnableFullAccess	munge;

		if (EmLowMem::TrapExists (sysTrapDlkGetSyncInfo))
		{
			char	userName[dlkUserNameBufSize];
			Err 	err = ::DlkGetSyncInfo (NULL, NULL, NULL, userName, NULL, NULL);
			if (!err)
			{
				Preference<string>	userNamePref (kPrefKeyUserName);
				userNamePref = string (userName);
			}
		}

		// Auto-load any files in the Autoload[Foo] directories.

		::PrvAutoload ();

		// Install the current date.

		::PrvSetCurrentDate ();

		// Wake up any current application so that they can respond
		// to events we pump in at EvtGetEvent time.

		::EvtWakeup ();
	}

	// Re-open any needed transports.  This could probably be done
	// at the time the session file is loaded, but we put it here
	// with the rest of the (deferred) post-load activities for
	// consistancy.

	for (EmUARTDeviceType ii = kUARTBegin; ii < kUARTEnd; ++ii)
	{
		if (EmHAL::GetLineDriverState (ii))
		{
			EmTransport* transport = gEmuPrefs->GetTransportForDevice (ii);

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


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::GetLibPatchTable
 *
 * DESCRIPTION:	.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

IEmPatchModule* EmPatchMgr::GetLibPatchTable (uint16 refNum)
{
	if (refNum >= gPatchedLibs.size ())
	{
		gPatchedLibs.resize (refNum + 1);
	}

	InstalledLibPatchEntry &libPtchEntry = gPatchedLibs[refNum];

	if (libPtchEntry.IsDirty () == true)
	{
		string	libName = ::GetLibraryName (refNum);

		IEmPatchModule *patchModuleIP = NULL;

		if (gPatchMapIP != NULL)
		{
			gPatchMapIP->GetModuleByName (libName, patchModuleIP);
		}


		libPtchEntry.SetPatchTableP (patchModuleIP);
		libPtchEntry.SetDirty (false);
	}

	return libPtchEntry.GetPatchTableP ();
}



/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::HandleSystemCall
 *
 * DESCRIPTION:	If this is a trap we could possibly have head- or
 *				tail-patched, handle those cases.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

CallROMType EmPatchMgr::HandleSystemCall (const SystemCallContext& context)
{
	EmAssert (gSession);
	if (gSession->GetNeedPostLoad ())
	{
		gSession->SetNeedPostLoad (false);
		EmPatchMgr::PostLoad ();
	}

	HeadpatchProc	hp;
	TailpatchProc	tp;
	EmPatchMgr::GetPatches (context, hp, tp);

	CallROMType handled = EmPatchMgr::HandlePatches (context, hp, tp);

	return handled;
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::GetPatches
 *
 * DESCRIPTION:	
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::GetPatches (	const SystemCallContext& context,
								HeadpatchProc& hp,
								TailpatchProc& tp)
{
	IEmPatchModule* patchModuleIP = NULL;

	// If this is in the system function range, check our table of
	// system function patches.

	if (::IsSystemTrap (context.fTrapWord))
	{
		static IEmPatchModule *sysPatchModuleIP = NULL;
		
		if (sysPatchModuleIP == NULL && gPatchMapIP != NULL)
		{
			gPatchMapIP->GetModuleByName (string ("~system"), sysPatchModuleIP);
		}
		
		patchModuleIP = sysPatchModuleIP;
	}
	
	else if (context.fExtra == kMagicRefNum) // See comments in HtalLibSendReply.
	{
		static IEmPatchModule *htalPatchModuleIP = NULL;
		
		if (htalPatchModuleIP == NULL && gPatchMapIP != NULL)
		{
			gPatchMapIP->GetModuleByName (string ("~Htal"), htalPatchModuleIP);
		}
		
		patchModuleIP = htalPatchModuleIP;
	}

	// Otherwise, see if this is a call to a patched library
	else
	{
		patchModuleIP = GetLibPatchTable (context.fExtra);
	}

	// Now that we've got the right patch table for this module, see if
	// that patch table has head- or tailpatches for this function.

	if (patchModuleIP != NULL)
	{
		patchModuleIP->GetHeadpatch (context.fTrapIndex, hp);
		patchModuleIP->GetTailpatch (context.fTrapIndex, tp);
	}
	else
	{
		hp = NULL;
		tp = NULL;
	}
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::HandlePatches
 *
 * DESCRIPTION:	
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

CallROMType EmPatchMgr::HandlePatches (const SystemCallContext& context,
									HeadpatchProc hp,
									TailpatchProc tp)
{
	CallROMType handled = kExecuteROM;

	// First, see if we have a SysHeadpatch for this function. If so, call
	// it. If it returns true, then that means that the head patch
	// completely handled the function.

	// !!! May have to mess with PC here in case patches do something
	// to enter the debugger.

	if (hp)
	{
		handled = CallHeadpatch (hp);
	}

	// Next, see if there's a SysTailpatch function for this trap. If
	// so, install the TRAP that will cause us to regain control
	// after the trap function has executed.

	if (tp)
	{
		if (handled == kExecuteROM)
		{
			SetupForTailpatch (tp, context);
		}
		else
		{
			CallTailpatch (tp);
		}
	}

	return handled;
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::HandleInstructionBreak
 *
 * DESCRIPTION:	Handle a tail patch, if any is registered for this
 *				memory location.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::HandleInstructionBreak (void)
{
	// Get the address of the tailpatch to call.  May return NULL if
	// there is no tailpatch for this memory location.

	TailpatchProc	tp = RecoverFromTailpatch (gCPU->GetPC ());

	// Call the tailpatch handler for the trap that just returned.

	CallTailpatch (tp);
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::InstallInstructionBreaks
 *
 * DESCRIPTION:	Set the MetaMemory bit that tells the CPU loop to stop
 *				when we get to the desired locations.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::InstallInstructionBreaks (void)
{
	TailPatchIndex::iterator	iter = gInstalledTailpatches.begin ();

	while (iter != gInstalledTailpatches.end ())
	{
		MetaMemory::MarkInstructionBreak (iter->fContext.fNextPC);
		++iter;
	}
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::RemoveInstructionBreaks
 *
 * DESCRIPTION:	Clear the MetaMemory bit that tells the CPU loop to stop
 *				when we get to the desired locations.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::RemoveInstructionBreaks (void)
{
	TailPatchIndex::iterator	iter = gInstalledTailpatches.begin ();

	while (iter != gInstalledTailpatches.end ())
	{
		MetaMemory::UnmarkInstructionBreak (iter->fContext.fNextPC);
		++iter;
	}
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::SetupForTailpatch
 *
 * DESCRIPTION:	Set up the pending TRAP $F call to be tailpatched.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::SetupForTailpatch (TailpatchProc tp, const SystemCallContext& context)
{
	// See if this function is already tailpatched.  If so, merely increment
	// the use-count field.

	TailPatchIndex::iterator	iter = gInstalledTailpatches.begin ();

	while (iter != gInstalledTailpatches.end ())
	{
		if (iter->fContext.fNextPC == context.fNextPC)
		{
			++(iter->fCount);
			return;
		}

		++iter;
	}

	// This function is not already tailpatched, so add a new entry
	// for the the PC/opcode we want to save.

	EmAssert (gSession);
	gSession->RemoveInstructionBreaks ();

	TailpatchType	newTailpatch;

	newTailpatch.fContext	= context;
	newTailpatch.fCount 	= 1;
	newTailpatch.fTailpatch = tp;

	gInstalledTailpatches.push_back (newTailpatch);

	gSession->InstallInstructionBreaks ();
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::RecoverFromTailpatch
 *
 * DESCRIPTION:	.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

TailpatchProc EmPatchMgr::RecoverFromTailpatch (emuptr startPC)
{
	// Get the current PC so that we can find the record for this tailpatch.

	emuptr patchPC = startPC;

	// Find the PC.

	TailPatchIndex::iterator	iter = gInstalledTailpatches.begin ();

	while (iter != gInstalledTailpatches.end ())
	{
		if (iter->fContext.fNextPC == patchPC)
		{
			TailpatchProc	result = iter->fTailpatch;

			// Decrement the use-count.  If it reaches zero, remove the
			// patch from our list.

			if (--(iter->fCount) == 0)
			{
				EmAssert (gSession);
				gSession->RemoveInstructionBreaks ();

				gInstalledTailpatches.erase (iter);

				gSession->InstallInstructionBreaks ();
			}

			return result;
		}

		++iter;
	}

	return NULL;
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::CallHeadpatch
 *
 * DESCRIPTION:	If the given system function is head patched, then call
 *				the headpatch.	Return "handled" (which means whether
 *				or not to call the ROM function after this one).
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

CallROMType EmPatchMgr::CallHeadpatch (HeadpatchProc hp, bool /* noProfiling */)
{
	CallROMType handled = kExecuteROM;

	if (hp)
	{
		// If (noProfiling == true) then stop all profiling activities. 
		// Stop cycle counting and stop the recording of function entries
		// and exits.  We want our trap patches to be as transparent as possible.

		StDisableAllProfiling	stopper (/*noProfiling*/);

		handled = hp ();
	}

	return handled;
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::CallTailpatch
 *
 * DESCRIPTION:	If the given function is tail patched, then call the
 *				tailpatch.
 *
 * PARAMETERS:	none
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

void EmPatchMgr::CallTailpatch (TailpatchProc tp, bool /* noProfiling */)
{
	if (tp)
	{
		// Stop all profiling activities. Stop cycle counting and stop the
		// recording of function entries and exits.  We want our trap patches
		// to be as transparent as possible.

		StDisableAllProfiling	stopper (/*noProfiling*/);

		tp ();
	}
}





/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::PuppetString
 *
 * DESCRIPTION:	Puppet stringing function for inserting events into
 *				the system.  We want to insert events when:
 *
 *				- Gremlins is running
 *				- The user types characters
 *				- The user clicks with the mouse
 *				- We need to trigger a switch another application
 *
 *				This function is called from headpatches to
 *				SysEvGroupWait and SysSemaphoreWait.  When the Palm OS
 *				needs an event, it calls EvtGetEvent.  EvtGetEvent
 *				looks in all the usual places for events to return. If
 *				it doesn't find any, it puts the system to sleep by
 *				calling SysEvGroupWait (or SysSemaphoreWait on 1.0
 *				systems).  SysEvGroupWait will wake up and return when
 *				an event is posted via something like EvtEnqueuePenPoint,
 *				EvtEnqueueKey, or KeyHandleInterrupt.
 *
 *				To puppet-string Palm OS, we therefore patch those
 *				functions and post events, preventing them from actually
 *				going to sleep.
 *
 * PARAMETERS:	callROM - return here whether or not the original ROM
 *					function still needs to be called.	Normally, the
 *					answer is "yes".
 *
 *				clearTimeout - set to true if the "timeout" parameter
 *					of the function we've patched needs to be prevented
 *					from being "infinite".
 *
 * RETURNED:	nothing
 *
 ***********************************************************************/

static void PrvForceNilEvent (void)
{
	// No event was posted.  What we'd like right now is to force
	// EvtGetEvent to return a nil event.  We can do that by returning
	// a non-zero result code from SysEvGroupWait.  EvtGetEvent doesn't
	// look too closely at the result, but let's try to be as close to
	// reality as possible. SysEvGroupWait currently returns "4"
	// (CJ_WRTMOUT) to indicate a timeout condition.  It should
	// probably get turned into sysErrTimeout somewhere along the way,
	// but that translation doesn't seem to occur.

	m68k_dreg (gRegs, 0) = 4;
}

void EmPatchMgr::PuppetString (CallROMType& callROM, Bool& clearTimeout)
{
	callROM = kExecuteROM;
	clearTimeout = false;

	// Set the return value (Err) to zero in case we return
	// "true" (saying that we handled the trap).

	m68k_dreg (gRegs, 0) = 0;

	// If the low-memory global "idle" is true, then we're being
	// called from EvtGetEvent or EvtGetPen, in which case we
	// need to check if we need to post some events.

	if (EmLowMem::GetEvtMgrIdle ())
	{
		// If there's an RPC request waiting for a nilEvent,
		// let it know that it happened.

		if (EmPatchState::GetLastEvtTrap () == sysTrapEvtGetEvent)
		{
			RPC::SignalWaiters (hostSignalIdle);
		}

		// If we're in the middle of calling a Palm OS function ourself,
		// and we are somehow at the point where the system is about to
		// doze, then just return now.  Don't let it doze!  Interrupts are
		// off, and HwrDoze will never return!

		if (gSession->IsNested ())
		{
			::PrvForceNilEvent ();
			callROM = kSkipROM;
			return;
		}

		EmAssert (gSession);

		// Check if Minimization is going on.

		if (EmEventPlayback::ReplayingEvents ())
		{
			if (EmPatchState::GetLastEvtTrap () == sysTrapEvtGetEvent)
			{
				if (!EmEventPlayback::ReplayGetEvent ())
				{
					::PrvForceNilEvent ();
					callROM = kSkipROM;
					return;
				}
			}
			else if (EmPatchState::GetLastEvtTrap () == sysTrapEvtGetPen)
			{
				EmEventPlayback::ReplayGetPen ();
			}

			// Never let the timeout be infinite.  If the above event-posting
			// attempts failed (which could happen, for instance, if we attempted
			// to post a pen event with the same coordinates as the previous
			// pen event), we'd end up waiting forever.

			clearTimeout = true;
		}

		// Check if Hords is going on.

		else if (Hordes::IsOn ())
		{
			if (EmPatchState::GetLastEvtTrap () == sysTrapEvtGetEvent)
			{
				if (!Hordes::PostFakeEvent ())
				{
					if (LogEnqueuedEvents ())
					{
						LogAppendMsg ("Hordes::PostFakeEvent did not post an event.");
					}

					::PrvForceNilEvent ();
					callROM = kSkipROM;
					return;
				}
			}
			else if (EmPatchState::GetLastEvtTrap () == sysTrapEvtGetPen)
			{
				Hordes::PostFakePenEvent ();
			}
			else
			{
				if (LogEnqueuedEvents ())
				{
					LogAppendMsg ("Last event was 0x%04X, so not posting event.", EmPatchState::GetLastEvtTrap ());
				}
			}

			// Never let the timeout be infinite.  If the above event-posting
			// attempts failed (which could happen, for instance, if we attempted
			// to post a pen event with the same coordinates as the previous
			// pen event), we'd end up waiting forever.

			clearTimeout = true;
		}

		// Gremlins aren't on; let's see if the user has typed some
		// keys that we need to pass on to the Palm device.

		else if (gSession->HasKeyEvent ())
		{
			EmKeyEvent	event = gSession->GetKeyEvent ();

			UInt16	modifiers = 0;

			if (event.fShiftDown)
				modifiers |= shiftKeyMask;

			if (event.fCapsLockDown)
				modifiers |= capsLockMask;

			if (event.fNumLockDown)
				modifiers |= numLockMask;

			// We don't really want to set this one.  commandKeyMask
			// means something special in Palm OS
//			if (event.fCommandDown)
//				modifiers |= commandKeyMask;

			if (event.fOptionDown)
				modifiers |= optionKeyMask;

			if (event.fControlDown)
				modifiers |= controlKeyMask;

			if (event.fAltDown)
				modifiers |= 0;	// no bit defined for this

			if (event.fWindowsDown)
				modifiers |= 0;	// no bit defined for this

			::StubAppEnqueueKey (event.fKey, 0, modifiers);
		}

		// No key events, let's see if there are pen events.

		else if (gSession->HasPenEvent ())
		{
			EmPoint		pen (-1, -1);
			EmPenEvent	event = gSession->GetPenEvent ();
			if (event.fPenIsDown)
			{
				pen = event.fPenPoint;
			}

			PointType	palmPen = pen;
			StubAppEnqueuePt (&palmPen);
		}

		// E. None of the above.  Let's see if there's an app
		//	  we're itching to switch to.

		else if (EmPatchState::GetNextAppDbID () != 0)
		{
			/*Err err =*/ SwitchToApp (EmPatchState::GetNextAppCardNo (), EmPatchState::GetNextAppDbID ());

			EmPatchState::SetNextAppCardNo (0);
			EmPatchState::SetNextAppDbID (0);
			
			clearTimeout = true;
		}
	}
	else
	{
		if (Hordes::IsOn () && LogEnqueuedEvents ())
		{
			LogAppendMsg ("Event Manager not idle, so not posting an event.");
		}
	}
}


/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::IntlMgrAvailable
 *
 * DESCRIPTION:	Indicates whether the international manager is available.
 *
 * PARAMETERS:	
 *
 * RETURNED:	True if it is (OS > 4.0), false otherwise.
 *
 ***********************************************************************/

Bool EmPatchMgr::IntlMgrAvailable (void)
{
	UInt32 romVersionData;
	FtrGet (sysFileCSystem, sysFtrNumROMVersion, &romVersionData);
	UInt32 romVersionMajor = sysGetROMVerMajor (romVersionData);

	return (romVersionMajor >= 4);
}



/***********************************************************************
 *
 * FUNCTION:	EmPatchMgr::SwitchToApp
 *
 * DESCRIPTION:	Switches to the given application or launchable document.
 *
 * PARAMETERS:	cardNo - the card number of the app to switch to.
 *
 *				dbID - the database id of the app to switch to.
 *
 * RETURNED:	Err number of any errors that occur
 *
 ***********************************************************************/

Err EmPatchMgr::SwitchToApp (UInt16 cardNo, LocalID dbID)
{
	UInt16	dbAttrs;
	UInt32	type, creator;

	Err err = ::DmDatabaseInfo (
				cardNo,
				dbID,
				NULL,				/*name*/
				&dbAttrs,
				NULL,				/*version*/
				NULL,				/*create date*/
				NULL,				/*modDate*/
				NULL,				/*backup date*/
				NULL,				/*modNum*/
				NULL,				/*appInfoID*/
				NULL,				/*sortInfoID*/
				&type,
				&creator);

	if (err)
		return err;

	//---------------------------------------------------------------------
	// If this is an executable, call SysUIAppSwitch
	//---------------------------------------------------------------------
	if (::IsExecutable (type, creator, dbAttrs))
	{
		err = ::SysUIAppSwitch (cardNo, dbID,
						sysAppLaunchCmdNormalLaunch, NULL);

		if (err)
			return err;
	}

	//---------------------------------------------------------------------
	// else, this must be a launchable data database. Find it's owner app
	//	and launch it with a pointer to the data database name.
	//---------------------------------------------------------------------
	else
	{
		DmSearchStateType	searchState;
		UInt16				appCardNo;
		LocalID 			appDbID;

		err = ::DmGetNextDatabaseByTypeCreator (true, &searchState,
						sysFileTApplication, creator,
						true, &appCardNo, &appDbID);
		if (err)
			return err;

		// Create the param block

		emuptr cmdPBP = (emuptr) ::MemPtrNew (sizeof (SysAppLaunchCmdOpenDBType));
		if (cmdPBP == EmMemNULL)
			return memErrNotEnoughSpace;

		// Fill it in

		::MemPtrSetOwner ((MemPtr) cmdPBP, 0);
		EmMemPut16 (cmdPBP + offsetof (SysAppLaunchCmdOpenDBType, cardNo), cardNo);
		EmMemPut32 (cmdPBP + offsetof (SysAppLaunchCmdOpenDBType, dbID), dbID);

		// Switch now

		err = ::SysUIAppSwitch (appCardNo, appDbID, sysAppLaunchCmdOpenDB, (MemPtr) cmdPBP);
		if (err)
			return err;
	}

	return errNone;
}