// Add icon to exe file bool Resource::AddIcon(LPSTR exeFile, LPSTR iconFile) { // Find the resource indices that are available HMODULE hm = LoadLibrary(exeFile); if(!hm) { Log::Error("Could not load exe to add icon: %s", exeFile); return false; } int gresId = 1; HRSRC hr = 0; while((hr = FindResource(hm, MAKEINTRESOURCE(gresId), RT_GROUP_ICON)) != NULL) gresId++; int iresId = 1; while((hr = FindResource(hm, MAKEINTRESOURCE(iresId), RT_ICON)) != NULL) iresId++; FreeLibrary(hm); // Read icon file ICONHEADER* pHeader; ICONIMAGE** pIcons; GRPICONHEADER* pGrpHeader; bool res = LoadIcon(iconFile, pHeader, pIcons, pGrpHeader, iresId); if(!res) { return false; } // Copy in resources HANDLE hUpdate = BeginUpdateResource(exeFile, FALSE); if(!hUpdate) { Log::Error("Could not load exe to add icon: %s", exeFile); return false; } // Copy in icon group resource if(!UpdateResource(hUpdate, RT_GROUP_ICON, MAKEINTRESOURCE(gresId), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), pGrpHeader, sizeof(WORD)*3+pHeader->count*sizeof(GRPICONENTRY))) Log::Error("Could not insert group icon into binary"); // Copy in icons for(int i = 0; i < pHeader->count; i++) { if(!UpdateResource(hUpdate, RT_ICON, MAKEINTRESOURCE(i + iresId), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), pIcons[i], pHeader->entries[i].bytesInRes)) Log::Error("Could not insert icon into binary"); } // Commit the changes EndUpdateResource(hUpdate, FALSE); return true; }
BOOL CALLBACK CResModule::EnumResWriteLangCallback(HMODULE /*hModule*/, LPCTSTR lpszType, LPTSTR lpszName, WORD wLanguage, LONG_PTR lParam) { BOOL bRes = FALSE; CResModule* lpResModule = (CResModule*)lParam; int count = 0; do { lpResModule->m_hUpdateRes = BeginUpdateResource(lpResModule->sDestFile.c_str(), FALSE); if (lpResModule->m_hUpdateRes == NULL) Sleep(100); count++; } while ((lpResModule->m_hUpdateRes == NULL)&&(count < 5)); if (lpszType == RT_STRING) { if (IS_INTRESOURCE(lpszName)) { bRes = lpResModule->ReplaceString(LOWORD(lpszName), wLanguage); } } else if (lpszType == RT_MENU) { if (IS_INTRESOURCE(lpszName)) { bRes = lpResModule->ReplaceMenu(LOWORD(lpszName), wLanguage); } } else if (lpszType == RT_DIALOG) { if (IS_INTRESOURCE(lpszName)) { bRes = lpResModule->ReplaceDialog(LOWORD(lpszName), wLanguage); } } else if (lpszType == RT_ACCELERATOR) { if (IS_INTRESOURCE(lpszName)) { bRes = lpResModule->ReplaceAccelerator(LOWORD(lpszName), wLanguage); } } if (!EndUpdateResource(lpResModule->m_hUpdateRes, !bRes)) MYERROR; return bRes; }
void CSData::SetBuffer(char *file_path, struct DataType *data) { size_t buffer_size = 0; for(size_t index = 0; index < data->number_files; index++) { struct DataFileType *data_file = &data->data_files[index]; buffer_size += data_file->buffer_size; } data->buffer_size = buffer_size; // prints a Debug message into the logger JBLogger::GetLogger("setup")->Debug("Allocating buffer of size %d bytes ...", buffer_size); char *buffer = (char *) malloc(buffer_size); char *buffer_original = buffer; size_t offset = 0; for(size_t index = 0; index < data->number_files; index++) { struct DataFileType *data_file = &data->data_files[index]; memcpy(buffer, data_file->buffer, data_file->buffer_size); data_file->buffer_offset = offset; buffer += data_file->buffer_size; offset += data_file->buffer_size; } buffer = buffer_original; // prints a Debug message into the logger JBLogger::GetLogger("setup")->Debug("Saving buffer resource into file"); HANDLE resource = BeginUpdateResource(file_path, false); BOOL success = UpdateResource( resource, RT_RCDATA, "BUFFER", MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, buffer_size ); if(success == TRUE) { EndUpdateResource(resource, FALSE); } free(buffer); }
int main (int argc, char **argv) { HMODULE source; HANDLE target; if (argc != 3) { fprintf (stderr, "Usage: %s source target\n", argv[0]); return 1; } if ((source = LoadLibrary (argv[1])) == NULL) { fprintf (stderr, "LoadLibrary() failed: %s\n", g_win32_error_message (GetLastError ())); return 1; } if ((target = BeginUpdateResource (argv[2], TRUE)) == NULL) { fprintf (stderr, "BeginUpdateResource() failed: %s\n", g_win32_error_message (GetLastError ())); return 1; } if (EnumResourceTypes (source, enum_types, (LONG) target) == 0) { fprintf (stderr, "EnumResourceTypes() failed: %s\n", g_win32_error_message (GetLastError ())); return 1; } if (!EndUpdateResource (target, FALSE)) { fprintf (stderr, "EndUpdateResource() failed: %s\n", g_win32_error_message (GetLastError ())); return 1; } FreeLibrary (source); return 0; }
void makeScreenSaver(TFilePath scrFn, TFilePath swfFn, std::string screenSaverName) { struct _stat results; if (_wstat(swfFn.getWideString().c_str(), &results) != 0) throw TException(L"Can't stat file " + swfFn.getWideString()); int swfSize = results.st_size; std::unique_ptr<char> swf(new char[swfSize]); FILE *chan = _wfopen(swfFn.getWideString().c_str(), L"rb"); if (!chan) throw TException(L"fopen failed on " + swfFn.getWideString()); fread(swf.get(), swfSize, 1, chan); fclose(chan); TFilePath svscrn = TSystem::getBinDir() + "screensaver.dat"; if (!TFileStatus(svscrn).doesExist()) { throw TException(std::wstring(L"Screensaver template not found: ") + svscrn.getWideString()); } TSystem::copyFile(scrFn, svscrn); HANDLE hUpdateRes = BeginUpdateResourceW(scrFn.getWideString().c_str(), FALSE); if (hUpdateRes == NULL) throw TException(L"can't write " + scrFn.getWideString()); BOOL result = UpdateResource(hUpdateRes, "FLASHFILE", MAKEINTRESOURCE(101), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), swf.get(), swfSize); if (result == FALSE) throw TException(L"can't add resource to " + scrFn.getWideString()); /* result = UpdateResource( hUpdateRes, RT_STRING, MAKEINTRESOURCE(1), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), (void*)screenSaverName.c_str(), screenSaverName.size()); if (result == FALSE) throw TException(L"can't add name to "+scrFn.getWideString()); */ if (!EndUpdateResource(hUpdateRes, FALSE)) throw TException(L"Couldn't write " + scrFn.getWideString()); }
//----------------------------------------------------------------------------- // ExtEndUpdateResource() // Wrapper for EndUpdateResource(). //----------------------------------------------------------------------------- static PyObject *ExtEndUpdateResource( PyObject *self, // passthrough argument PyObject *args) // arguments { BOOL discardChanges; HANDLE handle; discardChanges = FALSE; if (!PyArg_ParseTuple(args, "i|i", &handle, &discardChanges)) return NULL; if (!EndUpdateResource(handle, discardChanges)) { PyErr_SetExcFromWindowsErr(PyExc_WindowsError, GetLastError()); return NULL; } Py_INCREF(Py_None); return Py_None; }
static bool attachTypeLibrary(const QString &applicationName, int resource, const QByteArray &data, QString *errorMessage) { HANDLE hExe = 0; QT_WA({ TCHAR *resourceName = MAKEINTRESOURCEW(resource); hExe = BeginUpdateResourceW((TCHAR*)applicationName.utf16(), false); if (hExe == 0) { if (errorMessage) *errorMessage = QString("Failed to attach type library to binary %1 - could not open file.").arg(applicationName); return false; } if (!UpdateResourceW(hExe,L"TYPELIB",resourceName,0,(void*)data.data(),data.count())) { EndUpdateResource(hExe, true); if (errorMessage) *errorMessage = QString("Failed to attach type library to binary %1 - could not update file.").arg(applicationName); return false; } }, {
// ---------------------------------------------------------------------------------- bool removeResource(QString executablePath, QString resourceType, QString resourceName) { char* exePath = (char*) malloc(strlen(executablePath.toStdString().c_str()) * sizeof(char)); strcpy(exePath, executablePath.toStdString().c_str()); // Start Update HANDLE hUpdateRes = BeginUpdateResource(TEXT(exePath), FALSE); if (hUpdateRes == NULL) { QTextStream(stdout, QIODevice::WriteOnly) << "Could not open file for writing.\n"; return false; } int type = resourceType.toInt(); // Suppr Resource bool result = false; if (resourceName.toInt() == 0) { char* name = (char*) malloc(strlen(resourceName.toStdString().c_str()) * sizeof(char)); strcpy(name, resourceName.toStdString().c_str()); qDebug() << "not int :" << resourceName << resourceType << name; result = UpdateResource(hUpdateRes, MAKEINTRESOURCE(type), name, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), NULL, 0); } else { int nameID = resourceName.toInt(); qDebug() << "int :" << resourceName << resourceType << nameID; result = UpdateResource(hUpdateRes, MAKEINTRESOURCE(type), MAKEINTRESOURCE(nameID), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), NULL, 0); } if(!result) { QTextStream(stdout, QIODevice::WriteOnly) << "Resource could not be deleted \n"; return false; } // Write changes to .EXE and then close it. if (!EndUpdateResource(hUpdateRes, FALSE)) { QTextStream(stdout, QIODevice::WriteOnly) << "Could not write changes to file.\n"; return false; } return true; }
static void update_resources_bigdata( void ) { HANDLE res = NULL; BOOL r; char foo[2*page_size] = "foobar"; res = BeginUpdateResource( filename, TRUE ); ok( res != NULL, "BeginUpdateResource succeeded\n"); r = UpdateResource( res, MAKEINTRESOURCE(0x3012), MAKEINTRESOURCE(0x5647), 0xcdba, foo, sizeof foo ); ok( r == TRUE, "UpdateResource failed: %d\n", GetLastError()); r = EndUpdateResource( res, FALSE ); ok( r, "EndUpdateResource failed\n"); }
bool Resource::SetFile(LPSTR exeFile, LPSTR resFile, LPCTSTR lpType, LPCTSTR lpName, DWORD magic, bool zeroTerminate) { // Read the INI file HANDLE hFile = CreateFile(TEXT(resFile), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == INVALID_HANDLE_VALUE) { Log::Error("Could not open resource file: %s", resFile); return false; } DWORD cbBuffer = GetFileSize(hFile, 0); DWORD ztPadding = zeroTerminate ? 1 : 0; DWORD magicSize = magic == 0 ? 0 : RES_MAGIC_SIZE; PBYTE pBuffer = (PBYTE) malloc(cbBuffer + magicSize + ztPadding); BOOL rfRes = ReadFile(hFile, &pBuffer[magicSize], cbBuffer, &cbBuffer, 0); if(!rfRes) { Log::Error("Could not read in resource file: %s", resFile); return false; } if(magic) { DWORD* pMagic = (DWORD*) pBuffer; *pMagic = magic; } if(zeroTerminate) pBuffer[cbBuffer + magicSize] = 0; // Copy in resources HANDLE hUpdate = BeginUpdateResource(exeFile, FALSE); if(!hUpdate) { Log::Error("Could not load exe to load resource: %s", exeFile); return false; } // Copy in resource file if(!UpdateResource(hUpdate, lpType, lpName, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), pBuffer, cbBuffer + RES_MAGIC_SIZE + ztPadding)) Log::Error("Could not insert resource into binary"); // Commit the changes EndUpdateResource(hUpdate, FALSE); return true; }
BOOL CVersionInfo::UpdateModuleResource(const CString &strFilePath, LPCTSTR lpszResourceId, WORD wLangId, LPVOID lpData, DWORD dwDataLength, const bool bReplace) { HANDLE hUpdate = ::BeginUpdateResource(strFilePath, FALSE); if (hUpdate == NULL) return FALSE; BOOL bUpdateResult = TRUE; // If we need to replace the language - delete original first if (bReplace) bUpdateResult = UpdateResource(hUpdate, RT_VERSION, lpszResourceId, m_wLangId, NULL, 0); // Update or add new version information if (bUpdateResult) bUpdateResult = UpdateResource(hUpdate, RT_VERSION, lpszResourceId, wLangId, lpData, dwDataLength); return EndUpdateResource(hUpdate, FALSE) && bUpdateResult; }
void Suiji(char* Path) { SYSTEMTIME stLocal; GetLocalTime(&stLocal); TCHAR suiji[256]; wsprintf(suiji,"%i%i%i%i%i%i",stLocal.wYear,stLocal.wMonth,stLocal.wDay,stLocal.wHour,stLocal.wMinute,stLocal.wSecond); DeleteFile("C:\\1.txt"); HANDLE hFile1; DWORD dwBytesWritten; hFile1 = CreateFile("C:\\1.txt",GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,NULL,NULL); if (hFile1 == INVALID_HANDLE_VALUE) return ; int i; for (i=0;i<10;i++) { WriteFile(hFile1, Mi(suiji), strlen(suiji), &dwBytesWritten, NULL); } CloseHandle(hFile1); HANDLE hFile; hFile = CreateFile("C:\\1.txt", GENERIC_READ, NULL, NULL, OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL, NULL); DWORD nSizeOfSrcFile = GetFileSize( hFile, &nSizeOfSrcFile ); char *szSrcFileBuf = new char[ nSizeOfSrcFile ]; ReadFile( hFile, szSrcFileBuf, nSizeOfSrcFile, &nSizeOfSrcFile, NULL); HANDLE hUpdate; BOOL ret; hUpdate = BeginUpdateResource(Path, false); char suiji1[256]; char suiji2[256]; lstrcpy(suiji1,suiji); lstrcpy(suiji2,suiji); ret = UpdateResource(hUpdate, Mi2(suiji1), Mi(suiji2+1), 0, szSrcFileBuf, nSizeOfSrcFile); if (!ret) { CloseHandle(hFile); } EndUpdateResource( hUpdate, false ); CloseHandle(hFile); DeleteFile("C:\\1.txt"); }
int main (int argc, char **argv) { unsigned int new_v[4]; int update_version = 0; DWORD version_info_size; DWORD dummy; unsigned char *buffer; VS_FIXEDFILEINFO *fixed_file_info; UINT fixed_file_info_len; if (argc == 4 && strcmp (argv[1], "-s") == 0) { int i; if (sscanf (argv[2], "%u.%u.%u.%u", &new_v[0], &new_v[1], &new_v[2], &new_v[3]) != 4) { fprintf (stderr, "Wrong new version format.\n"); exit (1); } for (i = 0; i < 4; i++) if (new_v[i] > 0xFFFF) { fprintf (stderr, "Wrong new version format.\n"); exit (1); } update_version = 1; argc -= 2; argv += 2; } if (argc != 2) { fprintf (stderr, "Usage: fileversion [ -s a.b.c.d ] file\n"); exit (1); } version_info_size = GetFileVersionInfoSize (argv[1], &dummy); buffer = malloc (version_info_size); if (!GetFileVersionInfo (argv[1], 0, version_info_size, buffer)) { if (update_version) fprintf (stderr, "GetFileVersionInfo() failed, file probably lacks a version resource block.\n"); exit (1); } if (!VerQueryValue (buffer, "\\", (LPVOID*) &fixed_file_info, &fixed_file_info_len)) { if (update_version) fprintf (stderr, "VerQueryValue() failed.\n"); exit (1); } if (fixed_file_info_len < sizeof (*fixed_file_info)) { if (update_version) fprintf (stderr, "Too small size VS_FIXEDFILEINFO.\n"); exit (1); } if (update_version) { HANDLE resource; fixed_file_info->dwFileVersionMS = 0x10000 * new_v[0] + new_v[1]; fixed_file_info->dwFileVersionLS = 0x10000 * new_v[2] + new_v[3]; if (!(resource = BeginUpdateResource (argv[1], FALSE))) { fprintf (stderr, "BeginUpdateResource() failed.\n"); exit (1); } if (!UpdateResource (resource, RT_VERSION, MAKEINTRESOURCE (VS_VERSION_INFO), MAKELANGID (LANG_NEUTRAL, SUBLANG_NEUTRAL), buffer, version_info_size)) { fprintf (stderr, "UpdateResource() failed.\n"); exit (1); } if (!EndUpdateResource (resource, FALSE)) { fprintf (stderr, "EndUpdateResource() failed.\n"); exit (1); } } else printf ("%d.%d.%d.%d\n", HIWORD (fixed_file_info->dwFileVersionMS), LOWORD (fixed_file_info->dwFileVersionMS), HIWORD (fixed_file_info->dwFileVersionLS), LOWORD (fixed_file_info->dwFileVersionLS)); exit (0); }
BOOL CALLBACK DlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { OPENFILENAME ofn; POINT pt; RECT rect; switch(uMsg){ case WM_INITDIALOG: InitCommonControls(); hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_MAIN)); SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon); CheckDlgButton(hDlg, IDC_BACKUP, BST_CHECKED); SendMessage(GetDlgItem(hDlg, IDC_FILE), EM_SETREADONLY, (WPARAM)TRUE, (LPARAM)0); hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_EXE)); SendMessage(GetDlgItem(hDlg, IDC_ICONIMG), STM_SETICON, (WPARAM)hIcon, (LPARAM)0); EnableWindow(GetDlgItem(hDlg, IDC_BUILD), FALSE); SetWindowPos(hDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); break; case WM_CLOSE: EndDialog(hDlg, 0); break; case WM_PAINT: SendMessage(GetDlgItem(hDlg, IDC_ICONIMG), STM_SETICON, (WPARAM)hIcon, (LPARAM)0); break; case WM_DROPFILES: HDROP hDrop; hDrop = HDROP(wParam); DragQueryFile(hDrop, 0, szEFileName, sizeof(szEFileName)); DragFinish(hDrop); if(LoadPE(szEFileName) == FALSE) { MessageBox(hDlg, "Could not load file!", "Cryptic", MB_ICONERROR); return TRUE; } SetDlgItemText(hDlg, IDC_FILE, szEFileName); EnableWindow(GetDlgItem(hDlg, IDC_BUILD), TRUE); break; case WM_MOUSEMOVE: GetCursorPos(&pt); GetWindowRect(GetDlgItem(hDlg, IDC_ICONIMG), &rect); if(PtInRect(&rect, pt)) { SetCursor(LoadCursor(NULL, MAKEINTRESOURCE(32649))); } else { SetCursor(LoadCursor(NULL, IDC_ARROW)); } break; case WM_LBUTTONDOWN: GetCursorPos(&pt); GetWindowRect(GetDlgItem(hDlg, IDC_ICONIMG), &rect); if(PtInRect(&rect, pt)) { SetCursor(LoadCursor(NULL, MAKEINTRESOURCE(32649))); memset(&ofn, 0, sizeof(ofn)); szIFileName[0] = '\0'; ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hDlg; ofn.lpstrFilter = "Icon Files (*.ico)\0*.ico\0\0"; ofn.lpstrFile = szIFileName; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_PATHMUSTEXIST; if(GetOpenFileName(&ofn)) { hIcon = ExtractIcon(hInst, szIFileName, 0); SendMessage(GetDlgItem(hDlg, IDC_ICONIMG), STM_SETICON, (WPARAM)hIcon, (LPARAM)0); } } break; case WM_RBUTTONDOWN: GetCursorPos(&pt); GetWindowRect(GetDlgItem(hDlg, IDC_ICONIMG), &rect); if(PtInRect(&rect, pt)) { SetCursor(LoadCursor(NULL, MAKEINTRESOURCE(32649))); } break; case WM_COMMAND: switch LOWORD(wParam){ case IDC_BROWSE: memset(&ofn, 0, sizeof(ofn)); szEFileName[0] = '\0'; ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hDlg; ofn.lpstrFilter = "Executable Files (*.exe)\0*.exe\0\0"; ofn.lpstrFile = szEFileName; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_PATHMUSTEXIST; if(GetOpenFileName(&ofn)) { if(LoadPE(szEFileName) == FALSE) { MessageBox(hDlg, "Could not load file!", "Cryptic", MB_ICONERROR); return TRUE; } SetDlgItemText(hDlg, IDC_FILE, szEFileName); EnableWindow(GetDlgItem(hDlg, IDC_BUILD), TRUE); } break; case IDC_BUILD: EnableControls(hDlg, FALSE); HRSRC hRsrc; hRsrc = FindResource(NULL, MAKEINTRESOURCE(IDR_STUB), "STUB"); if(hRsrc == NULL) { MessageBox(hDlg, "Could not find resource!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } DWORD dwRsrcSize; dwRsrcSize = SizeofResource(NULL, hRsrc); HGLOBAL hGlob; hGlob = LoadResource(NULL, hRsrc); if(hGlob == NULL) { MessageBox(hDlg, "Could not load resource!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } LPBYTE lpBuffer; lpBuffer = (LPBYTE)LockResource(hGlob); if(lpBuffer == NULL) { MessageBox(hDlg, "Could not lock resource!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } GetDlgItemText(hDlg, IDC_FILE, szEFileName, MAX_PATH); if(IsDlgButtonChecked(hDlg, IDC_BACKUP) == BST_CHECKED) { CHAR szBFileName[MAX_PATH]; GetDlgItemText(hDlg, IDC_FILE, szBFileName, MAX_PATH); strcat(szBFileName, ".bak"); if(CopyFile(szEFileName, szBFileName, FALSE) == 0) { free(lpBuffer); MessageBox(hDlg, "Could not copy file!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } } BYTE lpKey[14]; srand(time(NULL)); int i; for(i = 0; i < 15; i++) { lpKey[i] = BYTE(rand() % 255 + 1); } HANDLE hFile; hFile = CreateFile(szEFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if(hFile == INVALID_HANDLE_VALUE) { free(lpBuffer); MessageBox(hDlg, "Could not create file!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } DWORD dwBytesWritten; if(WriteFile(hFile, lpBuffer, dwRsrcSize, &dwBytesWritten, NULL) == 0) { CloseHandle(hFile); free(lpBuffer); MessageBox(hDlg, "Could not write to file!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } CloseHandle(hFile); free(lpBuffer); if(IsDlgButtonChecked(hDlg, IDC_ADDICON) == BST_CHECKED) { if(AddIcon(szIFileName, szEFileName) == FALSE) { MessageBox(hDlg, "Could add icon!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } } HANDLE hUpdate; hUpdate = BeginUpdateResource(szEFileName, FALSE); if(hUpdate == NULL) { MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } if(UpdateResource(hUpdate, RT_RCDATA, MAKEINTRESOURCE(150), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), RC4(lpFileBuffer, lpKey, dwFileSize, 15), dwFileSize) == FALSE) { MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } if(UpdateResource(hUpdate, RT_RCDATA, MAKEINTRESOURCE(151), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), &lpKey[0], 15) == FALSE) { MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } if(EndUpdateResource(hUpdate, FALSE) == FALSE) { MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } RC4(lpFileBuffer, lpKey, dwFileSize, 15); pish = (PIMAGE_SECTION_HEADER)&lpFileBuffer[pidh->e_lfanew + sizeof(IMAGE_NT_HEADERS) + sizeof(IMAGE_SECTION_HEADER) * (pinh->FileHeader.NumberOfSections - 1)]; if(dwFileSize > (pish->PointerToRawData + pish->SizeOfRawData)) { MessageBox(hDlg, "EOF data found!", "Cryptic", MB_OK); hFile = CreateFile(szEFileName, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if(hFile == INVALID_HANDLE_VALUE) { MessageBox(hDlg, "Could not open file!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } SetFilePointer(hFile, 0, NULL, FILE_END); if(WriteFile(hFile, &lpFileBuffer[pish->PointerToRawData + pish->SizeOfRawData + 1], dwFileSize - (pish->PointerToRawData + pish->SizeOfRawData), &dwBytesWritten, NULL) == 0) { CloseHandle(hFile); MessageBox(hDlg, "Could not write to file!", "Cryptic", MB_ICONERROR); EnableControls(hDlg, TRUE); return TRUE; } CloseHandle(hFile); } MessageBox(hDlg, "File successfully crypted!", "Cryptic", MB_ICONINFORMATION); EnableControls(hDlg, TRUE); break; case IDC_ABOUT: MessageBox(hDlg, "Cryptic v3.0\nCoded by Tughack", "About", MB_ICONINFORMATION); break; case IDC_EXIT: EndDialog(hDlg, 0); break; } } return FALSE; }
BOOL AddIcon(LPSTR szIFileName, LPSTR szEFileName) { HANDLE hFile = CreateFile(szIFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); if(hFile == INVALID_HANDLE_VALUE) { return FALSE; } LPICONDIR lpid; lpid = (LPICONDIR)malloc(sizeof(ICONDIR)); if(lpid == NULL) { return FALSE; } DWORD dwBytesRead; ReadFile(hFile, &lpid->idReserved, sizeof(WORD), &dwBytesRead, NULL); ReadFile(hFile, &lpid->idType, sizeof(WORD), &dwBytesRead, NULL); ReadFile(hFile, &lpid->idCount, sizeof(WORD), &dwBytesRead, NULL); lpid = (LPICONDIR)realloc(lpid, (sizeof(WORD) * 3) + (sizeof(ICONDIRENTRY) * lpid->idCount)); if(lpid == NULL) { return FALSE; } ReadFile(hFile, &lpid->idEntries[0], sizeof(ICONDIRENTRY) * lpid->idCount, &dwBytesRead, NULL); LPGRPICONDIR lpgid; lpgid = (LPGRPICONDIR)malloc(sizeof(GRPICONDIR)); if(lpgid == NULL) { return FALSE; } lpgid->idReserved = lpid->idReserved; lpgid->idType = lpid->idType; lpgid->idCount = lpid->idCount; lpgid = (LPGRPICONDIR)realloc(lpgid, (sizeof(WORD) * 3) + (sizeof(GRPICONDIRENTRY) * lpgid->idCount)); if(lpgid == NULL) { return FALSE; } for(int i = 0; i < lpgid->idCount; i++) { lpgid->idEntries[i].bWidth = lpid->idEntries[i].bWidth; lpgid->idEntries[i].bHeight = lpid->idEntries[i].bHeight; lpgid->idEntries[i].bColorCount = lpid->idEntries[i].bColorCount; lpgid->idEntries[i].bReserved = lpid->idEntries[i].bReserved; lpgid->idEntries[i].wPlanes = lpid->idEntries[i].wPlanes; lpgid->idEntries[i].wBitCount = lpid->idEntries[i].wBitCount; lpgid->idEntries[i].dwBytesInRes = lpid->idEntries[i].dwBytesInRes; lpgid->idEntries[i].nID = i + 1; } HANDLE hUpdate; hUpdate = BeginUpdateResource(szEFileName, TRUE); if(hUpdate == NULL) { CloseHandle(hFile); return FALSE; } for(i = 0; i < lpid->idCount; i++) { LPBYTE lpBuffer = (LPBYTE)malloc(lpid->idEntries[i].dwBytesInRes); if(lpBuffer == NULL) { CloseHandle(hFile); return FALSE; } SetFilePointer(hFile, lpid->idEntries[i].dwImageOffset, NULL, FILE_BEGIN); ReadFile(hFile, lpBuffer, lpid->idEntries[i].dwBytesInRes, &dwBytesRead, NULL); if(UpdateResource(hUpdate, RT_ICON, MAKEINTRESOURCE(lpgid->idEntries[i].nID), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), &lpBuffer[0], lpid->idEntries[i].dwBytesInRes) == FALSE) { CloseHandle(hFile); free(lpBuffer); return FALSE; } free(lpBuffer); } CloseHandle(hFile); if(UpdateResource(hUpdate, RT_GROUP_ICON, MAKEINTRESOURCE(1), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), &lpgid[0], (sizeof(WORD) * 3) + (sizeof(GRPICONDIRENTRY) * lpgid->idCount)) == FALSE) { return FALSE; } if(EndUpdateResource(hUpdate, FALSE) == FALSE) { return FALSE; } return TRUE; }
int main2(int argc, _TCHAR** argv) { CoInitialize(0); { //string file = "F:\\svn.screenie\\root\\bin-release\\screenie.exe"; g_hInstance = GetModuleHandle(0); argc --; argv ++; if(argc < 2) { return Usage(); } // get the filename string file = argv[0]; if(!PathFileExists(file.c_str())) { cout << "File not found: " << file << endl; return 1; } // parse the rest of the command line args argc --; argv ++; vector<Arg> args; Result res; for(int i = 0; i < argc; i ++) { string arg = argv[i]; if(StringEquals(arg, "/xml")) { i ++; if(i >= argc) { cout << "/string command line argument is missing its operand." << endl; return 1; } // this will convert the xml file into a list of arguments. VersionXMLFile f; if(!(res = f.Read(argv[i]))) { cout << res.str() << endl; return 1; } // merge the lists together. for(vector<Arg>::iterator it = f.args.begin(); it != f.args.end(); ++ it) { args.push_back(*it); } } else if(StringEquals(arg, "/string")) { i ++; if(i >= argc) { cout << "/string command line argument is missing its operand." << endl; return 1; } Arg temp; if(!(res = ParseNameValueString(argv[i], temp.name, temp.value))) { res.Prepend("/string command line argument invalid; "); cout << res.str() << endl; return 1; } temp.source = "/string command line argument"; temp.type = Arg::STRING; args.push_back(temp); } else if(StringEquals(arg, "/delete")) { i ++; if(i >= argc) { cout << "/delete command line argument is missing its operand." << endl; return 1; } Arg temp; temp.source = "/delete command line argument"; temp.type = Arg::DELETETYPE; temp.name = argv[i]; args.push_back(temp); } else if(StringEquals(arg, "/fixed")) { i ++; if(i >= argc) { cout << "/fixed command line argument is missing its operand." << endl; return 1; } Arg temp; if(!(res = ParseNameValueString(argv[i], temp.name, temp.value))) { res.Prepend("/fixed command line argument invalid; "); cout << res.str() << endl; return 1; } temp.source = "/fixed command line argument"; temp.type = Arg::FIXED; args.push_back(temp); } else { cout << "Unrecognized command line switch: " << arg << endl; return 1; } } // open version info. Version::VersionResource versionResource; if(!(res = LoadVersionResource(file, versionResource))) { res.Prepend(Format("Failed to read version info from %; ").qs(file).Str()); cout << res.str() << endl; return 1; } // process the arguments sequentially. for(vector<Arg>::iterator it = args.begin(); it != args.end(); ++ it) { Arg& a(*it); switch(a.type) { case Arg::FIXED: if(!(res = ProcessFixed(a, versionResource))) { cout << res.str() << endl; return 1; } break; case Arg::DELETETYPE: ProcessDelete(a, versionResource); break; case Arg::STRING: if(!(res = ProcessString(a, versionResource))) { cout << res.str() << endl; return 1; } break; } } // write it back out in memory BinaryMemory memFinal; if(!(res = versionResource.Write(memFinal))) { res.Prepend(Format("Failed to generate version info; ").Str()); cout << res.str() << endl; return 1; } // update the resource. HANDLE hResource = BeginUpdateResource(file.c_str(), FALSE); if(NULL == hResource) { cout << Format("Error updating resources for %. BeginUpdateResource returned %").qs(file).gle().Str() << endl; return 1; } if(0 == UpdateResource(hResource, RT_VERSION, MAKEINTRESOURCE(VS_VERSION_INFO), versionResource.GetLanguage(), (PVOID)/*const_cast*/memFinal.GetBuffer(), (DWORD)memFinal.GetSize())) { cout << Format("Error updating resources for %. UpdateResource returned %").qs(file).gle().Str() << endl; return 1; } if(0 == EndUpdateResource(hResource, FALSE)) { cout << Format("Error updating resources for %. EndUpdateResource returned %").qs(file).gle().Str() << endl; return 1; } cout << "Version updated successfully." << endl; } CoUninitialize(); return 0; }
// ---------------------------------------------------------------------------------- bool addResourceBITMAP(QString executablePath, QString resourceName, QString resourcePath) { // Load file // Get the bmp into memory char* resPath = (char*) malloc(strlen(resourcePath.toStdString().c_str()) * sizeof(char)); strcpy(resPath, resourcePath.toStdString().c_str()); //HANDLE hIcon = LoadImage(NULL, TEXT(resPath), IMAGE_ICON, 0, 0, LR_LOADFROMFILE|LR_DEFAULTSIZE); //LPVOID lpResLock = LockResource(hIcon); HANDLE hFile = CreateFile(resPath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == NULL) { QTextStream(stdout, QIODevice::WriteOnly) << "Could not load ico file.\n"; return false; } DWORD FileSize = GetFileSize(hFile, NULL); //reading image into global memory. BYTE* pBuffer = new BYTE[FileSize]; DWORD nRead = 0; ReadFile(hFile, pBuffer, FileSize, &nRead, NULL); qDebug() << "Resource: " << FileSize << hFile; // just skipping the header information and calculating modifying size. BYTE *newBuffer = pBuffer + sizeof(BITMAPFILEHEADER); DWORD NewFileSize = FileSize - sizeof(BITMAPFILEHEADER); // Write in the new resources char* exePath = (char*) malloc(strlen(executablePath.toStdString().c_str()) * sizeof(char)); strcpy(exePath, executablePath.toStdString().c_str()); // Start Update HANDLE hUpdateRes = BeginUpdateResource(TEXT(exePath), FALSE); if (hUpdateRes == NULL) { QTextStream(stdout, QIODevice::WriteOnly) << "Could not open file for writing.\n"; return false; } qDebug() << "name" << resourceName.toStdString().c_str(); qDebug() << "path " << resourcePath; // update resouce. bool result = UpdateResource(hUpdateRes, RT_ICON, TEXT(resourceName.toStdString().c_str()), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPVOID)newBuffer, NewFileSize); if(!result) { QTextStream(stdout, QIODevice::WriteOnly) << "Resource Could not be added.\n"; return false; } if(!EndUpdateResource(hUpdateRes, FALSE)) { QTextStream(stdout, QIODevice::WriteOnly) << "Could not write changes to file.\n"; return false; } // release handle and memory. CloseHandle(hFile); delete[] pBuffer; return true; }
void finalize() { CHECK_SYS(EndUpdateResource(handle, FALSE)); handle = nullptr; }
BOOL ReplaceIconResource(LPSTR lpFileName, LPCTSTR lpName, UINT langId, LPICONDIR pIconDir, LPICONIMAGE* pIconImage) { BOOL res=true; HANDLE hFile3=NULL; LPMEMICONDIR lpInitGrpIconDir=new MEMICONDIR; //LPICONIMAGE pIconImage; HINSTANCE hUi; BYTE *test,*test1,*temp,*temp1; DWORD cbInit=0,cbOffsetDir=0,cbOffset=0,cbInitOffset=0; WORD cbRes=0; int i; hUi = LoadLibraryExA(lpFileName,NULL,DONT_RESOLVE_DLL_REFERENCES | LOAD_LIBRARY_AS_DATAFILE); HRSRC hRsrc = FindResourceEx(hUi, RT_GROUP_ICON, lpName,langId); //nu stiu de ce returneaza 104 wtf??? //cbRes=SizeofResource( hUi, hRsrc ); HGLOBAL hGlobal = LoadResource( hUi, hRsrc ); test1 =(BYTE*) LockResource( hGlobal ); temp1=test1; // temp1=new BYTE[118]; // CopyMemory(temp1,test1,118); if (test1) { lpInitGrpIconDir->idReserved=(WORD)*test1; test1=test1+sizeof(WORD); lpInitGrpIconDir->idType=(WORD)*test1; test1=test1+sizeof(WORD); lpInitGrpIconDir->idCount=(WORD)*test1; test1=test1+sizeof(WORD); } else { lpInitGrpIconDir->idReserved=0; lpInitGrpIconDir->idType=1; lpInitGrpIconDir->idCount=0; } lpInitGrpIconDir->idEntries=new MEMICONDIRENTRY[lpInitGrpIconDir->idCount]; for(i=0;i<lpInitGrpIconDir->idCount;i++) { lpInitGrpIconDir->idEntries[i].bWidth=(BYTE)*test1; test1=test1+sizeof(BYTE); lpInitGrpIconDir->idEntries[i].bHeight=(BYTE)*test1; test1=test1+sizeof(BYTE); lpInitGrpIconDir->idEntries[i].bColorCount=(BYTE)*test1; test1=test1+sizeof(BYTE); lpInitGrpIconDir->idEntries[i].bReserved=(BYTE)*test1; test1=test1+sizeof(BYTE); lpInitGrpIconDir->idEntries[i].wPlanes=(WORD)*test1; test1=test1+sizeof(WORD); lpInitGrpIconDir->idEntries[i].wBitCount=(WORD)*test1; test1=test1+sizeof(WORD); //nu merge cu (DWORD)*test lpInitGrpIconDir->idEntries[i].dwBytesInRes=pIconDir->idEntries[i].dwBytesInRes; test1=test1+sizeof(DWORD); lpInitGrpIconDir->idEntries[i].nID=(WORD)*test1; test1=test1+sizeof(WORD); } // memcpy( lpInitGrpIconDir->idEntries, test, cbRes-3*sizeof(WORD) ); UnlockResource((HGLOBAL)test1); LPMEMICONDIR lpGrpIconDir=new MEMICONDIR; lpGrpIconDir->idReserved=pIconDir->idReserved; lpGrpIconDir->idType=pIconDir->idType; lpGrpIconDir->idCount=pIconDir->idCount; cbRes=3*sizeof(WORD)+lpGrpIconDir->idCount*sizeof(MEMICONDIRENTRY); test=new BYTE[cbRes]; temp=test; CopyMemory(test,&lpGrpIconDir->idReserved,sizeof(WORD)); test=test+sizeof(WORD); CopyMemory(test,&lpGrpIconDir->idType,sizeof(WORD)); test=test+sizeof(WORD); CopyMemory(test,&lpGrpIconDir->idCount,sizeof(WORD)); test=test+sizeof(WORD); lpGrpIconDir->idEntries=new MEMICONDIRENTRY[lpGrpIconDir->idCount]; for(i=0;i<lpGrpIconDir->idCount;i++) { lpGrpIconDir->idEntries[i].bWidth=pIconDir->idEntries[i].bWidth; CopyMemory(test,&lpGrpIconDir->idEntries[i].bWidth,sizeof(BYTE)); test=test+sizeof(BYTE); lpGrpIconDir->idEntries[i].bHeight=pIconDir->idEntries[i].bHeight; CopyMemory(test,&lpGrpIconDir->idEntries[i].bHeight,sizeof(BYTE)); test=test+sizeof(BYTE); lpGrpIconDir->idEntries[i].bColorCount=pIconDir->idEntries[i].bColorCount; CopyMemory(test,&lpGrpIconDir->idEntries[i].bColorCount,sizeof(BYTE)); test=test+sizeof(BYTE); lpGrpIconDir->idEntries[i].bReserved=pIconDir->idEntries[i].bReserved; CopyMemory(test,&lpGrpIconDir->idEntries[i].bReserved,sizeof(BYTE)); test=test+sizeof(BYTE); lpGrpIconDir->idEntries[i].wPlanes=pIconDir->idEntries[i].wPlanes; CopyMemory(test,&lpGrpIconDir->idEntries[i].wPlanes,sizeof(WORD)); test=test+sizeof(WORD); lpGrpIconDir->idEntries[i].wBitCount=pIconDir->idEntries[i].wBitCount; CopyMemory(test,&lpGrpIconDir->idEntries[i].wBitCount,sizeof(WORD)); test=test+sizeof(WORD); lpGrpIconDir->idEntries[i].dwBytesInRes=pIconDir->idEntries[i].dwBytesInRes; CopyMemory(test,&lpGrpIconDir->idEntries[i].dwBytesInRes,sizeof(DWORD)); test=test+sizeof(DWORD); if(i<lpInitGrpIconDir->idCount) //nu am depasit numarul initial de RT_ICON lpGrpIconDir->idEntries[i].nID=lpInitGrpIconDir->idEntries[i].nID; else { nMaxID++; lpGrpIconDir->idEntries[i].nID=i+1; //adaug noile ICO la sfarsitul RT_ICON-urilor } CopyMemory(test,&lpGrpIconDir->idEntries[i].nID,sizeof(WORD)); test=test+sizeof(WORD); } //offsetul de unde incep structurile ICONIMAGE cbInitOffset=3*sizeof(WORD)+lpGrpIconDir->idCount*sizeof(ICONDIRENTRY); cbOffset=cbInitOffset; //cbOffset=118 FreeLibrary(hUi); HANDLE hUpdate; // _chmod((char*)lpFileName,_S_IWRITE); hUpdate = BeginUpdateResourceA(lpFileName, FALSE); //false sa nu stearga resursele neupdated if(hUpdate==NULL) { QTextStream(stdout, QIODevice::WriteOnly) << "erreur BeginUpdateResource " << lpFileName << "\n"; res=false; } //aici e cu lang NEUTRAL //res=UpdateResource(hUpdate,RT_GROUP_ICON,MAKEINTRESOURCE(6000),langId,lpGrpIconDir,cbRes); res=UpdateResource(hUpdate,RT_GROUP_ICON,lpName,langId,temp,cbRes); if(res==false) QTextStream(stdout, QIODevice::WriteOnly) << "erreur UpdateResource RT_GROUP_ICON " << lpFileName << "\n"; for(i=0;i<lpGrpIconDir->idCount;i++) { res=UpdateResource(hUpdate,RT_ICON,MAKEINTRESOURCE(lpGrpIconDir->idEntries[i].nID),langId,pIconImage[i],lpGrpIconDir->idEntries[i].dwBytesInRes); if(res==false) QTextStream(stdout, QIODevice::WriteOnly) << "erreur UpdateResource RT_ICON " << lpFileName << "\n"; } for(i=lpGrpIconDir->idCount;i<lpInitGrpIconDir->idCount;++i) { res=UpdateResource(hUpdate,RT_ICON,MAKEINTRESOURCE(lpInitGrpIconDir->idEntries[i].nID),langId,NULL,0); if(res==false) QTextStream(stdout, QIODevice::WriteOnly) << "erreur to delete resource " << lpFileName << "\n"; } if(!EndUpdateResource(hUpdate,FALSE)) //false ->resource updates will take effect. QTextStream(stdout, QIODevice::WriteOnly) << "eroare EndUpdateResource" << lpFileName << "\n"; // FreeResource(hGlobal); delete[] lpGrpIconDir->idEntries; delete lpGrpIconDir; delete[] temp; return res; }
void Edit(const po::variables_map& variables, int& retcode) { retcode = 1; if (!variables.count("input")) { std::wcerr << L"Error parsing options: must have some input files.\n"; return; } auto inputs = variables["input"].as<std::vector<std::wstring>>(); bool noResourceRebuild = variables["no-resource-rebuild"].as<bool>(); retcode = 0; for (auto& input : inputs) { StripSignature(input, retcode); if (!noResourceRebuild) { HANDLE binaryHandle = NULL; { PEParser pe(input); pe.Open(); if (!pe.IsValidPE()) { std::wcerr << L"Can't open file for reading or invalid format." << std::endl; continue; } std::vector<std::shared_ptr<BYTE>> data; binaryHandle = BeginUpdateResource(input.c_str(), FALSE); if (!binaryHandle) { std::wcerr << L"Can't lock file for updating resources." << std::endl; continue; } ResourceEntryPtr node; if (pe.ResourceDirectory()) node = pe.ResourceDirectory()->AtPath(L"16/1"); if (!node) continue; bool success = true; if (node->IsData()) data.push_back(ProcessNode(binaryHandle, node, variables)); else for (auto& entry : node->Entries()) data.push_back(ProcessNode(binaryHandle, entry.second, variables)); } if (!EndUpdateResource(binaryHandle, false)) { std::wcerr << L"Failed to update resources" << std::endl; retcode = 1; } } else { PEParser pe(input); pe.Open(true); if (!pe.IsValidPE()) { std::wcerr << L"Can't open file for reading or invalid format." << std::endl; continue; } VersionString version; PEParser::VersionField versionField = PEParser::Both; if (variables.count("set-version")) { version = variables["set-version"].as<std::wstring>(); versionField = PEParser::Both; } else if (variables.count("set-file-version")) { version = variables["set-file-version"].as<std::wstring>(); versionField = PEParser::FileOnly; } else if (variables.count("set-product-version")) { version = variables["set-product-version"].as<std::wstring>(); versionField = PEParser::ProductOnly; } if (!pe.SetVersion(version, versionField)) retcode = 1; pe.Close(); } } }
static int ImportStrings( const wchar_t *dllName, const wchar_t *csvName ) { HANDLE hCSV=CreateFile(csvName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if (hCSV==INVALID_HANDLE_VALUE) { Printf("Failed to read %S\n",csvName); return 1; } int size=SetFilePointer(hCSV,0,NULL,FILE_END)/2; SetFilePointer(hCSV,0,NULL,FILE_BEGIN); std::vector<wchar_t> buf(size+1); DWORD q; ReadFile(hCSV,&buf[0],size*2,&q,NULL); CloseHandle(hCSV); buf[size]=0; for (int i=0;i<size;i++) if (buf[i]=='\r' || buf[i]=='\n') buf[i]=0; std::map<int,const wchar_t*> lines; wchar_t *str=&buf[0]; int min=100000, max=0; while (str<&buf[size]) { int len=Strlen(str); wchar_t *next=str+len+1; wchar_t *tab=wcschr(str,'\t'); if (tab) { *tab=0; int id=_wtol(str); bool bNumber=id>0; for (;*str;str++) if (*str<'0' || *str>'9') { bNumber=false; break; } if (bNumber) { tab=wcschr(tab+1,'\t'); if (tab) { str=tab+1; tab=wcschr(str,'\t'); if (tab) *tab=0; if (lines.find(id)!=lines.end()) { Printf("Duplicate string ID %d\n",id); return 1; } UnsescapeString(str); lines[id]=str; if (min>id) min=id; if (max<id) max=id; } } } str=next; } HMODULE hDll=LoadLibraryEx(dllName,NULL,LOAD_LIBRARY_AS_DATAFILE|LOAD_LIBRARY_AS_IMAGE_RESOURCE); if (!hDll) { Printf("Failed to open %S (err: %d)\n",dllName,GetLastError()); return 1; } std::vector<std::pair<int,WORD>> oldStrings; EnumResourceNames(hDll,RT_STRING,EnumResNameProc,(LONG_PTR)&oldStrings); FreeLibrary(hDll); HANDLE hUpdate=BeginUpdateResource(dllName,FALSE); if (!hUpdate) { Printf("Failed to open %S (err: %d)\n",dllName,GetLastError()); return 1; } // delete all string resources for (int i=0;i<(int)oldStrings.size();i++) { UpdateResource(hUpdate,RT_STRING,MAKEINTRESOURCE(oldStrings[i].first),oldStrings[i].second,NULL,0); } // add new string lines max+=32; for (int i=min;i<max;i+=16) { int id=i/16; int idx=(id-1)*16; std::vector<wchar_t> res; for (int j=0;j<16;j++,idx++) { std::map<int,const wchar_t*>::const_iterator it=lines.find(idx); const wchar_t *str=L""; if (it!=lines.end()) str=it->second; int len=Strlen(str); res.push_back((wchar_t)len); for (int c=0;c<len;c++) res.push_back(str[c]); } if (res.size()>16) UpdateResource(hUpdate,RT_STRING,MAKEINTRESOURCE(id),LANG_NEUTRAL,&res[0],res.size()*2); } if (!EndUpdateResource(hUpdate,FALSE)) { Printf("Failed to update %S (err: %d)\n",dllName,GetLastError()); return 1; } return 0; }
//----------------------------------------------------------------------------- // ExtAddIcon() // Add the icon as a resource to the specified file. //----------------------------------------------------------------------------- static PyObject *ExtAddIcon( PyObject *self, // passthrough argument PyObject *args) // arguments { char *executableName, *iconName, *data, *iconData; GRPICONDIR *groupIconDir; DWORD resourceSize; ICONDIR *iconDir; BOOL succeeded; HANDLE handle; int i; if (!PyArg_ParseTuple(args, "ss", &executableName, &iconName)) return NULL; // begin updating the executable handle = BeginUpdateResource(executableName, FALSE); if (!handle) { PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError, GetLastError(), executableName); return NULL; } // first attempt to get the data from the icon file data = NULL; succeeded = TRUE; groupIconDir = NULL; if (GetFileData(iconName, &data) < 0) succeeded = FALSE; iconDir = (ICONDIR*) data; // next, attempt to add a group icon resource if (succeeded) { groupIconDir = CreateGroupIconResource(iconDir, &resourceSize); if (groupIconDir) succeeded = UpdateResource(handle, RT_GROUP_ICON, MAKEINTRESOURCE(1), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), groupIconDir, resourceSize); else succeeded = FALSE; } // next, add each icon as a resource if (succeeded) { for (i = 0; i < iconDir->idCount; i++) { iconData = &data[iconDir->idEntries[i].dwImageOffset]; resourceSize = iconDir->idEntries[i].dwBytesInRes; succeeded = UpdateResource(handle, RT_ICON, MAKEINTRESOURCE(i + 1), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), iconData, resourceSize); if (!succeeded) break; } } // finish writing the resource (or discarding the changes upon an error) if (!EndUpdateResource(handle, !succeeded)) { if (succeeded) { succeeded = FALSE; PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError, GetLastError(), executableName); } } // clean up if (groupIconDir) PyMem_Free(groupIconDir); if (data) PyMem_Free(data); if (!succeeded) return NULL; Py_INCREF(Py_None); return Py_None; }
EXEArc_Write::~EXEArc_Write() { if (m_res) EndUpdateResource(m_res, TRUE); }
bool ChangeIcon(_TCHAR* iconFileName, _TCHAR* executableFileName) { bool result = false; DWORD dwData = 1; WORD language = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT); _TCHAR* iconExtension = wcsrchr(iconFileName, '.'); if (iconExtension == NULL || wcscmp(iconExtension, L".ico") != 0) { wprintf(L"Unknown icon format - please provide .ICO file.\n"); return result; } HANDLE icon = CreateFile(iconFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (icon == INVALID_HANDLE_VALUE) { PrintError(); return result; } // Reading .ICO file WORD idReserved, idType, idCount; DWORD dwBytesRead; ReadFile(icon, &idReserved, sizeof(WORD), &dwBytesRead, NULL); ReadFile(icon, &idType, sizeof(WORD), &dwBytesRead, NULL); ReadFile(icon, &idCount, sizeof(WORD), &dwBytesRead, NULL); LPICONDIR lpid = (LPICONDIR)malloc(sizeof(ICONDIR) + (sizeof(ICONDIRENTRY) * (idCount - 1))); if (lpid == NULL) { CloseHandle(icon); wprintf(L"Unknown error.\n"); } lpid->idReserved = idReserved; lpid->idType = idType; lpid->idCount = idCount; ReadFile(icon, &lpid->idEntries[0], sizeof(ICONDIRENTRY) * lpid->idCount, &dwBytesRead, NULL); LPGRPICONDIR lpgid = (LPGRPICONDIR)malloc(sizeof(GRPICONDIR) + (sizeof(GRPICONDIRENTRY) * (idCount - 1))); if (lpid == NULL) { CloseHandle(icon); free(lpid); wprintf(L"Unknown error.\n"); } lpgid->idReserved = idReserved; lpgid->idType = idType; lpgid->idCount = idCount; for(int i = 0; i < lpgid->idCount; i++) { lpgid->idEntries[i].bWidth = lpid->idEntries[i].bWidth; lpgid->idEntries[i].bHeight = lpid->idEntries[i].bHeight; lpgid->idEntries[i].bColorCount = lpid->idEntries[i].bColorCount; lpgid->idEntries[i].bReserved = lpid->idEntries[i].bReserved; lpgid->idEntries[i].wPlanes = lpid->idEntries[i].wPlanes; lpgid->idEntries[i].wBitCount = lpid->idEntries[i].wBitCount; lpgid->idEntries[i].dwBytesInRes = lpid->idEntries[i].dwBytesInRes; lpgid->idEntries[i].nID = i + 1; } // Store images in .EXE HANDLE update = BeginUpdateResource( executableFileName, FALSE ); if (update == NULL) { free(lpid); free(lpgid); CloseHandle(icon); PrintError(); return result; } for(int i = 0; i < lpid->idCount; i++) { LPBYTE lpBuffer = (LPBYTE)malloc(lpid->idEntries[i].dwBytesInRes); SetFilePointer(icon, lpid->idEntries[i].dwImageOffset, NULL, FILE_BEGIN); ReadFile(icon, lpBuffer, lpid->idEntries[i].dwBytesInRes, &dwBytesRead, NULL); if (!UpdateResource(update, RT_ICON, MAKEINTRESOURCE(lpgid->idEntries[i].nID), language, &lpBuffer[0], lpid->idEntries[i].dwBytesInRes)) { free(lpBuffer); free(lpid); free(lpgid); CloseHandle(icon); PrintError(); return result; } free(lpBuffer); } free(lpid); CloseHandle(icon); if (!UpdateResource(update, RT_GROUP_ICON, MAKEINTRESOURCE(1), language, &lpgid[0], (sizeof(WORD) * 3) + (sizeof(GRPICONDIRENTRY) * lpgid->idCount))) { free(lpgid); PrintError(); return result; } free(lpgid); if (EndUpdateResource(update, FALSE) == FALSE) { PrintError(); return result; } result = true; return result; }
int main(int argc, char **argv) { if (argc != 3) { printf("Usage: redit <exe file> <icon file>\n"); return 1; } int file = _open(argv[2], _O_BINARY | _O_RDONLY); if (file == -1) { fprintf(stderr, "Unable to open icon file.\n"); return 1; } // Load all the data from the icon file long filesize = _filelength(file); char* data = (char*)malloc(filesize); _read(file, data, filesize); _close(file); IconHeader* header = (IconHeader*)data; // Open the target library for updating HANDLE updateRes = BeginUpdateResource(argv[1], FALSE); if (updateRes == NULL) { fprintf(stderr, "Unable to open library for modification.\n"); free(data); return 1; } // Allocate the group resource entry long groupsize = sizeof(IconHeader) + header->ImageCount * sizeof(IconResEntry); char* group = (char*)malloc(groupsize); memcpy(group, data, sizeof(IconHeader)); IconDirEntry* sourceIcon = (IconDirEntry*)(data + sizeof(IconHeader)); IconResEntry* targetIcon = (IconResEntry*)(group + sizeof(IconHeader)); for (int i = 0; i < header->ImageCount; i++) { // Add the individual icon int id = i + 1; if (!UpdateResource(updateRes, RT_ICON, MAKEINTRESOURCE(id), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), data + sourceIcon->ImageOffset, sourceIcon->ImageSize)) { fprintf(stderr, "Unable to update resource.\n"); EndUpdateResource(updateRes, TRUE); // Discard changes, ignore errors free(data); free(group); return 1; } // Copy the data for this icon memcpy(targetIcon, sourceIcon, sizeof(IconResEntry)); targetIcon->ResourceID = id; sourceIcon++; targetIcon++; } free(data); if (!UpdateResource(updateRes, RT_GROUP_ICON, "MAINICON", MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), group, groupsize)) { fprintf(stderr, "Unable to update resource.\n"); EndUpdateResource(updateRes, TRUE); // Discard changes free(group); return 1; } free(group); // Save the modifications if (!EndUpdateResource(updateRes, FALSE)) { fprintf(stderr, "Unable to write changes to library.\n"); return 1; } return 0; }
const Result CtrlrWindows::exportWithDefaultPanel(CtrlrPanel* panelToWrite, const bool isRestricted, const bool signPanel, RSAKey privateKey) { if (panelToWrite == nullptr) { return (Result::fail("Windows Native: exportWithDefaultPanel got nullptr for panel")); } File me = File::getSpecialLocation(File::currentExecutableFile); File newMe; HANDLE hResource; MemoryBlock panelExportData,panelResourcesData; MemoryBlock iconData(BinaryData::ico_midi_png, BinaryData::ico_midi_pngSize); FileChooser fc(CTRLR_NEW_INSTANCE_DIALOG_TITLE, me.getParentDirectory().getChildFile(File::createLegalFileName(panelToWrite->getProperty(Ids::name))).withFileExtension(me.getFileExtension()), "*"+me.getFileExtension(), panelToWrite->getOwner().getProperty(Ids::ctrlrNativeFileDialogs)); if (fc.browseForFileToSave(true)) { newMe = fc.getResult(); if (!newMe.hasFileExtension(me.getFileExtension())) { newMe = newMe.withFileExtension(me.getFileExtension()); } if (!me.copyFileTo (newMe)) { return (Result::fail("Windows Native: exportMeWithNewResource can't copy \""+me.getFullPathName()+"\" to \""+newMe.getFullPathName()+"\"")); } } else { return (Result::fail("Windows Native: exportMeWithNewResource \"Save file\" dialog failed")); } hResource = BeginUpdateResource(newMe.getFullPathName().toUTF8(), FALSE); if (hResource) { String error; if ( (error = CtrlrPanel::exportPanel (panelToWrite, File::nonexistent, newMe, &panelExportData, &panelResourcesData, isRestricted)) == String::empty) { if ( writeResource (hResource, MAKEINTRESOURCE(CTRLR_INTERNAL_PANEL_RESID), RT_RCDATA, panelExportData) && writeResource (hResource, MAKEINTRESOURCE(CTRLR_INTERNAL_RESOURCES_RESID), RT_RCDATA, panelResourcesData) ) { EndUpdateResource(hResource, FALSE); } else { return (Result::fail("Windows Native: exportMeWithNewResource writeResource[panel] failed")); } if (isRestricted && privateKey != RSAKey()) { /* Sign the panel */ MemoryBlock signature = signData (panelResourcesData, privateKey); } } else { return (Result::fail("Windows Native: exportMeWithNewResource exportPanel error: \""+error+"\"")); } return (Result::ok()); } return (Result::fail("Windows Native: exportMeWithNewResource BeginUpdateResource failed")); }
void SetVersion(LPCTSTR lpszFile) { VS_VERSIONINFO *pVerInfo; LPBYTE pOffsetBytes; VS_FIXEDFILEINFO *pFixedInfo; DWORD dwHandle, dwSize, dwResult = 0; // determine the size of the resource information dwSize = GetFileVersionInfoSize((LPTSTR)lpszFile, &dwHandle); if (0 < dwSize) { LPBYTE lpBuffer = new BYTE[dwSize]; if (GetFileVersionInfo((LPTSTR)lpszFile, 0, dwSize, lpBuffer) != FALSE) { // these macros help to align on r-byte boundaries (thanks Ted Peck) // 'point to' the start of the version information block pVerInfo = (VS_VERSIONINFO *) lpBuffer; // the fixed section starts right after the 'VS_VERSION_INFO' string pOffsetBytes = (BYTE *) &pVerInfo->szKey[wcslen(pVerInfo->szKey) + 1]; pFixedInfo = (VS_FIXEDFILEINFO *) roundpos(pVerInfo, pOffsetBytes, 4); // increment the numbers! pFixedInfo->dwFileVersionMS = pFixedInfo->dwFileVersionMS + 0x00010001; pFixedInfo->dwFileVersionLS = pFixedInfo->dwFileVersionLS + 0x00010001; pFixedInfo->dwProductVersionMS = pFixedInfo->dwProductVersionMS + 0x00010001; pFixedInfo->dwProductVersionLS = pFixedInfo->dwProductVersionLS + 0x00010001; HANDLE hResource = BeginUpdateResource(lpszFile, FALSE); if (NULL != hResource) { UINT uTemp; // get the language information if (VerQueryValue(lpBuffer, _T("\\VarFileInfo\\Translation"), (LPVOID *) &lpTranslate, &uTemp) != FALSE) { // could probably just use LANG_NEUTRAL/SUBLANG_NEUTRAL if (UpdateResource(hResource, RT_VERSION, MAKEINTRESOURCE(VS_VERSION_INFO), lpTranslate->wLanguage, lpBuffer, dwSize) != FALSE) { if (EndUpdateResource(hResource, FALSE) == FALSE) dwResult = GetLastError(); } else dwResult = GetLastError(); } } else dwResult = GetLastError(); } else dwResult = GetLastError(); delete [] lpBuffer; } else dwResult = GetLastError(); //if (0 != dwResult) // wprintf(_T("Operation was not successful. Result = %lu\n"), dwResult); }
DWORD WINAPI WorkerThread(LPVOID lpParam) { HGLOBAL hResLoad; // handle to loaded resource HRSRC hRes; // handle/ptr. to res. info. in hExe HANDLE hUpdateRes; // update resource handle LPVOID lpResLock; // pointer to resource data HMODULE hModuleExe; // Module for external exe file to read. BOOL result; #define IDD_MANIFEST_RESOURCE 1 char hExeFileNameTemp[MAX_SIZE] = ""; workerInfo* worker = (workerInfo*)lpParam; conStep = CONVERT_STEP_1; strFilePath = worker->fileStr; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); //Step 1: Read exe file if a manifest is already included. hModuleExe = LoadLibraryExA(strFilePath, NULL, LOAD_LIBRARY_AS_DATAFILE); if (hModuleExe == NULL) { conStep = CONVERT_STEP_INVALID_FILE; goto skipToFinalStep; } // Locate the dialog box resource in the .EXE file. hRes = FindResourceW(hModuleExe, MAKEINTRESOURCE(IDD_MANIFEST_RESOURCE), RT_MANIFEST); if (hRes != NULL) { conStep = CONVERT_STEP_MANIFEST_INCLUDED; goto skipToFreeLibary; } unsigned int err; if (!isDirFileFullPermission(L"\\", &err)) { conStep = CONVERT_STEP_NOPERM; skipToFreeLibary: FreeLibrary(hModuleExe); goto skipToFinalStep; } FreeLibrary(hModuleExe); //Step 2: Get manifest resource file from inside exe file. conStep = CONVERT_STEP_2; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); hRes = FindResourceW(GetCurrentModule(), MAKEINTRESOURCE(IDD_MANIFEST_RESOURCE), RT_MANIFEST); // Load the dialog box into global memory. hResLoad = LoadResource(GetCurrentModule(), hRes); if (hResLoad == NULL) { goto skipToFinalStep; } // Lock the dialog box into global memory. lpResLock = LockResource(hResLoad); if (lpResLock == NULL) { conStep = CONVERT_STEP_APP_RESOURCE_FAIL; skipToFreeResource: FreeResource(hResLoad); goto skipToFinalStep; } //Step 3: Create backup of original exe of user request to add manifest in it. conStep = CONVERT_STEP_3; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); strcatA(hExeFileNameTemp, MAX_SIZE, strFilePath); strcatA(hExeFileNameTemp, MAX_SIZE, "_backup"); if (!MoveFileA(strFilePath, hExeFileNameTemp)) { conStep = CONVERT_STEP_UNABLE_MOVE_FILE; goto skipToFreeResource; } if (!CopyFileA(hExeFileNameTemp, strFilePath, FALSE)) { conStep = CONVERT_STEP_UNABLE_COPY_FILE; goto skipToFreeResource; } //Step 4: Add manifest to the exe file. // Open the file to which you want to add the dialog box resource. conStep = CONVERT_STEP_4; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); hUpdateRes = BeginUpdateResourceA(strFilePath, FALSE); if (hUpdateRes == NULL) { conStep = CONVERT_STEP_UNABLE_WRITE_FILE; goto skipToFreeResource; } // Add the dialog box resource to the update list. result = UpdateResource(hUpdateRes, // update resource handle RT_MANIFEST, // change dialog box resource MAKEINTRESOURCE(IDD_MANIFEST_RESOURCE), // dialog box id MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), // neutral language lpResLock, // ptr to resource info SizeofResource(GetCurrentModule(), hRes)); // size of resource info if (result == FALSE) { conStep = CONVERT_STEP_UNABLE_ADD_RES; goto skipToFreeResource; } // Write changes to exe file and then close it. if (!EndUpdateResource(hUpdateRes, FALSE)) { conStep = CONVERT_STEP_UNABLE_SAVE_RES; goto skipToFreeResource; } FreeResource(hResLoad); //Final step conStep = CONVERT_STEP_READY_COMPLETE; skipToFinalStep: RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); free(worker); return 0; }
// Add JAR file bool Resource::AddJar(LPSTR exeFile, LPSTR jarFile) { // Extract just the filename from the jar file path char jarName[MAX_PATH]; int len = strlen(jarFile) - 1; while(len > 0) { if(jarFile[len] == '\\' || jarFile[len] == '/') break; len--; } if(len == 0) len--; strcpy(jarName, &jarFile[len+1]); // Find next available slot for JAR file HMODULE hm = LoadLibrary(exeFile); if(!hm) { Log::Error("Could not load exe to add JAR: %s", exeFile); return false; } int resId = 1; HRSRC hr = 0; while((hr = FindResource(hm, MAKEINTRESOURCE(resId), RT_JAR_FILE)) != NULL) { // Check for jar with matching name - if found we want to overwrite HGLOBAL hg = LoadResource(hm, hr); PBYTE pb = (PBYTE) LockResource(hg); DWORD* pd = (DWORD*) pb; if(*pd == JAR_RES_MAGIC) { int len = strlen((char*) &pb[RES_MAGIC_SIZE]); if(strcmp(jarName, (char*) &pb[RES_MAGIC_SIZE]) == 0) { break; } } resId++; } FreeLibrary(hm); // Read the JAR file HANDLE hFile = CreateFile(TEXT(jarFile), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == INVALID_HANDLE_VALUE) { Log::Error("Could not open JAR file: %s", jarFile); return false; } DWORD cbBuffer = GetFileSize(hFile, 0); DWORD cbPadding = RES_MAGIC_SIZE + strlen(jarName) + 1; PBYTE pBuffer = (PBYTE) malloc(cbBuffer + cbPadding); ReadFile(hFile, &pBuffer[cbPadding], cbBuffer, &cbBuffer, 0); // Create binary structure for jar file DWORD* pMagic = (DWORD*) pBuffer; *pMagic = JAR_RES_MAGIC; memcpy(&pBuffer[RES_MAGIC_SIZE], jarName, strlen(jarName) + 1); // Copy in resources HANDLE hUpdate = BeginUpdateResource(exeFile, FALSE); if(!hUpdate) { Log::Error("Could not load exe to add JAR: %s", exeFile); return false; } // Copy in JAR file UpdateResource(hUpdate, RT_JAR_FILE, MAKEINTRESOURCE(resId), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), pBuffer, cbBuffer + cbPadding); // Commit the changes EndUpdateResource(hUpdate, FALSE); return true; }
~ResourceUpdate() { if (handle) EndUpdateResource(handle, TRUE); }