xref: /OK3568_Linux_fs/external/rkupdate/RKAndroidDevice.cpp (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 #include "RKAndroidDevice.h"
2 #define tole(x)     (x)
3 #define look_for_userdata(name) \
4     memcmp(name, PARTNAME_USERDATA, sizeof(PARTNAME_USERDATA) - 1)
5 
6 
7 /*factor is 0xedb88320*/
8 bool CRKAndroidDevice::bGptFlag = 0;
9 extern int sdBootUpdate;
10 
11 char name[PART_NAME];// ��������
12 char file[RELATIVE_PATH];// ���·��������ȡ�ļ�ʱ�õ�
13 unsigned int part_size;//����ռ��������
14 unsigned int offset;// �ļ���Image�е�ƫ��
15 unsigned int flash_offset;// ��д��Flash�е�λ��(��sectorΪ��λ)
16 unsigned int usespace;// �ļ�ռ�ÿռ䣨��PAGE����)
17 unsigned int size;// �ֽ�����ʵ���ļ���С
18 
19 #ifdef USE_SIGNATURE_FW
20 RK_UPDATE_ORDER gstUpdateOrder[] =
21 {
22     {1, "rootfs",     {"", "", 0, 0, 0, 0, 0}, 0},
23     {2, "boot",       {"", "", 0, 0, 0, 0, 0}, 0},
24     {3, "uboot",      {"", "", 0, 0, 0, 0, 0}, 0},
25     {4, "bootloader", {"", "", 0, 0, 0, 0, 0}, 0},
26 };
27 #endif
28 
29 unsigned int crc32table_le[] =
30 {
31     tole(0x00000000L), tole(0x77073096L), tole(0xee0e612cL), tole(0x990951baL),
32     tole(0x076dc419L), tole(0x706af48fL), tole(0xe963a535L), tole(0x9e6495a3L),
33     tole(0x0edb8832L), tole(0x79dcb8a4L), tole(0xe0d5e91eL), tole(0x97d2d988L),
34     tole(0x09b64c2bL), tole(0x7eb17cbdL), tole(0xe7b82d07L), tole(0x90bf1d91L),
35     tole(0x1db71064L), tole(0x6ab020f2L), tole(0xf3b97148L), tole(0x84be41deL),
36     tole(0x1adad47dL), tole(0x6ddde4ebL), tole(0xf4d4b551L), tole(0x83d385c7L),
37     tole(0x136c9856L), tole(0x646ba8c0L), tole(0xfd62f97aL), tole(0x8a65c9ecL),
38     tole(0x14015c4fL), tole(0x63066cd9L), tole(0xfa0f3d63L), tole(0x8d080df5L),
39     tole(0x3b6e20c8L), tole(0x4c69105eL), tole(0xd56041e4L), tole(0xa2677172L),
40     tole(0x3c03e4d1L), tole(0x4b04d447L), tole(0xd20d85fdL), tole(0xa50ab56bL),
41     tole(0x35b5a8faL), tole(0x42b2986cL), tole(0xdbbbc9d6L), tole(0xacbcf940L),
42     tole(0x32d86ce3L), tole(0x45df5c75L), tole(0xdcd60dcfL), tole(0xabd13d59L),
43     tole(0x26d930acL), tole(0x51de003aL), tole(0xc8d75180L), tole(0xbfd06116L),
44     tole(0x21b4f4b5L), tole(0x56b3c423L), tole(0xcfba9599L), tole(0xb8bda50fL),
45     tole(0x2802b89eL), tole(0x5f058808L), tole(0xc60cd9b2L), tole(0xb10be924L),
46     tole(0x2f6f7c87L), tole(0x58684c11L), tole(0xc1611dabL), tole(0xb6662d3dL),
47     tole(0x76dc4190L), tole(0x01db7106L), tole(0x98d220bcL), tole(0xefd5102aL),
48     tole(0x71b18589L), tole(0x06b6b51fL), tole(0x9fbfe4a5L), tole(0xe8b8d433L),
49     tole(0x7807c9a2L), tole(0x0f00f934L), tole(0x9609a88eL), tole(0xe10e9818L),
50     tole(0x7f6a0dbbL), tole(0x086d3d2dL), tole(0x91646c97L), tole(0xe6635c01L),
51     tole(0x6b6b51f4L), tole(0x1c6c6162L), tole(0x856530d8L), tole(0xf262004eL),
52     tole(0x6c0695edL), tole(0x1b01a57bL), tole(0x8208f4c1L), tole(0xf50fc457L),
53     tole(0x65b0d9c6L), tole(0x12b7e950L), tole(0x8bbeb8eaL), tole(0xfcb9887cL),
54     tole(0x62dd1ddfL), tole(0x15da2d49L), tole(0x8cd37cf3L), tole(0xfbd44c65L),
55     tole(0x4db26158L), tole(0x3ab551ceL), tole(0xa3bc0074L), tole(0xd4bb30e2L),
56     tole(0x4adfa541L), tole(0x3dd895d7L), tole(0xa4d1c46dL), tole(0xd3d6f4fbL),
57     tole(0x4369e96aL), tole(0x346ed9fcL), tole(0xad678846L), tole(0xda60b8d0L),
58     tole(0x44042d73L), tole(0x33031de5L), tole(0xaa0a4c5fL), tole(0xdd0d7cc9L),
59     tole(0x5005713cL), tole(0x270241aaL), tole(0xbe0b1010L), tole(0xc90c2086L),
60     tole(0x5768b525L), tole(0x206f85b3L), tole(0xb966d409L), tole(0xce61e49fL),
61     tole(0x5edef90eL), tole(0x29d9c998L), tole(0xb0d09822L), tole(0xc7d7a8b4L),
62     tole(0x59b33d17L), tole(0x2eb40d81L), tole(0xb7bd5c3bL), tole(0xc0ba6cadL),
63     tole(0xedb88320L), tole(0x9abfb3b6L), tole(0x03b6e20cL), tole(0x74b1d29aL),
64     tole(0xead54739L), tole(0x9dd277afL), tole(0x04db2615L), tole(0x73dc1683L),
65     tole(0xe3630b12L), tole(0x94643b84L), tole(0x0d6d6a3eL), tole(0x7a6a5aa8L),
66     tole(0xe40ecf0bL), tole(0x9309ff9dL), tole(0x0a00ae27L), tole(0x7d079eb1L),
67     tole(0xf00f9344L), tole(0x8708a3d2L), tole(0x1e01f268L), tole(0x6906c2feL),
68     tole(0xf762575dL), tole(0x806567cbL), tole(0x196c3671L), tole(0x6e6b06e7L),
69     tole(0xfed41b76L), tole(0x89d32be0L), tole(0x10da7a5aL), tole(0x67dd4accL),
70     tole(0xf9b9df6fL), tole(0x8ebeeff9L), tole(0x17b7be43L), tole(0x60b08ed5L),
71     tole(0xd6d6a3e8L), tole(0xa1d1937eL), tole(0x38d8c2c4L), tole(0x4fdff252L),
72     tole(0xd1bb67f1L), tole(0xa6bc5767L), tole(0x3fb506ddL), tole(0x48b2364bL),
73     tole(0xd80d2bdaL), tole(0xaf0a1b4cL), tole(0x36034af6L), tole(0x41047a60L),
74     tole(0xdf60efc3L), tole(0xa867df55L), tole(0x316e8eefL), tole(0x4669be79L),
75     tole(0xcb61b38cL), tole(0xbc66831aL), tole(0x256fd2a0L), tole(0x5268e236L),
76     tole(0xcc0c7795L), tole(0xbb0b4703L), tole(0x220216b9L), tole(0x5505262fL),
77     tole(0xc5ba3bbeL), tole(0xb2bd0b28L), tole(0x2bb45a92L), tole(0x5cb36a04L),
78     tole(0xc2d7ffa7L), tole(0xb5d0cf31L), tole(0x2cd99e8bL), tole(0x5bdeae1dL),
79     tole(0x9b64c2b0L), tole(0xec63f226L), tole(0x756aa39cL), tole(0x026d930aL),
80     tole(0x9c0906a9L), tole(0xeb0e363fL), tole(0x72076785L), tole(0x05005713L),
81     tole(0x95bf4a82L), tole(0xe2b87a14L), tole(0x7bb12baeL), tole(0x0cb61b38L),
82     tole(0x92d28e9bL), tole(0xe5d5be0dL), tole(0x7cdcefb7L), tole(0x0bdbdf21L),
83     tole(0x86d3d2d4L), tole(0xf1d4e242L), tole(0x68ddb3f8L), tole(0x1fda836eL),
84     tole(0x81be16cdL), tole(0xf6b9265bL), tole(0x6fb077e1L), tole(0x18b74777L),
85     tole(0x88085ae6L), tole(0xff0f6a70L), tole(0x66063bcaL), tole(0x11010b5cL),
86     tole(0x8f659effL), tole(0xf862ae69L), tole(0x616bffd3L), tole(0x166ccf45L),
87     tole(0xa00ae278L), tole(0xd70dd2eeL), tole(0x4e048354L), tole(0x3903b3c2L),
88     tole(0xa7672661L), tole(0xd06016f7L), tole(0x4969474dL), tole(0x3e6e77dbL),
89     tole(0xaed16a4aL), tole(0xd9d65adcL), tole(0x40df0b66L), tole(0x37d83bf0L),
90     tole(0xa9bcae53L), tole(0xdebb9ec5L), tole(0x47b2cf7fL), tole(0x30b5ffe9L),
91     tole(0xbdbdf21cL), tole(0xcabac28aL), tole(0x53b39330L), tole(0x24b4a3a6L),
92     tole(0xbad03605L), tole(0xcdd70693L), tole(0x54de5729L), tole(0x23d967bfL),
93     tole(0xb3667a2eL), tole(0xc4614ab8L), tole(0x5d681b02L), tole(0x2a6f2b94L),
94     tole(0xb40bbe37L), tole(0xc30c8ea1L), tole(0x5a05df1bL), tole(0x2d02ef8dL)
95 };
FindIDBlock(char pos,char & IDBlockPos)96 CHAR CRKAndroidDevice::FindIDBlock(char pos, char &IDBlockPos)
97 {
98     BYTE bData[SECTOR_SIZE * 4];
99     int iRet = ERR_SUCCESS;
100     int i = FindValidBlocks(pos, 1);
101     if (i < 0)
102     {
103         return -1;
104     }
105     for (; i < IDBLOCK_TOP; i = FindValidBlocks(i + 1, 1))
106     {
107         if (i < 0)
108         {
109             break;
110         }
111         memset(bData, 0, SECTOR_SIZE * 4);
112         iRet = m_pComm->RKU_ReadSector(i * m_flashInfo.uiSectorPerBlock, 4, bData);
113 
114         if (ERR_SUCCESS != iRet)
115         {
116             if (m_pLog)
117             {
118                 m_pLog->Record(_T("ERROR:FindIDBlock-->RKU_ReadSector %x failed,RetCode(%d)"), i * m_flashInfo.uiSectorPerBlock, iRet);
119             }
120             return -1;//���ݶ�ȡʧ��
121         }
122         RKANDROID_IDB_SEC0 *pSec0;
123         pSec0 = (RKANDROID_IDB_SEC0 *)bData;
124         P_RC4((BYTE *)pSec0, SECTOR_SIZE);
125         //       if (bData[514]==0x69)//0x69='i'
126         if (pSec0->dwTag == 0x0FF0AA55)
127         {
128             //�����ж�tag
129             RKANDROID_IDB_SEC1 *pSec;
130             pSec = (RKANDROID_IDB_SEC1 *)(bData + SECTOR_SIZE);
131             if (pSec->uiChipTag == 0x38324B52)
132             {
133                 IDBlockPos = i;
134                 return 0;//�ҵ�idb
135             }
136             else
137             {
138                 continue;//tag����
139             }
140         }
141 
142     }
143     return -1;
144 }
FindAllIDB()145 char CRKAndroidDevice::FindAllIDB()
146 {
147     char i, iIndex, iStart = 0;
148     CHAR iRet;
149     m_oldIDBCounts = 0;
150     for (i = 0; i < 5; i++)
151     {
152         iRet = FindIDBlock(iStart, iIndex);
153         if (iRet < 0)
154         {
155             return m_oldIDBCounts;
156         }
157 
158         m_idBlockOffset[i] = iIndex;
159         m_oldIDBCounts++;
160         iStart = iIndex + 1;
161     }
162 
163     return m_oldIDBCounts;
164 }
ReserveIDBlock(char iBlockIndex,char iIdblockPos)165 bool CRKAndroidDevice::ReserveIDBlock(char iBlockIndex, char iIdblockPos)
166 {
167     char i;
168     CHAR iRet;
169     for (i = iIdblockPos; i < IDB_BLOCKS; i++)
170     {
171         iRet = iBlockIndex = FindValidBlocks(iBlockIndex, m_flashInfo.usPhyBlokcPerIDB);
172         if (iRet < 0)
173         {
174             return false;
175         }
176         m_idBlockOffset[i] = iBlockIndex;
177         iBlockIndex += m_flashInfo.usPhyBlokcPerIDB;
178     }
179     return true;
180 }
CalcIDBCount()181 bool CRKAndroidDevice::CalcIDBCount()
182 {
183     bool bRet;
184     UINT uiIdSectorNum;//ID BLOCK������
185 
186     bRet = GetLoaderSize();
187     if (!bRet)
188     {
189         if (m_pLog)
190         {
191             m_pLog->Record(_T("ERROR:CalcIDBCount-->GetLoaderSize failed"));
192         }
193         return false;
194     }
195     bRet = GetLoaderDataSize();
196     if (!bRet)
197     {
198         if (m_pLog)
199         {
200             m_pLog->Record(_T("ERROR:CalcIDBCount-->GetLoaderDataSize failed"));
201         }
202         return false;
203     }
204     if (m_pImage->m_bootObject->IsNewIDBFlag())
205     {
206         if (m_pLog)
207         {
208             m_pLog->Record(_T("INFO:CalcIDBCount IsNewIDBFlag is true"));
209         }
210         bRet = GetLoaderHeadSize();
211         if (!bRet)
212         {
213             if (m_pLog)
214             {
215                 m_pLog->Record(_T("ERROR:CalcIDBCount-->GetLoaderHeadSize failed"));
216             }
217             return false;
218         }
219         uiIdSectorNum = m_usFlashHeadSec + m_usFlashDataSec + m_usFlashBootSec;
220     }
221     else
222     {
223         uiIdSectorNum = 4 + m_usFlashDataSec + m_usFlashBootSec;
224     }
225 
226     m_flashInfo.uiSecNumPerIDB = uiIdSectorNum;
227     m_flashInfo.usPhyBlokcPerIDB = CALC_UNIT(uiIdSectorNum, m_flashInfo.usValidSecPerBlock);
228     return true;
229 }
OffsetIDBlock(char pos)230 bool CRKAndroidDevice::OffsetIDBlock(char pos)
231 {
232     int iBlockIndex, i;
233     for (i = 0; i < m_flashInfo.usPhyBlokcPerIDB; i++)
234     {
235         m_flashInfo.blockState[m_idBlockOffset[pos] + i] = 1; //����ϻ���
236     }
237     iBlockIndex = m_idBlockOffset[pos] + m_flashInfo.usPhyBlokcPerIDB;
238     for (i = pos; i < 5; i++)
239     {
240         iBlockIndex = FindValidBlocks(iBlockIndex, m_flashInfo.usPhyBlokcPerIDB);
241         if (iBlockIndex < 0)
242         {
243             return false;
244         }
245         m_idBlockOffset[i] = iBlockIndex;
246         iBlockIndex += m_flashInfo.usPhyBlokcPerIDB;
247     }
248 
249     return true;
250 }
GetLoaderSize()251 bool CRKAndroidDevice::GetLoaderSize()
252 {
253     if (!m_pImage)
254     {
255         return false;
256     }
257     CHAR index;
258     bool bRet;
259     tchar loaderName[] = _T("FlashBoot");
260     index = m_pImage->m_bootObject->GetIndexByName(ENTRYLOADER, loaderName);
261     if (index == -1)
262     {
263         return false;
264     }
265     DWORD dwDelay;
266     bRet = m_pImage->m_bootObject->GetEntryProperty(ENTRYLOADER, index, m_dwLoaderSize, dwDelay);
267     if (bRet)
268     {
269         m_usFlashBootSec = PAGEALIGN(BYTE2SECTOR(m_dwLoaderSize)) * 4;
270     }
271     return bRet;
272 }
GetLoaderDataSize()273 bool CRKAndroidDevice::GetLoaderDataSize()
274 {
275     if (!m_pImage)
276     {
277         return false;
278     }
279     CHAR index;
280     bool bRet;
281     tchar loaderName[] = _T("FlashData");
282     index = m_pImage->m_bootObject->GetIndexByName(ENTRYLOADER, loaderName);
283     if (index == -1)
284     {
285         return false;
286     }
287     DWORD dwDelay;
288     bRet = m_pImage->m_bootObject->GetEntryProperty(ENTRYLOADER, index, m_dwLoaderDataSize, dwDelay);
289     if (bRet)
290     {
291         m_usFlashDataSec = PAGEALIGN(BYTE2SECTOR(m_dwLoaderDataSize)) * 4;
292     }
293     return bRet;
294 }
295 
GetLoaderHeadSize()296 bool CRKAndroidDevice::GetLoaderHeadSize()
297 {
298     if (!m_pImage)
299     {
300         return false;
301     }
302     char index;
303     bool bRet;
304     tchar loaderName[] = _T("FlashHead");
305     index = m_pImage->m_bootObject->GetIndexByName(ENTRYLOADER, loaderName);
306     if (index == -1)
307     {
308         return false;
309     }
310     DWORD dwDelay;
311     bRet = m_pImage->m_bootObject->GetEntryProperty(ENTRYLOADER, index, m_dwLoaderHeadSize, dwDelay);
312     if (bRet)
313     {
314         m_usFlashHeadSec = PAGEALIGN(BYTE2SECTOR(m_dwLoaderHeadSize)) * 4;
315     }
316     return bRet;
317 }
318 
CRKAndroidDevice(STRUCT_RKDEVICE_DESC & device)319 CRKAndroidDevice::CRKAndroidDevice(STRUCT_RKDEVICE_DESC &device): CRKDevice(device)
320 {
321     m_oldSec0 = NULL;
322     m_oldSec1 = NULL;
323     m_oldSec2 = NULL;
324     m_oldSec3 = NULL;
325     m_dwLoaderSize = 0;
326     m_dwLoaderDataSize = 0;
327     m_dwLoaderHeadSize = 0;
328     m_oldIDBCounts = 0;
329     m_usFlashBootSec = 0;
330     m_usFlashDataSec = 0;
331     m_usFlashHeadSec = 0;
332     m_dwBackupOffset = 0xFFFFFFFF;
333     m_paramBuffer = NULL;
334     m_pCallback = NULL;
335     m_pProcessCallback = NULL;
336 }
~CRKAndroidDevice()337 CRKAndroidDevice::~CRKAndroidDevice()
338 {
339     if (m_oldSec0)
340     {
341         delete m_oldSec0;
342         m_oldSec0 = NULL;
343     }
344     if (m_oldSec1)
345     {
346         delete m_oldSec1;
347         m_oldSec1 = NULL;
348     }
349     if (m_oldSec2)
350     {
351         delete m_oldSec2;
352         m_oldSec2 = NULL;
353     }
354     if (m_oldSec3)
355     {
356         delete m_oldSec3;
357         m_oldSec3 = NULL;
358     }
359     if (m_paramBuffer)
360     {
361         delete []m_paramBuffer;
362         m_paramBuffer = NULL;
363     }
364 }
GetOldSectorData()365 bool CRKAndroidDevice::GetOldSectorData()
366 {
367     BYTE bData[SECTOR_SIZE * 4];
368 
369     if (m_oldIDBCounts <= 0)
370     {
371         return false;
372     }
373 
374     if (!GetWriteBackData(m_oldIDBCounts, bData))
375     {
376         if (m_pLog)
377         {
378             m_pLog->Record(_T("ERROR:GetOldSectorData-->GetWriteBackData failed"));
379         }
380         return false;//���ݶ�ȡʧ��
381     }
382     PBYTE pSec;
383     if (!m_oldSec0)
384     {
385         m_oldSec0 = new RKANDROID_IDB_SEC0;
386     }
387     pSec = (PBYTE)(m_oldSec0);
388     memset(pSec, 0, SECTOR_SIZE);
389     memcpy(pSec, bData, SECTOR_SIZE);
390     P_RC4(pSec, SECTOR_SIZE);
391 
392     if (!m_oldSec1)
393     {
394         m_oldSec1 = new RKANDROID_IDB_SEC1;
395     }
396     pSec = (PBYTE)(m_oldSec1);
397     memset(pSec, 0, SECTOR_SIZE);
398     memcpy(pSec, bData + 512, SECTOR_SIZE);
399 
400     if (!m_oldSec2)
401     {
402         m_oldSec2 = new RKANDROID_IDB_SEC2;
403     }
404     pSec = (PBYTE)(m_oldSec2);
405     memset(pSec, 0, SECTOR_SIZE);
406     memcpy(pSec, bData + 512 * 2, SECTOR_SIZE);
407     P_RC4(pSec, SECTOR_SIZE);
408 
409     if (!m_oldSec3)
410     {
411         m_oldSec3 = new RKANDROID_IDB_SEC3;
412     }
413     pSec = (PBYTE)(m_oldSec3);
414     memset(pSec, 0, SECTOR_SIZE);
415     memcpy(pSec, bData + 512 * 3, SECTOR_SIZE);
416     P_RC4(pSec, SECTOR_SIZE);
417 
418     return true;
419 
420 }
MakeSector0(PBYTE pSector)421 bool CRKAndroidDevice::MakeSector0(PBYTE pSector)
422 {
423     PRKANDROID_IDB_SEC0 pSec0;
424     memset(pSector, 0, SECTOR_SIZE);
425     pSec0 = (PRKANDROID_IDB_SEC0)pSector;
426 
427     pSec0->dwTag = 0x0FF0AA55;
428     if (m_pImage->m_bootObject->Rc4DisableFlag)
429     {
430         pSec0->uiRc4Flag = 1;
431     }
432     pSec0->usBootCode1Offset = 0x4;
433     pSec0->usBootCode2Offset = 0x4;
434     pSec0->usBootDataSize = m_usFlashDataSec;
435     pSec0->usBootCodeSize = m_usFlashDataSec + m_usFlashBootSec;
436 
437     //  pSec0->usCrc = CRC_16(pSector,SECTOR_SIZE-2);
438     return true;
439 }
440 
MakeSector1(PBYTE pSector)441 void CRKAndroidDevice::MakeSector1(PBYTE pSector)
442 {
443     PRKANDROID_IDB_SEC1 pSec1;
444     memset(pSector, 0, SECTOR_SIZE);
445     pSec1 = (PRKANDROID_IDB_SEC1)pSector;
446     USHORT usSysReserved;
447     if ((m_idBlockOffset[4] + 1) % 12 == 0)
448     {
449         usSysReserved = m_idBlockOffset[4] + 13;
450     }
451     else
452     {
453         usSysReserved = ((m_idBlockOffset[4] + 1) / 12 + 1) * 12;
454     }
455     if (usSysReserved > IDBLOCK_TOP)
456     {
457         usSysReserved = IDBLOCK_TOP;
458     }
459     pSec1->usSysReservedBlock = usSysReserved;
460 
461 
462     pSec1->usDisk0Size = 0;
463     pSec1->usDisk1Size = 0;
464     pSec1->usDisk2Size = 0;
465     pSec1->usDisk3Size = 0;
466     pSec1->uiChipTag = 0x38324B52;
467     pSec1->uiMachineId = 0;
468     pSec1->usLoaderYear = UshortToBCD(((STRUCT_RKTIME)m_pImage->m_bootObject->ReleaseTime).usYear);
469     pSec1->usLoaderDate = ByteToBCD(((STRUCT_RKTIME)m_pImage->m_bootObject->ReleaseTime).ucMonth);
470     pSec1->usLoaderDate = (pSec1->usLoaderDate << 8) | ByteToBCD(((STRUCT_RKTIME)m_pImage->m_bootObject->ReleaseTime).ucDay);
471     pSec1->usLoaderVer =  m_pImage->m_bootObject->Version;
472     if (m_oldSec1)
473     {
474         pSec1->usLastLoaderVer = m_oldSec1->usLoaderVer;
475         pSec1->usReadWriteTimes = m_oldSec1->usReadWriteTimes + 1;
476     }
477     else
478     {
479         pSec1->usLastLoaderVer = 0;
480         pSec1->usReadWriteTimes = 1;
481     }
482     pSec1->uiFlashSize = m_flashInfo.uiFlashSize * 2 * 1024;
483     pSec1->usBlockSize = m_flashInfo.usBlockSize * 2;
484     pSec1->bPageSize = m_flashInfo.uiPageSize * 2;
485     pSec1->bECCBits = m_flashInfo.bECCBits;
486     pSec1->bAccessTime = m_flashInfo.bAccessTime;
487 
488     pSec1->usFlashInfoLen = 0;
489     pSec1->usFlashInfoOffset = 0;
490 
491 
492     pSec1->usIdBlock0 = m_idBlockOffset[0];
493     pSec1->usIdBlock1 = m_idBlockOffset[1];
494     pSec1->usIdBlock2 = m_idBlockOffset[2];
495     pSec1->usIdBlock3 = m_idBlockOffset[3];
496     pSec1->usIdBlock4 = m_idBlockOffset[4];
497 }
MakeSector2(PBYTE pSector)498 bool CRKAndroidDevice::MakeSector2(PBYTE pSector)
499 {
500     PRKANDROID_IDB_SEC2 pSec2;
501     pSec2 = (PRKANDROID_IDB_SEC2)pSector;
502 
503     pSec2->usInfoSize = 0;
504     memset(pSec2->bChipInfo, 0, CHIPINFO_LEN);
505 
506     if (m_oldSec2)
507     {
508         memcpy(pSec2->reserved, m_oldSec2->reserved, RKANDROID_SEC2_RESERVED_LEN);
509         pSec2->usSec3CustomDataOffset = m_oldSec2->usSec3CustomDataOffset;
510         pSec2->usSec3CustomDataSize = m_oldSec2->usSec3CustomDataSize;
511     }
512     else
513     {
514         memset(pSec2->reserved, 0, RKANDROID_SEC2_RESERVED_LEN);
515         pSec2->usSec3CustomDataOffset = m_usWriteBackCustomDataOffset;
516         pSec2->usSec3CustomDataSize = m_usWriteBackCustomDataSize;
517     }
518 
519     strcpy(pSec2->szVcTag, "VC");
520     strcpy(pSec2->szCrcTag, "CRC");
521     return true;
522 }
MakeSector3(PBYTE pSector)523 bool CRKAndroidDevice::MakeSector3(PBYTE pSector)
524 {
525     PRKANDROID_IDB_SEC3 pSec3;
526     memset(pSector, 0, SECTOR_SIZE);
527     pSec3 = (PRKANDROID_IDB_SEC3)pSector;
528 
529     if (m_oldSec3)
530     {
531         memcpy(pSector, (PBYTE)m_oldSec3, SECTOR_SIZE);
532     }
533     else
534     {
535         if (m_backupBuffer)
536         {
537             memcpy(pSector, (PBYTE)m_backupBuffer, SECTOR_SIZE);
538         }
539     }
540 
541 
542     if (m_uid)
543     {
544         if ((m_oldSec3) || (m_backupBuffer))
545         {
546             if (!CheckUid(pSec3->uidSize, pSec3->uid))
547             {
548                 pSec3->uidSize = RKDEVICE_UID_LEN;
549                 memcpy(pSec3->uid, m_uid, RKDEVICE_UID_LEN);
550             }
551         }
552         else
553         {
554             pSec3->uidSize = RKDEVICE_UID_LEN;
555             memcpy(pSec3->uid, m_uid, RKDEVICE_UID_LEN);
556         }
557     }
558 
559     return true;
560 }
MakeIDBlockData(PBYTE lpIDBlock)561 int CRKAndroidDevice::MakeIDBlockData(PBYTE lpIDBlock)
562 {
563     if (m_pLog)
564     {
565         m_pLog->Record(_T("INFO:MakeIDBlockData in"));
566     }
567     RKANDROID_IDB_SEC0 sector0Info;
568     RKANDROID_IDB_SEC1 sector1Info;
569     RKANDROID_IDB_SEC2 sector2Info;
570     RKANDROID_IDB_SEC3 sector3Info;
571 
572     if (!m_pImage)
573     {
574         if (m_pLog)
575         {
576             m_pLog->Record(_T("ERROR:MakeIDBlockData-->Image is invalid"));
577         }
578         return -1;
579     }
580     CHAR index;
581     tchar loaderCodeName[] = _T("FlashBoot");
582     index = m_pImage->m_bootObject->GetIndexByName(ENTRYLOADER, loaderCodeName);
583     if (index == -1)
584     {
585         if (m_pLog)
586         {
587             m_pLog->Record(_T("ERROR:MakeIDBlockData-->Get LoaderCode Entry failed"));
588         }
589         return -2;
590     }
591     PBYTE loaderCodeBuffer;
592     loaderCodeBuffer = new BYTE[m_dwLoaderSize];
593     memset(loaderCodeBuffer, 0, m_dwLoaderSize);
594     if (!m_pImage->m_bootObject->GetEntryData(ENTRYLOADER, index, loaderCodeBuffer))
595     {
596         if (m_pLog)
597         {
598             m_pLog->Record(_T("ERROR:MakeIDBlockData-->Get LoaderCode Data failed"));
599         }
600         delete []loaderCodeBuffer;
601         return -3;
602     }
603 
604     tchar loaderDataName[] = _T("FlashData");
605     index = m_pImage->m_bootObject->GetIndexByName(ENTRYLOADER, loaderDataName);
606     if (index == -1)
607     {
608         if (m_pLog)
609         {
610             m_pLog->Record(_T("ERROR:MakeIDBlockData-->Get LoaderData Entry failed"));
611         }
612         delete []loaderCodeBuffer;
613         return -4;
614     }
615     PBYTE loaderDataBuffer;
616     loaderDataBuffer = new BYTE[m_dwLoaderDataSize];
617     memset(loaderDataBuffer, 0, m_dwLoaderDataSize);
618     if (!m_pImage->m_bootObject->GetEntryData(ENTRYLOADER, index, loaderDataBuffer))
619     {
620         if (m_pLog)
621         {
622             m_pLog->Record(_T("ERROR:MakeIDBlockData-->Get LoaderData Data failed"));
623         }
624         delete []loaderDataBuffer;
625         delete []loaderCodeBuffer;
626         return -5;
627     }
628 
629     ////////////// �������� ////////////////////////////////////////////
630     UINT i;
631     MakeSector0((PBYTE)&sector0Info);
632     MakeSector1((PBYTE)&sector1Info);
633     if (!MakeSector2((PBYTE)&sector2Info))
634     {
635         if (m_pLog)
636         {
637             m_pLog->Record(_T("ERROR:MakeIDBlockData-->MakeSector2 failed"));
638         }
639         return -6;
640     }
641     if (!MakeSector3((PBYTE)&sector3Info))
642     {
643         if (m_pLog)
644         {
645             m_pLog->Record(_T("ERROR:MakeIDBlockData-->MakeSector3 failed"));
646         }
647         return -7;
648     }
649     sector2Info.usSec0Crc = CRC_16((PBYTE)&sector0Info, SECTOR_SIZE);
650     sector2Info.usSec1Crc = CRC_16((PBYTE)&sector1Info, SECTOR_SIZE);
651     sector2Info.usSec3Crc = CRC_16((PBYTE)&sector3Info, SECTOR_SIZE);
652 
653     memcpy(lpIDBlock, &sector0Info, SECTOR_SIZE);
654     memcpy(lpIDBlock + SECTOR_SIZE, &sector1Info, SECTOR_SIZE);
655     //  memcpy(lpIDBlock+SECTOR_SIZE*2, &sector2Info, SECTOR_SIZE);
656     memcpy(lpIDBlock + SECTOR_SIZE * 3, &sector3Info, SECTOR_SIZE);
657 
658     if (sector0Info.uiRc4Flag)
659     {
660         //close rc4 encryption
661         for (i = 0; i < m_dwLoaderDataSize / SECTOR_SIZE; i++)
662         {
663             P_RC4(loaderDataBuffer + SECTOR_SIZE * i, SECTOR_SIZE);
664         }
665         for (i = 0; i < m_dwLoaderSize / SECTOR_SIZE; i++)
666         {
667             P_RC4(loaderCodeBuffer + SECTOR_SIZE * i, SECTOR_SIZE);
668         }
669     }
670 
671     memcpy(lpIDBlock + SECTOR_SIZE * 4, loaderDataBuffer, m_dwLoaderDataSize);
672     memcpy(lpIDBlock + SECTOR_SIZE * (4 + m_usFlashDataSec), loaderCodeBuffer, m_dwLoaderSize);
673 
674     sector2Info.uiBootCodeCrc = CRC_32((PBYTE)(lpIDBlock + SECTOR_SIZE * 4), sector0Info.usBootCodeSize * SECTOR_SIZE);
675     memcpy(lpIDBlock + SECTOR_SIZE * 2, &sector2Info, SECTOR_SIZE);
676 
677     for (i = 0; i < 4; i++)
678     {
679         if (i == 1)
680         {
681             continue;
682         }
683         else
684         {
685             P_RC4(lpIDBlock + SECTOR_SIZE * i, SECTOR_SIZE);
686         }
687     }
688 
689     delete []loaderDataBuffer;
690     delete []loaderCodeBuffer;
691     if (m_pLog)
692     {
693         m_pLog->Record(_T("INFO:MakeIDBlockData out"));
694     }
695     return 0;
696 }
697 
MakeNewIDBlockData(PBYTE lpIDBlock)698 int CRKAndroidDevice::MakeNewIDBlockData(PBYTE lpIDBlock)
699 {
700     int i;
701 
702     if (m_pLog)
703     {
704         m_pLog->Record(_T("INFO:MakeNewIDBlockData in"));
705     }
706 
707     if (!m_pImage)
708     {
709         if (m_pLog)
710         {
711             m_pLog->Record(_T("ERROR:MakeNewIDBlockData-->Image is invalid"));
712         }
713         return -1;
714     }
715     char index;
716     tchar loaderCodeName[] = _T("FlashBoot");
717     index = m_pImage->m_bootObject->GetIndexByName(ENTRYLOADER, loaderCodeName);
718     if (index == -1)
719     {
720         if (m_pLog)
721         {
722             m_pLog->Record(_T("ERROR:MakeNewIDBlockData-->Get LoaderCode Entry failed"));
723         }
724         return -2;
725     }
726     PBYTE loaderCodeBuffer;
727     loaderCodeBuffer = new BYTE[m_dwLoaderSize];
728     memset(loaderCodeBuffer, 0, m_dwLoaderSize);
729     if (!m_pImage->m_bootObject->GetEntryData(ENTRYLOADER, index, loaderCodeBuffer))
730     {
731         if (m_pLog)
732         {
733             m_pLog->Record(_T("ERROR:MakeNewIDBlockData-->Get LoaderCode Data failed"));
734         }
735         delete []loaderCodeBuffer;
736         return -3;
737     }
738 
739     tchar loaderDataName[] = _T("FlashData");
740     index = m_pImage->m_bootObject->GetIndexByName(ENTRYLOADER, loaderDataName);
741     if (index == -1)
742     {
743         if (m_pLog)
744         {
745             m_pLog->Record(_T("ERROR:MakeNewIDBlockData-->Get LoaderData Entry failed"));
746         }
747         delete []loaderCodeBuffer;
748         return -4;
749     }
750     PBYTE loaderDataBuffer;
751     loaderDataBuffer = new BYTE[m_dwLoaderDataSize];
752     memset(loaderDataBuffer, 0, m_dwLoaderDataSize);
753     if (!m_pImage->m_bootObject->GetEntryData(ENTRYLOADER, index, loaderDataBuffer))
754     {
755         if (m_pLog)
756         {
757             m_pLog->Record(_T("ERROR:MakeNewIDBlockData-->Get LoaderData Data failed"));
758         }
759         delete []loaderDataBuffer;
760         delete []loaderCodeBuffer;
761         return -5;
762     }
763 
764     tchar loaderHeadName[] = _T("FlashHead");
765     index = m_pImage->m_bootObject->GetIndexByName(ENTRYLOADER, loaderHeadName);
766     if (index == -1)
767     {
768         if (m_pLog)
769         {
770             m_pLog->Record(_T("ERROR:MakeNewIDBlockData-->Get LoaderHead Entry failed"));
771         }
772         delete []loaderDataBuffer;
773         delete []loaderCodeBuffer;
774         return -6;
775     }
776     PBYTE loaderHeadBuffer;
777     loaderHeadBuffer = new BYTE[m_dwLoaderHeadSize];
778     memset(loaderHeadBuffer, 0, m_dwLoaderHeadSize);
779     if (!m_pImage->m_bootObject->GetEntryData(ENTRYLOADER, index, loaderHeadBuffer))
780     {
781         if (m_pLog)
782         {
783             m_pLog->Record(_T("ERROR:MakeNewIDBlockData-->Get LoaderHead Data failed"));
784         }
785         delete []loaderDataBuffer;
786         delete []loaderCodeBuffer;
787         delete []loaderHeadBuffer;
788         return -7;
789     }
790 
791     if (m_pImage->m_bootObject->Rc4DisableFlag)
792     {
793         //close rc4 encryption
794         for (i = 0; i < m_dwLoaderHeadSize / SECTOR_SIZE; i++)
795         {
796             P_RC4(loaderHeadBuffer + SECTOR_SIZE * i, SECTOR_SIZE);
797         }
798         for (i = 0; i < m_dwLoaderDataSize / SECTOR_SIZE; i++)
799         {
800             P_RC4(loaderDataBuffer + SECTOR_SIZE * i, SECTOR_SIZE);
801         }
802         for (i = 0; i < m_dwLoaderSize / SECTOR_SIZE; i++)
803         {
804             P_RC4(loaderCodeBuffer + SECTOR_SIZE * i, SECTOR_SIZE);
805         }
806     }
807     memcpy(lpIDBlock, loaderHeadBuffer, m_dwLoaderHeadSize);
808     memcpy(lpIDBlock + SECTOR_SIZE * m_usFlashHeadSec, loaderDataBuffer, m_dwLoaderDataSize);
809     memcpy(lpIDBlock + SECTOR_SIZE * (m_usFlashHeadSec + m_usFlashDataSec), loaderCodeBuffer, m_dwLoaderSize);
810 
811 
812     delete []loaderDataBuffer;
813     delete []loaderCodeBuffer;
814     delete []loaderHeadBuffer;
815 
816     if (m_pLog)
817     {
818         m_pLog->Record(_T("INFO:MakeNewIDBlockData out"));
819     }
820     return 0;
821 }
822 
MakeSpareData(PBYTE lpIDBlock,DWORD dwSectorNum,PBYTE lpSpareBuffer)823 bool CRKAndroidDevice::MakeSpareData(PBYTE lpIDBlock, DWORD dwSectorNum, PBYTE lpSpareBuffer)
824 {
825     int i = 0;
826     BYTE bchOutBuf[512 + 3 + 13];
827     BYTE bchInBuf[512 + 3];
828 
829     for (i = 0; i < dwSectorNum; i++)
830     {
831         memcpy(bchInBuf, lpIDBlock + 512 * i, 512);
832         bchInBuf[514] = ((i == 0) ? 'i' : 0xff);
833         bchInBuf[512] = 0xff;
834         bchInBuf[513] = 0xff;
835         //��bchInBuf����BCH���루����13���ֽڵı��룩�����ɵ�bchOutBuf(528 Bytes)
836         //��bchInBuf(515 Bytes)��BCH����(13 Bytes)���
837         bch_encode(bchInBuf, bchOutBuf);
838         memcpy(lpSpareBuffer + i * 16 + 3, bchOutBuf + 515, 13);
839     }
840     lpSpareBuffer[2] = 'i';
841     return true;
842 }
843 
WriteIDBlock(PBYTE lpIDBlock,DWORD dwSectorNum,bool bErase)844 int CRKAndroidDevice::WriteIDBlock(PBYTE lpIDBlock, DWORD dwSectorNum, bool bErase)
845 {
846     if (m_pLog)
847     {
848         m_pLog->Record(_T("INFO:WriteIDBlock in"));
849         m_pLog->Record(_T("INFO:---------------------"));
850     }
851 
852     UINT uiBufferSize = 16 * 1024;
853     int iRet, i, nTryCount = 3;
854     UINT uiTotal;
855     uiTotal = dwSectorNum * SECTOR_SIZE;
856 
857     while (nTryCount > 0)
858     {
859         m_pLog->Record(_T("dwSectorNum=%d"), dwSectorNum);
860         m_pLog->Record(_T("uiTotal=%d\n"), uiTotal);
861 
862         //iRet = m_pComm->RKU_EndWriteSector((BYTE*)&end_write_sector_data);
863         for (i = 0; i <= 4; i++)
864         {
865             iRet = m_pComm->RKU_LoaderWriteLBA(64 + i * 1024, dwSectorNum, lpIDBlock);
866             if (iRet != ERR_SUCCESS)
867             {
868                 if (m_pLog)
869                 {
870                     m_pLog->Record(_T("ERROR:WriteIDBlock-->RKU_WriteSector failed!"));
871                 }
872                 return -1;
873             }
874         }
875 
876         if (iRet == ERR_SUCCESS)
877         {
878             break;
879         }
880         nTryCount--;
881     }
882 
883     if (nTryCount <= 0)
884     {
885         return -2;
886     }
887 
888     if (m_pLog)
889     {
890         m_pLog->Record(_T("INFO:WriteIDBlock out"));
891     }
892     return 0;
893 }
894 
PrepareIDB()895 int CRKAndroidDevice::PrepareIDB()
896 {
897     int i;
898     generate_gf();
899     gen_poly();
900     string strInfo = "";
901     char szTmp[32];
902     bool bFirstCS = false;
903 
904     #if 0   //chad.ma closed 2018/09/27
905     for (i = 0; i < 8; i++)
906     {
907         if (m_flashInfo.bFlashCS & (1 << i))
908         {
909             if (i == 0)
910             {
911                 bFirstCS = true;
912             }
913             if (m_pLog)
914             {
915                 m_pLog->Record(_T("INFO:CS(%d)\t\t(%dMB)\t\t(%s)"), i + 1, m_flashInfo.uiFlashSize, m_flashInfo.szManufacturerName);
916             }
917         }
918     }
919     if (!bFirstCS)
920     {
921         if (m_pLog)
922         {
923             m_pLog->Record(_T("ERROR:PrepareIDB-->No Found 1st Flash CS"));
924         }
925         return -1;
926     }
927 
928     if (!BuildBlockStateMap(0))
929     {
930         if (m_pLog)
931         {
932             m_pLog->Record(_T("ERROR:PrepareIDB-->BuildBlockStateMap failed"));
933         }
934         return -2;
935     }
936 
937     FindAllIDB();
938 
939     if (m_pLog)
940     {
941         m_pLog->Record(_T("ERROR:PrepareIDB-->IDblock count=%d."), m_oldIDBCounts);
942     }
943 
944     memset(m_backupBuffer, 0, SECTOR_SIZE);
945 
946     if (m_oldIDBCounts > 0)
947     {
948         if (m_pLog)
949         {
950             strInfo = "";
951             for (i = 0; i < m_oldIDBCounts; i++)
952             {
953                 sprintf(szTmp, "%d ", m_idBlockOffset[i]);
954                 strInfo += szTmp;
955             }
956             m_pLog->Record(_T("ERROR:PrepareIDB-->IDblock offset=%s."), strInfo.c_str());
957         }
958         BYTE buffer[4 * SECTOR_SIZE];
959         PRKANDROID_IDB_SEC3 pSec;
960         PRKANDROID_IDB_SEC2 pSec2;
961         pSec2 = (PRKANDROID_IDB_SEC2)(buffer + 2 * SECTOR_SIZE);
962         pSec = (PRKANDROID_IDB_SEC3)(buffer + 3 * SECTOR_SIZE);
963 
964         if (!GetWriteBackData(m_oldIDBCounts, buffer))
965         {
966             if (m_pLog)
967             {
968                 m_pLog->Record(_T("ERROR:PrepareIDB-->GetWriteBackData failed"));
969             }
970             return -3;
971         }
972         P_RC4((PBYTE)pSec2, SECTOR_SIZE);
973         P_RC4((PBYTE)pSec, SECTOR_SIZE);
974         IsExistSector3Crc(pSec2);
975 
976         m_usWriteBackCrc = CRC_16((PBYTE)pSec, SECTOR_SIZE);
977         if (m_bExistSector3Crc)
978         {
979             m_usWriteBackCustomDataOffset = pSec2->usSec3CustomDataOffset;
980             m_usWriteBackCustomDataSize = pSec2->usSec3CustomDataSize;
981             if (m_usSector3Crc != m_usWriteBackCrc)
982             {
983                 if (m_pLog)
984                 {
985                     m_pLog->Record(_T("ERROR:PrepareIDB-->Check sector3 crc failed"));
986                 }
987             }
988         }
989         memcpy(m_backupBuffer, pSec, SECTOR_SIZE);
990     }
991     else
992     {
993         FindBackupBuffer();
994     }
995 
996     if (m_oldIDBCounts > 0)
997     {
998         if (!GetOldSectorData())
999         {
1000             if (m_pLog)
1001             {
1002                 m_pLog->Record(_T("ERROR:PrepareIDB-->GetOldSectorData failed"));
1003             }
1004             return -4;
1005         }
1006     }
1007     #endif
1008 
1009     if (!CalcIDBCount())
1010     {
1011         if (m_pLog)
1012         {
1013             m_pLog->Record(_T("ERROR:PrepareIDB-->CalcIDBCount failed"));
1014         }
1015         return -5;
1016     }
1017     if (!ReserveIDBlock())
1018     {
1019         if (m_pLog)
1020         {
1021             m_pLog->Record(_T("ERROR:PrepareIDB-->ReserveIDBlock failed"));
1022         }
1023         return -6;
1024     }
1025     if (m_pLog)
1026     {
1027         strInfo = "";
1028         for (i = 0; i < 5; i++)
1029         {
1030             sprintf(szTmp, "%d ", m_idBlockOffset[i]);
1031             strInfo += szTmp;
1032         }
1033         m_pLog->Record(_T("ERROR:PrepareIDB-->New IDblock offset=%s."), strInfo.c_str());
1034     }
1035 
1036     return 0;
1037 }
1038 
DownloadIDBlock()1039 int CRKAndroidDevice::DownloadIDBlock()
1040 {
1041     DWORD dwSectorNum;
1042     dwSectorNum = m_flashInfo.uiSecNumPerIDB;
1043 
1044     PBYTE pIDBData = NULL;
1045     pIDBData = new BYTE[dwSectorNum * SECTOR_SIZE];
1046     if (!pIDBData)
1047     {
1048         return -1;
1049     }
1050 
1051     int iRet = 0;
1052     memset(pIDBData, 0, dwSectorNum * SECTOR_SIZE);
1053 
1054     // iRet = MakeIDBlockData(pIDBData);
1055     if (m_pImage->m_bootObject->IsNewIDBFlag())
1056     {
1057         if (m_pLog)
1058         {
1059             m_pLog->Record(_T("INFO:DownloadIDBlock-->IsNewIDBFlag is true"), iRet);
1060         }
1061         iRet = MakeNewIDBlockData(pIDBData);
1062     }
1063     else
1064     {
1065         iRet = MakeIDBlockData(pIDBData);
1066     }
1067 
1068     if (iRet != 0)
1069     {
1070         if (m_pLog)
1071         {
1072             m_pLog->Record(_T("ERROR:DownloadIDBlock-->MakeIDBlockData failed,RetCode(%d)"), iRet);
1073         }
1074         return -2;
1075     }
1076 
1077     iRet = WriteIDBlock(pIDBData, dwSectorNum, false);
1078     delete []pIDBData;
1079     if (iRet == 0)
1080     {
1081         return 0;
1082     }
1083     else
1084     {
1085         if (m_pLog)
1086         {
1087             m_pLog->Record(_T("ERROR:DownloadIDBlock-->WriteIDBlock failed,RetCode(%d)"), iRet);
1088         }
1089         //BufferWriteBack();
1090         return -3;
1091     }
1092 }
1093 
IsExistPartitionInFw(const char * partName,UINT & offset,UINT & size)1094 bool CRKAndroidDevice::IsExistPartitionInFw(const char *partName, UINT &offset, UINT &size)
1095 {
1096     bool bRet;
1097     long long dwFwOffset;
1098     bool  bFound = false;
1099     STRUCT_RKIMAGE_HDR rkImageHead;
1100     int iHeadSize;
1101 
1102     dwFwOffset = m_pImage->FWOffset;
1103     iHeadSize = sizeof(STRUCT_RKIMAGE_HDR);
1104 
1105     bRet = m_pImage->GetData(dwFwOffset, iHeadSize, (PBYTE)&rkImageHead);
1106     if (!bRet)
1107     {
1108         return false;
1109     }
1110     if (rkImageHead.item_count <= 0)
1111     {
1112         return false;
1113     }
1114 
1115     /* get partition size and offset in fw data to buffer */
1116     long long partitionSize;
1117     long long partitionOffset;
1118 
1119     for (int i = 0; i < rkImageHead.item_count; i++)
1120     {
1121         if (strncmp(rkImageHead.item[i].name, partName, strlen(partName)) != 0)
1122         {
1123             continue;
1124         }
1125 
1126         if (rkImageHead.item[i].file[55] == 'H')
1127         {
1128             partitionSize = *((DWORD *)(&rkImageHead.item[i].file[56]));
1129             partitionSize <<= 32;
1130             partitionSize += rkImageHead.item[i].size;
1131         }
1132         else
1133         {
1134             partitionSize = rkImageHead.item[i].size;
1135         }
1136 
1137         partitionOffset = rkImageHead.item[i].offset;
1138         offset         = (UINT)partitionOffset;
1139         size           = (UINT)partitionSize;
1140         bFound = true;
1141 
1142         break;
1143     }
1144 
1145     return bFound;
1146 }
1147 
IsExistBootloaderInFw()1148 bool CRKAndroidDevice::IsExistBootloaderInFw()
1149 {
1150     bool bRet;
1151     long long dwFwOffset;
1152     bool  bExistLoader = false;
1153     FILE *pfPackageFile = NULL;
1154     STRUCT_RKIMAGE_HDR rkImageHead;
1155     PBYTE pBuffer = NULL;
1156     int iHeadSize;
1157 
1158     dwFwOffset = m_pImage->FWOffset;
1159     iHeadSize = sizeof(STRUCT_RKIMAGE_HDR);
1160     bRet = m_pImage->GetData(dwFwOffset, iHeadSize, (PBYTE)&rkImageHead);
1161 
1162     if (!bRet)
1163     {
1164         return false;
1165     }
1166     if (rkImageHead.item_count <= 0)
1167     {
1168         return false;
1169     }
1170 
1171     const char *package_name = "/tmp/package-file";
1172     pfPackageFile = fopen(package_name, "wb+");
1173     if (!pfPackageFile)
1174     {
1175         printf("open %s fail !\n", package_name);
1176         return false;
1177     }
1178 
1179     /* get package-file data to buffer */
1180     long long fileBufferSize;
1181     long long entryStartOffset;
1182     unsigned int uiBufferSize = LBA_TRANSFER_SIZE_16K;
1183 
1184     for (int i = 0; i < rkImageHead.item_count; i++)
1185     {
1186         if (strcmp(rkImageHead.item[i].name, "package-file") != 0)
1187         {
1188             continue;
1189         }
1190 
1191         if (rkImageHead.item[i].file[55] == 'H')
1192         {
1193             fileBufferSize = *((DWORD *)(&rkImageHead.item[i].file[56]));
1194             fileBufferSize <<= 32;
1195             fileBufferSize += rkImageHead.item[i].size;
1196         }
1197         else
1198         {
1199             fileBufferSize = rkImageHead.item[i].size;
1200         }
1201 
1202         if (fileBufferSize > 0)
1203         {
1204             if (rkImageHead.item[i].file[50] == 'H')
1205             {
1206                 entryStartOffset = *((DWORD *)(&rkImageHead.item[i].file[51]));
1207                 entryStartOffset <<= 32;
1208                 entryStartOffset += rkImageHead.item[i].offset;
1209                 entryStartOffset += m_pImage->FWOffset;
1210             }
1211             else
1212             {
1213                 entryStartOffset = m_pImage->FWOffset;
1214                 entryStartOffset += rkImageHead.item[i].offset;
1215             }
1216 
1217             pBuffer = new BYTE[uiBufferSize];
1218             if (!pBuffer)
1219             {
1220                 printf("Err: No enough memory!\n");
1221                 goto END;
1222             }
1223 
1224             unsigned int uiWroteByte = 0;
1225             long long uiEntryOffset = 0;
1226             while (fileBufferSize > 0)
1227             {
1228                 memset(pBuffer, 0, uiBufferSize);
1229                 if (fileBufferSize < uiBufferSize)
1230                 {
1231                     uiWroteByte = fileBufferSize;
1232                 }
1233                 else
1234                 {
1235                     uiWroteByte = uiBufferSize;
1236                 }
1237 
1238                 bRet = m_pImage->GetData(entryStartOffset + uiEntryOffset,
1239                                          uiWroteByte, pBuffer);
1240                 if (!bRet)
1241                 {
1242                     goto END;
1243                 }
1244 
1245                 /* write package-file to file */
1246                 size_t size_wr = 0;
1247                 if (!strcmp(rkImageHead.item[i].name, PARTNAME_PARAMETER))
1248                 {
1249                     size_wr = fwrite(pBuffer + 8, 1, uiWroteByte - 12, pfPackageFile);
1250                 }
1251                 else
1252                 {
1253                     size_wr = fwrite(pBuffer, 1, uiWroteByte, pfPackageFile);
1254                 }
1255 
1256                 if (size_wr != uiWroteByte)
1257                 {
1258                     printf(" ### save %s fail!!! ###\n", rkImageHead.item[i].name);
1259                     goto END;
1260                 }
1261 
1262                 fileBufferSize -= uiWroteByte;
1263                 uiEntryOffset  += uiWroteByte;
1264             }
1265         }
1266 
1267         /* judge whether exist bootloader string in package-file */
1268         ssize_t read;
1269         size_t  len = 0;
1270         char *line = NULL;
1271         fseek(pfPackageFile, 0, SEEK_SET);
1272         while ((read = getline(&line, &len, pfPackageFile)) != -1)
1273         {
1274             printf("%s", line);
1275             int i = 0;
1276 
1277             if (strstr(line, INCLUDE_LOADER) == NULL)
1278             {
1279                 continue;
1280             }
1281             for (i = 0; i < read; i++)
1282             {
1283                 if (line[i] == '#')
1284                 {
1285                     bExistLoader = false;
1286                     break;
1287                 }
1288                 if (line[i] == 'b')
1289                 {
1290                     bExistLoader = true;
1291                     break;
1292                 }
1293             }
1294         }
1295         if (line)
1296         {
1297             free(line);
1298         }
1299     }
1300 
1301 END:
1302     if (pfPackageFile)
1303     {
1304         fclose(pfPackageFile);
1305     }
1306     if (pBuffer)
1307     {
1308         delete []pBuffer;
1309         pBuffer = NULL;
1310     }
1311     return bExistLoader;
1312 }
1313 
isInOrderList(char * partName)1314 static bool isInOrderList(char *partName)
1315 {
1316     bool bExist = false;
1317     int i = 0;
1318     #ifdef USE_SIGNATURE_FW
1319     for (; i < ARRAY_LENGTH(gstUpdateOrder); i++)
1320     {
1321         if (!strcmp(partName, gstUpdateOrder[i].partName))
1322         {
1323             bExist = true;
1324             break;
1325         }
1326     }
1327     #endif
1328     return bExist;
1329 }
1330 
DownloadImage()1331 int CRKAndroidDevice::DownloadImage()
1332 {
1333     long long dwFwOffset;
1334     bool  bRet;
1335     dwFwOffset = m_pImage->FWOffset;
1336     STRUCT_RKIMAGE_HDR rkImageHead;
1337     int i;
1338     int iHeadSize;
1339     char szPrompt[100];
1340     int iParamPos = -1;
1341     bool bFoundParam = false;
1342     bool bFwFromUserdata = false;
1343     long long uiTotalSize = 0;
1344     long long ulItemSize;
1345 
1346     iHeadSize = sizeof(STRUCT_RKIMAGE_HDR);
1347     if (m_pProcessCallback)
1348     {
1349         m_pProcessCallback(0.1, 5);
1350     }
1351     bRet = m_pImage->GetData(dwFwOffset, iHeadSize, (PBYTE)&rkImageHead);
1352     if (!bRet)
1353     {
1354         if (m_pLog)
1355         {
1356             m_pLog->Record(_T("ERROR:DownloadImage-->GetData failed"));
1357         }
1358         return -1;
1359     }
1360     if (rkImageHead.item_count <= 0)
1361     {
1362         if (m_pLog)
1363         {
1364             m_pLog->Record(_T("ERROR:DownloadImage-->No Found item"));
1365         }
1366         return -2;
1367     }
1368 
1369     if (!memcmp(m_pImage->GetFwPath(), "/userdata", 9) ||
1370         !memcmp(m_pImage->GetFwPath(), "/data", 5))
1371     {
1372         bFwFromUserdata = true;
1373     }
1374 
1375     m_dwBackupOffset = 0xFFFFFFFF;
1376     for (i = 0; i < rkImageHead.item_count; i++)
1377     {
1378         if (rkImageHead.item[i].flash_offset != 0xFFFFFFFF)
1379         {
1380             if (strcmp(rkImageHead.item[i].name, PARTNAME_PARAMETER) == 0)
1381             {
1382                 bFoundParam = true;
1383                 iParamPos = i;
1384             }
1385             else
1386             {
1387                 if (strcmp(rkImageHead.item[i].name, PARTNAME_BACKUP) == 0)
1388                 {
1389                     m_dwBackupOffset = rkImageHead.item[i].flash_offset;
1390                 }
1391 
1392                 if (strcmp(rkImageHead.item[i].name, PARTNAME_RECOVERY) == 0 ||
1393                     strcmp(rkImageHead.item[i].name, PARTNAME_MISC) == 0)
1394                 {
1395                     //if find "recovery" or "misc" partition, we ignore,
1396                     //recovery.img update processing in normal system.
1397                     //misc.img not process here.
1398                     if (!sdBootUpdate)
1399                     {
1400                         continue;
1401                     }
1402                 }
1403 
1404                 // if fw is in userdata and fw have userdata partiton, we ignore update userdata partition.
1405                 if (look_for_userdata(rkImageHead.item[i].name) == 0 && bFwFromUserdata)
1406                     continue;
1407 
1408                 if (rkImageHead.item[i].file[55] == 'H')
1409                 {
1410                     ulItemSize = *((DWORD *)(&rkImageHead.item[i].file[56]));
1411                     ulItemSize <<= 32;
1412                     ulItemSize += rkImageHead.item[i].size;
1413                 }
1414                 else
1415                 {
1416                     ulItemSize = rkImageHead.item[i].size;
1417                 }
1418 
1419                 #ifdef USE_SIGNATURE_FW
1420                 for (int idx = 0; idx < ARRAY_LENGTH(gstUpdateOrder); idx++)
1421                 {
1422                     if (!strcmp(rkImageHead.item[i].name, gstUpdateOrder[idx].partName))
1423                     {
1424                         gstUpdateOrder[idx].stItem = rkImageHead.item[i];
1425                         gstUpdateOrder[idx].ulItemSize = ulItemSize;
1426                     }
1427                 }
1428                 #endif
1429 
1430                 uiTotalSize += ulItemSize;
1431             }
1432         }
1433     }
1434 
1435     if (!bFoundParam)
1436     {
1437         if (m_pLog)
1438         {
1439             m_pLog->Record(_T("ERROR:DownloadImage-->No Found Parameter file"));
1440         }
1441         return -3;
1442     }
1443 
1444     if (!MakeParamFileBuffer(rkImageHead.item[iParamPos]))
1445     {
1446         if (m_pLog)
1447         {
1448             m_pLog->Record(_T("ERROR:DownloadImage-->MakeParamFileBuffer failed"));
1449         }
1450         return -12;
1451     }
1452 
1453     GptFlag = GetParameterGptFlag(rkImageHead.item[iParamPos]);
1454     bGptFlag = GptFlag;
1455     printf(">>>>>>>> bGptFlag = %d, lineno = %d\n", bGptFlag, __LINE__);
1456     printf(">>>>>>>> CRKAndroidDevice::bGptFlag = %d \n", CRKAndroidDevice::bGptFlag);
1457     if (!GptFlag)
1458     {
1459         if (!CheckParamPartSize(rkImageHead, iParamPos))
1460         {
1461             if (m_pLog)
1462             {
1463                 m_pLog->Record(_T("ERROR:DownloadImage-->CheckParamPartSize failed"));
1464             }
1465             return -13;
1466         }
1467         uiTotalSize += (8 * m_uiParamFileSize);
1468     }
1469     else
1470     {
1471         uiTotalSize += (SECTOR_SIZE * 67);
1472     }
1473     m_uiLBATimes = 1;
1474     if (m_pProcessCallback)
1475     {
1476         m_pProcessCallback(0.4, 60);
1477     }
1478 
1479     /*
1480      * **************************************************************
1481      *
1482      * upgrade partiton fw data
1483      *
1484      * **************************************************************
1485     */
1486     long long uiCurrentByte = 0;
1487     for (i = 0; i < rkImageHead.item_count; i++)
1488     {
1489         if (m_pProcessCallback)
1490         {
1491             m_pProcessCallback((double)uiCurrentByte / (double)uiTotalSize, 0);
1492         }
1493         if (rkImageHead.item[i].flash_offset == 0xFFFFFFFF)
1494         {
1495             continue;
1496         }
1497 
1498         if (i == iParamPos)
1499         {
1500             if (m_pCallback)
1501             {
1502                 sprintf(szPrompt, "%s writing...\n", rkImageHead.item[i].name);
1503                 m_pCallback(szPrompt);
1504             }
1505             if (GptFlag)
1506             {
1507                 m_pLog->Record(_T("########### RKA_Gpt_Download #########"));
1508                 bRet = RKA_Gpt_Download(rkImageHead.item[i], uiCurrentByte, uiTotalSize);
1509                 if (!bRet)
1510                 {
1511                     if (m_pLog)
1512                     {
1513                         m_pLog->Record(_T("ERROR:DownloadImage-->RKA_Gpt_Download failed"));
1514                     }
1515                     return -4;
1516                 }
1517             }
1518             else
1519             {
1520                 bRet = RKA_Param_Download(rkImageHead.item[i], uiCurrentByte, uiTotalSize);
1521                 if (!bRet)
1522                 {
1523                     if (m_pLog)
1524                     {
1525                         m_pLog->Record(_T(" ERROR:DownloadImage-->RKA_Param_Download failed"));
1526                     }
1527                     // if(m_pCallback)
1528                     // {
1529                     //  sprintf(szPrompt,"%s writing... failed",rkImageHead.item[i].name);
1530                     //  m_pCallback(szPrompt);
1531                     // }
1532                     return -4;
1533                 }
1534             }
1535         }
1536         else
1537         {
1538             if (strcmp(rkImageHead.item[i].name, PARTNAME_RECOVERY) == 0 ||
1539                 strcmp(rkImageHead.item[i].name, PARTNAME_MISC) == 0)
1540             {
1541                 if (!sdBootUpdate)
1542                 {
1543                     //if not sd boot update image, we will ignore download partiton.
1544                     //chad.ma add for ignore 'recovery' or 'misc' or 'userdata' partition update at here.
1545                     m_pLog->Record(_T("INFO:##  Ignore [ %s ] download  ##"), rkImageHead.item[i].name);
1546                     continue;
1547                 }
1548             }
1549 
1550             // if fw is in userdata and fw have userdata partiton, we ignore check userdata partition.
1551             if (look_for_userdata(rkImageHead.item[i].name) == 0 && bFwFromUserdata)
1552                 continue;
1553 
1554             #ifdef USE_SIGNATURE_FW
1555             if (isInOrderList(rkImageHead.item[i].name))
1556             {
1557                 continue;
1558             }
1559             #endif
1560 
1561             m_pLog->Record(_T("INFO:###### Downloading %s #######"), rkImageHead.item[i].name);
1562 
1563             if (rkImageHead.item[i].file[55] == 'H')
1564             {
1565                 ulItemSize = *((DWORD *)(&rkImageHead.item[i].file[56]));
1566                 ulItemSize <<= 32;
1567                 ulItemSize += rkImageHead.item[i].size;
1568             }
1569             else
1570             {
1571                 ulItemSize = rkImageHead.item[i].size;
1572             }
1573 
1574             if (ulItemSize > 0)
1575             {
1576                 if (m_pCallback)
1577                 {
1578                     sprintf(szPrompt, "%s writing...\n", rkImageHead.item[i].name);
1579                     m_pCallback(szPrompt);
1580                 }
1581                 bRet = RKA_File_Download(rkImageHead.item[i], uiCurrentByte, uiTotalSize);
1582                 if (!bRet)
1583                 {
1584                     if (m_pLog)
1585                     {
1586                         m_pLog->Record(_T("ERROR:DownloadImage-->RKA_File_Download failed(%s)"),
1587                                        rkImageHead.item[i].name);
1588                     }
1589                     return -5;
1590                 }
1591                 m_pLog->Record(_T("INFO:###### Download %s Done #######"), rkImageHead.item[i].name);
1592             }
1593         }
1594     }
1595 
1596     #ifdef USE_SIGNATURE_FW
1597     for (int idx = 0; idx < ARRAY_LENGTH(gstUpdateOrder); idx++)
1598     {
1599         if (gstUpdateOrder[idx].ulItemSize > 0)
1600         {
1601             m_pLog->Record(_T("INFO:###### Downloading %s #######"), rkImageHead.item[i].name);
1602             if (m_pCallback)
1603             {
1604                 sprintf(szPrompt, "%s writing...\n", gstUpdateOrder[idx].partName);
1605                 m_pCallback(szPrompt);
1606             }
1607             bRet = RKA_File_Download(gstUpdateOrder[idx].stItem, uiCurrentByte, uiTotalSize);
1608             if (!bRet)
1609             {
1610                 if (m_pLog)
1611                 {
1612                     m_pLog->Record(_T("ERROR:DownloadImage-->RKA_File_Download failed(%s)"),
1613                                    gstUpdateOrder[idx].partName);
1614                 }
1615                 return -5;
1616             }
1617             m_pLog->Record(_T("INFO:###### Download %s Done #######"), gstUpdateOrder[idx].partName);
1618         }
1619     }
1620     #endif
1621 
1622     /*
1623      * **************************************************************
1624      *
1625      * Check partiton fw data
1626      *
1627      * **************************************************************
1628     */
1629     m_pComm->RKU_ReopenLBAHandle();
1630     if (m_pProcessCallback)
1631     {
1632         m_pProcessCallback(1, 0);
1633     }
1634     if (m_pProcessCallback)
1635     {
1636         m_pProcessCallback(0.4, 60);
1637     }
1638     uiCurrentByte = 0;
1639     for (i = 0; i < rkImageHead.item_count; i++)
1640     {
1641         if (m_pProcessCallback)
1642         {
1643             m_pProcessCallback((double)uiCurrentByte / (double)uiTotalSize, 0);
1644         }
1645         if (rkImageHead.item[i].flash_offset == 0xFFFFFFFF)
1646         {
1647             continue;
1648         }
1649         if (i == iParamPos)
1650         {
1651             if (m_pCallback)
1652             {
1653                 sprintf(szPrompt, "%s checking...\n", rkImageHead.item[i].name);
1654                 m_pCallback(szPrompt);
1655             }
1656             if (GptFlag)
1657             {
1658                 bRet = RKA_Gpt_Check(rkImageHead.item[i], uiCurrentByte, uiTotalSize);
1659                 if (!bRet)
1660                 {
1661                     if (m_pLog)
1662                     {
1663                         m_pLog->Record(_T("ERROR:DownloadImage-->RKA_Gpt_Check failed"));
1664                     }
1665                     return -6;
1666                 }
1667             }
1668             else
1669             {
1670                 bRet = RKA_Param_Check(rkImageHead.item[i], uiCurrentByte, uiTotalSize);
1671                 if (!bRet)
1672                 {
1673                     if (m_pLog)
1674                     {
1675                         m_pLog->Record(_T("ERROR:DownloadImage-->RKA_Param_Check failed"));
1676                     }
1677                     return -6;
1678                 }
1679             }
1680         }
1681         else
1682         {
1683             if (strcmp(rkImageHead.item[i].name, PARTNAME_RECOVERY) == 0 ||
1684                 strcmp(rkImageHead.item[i].name, PARTNAME_MISC) == 0 ||
1685                 look_for_userdata(rkImageHead.item[i].name) == 0)
1686             {
1687                 if (!sdBootUpdate)
1688                 {
1689                     //not sdboot update image , we will ignore check partiton.
1690                     //chad.ma add for ignore 'recovery' or 'misc' or 'userdata' partition check at here.
1691                     m_pLog->Record(_T("INFO:# Ignore [ %s ] Check #"), rkImageHead.item[i].name);
1692                     continue;
1693                 }
1694             }
1695 
1696             if (rkImageHead.item[i].file[55] == 'H')
1697             {
1698                 ulItemSize = *((DWORD *)(&rkImageHead.item[i].file[56]));
1699                 ulItemSize <<= 32;
1700                 ulItemSize += rkImageHead.item[i].size;
1701             }
1702             else
1703             {
1704                 ulItemSize = rkImageHead.item[i].size;
1705             }
1706             if (ulItemSize > 0)
1707             {
1708                 if (m_pCallback)
1709                 {
1710                     sprintf(szPrompt, "%s checking...\n", rkImageHead.item[i].name);
1711                     m_pCallback(szPrompt);
1712                 }
1713                 bRet = RKA_File_Check(rkImageHead.item[i], uiCurrentByte, uiTotalSize);
1714                 if (!bRet)
1715                 {
1716                     if (m_pLog)
1717                     {
1718                         m_pLog->Record(_T("ERROR:DownloadImage-->RKA_File_Check failed(%s)"), rkImageHead.item[i].name);
1719                     }
1720                     return -7;
1721                 }
1722             }
1723         }
1724     }
1725     if (m_pProcessCallback)
1726     {
1727         m_pProcessCallback(1, 0);
1728     }
1729 
1730     return 0;
1731 }
1732 
write_partition_upgrade_flag(DWORD dwOffset,BYTE * pMd5,UINT uiFlag)1733 bool CRKAndroidDevice::write_partition_upgrade_flag(DWORD dwOffset, BYTE *pMd5, UINT uiFlag)
1734 {
1735     BYTE flagSector[SECTOR_SIZE];
1736     int iRet;
1737     memset(flagSector, 0, SECTOR_SIZE);
1738     memcpy(flagSector, pMd5, 32);
1739     memcpy(flagSector + 32, (BYTE *)(&uiFlag), 4);
1740     iRet = m_pComm->RKU_WriteLBA(dwOffset, 1, flagSector);
1741     if (iRet != ERR_SUCCESS)
1742     {
1743         if (m_pLog)
1744         {
1745             m_pLog->Record("ERROR:write_partition_upgrade_flag-->RKU_WriteLBA failed,err=%d", iRet);
1746         }
1747         return false;
1748     }
1749     return true;
1750 }
read_partition_upgrade_flag(DWORD dwOffset,BYTE * pMd5,UINT * uiFlag)1751 bool CRKAndroidDevice::read_partition_upgrade_flag(DWORD dwOffset, BYTE *pMd5, UINT *uiFlag)
1752 {
1753     if (m_pLog)
1754     {
1755         m_pLog->Record("INFO:read_partition_upgrade_flag in");
1756     }
1757     BYTE flagSector[SECTOR_SIZE];
1758     int iRet;
1759     iRet = m_pComm->RKU_ReadLBA(dwOffset, 1, flagSector);
1760     if (iRet != ERR_SUCCESS)
1761     {
1762         if (m_pLog)
1763         {
1764             m_pLog->Record("ERROR:read_partition_upgrade_flag-->RKU_ReadLBA failed,err=%d", iRet);
1765         }
1766         return false;
1767     }
1768     memcpy(pMd5, flagSector, 32);
1769     (*uiFlag) = *((UINT *)(flagSector + 32));
1770     if (m_pLog)
1771     {
1772         m_pLog->Record("INFO:read_partition_upgrade_flag out,flag=0x%x", *uiFlag);
1773     }
1774     return true;
1775 }
1776 
UpgradePartition()1777 int CRKAndroidDevice::UpgradePartition()
1778 {
1779     long long dwFwOffset;
1780     bool bRet, bSameFw = false;
1781     BYTE localMd5[32];
1782     BYTE *fwMd5, *fwSignMd5;
1783     UINT uiFlag;
1784     DWORD dwFlagSector = 0;
1785     dwFwOffset = m_pImage->FWOffset;
1786     STRUCT_RKIMAGE_HDR rkImageHead;
1787     vector<int> vecUpgradePartition;
1788     vecUpgradePartition.clear();
1789     char szPrompt[100];
1790     int iHeadSize = 0;
1791     if (m_pProcessCallback)
1792     {
1793         m_pProcessCallback(0.1, 5);
1794     }
1795 
1796     iHeadSize = sizeof(STRUCT_RKIMAGE_HDR);
1797     bRet = m_pImage->GetData(dwFwOffset, iHeadSize, (PBYTE)&rkImageHead);
1798     if (!bRet)
1799     {
1800         if (m_pLog)
1801         {
1802             m_pLog->Record(_T("ERROR:UpgradePartition-->GetData failed"));
1803         }
1804         return -1;
1805     }
1806     if (rkImageHead.item_count <= 0)
1807     {
1808         if (m_pLog)
1809         {
1810             m_pLog->Record(_T("ERROR:UpgradePartition-->No Found partition item"));
1811         }
1812         return -2;
1813     }
1814 
1815     int i;
1816     vector<int>::iterator iter;
1817     m_dwBackupOffset = 0xFFFFFFFF;
1818     int iParamPos = - 1;
1819     long long uiTotalSize = 0;
1820     long long ulItemSize  = 0;
1821     bool bFoundParam = false, bFoundSystem = false, bFoundUserData = false;
1822     for (i = 0; i < rkImageHead.item_count; i++)
1823     {
1824         if (rkImageHead.item[i].flash_offset != 0xFFFFFFFF)
1825         {
1826             for (iter = vecUpgradePartition.begin(); iter != vecUpgradePartition.end(); iter++)
1827             {
1828                 if (rkImageHead.item[*iter].flash_offset > rkImageHead.item[i].flash_offset)
1829                 {
1830                     iter = vecUpgradePartition.insert(iter, i);
1831                     break;
1832                 }
1833             }
1834 
1835             if (iter == vecUpgradePartition.end())
1836             {
1837                 vecUpgradePartition.push_back(i);
1838             }
1839             if (strcmp(rkImageHead.item[i].name, PARTNAME_PARAMETER) == 0)
1840             {
1841                 bFoundParam = true;
1842                 iParamPos = i;
1843             }
1844             else
1845             {
1846                 if (strcmp(rkImageHead.item[i].name, PARTNAME_SYSTEM) == 0 ||
1847                     !strcmp(rkImageHead.item[i].name, PARTNAME_ROOTFS))
1848                 {
1849                     bFoundSystem = true;
1850                 }
1851                 if (strcmp(rkImageHead.item[i].name, PARTNAME_MISC) == 0)
1852                 {
1853                     dwFlagSector = rkImageHead.item[i].flash_offset + rkImageHead.item[i].part_size - 4;
1854                 }
1855                 if (look_for_userdata(rkImageHead.item[i].name) == 0)
1856                 {
1857                     bFoundUserData = true;
1858                 }
1859 
1860                 if (strcmp(rkImageHead.item[i].name, PARTNAME_BACKUP) == 0)
1861                 {
1862                     m_dwBackupOffset = rkImageHead.item[i].flash_offset;
1863                 }
1864 
1865                 if (rkImageHead.item[i].file[55] == 'H')
1866                 {
1867                     ulItemSize = *((DWORD *)(&rkImageHead.item[i].file[56]));
1868                     ulItemSize <<= 32;
1869                     ulItemSize += rkImageHead.item[i].size;
1870                 }
1871                 else
1872                 {
1873                     ulItemSize = rkImageHead.item[i].size;
1874                 }
1875                 uiTotalSize += ulItemSize;
1876             }
1877         }
1878     }
1879 
1880     if (!bFoundParam)
1881     {
1882         if (m_pLog)
1883         {
1884             m_pLog->Record(_T("ERROR:UpgradePartition-->No Found Parameter file"));
1885         }
1886         return -3;
1887     }
1888 
1889     if (!MakeParamFileBuffer(rkImageHead.item[iParamPos]))
1890     {
1891         if (m_pLog)
1892         {
1893             m_pLog->Record(_T("ERROR:UpgradePartition-->MakeParamFileBuffer failed"));
1894         }
1895         return -12;
1896     }
1897 
1898     if (!CheckParamPartSize(rkImageHead, iParamPos))
1899     {
1900         if (m_pLog)
1901         {
1902             m_pLog->Record(_T("ERROR:UpgradePartition-->CheckParamPartSize failed"));
1903         }
1904         return -13;
1905     }
1906     uiTotalSize += (8 * m_uiParamFileSize); //���ϲ����ļ���Ҫ�Ĵ�С
1907     m_uiLBATimes = 1;
1908     m_pImage->GetMd5Data(fwMd5, fwSignMd5);
1909     if (dwFlagSector != 0)
1910     {
1911         if (read_partition_upgrade_flag(dwFlagSector, localMd5, &uiFlag))
1912         {
1913             if (memcmp(localMd5, fwMd5, 32) == 0)
1914             {
1915                 bSameFw = true;
1916             }
1917         }
1918     }
1919     if (m_pProcessCallback)
1920     {
1921         m_pProcessCallback(0.8, 90);
1922     }
1923     long long uiCurrentByte = 0;
1924     for (i = 0; i < vecUpgradePartition.size(); i++)
1925     {
1926         if (m_pProcessCallback)
1927         {
1928             m_pProcessCallback((double)uiCurrentByte / (double)uiTotalSize, 0);
1929         }
1930         if (vecUpgradePartition[i] == iParamPos)
1931         {
1932             if ((bSameFw) && (uiFlag >= rkImageHead.item[vecUpgradePartition[i]].flash_offset))
1933             {
1934                 uiCurrentByte += (8 * m_uiParamFileSize);
1935                 continue;
1936             }
1937             if (m_pCallback)
1938             {
1939                 sprintf(szPrompt, "%s writing...\n", rkImageHead.item[vecUpgradePartition[i]].name);
1940                 m_pCallback(szPrompt);
1941             }
1942             bRet = RKA_Param_Download(rkImageHead.item[vecUpgradePartition[i]], uiCurrentByte, uiTotalSize);
1943             if (!bRet)
1944             {
1945                 if (m_pLog)
1946                 {
1947                     m_pLog->Record(_T(" ERROR:UpgradePartition-->RKA_Param_Download failed"));
1948                 }
1949                 return -4;
1950             }
1951             m_pComm->RKU_ReopenLBAHandle();
1952             if (m_pCallback)
1953             {
1954                 sprintf(szPrompt, "%s checking...\n", rkImageHead.item[vecUpgradePartition[i]].name);
1955                 m_pCallback(szPrompt);
1956             }
1957             uiCurrentByte -= (8 * m_uiParamFileSize);
1958             bRet = RKA_Param_Check(rkImageHead.item[vecUpgradePartition[i]], uiCurrentByte, uiTotalSize);
1959             if (!bRet)
1960             {
1961                 if (m_pLog)
1962                 {
1963                     m_pLog->Record(_T("ERROR:UpgradePartition-->RKA_Param_Check failed"));
1964                 }
1965                 return -6;
1966             }
1967         }
1968         else
1969         {
1970             if (rkImageHead.item[vecUpgradePartition[i]].file[55] == 'H')
1971             {
1972                 ulItemSize = *((DWORD *)(&rkImageHead.item[vecUpgradePartition[i]].file[56]));
1973                 ulItemSize <<= 32;
1974                 ulItemSize += rkImageHead.item[vecUpgradePartition[i]].size;
1975             }
1976             else
1977             {
1978                 ulItemSize = rkImageHead.item[vecUpgradePartition[i]].size;
1979             }
1980             if ((bSameFw) && (uiFlag >= rkImageHead.item[vecUpgradePartition[i]].flash_offset))
1981             {
1982                 uiCurrentByte += ulItemSize;
1983                 continue;
1984             }
1985 
1986             if (ulItemSize > 0)
1987             {
1988                 if (m_pCallback)
1989                 {
1990                     sprintf(szPrompt, "%s writing...\n", rkImageHead.item[vecUpgradePartition[i]].name);
1991                     m_pCallback(szPrompt);
1992                 }
1993                 bRet = RKA_File_Download(rkImageHead.item[vecUpgradePartition[i]], uiCurrentByte, uiTotalSize);
1994                 if (!bRet)
1995                 {
1996                     if (m_pLog)
1997                     {
1998                         m_pLog->Record(_T("ERROR:UpgradePartition-->RKA_File_Download failed(%s)"), rkImageHead.item[vecUpgradePartition[i]].name);
1999                     }
2000                     return -5;
2001                 }
2002                 m_pComm->RKU_ReopenLBAHandle();
2003                 if (m_pCallback)
2004                 {
2005                     sprintf(szPrompt, "%s checking...\n", rkImageHead.item[vecUpgradePartition[i]].name);
2006                     m_pCallback(szPrompt);
2007                 }
2008                 uiCurrentByte -= ulItemSize;
2009                 bRet = RKA_File_Check(rkImageHead.item[vecUpgradePartition[i]], uiCurrentByte, uiTotalSize);
2010                 if (!bRet)
2011                 {
2012                     if (m_pLog)
2013                     {
2014                         m_pLog->Record(_T("ERROR:UpgradePartition-->RKA_File_Check failed(%s)"), rkImageHead.item[vecUpgradePartition[i]].name);
2015                     }
2016                     return -7;
2017                 }
2018             }
2019             else
2020             {
2021                 continue;
2022             }
2023         }
2024         if (dwFlagSector != 0)
2025         {
2026             write_partition_upgrade_flag(dwFlagSector, fwMd5, rkImageHead.item[vecUpgradePartition[i]].flash_offset);
2027         }
2028     }
2029     if (m_pProcessCallback)
2030     {
2031         m_pProcessCallback(1, 0);
2032     }
2033     return 0;
2034 }
EraseIDB()2035 int CRKAndroidDevice::EraseIDB()
2036 {
2037     DWORD dwEraseCounts;
2038     if (m_oldIDBCounts > 0)
2039     {
2040         dwEraseCounts = m_oldSec1->usSysReservedBlock;
2041     }
2042     else
2043     {
2044         dwEraseCounts = IDBLOCK_TOP;
2045     }
2046     if (m_bEmmc)
2047     {
2048         if (EraseEmmcBlock(0, 0, dwEraseCounts) != ERR_SUCCESS)
2049         {
2050             if (m_pLog)
2051             {
2052                 m_pLog->Record(_T("ERROR:EraseIDB-->EraseEmmcBlock failed"));
2053             }
2054             return -1;
2055         }
2056     }
2057     else
2058     {
2059         if (!EraseMutilBlock(0, 0, dwEraseCounts, false))
2060         {
2061             if (m_pLog)
2062             {
2063                 m_pLog->Record(_T("ERROR:EraseIDB-->EraseMutilBlock failed"));
2064             }
2065             return -1;
2066         }
2067     }
2068 
2069     return 0;
2070 }
EraseAllBlocks()2071 int CRKAndroidDevice::EraseAllBlocks()
2072 {
2073     int i;
2074     UINT uiBlockCount;
2075     int iRet = ERR_SUCCESS, iErasePos = 0, iEraseBlockNum = 0, iEraseTimes = 0, iCSIndex = 0;
2076     BYTE bCSCount = 0;
2077     for (i = 0; i < 8; i++)
2078     {
2079         if (m_flashInfo.bFlashCS & (1 << i))
2080         {
2081             bCSCount++;
2082         }
2083     }
2084 
2085     for (i = 0; i < 8; i++)
2086     {
2087         if (m_flashInfo.bFlashCS & (1 << i))
2088         {
2089             uiBlockCount = m_flashInfo.uiBlockNum;
2090             iErasePos = 0;
2091             iEraseTimes = 0;
2092             while (uiBlockCount > 0)
2093             {
2094                 iEraseBlockNum = (uiBlockCount < MAX_ERASE_BLOCKS) ? uiBlockCount : MAX_ERASE_BLOCKS;
2095                 if (m_bEmmc)
2096                 {
2097                     iRet = EraseEmmcBlock(i, iErasePos, iEraseBlockNum);
2098                     if (iRet != ERR_SUCCESS)
2099                     {
2100                         if (m_pLog)
2101                         {
2102                             m_pLog->Record(_T("ERROR:EraseAllBlocks-->EraseEmmcBlock failed,RetCode(%d)"), iRet);
2103                         }
2104                         return -1;
2105                     }
2106                 }
2107                 else
2108                 {
2109                     iRet = m_pComm->RKU_EraseBlock(i, iErasePos, iEraseBlockNum, ERASE_FORCE);
2110                     if ((iRet != ERR_SUCCESS) && (iRet != ERR_FOUND_BAD_BLOCK))
2111                     {
2112                         if (m_pLog)
2113                         {
2114                             m_pLog->Record(_T("ERROR:EraseAllBlocks-->RKU_EraseBlock failed,RetCode(%d)"), iRet);
2115                         }
2116                         return -1;
2117                     }
2118                 }
2119 
2120                 iErasePos += iEraseBlockNum;
2121                 uiBlockCount -= iEraseBlockNum;
2122                 iEraseTimes++;
2123             }
2124             iCSIndex++;
2125         }
2126     }
2127 
2128     return 0;
2129 }
2130 
BufferWriteBack()2131 bool CRKAndroidDevice::BufferWriteBack()
2132 {
2133     FindAllIDB();
2134     if (m_oldIDBCounts > 0)
2135     {
2136         if (m_pLog)
2137         {
2138             m_pLog->Record(_T("ERROR:BufferWriteBack-->Found IDB"));
2139         }
2140         return true;
2141     }
2142     if (m_usWriteBackCrc == 0)
2143     {
2144         if (m_pLog)
2145         {
2146             m_pLog->Record(_T("INFO:BufferWriteBack-->Crc is zero"));
2147         }
2148         return true;
2149     }
2150     BYTE pWriteBackBuffer[2 * SECTOR_SIZE];
2151 
2152     char *pszTag = (char *)pWriteBackBuffer;
2153     USHORT *pValue = (USHORT *)(pWriteBackBuffer + 4);
2154 
2155     memset(pWriteBackBuffer, 0, 2 * SECTOR_SIZE);
2156 
2157 
2158     strcpy(pszTag, "CRC");
2159     *pValue = m_usWriteBackCrc;
2160     pValue++;
2161     *pValue = m_usWriteBackCustomDataOffset;
2162     pValue++;
2163     *pValue = m_usWriteBackCustomDataSize;
2164     memcpy(pWriteBackBuffer + SECTOR_SIZE, m_backupBuffer, SECTOR_SIZE);
2165 
2166     STRUCT_END_WRITE_SECTOR end_write_sector_data;
2167     BYTE writeBuf[8 * SECTOR_SIZE];
2168     UINT uiOffset, uiTotal, uiWriteByte, uiCrc;
2169     int iRet, i, nTryCount = 3;
2170     uiTotal = 2 * SECTOR_SIZE;
2171     uiCrc = CRC_32(pWriteBackBuffer, uiTotal);
2172     end_write_sector_data.uiSize = uiTotal;
2173     end_write_sector_data.uiCrc = uiCrc;
2174     for (i = WBBUFFER_BOTTOM; i < WBBUFFER_TOP; i++)
2175     {
2176         end_write_sector_data.uiBlock[i] = i;
2177     }
2178     while (nTryCount > 0)
2179     {
2180         uiOffset = 0;
2181         uiTotal = 2 * SECTOR_SIZE;
2182         while (uiTotal > 0)
2183         {
2184             if (uiTotal >= 2048)
2185             {
2186                 uiWriteByte = 2048;
2187             }
2188             else
2189             {
2190                 uiWriteByte = uiTotal;
2191             }
2192 
2193             memcpy(writeBuf + 8, pWriteBackBuffer + uiOffset, uiWriteByte);
2194             iRet = m_pComm->RKU_WriteLBA(64 + uiOffset, uiWriteByte, writeBuf);
2195             if (iRet != ERR_SUCCESS)
2196             {
2197                 if (m_pLog)
2198                 {
2199                     m_pLog->Record(_T("ERROR:BufferWriteBack-->RKU_WriteSector failed!"));
2200                 }
2201                 return false;
2202             }
2203             uiOffset += uiWriteByte;
2204             uiTotal -= uiWriteByte;
2205         }
2206         //iRet = m_pComm->RKU_EndWriteSector((BYTE*)&end_write_sector_data);
2207         if (iRet == ERR_SUCCESS)
2208         {
2209             break;
2210         }
2211         nTryCount--;
2212     }
2213     if (nTryCount <= 0)
2214     {
2215         return false;
2216     }
2217 
2218     return true;
2219 }
FindBackupBuffer()2220 bool CRKAndroidDevice::FindBackupBuffer()
2221 {
2222     int i, iRet;
2223     bool bRet;
2224     BYTE buffer[2 * SECTOR_SIZE];
2225     for (i = WBBUFFER_BOTTOM; i < WBBUFFER_TOP; i++)
2226     {
2227         memset(buffer, 0, 2 * SECTOR_SIZE);
2228         iRet = m_pComm->RKU_ReadSector(i * m_flashInfo.uiSectorPerBlock, 2, buffer);
2229         if (iRet != ERR_SUCCESS)
2230         {
2231             if (m_pLog)
2232             {
2233                 m_pLog->Record(_T("ERROR:FindBackupBuffer-->RKU_ReadSector failed,RetCode(%d)"), iRet);
2234             }
2235             continue;
2236         }
2237         else
2238         {
2239             PSTRUCT_RKANDROID_WBBUFFER pWriteBack;
2240             pWriteBack = (PSTRUCT_RKANDROID_WBBUFFER)buffer;
2241             char *pszCrcTag = (char *)buffer;
2242             if (pWriteBack->dwTag == 0x38324B52)
2243             {
2244                 bRet = CheckCrc16(buffer, SECTOR_SIZE - 2, pWriteBack->usCrc);
2245                 if (!bRet)
2246                 {
2247                     if (m_pLog)
2248                     {
2249                         m_pLog->Record(_T("ERROR:FindBackupBuffer-->Check Crc Failed"));
2250                     }
2251                     //                  continue;
2252                 }
2253                 PRKANDROID_IDB_SEC3 pSec = (PRKANDROID_IDB_SEC3)m_backupBuffer;
2254                 pSec->usSNSize = pWriteBack->usSnSize;
2255                 memcpy(pSec->sn, pWriteBack->btSnData, RKDEVICE_SN_LEN);
2256                 memset(pSec->reserved, 0, RKANDROID_SEC3_RESERVED_LEN);
2257                 memcpy(pSec->reserved + 6, pWriteBack->btReserve, RKANDROID_SEC3_RESERVED_LEN - 6);
2258                 pSec->imeiSize = pWriteBack->btImeiSize;
2259                 memcpy(pSec->imei, pWriteBack->btImeiData, RKDEVICE_IMEI_LEN);
2260                 pSec->uidSize = pWriteBack->btUidSize;
2261                 memcpy(pSec->uid, pWriteBack->btUidData, RKDEVICE_UID_LEN);
2262                 pSec->blueToothSize = pWriteBack->btBlueToothSize;
2263                 memcpy(pSec->blueToothAddr, pWriteBack->btBlueToothData, RKDEVICE_BT_LEN);
2264                 pSec->macSize = pWriteBack->btMacSize;
2265                 memcpy(pSec->macAddr, pWriteBack->btMacData, RKDEVICE_MAC_LEN);
2266                 m_usWriteBackCrc = CRC_16(m_backupBuffer, SECTOR_SIZE);
2267             }
2268             else if (strcmp(pszCrcTag, "CRC") == 0)
2269             {
2270                 m_usWriteBackCrc = *((USHORT *)(buffer + 4));
2271                 m_usWriteBackCustomDataOffset = *((USHORT *)(buffer + 6));
2272                 m_usWriteBackCustomDataSize = *((USHORT *)(buffer + 8));
2273                 bRet = CheckCrc16(buffer + SECTOR_SIZE, SECTOR_SIZE, m_usWriteBackCrc);
2274                 if (!bRet)
2275                 {
2276                     if (m_pLog)
2277                     {
2278                         m_pLog->Record(_T("ERROR:FindBackupBuffer-->Check Crc Failed"));
2279                     }
2280                     m_usWriteBackCrc = CRC_16(buffer + SECTOR_SIZE + SPARE_SIZE, SECTOR_SIZE);
2281                     //                  continue;
2282                 }
2283                 memcpy(m_backupBuffer, buffer + SECTOR_SIZE, SECTOR_SIZE);
2284             }
2285             else
2286             {
2287                 if (m_pLog)
2288                 {
2289                     m_pLog->Record(_T("INFO:FindBackupBuffer-->No Found Tag"));
2290                 }
2291                 continue;
2292             }
2293 
2294             break;
2295         }
2296     }
2297     if (i < WBBUFFER_TOP)
2298     {
2299         return true;
2300     }
2301     else
2302     {
2303         return false;
2304     }
2305 }
2306 
RKA_File_Download(STRUCT_RKIMAGE_ITEM & entry,long long & currentByte,long long totalByte)2307 bool CRKAndroidDevice::RKA_File_Download(STRUCT_RKIMAGE_ITEM &entry, long long &currentByte, long long totalByte)
2308 {
2309     int iRet;
2310     bool bRet;
2311     UINT uiLBATransferSize;
2312 
2313     /* To reduce the write frequency of EMMC flash memory, we use different block sizes
2314      * according to the flash memory type configuration, EMMC flash memory is 1M, nand or other devices use 16K by default.
2315      */
2316     if (m_bEmmc)
2317         uiLBATransferSize = (LBA_TRANSFER_SIZE_1M) * m_uiLBATimes;
2318     else
2319         uiLBATransferSize = (LBA_TRANSFER_SIZE_16K) * m_uiLBATimes;
2320     UINT uiLBASector = uiLBATransferSize / SECTOR_SIZE;
2321 
2322     UINT uiBufferSize = uiLBATransferSize;
2323     long long uifileBufferSize;
2324     long long ulEntryStartOffset;
2325     DWORD dwFWOffset;
2326     dwFWOffset = m_pImage->FWOffset;
2327     if (entry.file[50] == 'H')
2328     {
2329         ulEntryStartOffset = *((DWORD *)(&entry.file[51]));
2330         ulEntryStartOffset <<= 32;
2331         ulEntryStartOffset += entry.offset;
2332         ulEntryStartOffset += m_pImage->FWOffset;
2333     }
2334     else
2335     {
2336         ulEntryStartOffset = m_pImage->FWOffset;
2337         ulEntryStartOffset += entry.offset;
2338     }
2339     if (entry.file[55] == 'H')
2340     {
2341         uifileBufferSize = *((DWORD *)(&entry.file[56]));
2342         uifileBufferSize <<= 32;
2343         uifileBufferSize += entry.size;
2344     }
2345     else
2346     {
2347         uifileBufferSize = entry.size;
2348     }
2349     if (m_pLog)
2350     {
2351         m_pLog->Record(_T("INFO:Start updating [ %s ],offset=0x%x,size=%llu"), entry.name, entry.flash_offset, uifileBufferSize);
2352     }
2353 
2354     BYTE byRWMethod = RWMETHOD_IMAGE;
2355 
2356     if (entry.flash_offset > m_dwBackupOffset)
2357     {
2358         byRWMethod = RWMETHOD_LBA;
2359     }
2360 
2361     PBYTE pBuffer = NULL;
2362     pBuffer = new BYTE[uiBufferSize];
2363     if (!pBuffer)
2364     {
2365         if (m_pLog)
2366         {
2367             m_pLog->Record(_T("ERROR:RKA_File_Download-->New memory failed"));
2368         }
2369         return false;
2370     }
2371 
2372     bool bUser = false;
2373     //  if (strcmp(entry.name,PARTNAME_MISC)==0)
2374     //  {
2375     //      currentByte += uifileBufferSize;
2376     //      return true;
2377     //  }
2378     if (strcmp(entry.name, PARTNAME_USER) == 0)
2379     {
2380         bUser = true;
2381     }
2382 
2383     UINT uiBegin, uiLen, uiWriteByte;
2384     u64 uiEntryOffset;
2385 
2386     uiBegin = entry.flash_offset;
2387     uiLen = 0;
2388     uiWriteByte = 0;
2389     uiEntryOffset = 0;
2390 #ifdef USE_SIMULATE_POWER_OFF
2391     UINT cnt = 5;
2392     long long itemTotalsize;
2393     bool isInOrder = false;
2394     itemTotalsize = uifileBufferSize;
2395     isInOrder = isInOrderList(entry.name);
2396 #endif
2397 
2398     while (uifileBufferSize > 0)
2399     {
2400         #ifdef USE_SIMULATE_POWER_OFF
2401         if (isInOrder && uifileBufferSize < itemTotalsize / 2)
2402         {
2403             while (cnt > 0)
2404             {
2405                 if (m_pLog)
2406                 {
2407                     printf("******************************************************\n");
2408                     printf("current is %s upgrading\n", entry.name);
2409                     printf("This is simulate abnormal power off test\n");
2410                     printf("left --- %ds ---\n", cnt);
2411                     printf("******************************************************\n");
2412                 }
2413                 sleep(1);
2414                 cnt--;
2415             }
2416         }
2417         #endif
2418         memset(pBuffer, 0, uiBufferSize);
2419         if (uifileBufferSize < uiBufferSize)
2420         {
2421             uiWriteByte = uifileBufferSize;
2422             uiLen = ((uiWriteByte % SECTOR_SIZE == 0) ? (uiWriteByte / SECTOR_SIZE) : (uiWriteByte / SECTOR_SIZE + 1));
2423         }
2424         else
2425         {
2426             uiWriteByte = uiBufferSize;
2427             uiLen = uiLBASector;
2428         }
2429         bRet = m_pImage->GetData(ulEntryStartOffset + uiEntryOffset, uiWriteByte, pBuffer);
2430         if (!bRet)
2431         {
2432             if (m_pLog)
2433             {
2434                 m_pLog->Record(_T("ERROR:RKA_File_Download-->GetFileData failed"));
2435             }
2436             delete []pBuffer;
2437             pBuffer = NULL;
2438             return false;
2439         }
2440         if (bUser)
2441         {
2442             if ((pBuffer[0] == 0xEB) && (pBuffer[1] == 0x58) && (pBuffer[2] == 0x90))
2443             {
2444                 //fat user image
2445                 iRet = m_pComm->RKU_TestDeviceReady((DWORD *)&m_uiUserSectors, NULL, TU_GETUSERSECTOR_SUBCODE);
2446                 if (iRet != ERR_SUCCESS)
2447                 {
2448                     if (m_pLog)
2449                     {
2450                         m_pLog->Record(_T("ERROR:RKA_File_Download-->Get user sectors failed,RetCode(%d)"), iRet);
2451                     }
2452 
2453                     delete []pBuffer;
2454                     pBuffer = NULL;
2455                     return false;
2456                 }
2457                 if ((m_uiUserSectors == 0) || (m_uiUserSectors == (DWORD) -1))
2458                 {
2459                     if (m_pLog)
2460                     {
2461                         m_pLog->Record(_T("ERROR:RKA_File_Download-->User size is wrong,value=0x%x"), m_uiUserSectors);
2462                     }
2463 
2464                     delete []pBuffer;
2465                     pBuffer = NULL;
2466                     return false;
2467                 }
2468                 if (m_uiUserSectors <= uiBegin)
2469                 {
2470                     if (m_pLog)
2471                     {
2472                         m_pLog->Record(_T("ERROR:RKA_File_Download-->Available total is smaller than user offset"));
2473                     }
2474 
2475                     delete []pBuffer;
2476                     pBuffer = NULL;
2477                     return false;
2478                 }
2479                 m_uiUserSectors -= uiBegin;
2480 
2481                 PBYTE pDbr, pCopyDbr;
2482                 pDbr = pBuffer;
2483                 pCopyDbr = pBuffer + SECTOR_SIZE * 6;
2484                 if (*(UINT *)(pDbr + 32) < m_uiUserSectors)
2485                 {
2486                     if (m_pLog)
2487                     {
2488                         m_pLog->Record(_T("ERROR:RKA_File_Download-->Original size is smaller than current user size"));
2489                     }
2490 
2491                     delete []pBuffer;
2492                     pBuffer = NULL;
2493                     return false;
2494                 }
2495 
2496                 (*(UINT *)(pDbr + 32)) = m_uiUserSectors;
2497                 (*(UINT *)(pCopyDbr + 32)) = m_uiUserSectors;
2498             }
2499 
2500             bUser = false;
2501         }
2502 
2503         iRet = m_pComm->RKU_WriteLBA(uiBegin, uiLen, pBuffer, byRWMethod);
2504         if (iRet != ERR_SUCCESS)
2505         {
2506             if (m_pLog)
2507             {
2508                 m_pLog->Record(_T("ERROR:RKA_File_Download-->RKU_WriteLBA failed,Written(%d),RetCode(%d)"), uiEntryOffset, iRet);
2509             }
2510 
2511             delete []pBuffer;
2512             pBuffer = NULL;
2513             return false;
2514         }
2515         uifileBufferSize -= uiWriteByte;
2516         uiEntryOffset += uiWriteByte;
2517         uiBegin += uiLen;
2518         currentByte += uiWriteByte;
2519     }
2520 
2521     delete []pBuffer;
2522     pBuffer = NULL;
2523 
2524     // if (m_pLog)
2525     // {
2526     //  m_pLog->Record(_T("INFO:[ %s ] upgrade Done!"), entry.name);
2527     // }
2528     return true;
2529 }
2530 
RKA_File_Check(STRUCT_RKIMAGE_ITEM & entry,long long & currentByte,long long totalByte)2531 bool CRKAndroidDevice::RKA_File_Check(STRUCT_RKIMAGE_ITEM &entry, long long &currentByte, long long totalByte)
2532 {
2533     int iRet;
2534     bool bRet;
2535     UINT uiLBATransferSize;
2536     if (m_bEmmc)
2537         uiLBATransferSize = (LBA_TRANSFER_SIZE_1M) * m_uiLBATimes;
2538     else
2539         uiLBATransferSize = (LBA_TRANSFER_SIZE_16K) * m_uiLBATimes;
2540     UINT uiLBASector       = uiLBATransferSize / SECTOR_SIZE;
2541     UINT uiBufferSize      = uiLBATransferSize;
2542     long long uifileBufferSize;
2543     long long ulEntryStartOffset;
2544     DWORD dwFWOffset;
2545     dwFWOffset = m_pImage->FWOffset;
2546     if (entry.file[50] == 'H')
2547     {
2548         ulEntryStartOffset = *((DWORD *)(&entry.file[51]));
2549         ulEntryStartOffset <<= 32;
2550         ulEntryStartOffset += entry.offset;
2551         ulEntryStartOffset += m_pImage->FWOffset;
2552     }
2553     else
2554     {
2555         ulEntryStartOffset = m_pImage->FWOffset;
2556         ulEntryStartOffset += entry.offset;
2557     }
2558     if (entry.file[55] == 'H')
2559     {
2560         uifileBufferSize = *((DWORD *)(&entry.file[56]));
2561         uifileBufferSize <<= 32;
2562         uifileBufferSize += entry.size;
2563     }
2564     else
2565     {
2566         uifileBufferSize = entry.size;
2567     }
2568 
2569     BYTE byRWMethod = RWMETHOD_IMAGE;
2570     if (entry.flash_offset > m_dwBackupOffset)
2571     {
2572         byRWMethod = RWMETHOD_LBA;
2573     }
2574 
2575     PBYTE pBufferFromFile = NULL;
2576     pBufferFromFile = new BYTE[uiBufferSize];
2577     if (!pBufferFromFile)
2578     {
2579         if (m_pLog)
2580         {
2581             m_pLog->Record(_T("ERROR:RKA_File_Check-->New memory failed"));
2582         }
2583         return false;
2584     }
2585     PBYTE pBufferFromFlash = NULL;
2586     pBufferFromFlash = new BYTE[uiBufferSize];
2587     if (!pBufferFromFlash)
2588     {
2589         if (m_pLog)
2590         {
2591             m_pLog->Record(_T("ERROR:RKA_File_Check-->New memory failed"));
2592         }
2593         delete []pBufferFromFile;
2594         return false;
2595     }
2596 
2597     bool bUser = false;
2598     //  if (strcmp(entry.name,PARTNAME_MISC)==0)
2599     //  {
2600     //      currentByte += uifileBufferSize;
2601     //      return true;
2602     //  }
2603     if (strcmp(entry.name, PARTNAME_USER) == 0)
2604     {
2605         bUser = true;
2606         if ((entry.name[PART_NAME - 2] == 'N') && (entry.name[PART_NAME - 1] == 'C'))
2607         {
2608             //no check user
2609             currentByte += uifileBufferSize;
2610             return true;
2611         }
2612     }
2613 
2614     UINT uiBegin, uiLen, uiWriteByte;
2615     long long uiEntryOffset;
2616     uiBegin = entry.flash_offset;
2617     uiLen = 0;
2618     uiWriteByte = 0;
2619     uiEntryOffset = 0;
2620     while (uifileBufferSize > 0)
2621     {
2622         if (uifileBufferSize < uiBufferSize)
2623         {
2624             uiWriteByte = uifileBufferSize;
2625             uiLen = ((uiWriteByte % SECTOR_SIZE == 0) ? (uiWriteByte / SECTOR_SIZE) : (uiWriteByte / SECTOR_SIZE + 1));
2626         }
2627         else
2628         {
2629             uiWriteByte = uiBufferSize;
2630             uiLen = uiLBASector;
2631         }
2632 
2633         memset(pBufferFromFile, 0, uiBufferSize);
2634         memset(pBufferFromFlash, 0, uiBufferSize);
2635 
2636         iRet = m_pComm->RKU_ReadLBA(uiBegin, uiLen, pBufferFromFlash, byRWMethod);
2637         if (iRet != ERR_SUCCESS)
2638         {
2639             if (m_pLog)
2640             {
2641                 m_pLog->Record(_T("ERROR:RKA_File_Check-->RKU_ReadLBA failed,Read(%d),RetCode(%d)"), uiEntryOffset, iRet);
2642             }
2643             delete []pBufferFromFile;
2644             delete []pBufferFromFlash;
2645             return false;
2646         }
2647         bRet = m_pImage->GetData(ulEntryStartOffset + uiEntryOffset, uiWriteByte, pBufferFromFile);
2648         if (!bRet)
2649         {
2650             if (m_pLog)
2651             {
2652                 m_pLog->Record(_T("ERROR:RKA_File_Check-->GetFileData failed"));
2653             }
2654             delete []pBufferFromFile;
2655             delete []pBufferFromFlash;
2656             return false;
2657         }
2658         if (bUser)
2659         {
2660             if ((pBufferFromFile[0] == 0xEB) && (pBufferFromFile[1] == 0x58) && (pBufferFromFile[2] == 0x90))
2661             {
2662                 //fat user image
2663                 PBYTE pDbr, pCopyDbr;
2664                 pDbr = pBufferFromFile;
2665                 pCopyDbr = pBufferFromFile + SECTOR_SIZE * 6;
2666 
2667                 (*(UINT *)(pDbr + 32)) = m_uiUserSectors;
2668                 (*(UINT *)(pCopyDbr + 32)) = m_uiUserSectors;
2669             }
2670 
2671             bUser = false;
2672         }
2673 
2674         if (memcmp(pBufferFromFile, pBufferFromFlash, uiWriteByte) != 0)
2675         {
2676             if (m_pLog)
2677             {
2678                 m_pLog->Record(_T("ERROR:RKA_File_Check-->Memcmp failed,Read(%d)"), uiEntryOffset);
2679                 tchar szDateTime[100];
2680                 tstring strFile;
2681                 time_t  now;
2682                 struct tm timeNow;
2683                 time(&now);
2684                 localtime_r(&now, &timeNow);
2685                 _stprintf(szDateTime, _T("%02d-%02d-%02d"), timeNow.tm_hour, timeNow.tm_min, timeNow.tm_sec);
2686 
2687                 strFile = szDateTime;
2688                 strFile += _T("/tmp/file.bin");
2689                 m_pLog->SaveBuffer(strFile, pBufferFromFile, uiWriteByte);
2690 
2691                 strFile = szDateTime;
2692                 strFile += _T("/tmp/flash.bin");
2693                 m_pLog->SaveBuffer(strFile, pBufferFromFlash, uiWriteByte);
2694             }
2695             delete []pBufferFromFile;
2696             delete []pBufferFromFlash;
2697             return false;
2698         }
2699         //      if (uiBegin == entry.flash_offset)
2700         //      {
2701         //          tstring strFile;
2702         //          strFile = "/tmp/";
2703         //          strFile += entry.name;
2704         //          strFile += ".img";
2705         //          m_pLog->SaveBuffer( strFile,pBufferFromFlash,uiWriteByte );
2706         //          m_pLog->Record("%s=%x %x %x %x",entry.name,pBufferFromFlash[0],pBufferFromFlash[1],pBufferFromFlash[2],pBufferFromFlash[3]);
2707         //      }
2708 
2709         currentByte += uiWriteByte;
2710         uiEntryOffset += uiWriteByte;
2711         uifileBufferSize -= uiWriteByte;
2712         uiBegin += uiLen;
2713     }
2714 
2715     delete []pBufferFromFile;
2716     delete []pBufferFromFlash;
2717     return true;
2718 }
2719 
RKA_Param_Download(STRUCT_RKIMAGE_ITEM & entry,long long & currentByte,long long totalByte)2720 bool CRKAndroidDevice::RKA_Param_Download(STRUCT_RKIMAGE_ITEM &entry, long long &currentByte, long long totalByte)
2721 {
2722     //д5�ݲ����ļ�
2723     UINT uiLBATransferSize = (LBA_TRANSFER_SIZE_16K) * m_uiLBATimes;
2724     UINT uiLBASector = uiLBATransferSize / SECTOR_SIZE;
2725     int  iRet, i;
2726     BYTE byRWMethod = RWMETHOD_IMAGE;
2727     if (entry.flash_offset > m_dwBackupOffset)
2728     {
2729         byRWMethod = RWMETHOD_LBA;
2730     }
2731 
2732     UINT uiTransfer;
2733     UINT uiStepSec = entry.part_size / 8;
2734     //  if (m_pLog)
2735     //  {
2736     //      m_pLog->Record(_T("INFO:RKA_Param_Download-->step=%d"),uiStepSec);
2737     //  }
2738 
2739     UINT uiLen, uiWriteByte, uiFileSize;
2740     UINT uiBegin;
2741     for (i = 0; i < 8; i++)
2742     {
2743         uiFileSize = m_uiParamFileSize;
2744         uiBegin = entry.flash_offset + uiStepSec * i;
2745         uiLen = 0;
2746         uiWriteByte = 0;
2747         uiTransfer = 0;
2748         //      if (m_pLog)
2749         //      {
2750         //          m_pLog->Record(_T("INFO:RKA_Param_Download-->no %d,offset=%d"),i+1,uiBegin);
2751         //      }
2752         while (uiFileSize > 0)
2753         {
2754             if (uiFileSize < uiLBATransferSize)
2755             {
2756                 uiWriteByte = uiFileSize;
2757                 uiLen = ((uiWriteByte % 512 == 0) ? (uiWriteByte / 512) : (uiWriteByte / 512 + 1));
2758             }
2759             else
2760             {
2761                 uiWriteByte = uiLBATransferSize;
2762                 uiLen = uiLBASector;
2763             }
2764             iRet = m_pComm->RKU_WriteLBA(uiBegin, uiLen, m_paramBuffer + uiTransfer, byRWMethod); //ÿ�ζ�Ҫд32����,��page����
2765             if (iRet != ERR_SUCCESS)
2766             {
2767                 if (m_pLog)
2768                 {
2769                     m_pLog->Record(_T("ERROR:RKA_Param_Download-->RKU_WriteLBA failed,Written(%d),RetCode(%d)"), uiTransfer, iRet);
2770                 }
2771 
2772                 return false;
2773             }
2774 
2775             uiTransfer += uiWriteByte;
2776             currentByte += uiWriteByte;
2777             uiBegin += uiLen;
2778             uiFileSize -= uiWriteByte;
2779 
2780         }
2781     }
2782 
2783     return true;
2784 }
RKA_Param_Check(STRUCT_RKIMAGE_ITEM & entry,long long & currentByte,long long totalByte)2785 bool CRKAndroidDevice::RKA_Param_Check(STRUCT_RKIMAGE_ITEM &entry, long long &currentByte, long long totalByte)
2786 {
2787     UINT uiLBATransferSize = (LBA_TRANSFER_SIZE_16K) * m_uiLBATimes;
2788     UINT uiLBASector = uiLBATransferSize / SECTOR_SIZE;
2789     int iRet, i;
2790     UINT uiReadBufferSize = uiLBATransferSize;
2791     BYTE byRWMethod = RWMETHOD_IMAGE;
2792     if (entry.flash_offset > m_dwBackupOffset)
2793     {
2794         byRWMethod = RWMETHOD_LBA;
2795     }
2796 
2797     PBYTE pRead = NULL;
2798     pRead = new BYTE[uiReadBufferSize];
2799     if (!pRead)
2800     {
2801         if (m_pLog)
2802         {
2803             m_pLog->Record(_T("ERROR:RKA_Param_Check-->New ReadBuffer failed"));
2804         }
2805         return false;
2806     }
2807 
2808     UINT uiTransfer;
2809     UINT uiStepSec = entry.part_size / 8;
2810 
2811     UINT uiLen, uiWriteByte, uiFileSize;
2812     UINT uiBegin;
2813     for (i = 0; i < 8; i++)
2814     {
2815         uiFileSize = m_uiParamFileSize;
2816         uiBegin = entry.flash_offset + uiStepSec * i;
2817         uiLen = 0;
2818         uiWriteByte = 0;
2819         uiTransfer = 0;
2820         //      if (m_pLog)
2821         //      {
2822         //          m_pLog->Record(_T("INFO:RKA_Param_Check-->no %d,offset=%d"),i+1,uiBegin);
2823         //      }
2824         while (uiFileSize > 0)
2825         {
2826             memset(pRead, 0, uiReadBufferSize);
2827             if (uiFileSize < uiLBATransferSize)
2828             {
2829                 uiWriteByte = uiFileSize;
2830                 uiLen = ((uiWriteByte % 512 == 0) ? (uiWriteByte / 512) : (uiWriteByte / 512 + 1));
2831             }
2832             else
2833             {
2834                 uiWriteByte = uiLBATransferSize;
2835                 uiLen = uiLBASector;
2836             }
2837             iRet = m_pComm->RKU_ReadLBA(uiBegin, uiLen, pRead, byRWMethod);
2838             if (iRet != ERR_SUCCESS)
2839             {
2840                 if (m_pLog)
2841                 {
2842                     m_pLog->Record(_T("ERROR:RKA_Param_Check-->RKU_ReadLBA failed,Read(%d),RetCode(%d)"), uiTransfer, iRet);
2843                 }
2844                 delete []pRead;
2845                 return false;
2846             }
2847             if (memcmp(pRead, m_paramBuffer + uiTransfer, uiWriteByte) != 0)
2848             {
2849                 if (m_pLog)
2850                 {
2851                     m_pLog->Record(_T("ERROR:RKA_Param_Check-->Memcmp failed,Read(%d)"), uiTransfer);
2852                     tchar szDateTime[100];
2853                     tstring strFile;
2854                     time_t  now;
2855                     struct tm timeNow;
2856                     time(&now);
2857                     localtime_r(&now, &timeNow);
2858                     _stprintf(szDateTime, _T("%02d-%02d-%02d"), timeNow.tm_hour + 1, timeNow.tm_min + 1, timeNow.tm_sec + 1);
2859 
2860                     strFile = szDateTime;
2861                     strFile += _T("/tmp/file.bin");
2862                     m_pLog->SaveBuffer(strFile, m_paramBuffer + uiTransfer, uiWriteByte);
2863 
2864                     strFile = szDateTime;
2865                     strFile += _T("/tmp/flash.bin");
2866                     m_pLog->SaveBuffer(strFile, pRead, uiWriteByte);
2867                 }
2868 
2869                 delete []pRead;
2870                 return false;
2871 
2872             }
2873             //          if (m_pLog)
2874             //          {
2875             //              string strSrc,strDst;
2876             //              if (uiWriteByte>16)
2877             //              {
2878             //                  m_pLog->PrintBuffer(strSrc,pRead,16);
2879             //                  m_pLog->PrintBuffer(strDst,m_paramBuffer+uiTransfer,16);
2880             //              }
2881             //              else
2882             //              {
2883             //                  m_pLog->PrintBuffer(strSrc,pRead,uiWriteByte);
2884             //                  m_pLog->PrintBuffer(strDst,m_paramBuffer+uiTransfer,uiWriteByte);
2885             //              }
2886             //              m_pLog->Record("Read:%s",strSrc.c_str());
2887             //              m_pLog->Record("Compare:%s",strDst.c_str());
2888             //          }
2889             uiTransfer += uiWriteByte;
2890             currentByte += uiWriteByte;
2891             uiBegin += uiLen;
2892             uiFileSize -= uiWriteByte;
2893 
2894         }
2895     }
2896 
2897     delete []pRead;
2898     return true;
2899 }
2900 
RKA_Gpt_Download(STRUCT_RKIMAGE_ITEM & entry,long long & currentByte,long long totalByte)2901 bool CRKAndroidDevice::RKA_Gpt_Download(STRUCT_RKIMAGE_ITEM &entry, long long &currentByte, long long totalByte)
2902 {
2903     UINT uiLBATransferSize = (LBA_TRANSFER_SIZE_16K) * m_uiLBATimes;
2904     UINT uiLBALoopLimit = (LBA_LOOP_SIZE) / uiLBATransferSize;
2905     UINT uiLBASector = uiLBATransferSize / SECTOR_SIZE;
2906     int  iRet;
2907     bool bRet;
2908     PARAM_ITEM_VECTOR vecItems;
2909     CONFIG_ITEM_VECTOR vecUuids;
2910     BYTE byRWMethod = RWMETHOD_IMAGE;
2911     BYTE *backup_gpt;
2912 
2913     if (!m_gptBuffer)
2914     {
2915         m_gptBuffer = new BYTE[SECTOR_SIZE * 67];
2916         if (!m_gptBuffer)
2917         {
2918             if (m_pLog)
2919             {
2920                 m_pLog->Record(_T("ERROR:RKA_Gpt_Download-->new memory failed,err=%d)"), errno);
2921             }
2922             return false;
2923         }
2924     }
2925     memset(m_gptBuffer, 0, SECTOR_SIZE * 67);
2926     bRet = parse_parameter((char *)(m_paramBuffer + 8), vecItems);
2927     if (!bRet)
2928     {
2929         if (m_pLog)
2930         {
2931             m_pLog->Record(_T("ERROR:RKA_Gpt_Download-->parse_parameter failed)"));
2932         }
2933         return false;
2934     }
2935     bRet = get_uuid_from_parameter((char *)(m_paramBuffer + 8), vecUuids);
2936     backup_gpt = m_gptBuffer + 34 * SECTOR_SIZE;
2937 
2938     //create_gpt_buffer(m_gptBuffer,vecItems,vecUuids,m_flashInfo.uiFlashSize*2048);
2939     create_gpt_buffer(m_gptBuffer, vecItems, vecUuids, m_flashInfo.uiBlockNum);
2940     memcpy(backup_gpt, m_gptBuffer + 2 * SECTOR_SIZE, 32 * SECTOR_SIZE);
2941     memcpy(backup_gpt + 32 * SECTOR_SIZE, m_gptBuffer + SECTOR_SIZE, SECTOR_SIZE);
2942     prepare_gpt_backup(m_paramBuffer, backup_gpt);
2943 
2944     iRet = m_pComm->RKU_WriteLBA(0, 34, m_gptBuffer);
2945     if (iRet != ERR_SUCCESS)
2946     {
2947         if (m_pLog)
2948         {
2949             m_pLog->Record(_T("ERROR:RKA_Gpt_Download-->write gpt master failed,RetCode(%d)"), iRet);
2950         }
2951         return false;
2952     }
2953 
2954     DWORD dwPos;
2955     //dwPos = m_flashInfo.uiFlashSize*2048-33;
2956     dwPos = m_flashInfo.uiBlockNum - 33;
2957     iRet = m_pComm->RKU_WriteLBA(dwPos, 33, backup_gpt);
2958     if (iRet != ERR_SUCCESS)
2959     {
2960         if (m_pLog)
2961         {
2962             m_pLog->Record(_T("ERROR:RKA_Gpt_Download-->write gpt backup failed,RetCode(%d)"), iRet);
2963         }
2964         return false;
2965     }
2966     currentByte += (SECTOR_SIZE * 67);
2967 
2968     return true;
2969 }
RKA_Gpt_Check(STRUCT_RKIMAGE_ITEM & entry,long long & currentByte,long long totalByte)2970 bool CRKAndroidDevice::RKA_Gpt_Check(STRUCT_RKIMAGE_ITEM &entry, long long &currentByte, long long totalByte)
2971 {
2972     UINT uiLBATransferSize = (LBA_TRANSFER_SIZE_16K) * m_uiLBATimes;
2973     UINT uiLBALoopLimit = (LBA_LOOP_SIZE) / uiLBATransferSize;
2974     UINT uiLBASector = uiLBATransferSize / SECTOR_SIZE;
2975     int iRet;
2976     BYTE byRWMethod = RWMETHOD_IMAGE;
2977 
2978     PBYTE pRead = NULL;
2979     pRead = new BYTE[34 * SECTOR_SIZE];
2980     if (!pRead)
2981     {
2982         if (m_pLog)
2983         {
2984             m_pLog->Record(_T("ERROR:RKA_Gpt_Check-->New ReadBuffer failed,err=%d"), errno);
2985         }
2986         return false;
2987     }
2988     iRet = m_pComm->RKU_ReadLBA(0, 34, pRead);
2989     if (iRet != ERR_SUCCESS)
2990     {
2991         if (m_pLog)
2992         {
2993             m_pLog->Record(_T("ERROR:RKA_Gpt_Download-->read gpt master failed,RetCode(%d)"), iRet);
2994         }
2995         delete []pRead;
2996         return false;
2997     }
2998     if (memcmp(m_gptBuffer, pRead, 34 * SECTOR_SIZE) != 0)
2999     {
3000         if (m_pLog)
3001         {
3002             if (m_pLog)
3003             {
3004                 m_pLog->Record(_T("ERROR:RKA_Gpt_Download-->compare gpt master failed"));
3005             }
3006             tchar szDateTime[100];
3007             tstring strFile;
3008             time_t  now;
3009             struct tm timeNow;
3010             time(&now);
3011             localtime_r(&now, &timeNow);
3012             _stprintf(szDateTime, _T("%02d-%02d-%02d"), timeNow.tm_hour + 1, timeNow.tm_min + 1, timeNow.tm_sec + 1);
3013             strFile = m_pLog->LogSavePath;
3014             strFile += szDateTime;
3015             strFile += _T("file.bin");
3016             m_pLog->SaveBuffer(strFile, m_gptBuffer, 34 * SECTOR_SIZE);
3017             strFile = m_pLog->LogSavePath;
3018             strFile += szDateTime;
3019             strFile += _T("flash.bin");
3020             m_pLog->SaveBuffer(strFile, pRead, 34 * SECTOR_SIZE);
3021         }
3022         delete []pRead;
3023         return false;
3024     }
3025 
3026     iRet = m_pComm->RKU_ReadLBA(m_flashInfo.uiBlockNum - 33, 33, pRead);
3027     //iRet = m_pComm->RKU_ReadLBA(m_flashInfo.uiFlashSize*2048-33,33,pRead);
3028     if (iRet != ERR_SUCCESS)
3029     {
3030         if (m_pLog)
3031         {
3032             m_pLog->Record(_T("ERROR:RKA_Gpt_Download-->read gpt backup failed,RetCode(%d)"), iRet);
3033         }
3034         delete []pRead;
3035         return false;
3036     }
3037     if (memcmp(m_gptBuffer + 34 * SECTOR_SIZE, pRead, 33 * SECTOR_SIZE) != 0)
3038     {
3039         if (m_pLog)
3040         {
3041             if (m_pLog)
3042             {
3043                 m_pLog->Record(_T("ERROR:RKA_Gpt_Download-->compare gpt backup failed"));
3044             }
3045             tchar szDateTime[100];
3046             tstring strFile;
3047             time_t  now;
3048             struct tm timeNow;
3049             time(&now);
3050             localtime_r(&now, &timeNow);
3051             _stprintf(szDateTime, _T("%02d-%02d-%02d"), timeNow.tm_hour + 1, timeNow.tm_min + 1, timeNow.tm_sec + 1);
3052             strFile = m_pLog->LogSavePath;
3053             strFile += szDateTime;
3054             strFile += _T("file.bin");
3055             m_pLog->SaveBuffer(strFile, m_gptBuffer + 34 * SECTOR_SIZE, 33 * SECTOR_SIZE);
3056             strFile = m_pLog->LogSavePath;
3057             strFile += szDateTime;
3058             strFile += _T("flash.bin");
3059             m_pLog->SaveBuffer(strFile, pRead, 33 * SECTOR_SIZE);
3060         }
3061         delete []pRead;
3062         return false;
3063     }
3064     currentByte += (SECTOR_SIZE * 67);
3065 
3066     delete []pRead;
3067     return true;
3068 }
3069 
MakeParamFileBuffer(STRUCT_RKIMAGE_ITEM & entry)3070 bool CRKAndroidDevice::MakeParamFileBuffer(STRUCT_RKIMAGE_ITEM &entry)
3071 {
3072     bool bRet;
3073     UINT uiFileBufferSize;
3074     long long dwFWOffset;
3075 
3076     dwFWOffset = m_pImage->FWOffset;
3077     uiFileBufferSize = 2 * entry.size;
3078     m_uiParamFileSize = entry.size;
3079     PBYTE pBuffer = NULL;
3080     pBuffer = new BYTE[uiFileBufferSize];
3081     if (!pBuffer)
3082     {
3083         if (m_pLog)
3084         {
3085             m_pLog->Record(_T("ERROR:MakeParamFileBuffer-->New memory failed"));
3086         }
3087         return false;
3088     }
3089     memset(pBuffer, 0, uiFileBufferSize);
3090     bRet = m_pImage->GetData(dwFWOffset + entry.offset, entry.size, pBuffer);
3091     if (!bRet)
3092     {
3093         if (m_pLog)
3094         {
3095             m_pLog->Record(_T("ERROR:MakeParamFileBuffer-->GetFileData failed"));
3096         }
3097         delete[] pBuffer;
3098         pBuffer = NULL;
3099         return false;
3100     }
3101     //�ж��Ƿ�Ҫ�޸�Paramter�ļ�����,�ֻ�������Ҫ��paramter�ļ��е�partition�������ݸij����ֽ�Ϊ��λ����ƫ��
3102 
3103     UINT uiParamSec;
3104     if (m_uiParamFileSize % 512 == 0)
3105     {
3106         uiParamSec = m_uiParamFileSize / 512;
3107     }
3108     else
3109     {
3110         uiParamSec = (m_uiParamFileSize + 512) / 512;
3111     }
3112 
3113     if (m_paramBuffer)
3114     {
3115         delete []m_paramBuffer;
3116         m_paramBuffer = NULL;
3117     }
3118     m_paramBuffer = new BYTE[uiParamSec * 512];
3119     if (!m_paramBuffer)
3120     {
3121         if (m_pLog)
3122         {
3123             m_pLog->Record(_T("ERROR:MakeParamFileBuffer-->new memory failed"));
3124         }
3125         delete []pBuffer;
3126         return false;
3127     }
3128     memset(m_paramBuffer, 0, uiParamSec * 512);
3129     memcpy(m_paramBuffer, pBuffer, m_uiParamFileSize);
3130     delete []pBuffer;
3131     return true;
3132 }
CheckParamPartSize(STRUCT_RKIMAGE_HDR & rkImageHead,int iParamPos)3133 bool CRKAndroidDevice::CheckParamPartSize(STRUCT_RKIMAGE_HDR &rkImageHead, int iParamPos)
3134 {
3135     //  UINT uiParamPartSize;
3136     //  int i;
3137     //  uiParamPartSize = 0xFFFFFFFF;
3138     //  for (i=0;i<rkImageHead.item_count;i++)
3139     //  {
3140     //      if (i!=iParamPos)
3141     //      {
3142     //          if (rkImageHead.item[i].flash_offset<uiParamPartSize)
3143     //          {
3144     //              uiParamPartSize = rkImageHead.item[i].flash_offset;
3145     //          }
3146     //      }
3147     //  }
3148     if (!GetParameterPartSize(rkImageHead.item[iParamPos]))
3149     {
3150         return false;
3151     }
3152     if (m_uiParamFileSize > rkImageHead.item[iParamPos].part_size / 8 * 512) //�Ƿ�������8��
3153     {
3154         return false;
3155     }
3156 
3157     return true;
3158 }
IsExistSector3Crc(PRKANDROID_IDB_SEC2 pSec)3159 bool CRKAndroidDevice::IsExistSector3Crc(PRKANDROID_IDB_SEC2 pSec)
3160 {
3161     if (!pSec)
3162     {
3163         return false;
3164     }
3165 
3166     if (strcmp(pSec->szCrcTag, "CRC") == 0)
3167     {
3168         m_bExistSector3Crc = true;
3169         m_usSector3Crc = pSec->usSec3Crc;
3170     }
3171     return true;
3172 }
ParsePartitionInfo(string & strPartInfo,string & strName,UINT & uiOffset,UINT & uiLen)3173 bool CRKAndroidDevice::ParsePartitionInfo(string &strPartInfo, string &strName, UINT &uiOffset, UINT &uiLen)
3174 {
3175     string::size_type pos, prevPos;
3176     string strOffset, strLen;
3177     int iCount;
3178     prevPos = pos = 0;
3179     if (strPartInfo.size() <= 0)
3180     {
3181         return false;
3182     }
3183     pos = strPartInfo.find('@');
3184     if (pos == string::npos)
3185     {
3186         return false;
3187     }
3188     strLen = strPartInfo.substr(prevPos, pos - prevPos);
3189     strLen.erase(0, strLen.find_first_not_of(" "));
3190     strLen.erase(strLen.find_last_not_of(" ") + 1);
3191     if (strchr(strLen.c_str(), '-'))
3192     {
3193         uiLen = 0xFFFFFFFF;
3194     }
3195     else
3196     {
3197         iCount = sscanf(strLen.c_str(), "0x%x", &uiLen);
3198         if (iCount != 1)
3199         {
3200             return false;
3201         }
3202     }
3203 
3204     prevPos = pos + 1;
3205     pos = strPartInfo.find('(', prevPos);
3206     if (pos == string::npos)
3207     {
3208         return false;
3209     }
3210     strOffset = strPartInfo.substr(prevPos, pos - prevPos);
3211     strOffset.erase(0, strOffset.find_first_not_of(" "));
3212     strOffset.erase(strOffset.find_last_not_of(" ") + 1);
3213     iCount = sscanf(strOffset.c_str(), "0x%x", &uiOffset);
3214     if (iCount != 1)
3215     {
3216         return false;
3217     }
3218 
3219     prevPos = pos + 1;
3220     pos = strPartInfo.find(')', prevPos);
3221     if (pos == string::npos)
3222     {
3223         return false;
3224     }
3225     strName = strPartInfo.substr(prevPos, pos - prevPos);
3226     strName.erase(0, strName.find_first_not_of(" "));
3227     strName.erase(strName.find_last_not_of(" ") + 1);
3228 
3229     return true;
3230 }
GetParameterPartSize(STRUCT_RKIMAGE_ITEM & paramItem)3231 bool CRKAndroidDevice::GetParameterPartSize(STRUCT_RKIMAGE_ITEM &paramItem)
3232 {
3233     PBYTE pParamBuf = NULL;
3234     pParamBuf = new BYTE[paramItem.size - 12 + 1];
3235     if (!pParamBuf)
3236     {
3237         return false;
3238     }
3239     memset(pParamBuf, 0, paramItem.size - 12 + 1);
3240     bool bRet;
3241     bRet = m_pImage->GetData(m_pImage->FWOffset + paramItem.offset + 8, paramItem.size - 12, pParamBuf);
3242     if (!bRet)
3243     {
3244         delete []pParamBuf;
3245         return false;
3246     }
3247     string strParamFile = (char *)pParamBuf;
3248     stringstream paramStream(strParamFile);
3249     delete []pParamBuf;
3250 
3251     string strLine, strPartition, strPartInfo, strPartName;
3252     string::size_type line_size, pos, posColon, posComma;
3253     UINT uiPartOffset, uiPartSize;
3254     while (!paramStream.eof())
3255     {
3256         getline(paramStream, strLine);
3257         line_size = strLine.size();
3258         if (line_size <= 0)
3259         {
3260             continue;
3261         }
3262         if (strLine[line_size - 1] == '\r')
3263         {
3264             strLine = strLine.substr(0, line_size - 1);
3265         }
3266         if (strLine.size() <= 0)
3267         {
3268             continue;
3269         }
3270         if (strLine[0] == '#')
3271         {
3272             continue;
3273         }
3274         pos = strLine.find("mtdparts");
3275         if (pos == string::npos)
3276         {
3277             continue;
3278         }
3279         posColon = strLine.find(':', pos);
3280         if (posColon == string::npos)
3281         {
3282             continue;
3283         }
3284         strPartition = strLine.substr(posColon + 1);
3285         //��ȡ������Ϣ
3286         pos = 0;
3287         posComma = strPartition.find(',', pos);
3288         while (posComma != string::npos)
3289         {
3290             strPartInfo = strPartition.substr(pos, posComma - pos);
3291             bRet = ParsePartitionInfo(strPartInfo, strPartName, uiPartOffset, uiPartSize);
3292             if (!bRet)
3293             {
3294                 if (m_pLog)
3295                 {
3296                     m_pLog->Record(_T("ERROR:GetParameterPartSize-->ParsePartitionInfo failed"));
3297                 }
3298                 return false;
3299             }
3300             paramItem.part_size = uiPartOffset;
3301             return true;
3302         }
3303     }
3304     return false;
3305 }
3306 
GetPublicKey(unsigned char * pKey,unsigned int & nKeySize)3307 bool CRKAndroidDevice::GetPublicKey(unsigned char *pKey, unsigned int &nKeySize)
3308 {
3309     int i, j, iRet, nRsaByte;
3310     bool bRet;
3311     BYTE bData[SECTOR_SIZE * 8];
3312     PRKANDROID_IDB_SEC0 pSec0 = (PRKANDROID_IDB_SEC0)bData;
3313     PRK_SECURE_HEADER pSecureHdr = (PRK_SECURE_HEADER)(bData + SECTOR_SIZE * 4);
3314     string strOutput;
3315     bRet = GetFlashInfo();
3316     if (!bRet)
3317     {
3318         if (m_pLog)
3319         {
3320             m_pLog->Record(_T("ERROR:GetPublicKey-->GetFlashInfo failed"));
3321         }
3322         return false;
3323     }
3324     if (!BuildBlockStateMap(0))
3325     {
3326         if (m_pLog)
3327         {
3328             m_pLog->Record(_T("ERROR:GetPublicKey-->BuildBlockStateMap failed"));
3329         }
3330         return false;
3331     }
3332 
3333     FindAllIDB();
3334     //  sleep(1);
3335     //  if (m_pLog)
3336     //  {
3337     //      m_pLog->Record(_T("INFO:GetPublicKey-->IDblock count=%d."),m_oldIDBCounts);
3338     //  }
3339     if (m_oldIDBCounts <= 0)
3340     {
3341         if (m_pLog)
3342         {
3343             m_pLog->Record(_T("ERROR:GetPublicKey-->IDblock count=%d."), m_oldIDBCounts);
3344         }
3345         return false;
3346     }
3347     for (i = 0; i < m_oldIDBCounts; i++)
3348     {
3349         iRet = m_pComm->RKU_ReadSector(m_idBlockOffset[i] * m_flashInfo.uiSectorPerBlock, 8, bData);
3350         //      sleep(1);
3351         if (iRet != ERR_SUCCESS)
3352         {
3353             if (m_pLog)
3354             {
3355                 m_pLog->Record(_T("ERROR:GetPublicKey-->RKU_ReadSector failed,RetCode(%d)"), iRet);
3356             }
3357             return false;
3358         }
3359 
3360         P_RC4(bData, SECTOR_SIZE);
3361 
3362         if (pSec0->uiRc4Flag == 0)
3363         {
3364             //          if (m_pLog)
3365             //          {
3366             //              m_pLog->PrintBuffer(strOutput,bData+4*512,512,16);
3367             //              m_pLog->Record("INFO:secure header\n%s",strOutput.c_str());
3368             //          }
3369             for (j = 0; j < 4; j++)
3370             {
3371                 P_RC4(bData + SECTOR_SIZE * (j + 4), SECTOR_SIZE);
3372             }
3373             //          if (m_pLog)
3374             //          {
3375             //              m_pLog->PrintBuffer(strOutput,bData+4*512,512,16);
3376             //              m_pLog->Record("INFO:secure header rc4\n%s",strOutput.c_str());
3377             //          }
3378         }
3379         //      if (m_pLog)
3380         //      {
3381         //          m_pLog->Record("INFO:secure header tag=0x%x",pSecureHdr->uiTag);
3382         //      }
3383         if (pSecureHdr->uiTag == 0x4B415352)
3384         {
3385             nRsaByte = pSecureHdr->usRsaBit / 8;
3386             *((USHORT *)pKey) = pSecureHdr->usRsaBit;
3387             for (j = 0; j < nRsaByte; j++)
3388             {
3389                 *(pKey + j + 2) = pSecureHdr->nFactor[nRsaByte - j - 1];
3390             }
3391             for (j = 0; j < nRsaByte; j++)
3392             {
3393                 *(pKey + j + 2 + nRsaByte) = pSecureHdr->eFactor[nRsaByte - j - 1];
3394             }
3395             nKeySize = nRsaByte * 2 + 2;
3396             //          if (m_pLog)
3397             //          {
3398             //              m_pLog->PrintBuffer(strOutput,pKey,nKeySize,16);
3399             //              m_pLog->Record("INFO:Key\n%s",strOutput.c_str());
3400             //          }
3401             return true;
3402         }
3403 
3404     }
3405 
3406     return false;
3407 }
3408 
GetParameterGptFlag(STRUCT_RKIMAGE_ITEM & paramItem)3409 bool CRKAndroidDevice::GetParameterGptFlag(STRUCT_RKIMAGE_ITEM &paramItem)
3410 {
3411     PBYTE pParamBuf = NULL;
3412     bool bGpt = false;
3413     pParamBuf = new BYTE[paramItem.size - 12 + 1];
3414     if (!pParamBuf)
3415     {
3416         return false;
3417     }
3418     memset(pParamBuf, 0, paramItem.size - 12 + 1);
3419     bool bRet;
3420     bRet = m_pImage->GetData(m_pImage->FWOffset + paramItem.offset + 8, paramItem.size - 12, pParamBuf);
3421     if (!bRet)
3422     {
3423         delete []pParamBuf;
3424         return false;
3425     }
3426     string strParamFile = (char *)pParamBuf;
3427     stringstream paramStream(strParamFile);
3428     delete []pParamBuf;
3429 
3430 
3431     string strLine;
3432     string::size_type pos, line_size;
3433     while (!paramStream.eof())
3434     {
3435         getline(paramStream, strLine);
3436         line_size = strLine.size();
3437         if (line_size <= 0)
3438         {
3439             continue;
3440         }
3441         if (strLine[line_size - 1] == '\r')
3442         {
3443             strLine = strLine.substr(0, line_size - 1);
3444         }
3445         if (strLine.size() <= 0)
3446         {
3447             continue;
3448         }
3449         if (strLine[0] == '#')
3450         {
3451             continue;
3452         }
3453         transform(strLine.begin(), strLine.end(), strLine.begin(), (int(*)(int))toupper);
3454         pos = strLine.find("TYPE");
3455         if (pos == string::npos)
3456         {
3457             continue;
3458         }
3459         if ((pos = strLine.find("GPT")) != string::npos)
3460         {
3461             bGpt = true;
3462             break;
3463         }
3464         else
3465         {
3466             continue;
3467         }
3468     }
3469     return bGpt;
3470 }
3471 
3472 #define DO_CRC(x) crc = tab[ (crc ^ (x)) & 255 ] ^ (crc>>8)
crc32_le(unsigned int crc,unsigned char * p,unsigned int len)3473 unsigned int crc32_le(unsigned int crc, unsigned char *p, unsigned int len)
3474 {
3475     unsigned int      *b = (unsigned int *)p;
3476     unsigned int      *tab = crc32table_le;
3477     crc = crc ^ 0xFFFFFFFF;
3478     if ((((long)b) & 3 && len))
3479     {
3480         do
3481         {
3482             unsigned char *p = (unsigned char *)b;
3483             DO_CRC(*p++);
3484             b = (unsigned int *)p;
3485         } while ((--len) && ((long)b) & 3);
3486     }
3487     if ((len >= 4))
3488     {
3489         unsigned int save_len = len & 3;
3490         len = len >> 2;
3491         --b;
3492         do
3493         {
3494             crc ^= *++b;
3495             DO_CRC(0);
3496             DO_CRC(0);
3497             DO_CRC(0);
3498             DO_CRC(0);
3499         } while (--len);
3500         b++;
3501         len = save_len;
3502     }
3503     if (len)
3504     {
3505         do
3506         {
3507             unsigned char *p = (unsigned char *)b;
3508             DO_CRC(*p++);
3509             b = (unsigned int *)p;
3510         } while (--len);
3511     }
3512     crc = crc ^ 0xFFFFFFFF;
3513     return crc;
3514 
3515 }
prepare_gpt_backup(u8 * master,u8 * backup)3516 void prepare_gpt_backup(u8 *master, u8 *backup)
3517 {
3518     gpt_header *gptMasterHead = (gpt_header *)(master + SECTOR_SIZE);
3519     gpt_header *gptBackupHead = (gpt_header *)(backup + 32 * SECTOR_SIZE);
3520     u32 calc_crc32;
3521     u64 val;
3522 
3523     /* recalculate the values for the Backup GPT Header */
3524     val = le64_to_cpu(gptMasterHead->my_lba);
3525     gptBackupHead->my_lba = gptMasterHead->alternate_lba;
3526     gptBackupHead->alternate_lba = cpu_to_le64(val);
3527     gptBackupHead->partition_entry_lba = cpu_to_le64(le64_to_cpu(gptMasterHead->last_usable_lba) + 1);
3528     gptBackupHead->header_crc32 = 0;
3529 
3530     calc_crc32 = crc32_le(0, (unsigned char *)gptBackupHead, le32_to_cpu(gptBackupHead->header_size));
3531     gptBackupHead->header_crc32 = cpu_to_le32(calc_crc32);
3532 }
gen_rand_uuid(unsigned char * uuid_bin)3533 void gen_rand_uuid(unsigned char *uuid_bin)
3534 {
3535     efi_guid_t id;
3536     unsigned int *ptr = (unsigned int *)&id;
3537     unsigned int i;
3538 
3539     /* Set all fields randomly */
3540     for (i = 0; i < sizeof(id) / sizeof(*ptr); i++)
3541     {
3542         *(ptr + i) = cpu_to_be32(rand());
3543     }
3544 
3545     id.uuid.time_hi_and_version = (id.uuid.time_hi_and_version & 0x0FFF) | 0x4000;
3546     id.uuid.clock_seq_hi_and_reserved = id.uuid.clock_seq_hi_and_reserved | 0x80;
3547 
3548     memcpy(uuid_bin, id.raw, sizeof(id));
3549 }
create_gpt_buffer(u8 * gpt,PARAM_ITEM_VECTOR & vecParts,CONFIG_ITEM_VECTOR & vecUuid,u64 diskSectors)3550 void create_gpt_buffer(u8 *gpt, PARAM_ITEM_VECTOR &vecParts, CONFIG_ITEM_VECTOR &vecUuid, u64 diskSectors)
3551 {
3552     legacy_mbr *mbr = (legacy_mbr *)gpt;
3553     gpt_header *gptHead = (gpt_header *)(gpt + SECTOR_SIZE);
3554     gpt_entry *gptEntry = (gpt_entry *)(gpt + 2 * SECTOR_SIZE);
3555     u32 i, j;
3556     int pos;
3557     tstring strPartName;
3558     string::size_type iPos;
3559     /*1.protective mbr*/
3560     memset(gpt, 0, SECTOR_SIZE);
3561     mbr->signature = MSDOS_MBR_SIGNATURE;
3562     mbr->partition_record[0].sys_ind = EFI_PMBR_OSTYPE_EFI_GPT;
3563     mbr->partition_record[0].start_sect = 1;
3564     mbr->partition_record[0].nr_sects = (u32) - 1;
3565     /*2.gpt header*/
3566     memset(gpt + SECTOR_SIZE, 0, SECTOR_SIZE);
3567     gptHead->signature = cpu_to_le64(GPT_HEADER_SIGNATURE);
3568     gptHead->revision = cpu_to_le32(GPT_HEADER_REVISION_V1);
3569     gptHead->header_size = cpu_to_le32(sizeof(gpt_header));
3570     gptHead->my_lba = cpu_to_le64(1);
3571     gptHead->alternate_lba = cpu_to_le64(diskSectors - 1);
3572     gptHead->first_usable_lba = cpu_to_le64(34);
3573     gptHead->last_usable_lba = cpu_to_le64(diskSectors - 34);
3574     gptHead->partition_entry_lba = cpu_to_le64(2);
3575     gptHead->num_partition_entries = cpu_to_le32(GPT_ENTRY_NUMBERS);
3576     gptHead->sizeof_partition_entry = cpu_to_le32(GPT_ENTRY_SIZE);
3577     gptHead->header_crc32 = 0;
3578     gptHead->partition_entry_array_crc32 = 0;
3579     gen_rand_uuid(gptHead->disk_guid.raw);
3580 
3581     /*3.gpt partition entry*/
3582     memset(gpt + 2 * SECTOR_SIZE, 0, 32 * SECTOR_SIZE);
3583     for (i = 0; i < vecParts.size(); i++)
3584     {
3585         gen_rand_uuid(gptEntry->partition_type_guid.raw);
3586         gen_rand_uuid(gptEntry->unique_partition_guid.raw);
3587         gptEntry->starting_lba = cpu_to_le64(vecParts[i].uiItemOffset);
3588         gptEntry->ending_lba = cpu_to_le64(gptEntry->starting_lba + vecParts[i].uiItemSize - 1);
3589         gptEntry->attributes.raw = 0;
3590         strPartName = vecParts[i].szItemName;
3591         iPos = strPartName.find(_T(':'));
3592         if (iPos != tstring::npos)
3593         {
3594             transform(strPartName.begin(), strPartName.end(), strPartName.begin(), (int(*)(int))tolower);
3595             if (strPartName.find(_T("bootable")) != tstring::npos)
3596             {
3597                 gptEntry->attributes.raw = PART_PROPERTY_BOOTABLE;
3598             }
3599             if (strPartName.find(_T("grow")) != tstring::npos)
3600             {
3601                 gptEntry->ending_lba = cpu_to_le64(diskSectors - 34);
3602             }
3603             strPartName = strPartName.substr(0, iPos);
3604             vecParts[i].szItemName[strPartName.size()] = 0;
3605         }
3606         for (j = 0; j < _tcslen(vecParts[i].szItemName); j++)
3607         {
3608             gptEntry->partition_name[j] = vecParts[i].szItemName[j];
3609         }
3610         if ((pos = find_uuid_item(vecUuid, vecParts[i].szItemName)) != -1)
3611         {
3612             memcpy(gptEntry->unique_partition_guid.raw, vecUuid[pos].szItemValue, 16);
3613         }
3614         gptEntry++;
3615     }
3616 
3617     gptHead->partition_entry_array_crc32 = cpu_to_le32(crc32_le(0, gpt + 2 * SECTOR_SIZE, GPT_ENTRY_SIZE * GPT_ENTRY_NUMBERS));
3618     gptHead->header_crc32 = cpu_to_le32(crc32_le(0, gpt + SECTOR_SIZE, sizeof(gpt_header)));
3619 
3620 }
ParseUuidInfo(string & strUuidInfo,string & strName,string & strUUid)3621 bool ParseUuidInfo(string &strUuidInfo, string &strName, string &strUUid)
3622 {
3623     string::size_type pos(0);
3624 
3625     if (strUuidInfo.size() <= 0)
3626     {
3627         return false;
3628     }
3629     pos = strUuidInfo.find('=');
3630     if (pos == string::npos)
3631     {
3632         return false;
3633     }
3634     strName = strUuidInfo.substr(0, pos);
3635     strName.erase(0, strName.find_first_not_of(" "));
3636     strName.erase(strName.find_last_not_of(" ") + 1);
3637 
3638     strUUid = strUuidInfo.substr(pos + 1);
3639     strUUid.erase(0, strUUid.find_first_not_of(" "));
3640     strUUid.erase(strUUid.find_last_not_of(" ") + 1);
3641 
3642     while (true)
3643     {
3644         pos = 0;
3645         if ((pos = strUUid.find("-")) != string::npos)
3646         {
3647             strUUid.replace(pos, 1, "");
3648         }
3649         else
3650         {
3651             break;
3652         }
3653     }
3654     if (strUUid.size() != 32)
3655     {
3656         return false;
3657     }
3658     return true;
3659 }
string_to_uuid(string strUUid,char * uuid)3660 void string_to_uuid(string strUUid, char *uuid)
3661 {
3662     unsigned int i;
3663     char value;
3664     memset(uuid, 0, 16);
3665     for (i = 0; i < strUUid.size(); i++)
3666     {
3667         value = 0;
3668         if ((strUUid[i] >= '0') && (strUUid[i] <= '9'))
3669         {
3670             value = strUUid[i] - '0';
3671         }
3672         if ((strUUid[i] >= 'a') && (strUUid[i] <= 'f'))
3673         {
3674             value = strUUid[i] - 'a' + 10;
3675         }
3676         if ((strUUid[i] >= 'A') && (strUUid[i] <= 'F'))
3677         {
3678             value = strUUid[i] - 'A' + 10;
3679         }
3680         if ((i % 2) == 0)
3681         {
3682             uuid[i / 2] += (value << 4);
3683         }
3684         else
3685         {
3686             uuid[i / 2] += value;
3687         }
3688     }
3689     unsigned int *p32;
3690     unsigned short *p16;
3691     p32 = (unsigned int *)uuid;
3692     *p32 = cpu_to_be32(*p32);
3693     p16 = (unsigned short *)(uuid + 4);
3694     *p16 = cpu_to_be16(*p16);
3695     p16 = (unsigned short *)(uuid + 6);
3696     *p16 = cpu_to_be16(*p16);
3697 }
get_uuid_from_parameter(char * pParameter,CONFIG_ITEM_VECTOR & vecItem)3698 bool get_uuid_from_parameter(char *pParameter, CONFIG_ITEM_VECTOR &vecItem)
3699 {
3700     stringstream paramStream(pParameter);
3701     bool bRet;
3702     string strLine, strUUid, strPartInfo, strPartName;
3703     string::size_type line_size, pos, posColon, posComma;
3704     STRUCT_CONFIG_ITEM uuid_item;
3705     vecItem.clear();
3706     while (!paramStream.eof())
3707     {
3708         getline(paramStream, strLine);
3709         line_size = strLine.size();
3710         if (line_size == 0)
3711         {
3712             continue;
3713         }
3714         if (strLine[line_size - 1] == '\r')
3715         {
3716             strLine = strLine.substr(0, line_size - 1);
3717         }
3718         pos = strLine.find("uuid:");
3719         if (pos != string::npos)
3720         {
3721             strPartInfo = strLine.substr(pos + 5);
3722             bRet = ParseUuidInfo(strPartInfo, strPartName, strUUid);
3723             if (bRet)
3724             {
3725                 strcpy(uuid_item.szItemName, strPartName.c_str());
3726                 string_to_uuid(strUUid, uuid_item.szItemValue);
3727                 vecItem.push_back(uuid_item);
3728             }
3729         }
3730     }
3731     return (vecItem.size() > 0);
3732 }
find_uuid_item(CONFIG_ITEM_VECTOR & vecItems,char * pszName)3733 int find_uuid_item(CONFIG_ITEM_VECTOR &vecItems, char *pszName)
3734 {
3735     unsigned int i;
3736     for (i = 0; i < vecItems.size(); i++)
3737     {
3738         if (strcasecmp(pszName, vecItems[i].szItemName) == 0)
3739         {
3740             return i;
3741         }
3742     }
3743     return -1;
3744 }
3745