This repository was archived by the owner on Jun 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathCommands.cpp
More file actions
1719 lines (1342 loc) · 56.9 KB
/
Commands.cpp
File metadata and controls
1719 lines (1342 loc) · 56.9 KB
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
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "TinyBooter.h"
#include <TinyBooterEntry.h>
#include "ConfigurationManager.h"
#include <TinyCLR_Endian.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
extern Loader_Engine g_eng;
//--//
UINT8* g_ConfigBuffer = NULL;
int g_ConfigBufferLength = 0;
static const int g_ConfigBufferTotalSize = sizeof(ConfigurationSector);
//--//
static const int AccessMemory_Check = 0x00;
static const int AccessMemory_Read = 0x01;
static const int AccessMemory_Write = 0x02;
static const int AccessMemory_Erase = 0x03;
static const int AccessMemory_Mask = 0x0F;
static bool AccessMemory( UINT32 location, UINT32 lengthInBytes, BYTE* buf, int mode );
//--//
struct BitFieldManager
{
volatile SECTOR_BIT_FIELD* m_signatureCheck ;
SECTOR_BIT_FIELD m_skipCfgSectorCheck;
BOOL m_fSignatureCheckDirty;
BlockStorageDevice* m_blockDevice;
UINT32 m_cfgPhysicalAddress;
const BlockRegionInfo* m_region;
BOOL m_fUsingRAM;
//--//
static const UINT32 s_bitFieldOffset = offsetof(ConfigurationSector, SignatureCheck);
//--//
// current non-volatile signature check sector bitfield
#define BITS_PER_UINT32 (8*sizeof(UINT32))
#define TINYBOOTER_SECTOR_BITFIELD_VALID_BIT (1ul<<(BITS_PER_UINT32-1))
#define TINYBOOTER_IS_SECTOR_BITFIELD_VALID(x) (TINYBOOTER_SECTOR_BITFIELD_VALID_BIT == (x->BitField[ SECTOR_BIT_FIELD::c_MaxFieldUnits-1 ] & TINYBOOTER_SECTOR_BITFIELD_VALID_BIT))
void ResetBitFieldManager()
{
m_signatureCheck = NULL;
m_fSignatureCheckDirty = false;
m_blockDevice = NULL;
m_cfgPhysicalAddress = 0;
m_region = NULL;
m_fUsingRAM = FALSE;
}
// The ResetSignatureCheckArray method is called when there are no available signature check bitfields left.
// Reset the SECTOR_BIT_FIELD in teh CONFIG block of the Current pointing block device
void ResetSignatureCheckArray()
{
BYTE* data;
if(m_blockDevice == NULL) return; // no Block device has set or RAM device
if(m_fUsingRAM)
{
memset(&m_skipCfgSectorCheck, 0xff, sizeof(m_skipCfgSectorCheck));
m_signatureCheck = &m_skipCfgSectorCheck;
}
else
{
const BlockDeviceInfo* deviceInfo = m_blockDevice->GetDeviceInfo();
data = (BYTE*)malloc( m_region->BytesPerBlock );
if(data != NULL)
{
// read the whole configure block, no matter it is NAND/NOR
if(deviceInfo->Attribute.SupportsXIP)
{
memcpy(data, (void*)m_cfgPhysicalAddress, m_region->BytesPerBlock);
}
else
{
m_blockDevice->Read( m_cfgPhysicalAddress, m_region->BytesPerBlock, data );
}
m_blockDevice->EraseBlock( m_cfgPhysicalAddress );
// erase signature check area
ConfigurationSector *pCfg = (ConfigurationSector*)data;
memset( (void*)&pCfg->SignatureCheck[ 0 ], 0xFF, sizeof(pCfg->SignatureCheck) );
m_blockDevice->Write( m_cfgPhysicalAddress, m_region->BytesPerBlock,data, FALSE );
free(data);
}
else
{
debug_printf("Failed to malloc spaces at ResetSignatureCheckArray\r\n");
}
}
}
// The SetDirtySectorBit method is used to mark a sector as dirty. It does so by setting a bit in non-
// volatile FLASH memory. The sectors are indexed from LSb to MSb. The MSb bit in the last word of the
// entire bitfield indicates the validity of the entire field.
// if is at NAND, SECTOR_BIT_FIELD bitField is most likely point to RAM has been loaded up
void SetDirtySectorBit( UINT32 sectorIndex )
{
volatile FLASH_WORD* dataAddr;
volatile FLASH_WORD* dataRdAddr;
FLASH_WORD data;
if(sectorIndex > SECTOR_BIT_FIELD::c_MaxSectorCount) return; // Error condition!
if(m_fUsingRAM)
{
m_signatureCheck->BitField[ sectorIndex / BITS_PER_UINT32 ] &= ~( 1ul << (sectorIndex % BITS_PER_UINT32) );
m_fSignatureCheckDirty = true;
return;
}
if(m_blockDevice == NULL) return; // no Block device has set or it is RAM write, then no need to check dirty bit
const BlockDeviceInfo* deviceInfo = m_blockDevice->GetDeviceInfo();
m_fSignatureCheckDirty = true;
if(deviceInfo->Attribute.SupportsXIP)
{
dataAddr = (volatile FLASH_WORD*)&m_signatureCheck->BitField[ sectorIndex / BITS_PER_UINT32 ];
// read back the
dataRdAddr = (volatile FLASH_WORD*)CPU_GetUncachableAddress( dataAddr );
data = (*dataRdAddr) & ~( 1ul << (sectorIndex % BITS_PER_UINT32) );
// write directly
m_blockDevice->Write( (UINT32)dataAddr, sizeof(FLASH_WORD), (BYTE*)&data, FALSE );
}
else
{
UINT32 length = m_region->BytesPerBlock;
BYTE* dataptr = (BYTE*)malloc(length);
if(dataptr != NULL)
{
// read the whole configure block, no matter
// There is a assumption that ConfigurationSector is at the beginning of the Block if there is A CONFIG BLOCK in the device
m_blockDevice->Read( m_cfgPhysicalAddress, length, dataptr );
// erase signature check area
ConfigurationSector *pCfg = (ConfigurationSector*)dataptr;
for( int i = 0; i < ConfigurationSector::c_MaxSignatureCount; ++i )
{
SECTOR_BIT_FIELD* bit = (SECTOR_BIT_FIELD*)&pCfg->SignatureCheck[ i ];
if(TINYBOOTER_IS_SECTOR_BITFIELD_VALID(bit))
{
bit->BitField[ sectorIndex / BITS_PER_UINT32 ] &= ~( 1ul << (sectorIndex % BITS_PER_UINT32) );
break;
}
}
// write back to sector, as we only change one bit from 0 to 1, no need to erase sector
m_blockDevice->Write( m_cfgPhysicalAddress, length, dataptr, FALSE );
free(dataptr);
}
}
}
// The GetNextSectorSignatureCheck method gets the next valid signature check bitfield for use during
// programming (or boot up). It searches for a valid bitfield in the signature check bitfield array.
// If a valid field can not be found, the array is reset and the first field is returned.
void GetNextSectorSignatureCheck( BlockStorageDevice* device, SECTOR_BIT_FIELD& bitField )
{
m_blockDevice = device;
if(device == NULL) return;
BlockStorageStream stream;
if (!stream.Initialize( BlockUsage::CONFIG, device ))
{
memset( &m_skipCfgSectorCheck, 0xff, sizeof(m_skipCfgSectorCheck ));
m_signatureCheck = &m_skipCfgSectorCheck;
m_fUsingRAM = TRUE;
m_cfgPhysicalAddress = 0;
bitField = m_skipCfgSectorCheck;
}
else
{
UINT32 regionIndex, rangeIndex;
ConfigurationSector* configSector;
BYTE* data;
const BlockDeviceInfo* deviceInfo = stream.Device->GetDeviceInfo();
m_cfgPhysicalAddress = stream.BaseAddress;
if(!deviceInfo->FindRegionFromAddress( stream.BaseAddress, regionIndex, rangeIndex ))
{
ASSERT(FALSE);
return;
}
m_region = &deviceInfo->Regions[ regionIndex ];
m_fUsingRAM = FALSE;
if(!deviceInfo->Attribute.SupportsXIP)
{
// have to read the whole block;
UINT32 length = sizeof(ConfigurationSector);
memset( &m_skipCfgSectorCheck, 0xff, sizeof(m_skipCfgSectorCheck) );
data = (BYTE*)malloc(length);
stream.Device->Read( m_cfgPhysicalAddress, length, (BYTE *)data );
configSector = (ConfigurationSector*)data;
m_signatureCheck = NULL;
for(int i=0; i<ConfigurationSector::c_MaxSignatureCount; i++)
{
SECTOR_BIT_FIELD *pBF = (SECTOR_BIT_FIELD*)&configSector->SignatureCheck[ i ];
if(TINYBOOTER_IS_SECTOR_BITFIELD_VALID(pBF))
{
memcpy( (BYTE *)&m_skipCfgSectorCheck,(BYTE*) &configSector->SignatureCheck[ i ], sizeof(SECTOR_BIT_FIELD) );
bitField = m_skipCfgSectorCheck;
m_signatureCheck = &m_skipCfgSectorCheck;
break;
}
}
if(m_signatureCheck ==NULL)
{
ResetSignatureCheckArray();
bitField = m_skipCfgSectorCheck;
m_signatureCheck = &m_skipCfgSectorCheck;
}
free(data);
}
else // XIP device
{
configSector = (ConfigurationSector*)CPU_GetUncachableAddress( m_cfgPhysicalAddress ); // global config not in flash for bootloader
m_signatureCheck = NULL;
for(int i=0; i<ConfigurationSector::c_MaxSignatureCount; i++)
{
SECTOR_BIT_FIELD* pBF = (SECTOR_BIT_FIELD*)&configSector->SignatureCheck[ i ];
if(TINYBOOTER_IS_SECTOR_BITFIELD_VALID(pBF))
{
bitField = *pBF;
m_signatureCheck =pBF;
break;
}
}
if(m_signatureCheck == NULL)
{
ResetSignatureCheckArray();
bitField = configSector->SignatureCheck[ 0 ];
m_signatureCheck = (volatile SECTOR_BIT_FIELD*)&(configSector->SignatureCheck[ 0 ]);
}
}
}
}
// The InvalidateSectorBitField method is used to invalidate the given signature bitfield
// It does so by invalidating the most significant bit of the last word in the bitfield.
void InvalidateSectorBitField()
{
SECTOR_BIT_FIELD bitField;
if(m_fSignatureCheckDirty)
{
// set the most significant bit of the last word to indicate that this bit field is invalid
SetDirtySectorBit( SECTOR_BIT_FIELD::c_MaxSectorCount );
GetNextSectorSignatureCheck( m_blockDevice, bitField );
m_fSignatureCheckDirty = false;
}
}
// The EraseOnSignatureCheckFail method is called on initialization to validate the last
// programming
void EraseOnSignatureCheckFail()
{
SECTOR_BIT_FIELD bitField;
BlockStorageDevice* device = BlockStorageList::GetFirstDevice();
ConfigurationSector Cfg;
while (device != NULL)
{
// clear all the member before checking.
ResetBitFieldManager();
GetNextSectorSignatureCheck( device, bitField );
int iRegion = 0, iRange = 0, iAbsBlock = 0;
const BlockDeviceInfo* deviceInfo = device->GetDeviceInfo();
const BlockRegionInfo* pRegion = &deviceInfo->Regions[ iRegion ];
for(int i=0; i<SECTOR_BIT_FIELD::c_MaxFieldUnits; i++ )
{
// zero bit represents a dirty sector
if(bitField.BitField[ i ] != 0xFFFFFFFF)
{
int sectorIndex = i * BITS_PER_UINT32;
m_fSignatureCheckDirty = true;
for(int j=0; j<BITS_PER_UINT32; j++)
{
// Erase any sector that is marked as dirty
if(0 == (bitField.BitField[ i ] & (1ul<<j)))
{
int blockIndex = sectorIndex + j;
bool found = false;
while(!found)
{
while(!found)
{
int rangeBlocks = pRegion->BlockRanges[ iRange ].GetBlockCount();
if(iAbsBlock <= blockIndex && blockIndex <= (iAbsBlock + rangeBlocks))
{
ByteAddress eraseAddress = pRegion->BlockAddress(blockIndex - iAbsBlock);
if (CheckFlashSectorPermission(device, eraseAddress))
device->EraseBlock( eraseAddress );
else
debug_printf(" BOOTER BLOCK IS Dirty ??? !!! ");
found = true;
break;
}
iAbsBlock += rangeBlocks;
iRange++;
if(iRange >= pRegion->NumBlockRanges)
{
break;
}
}
if(!found)
{
iRegion++;
if(iRegion < deviceInfo->NumRegions)
{
pRegion = &deviceInfo->Regions[ iRegion ];
}
else
{
ASSERT(FALSE);
break;
}
}
}
}
}
}
}
// if we found any dirty sector (and erased them) then invalidate this sector field
if(m_fSignatureCheckDirty)
{
InvalidateSectorBitField();
}
device = BlockStorageList::GetNextDevice( *device );
}
// clear the members data
}
} g_BitFieldManager;// end of BitFiedManage
/////////////////////////////////////////////////////////////////////
//location is the physical address of the memory to be written
static bool AccessMemory( UINT32 location, UINT32 lengthInBytes, BYTE* buf, int mode )
{
mode &= AccessMemory_Mask;
BlockStorageDevice *device;
ByteAddress sectAddress;
if (BlockStorageList::FindDeviceForPhysicalAddress( &device, location, sectAddress ))
{
UINT32 iRegion, iRange;
const BlockDeviceInfo* deviceInfo = device->GetDeviceInfo() ;
if(!device->FindRegionFromAddress( location, iRegion, iRange ))
{
debug_printf(" Invalid condition - Fail to find the block number from the ByteAddress %x \r\n",location);
return FALSE;
}
UINT32 accessPhyAddress = location;
BYTE* bufPtr = buf;
BOOL success = TRUE;
INT32 accessLenInBytes = lengthInBytes;
INT32 blockOffset = deviceInfo->Regions[ iRegion ].OffsetFromBlock( accessPhyAddress );
if(blockOffset < 0)
{
blockOffset = 0;
ASSERT(FALSE);
}
for(; iRegion < deviceInfo->NumRegions; iRegion++)
{
const BlockRegionInfo *pRegion = &deviceInfo->Regions[ iRegion ];
UINT32 RangeBaseAddress = pRegion->BlockAddress( pRegion->BlockRanges[ iRange ].StartBlock );
UINT32 blockIndex = pRegion->BlockIndexFromAddress( accessPhyAddress );
UINT32 accessMaxLength = pRegion->BytesPerBlock - blockOffset;
blockOffset = 0;
for(;blockIndex < pRegion->NumBlocks; blockIndex++)
{
//accessMaxLength =the current largest number of bytes can be read from the block from the address to its block boundary.
UINT32 NumOfBytes = __min(accessMaxLength, accessLenInBytes);
accessMaxLength = pRegion->BytesPerBlock;
if(blockIndex > pRegion->BlockRanges[ iRange ].EndBlock)
{
iRange++;
if(iRange >= pRegion->NumBlockRanges)
{
ASSERT(FALSE);
break;
}
RangeBaseAddress = pRegion->BlockAddress( pRegion->BlockRanges[ iRange ].StartBlock );
}
switch(mode)
{
case AccessMemory_Check:
case AccessMemory_Read:
if (deviceInfo->Attribute.SupportsXIP)
{
if(mode == AccessMemory_Check)
{
*(UINT32*)buf = SUPPORT_ComputeCRC( (const void*)accessPhyAddress, NumOfBytes, *(UINT32*)buf );
}
else
{
memcpy( (BYTE*)bufPtr, (const void*)accessPhyAddress, NumOfBytes );
}
}
else
{
if (mode == AccessMemory_Check)
{
bufPtr = (BYTE*) malloc(NumOfBytes);
if(!bufPtr) return false;
}
success = device->Read( accessPhyAddress, NumOfBytes, (BYTE *)bufPtr );
if(!success)
{
if (mode == AccessMemory_Check)
{
free(bufPtr);
}
break;
}
if (mode == AccessMemory_Check)
{
*(UINT32*)buf = SUPPORT_ComputeCRC( bufPtr, NumOfBytes, *(UINT32*)buf );
free(bufPtr);
}
}
break;
case AccessMemory_Write:
if(!CheckFlashSectorPermission(device, accessPhyAddress)) return false;
if(!pRegion->BlockRanges[ iRange ].IsConfig())
{
UINT32 startBlock = pRegion->BlockAddress( blockIndex );
if(accessPhyAddress == startBlock && !device->IsBlockErased( startBlock, pRegion->BytesPerBlock ))
{
device->EraseBlock( startBlock );
}
if(!(success = device->Write( accessPhyAddress , NumOfBytes, (BYTE *)bufPtr, FALSE )))
{
debug_printf(" Failed WriteSector at location %x, size %x \r\n", accessPhyAddress, NumOfBytes);
break;
}
}
else // write to RAM for config sector
{
// new write to a config block.
if (accessPhyAddress == RangeBaseAddress)
{
if(g_ConfigBuffer != NULL)
{
free(g_ConfigBuffer);
}
g_ConfigBufferLength = 0;
// g_ConfigBuffer = (UINT8*)malloc(pRegion->BytesPerBlock);
// Just allocate the configuration Sector size, configuration block can be large and not necessary to have that buffer.
g_ConfigBuffer = (UINT8*)malloc(g_ConfigBufferTotalSize);
}
else if(g_ConfigBufferTotalSize < ( g_ConfigBufferLength + lengthInBytes))
{
UINT8* tmp = (UINT8*)malloc(g_ConfigBufferLength + lengthInBytes);
if(tmp == NULL)
{
return false;
}
memcpy( tmp, g_ConfigBuffer, g_ConfigBufferLength );
free(g_ConfigBuffer);
g_ConfigBuffer = tmp;
}
// out of memory or it was not re-writing from the begining of the config sector
if(g_ConfigBuffer == NULL)
{
return false;
}
memcpy( &g_ConfigBuffer[ g_ConfigBufferLength ], bufPtr, lengthInBytes );
g_ConfigBufferLength += lengthInBytes;
}
break;
case AccessMemory_Erase:
if(!CheckFlashSectorPermission(device, accessPhyAddress)) return false;
// don't erase of config sector (we will only do that after checking the signature in RAM)
if(!pRegion->BlockRanges[ iRange ].IsConfig())
{
success = device->EraseBlock( pRegion->BlockAddress( blockIndex ) );
if(!success) break;
}
break;
}
accessLenInBytes -= NumOfBytes;
if (accessLenInBytes <= 0 || (!success)) break;
if(bufPtr) bufPtr += NumOfBytes;
accessPhyAddress += NumOfBytes;
}
if (accessLenInBytes <= 0 || (!success)) break;
blockIndex = 0;
iRange = 0;
}
}
else // device == NULL ->RAM operation
{
UINT32 locationEnd = location + lengthInBytes;
UINT32 ramStartAddress = HalSystemConfig.RAM1.Base;
UINT32 ramEndAddress = ramStartAddress + HalSystemConfig.RAM1.Size ;
if((location <ramStartAddress) || (location >=ramEndAddress) || (locationEnd >ramEndAddress) )
{
debug_printf(" Invalid address %x and range %x Ram Start %x, Ram end %x\r\n", location, lengthInBytes, ramStartAddress, ramEndAddress);
return FALSE;
}
switch(mode)
{
case AccessMemory_Check:
break;
case AccessMemory_Read:
memcpy( buf, (const void*)location, lengthInBytes );
break;
case AccessMemory_Write:
BYTE * memPtr;
memPtr = (BYTE*)location;
memcpy( memPtr, buf, lengthInBytes );
break;
case AccessMemory_Erase:
memPtr = (BYTE*)location;
if (lengthInBytes !=0) memset( memPtr, 0xFF, lengthInBytes );
break;
default:
break;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool Loader_Engine::SignedDataState::CheckDirty()
{
return ((m_dataAddress != 0) || (m_dataLength != 0));
}
void Loader_Engine::SignedDataState::Reset()
{
m_dataAddress = 0;
m_dataLength = 0;
m_pDevice = NULL;
g_BitFieldManager.ResetBitFieldManager();
}
void Loader_Engine::SignedDataState::EraseMemoryAndReset()
{
if(m_dataAddress != 0)
{
AccessMemory( m_dataAddress, m_dataLength, NULL, AccessMemory_Erase );
g_BitFieldManager.InvalidateSectorBitField();
g_BitFieldManager.ResetBitFieldManager();
Reset();
}
}
bool Loader_Engine::SignedDataState::VerifyContiguousData( UINT32 address, UINT32 length )
{
BlockStorageDevice *device;
ByteAddress sectAddr;
UINT32 BlockType;
UINT32 regionIndex, rangeIndex;
if (BlockStorageList::FindDeviceForPhysicalAddress( &device, address, sectAddr))
{
SECTOR_BIT_FIELD p;
const BlockDeviceInfo* deviceInfo = device->GetDeviceInfo();
if(device->FindRegionFromAddress( sectAddr, regionIndex, rangeIndex))
{
BlockType = deviceInfo->Regions[ regionIndex ].BlockRanges[ rangeIndex ].RangeType;
// The only blocks that should be distinguished by TinyBooter are CONFIG,
// Bootstrap and reserved blocks (DirtyBit is another version of CONFIG).
if(BlockRange::IsBlockTinyBooterAgnostic(BlockType))
{
BlockType = BlockRange::BLOCKTYPE_CODE;
}
}
else
{
return false;
}
}
else
{
// if not found - RAM
device = NULL;
sectAddr = address;
BlockType = 0;
}
// initial condition
if(m_dataAddress == 0)
{
// We don't verify signature for config sector
m_dataAddress = address;
m_dataLength = length;
m_pDevice = device;
// assume the data bytes per sector is same for all
m_sectorType = BlockType;
// set up the bitField manager
SECTOR_BIT_FIELD p;
g_BitFieldManager.GetNextSectorSignatureCheck( m_pDevice, p );
return true;
}
else
{
if((device != m_pDevice ) || (BlockType != m_sectorType) || ((m_dataAddress + m_dataLength)!= address )) return false;
m_dataLength += length;
}
return true;
}
bool Loader_Engine::SignedDataState::VerifySignature( UINT8* signature, UINT32 length, UINT32 keyIndex )
{
BYTE *signCheckedAddr;
bool fret;
if(
(keyIndex >= ConfigurationSector::c_DeployKeyCount) ||
(length != RSA_BLOCK_SIZE_BYTES)
)
{
EraseMemoryAndReset();
return false;
}
// for RAM device, return
if (m_pDevice == NULL)
{
Reset();
return TRUE;
}
// if it is non-XIP device, need to reload the content from memory to RAM for signature checking.
const BlockDeviceInfo* deviceInfo = m_pDevice->GetDeviceInfo();
if(!deviceInfo->Attribute.SupportsXIP)
{
signCheckedAddr = (BYTE*)malloc(m_dataLength);
if (signCheckedAddr == NULL)
{
EraseMemoryAndReset();
return false;
}
if(!m_pDevice->Read( m_dataAddress, m_dataLength, signCheckedAddr ))
{
EraseMemoryAndReset();
free(signCheckedAddr);
return false;
}
}
else
{
signCheckedAddr = (BYTE *)m_dataAddress;
}
CryptoState st( (UINT32)signCheckedAddr, m_dataLength, signature, length, m_sectorType );
if(st.VerifySignature( keyIndex ))
{
g_BitFieldManager.InvalidateSectorBitField();
Reset();
fret = true;
}
else
{
EraseMemoryAndReset();
fret =false;
}
if(!deviceInfo->Attribute.SupportsXIP)
{
free(signCheckedAddr);
}
return fret;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
static const Loader_Engine::CommandHandlerLookup c_Lookup_Request[] =
{
/*******************************************************************************************************************************************************************/
#define DEFINE_CMD(cmd) { CLR_DBG_Commands::c_Monitor_##cmd, &Loader_Engine::Monitor_##cmd }
DEFINE_CMD(Ping ),
DEFINE_CMD(Reboot ),
//
DEFINE_CMD(ReadMemory ),
DEFINE_CMD(WriteMemory),
DEFINE_CMD(CheckMemory),
DEFINE_CMD(EraseMemory),
//
DEFINE_CMD(Execute ),
DEFINE_CMD(MemoryMap ),
//
DEFINE_CMD(CheckSignature),
//
DEFINE_CMD(FlashSectorMap ),
DEFINE_CMD(SignatureKeyUpdate),
DEFINE_CMD(OemInfo),
#undef DEFINE_CMD
/*******************************************************************************************************************************************************************/
};
static const Loader_Engine::CommandHandlerLookup c_Lookup_Reply[] =
{
/*******************************************************************************************************************************************************************/
#define DEFINE_CMD(cmd) { CLR_DBG_Commands::c_Monitor_##cmd, &Loader_Engine::Monitor_##cmd }
DEFINE_CMD(Ping),
#undef DEFINE_CMD
/*******************************************************************************************************************************************************************/
};
////////////////////////////////////////////////////////////////////////////////////////////////////
bool Loader_Engine::Phy_ReceiveBytes( void* state, UINT8* & ptr, UINT32 & size )
{
Loader_Engine* pThis = (Loader_Engine*)state;
if(size)
{
int read = DebuggerPort_Read( pThis->m_port, (char*)ptr, size ); if(read <= 0) return false;
ptr += read;
size -= read;
}
return true;
}
bool Loader_Engine::Phy_TransmitMessage( void* state, const WP_Message* msg )
{
Loader_Engine* pThis = (Loader_Engine*)state;
return pThis->TransmitMessage( msg, true );
}
//--//
bool Loader_Engine::App_ProcessHeader( void* state, WP_Message* msg )
{
Loader_Engine* pThis = (Loader_Engine*)state;
if(pThis->ProcessHeader( msg ) == false)
{
return false;
}
if(LOADER_ENGINE_ISFLAGSET(pThis, c_LoaderEngineFlag_ReceptionBufferInUse) || msg->m_header.m_size > sizeof(pThis->m_receptionBuffer))
{
return false;
}
msg->m_payload = pThis->m_receptionBuffer;
LOADER_ENGINE_SETFLAG(pThis, c_LoaderEngineFlag_ReceptionBufferInUse);
return true;
}
bool Loader_Engine::App_ProcessPayload( void* state, WP_Message* msg )
{
Loader_Engine* pThis = (Loader_Engine*)state;
// Prevent processing duplicate packets
if((UINT32)msg->m_header.m_seq == pThis->m_lastPacketSequence)
return false; // Do not even respond to a repeat packet
pThis->m_lastPacketSequence = (UINT32)msg->m_header.m_seq;
if(pThis->ProcessPayload( msg ) == false)
{
return false;
}
return true;
}
bool Loader_Engine::App_Release( void* state, WP_Message* msg )
{
Loader_Engine* pThis = (Loader_Engine*)state;
if(msg->m_payload == pThis->m_receptionBuffer)
{
LOADER_ENGINE_CLEARFLAG(pThis, c_LoaderEngineFlag_ReceptionBufferInUse);
msg->m_payload = NULL;
}
return true;
}
//--//
const WP_PhysicalLayer c_Debugger_phy =
{
&Loader_Engine::Phy_ReceiveBytes ,
&Loader_Engine::Phy_TransmitMessage,
};
const WP_ApplicationLayer c_Debugger_app =
{
&Loader_Engine::App_ProcessHeader ,
&Loader_Engine::App_ProcessPayload,
&Loader_Engine::App_Release ,
};
////////////////////////////////////////////////////////////////////////////////////////////////////
HRESULT Loader_Engine::Initialize( COM_HANDLE port )
{
TINYCLR_HEADER();
LOADER_ENGINE_CLEARFLAG(this, c_LoaderEngineFlag_ValidConnection);
m_port = port;
// Initialize to a packet sequence number impossible to encounter
m_lastPacketSequence = 0x00FEFFFF;
m_controller.Initialize( MARKER_DEBUGGER_V1, &c_Debugger_phy, &c_Debugger_app, this );
m_signedDataState.Reset();
g_PrimaryConfigManager.LocateConfigurationSector( BlockUsage::CONFIG );
// make sure we performed signature check during the last programming
g_BitFieldManager.EraseOnSignatureCheckFail();
TINYCLR_NOCLEANUP_NOLABEL();
}
//--//
void Loader_Engine::ProcessCommands()
{
m_controller.AdvanceState();
}
bool Loader_Engine::ProcessHeader( WP_Message* msg )
{
return true;
}
bool Loader_Engine::ProcessPayload( WP_Message* msg )
{
if(msg->m_header.m_flags & WP_Flags::c_NACK)
{
//
// Bad packet...
//
return true;
}
LOADER_ENGINE_SETFLAG( this, c_LoaderEngineFlag_ValidConnection );
//--//
#if defined(NETMF_TARGET_BIG_ENDIAN)
SwapEndian( msg, msg->m_payload, msg->m_header.m_size, false );
#endif
size_t num;
const CommandHandlerLookup* cmd;
if(msg->m_header.m_flags & WP_Flags::c_Reply)
{
num = ARRAYSIZE(c_Lookup_Reply);
cmd = c_Lookup_Reply;
}
else
{
num = ARRAYSIZE(c_Lookup_Request);
cmd = c_Lookup_Request;
}
while(num--)
{