Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2890 lines
93 KiB

  1. /*
  2. *
  3. * Resource Updating Functions
  4. */
  5. #if WINNT /* for UNICODE_STRING */
  6. #include <nt.h>
  7. #include <ntrtl.h>
  8. #include <nturtl.h>
  9. #include <malloc.h>
  10. #include <stdlib.h>
  11. #endif
  12. #include <windows.h>
  13. #pragma hdrstop
  14. #include "..\wextract\cpldebug.h"
  15. #include "updres.h"
  16. #define DPrintf( a )
  17. #define DPrintfn( a )
  18. #define DPrintfu( a )
  19. #define RtlAllocateHeap(a,b,c) malloc( c )
  20. #define RtlFreeHeap(a,b,c) free( c )
  21. /*
  22. * BUGBUG - OPTIMIZATION PROBLEM?
  23. * BUGBUG - The program mysteriously does not work correctly unless
  24. * BUGBUG optimization is turned off in the early section of this file.
  25. * BUGBUG I don't have time to debug this, if you do please tell me what
  26. * BUGBUG is wrong
  27. */
  28. #pragma optimize( "", off )
  29. #define cbPadMax 16L
  30. char *pchPad = "PADDINGXXPADDING";
  31. char *pchZero = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
  32. WCHAR *
  33. MakeUnicodeCopy( LPCSTR psz )
  34. {
  35. LPWSTR result;
  36. if (((ULONG_PTR) psz) & (ULONG_PTR)0xFFFF0000) {
  37. result = (LPWSTR) malloc( (strlen(psz) + 1) * sizeof(WCHAR) );
  38. // BUGBUG ERROR CHECKING!!! Internal tool only
  39. mbstowcs( result, psz, strlen(psz) + 1);
  40. return( result );
  41. } else {
  42. return( (WCHAR *) psz );
  43. }
  44. }
  45. /****************************************************************************
  46. **
  47. ** API entry points
  48. **
  49. ****************************************************************************/
  50. /*++
  51. Routine Description
  52. Begins an update of resources. Save away the name
  53. and current resources in a list, using EnumResourceXxx
  54. api set.
  55. Parameters:
  56. lpFileName - Supplies the name of the executable file that the
  57. resource specified by lpType/lpName/language will be updated
  58. in. This file must be able to be opened for writing (ie, not
  59. currently executing, etc.) The file may be fully qualified,
  60. or if not, the current directory is assumed. It must be a
  61. valid Windows executable file.
  62. bDeleteExistingResources - if TRUE, existing resources are
  63. deleted, and only new resources will appear in the result.
  64. Otherwise, all resources in the input file will be in the
  65. output file unless specifically deleted or replaced.
  66. Return Value:
  67. NULL - The file specified was not able to be opened for writing.
  68. Either it was not an executable image, the executable image is
  69. already loaded, or the filename did not exist. More information may
  70. be available via GetLastError api.
  71. HANDLE - A handle to be passed to the UpdateResource and
  72. EndUpdateResources function.
  73. --*/
  74. HANDLE
  75. LocalBeginUpdateResource( LPCSTR pwch, BOOL bDeleteExistingResources )
  76. {
  77. HMODULE hModule;
  78. PUPDATEDATA pUpdate;
  79. HANDLE hUpdate;
  80. LPSTR pFileName;
  81. DWORD attr;
  82. SetLastError(NO_ERROR);
  83. // Pointer Sanity check
  84. if (pwch == NULL) {
  85. SetLastError(ERROR_INVALID_PARAMETER);
  86. return NULL;
  87. }
  88. // Allocate Resource Editing State (contains lists of resources)
  89. hUpdate = GlobalAlloc(GHND, sizeof(UPDATEDATA));
  90. if (hUpdate == NULL) {
  91. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  92. return NULL;
  93. }
  94. pUpdate = (PUPDATEDATA)GlobalLock(hUpdate);
  95. if (pUpdate == NULL) {
  96. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  97. return NULL;
  98. }
  99. // Set reasonable start condition
  100. pUpdate->Status = NO_ERROR;
  101. // Copy Filename into state table
  102. pUpdate->hFileName = GlobalAlloc(GHND, (strlen(pwch)+1) * sizeof(TCHAR) );
  103. if (pUpdate->hFileName == NULL) {
  104. GlobalUnlock(hUpdate);
  105. GlobalFree(hUpdate);
  106. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  107. return NULL;
  108. }
  109. pFileName = (LPSTR)GlobalLock(pUpdate->hFileName);
  110. if (pFileName == NULL) {
  111. GlobalUnlock(hUpdate);
  112. GlobalFree(hUpdate);
  113. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  114. return NULL;
  115. }
  116. lstrcpy(pFileName, pwch);
  117. GlobalUnlock(pUpdate->hFileName);
  118. // Make sure file is writable, not a directory, etc.
  119. attr = GetFileAttributes(pFileName);
  120. if (attr == 0xffffffff) {
  121. GlobalUnlock(hUpdate);
  122. GlobalFree(hUpdate);
  123. return NULL;
  124. } else if (attr & (FILE_ATTRIBUTE_READONLY |
  125. FILE_ATTRIBUTE_SYSTEM |
  126. FILE_ATTRIBUTE_HIDDEN |
  127. FILE_ATTRIBUTE_DIRECTORY)) {
  128. GlobalUnlock(hUpdate);
  129. GlobalFree(hUpdate);
  130. SetLastError(ERROR_WRITE_PROTECT);
  131. return NULL;
  132. }
  133. // If not deleting all resources, load them all in
  134. // by enumerating all the resources
  135. if (! bDeleteExistingResources) {
  136. hModule = LoadLibraryEx(pwch, NULL,LOAD_LIBRARY_AS_DATAFILE| DONT_RESOLVE_DLL_REFERENCES);
  137. if (hModule == NULL) {
  138. GlobalUnlock(hUpdate);
  139. GlobalFree(hUpdate);
  140. if (GetLastError() == NO_ERROR)
  141. SetLastError(ERROR_BAD_EXE_FORMAT);
  142. return NULL;
  143. } else {
  144. EnumResourceTypes(hModule, (ENUMRESTYPEPROC) EnumTypesFunc, (LONG_PTR) pUpdate);
  145. }
  146. FreeLibrary(hModule);
  147. }
  148. if (pUpdate->Status != NO_ERROR) {
  149. GlobalUnlock(hUpdate);
  150. GlobalFree(hUpdate);
  151. return NULL;
  152. }
  153. GlobalUnlock(hUpdate);
  154. return hUpdate;
  155. }
  156. /*++
  157. Routine Description
  158. This routine adds, deletes or modifies the input resource
  159. in the list initialized by BeginUpdateResource. The modify
  160. case is simple, the add is easy, the delete is hard.
  161. The ASCII entry point converts inputs to UNICODE.
  162. Parameters:
  163. hUpdateFile - The handle returned by the BeginUpdateResources
  164. function.
  165. lpType - Points to a null-terminated character string that
  166. represents the type name of the resource to be updated or
  167. added. May be an integer value passed to MAKEINTRESOURCE
  168. macro. For predefined resource types, the lpType parameter
  169. should be one of the following values:
  170. RT_ACCELERATOR - Accelerator table
  171. RT_BITMAP - Bitmap resource
  172. RT_DIALOG - Dialog box
  173. RT_FONT - Font resource
  174. RT_FONTDIR - Font directory resource
  175. RT_MENU - Menu resource
  176. RT_RCDATA - User-defined resource (raw data)
  177. RT_VERSION - Version resource
  178. RT_ICON - Icon resource
  179. RT_CURSOR - Cursor resource
  180. lpName - Points to a null-terminated character string that
  181. represents the name of the resource to be updated or added.
  182. May be an integer value passed to MAKEINTRESOURCE macro.
  183. language - Is the word value that specifies the language of the
  184. resource to be updated. A complete list of values is
  185. available in winnls.h.
  186. lpData - A pointer to the raw data to be inserted into the
  187. executable image's resource table and data. If the data is
  188. one of the predefined types, it must be valid and properly
  189. aligned. If lpData is NULL, the specified resource is to be
  190. deleted from the executable image.
  191. cb - count of bytes in the data.
  192. Return Value:
  193. TRUE - The resource specified was successfully replaced in, or added
  194. to, the specified executable image.
  195. FALSE/NULL - The resource specified was not successfully added to or
  196. updated in the executable image. More information may be available
  197. via GetLastError api.
  198. --*/
  199. BOOL
  200. LocalUpdateResource(
  201. HANDLE hUpdate,
  202. LPCTSTR lpType,
  203. LPCTSTR lpName,
  204. WORD language,
  205. LPVOID lpData,
  206. ULONG cb
  207. )
  208. {
  209. PUPDATEDATA pUpdate;
  210. PSDATA Type;
  211. PSDATA Name;
  212. PVOID lpCopy;
  213. LONG fRet;
  214. LPWSTR lpwType;
  215. LPWSTR lpwName;
  216. // Reset Error
  217. SetLastError(0);
  218. // Get pointer to Resource Update Session
  219. pUpdate = (PUPDATEDATA) GlobalLock(hUpdate);
  220. lpwType = MakeUnicodeCopy( lpType );
  221. lpwName = MakeUnicodeCopy( lpName );
  222. Name = AddStringOrID(lpwName, pUpdate);
  223. if (Name == NULL) {
  224. pUpdate->Status = ERROR_NOT_ENOUGH_MEMORY;
  225. GlobalUnlock(hUpdate);
  226. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  227. return FALSE;
  228. }
  229. Type = AddStringOrID(lpwType, pUpdate);
  230. if (Type == NULL) {
  231. pUpdate->Status = ERROR_NOT_ENOUGH_MEMORY;
  232. GlobalUnlock(hUpdate);
  233. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  234. return FALSE;
  235. }
  236. if (lpwType != (LPWSTR) lpType)
  237. free( lpwType );
  238. if (lpwName != (LPWSTR) lpName)
  239. free( lpwName );
  240. if (cb == 0) {
  241. lpCopy = NULL;
  242. } else {
  243. // RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( RES_TAG ), cb);
  244. lpCopy = malloc( cb );
  245. if (lpCopy == NULL) {
  246. pUpdate->Status = ERROR_NOT_ENOUGH_MEMORY;
  247. GlobalUnlock(hUpdate);
  248. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  249. return FALSE;
  250. }
  251. memcpy( lpCopy, lpData, cb);
  252. }
  253. fRet = AddResource(Type, Name, language, pUpdate, lpCopy, cb);
  254. GlobalUnlock(hUpdate);
  255. if (fRet == NO_ERROR) {
  256. return TRUE;
  257. } else {
  258. SetLastError(fRet);
  259. if (lpData != NULL)
  260. free( lpData );
  261. return FALSE;
  262. }
  263. }
  264. /*++
  265. Routine Description
  266. Finishes the UpdateResource action. Copies the
  267. input file to a temporary, adds the resources left
  268. in the list (hUpdate) to the exe.
  269. Parameters:
  270. hUpdateFile - The handle returned by the BeginUpdateResources
  271. function.
  272. fDiscard - If TRUE, discards all the updates, frees all memory.
  273. Return Value:
  274. FALSE - The file specified was not able to be written. More
  275. information may be available via GetLastError api.
  276. TRUE - The accumulated resources specified by UpdateResource calls
  277. were written to the executable file specified by the hUpdateFile
  278. handle.
  279. --*/
  280. BOOL
  281. LocalEndUpdateResource(
  282. HANDLE hUpdate,
  283. BOOL fDiscard
  284. )
  285. {
  286. LPTSTR pFileName;
  287. PUPDATEDATA pUpdate;
  288. TCHAR pTempFileName[MAX_PATH];
  289. INT cch;
  290. LPTSTR p;
  291. LONG rc;
  292. SetLastError(0);
  293. pUpdate = (PUPDATEDATA)GlobalLock(hUpdate);
  294. if (fDiscard) {
  295. rc = NO_ERROR;
  296. } else {
  297. pFileName = (LPTSTR)GlobalLock(pUpdate->hFileName);
  298. strcpy(pTempFileName, pFileName);
  299. cch = strlen(pTempFileName);
  300. p = pTempFileName + cch;
  301. while (*p != '\\' && p >= pTempFileName)
  302. p--;
  303. *(p+1) = 0;
  304. rc = GetTempFileName(pTempFileName, "RCX", 0, pTempFileName);
  305. if (rc == 0) {
  306. rc = GetTempPath(MAX_PATH, pTempFileName);
  307. if (rc == 0) {
  308. pTempFileName[0] = '.';
  309. pTempFileName[1] = '\\';
  310. pTempFileName[2] = 0;
  311. }
  312. rc = GetTempFileName(pTempFileName, "RCX", 0, pTempFileName);
  313. if (rc == 0) {
  314. rc = GetLastError();
  315. } else {
  316. rc = WriteResFile(hUpdate, pTempFileName);
  317. if (rc == NO_ERROR) {
  318. DeleteFile(pFileName);
  319. MoveFile(pTempFileName, pFileName);
  320. } else {
  321. SetLastError(rc);
  322. DeleteFile(pTempFileName);
  323. }
  324. }
  325. } else {
  326. rc = WriteResFile(hUpdate, pTempFileName);
  327. if (rc == NO_ERROR) {
  328. DeleteFile(pFileName);
  329. MoveFile(pTempFileName, pFileName);
  330. } else {
  331. SetLastError(rc);
  332. DeleteFile(pTempFileName);
  333. }
  334. }
  335. GlobalUnlock(pUpdate->hFileName);
  336. GlobalFree(pUpdate->hFileName);
  337. }
  338. FreeData(pUpdate);
  339. GlobalUnlock(hUpdate);
  340. GlobalFree(hUpdate);
  341. return rc?FALSE:TRUE;
  342. }
  343. /**********************************************************************
  344. **
  345. ** End of API entry points.
  346. **
  347. ** Beginning of private entry points for worker routines to do the
  348. ** real work.
  349. **
  350. ***********************************************************************/
  351. BOOL
  352. EnumTypesFunc(
  353. HANDLE hModule,
  354. LPSTR lpType,
  355. LONG_PTR lParam
  356. )
  357. {
  358. EnumResourceNames(hModule, lpType, (ENUMRESNAMEPROC)EnumNamesFunc, lParam);
  359. return TRUE;
  360. }
  361. BOOL
  362. EnumNamesFunc(
  363. HANDLE hModule,
  364. LPSTR lpType,
  365. LPSTR lpName,
  366. LONG_PTR lParam
  367. )
  368. {
  369. EnumResourceLanguages(hModule, lpType, lpName, (ENUMRESLANGPROC)EnumLangsFunc, lParam);
  370. return TRUE;
  371. }
  372. BOOL
  373. EnumLangsFunc(
  374. HANDLE hModule,
  375. LPSTR lpType,
  376. LPSTR lpName,
  377. WORD language,
  378. LONG_PTR lParam
  379. )
  380. {
  381. HANDLE hResInfo;
  382. LONG fError;
  383. PSDATA Type;
  384. PSDATA Name;
  385. ULONG cb;
  386. PVOID lpData;
  387. HANDLE hResource;
  388. PVOID lpResource;
  389. LPWSTR lpwType;
  390. LPWSTR lpwName;
  391. hResInfo = FindResourceEx(hModule, lpType, lpName, language);
  392. if (hResInfo == NULL) {
  393. return FALSE;
  394. }
  395. lpwType = MakeUnicodeCopy( lpType );
  396. if(lpwType == NULL) {
  397. return FALSE;
  398. }
  399. lpwName = MakeUnicodeCopy( lpName );
  400. if(lpwName == NULL) {
  401. if (lpType != (LPSTR) lpwType)free(lpwType);
  402. return FALSE;
  403. }
  404. Type = AddStringOrID(lpwType, (PUPDATEDATA)lParam);
  405. if (Type == NULL) {
  406. ((PUPDATEDATA)lParam)->Status = ERROR_NOT_ENOUGH_MEMORY;
  407. return FALSE;
  408. }
  409. Name = AddStringOrID(lpwName, (PUPDATEDATA)lParam);
  410. if (Name == NULL) {
  411. ((PUPDATEDATA)lParam)->Status = ERROR_NOT_ENOUGH_MEMORY;
  412. return FALSE;
  413. }
  414. if (lpType != (LPSTR) lpwType)
  415. free( lpwType );
  416. if (lpName != (LPSTR) lpwName)
  417. free( lpwName );
  418. cb = SizeofResource(hModule, hResInfo);
  419. if (cb == 0) {
  420. return FALSE;
  421. }
  422. lpData = RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( RES_TAG ), cb);
  423. if (lpData == NULL) {
  424. return FALSE;
  425. }
  426. RtlZeroMemory(lpData, cb);
  427. hResource = LoadResource(hModule, hResInfo);
  428. if (hResource == NULL) {
  429. RtlFreeHeap(RtlProcessHeap(), 0, lpData);
  430. return FALSE;
  431. }
  432. lpResource = (PVOID)LockResource(hResource);
  433. if (lpResource == NULL) {
  434. RtlFreeHeap(RtlProcessHeap(), 0, lpData);
  435. return FALSE;
  436. }
  437. RtlCopyMemory(lpData, lpResource, cb);
  438. (VOID)UnlockResource(hResource);
  439. (VOID)FreeResource(hResource);
  440. fError = AddResource(Type, Name, language, (PUPDATEDATA)lParam, lpData, cb);
  441. if (fError != NO_ERROR) {
  442. ((PUPDATEDATA)lParam)->Status = ERROR_NOT_ENOUGH_MEMORY;
  443. return FALSE;
  444. }
  445. return TRUE;
  446. }
  447. /*
  448. * BUGBUG END OF OPTIMIZATION PROBLEM
  449. */
  450. #pragma optimize( "", on )
  451. VOID
  452. FreeOne(
  453. PRESNAME pRes
  454. )
  455. {
  456. RtlFreeHeap(RtlProcessHeap(), 0, (PVOID)pRes->OffsetToDataEntry);
  457. RtlFreeHeap(RtlProcessHeap(), 0, (PVOID)pRes);
  458. }
  459. VOID
  460. FreeData(
  461. PUPDATEDATA pUpd
  462. )
  463. {
  464. PRESTYPE pType;
  465. PRESNAME pRes;
  466. PSDATA pstring, pStringTmp;
  467. for (pType=pUpd->ResTypeHeadID ; pUpd->ResTypeHeadID ; pType=pUpd->ResTypeHeadID) {
  468. pUpd->ResTypeHeadID = pUpd->ResTypeHeadID->pnext;
  469. for (pRes=pType->NameHeadID ; pType->NameHeadID ; pRes=pType->NameHeadID ) {
  470. pType->NameHeadID = pType->NameHeadID->pnext;
  471. FreeOne(pRes);
  472. }
  473. for (pRes=pType->NameHeadName ; pType->NameHeadName ; pRes=pType->NameHeadName ) {
  474. pType->NameHeadName = pType->NameHeadName->pnext;
  475. FreeOne(pRes);
  476. }
  477. RtlFreeHeap(RtlProcessHeap(), 0, (PVOID)pType);
  478. }
  479. for (pType=pUpd->ResTypeHeadName ; pUpd->ResTypeHeadName ; pType=pUpd->ResTypeHeadName) {
  480. pUpd->ResTypeHeadName = pUpd->ResTypeHeadName->pnext;
  481. for (pRes=pType->NameHeadID ; pType->NameHeadID ; pRes=pType->NameHeadID ) {
  482. pType->NameHeadID = pType->NameHeadID->pnext;
  483. FreeOne(pRes);
  484. }
  485. for (pRes=pType->NameHeadName ; pType->NameHeadName ; pRes=pType->NameHeadName ) {
  486. pType->NameHeadName = pType->NameHeadName->pnext;
  487. FreeOne(pRes);
  488. }
  489. }
  490. pstring = pUpd->StringHead;
  491. while (pstring != NULL) {
  492. pStringTmp = pstring->uu.ss.pnext;
  493. if (pstring->discriminant == IS_STRING)
  494. RtlFreeHeap(RtlProcessHeap(), 0, (PVOID)pstring->szStr);
  495. RtlFreeHeap(RtlProcessHeap(), 0, (PVOID)pstring);
  496. pstring = pStringTmp;
  497. }
  498. return;
  499. }
  500. /*+++
  501. Routines to register strings
  502. ---*/
  503. //
  504. // Resources are DWORD aligned and may be in any order.
  505. //
  506. #define TABLE_ALIGN 4
  507. #define DATA_ALIGN 4L
  508. PSDATA
  509. AddStringOrID(
  510. LPCWSTR lp,
  511. PUPDATEDATA pupd
  512. )
  513. {
  514. USHORT cb;
  515. PSDATA pstring;
  516. PPSDATA ppstring;
  517. if (((ULONG_PTR)lp & (ULONG_PTR)0xFFFF0000) == 0) {
  518. //
  519. // an ID
  520. //
  521. pstring = (PSDATA)RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( RES_TAG ), sizeof(SDATA));
  522. if (pstring == NULL)
  523. return NULL;
  524. RtlZeroMemory((PVOID)pstring, sizeof(SDATA));
  525. pstring->discriminant = IS_ID;
  526. pstring->uu.Ordinal = (WORD)((ULONG_PTR)lp & (ULONG_PTR)0x0000ffff);
  527. }
  528. else {
  529. //
  530. // a string
  531. //
  532. cb = wcslen(lp) + 1;
  533. ppstring = &pupd->StringHead;
  534. while ((pstring = *ppstring) != NULL) {
  535. if (!wcsncmp(pstring->szStr, lp, cb))
  536. break;
  537. ppstring = &(pstring->uu.ss.pnext);
  538. }
  539. if (!pstring) {
  540. //
  541. // allocate a new one
  542. //
  543. pstring = (PSDATA)RtlAllocateHeap(RtlProcessHeap(),
  544. MAKE_TAG( RES_TAG ) | HEAP_ZERO_MEMORY,
  545. sizeof(SDATA)
  546. );
  547. if (pstring == NULL)
  548. return NULL;
  549. RtlZeroMemory((PVOID)pstring, sizeof(SDATA));
  550. pstring->szStr = (WCHAR*)RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( RES_TAG ),
  551. cb*sizeof(WCHAR));
  552. if (pstring->szStr == NULL) {
  553. RtlFreeHeap(RtlProcessHeap(), 0, (PVOID)pstring);
  554. return NULL;
  555. }
  556. pstring->discriminant = IS_STRING;
  557. pstring->OffsetToString = pupd->cbStringTable;
  558. pstring->cbData = sizeof(pstring->cbsz) + cb * sizeof(WCHAR);
  559. pstring->cbsz = cb - 1; /* don't include zero terminator */
  560. RtlCopyMemory(pstring->szStr, lp, cb*sizeof(WCHAR));
  561. pupd->cbStringTable += pstring->cbData;
  562. pstring->uu.ss.pnext=NULL;
  563. *ppstring=pstring;
  564. }
  565. }
  566. return(pstring);
  567. }
  568. //
  569. // add a resource into the resource directory hiearchy
  570. //
  571. LONG
  572. AddResource(
  573. IN PSDATA Type,
  574. IN PSDATA Name,
  575. IN WORD Language,
  576. IN PUPDATEDATA pupd,
  577. IN PVOID lpData,
  578. IN ULONG cb
  579. )
  580. {
  581. PRESTYPE pType;
  582. PPRESTYPE ppType;
  583. PRESNAME pName;
  584. PRESNAME pNameM;
  585. PPRESNAME ppName = NULL;
  586. BOOL fTypeID=(Type->discriminant == IS_ID);
  587. BOOL fNameID=(Name->discriminant == IS_ID);
  588. BOOL fSame=FALSE;
  589. //
  590. // figure out which list to store it in
  591. //
  592. ppType = fTypeID ? &pupd->ResTypeHeadID : &pupd->ResTypeHeadName;
  593. //
  594. // Try to find the Type in the list
  595. //
  596. while ((pType=*ppType) != NULL) {
  597. if (pType->Type->uu.Ordinal == Type->uu.Ordinal) {
  598. ppName = fNameID ? &pType->NameHeadID : &pType->NameHeadName;
  599. break;
  600. }
  601. if (fTypeID) {
  602. if (Type->uu.Ordinal < pType->Type->uu.Ordinal)
  603. break;
  604. }
  605. else {
  606. if (wcsncmp(Type->szStr, pType->Type->szStr, Type->cbsz) < 0)
  607. break;
  608. }
  609. ppType = &(pType->pnext);
  610. }
  611. //
  612. // Create a new type if needed
  613. //
  614. if (ppName == NULL) {
  615. pType = (PRESTYPE)RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( RES_TAG ), sizeof(RESTYPE));
  616. if (pType == NULL)
  617. return ERROR_NOT_ENOUGH_MEMORY;
  618. RtlZeroMemory((PVOID)pType, sizeof(RESTYPE));
  619. pType->pnext = *ppType;
  620. *ppType = pType;
  621. pType->Type = Type;
  622. ppName = fNameID ? &pType->NameHeadID : &pType->NameHeadName;
  623. }
  624. //
  625. // Find proper place for name
  626. //
  627. while ( (pName = *ppName) != NULL) {
  628. if (fNameID) {
  629. if (Name->uu.Ordinal == pName->Name->uu.Ordinal) {
  630. fSame = TRUE;
  631. break;
  632. }
  633. if (Name->uu.Ordinal < pName->Name->uu.Ordinal)
  634. break;
  635. }
  636. else {
  637. if (wcsncmp(Name->szStr, pName->Name->szStr, Name->cbsz) == 0) {
  638. fSame = TRUE;
  639. break;
  640. }
  641. if (wcsncmp(Name->szStr, pName->Name->szStr, Name->cbsz) < 0)
  642. break;
  643. }
  644. ppName = &(pName->pnext);
  645. }
  646. //
  647. // check for delete/modify
  648. //
  649. if (fSame) { /* same name, new language */
  650. if (pName->NumberOfLanguages == 1) { /* one language currently ? */
  651. if (Language == pName->LanguageId) { /* REPLACE || DELETE */
  652. pName->DataSize = cb;
  653. if (lpData == NULL) { /* DELETE */
  654. return DeleteResourceFromList(pupd, pType, pName, Language, fTypeID, fNameID);
  655. }
  656. RtlFreeHeap(RtlProcessHeap(),0,(PVOID)pName->OffsetToDataEntry);
  657. pName->OffsetToDataEntry = (ULONG_PTR)lpData;
  658. return NO_ERROR;
  659. }
  660. else {
  661. if (lpData == NULL) { /* no data but new? */
  662. return ERROR_INVALID_PARAMETER; /* badness */
  663. }
  664. return InsertResourceIntoLangList(pupd, Type, Name, pType, pName, Language, fNameID, cb, lpData);
  665. }
  666. }
  667. else { /* many languages currently */
  668. pNameM = pName; /* save head of lang list */
  669. while ( (pName = *ppName) != NULL) {/* find insertion point */
  670. if (pName->Name != pNameM->Name ||
  671. Language <= pName->LanguageId) /* here? */
  672. break; /* yes */
  673. ppName = &(pName->pnext); /* traverse language list */
  674. }
  675. if (pName && Language == pName->LanguageId) { /* language found? */
  676. if (lpData == NULL) { /* DELETE */
  677. return DeleteResourceFromList(pupd, pType, pName, Language, fTypeID, fNameID);
  678. }
  679. pName->DataSize = cb; /* REPLACE */
  680. RtlFreeHeap(RtlProcessHeap(),0,(PVOID)pName->OffsetToDataEntry);
  681. pName->OffsetToDataEntry = (ULONG_PTR)lpData;
  682. return NO_ERROR;
  683. }
  684. else { /* add new language */
  685. return InsertResourceIntoLangList(pupd, Type, Name, pType, pNameM, Language, fNameID, cb, lpData);
  686. }
  687. }
  688. }
  689. else { /* unique name */
  690. if (lpData == NULL) { /* can't delete new name */
  691. return ERROR_INVALID_PARAMETER;
  692. }
  693. }
  694. //
  695. // add new name/language
  696. //
  697. if (!fSame) {
  698. if (fNameID)
  699. pType->NumberOfNamesID++;
  700. else
  701. pType->NumberOfNamesName++;
  702. }
  703. pName = (PRESNAME)RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( RES_TAG ), sizeof(RESNAME));
  704. if (pName == NULL)
  705. return ERROR_NOT_ENOUGH_MEMORY;
  706. RtlZeroMemory((PVOID)pName, sizeof(RESNAME));
  707. pName->pnext = *ppName;
  708. *ppName = pName;
  709. pName->Name = Name;
  710. pName->Type = Type;
  711. pName->NumberOfLanguages = 1;
  712. pName->LanguageId = Language;
  713. pName->DataSize = cb;
  714. pName->OffsetToDataEntry = (ULONG_PTR)lpData;
  715. return NO_ERROR;
  716. }
  717. BOOL
  718. DeleteResourceFromList(
  719. PUPDATEDATA pUpd,
  720. PRESTYPE pType,
  721. PRESNAME pName,
  722. INT Language,
  723. INT fType,
  724. INT fName
  725. )
  726. {
  727. PPRESTYPE ppType;
  728. PPRESNAME ppName;
  729. PRESNAME pNameT;
  730. /* find previous type node */
  731. ppType = fType ? &pUpd->ResTypeHeadID : &pUpd->ResTypeHeadName;
  732. while (*ppType != pType) {
  733. ppType = &((*ppType)->pnext);
  734. }
  735. /* find previous type node */
  736. ppName = fName ? &pType->NameHeadID : &pType->NameHeadName;
  737. pNameT = NULL;
  738. while (*ppName != pName) {
  739. if (pNameT == NULL) { /* find first Name in lang list */
  740. if (fName) {
  741. if ((*ppName)->Name->uu.Ordinal == pName->Name->uu.Ordinal) {
  742. pNameT = *ppName;
  743. }
  744. }
  745. else {
  746. if (wcsncmp((*ppName)->Name->szStr, pName->Name->szStr, (*ppName)->Name->cbsz) == 0) {
  747. pNameT = *ppName;
  748. }
  749. }
  750. }
  751. ppName = &((*ppName)->pnext);
  752. }
  753. if (pNameT == NULL) { /* first of this name? */
  754. pNameT = pName->pnext; /* then (possibly) make next head of lang */
  755. if (pNameT != NULL) {
  756. if (fName) {
  757. if (pNameT->Name->uu.Ordinal == pName->Name->uu.Ordinal) {
  758. pNameT->NumberOfLanguages = pName->NumberOfLanguages - 1;
  759. }
  760. }
  761. else {
  762. if (wcsncmp(pNameT->Name->szStr, pName->Name->szStr, pNameT->Name->cbsz) == 0) {
  763. pNameT->NumberOfLanguages = pName->NumberOfLanguages - 1;
  764. }
  765. }
  766. }
  767. }
  768. else
  769. pNameT->NumberOfLanguages--;
  770. if (pNameT) {
  771. if (pNameT->NumberOfLanguages == 0) {
  772. if (fName)
  773. pType->NumberOfNamesID -= 1;
  774. else
  775. pType->NumberOfNamesName -= 1;
  776. }
  777. }
  778. *ppName = pName->pnext; /* link to next */
  779. RtlFreeHeap(RtlProcessHeap(), 0, (PVOID)pName->OffsetToDataEntry);
  780. RtlFreeHeap(RtlProcessHeap(), 0, pName); /* and free */
  781. if (*ppName == NULL) { /* type list completely empty? */
  782. *ppType = pType->pnext; /* link to next */
  783. RtlFreeHeap(RtlProcessHeap(), 0, pType); /* and free */
  784. }
  785. return NO_ERROR;
  786. }
  787. BOOL
  788. InsertResourceIntoLangList(
  789. PUPDATEDATA pUpd,
  790. PSDATA Type,
  791. PSDATA Name,
  792. PRESTYPE pType,
  793. PRESNAME pName,
  794. INT Language,
  795. INT fName,
  796. INT cb,
  797. PVOID lpData
  798. )
  799. {
  800. PRESNAME pNameM;
  801. PRESNAME pNameNew;
  802. PPRESNAME ppName;
  803. pNameNew = (PRESNAME)RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( RES_TAG ), sizeof(RESNAME));
  804. if (pNameNew == NULL)
  805. return ERROR_NOT_ENOUGH_MEMORY;
  806. RtlZeroMemory((PVOID)pNameNew, sizeof(RESNAME));
  807. pNameNew->Name = Name;
  808. pNameNew->Type = Type;
  809. pNameNew->LanguageId = (WORD)Language;
  810. pNameNew->DataSize = cb;
  811. pNameNew->OffsetToDataEntry = (ULONG_PTR)lpData;
  812. if (Language < pName->LanguageId) { /* have to add to the front */
  813. pNameNew->NumberOfLanguages = pName->NumberOfLanguages + 1;
  814. pName->NumberOfLanguages = 1;
  815. ppName = fName ? &pType->NameHeadID : &pType->NameHeadName;
  816. /* don't have to look for NULL at end of list !!! */
  817. while (pName != *ppName) { /* find insertion point */
  818. ppName = &((*ppName)->pnext); /* traverse language list */
  819. }
  820. pNameNew->pnext = *ppName; /* insert */
  821. *ppName = pNameNew;
  822. }
  823. else {
  824. pNameM = pName;
  825. pName->NumberOfLanguages += 1;
  826. while (pName != NULL) { /* find insertion point */
  827. if (Language <= pName->LanguageId) /* here? */
  828. break; /* yes */
  829. pNameM = pName;
  830. pName = pName->pnext; /* traverse language list */
  831. }
  832. pName = pNameM->pnext;
  833. pNameM->pnext = pNameNew;
  834. pNameNew->pnext = pName;
  835. }
  836. return NO_ERROR;
  837. }
  838. /*
  839. * Utility routines
  840. */
  841. ULONG
  842. FilePos(int fh)
  843. {
  844. return _llseek(fh, 0L, SEEK_CUR);
  845. }
  846. ULONG
  847. MuMoveFilePos( INT fh, ULONG pos )
  848. {
  849. return _llseek( fh, pos, SEEK_SET );
  850. }
  851. ULONG
  852. MuWrite( INT fh, UCHAR*p, ULONG n )
  853. {
  854. ULONG n1;
  855. if ((n1 = _lwrite(fh, p, n)) != n) {
  856. return n1;
  857. }
  858. else
  859. return 0;
  860. }
  861. ULONG
  862. MuRead(INT fh, UCHAR*p, ULONG n )
  863. {
  864. ULONG n1;
  865. if ((n1 = _lread( fh, p, n )) != n) {
  866. return n1;
  867. }
  868. else
  869. return 0;
  870. }
  871. BOOL
  872. MuCopy( INT srcfh, INT dstfh, ULONG nbytes )
  873. {
  874. ULONG n;
  875. ULONG cb=0L;
  876. PUCHAR pb;
  877. pb = (PUCHAR)RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( RES_TAG ), BUFSIZE);
  878. if (pb == NULL)
  879. return 0;
  880. RtlZeroMemory((PVOID)pb, BUFSIZE);
  881. while (nbytes) {
  882. if (nbytes <= BUFSIZE)
  883. n = nbytes;
  884. else
  885. n = BUFSIZE;
  886. nbytes -= n;
  887. if (!MuRead( srcfh, pb, n )) {
  888. cb += n;
  889. MuWrite( dstfh, pb, n );
  890. }
  891. else {
  892. RtlFreeHeap(RtlProcessHeap(), 0, pb);
  893. return cb;
  894. }
  895. }
  896. RtlFreeHeap(RtlProcessHeap(), 0, pb);
  897. return cb;
  898. }
  899. VOID
  900. SetResdata(
  901. PIMAGE_RESOURCE_DATA_ENTRY pResData,
  902. ULONG offset,
  903. ULONG size)
  904. {
  905. pResData->OffsetToData = offset;
  906. pResData->Size = size;
  907. pResData->CodePage = DEFAULT_CODEPAGE;
  908. pResData->Reserved = 0L;
  909. }
  910. VOID
  911. SetRestab(
  912. PIMAGE_RESOURCE_DIRECTORY pRestab,
  913. LONG time,
  914. WORD cNamed,
  915. WORD cId)
  916. {
  917. pRestab->Characteristics = 0L;
  918. pRestab->TimeDateStamp = time;
  919. pRestab->MajorVersion = MAJOR_RESOURCE_VERSION;
  920. pRestab->MinorVersion = MINOR_RESOURCE_VERSION;
  921. pRestab->NumberOfNamedEntries = cNamed;
  922. pRestab->NumberOfIdEntries = cId;
  923. }
  924. PIMAGE_SECTION_HEADER
  925. FindSection(
  926. PIMAGE_SECTION_HEADER pObjBottom,
  927. PIMAGE_SECTION_HEADER pObjTop,
  928. LPSTR pName
  929. )
  930. {
  931. while (pObjBottom < pObjTop) {
  932. if (strcmp(pObjBottom->Name, pName) == 0)
  933. return pObjBottom;
  934. pObjBottom++;
  935. }
  936. return NULL;
  937. }
  938. ULONG
  939. AssignResourceToSection(
  940. PRESNAME *ppRes, /* resource to assign */
  941. ULONG ExtraSectionOffset, /* offset between .rsrc and .rsrc1 */
  942. ULONG Offset, /* next available offset in section */
  943. LONG Size, /* Maximum size of .rsrc */
  944. PLONG pSizeRsrc1
  945. )
  946. {
  947. ULONG cb;
  948. /* Assign this res to this section */
  949. cb = ROUNDUP((*ppRes)->DataSize, CBLONG);
  950. if (Offset < ExtraSectionOffset && Offset + cb > (ULONG)Size) {
  951. *pSizeRsrc1 = Offset;
  952. Offset = ExtraSectionOffset;
  953. DPrintf((DebugBuf, "<<< Secondary resource section @%#08lx >>>\n", Offset));
  954. }
  955. (*ppRes)->OffsetToData = Offset;
  956. *ppRes = (*ppRes)->pnext;
  957. DPrintf((DebugBuf, " --> %#08lx bytes at %#08lx\n", cb, Offset));
  958. return Offset + cb;
  959. }
  960. /***************************** Main Worker Function ***************************
  961. * LONG PEWriteResFile
  962. *
  963. * This function writes the resources to the named executable file.
  964. * It assumes that resources have no fixups (even any existing resources
  965. * that it removes from the executable.) It places all the resources into
  966. * one or two sections. The resources are packed tightly into the section,
  967. * being aligned on dword boundaries. Each section is padded to a file
  968. * sector size (no invalid or zero-filled pages), and each
  969. * resource is padded to the afore-mentioned dword boundary. This
  970. * function uses the capabilities of the NT system to enable it to easily
  971. * manipulate the data: to wit, it assumes that the system can allocate
  972. * any sized piece of data, in particular the section and resource tables.
  973. * If it did not, it might have to deal with temporary files (the system
  974. * may have to grow the swap file, but that's what the system is for.)
  975. *
  976. * Return values are:
  977. * TRUE - file was written succesfully.
  978. * FALSE - file was not written succesfully.
  979. *
  980. * Effects:
  981. *
  982. * History:
  983. * Thur Apr 27, 1989 by Floyd Rogers [floydr]
  984. * Created.
  985. * 12/8/89 sanfords Added multiple section support.
  986. * 12/11/90 floydr Modified for new (NT) Linear Exe format
  987. * 1/18/92 vich Modified for new (NT) Portable Exe format
  988. * 5/8/92 bryant General cleanup so resonexe can work with unicode
  989. * 6/9/92 floydr incorporate bryan's changes
  990. * 6/15/92 floydr debug section separate from debug table
  991. * 9/25/92 floydr account for .rsrc not being last-1
  992. * 9/28/92 floydr account for adding lots of resources by adding
  993. * a second .rsrc section.
  994. \****************************************************************************/
  995. /* */
  996. LONG
  997. PEWriteResFile(
  998. INT inpfh,
  999. INT outfh,
  1000. ULONG cbOldexe,
  1001. PUPDATEDATA pUpdate
  1002. )
  1003. {
  1004. IMAGE_NT_HEADERS Old; /* original header */
  1005. IMAGE_NT_HEADERS New; /* working header */
  1006. PRESNAME pRes;
  1007. PRESNAME pResSave;
  1008. PRESTYPE pType;
  1009. ULONG clock = GetTickCount(); /* current time */
  1010. ULONG cbName=0; /* count of bytes in name strings */
  1011. ULONG cbType=0; /* count of bytes in type strings */
  1012. ULONG cTypeStr=0; /* count of strings */
  1013. ULONG cNameStr=0; /* count of strings */
  1014. LONG cb; /* temp byte count and file index */
  1015. ULONG cTypes = 0L; /* count of resource types */
  1016. ULONG cNames = 0L; /* Count of names for multiple languages/name */
  1017. ULONG cRes = 0L; /* count of resources */
  1018. ULONG cbRestab; /* count of resources */
  1019. LONG cbNew = 0L; /* general count */
  1020. ULONG ibObjTab;
  1021. ULONG ibObjTabEnd;
  1022. ULONG ibSave;
  1023. ULONG adjust=0;
  1024. PIMAGE_SECTION_HEADER pObjtblOld,
  1025. pObjtblNew = NULL,
  1026. pObjDebug,
  1027. pObjResourceOld,
  1028. pObjResourceNew,
  1029. pObjResourceOldX,
  1030. pObjDebugDirOld,
  1031. pObjDebugDirNew,
  1032. pObjNew,
  1033. pObjOld,
  1034. pObjLast;
  1035. PUCHAR p;
  1036. PIMAGE_RESOURCE_DIRECTORY pResTab;
  1037. PIMAGE_RESOURCE_DIRECTORY pResTabN;
  1038. PIMAGE_RESOURCE_DIRECTORY pResTabL;
  1039. PIMAGE_RESOURCE_DIRECTORY_ENTRY pResDirL;
  1040. PIMAGE_RESOURCE_DIRECTORY_ENTRY pResDirN;
  1041. PIMAGE_RESOURCE_DIRECTORY_ENTRY pResDirT;
  1042. PIMAGE_RESOURCE_DATA_ENTRY pResData;
  1043. PUSHORT pResStr;
  1044. PUSHORT pResStrEnd;
  1045. PSDATA pPreviousName;
  1046. LONG nObjResource=-1;
  1047. LONG nObjResourceX=-1;
  1048. ULONG cbResource;
  1049. ULONG cbMustPad = 0;
  1050. ULONG ibMaxDbgOffsetOld;
  1051. MuMoveFilePos(inpfh, cbOldexe);
  1052. MuRead(inpfh, (PUCHAR)&Old, sizeof(IMAGE_NT_HEADERS));
  1053. ibObjTab = cbOldexe + sizeof(ULONG) + sizeof(IMAGE_FILE_HEADER) +
  1054. Old.FileHeader.SizeOfOptionalHeader;
  1055. ibObjTabEnd = ibObjTab + Old.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
  1056. if (*(PUSHORT)&Old.Signature != IMAGE_NT_SIGNATURE)
  1057. return ERROR_INVALID_EXE_SIGNATURE;
  1058. if ((Old.FileHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE) == 0 &&
  1059. (Old.FileHeader.Characteristics & IMAGE_FILE_DLL) == 0) {
  1060. return ERROR_EXE_MARKED_INVALID;
  1061. }
  1062. DPrintfn((DebugBuf, "\n"));
  1063. /* New header is like old one. */
  1064. RtlCopyMemory(&New, &Old, sizeof(IMAGE_NT_HEADERS));
  1065. /* Read section table */
  1066. pObjtblOld = (PIMAGE_SECTION_HEADER)RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( RES_TAG ),
  1067. Old.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER));
  1068. if (pObjtblOld == NULL) {
  1069. cb = ERROR_NOT_ENOUGH_MEMORY;
  1070. goto AbortExit;
  1071. }
  1072. RtlZeroMemory((PVOID)pObjtblOld, Old.FileHeader.NumberOfSections*sizeof(IMAGE_SECTION_HEADER));
  1073. DPrintf((DebugBuf, "Old section table: %#08lx bytes at %#08lx(mem)\n",
  1074. Old.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER),
  1075. pObjtblOld));
  1076. MuMoveFilePos(inpfh, ibObjTab);
  1077. MuRead(inpfh, (PUCHAR)pObjtblOld,
  1078. Old.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER));
  1079. pObjLast = pObjtblOld + Old.FileHeader.NumberOfSections;
  1080. ibMaxDbgOffsetOld = 0;
  1081. for (pObjOld=pObjtblOld ; pObjOld<pObjLast ; pObjOld++) {
  1082. if (pObjOld->PointerToRawData > ibMaxDbgOffsetOld) {
  1083. ibMaxDbgOffsetOld = pObjOld->PointerToRawData + pObjOld->SizeOfRawData;
  1084. }
  1085. }
  1086. DPrintf((DebugBuf, "Maximum debug offset in old file: %08x\n", ibMaxDbgOffsetOld ));
  1087. /*
  1088. * First, count up the resources. We need this information
  1089. * to discover how much room for header information to allocate
  1090. * in the resource section. cRes tells us how
  1091. * many language directory entries/tables. cNames and cTypes
  1092. * is used for the respective tables and/or entries. cbName totals
  1093. * the bytes required to store the alpha names (including the leading
  1094. * length word). cNameStr counts these strings.
  1095. */
  1096. DPrintf((DebugBuf, "Beginning loop to count resources\n"));
  1097. /* first, count those in the named type list */
  1098. cbResource = 0;
  1099. //DPrintf((DebugBuf, "Walk type: NAME list\n"));
  1100. pType = pUpdate->ResTypeHeadName;
  1101. while (pType != NULL) {
  1102. if (pType->NameHeadName != NULL || pType->NameHeadID != NULL) {
  1103. //DPrintf((DebugBuf, "Resource type "));
  1104. //DPrintfu((pType->Type->szStr));
  1105. //DPrintfn((DebugBuf, "\n"));
  1106. cTypes++;
  1107. cTypeStr++;
  1108. cbType += (pType->Type->cbsz + 1) * sizeof(WORD);
  1109. //DPrintf((DebugBuf, "Walk name: Alpha list\n"));
  1110. pPreviousName = NULL;
  1111. pRes = pType->NameHeadName;
  1112. while (pRes) {
  1113. //DPrintf((DebugBuf, "Resource "));
  1114. //DPrintfu((pRes->Name->szStr));
  1115. //DPrintfn((DebugBuf, "\n"));
  1116. cRes++;
  1117. if (pPreviousName == NULL ||
  1118. wcsncmp(pPreviousName->szStr,
  1119. pRes->Name->szStr,
  1120. pRes->Name->cbsz) != 0) {
  1121. cbName += (pRes->Name->cbsz + 1) * sizeof(WORD);
  1122. cNameStr++;
  1123. cNames++;
  1124. }
  1125. cbResource += ROUNDUP(pRes->DataSize, CBLONG);
  1126. pPreviousName = pRes->Name;
  1127. pRes = pRes->pnext;
  1128. }
  1129. //DPrintf((DebugBuf, "Walk name: ID list\n"));
  1130. pPreviousName = NULL;
  1131. pRes = pType->NameHeadID;
  1132. while (pRes) {
  1133. //DPrintf((DebugBuf, "Resource %hu\n", pRes->Name->uu.Ordinal));
  1134. cRes++;
  1135. if (pPreviousName == NULL ||
  1136. pPreviousName->uu.Ordinal != pRes->Name->uu.Ordinal) {
  1137. cNames++;
  1138. }
  1139. cbResource += ROUNDUP(pRes->DataSize, CBLONG);
  1140. pPreviousName = pRes->Name;
  1141. pRes = pRes->pnext;
  1142. }
  1143. }
  1144. pType = pType->pnext;
  1145. }
  1146. /* second, count those in the ID type list */
  1147. //DPrintf((DebugBuf, "Walk type: ID list\n"));
  1148. pType = pUpdate->ResTypeHeadID;
  1149. while (pType != NULL) {
  1150. if (pType->NameHeadName != NULL || pType->NameHeadID != NULL) {
  1151. //DPrintf((DebugBuf, "Resource type %hu\n", pType->Type->uu.Ordinal));
  1152. cTypes++;
  1153. //DPrintf((DebugBuf, "Walk name: Alpha list\n"));
  1154. pPreviousName = NULL;
  1155. pRes = pType->NameHeadName;
  1156. while (pRes) {
  1157. //DPrintf((DebugBuf, "Resource "));
  1158. //DPrintfu((pRes->Name->szStr));
  1159. //DPrintfn((DebugBuf, "\n"));
  1160. cRes++;
  1161. if (pPreviousName == NULL ||
  1162. wcsncmp(pPreviousName->szStr,
  1163. pRes->Name->szStr,
  1164. pRes->Name->cbsz) != 0) {
  1165. cNames++;
  1166. cbName += (pRes->Name->cbsz + 1) * sizeof(WORD);
  1167. cNameStr++;
  1168. }
  1169. cbResource += ROUNDUP(pRes->DataSize, CBLONG);
  1170. pPreviousName = pRes->Name;
  1171. pRes = pRes->pnext;
  1172. }
  1173. //DPrintf((DebugBuf, "Walk name: ID list\n"));
  1174. pPreviousName = NULL;
  1175. pRes = pType->NameHeadID;
  1176. while (pRes) {
  1177. //DPrintf((DebugBuf, "Resource %hu\n", pRes->Name->uu.Ordinal));
  1178. cRes++;
  1179. if (pPreviousName == NULL ||
  1180. pPreviousName->uu.Ordinal != pRes->Name->uu.Ordinal) {
  1181. cNames++;
  1182. }
  1183. cbResource += ROUNDUP(pRes->DataSize, CBLONG);
  1184. pPreviousName = pRes->Name;
  1185. pRes = pRes->pnext;
  1186. }
  1187. }
  1188. pType = pType->pnext;
  1189. }
  1190. cb = REMAINDER(cbName + cbType, CBLONG);
  1191. /* Add up the number of bytes needed to store the directory. There is
  1192. * one type table with cTypes entries. They point to cTypes name tables
  1193. * that have a total of cNames entries. Each of them points to a language
  1194. * table and there are a total of cRes entries in all the language tables.
  1195. * Finally, we have the space needed for the Directory string entries,
  1196. * some extra padding to attain the desired alignment, and the space for
  1197. * cRes data entry headers.
  1198. */
  1199. cbRestab = sizeof(IMAGE_RESOURCE_DIRECTORY) + /* root dir (types) */
  1200. cTypes * sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY) +
  1201. cTypes * sizeof(IMAGE_RESOURCE_DIRECTORY) + /* subdir2 (names) */
  1202. cNames * sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY) +
  1203. cNames * sizeof(IMAGE_RESOURCE_DIRECTORY) + /* subdir3 (langs) */
  1204. cRes * sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY) +
  1205. (cbName + cbType) + /* name/type strings */
  1206. cb + /* padding */
  1207. cRes * sizeof(IMAGE_RESOURCE_DATA_ENTRY); /* data entries */
  1208. cbResource += cbRestab; /* add in the resource table */
  1209. // Find any current resource sections
  1210. pObjResourceOld = FindSection(pObjtblOld, pObjLast, ".rsrc");
  1211. pObjResourceOldX = FindSection(pObjtblOld, pObjLast, ".rsrc1");
  1212. if (pObjResourceOld == NULL) {
  1213. cb = 0x7fffffff; /* can fill forever */
  1214. }
  1215. else if (pObjResourceOld + 1 == pObjResourceOldX) {
  1216. nObjResource = (LONG)(pObjResourceOld - pObjtblOld);
  1217. DPrintf((DebugBuf,"Old Resource section #%lu\n", nObjResource+1));
  1218. DPrintf((DebugBuf,"Merging old Resource extra section #%lu\n", nObjResource+2));
  1219. cb = 0x7fffffff; /* merge resource sections */
  1220. }
  1221. else {
  1222. nObjResource = (LONG)(pObjResourceOld - pObjtblOld);
  1223. DPrintf((DebugBuf,"Old Resource section #%lu\n", nObjResource+1));
  1224. cb = (pObjResourceOld+1)->VirtualAddress -
  1225. pObjResourceOld->VirtualAddress;
  1226. if (cbRestab > (ULONG)cb) {
  1227. DPrintf((DebugBuf, "Resource Table Too Large\n"));
  1228. return ERROR_INVALID_DATA;
  1229. }
  1230. }
  1231. /*
  1232. * Discover where the first discardable section is. This is where
  1233. * we will stick any new resource section.
  1234. *
  1235. * Note that we are ignoring discardable sections such as .CRT -
  1236. * this is so that we don't cause any relocation problems.
  1237. * Let's hope that .reloc is the one we want!!!
  1238. */
  1239. pObjOld = FindSection(pObjtblOld, pObjLast, ".reloc");
  1240. if (pObjResourceOld != NULL && cbResource > (ULONG)cb) {
  1241. if (pObjResourceOld != NULL && pObjOld == pObjResourceOld + 1) {
  1242. DPrintf((DebugBuf, "Large resource section pushes .reloc\n"));
  1243. cb = 0x7fffffff; /* can fill forever */
  1244. }
  1245. else if (pObjResourceOldX == NULL) {
  1246. DPrintf((DebugBuf, "Too much resource data for old .rsrc section\n"));
  1247. nObjResourceX = (LONG)(pObjOld - pObjtblOld);
  1248. adjust = pObjOld->VirtualAddress - pObjResourceOld->VirtualAddress;
  1249. }
  1250. else { /* have already merged .rsrc & .rsrc1, if possible */
  1251. DPrintf((DebugBuf, ".rsrc1 section not empty\n"));
  1252. nObjResourceX = (LONG)(pObjResourceOldX - pObjtblOld);
  1253. adjust = pObjResourceOldX->VirtualAddress -
  1254. pObjResourceOld ->VirtualAddress;
  1255. }
  1256. }
  1257. /*
  1258. * Walk the type lists and figure out where the Data entry header will
  1259. * go. Keep a running total of the size for each data element so we
  1260. * can store this in the section header.
  1261. */
  1262. DPrintf((DebugBuf, "Beginning loop to assign resources to addresses\n"));
  1263. /* first, those in the named type list */
  1264. cbResource = cbRestab; /* assign resource table to 1st rsrc section */
  1265. /* adjust == offset to .rsrc1 */
  1266. /* cb == size availble in .rsrc */
  1267. cbNew = 0; /* count of bytes in second .rsrc */
  1268. DPrintf((DebugBuf, "Walk type: NAME list\n"));
  1269. pType = pUpdate->ResTypeHeadName;
  1270. while (pType != NULL) {
  1271. if (pType->NameHeadName != NULL || pType->NameHeadID != NULL) {
  1272. DPrintf((DebugBuf, "Resource type "));
  1273. DPrintfu((pType->Type->szStr));
  1274. DPrintfn((DebugBuf, "\n"));
  1275. pRes = pType->NameHeadName;
  1276. while (pRes) {
  1277. DPrintf((DebugBuf, "Resource "));
  1278. DPrintfu((pRes->Name->szStr));
  1279. DPrintfn((DebugBuf, "\n"));
  1280. cbResource = AssignResourceToSection(&pRes,
  1281. adjust, cbResource, cb, &cbNew);
  1282. }
  1283. pRes = pType->NameHeadID;
  1284. while (pRes) {
  1285. DPrintf((DebugBuf, "Resource %hu\n", pRes->Name->uu.Ordinal));
  1286. cbResource = AssignResourceToSection(&pRes,
  1287. adjust, cbResource, cb, &cbNew);
  1288. }
  1289. }
  1290. pType = pType->pnext;
  1291. }
  1292. /* then, count those in the ID type list */
  1293. DPrintf((DebugBuf, "Walk type: ID list\n"));
  1294. pType = pUpdate->ResTypeHeadID;
  1295. while (pType != NULL) {
  1296. if (pType->NameHeadName != NULL || pType->NameHeadID != NULL) {
  1297. DPrintf((DebugBuf, "Resource type %hu\n", pType->Type->uu.Ordinal));
  1298. pRes = pType->NameHeadName;
  1299. while (pRes) {
  1300. DPrintf((DebugBuf, "Resource "));
  1301. DPrintfu((pRes->Name->szStr));
  1302. DPrintfn((DebugBuf, "\n"));
  1303. cbResource = AssignResourceToSection(&pRes,
  1304. adjust, cbResource, cb, &cbNew);
  1305. }
  1306. pRes = pType->NameHeadID;
  1307. while (pRes) {
  1308. DPrintf((DebugBuf, "Resource %hu\n", pRes->Name->uu.Ordinal));
  1309. cbResource = AssignResourceToSection(&pRes,
  1310. adjust, cbResource, cb, &cbNew);
  1311. }
  1312. }
  1313. pType = pType->pnext;
  1314. }
  1315. /*
  1316. * At this point:
  1317. * cbResource has offset of first byte past the last resource.
  1318. * cbNew has the count of bytes in the first resource section,
  1319. * if there are two sections.
  1320. */
  1321. if (cbNew == 0)
  1322. cbNew = cbResource;
  1323. /*
  1324. * Discover where the Debug info is (if any)?
  1325. */
  1326. pObjDebug = FindSection(pObjtblOld, pObjLast, ".debug");
  1327. if (pObjDebug != NULL) {
  1328. if (Old.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress == 0) {
  1329. DPrintf((DebugBuf, ".debug section but no debug directory\n"));
  1330. return ERROR_INVALID_DATA;
  1331. }
  1332. if (pObjDebug != pObjLast-1) {
  1333. DPrintf((DebugBuf, "debug section not last section in file\n"));
  1334. return ERROR_INVALID_DATA;
  1335. }
  1336. DPrintf((DebugBuf, "Debug section: %#08lx bytes @%#08lx\n",
  1337. pObjDebug->SizeOfRawData,
  1338. pObjDebug->PointerToRawData));
  1339. }
  1340. pObjDebugDirOld = NULL;
  1341. for (pObjOld=pObjtblOld ; pObjOld<pObjLast ; pObjOld++) {
  1342. if (Old.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress >= pObjOld->VirtualAddress &&
  1343. Old.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress < pObjOld->VirtualAddress+pObjOld->SizeOfRawData) {
  1344. pObjDebugDirOld = pObjOld;
  1345. break;
  1346. }
  1347. }
  1348. /*
  1349. * Discover where the first discardable section is. This is where
  1350. * we will stick any new resource section.
  1351. *
  1352. * Note that we are ignoring discardable sections such as .CRT -
  1353. * this is so that we don't cause any relocation problems.
  1354. * Let's hope that .reloc is the one we want!!!
  1355. */
  1356. pObjOld = FindSection(pObjtblOld, pObjLast, ".reloc");
  1357. if (nObjResource == -1) { /* no old resource section */
  1358. if (pObjOld != NULL)
  1359. nObjResource = (LONG)(pObjOld - pObjtblOld);
  1360. else if (pObjDebug != NULL)
  1361. nObjResource = (LONG)(pObjDebug - pObjtblOld);
  1362. else
  1363. nObjResource = New.FileHeader.NumberOfSections;
  1364. New.FileHeader.NumberOfSections++;
  1365. }
  1366. DPrintf((DebugBuf, "Resources assigned to section #%lu\n", nObjResource+1));
  1367. if (nObjResourceX != -1) {
  1368. if (pObjResourceOldX != NULL) {
  1369. nObjResourceX = (LONG)(pObjResourceOldX - pObjtblOld);
  1370. New.FileHeader.NumberOfSections--;
  1371. }
  1372. else if (pObjOld != NULL)
  1373. nObjResourceX = (LONG)(pObjOld - pObjtblOld);
  1374. else if (pObjDebug != NULL)
  1375. nObjResourceX = (LONG)(pObjDebug - pObjtblOld);
  1376. else
  1377. nObjResourceX = New.FileHeader.NumberOfSections;
  1378. New.FileHeader.NumberOfSections++;
  1379. DPrintf((DebugBuf, "Extra resources assigned to section #%lu\n",
  1380. nObjResourceX+1));
  1381. }
  1382. else if (pObjResourceOldX != NULL) { /* Was old .rsrc1 section? */
  1383. DPrintf((DebugBuf, "Extra resource section deleted\n"));
  1384. New.FileHeader.NumberOfSections--; /* yes, delete it */
  1385. }
  1386. /*
  1387. * If we had to add anything to the header (section table),
  1388. * then we have to update the header size and rva's in the header.
  1389. */
  1390. adjust = (New.FileHeader.NumberOfSections -
  1391. Old.FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER);
  1392. cb = Old.OptionalHeader.SizeOfHeaders -
  1393. (Old.FileHeader.NumberOfSections*sizeof(IMAGE_SECTION_HEADER) +
  1394. sizeof(IMAGE_NT_HEADERS) + cbOldexe );
  1395. if (adjust > (ULONG)cb) {
  1396. int i;
  1397. adjust -= cb;
  1398. DPrintf((DebugBuf, "Adjusting header RVAs by %#08lx\n", adjust));
  1399. for (i = 0; i < IMAGE_NUMBEROF_DIRECTORY_ENTRIES ; i++) {
  1400. if (New.OptionalHeader.DataDirectory[i].VirtualAddress &&
  1401. New.OptionalHeader.DataDirectory[i].VirtualAddress < New.OptionalHeader.SizeOfHeaders) {
  1402. DPrintf((DebugBuf, "Adjusting unit[%s] RVA from %#08lx to %#08lx\n",
  1403. apszUnit[i],
  1404. New.OptionalHeader.DataDirectory[i].VirtualAddress,
  1405. New.OptionalHeader.DataDirectory[i].VirtualAddress + adjust));
  1406. New.OptionalHeader.DataDirectory[i].VirtualAddress += adjust;
  1407. }
  1408. }
  1409. New.OptionalHeader.SizeOfHeaders += adjust;
  1410. }
  1411. /* Allocate storage for new section table */
  1412. cb = New.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
  1413. pObjtblNew = (PIMAGE_SECTION_HEADER)RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( RES_TAG ), (short)cb);
  1414. if (pObjtblNew == NULL) {
  1415. cb = ERROR_NOT_ENOUGH_MEMORY;
  1416. goto AbortExit;
  1417. }
  1418. RtlZeroMemory((PVOID)pObjtblNew, cb);
  1419. DPrintf((DebugBuf, "New section table: %#08lx bytes at %#08lx\n", cb, pObjtblNew));
  1420. pObjResourceNew = pObjtblNew + nObjResource;
  1421. /*
  1422. * copy old section table to new
  1423. */
  1424. adjust = 0; /* adjustment to virtual address */
  1425. for (pObjOld=pObjtblOld,pObjNew=pObjtblNew ; pObjOld<pObjLast ; pObjOld++) {
  1426. if (pObjOld == pObjResourceOldX) {
  1427. if (nObjResourceX == -1) {
  1428. // we have to move back all the other section.
  1429. // the .rsrc1 is bigger than what we need
  1430. // adjust must be a negative number
  1431. adjust -= (pObjOld+1)->VirtualAddress - pObjOld->VirtualAddress;
  1432. }
  1433. continue;
  1434. }
  1435. else if (pObjNew == pObjResourceNew) {
  1436. DPrintf((DebugBuf, "Resource Section %i\n", nObjResource+1));
  1437. cb = ROUNDUP(cbNew, New.OptionalHeader.FileAlignment);
  1438. if (pObjResourceOld == NULL) {
  1439. adjust = ROUNDUP(cbNew, New.OptionalHeader.SectionAlignment);
  1440. RtlZeroMemory(pObjNew, sizeof(IMAGE_SECTION_HEADER));
  1441. strcpy(pObjNew->Name, ".rsrc");
  1442. pObjNew->VirtualAddress = pObjOld->VirtualAddress;
  1443. pObjNew->PointerToRawData = pObjOld->PointerToRawData;
  1444. pObjNew->Characteristics = IMAGE_SCN_MEM_READ |
  1445. IMAGE_SCN_MEM_WRITE | IMAGE_SCN_CNT_INITIALIZED_DATA;
  1446. pObjNew->SizeOfRawData = cb;
  1447. pObjNew->Misc.VirtualSize = ROUNDUP(cb, New.OptionalHeader.SectionAlignment);
  1448. }
  1449. else {
  1450. *pObjNew = *pObjOld; /* copy obj table entry */
  1451. pObjNew->SizeOfRawData = cb;
  1452. pObjNew->Misc.VirtualSize = ROUNDUP(cb, New.OptionalHeader.SectionAlignment);
  1453. if (pObjNew->SizeOfRawData == pObjOld->SizeOfRawData) {
  1454. adjust = 0;
  1455. }
  1456. else if (pObjNew->SizeOfRawData > pObjOld->SizeOfRawData) {
  1457. adjust +=
  1458. ROUNDUP(cbNew, New.OptionalHeader.SectionAlignment) -
  1459. ((pObjOld+1)->VirtualAddress-pObjOld->VirtualAddress);
  1460. }
  1461. else { /* is smaller, but pad so will be valid */
  1462. adjust = 0;
  1463. pObjNew->SizeOfRawData = pObjResourceOld->SizeOfRawData;
  1464. pObjNew->Misc.VirtualSize = ROUNDUP(pObjNew->SizeOfRawData, New.OptionalHeader.SectionAlignment);
  1465. /* don't need to set VirtualSize - will be the same */
  1466. cbMustPad = pObjResourceOld->SizeOfRawData;
  1467. }
  1468. }
  1469. pObjNew++;
  1470. if (pObjResourceOld == NULL)
  1471. goto rest_of_table;
  1472. }
  1473. else if (nObjResourceX != -1 && pObjNew == pObjtblNew + nObjResourceX) {
  1474. DPrintf((DebugBuf, "Additional Resource Section %i\n",
  1475. nObjResourceX+1));
  1476. RtlZeroMemory(pObjNew, sizeof(IMAGE_SECTION_HEADER));
  1477. strcpy(pObjNew->Name, ".rsrc1");
  1478. /*
  1479. * Before we copy the virtual address we have to move back the
  1480. * .reloc * virtual address. Otherwise we will keep moving the
  1481. * reloc VirtualAddress forward.
  1482. * We will have to move back the address of .rsrc1
  1483. */
  1484. if (pObjResourceOldX == NULL) {
  1485. // This is the first time we have a .rsrc1
  1486. pObjNew->VirtualAddress = pObjOld->VirtualAddress;
  1487. pObjNew->Characteristics = IMAGE_SCN_MEM_READ |
  1488. IMAGE_SCN_MEM_WRITE | IMAGE_SCN_CNT_INITIALIZED_DATA;
  1489. adjust = ROUNDUP(cbResource, New.OptionalHeader.SectionAlignment) +
  1490. pObjResourceNew->VirtualAddress - pObjNew->VirtualAddress;
  1491. DPrintf((DebugBuf, "Added .rsrc1. VirtualAddress %lu\t adjust: %lu\n", pObjNew->VirtualAddress, adjust ));
  1492. }
  1493. else {
  1494. // we already have an .rsrc1 use the position of that and
  1495. // calculate the new adjust
  1496. pObjNew->VirtualAddress = pObjResourceOldX->VirtualAddress;
  1497. pObjNew->Characteristics = IMAGE_SCN_MEM_READ |
  1498. IMAGE_SCN_MEM_WRITE | IMAGE_SCN_CNT_INITIALIZED_DATA;
  1499. DPrintf((DebugBuf, ".rsrc1 Keep old position.\t\tVirtualAddress %lu\t", pObjNew->VirtualAddress ));
  1500. // Check if we have enough room in the old .rsrc1
  1501. // Include the full size of the section, data + roundup
  1502. if (cbResource -
  1503. (pObjResourceOldX->VirtualAddress - pObjResourceOld->VirtualAddress) <=
  1504. pObjOld->VirtualAddress - pObjNew->VirtualAddress ) {
  1505. // we have to move back all the other section.
  1506. // the .rsrc1 is bigger than what we need
  1507. // adjust must be a negative number
  1508. // calc new adjust size
  1509. adjust = ROUNDUP(cbResource, New.OptionalHeader.SectionAlignment) +
  1510. pObjResourceNew->VirtualAddress -
  1511. pObjOld->VirtualAddress;
  1512. DPrintf((DebugBuf, "adjust: %ld\tsmall: New %lu\tOld %lu\n", adjust,
  1513. cbResource -
  1514. (pObjResourceOldX->VirtualAddress - pObjResourceOld->VirtualAddress),
  1515. pObjOld->VirtualAddress - pObjNew->VirtualAddress));
  1516. }
  1517. else {
  1518. // we have to move the section again.
  1519. // The .rsrc1 is too small
  1520. adjust = ROUNDUP(cbResource, New.OptionalHeader.SectionAlignment) +
  1521. pObjResourceNew->VirtualAddress -
  1522. pObjOld->VirtualAddress;
  1523. DPrintf((DebugBuf, "adjust: %lu\tsmall: New %lu\tOld %lu\n", adjust,
  1524. cbResource -
  1525. (pObjResourceOldX->VirtualAddress - pObjResourceOld->VirtualAddress),
  1526. pObjOld->VirtualAddress - pObjNew->VirtualAddress));
  1527. }
  1528. }
  1529. pObjNew++;
  1530. goto rest_of_table;
  1531. }
  1532. else if (pObjNew < pObjResourceNew) {
  1533. DPrintf((DebugBuf, "copying section table entry %i@%#08lx\n",
  1534. pObjOld - pObjtblOld + 1, pObjNew));
  1535. *pObjNew++ = *pObjOld; /* copy obj table entry */
  1536. }
  1537. else {
  1538. rest_of_table:
  1539. DPrintf((DebugBuf, "copying section table entry %i@%#08lx\n",
  1540. pObjOld - pObjtblOld + 1, pObjNew));
  1541. DPrintf((DebugBuf, "adjusting VirtualAddress by %#08lx\n", adjust));
  1542. *pObjNew++ = *pObjOld;
  1543. (pObjNew-1)->VirtualAddress += adjust;
  1544. }
  1545. }
  1546. pObjNew = pObjtblNew + New.FileHeader.NumberOfSections - 1;
  1547. New.OptionalHeader.SizeOfImage = ROUNDUP(pObjNew->VirtualAddress +
  1548. pObjNew->SizeOfRawData,
  1549. New.OptionalHeader.SectionAlignment);
  1550. /* allocate room to build the resource directory/tables in */
  1551. pResTab = (PIMAGE_RESOURCE_DIRECTORY)RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( RES_TAG ), cbRestab);
  1552. if (pResTab == NULL) {
  1553. cb = ERROR_NOT_ENOUGH_MEMORY;
  1554. goto AbortExit;
  1555. }
  1556. /* First, setup the "root" type directory table. It will be followed by */
  1557. /* Types directory entries. */
  1558. RtlZeroMemory((PVOID)pResTab, cbRestab);
  1559. DPrintf((DebugBuf, "resource directory tables: %#08lx bytes at %#08lx(mem)\n", cbRestab, pResTab));
  1560. p = (PUCHAR)pResTab;
  1561. pResTab->Characteristics = 0L;
  1562. pResTab->TimeDateStamp = clock;
  1563. pResTab->MajorVersion = MAJOR_RESOURCE_VERSION;
  1564. pResTab->MinorVersion = MINOR_RESOURCE_VERSION;
  1565. pResTab->NumberOfNamedEntries = (USHORT)cTypeStr;
  1566. pResTab->NumberOfIdEntries = (USHORT)(cTypes - cTypeStr);
  1567. /* Calculate the start of the various parts of the resource table. */
  1568. /* We need the start of the Type/Name/Language directories as well */
  1569. /* as the start of the UNICODE strings and the actual data nodes. */
  1570. pResDirT = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pResTab + 1);
  1571. pResDirN = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(((PUCHAR)pResDirT) +
  1572. cTypes * sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY));
  1573. pResDirL = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(((PUCHAR)pResDirN) +
  1574. cTypes * sizeof(IMAGE_RESOURCE_DIRECTORY) +
  1575. cNames * sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY));
  1576. pResData = (PIMAGE_RESOURCE_DATA_ENTRY)(((PUCHAR)pResDirL) +
  1577. cNames * sizeof(IMAGE_RESOURCE_DIRECTORY) +
  1578. cRes * sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY));
  1579. pResStr = (PUSHORT)(((PUCHAR)pResData) +
  1580. cRes * sizeof(IMAGE_RESOURCE_DATA_ENTRY));
  1581. pResStrEnd = (PUSHORT)(((PUCHAR)pResStr) + cbName + cbType);
  1582. /*
  1583. * Loop over type table, building the PE resource table.
  1584. */
  1585. /*
  1586. * *****************************************************************
  1587. * This code doesn't sort the table - the TYPEINFO and RESINFO **
  1588. * insertion code in rcp.c (AddResType and SaveResFile) do the **
  1589. * insertion by ordinal type and name, so we don't have to sort **
  1590. * it at this point. **
  1591. * *****************************************************************
  1592. */
  1593. DPrintf((DebugBuf, "building resource directory\n"));
  1594. // First, add all the entries in the Types: Alpha list.
  1595. DPrintf((DebugBuf, "Walk the type: Alpha list\n"));
  1596. pType = pUpdate->ResTypeHeadName;
  1597. while (pType) {
  1598. DPrintf((DebugBuf, "resource type "));
  1599. DPrintfu((pType->Type->szStr));
  1600. DPrintfn((DebugBuf, "\n"));
  1601. pResDirT->Name = (ULONG)((((PUCHAR)pResStr) - p) |
  1602. IMAGE_RESOURCE_NAME_IS_STRING);
  1603. pResDirT->OffsetToData = (ULONG)((((PUCHAR)pResDirN) - p) |
  1604. IMAGE_RESOURCE_DATA_IS_DIRECTORY);
  1605. pResDirT++;
  1606. *pResStr = pType->Type->cbsz;
  1607. wcsncpy((WCHAR*)(pResStr+1), pType->Type->szStr, pType->Type->cbsz);
  1608. pResStr += pType->Type->cbsz + 1;
  1609. pResTabN = (PIMAGE_RESOURCE_DIRECTORY)pResDirN;
  1610. SetRestab(pResTabN, clock,
  1611. (USHORT)pType->NumberOfNamesName, (USHORT)pType->NumberOfNamesID);
  1612. pResDirN = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pResTabN + 1);
  1613. pPreviousName = NULL;
  1614. pRes = pType->NameHeadName;
  1615. while (pRes) {
  1616. DPrintf((DebugBuf, "resource "));
  1617. DPrintfu((pRes->Name->szStr));
  1618. DPrintfn((DebugBuf, "\n"));
  1619. if (pPreviousName == NULL ||
  1620. wcsncmp(pPreviousName->szStr,
  1621. pRes->Name->szStr,
  1622. pRes->Name->cbsz) != 0) {
  1623. // Setup a new name directory
  1624. pResDirN->Name = (ULONG)((((PUCHAR)pResStr)-p) |
  1625. IMAGE_RESOURCE_NAME_IS_STRING);
  1626. pResDirN->OffsetToData = (ULONG)((((PUCHAR)pResDirL)-p) |
  1627. IMAGE_RESOURCE_DATA_IS_DIRECTORY);
  1628. pResDirN++;
  1629. // Copy the alpha name to a string entry
  1630. *pResStr = pRes->Name->cbsz;
  1631. wcsncpy((WCHAR*)(pResStr+1),pRes->Name->szStr,pRes->Name->cbsz);
  1632. pResStr += pRes->Name->cbsz + 1;
  1633. pPreviousName = pRes->Name;
  1634. // Setup the Language table
  1635. pResTabL = (PIMAGE_RESOURCE_DIRECTORY)pResDirL;
  1636. SetRestab(pResTabL, clock,
  1637. (USHORT)0, (USHORT)pRes->NumberOfLanguages);
  1638. pResDirL = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pResTabL + 1);
  1639. }
  1640. // Setup a new Language directory
  1641. pResDirL->Name = pRes->LanguageId;
  1642. pResDirL->OffsetToData = (ULONG)(((PUCHAR)pResData) - p);
  1643. pResDirL++;
  1644. // Setup a new resource data entry
  1645. SetResdata(pResData,
  1646. pRes->OffsetToData+pObjtblNew[nObjResource].VirtualAddress,
  1647. pRes->DataSize);
  1648. pResData++;
  1649. pRes = pRes->pnext;
  1650. }
  1651. pPreviousName = NULL;
  1652. pRes = pType->NameHeadID;
  1653. while (pRes) {
  1654. DPrintf((DebugBuf, "resource %hu\n", pRes->Name->uu.Ordinal));
  1655. if (pPreviousName == NULL ||
  1656. pPreviousName->uu.Ordinal != pRes->Name->uu.Ordinal) {
  1657. // Setup the name directory to point to the next language
  1658. // table
  1659. pResDirN->Name = pRes->Name->uu.Ordinal;
  1660. pResDirN->OffsetToData = (ULONG)((((PUCHAR)pResDirL)-p) |
  1661. IMAGE_RESOURCE_DATA_IS_DIRECTORY);
  1662. pResDirN++;
  1663. pPreviousName = pRes->Name;
  1664. // Init a new Language table
  1665. pResTabL = (PIMAGE_RESOURCE_DIRECTORY)pResDirL;
  1666. SetRestab(pResTabL, clock,
  1667. (USHORT)0, (USHORT)pRes->NumberOfLanguages);
  1668. pResDirL = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pResTabL + 1);
  1669. }
  1670. // Setup a new language directory entry to point to the next
  1671. // resource
  1672. pResDirL->Name = pRes->LanguageId;
  1673. pResDirL->OffsetToData = (ULONG)(((PUCHAR)pResData) - p);
  1674. pResDirL++;
  1675. // Setup a new resource data entry
  1676. SetResdata(pResData,
  1677. pRes->OffsetToData+pObjtblNew[nObjResource].VirtualAddress,
  1678. pRes->DataSize);
  1679. pResData++;
  1680. pRes = pRes->pnext;
  1681. }
  1682. pType = pType->pnext;
  1683. }
  1684. // Do the same thing, but this time, use the Types: ID list.
  1685. DPrintf((DebugBuf, "Walk the type: ID list\n"));
  1686. pType = pUpdate->ResTypeHeadID;
  1687. while (pType) {
  1688. DPrintf((DebugBuf, "resource type %hu\n", pType->Type->uu.Ordinal));
  1689. pResDirT->Name = (ULONG)pType->Type->uu.Ordinal;
  1690. pResDirT->OffsetToData = (ULONG)((((PUCHAR)pResDirN) - p) |
  1691. IMAGE_RESOURCE_DATA_IS_DIRECTORY);
  1692. pResDirT++;
  1693. pResTabN = (PIMAGE_RESOURCE_DIRECTORY)pResDirN;
  1694. SetRestab(pResTabN, clock,
  1695. (USHORT)pType->NumberOfNamesName, (USHORT)pType->NumberOfNamesID);
  1696. pResDirN = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pResTabN + 1);
  1697. pPreviousName = NULL;
  1698. pRes = pType->NameHeadName;
  1699. while (pRes) {
  1700. DPrintf((DebugBuf, "resource "));
  1701. DPrintfu((pRes->Name->szStr));
  1702. DPrintfn((DebugBuf, "\n"));
  1703. if (pPreviousName == NULL ||
  1704. wcsncmp(pPreviousName->szStr,
  1705. pRes->Name->szStr,
  1706. pRes->Name->cbsz) != 0) {
  1707. // Setup a new name directory
  1708. pResDirN->Name = (ULONG)((((PUCHAR)pResStr)-p) |
  1709. IMAGE_RESOURCE_NAME_IS_STRING);
  1710. pResDirN->OffsetToData = (ULONG)((((PUCHAR)pResDirL)-p) |
  1711. IMAGE_RESOURCE_DATA_IS_DIRECTORY);
  1712. pResDirN++;
  1713. // Copy the alpha name to a string entry.
  1714. *pResStr = pRes->Name->cbsz;
  1715. wcsncpy((WCHAR*)(pResStr+1),pRes->Name->szStr,pRes->Name->cbsz);
  1716. pResStr += pRes->Name->cbsz + 1;
  1717. pPreviousName = pRes->Name;
  1718. // Setup the Language table
  1719. pResTabL = (PIMAGE_RESOURCE_DIRECTORY)pResDirL;
  1720. SetRestab(pResTabL, clock,
  1721. (USHORT)0, (USHORT)pRes->NumberOfLanguages);
  1722. pResDirL = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pResTabL + 1);
  1723. }
  1724. // Setup a new Language directory
  1725. pResDirL->Name = pRes->LanguageId;
  1726. pResDirL->OffsetToData = (ULONG)(((PUCHAR)pResData) - p);
  1727. pResDirL++;
  1728. // Setup a new resource data entry
  1729. SetResdata(pResData,
  1730. pRes->OffsetToData+pObjtblNew[nObjResource].VirtualAddress,
  1731. pRes->DataSize);
  1732. pResData++;
  1733. pRes = pRes->pnext;
  1734. }
  1735. pPreviousName = NULL;
  1736. pRes = pType->NameHeadID;
  1737. while (pRes) {
  1738. DPrintf((DebugBuf, "resource %hu\n", pRes->Name->uu.Ordinal));
  1739. if (pPreviousName == NULL ||
  1740. pPreviousName->uu.Ordinal != pRes->Name->uu.Ordinal) {
  1741. // Setup the name directory to point to the next language
  1742. // table
  1743. pResDirN->Name = pRes->Name->uu.Ordinal;
  1744. pResDirN->OffsetToData = (ULONG)((((PUCHAR)pResDirL)-p) |
  1745. IMAGE_RESOURCE_DATA_IS_DIRECTORY);
  1746. pResDirN++;
  1747. pPreviousName = pRes->Name;
  1748. // Init a new Language table
  1749. pResTabL = (PIMAGE_RESOURCE_DIRECTORY)pResDirL;
  1750. SetRestab(pResTabL, clock,
  1751. (USHORT)0, (USHORT)pRes->NumberOfLanguages);
  1752. pResDirL = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pResTabL + 1);
  1753. }
  1754. // Setup a new language directory entry to point to the next
  1755. // resource
  1756. pResDirL->Name = pRes->LanguageId;
  1757. pResDirL->OffsetToData = (ULONG)(((PUCHAR)pResData) - p);
  1758. pResDirL++;
  1759. // Setup a new resource data entry
  1760. SetResdata(pResData,
  1761. pRes->OffsetToData+pObjtblNew[nObjResource].VirtualAddress,
  1762. pRes->DataSize);
  1763. pResData++;
  1764. pRes = pRes->pnext;
  1765. }
  1766. pType = pType->pnext;
  1767. }
  1768. DPrintf((DebugBuf, "Zeroing %u bytes after strings at %#08lx(mem)\n",
  1769. (pResStrEnd - pResStr) * sizeof(*pResStr), pResStr));
  1770. while (pResStr < pResStrEnd) {
  1771. *pResStr++ = 0;
  1772. }
  1773. #if DBG
  1774. {
  1775. USHORT j = 0;
  1776. PUSHORT pus = (PUSHORT)pResTab;
  1777. while (pus < (PUSHORT)pResData) {
  1778. DPrintf((DebugBuf, "%04x\t%04x %04x %04x %04x %04x %04x %04x %04x\n",
  1779. j,
  1780. *pus,
  1781. *(pus + 1),
  1782. *(pus + 2),
  1783. *(pus + 3),
  1784. *(pus + 4),
  1785. *(pus + 5),
  1786. *(pus + 6),
  1787. *(pus + 7)));
  1788. pus += 8;
  1789. j += 16;
  1790. }
  1791. }
  1792. #endif /* DBG */
  1793. /*
  1794. * copy the Old exe header and stub, and allocate room for the PE header.
  1795. */
  1796. DPrintf((DebugBuf, "copying through PE header: %#08lx bytes @0x0\n",
  1797. cbOldexe + sizeof(IMAGE_NT_HEADERS)));
  1798. MuMoveFilePos(inpfh, 0L);
  1799. MuCopy(inpfh, outfh, cbOldexe + sizeof(IMAGE_NT_HEADERS));
  1800. /*
  1801. * Copy rest of file header
  1802. */
  1803. DPrintf((DebugBuf, "skipping section table: %#08lx bytes @%#08lx\n",
  1804. New.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER),
  1805. FilePos(outfh)));
  1806. DPrintf((DebugBuf, "copying hdr data: %#08lx bytes @%#08lx ==> @%#08lx\n",
  1807. Old.OptionalHeader.SizeOfHeaders - ibObjTabEnd,
  1808. ibObjTabEnd,
  1809. ibObjTabEnd + New.OptionalHeader.SizeOfHeaders -
  1810. Old.OptionalHeader.SizeOfHeaders));
  1811. MuMoveFilePos(outfh, ibObjTabEnd + New.OptionalHeader.SizeOfHeaders -
  1812. Old.OptionalHeader.SizeOfHeaders);
  1813. MuMoveFilePos(inpfh, ibObjTabEnd);
  1814. MuCopy(inpfh, outfh, Old.OptionalHeader.SizeOfHeaders - ibObjTabEnd);
  1815. /*
  1816. * copy existing image sections
  1817. */
  1818. /* Align data sections on sector boundary */
  1819. cb = REMAINDER(New.OptionalHeader.SizeOfHeaders, New.OptionalHeader.FileAlignment);
  1820. New.OptionalHeader.SizeOfHeaders += cb;
  1821. DPrintf((DebugBuf, "padding header with %#08lx bytes @%#08lx\n", cb, FilePos(outfh)));
  1822. while (cb >= cbPadMax) {
  1823. MuWrite(outfh, pchZero, cbPadMax);
  1824. cb -= cbPadMax;
  1825. }
  1826. MuWrite(outfh, pchZero, cb);
  1827. cb = ROUNDUP(Old.OptionalHeader.SizeOfHeaders, Old.OptionalHeader.FileAlignment);
  1828. MuMoveFilePos(inpfh, cb);
  1829. /* copy one section at a time */
  1830. New.OptionalHeader.SizeOfInitializedData = 0;
  1831. for (pObjOld = pObjtblOld , pObjNew = pObjtblNew ;
  1832. pObjOld < pObjLast ;
  1833. pObjNew++) {
  1834. if (pObjOld == pObjResourceOldX)
  1835. pObjOld++;
  1836. if (pObjNew == pObjResourceNew) {
  1837. /* Write new resource section */
  1838. DPrintf((DebugBuf, "Primary resource section %i to %#08lx\n",
  1839. nObjResource+1, FilePos(outfh)));
  1840. pObjNew->PointerToRawData = FilePos(outfh);
  1841. New.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = pObjResourceNew->VirtualAddress;
  1842. New.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = cbResource;
  1843. ibSave = FilePos(outfh);
  1844. DPrintf((DebugBuf,
  1845. "writing resource header data: %#08lx bytes @%#08lx\n",
  1846. cbRestab, ibSave));
  1847. MuWrite(outfh, (PUCHAR)pResTab, cbRestab);
  1848. pResSave = WriteResSection(pUpdate, outfh,
  1849. New.OptionalHeader.FileAlignment,
  1850. pObjResourceNew->SizeOfRawData-cbRestab,
  1851. NULL);
  1852. cb = FilePos(outfh);
  1853. DPrintf((DebugBuf, "wrote resource data: %#08lx bytes @%#08lx\n",
  1854. cb - ibSave - cbRestab, ibSave + cbRestab));
  1855. if (cbMustPad != 0) {
  1856. cbMustPad -= cb - ibSave;
  1857. DPrintf((DebugBuf, "writing MUNGE pad: %#04lx bytes @%#08lx\n",
  1858. cbMustPad, cb));
  1859. /* assumes that cbMustPad % cbpadMax == 0 */
  1860. while (cbMustPad > 0) {
  1861. MuWrite(outfh, pchPad, cbPadMax);
  1862. cbMustPad -= cbPadMax;
  1863. }
  1864. cb = FilePos(outfh);
  1865. }
  1866. if (nObjResourceX == -1) {
  1867. MuMoveFilePos(outfh, ibSave);
  1868. DPrintf((DebugBuf,
  1869. "re-writing resource directory: %#08x bytes @%#08lx\n",
  1870. cbRestab, ibSave));
  1871. MuWrite(outfh, (PUCHAR)pResTab, cbRestab);
  1872. MuMoveFilePos(outfh, cb);
  1873. cb = FilePos(inpfh);
  1874. MuMoveFilePos(inpfh, cb+pObjOld->SizeOfRawData);
  1875. }
  1876. New.OptionalHeader.SizeOfInitializedData += pObjNew->SizeOfRawData;
  1877. if (pObjResourceOld == NULL) {
  1878. pObjNew++;
  1879. goto next_section;
  1880. }
  1881. else
  1882. pObjOld++;
  1883. }
  1884. else if (nObjResourceX != -1 && pObjNew == pObjtblNew + nObjResourceX) {
  1885. /* Write new resource section */
  1886. DPrintf((DebugBuf, "Secondary resource section %i @%#08lx\n",
  1887. nObjResourceX+1, FilePos(outfh)));
  1888. pObjNew->PointerToRawData = FilePos(outfh);
  1889. (void)WriteResSection(pUpdate, outfh,
  1890. New.OptionalHeader.FileAlignment, 0xffffffff, pResSave);
  1891. cb = FilePos(outfh);
  1892. pObjNew->SizeOfRawData = cb - pObjNew->PointerToRawData;
  1893. pObjNew->Misc.VirtualSize = ROUNDUP(pObjNew->SizeOfRawData, New.OptionalHeader.SectionAlignment);
  1894. DPrintf((DebugBuf, "wrote resource data: %#08lx bytes @%#08lx\n",
  1895. pObjNew->SizeOfRawData, pObjNew->PointerToRawData));
  1896. MuMoveFilePos(outfh, ibSave);
  1897. DPrintf((DebugBuf,
  1898. "re-writing resource directory: %#08x bytes @%#08lx\n",
  1899. cbRestab, ibSave));
  1900. MuWrite(outfh, (PUCHAR)pResTab, cbRestab);
  1901. MuMoveFilePos(outfh, cb);
  1902. New.OptionalHeader.SizeOfInitializedData += pObjNew->SizeOfRawData;
  1903. pObjNew++;
  1904. goto next_section;
  1905. }
  1906. else {
  1907. if (pObjNew < pObjResourceNew &&
  1908. pObjOld->PointerToRawData != 0 &&
  1909. pObjOld->PointerToRawData != FilePos(outfh)) {
  1910. MuMoveFilePos(outfh, pObjOld->PointerToRawData);
  1911. }
  1912. next_section:
  1913. /* Nop this section, because SteveWo doesn't know what he's doing
  1914. if ((Old.OptionalHeader.BaseOfCode == 0x400) &&
  1915. (Old.FileHeader.Machine == IMAGE_FILE_MACHINE_R3000 ||
  1916. Old.FileHeader.Machine == IMAGE_FILE_MACHINE_R4000
  1917. ) &&
  1918. (pObjOld->PointerToRawData != 0) &&
  1919. (pObjOld->VirtualAddress != New.OptionalHeader.BaseOfCode) &&
  1920. ((pObjOld->Characteristics&IMAGE_SCN_CNT_CODE) != 0)
  1921. ) {
  1922. cb = FilePos(outfh) & 0xFFF;
  1923. if (cb != 0) {
  1924. cb = (cb ^ 0xFFF) + 1;
  1925. DPrintf((DebugBuf, "padding driver code section %#08lx bytes @%#08lx\n", cb, FilePos(outfh)));
  1926. while (cb >= cbPadMax) {
  1927. MuWrite(outfh, pchZero, cbPadMax);
  1928. cb -= cbPadMax;
  1929. }
  1930. MuWrite(outfh, pchZero, cb);
  1931. }
  1932. }
  1933. End nop. */
  1934. DPrintf((DebugBuf, "copying section %i @%#08lx\n",
  1935. pObjNew-pObjtblNew+1, FilePos(outfh)));
  1936. if (pObjOld->PointerToRawData != 0) {
  1937. pObjNew->PointerToRawData = FilePos(outfh);
  1938. MuMoveFilePos(inpfh, pObjOld->PointerToRawData);
  1939. MuCopy(inpfh, outfh, pObjOld->SizeOfRawData);
  1940. }
  1941. if (pObjOld == pObjDebugDirOld) {
  1942. pObjDebugDirNew = pObjNew;
  1943. }
  1944. if ((pObjNew->Characteristics&IMAGE_SCN_CNT_INITIALIZED_DATA) != 0)
  1945. New.OptionalHeader.SizeOfInitializedData +=
  1946. pObjNew->SizeOfRawData;
  1947. pObjOld++;
  1948. }
  1949. }
  1950. if (pObjResourceOldX != NULL)
  1951. New.OptionalHeader.SizeOfInitializedData -=
  1952. pObjResourceOldX->SizeOfRawData;
  1953. /* Update the address of the relocation table */
  1954. pObjNew = FindSection(pObjtblNew,
  1955. pObjtblNew+New.FileHeader.NumberOfSections,
  1956. ".reloc");
  1957. if (pObjNew != NULL) {
  1958. New.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = pObjNew->VirtualAddress;
  1959. }
  1960. /*
  1961. * Write new section table out.
  1962. */
  1963. DPrintf((DebugBuf, "Writing new section table: %#08x bytes @%#08lx\n",
  1964. New.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER),
  1965. ibObjTab));
  1966. MuMoveFilePos(outfh, ibObjTab);
  1967. MuWrite(outfh, (PUCHAR)pObjtblNew, New.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER));
  1968. /* Seek to end of output file and issue truncating write */
  1969. adjust = _llseek(outfh, 0L, SEEK_END);
  1970. MuWrite(outfh, NULL, 0);
  1971. DPrintf((DebugBuf, "File size is: %#08lx\n", adjust));
  1972. /* If a debug section, fix up the debug table */
  1973. pObjNew = FindSection(pObjtblNew,
  1974. pObjtblNew+New.FileHeader.NumberOfSections,
  1975. ".debug");
  1976. cb = PatchDebug(inpfh, outfh,
  1977. pObjDebug, pObjNew,
  1978. pObjDebugDirOld, pObjDebugDirNew,
  1979. &Old, &New, ibMaxDbgOffsetOld, &adjust);
  1980. if (cb == NO_ERROR) {
  1981. if (pObjResourceOld == NULL) {
  1982. cb = (LONG)pObjResourceNew->SizeOfRawData;
  1983. }
  1984. else {
  1985. cb = (LONG)pObjResourceOld->SizeOfRawData -
  1986. (LONG)pObjResourceNew->SizeOfRawData;
  1987. }
  1988. cb = PatchRVAs(inpfh, outfh, pObjtblNew, cb,
  1989. &New, Old.OptionalHeader.SizeOfHeaders);
  1990. }
  1991. /* copy NOTMAPPED debug info */
  1992. if (pObjDebugDirOld != NULL && pObjDebug == NULL &&
  1993. New.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size
  1994. != 0) {
  1995. if (New.FileHeader.PointerToSymbolTable != 0)
  1996. New.FileHeader.PointerToSymbolTable = adjust; /* update symbol table ptr */
  1997. ibSave = _llseek(inpfh, 0L, SEEK_END); /* copy debug data */
  1998. _llseek(outfh, 0L, SEEK_END); /* to EOF */
  1999. MuMoveFilePos(inpfh, adjust); /* returned by PatchDebug */
  2000. DPrintf((DebugBuf, "Copying NOTMAPPED Debug Information, %#08lx bytes\n", ibSave-adjust));
  2001. MuCopy(inpfh, outfh, ibSave-adjust);
  2002. }
  2003. /*
  2004. * Write updated PE header
  2005. */
  2006. DPrintf((DebugBuf, "Writing updated file header: %#08x bytes @%#08lx\n",
  2007. sizeof(IMAGE_NT_HEADERS),
  2008. cbOldexe));
  2009. MuMoveFilePos(outfh, (long)cbOldexe);
  2010. MuWrite(outfh, (char*)&New, sizeof(IMAGE_NT_HEADERS));
  2011. /* free up allocated memory */
  2012. DPrintf((DebugBuf, "Freeing old section table: %#08lx(mem)\n", pObjtblOld));
  2013. RtlFreeHeap(RtlProcessHeap(), 0, pObjtblOld);
  2014. DPrintf((DebugBuf, "Freeing resource directory: %#08lx(mem)\n", pResTab));
  2015. RtlFreeHeap(RtlProcessHeap(), 0, pResTab);
  2016. AbortExit:
  2017. if (pObjtblNew)
  2018. {
  2019. DPrintf((DebugBuf, "Freeing new section table: %#08lx(mem)\n", pObjtblNew));
  2020. RtlFreeHeap(RtlProcessHeap(), 0, pObjtblNew);
  2021. }
  2022. return cb;
  2023. }
  2024. /***************************************************************************
  2025. * WriteResSection
  2026. *
  2027. * This routine writes out the resources asked for into the current section.
  2028. * It pads resources to dword (4-byte) boundaries.
  2029. **************************************************************************/
  2030. PRESNAME
  2031. WriteResSection(
  2032. PUPDATEDATA pUpdate,
  2033. INT outfh,
  2034. ULONG align,
  2035. ULONG cbLeft,
  2036. PRESNAME pResSave
  2037. )
  2038. {
  2039. ULONG cbB=0; /* bytes in current section */
  2040. ULONG cbT; /* bytes in current section */
  2041. ULONG size;
  2042. PRESNAME pRes;
  2043. PRESTYPE pType;
  2044. BOOL fName;
  2045. PVOID lpData;
  2046. /* Output contents associated with each resource */
  2047. pType = pUpdate->ResTypeHeadName;
  2048. while (pType) {
  2049. pRes = pType->NameHeadName;
  2050. fName = TRUE;
  2051. loop1:
  2052. for ( ; pRes ; pRes = pRes->pnext) {
  2053. if (pResSave != NULL && pRes != pResSave)
  2054. continue;
  2055. pResSave = NULL;
  2056. #if DBG
  2057. if (pType->Type->discriminant == IS_STRING) {
  2058. DPrintf((DebugBuf, " "));
  2059. DPrintfu((pType->Type->szStr));
  2060. DPrintfn((DebugBuf, "."));
  2061. }
  2062. else {
  2063. DPrintf(( DebugBuf, " %d.", pType->Type->uu.Ordinal ));
  2064. }
  2065. if (pRes->Name->discriminant == IS_STRING) {
  2066. DPrintfu((pRes->Name->szStr));
  2067. }
  2068. else {
  2069. DPrintfn(( DebugBuf, "%d", pRes->Name->uu.Ordinal ));
  2070. }
  2071. #endif
  2072. lpData = (PVOID)pRes->OffsetToDataEntry;
  2073. DPrintfn((DebugBuf, "\n"));
  2074. /* if there is room in the current section, write it there */
  2075. size = pRes->DataSize;
  2076. if (cbLeft != 0 && cbLeft >= size) { /* resource fits? */
  2077. DPrintf((DebugBuf,
  2078. "Writing resource: %#04lx bytes @%#08lx\n",
  2079. size, FilePos(outfh)));
  2080. MuWrite(outfh, lpData, size);
  2081. /* pad resource */
  2082. cbT = REMAINDER(size, CBLONG);
  2083. #ifdef DBG
  2084. if (cbT != 0)
  2085. DPrintf((DebugBuf,
  2086. "Writing small pad: %#04lx bytes @%#08lx\n",
  2087. cbT, FilePos(outfh)));
  2088. #endif
  2089. MuWrite(outfh, pchPad, cbT); /* dword */
  2090. cbB += size + cbT;
  2091. cbLeft -= size + cbT; /* less left */
  2092. continue; /* next resource */
  2093. }
  2094. else { /* will fill up section */
  2095. DPrintf((DebugBuf, "Done with .rsrc section\n"));
  2096. goto write_pad;
  2097. }
  2098. }
  2099. if (fName) {
  2100. fName = FALSE;
  2101. pRes = pType->NameHeadID;
  2102. goto loop1;
  2103. }
  2104. pType = pType->pnext;
  2105. }
  2106. pType = pUpdate->ResTypeHeadID;
  2107. while (pType) {
  2108. pRes = pType->NameHeadName;
  2109. fName = TRUE;
  2110. loop2:
  2111. for ( ; pRes ; pRes = pRes->pnext) {
  2112. if (pResSave != NULL && pRes != pResSave)
  2113. continue;
  2114. pResSave = NULL;
  2115. #if DBG
  2116. if (pType->Type->discriminant == IS_STRING) {
  2117. DPrintf((DebugBuf, " "));
  2118. DPrintfu((pType->Type->szStr));
  2119. DPrintfn((DebugBuf, "."));
  2120. }
  2121. else {
  2122. DPrintf(( DebugBuf, " %d.", pType->Type->uu.Ordinal ));
  2123. }
  2124. if (pRes->Name->discriminant == IS_STRING) {
  2125. DPrintfu((pRes->Name->szStr));
  2126. }
  2127. else {
  2128. DPrintfn(( DebugBuf, "%d", pRes->Name->uu.Ordinal ));
  2129. }
  2130. #endif
  2131. lpData = (PVOID)pRes->OffsetToDataEntry;
  2132. DPrintfn((DebugBuf, "\n"));
  2133. /* if there is room in the current section, write it there */
  2134. size = pRes->DataSize;
  2135. if (cbLeft != 0 && cbLeft >= size) { /* resource fits? */
  2136. DPrintf((DebugBuf,
  2137. "Writing resource: %#04lx bytes @%#08lx\n",
  2138. size, FilePos(outfh)));
  2139. MuWrite(outfh, lpData, size);
  2140. /* pad resource */
  2141. cbT = REMAINDER(size, CBLONG);
  2142. #ifdef DBG
  2143. if (cbT != 0)
  2144. DPrintf((DebugBuf,
  2145. "Writing small pad: %#04lx bytes @%#08lx\n",
  2146. cbT, FilePos(outfh)));
  2147. #endif
  2148. MuWrite(outfh, pchPad, cbT); /* dword */
  2149. cbB += size + cbT;
  2150. cbLeft -= size + cbT; /* less left */
  2151. continue; /* next resource */
  2152. }
  2153. else { /* will fill up section */
  2154. DPrintf((DebugBuf, "Done with .rsrc section\n"));
  2155. goto write_pad;
  2156. }
  2157. }
  2158. if (fName) {
  2159. fName = FALSE;
  2160. pRes = pType->NameHeadID;
  2161. goto loop2;
  2162. }
  2163. pType = pType->pnext;
  2164. }
  2165. pRes = NULL;
  2166. write_pad:
  2167. /* pad to alignment boundary */
  2168. cbB = FilePos(outfh);
  2169. cbT = ROUNDUP(cbB, align);
  2170. cbLeft = cbT - cbB;
  2171. DPrintf((DebugBuf, "Writing file sector pad: %#04lx bytes @%#08lx\n",
  2172. cbLeft, FilePos(outfh)));
  2173. if (cbLeft != 0) {
  2174. while (cbLeft >= cbPadMax) {
  2175. MuWrite(outfh, pchPad, cbPadMax);
  2176. cbLeft -= cbPadMax;
  2177. }
  2178. MuWrite(outfh, pchPad, cbLeft);
  2179. }
  2180. return pRes;
  2181. }
  2182. #if DBG
  2183. void
  2184. wchprintf(WCHAR*wch)
  2185. {
  2186. UNICODE_STRING ustring;
  2187. STRING string;
  2188. char buf[257];
  2189. ustring.MaximumLength = ustring.Length = wcslen(wch) * sizeof(WCHAR);
  2190. ustring.Buffer = wch;
  2191. string.Length = 0;
  2192. string.MaximumLength = 256;
  2193. string.Buffer = buf;
  2194. RtlUnicodeStringToAnsiString(&string, &ustring, FALSE);
  2195. buf[string.Length] = '\000';
  2196. DPrintfn((DebugBuf, "%s", buf));
  2197. }
  2198. #endif
  2199. //
  2200. // adjust debug directory table
  2201. //
  2202. /* */
  2203. LONG
  2204. PatchDebug(int inpfh,
  2205. int outfh,
  2206. PIMAGE_SECTION_HEADER pDebugOld,
  2207. PIMAGE_SECTION_HEADER pDebugNew,
  2208. PIMAGE_SECTION_HEADER pDebugDirOld,
  2209. PIMAGE_SECTION_HEADER pDebugDirNew,
  2210. PIMAGE_NT_HEADERS pOld,
  2211. PIMAGE_NT_HEADERS pNew,
  2212. ULONG ibMaxDbgOffsetOld,
  2213. PULONG pPointerToRawData)
  2214. {
  2215. PIMAGE_DEBUG_DIRECTORY pDbgLast;
  2216. PIMAGE_DEBUG_DIRECTORY pDbgSave;
  2217. PIMAGE_DEBUG_DIRECTORY pDbg;
  2218. ULONG ib;
  2219. ULONG adjust;
  2220. ULONG ibNew;
  2221. if (pDebugDirOld == NULL ||
  2222. pNew->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size==0)
  2223. return NO_ERROR;
  2224. pDbgSave = pDbg = (PIMAGE_DEBUG_DIRECTORY)RtlAllocateHeap(
  2225. RtlProcessHeap(), MAKE_TAG( RES_TAG ),
  2226. pNew->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size);
  2227. if (pDbg == NULL)
  2228. return ERROR_NOT_ENOUGH_MEMORY;
  2229. if (pDebugOld) {
  2230. DPrintf((DebugBuf, "Patching dbg directory: @%#08lx ==> @%#08lx\n",
  2231. pDebugOld->PointerToRawData, pDebugNew->PointerToRawData));
  2232. }
  2233. else
  2234. adjust = *pPointerToRawData; /* passed in EOF of new file */
  2235. ib = pOld->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress - pDebugDirOld->VirtualAddress;
  2236. MuMoveFilePos(inpfh, pDebugDirOld->PointerToRawData+ib);
  2237. pDbgLast = pDbg + (pNew->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size)/sizeof(IMAGE_DEBUG_DIRECTORY);
  2238. MuRead(inpfh, (PUCHAR)pDbg, pNew->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size);
  2239. if (pDebugOld == NULL) {
  2240. /* find 1st entry - use for offset */
  2241. DPrintf((DebugBuf, "Adjust: %#08lx\n",adjust));
  2242. for (ibNew=0xffffffff ; pDbg<pDbgLast ; pDbg++)
  2243. if (pDbg->PointerToRawData >= ibMaxDbgOffsetOld &&
  2244. pDbg->PointerToRawData < ibNew
  2245. )
  2246. ibNew = pDbg->PointerToRawData;
  2247. if (ibNew != 0xffffffff)
  2248. *pPointerToRawData = ibNew;
  2249. else
  2250. *pPointerToRawData = _llseek(inpfh, 0L, SEEK_END);
  2251. for (pDbg=pDbgSave ; pDbg<pDbgLast ; pDbg++) {
  2252. DPrintf((DebugBuf, "Old debug file offset: %#08lx\n",
  2253. pDbg->PointerToRawData));
  2254. if (pDbg->PointerToRawData >= ibMaxDbgOffsetOld)
  2255. pDbg->PointerToRawData += adjust - ibNew;
  2256. DPrintf((DebugBuf, "New debug file offset: %#08lx\n",
  2257. pDbg->PointerToRawData));
  2258. }
  2259. }
  2260. else {
  2261. for ( ; pDbg<pDbgLast ; pDbg++) {
  2262. DPrintf((DebugBuf, "Old debug addr: %#08lx, file offset: %#08lx\n",
  2263. pDbg->AddressOfRawData,
  2264. pDbg->PointerToRawData));
  2265. pDbg->AddressOfRawData += pDebugNew->VirtualAddress -
  2266. pDebugOld->VirtualAddress;
  2267. pDbg->PointerToRawData += pDebugNew->PointerToRawData -
  2268. pDebugOld->PointerToRawData;
  2269. DPrintf((DebugBuf, "New debug addr: %#08lx, file offset: %#08lx\n",
  2270. pDbg->AddressOfRawData,
  2271. pDbg->PointerToRawData));
  2272. }
  2273. }
  2274. MuMoveFilePos(outfh, pDebugDirNew->PointerToRawData+ib);
  2275. MuWrite(outfh, (PUCHAR)pDbgSave, pNew->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size);
  2276. RtlFreeHeap(RtlProcessHeap(), 0, pDbgSave);
  2277. return NO_ERROR;
  2278. }
  2279. //
  2280. // This routine patches various RVAs in the file to compensate
  2281. // for extra section table entries.
  2282. //
  2283. LONG
  2284. PatchRVAs(int inpfh,
  2285. int outfh,
  2286. PIMAGE_SECTION_HEADER po32,
  2287. ULONG pagedelta,
  2288. PIMAGE_NT_HEADERS pNew,
  2289. ULONG OldSize)
  2290. {
  2291. ULONG hdrdelta;
  2292. ULONG offset, rvaiat, offiat, iat;
  2293. IMAGE_EXPORT_DIRECTORY Exp;
  2294. IMAGE_IMPORT_DESCRIPTOR Imp;
  2295. ULONG i, cmod, cimp;
  2296. hdrdelta = pNew->OptionalHeader.SizeOfHeaders - OldSize;
  2297. if (hdrdelta == 0) {
  2298. return NO_ERROR;
  2299. }
  2300. //
  2301. // Patch export section RVAs
  2302. //
  2303. DPrintf((DebugBuf, "Export offset=%08lx, hdrsize=%08lx\n",
  2304. pNew->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress,
  2305. pNew->OptionalHeader.SizeOfHeaders));
  2306. if ((offset = pNew->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress) == 0)
  2307. {
  2308. DPrintf((DebugBuf, "No exports to patch\n"));
  2309. }
  2310. else if (offset >= pNew->OptionalHeader.SizeOfHeaders)
  2311. {
  2312. DPrintf((DebugBuf, "No exports in header to patch\n"));
  2313. }
  2314. else
  2315. {
  2316. MuMoveFilePos(inpfh, offset - hdrdelta);
  2317. MuRead(inpfh, (PUCHAR) &Exp, sizeof(Exp));
  2318. Exp.Name += hdrdelta;
  2319. (ULONG)Exp.AddressOfFunctions += hdrdelta;
  2320. (ULONG)Exp.AddressOfNames += hdrdelta;
  2321. (ULONG)Exp.AddressOfNameOrdinals += hdrdelta;
  2322. MuMoveFilePos(outfh, offset);
  2323. MuWrite(outfh, (PUCHAR) &Exp, sizeof(Exp));
  2324. }
  2325. //
  2326. // Patch import section RVAs
  2327. //
  2328. DPrintf((DebugBuf, "Import offset=%08lx, hdrsize=%08lx\n",
  2329. pNew->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress,
  2330. pNew->OptionalHeader.SizeOfHeaders));
  2331. if ((offset = pNew->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress) == 0)
  2332. {
  2333. DPrintf((DebugBuf, "No imports to patch\n"));
  2334. }
  2335. else if (offset >= pNew->OptionalHeader.SizeOfHeaders)
  2336. {
  2337. DPrintf((DebugBuf, "No imports in header to patch\n"));
  2338. }
  2339. else
  2340. {
  2341. for (cimp = cmod = 0; ; cmod++)
  2342. {
  2343. MuMoveFilePos(inpfh, offset + cmod * sizeof(Imp) - hdrdelta);
  2344. MuRead(inpfh, (PUCHAR) &Imp, sizeof(Imp));
  2345. if (Imp.FirstThunk == 0)
  2346. {
  2347. break;
  2348. }
  2349. Imp.Name += hdrdelta;
  2350. MuMoveFilePos(outfh, offset + cmod * sizeof(Imp));
  2351. MuWrite(outfh, (PUCHAR) &Imp, sizeof(Imp));
  2352. rvaiat = (ULONG)Imp.FirstThunk;
  2353. DPrintf((DebugBuf, "RVAIAT = %#08lx\n", (ULONG)rvaiat));
  2354. for (i = 0; i < pNew->FileHeader.NumberOfSections; i++) {
  2355. if (rvaiat >= po32[i].VirtualAddress &&
  2356. rvaiat < po32[i].VirtualAddress + po32[i].SizeOfRawData) {
  2357. offiat = rvaiat - po32[i].VirtualAddress + po32[i].PointerToRawData;
  2358. goto found;
  2359. }
  2360. }
  2361. DPrintf((DebugBuf, "IAT not found\n"));
  2362. return ERROR_INVALID_DATA;
  2363. found:
  2364. DPrintf((DebugBuf, "IAT offset: @%#08lx ==> @%#08lx\n",
  2365. offiat - pagedelta,
  2366. offiat));
  2367. MuMoveFilePos(inpfh, offiat - pagedelta);
  2368. MuMoveFilePos(outfh, offiat);
  2369. for (;;) {
  2370. MuRead(inpfh, (PUCHAR) &iat, sizeof(iat));
  2371. if (iat == 0) {
  2372. break;
  2373. }
  2374. if ((iat & IMAGE_ORDINAL_FLAG) == 0) { // if import by name
  2375. DPrintf((DebugBuf, "Patching IAT: %08lx + %04lx ==> %08lx\n",
  2376. iat,
  2377. hdrdelta,
  2378. iat + hdrdelta));
  2379. iat += hdrdelta;
  2380. cimp++;
  2381. }
  2382. MuWrite(outfh, (PUCHAR) &iat, sizeof(iat)); // Avoids seeking
  2383. }
  2384. }
  2385. DPrintf((DebugBuf, "%u import module name RVAs patched\n", cmod));
  2386. DPrintf((DebugBuf, "%u IAT name RVAs patched\n", cimp));
  2387. if (cmod == 0)
  2388. {
  2389. DPrintf((DebugBuf, "No import modules to patch\n"));
  2390. }
  2391. if (cimp == 0)
  2392. {
  2393. DPrintf((DebugBuf, "No import name RVAs to patch\n"));
  2394. }
  2395. }
  2396. return NO_ERROR;
  2397. }
  2398. /*---------------------------------------------------------------------------*/
  2399. /* */
  2400. /* WriteResFile() - */
  2401. /* */
  2402. /*---------------------------------------------------------------------------*/
  2403. LONG
  2404. WriteResFile(
  2405. HANDLE hUpdate,
  2406. CHAR *pDstname)
  2407. {
  2408. HANDLE inh;
  2409. HANDLE outh;
  2410. INT inpfh;
  2411. INT outfh;
  2412. ULONG onewexe;
  2413. IMAGE_DOS_HEADER oldexe;
  2414. PUPDATEDATA pUpdate;
  2415. INT rc;
  2416. CHAR *pFilename;
  2417. pUpdate = (PUPDATEDATA)GlobalLock(hUpdate);
  2418. pFilename = (CHAR*)GlobalLock(pUpdate->hFileName);
  2419. /* open the original exe file */
  2420. inh = CreateFile(pFilename, GENERIC_READ, 0 /*exclusive access*/, NULL /* security attr */, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  2421. GlobalUnlock(pUpdate->hFileName);
  2422. if ( inh == INVALID_HANDLE_VALUE ) {
  2423. GlobalUnlock(hUpdate);
  2424. return ERROR_OPEN_FAILED;
  2425. }
  2426. inpfh = (INT)HandleToLong(inh);
  2427. /* read the old format EXE header */
  2428. rc = _lread(inpfh, (char*)&oldexe, sizeof(oldexe));
  2429. if (rc != sizeof(oldexe)) {
  2430. _lclose(inpfh);
  2431. GlobalUnlock(hUpdate);
  2432. return ERROR_READ_FAULT;
  2433. }
  2434. /* make sure its really an EXE file */
  2435. if (oldexe.e_magic != IMAGE_DOS_SIGNATURE) {
  2436. _lclose(inpfh);
  2437. GlobalUnlock(hUpdate);
  2438. return ERROR_INVALID_EXE_SIGNATURE;
  2439. }
  2440. /* make sure theres a new EXE header floating around somewhere */
  2441. if (!(onewexe = oldexe.e_lfanew)) {
  2442. _lclose(inpfh);
  2443. GlobalUnlock(hUpdate);
  2444. return ERROR_BAD_EXE_FORMAT;
  2445. }
  2446. outh = CreateFile(pDstname, GENERIC_READ|GENERIC_WRITE, 0 /*exclusive access*/, NULL /* security attr */, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  2447. if ( outh != INVALID_HANDLE_VALUE ) {
  2448. outfh = (INT)HandleToLong( outh );
  2449. rc = PEWriteResFile(inpfh, outfh, onewexe, pUpdate);
  2450. _lclose(outfh);
  2451. }
  2452. _lclose(inpfh);
  2453. GlobalUnlock(hUpdate);
  2454. return rc;
  2455. }