I am seeing the same issue … I was trying to access the ListView
I have also tried to use the pywinauto lib to access the component directly and below is the trace:
WindowsError Traceback (most recent call last)
in ()
—-> 1 h.ListView.GetItem(‘SEM’).Check()
c:python27libsite-packagespywinauto-0.5.4-py2.7.eggpywinautocontrolscommon_controls.pyc in GetItem(self, item_index, subitem_index)
757 «»»
758
—> 759 return _listview_item(self, item_index, subitem_index)
760
761 Item = GetItem # this is an alias to be consistent with other content elements
c:python27libsite-packagespywinauto-0.5.4-py2.7.eggpywinautocontrolscommon_controls.pyc in init(self, lv_ctrl, item_index, subitem_
ndex)
67 # ensure the item_index is an integer or
68 # convert it to one
—> 69 self.item_index = self.listview_ctrl._as_item_index(item_index)
70 self.subitem_index = subitem_index
71 #self.as_parameter = self.item_index
c:python27libsite-packagespywinauto-0.5.4-py2.7.eggpywinautocontrolscommon_controls.pyc in _as_item_index(self, item)
743 index = item
744 if isinstance(item, six.string_types):
—> 745 index = int((self.Texts().index(item) — 1) / self.ColumnCount())
746
747 return index
c:python27libsite-packagespywinauto-0.5.4-py2.7.eggpywinautocontrolscommon_controls.pyc in Texts(self)
787 «Get the texts for the ListView control»
788 texts = [self.WindowText()]
—> 789 texts.extend([item[‘text’] for item in self.Items()])
790 return texts
791
c:python27libsite-packagespywinauto-0.5.4-py2.7.eggpywinautocontrolscommon_controls.pyc in getitem(self, key)
155 ‘Use methods Text(), State(), Image() and Indent().’, DeprecationWarning)
156
—> 157 item, text = self._readitem()
158 if key == ‘text’:
159 return text
c:python27libsite-packagespywinauto-0.5.4-py2.7.eggpywinautocontrolscommon_controls.pyc in _readitem(self)
135 # Read the remote text string
136 char_data = self.listview_ctrl.create_buffer(2000)
—> 137 remote_mem.Read(char_data, item.pszText)
138
139 text = self.listview_ctrl.text_decode(char_data.value)
c:python27libsite-packagespywinauto-0.5.4-py2.7.eggpywinautoRemoteMemoryBlock.py in Read(self, data, address, size)
253
254 ActionLogger().log(‘lpNumberOfBytesRead =’ + str(lpNumberOfBytesRead) + ‘ nSize =’ + str(nSize))
—> 255 raise ctypes.WinError()
256 else:
257 ActionLogger().log(‘Warning! Read OK: 2nd attempt!’)
WindowsError: [Error 299] Only part of a ReadProcessMemory or WriteProcessMemory request was completed.
ReadProcessMemory… code error 299
, Помогите справиться с кодом 299
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Senior Member Рейтинг (т): 10 |
Пытаюсь прочитать память процесса по заранее известному адресу…..
HANDLE hQip=0; HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); PROCESSENTRY32 ProcEntry; ProcEntry.dwSize = sizeof(PROCESSENTRY32); Process32First(hSnapShot,&ProcEntry); do { if(lstrcmp(«qip.exe»,ProcEntry.szExeFile)==0) { hQip = OpenProcess(PROCESS_ALL_ACCESS,TRUE,ProcEntry.th32ProcessID); if(hQip==0) return 0; } } while(Process32Next(hSnapShot,&ProcEntry)); if(ReadProcessMemory(hQip,(PVOID)0x006A3AC,n,1000,&d) == 0) { d = GetLastError(); sprintf(n,»%d»,d); MessageBox(HWND_DESKTOP,n,»pass:»,0); } else { MessageBox(HWND_DESKTOP,n,»»,0); } GetLastError() всегда говорит о 299 ошибке: ReadWriteProcessMemory запрос выполнен не полнустью. |
Мальчиш |
|
barberan
if (hQip) { if(ReadProcessMemory(hQip,(PVOID)0x006A3AC,n,1000,&d) == 0) { d = GetLastError(); sprintf(n,»%d»,d); MessageBox(HWND_DESKTOP,n,»pass:»,0); } else { MessageBox(HWND_DESKTOP,n,»»,0); } } во вторых адрес 0x006A3AC на разных платформах, системах, при разных условиях может быть разным. Добавлено 26.08.08, 06:52 Добавлено 26.08.08, 06:53 |
leo |
|
Цитата Мальчиш @ 26.08.08, 06:51 во вторых адрес 0x006A3AC на разных платформах, системах, при разных условиях может быть разным.
Во-вторых — верно, а в-третьих — Майкрософт А вот хватает ли размера переменной n для 1000 байт — из приведенного кода не видно |
barberan |
|
Senior Member Рейтинг (т): 10 |
if (hQip) это проверено заранее. |
leo |
|
Ошибка 299 вылезает и в том случае, когда память по адресу вообще не доступна. Проверь число прочитанных байт d — если 0, значит память по данному адресу вообще не выделена — можешь проверить по VirtualQueryEx |
barberan |
|
Senior Member Рейтинг (т): 10 |
С этим разобрался, спасибо. А еще вопрос.. как в памяти процесса найти что-то определнное, и узнать по какому адресу оно лежит ? |
leo |
|
Цитата barberan @ 26.08.08, 16:59 как в памяти процесса найти что-то определнное, и узнать по какому адресу оно лежит ?
Сам понимаешь, вопрос не только не новый, но и достаточно «популярный» |
barberan |
|
Senior Member Рейтинг (т): 10 |
Подскажите, как найти границы адресов процесса? Делаю так:
MEMORY_BASIC_INFORMATION mbi; SIZE_T mbi_size = sizeof(mbi); DWORD startaddr=0, //начальный адрес lowaddr, //нижняя граница highaddr; //верхняя граница do { if( VirtualQueryEx(hQip,(LPCVOID)startaddr,&mbi,mbi_size) != sizeof(mbi)) { return 0; } startaddr+=(DWORD)mbi.RegionSize; }while(mbi.State != MEM_COMMIT); lowaddr = mbi.BaseAddress; //типа нашли нижнюю границу процесса. Через отладчик смарел… startaddr сначала +=65536 потом еще +=4096… Получается всего 2 страницы MEM_COMMIT чего быть то и не может. |
B.V. |
|
leo |
|
Цитата barberan @ 27.08.08, 21:11 как найти границы адресов процесса?
Еще как может Похоже ты не понимаешь главного — память процесса это не только образ загруженного экзешника, но и образы подключенных длл (системных и «личных»), стек(и) потока(ов), динамическая память (виндовая куча, собственная куча, отдельные блоки VirtualAlloc), плюс множество служебных регионов памяти типа переменных окружения, списка загруженных модулей (куча загрузчика) и т.д. и т.п. Каждая из этих «сущностей» занимает непрерывные регионы памяти, но между собой эти регионы не «склеены» и как правило разделены «дырами», хотя бы потому что в винде адреса резервируются с шагом 64К, а физ.память выделяется (commit) страницами по 4К. |
barberan |
|
Senior Member Рейтинг (т): 10 |
Хм.. РАзобрался. А вот еще вопрос… ведь каждый адресс, если верить карте памяти состояит из 16 байт(или как это… — секций чтоли). В каждом байте(секции) хранится 1 символ. Иногда у меня странно считываетются не все 16(я точно не знаю что происходит), но знаючи, что например по данному адрессу «hello,world» я вижу чёта типа «lo,world» или «hello,wor». Что есть что? |
leo |
|
Цитата barberan @ 28.08.08, 20:13 ведь каждый адресс, если верить карте памяти состояит из 16 байт Не верь глазам своим Это делается просто для удобства отображения — в каждой строке выводится по 16 байтсимволов по адресам кратным 0x10. Поэтому если ты вместо «hello,world» видишь чёта типа «lo,world» по адресу X, значит действительный адрес начала текста = X-3 и ничего более |
barberan |
|
Senior Member Рейтинг (т): 10 |
а как бы это корректировать по ходу ??? ведь не знаю что увижу, толи леву половинку, толи правую. КАк быть? |
leo |
|
Никак. PS: В дельфиBCB поиск подстроки реализуется легко — выделяем память под AnsiString через SetLength(s,mbi.RegionSize), читаем в строку весь регион и затем ищем подстроку функцией Pos. Такой поиск работает для любых бинарных данных, т.к. диапазон поиска ограничивается явно заданной длиной строки, а не нулевыми символами, которые могут встречаться в произвольных данных. Есть ли нечто подобное в CC++ не знаю. Если нет, то придется организовать ручками: юзать в цикле strstr и перескакивать нулевые символы, пока не дойдем до конца региона |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- Visual C++ / MFC / WTL
- Следующая тема
[ Script execution time: 0,0765 ] [ 16 queries used ] [ Generated: 10.02.23, 01:33 GMT ]
-
02-07-2008
#1
Registered User
ReadProcessMemory Error
Hey, I am trying to use the ReadProcessMemory function but every time I call it I get the error code 299 from the function GetLastError() that means: «Only part of a ReadProcessMemory or WriteProcessMemory request was completed.».
OS: Windows Vista.
Code from the «reader»:Code:
handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, getPid()); SIZE_T bytesRead; std::string buffer(8, ''); unsigned long address = 0x001cf834; if (ReadProcessMemory(handle, &address, &buffer[0], 8, &bytesRead)) { return true; } else { cout << GetLastError() << 'n'; return false; }
Remark: the process ID is correct, I assure you .
Code from the «readed»:
Code:
#include <iostream> #include <fstream> using namespace std; int main() { char t[] = "my pattern" ; cout << "addr: " << &t << 'n'; cin.get(); }
1) The address chosen to be the parameter of ReadProcessMemory is the address printed in the readed program, is that right?
2) By the way, always when i restart the readed program the address of char t changes, why? If I am allocating it statically shouldn’t it have always the same address?
3) How can i search a program’s memory like a debugger? I have tought of scanning its memory trough ReadProcessMemory respecting the maximum and minimum base addresses provided by the function GetSystemInfo(), is it the correct way of doing that?
4) If the last question is true, how much should be the buffer size of the ReadProcessMemory because I imagine that a call to this function should take a lot of time so implementing a buffer would help?
Thank You
-
02-08-2008
#2
Kernel hacker
The error 299 is ERROR_PARTIAL_COPY — so for some reason, the OS thinks it’s fine to read parts of the memory, but not all.
How many bytes does it report that you got?
—
MatsCompilers can produce warnings — make the compiler programmers happy: Use them!
Please don’t PM me for help — and no, I don’t do help over instant messengers.
-
02-08-2008
#3
Registered User
Hey, I am trying to use the ReadProcessMemory function but every time I call it I get the error code 299 from the function GetLastError() that means: «Only part of a ReadProcessMemory or WriteProcessMemory request was completed.».
It may be due to your not elevating the token privilege level since you’re reading memory on the system level. But even if your are elevating the privilege level, you may not be doing it correctly. The reason being is that I noticed you were not elevating the privilege level correctly in one of your other posts. You were calling it after opening the process. It must be called prior to opening the process. Also, the 0x001cf834 address is incorrect. I put some info in the sample to explain the address.
But anyway, the following example displays the command line parms (if any) of the process in question.
Code:
#define UNICODE #define _UNICODE #include <windows.h> #include <stdio.h> #include <tchar.h> #pragma comment(lib, "advapi32.lib") // Process data block is found in an NT machine. // on an Intel system at 0x00020000 which is the 32 // memory page. At offset 0x0498 is what I believe to be // the process' startup directory which is followed by // the system's PATH. Next is process full command // followed by the exe name. #define PROCESS_DATA_BLOCK_ADDRESS (LPVOID)0x00020498 // align pointer #define ALIGNMENT(x) ( (x & 0xFFFFFFFC) ? (x & 0xFFFFFFFC) + sizeof(DWORD) : x ) BOOL GetCommandLine (HANDLE hProcess, LPWSTR lpszCmdLine) { LPBYTE lpBuffer = NULL; LPBYTE lpPosition = NULL; DWORD dwBytesRead; MEMORY_BASIC_INFORMATION mbi; SYSTEM_INFO sysinfo; GetSystemInfo (&sysinfo); lpBuffer = (LPBYTE)malloc (sysinfo.dwPageSize); if ( lpBuffer == NULL ) return FALSE; if ( VirtualQueryEx (hProcess, PROCESS_DATA_BLOCK_ADDRESS, &mbi, sizeof(mbi) ) == 0) return FALSE; if (!ReadProcessMemory ( hProcess, mbi.BaseAddress, (LPVOID)lpBuffer, sysinfo.dwPageSize, &dwBytesRead)) return FALSE; lpPosition = lpBuffer + ((DWORD)PROCESS_DATA_BLOCK_ADDRESS - (DWORD)mbi.BaseAddress); lpPosition = lpPosition + (wcslen ((LPWSTR)lpPosition) + 1) * sizeof(WCHAR); lpPosition = (LPBYTE)ALIGNMENT((DWORD)lpPosition); lpPosition = lpPosition + (wcslen ((LPWSTR)lpPosition) + 1) * sizeof(WCHAR); if ( *lpPosition == '' ) lpPosition += sizeof(WCHAR); wcsncpy ( lpszCmdLine, (LPWSTR)lpPosition, MAX_PATH ); lpszCmdLine[MAX_PATH-1] = L''; if (lpBuffer != NULL) free(lpBuffer); return TRUE; } BOOL EnableTokenPrivilege (LPTSTR privilege) { HANDLE hToken; TOKEN_PRIVILEGES token_privileges; DWORD dwSize; ZeroMemory (&token_privileges, sizeof (token_privileges)); token_privileges.PrivilegeCount = 1; if ( !OpenProcessToken (GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken)) return FALSE; if (!LookupPrivilegeValue ( NULL, privilege, &token_privileges.Privileges[0].Luid)) { CloseHandle (hToken); return FALSE; } token_privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!AdjustTokenPrivileges ( hToken, FALSE, &token_privileges, 0, NULL, &dwSize)) { CloseHandle (hToken); return FALSE; } CloseHandle (hToken); return TRUE; } int wmain (int argc, wchar_t *argv[]) { WCHAR CommandLine[MAX_PATH] = {0}; WCHAR *endptr; DWORD pID; HANDLE hProcess = NULL; if ( argc != 2 ) return 0; pID = wcstoul ( argv[1], &endptr, 10 ); if ( !EnableTokenPrivilege (SE_DEBUG_NAME) ) { printf ( "Cannot get required privilege %lun", GetLastError () ); return 0; } hProcess = OpenProcess (PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pID); if ( hProcess == NULL ) { printf ("Cannot open process. pID: %lu, error %lun", pID, GetLastError ()); return 0; } if ( !GetCommandLine ( hProcess, CommandLine ) ) { printf ("Cannot get process command line, error: %lun", GetLastError ()); return 0; } else printf ("The command line is %Sn", CommandLine); CloseHandle ( hProcess ); return 0; }
-
02-10-2008
#4
Registered User
@ matsp
It says that i have read 0 bytes…
@ BobS0327
Even your example doesn’t work… The functions all return ok with no error messages but the CommandLine is empty….
And im sorry to say, i haven’t understood well addressing, what I do to get and address now is do debug my application, search it for the bytes that form «my pattern» string and get its address… It is correct isn’t it?
I have adapted your code of enabling debug privilege into mine but i still get incomplete reads.
-
02-10-2008
#5
Registered User
What I believe may be the problem is that you’re running the code under Vista. I’ve tested the sample under XP and Win2K without any problems.
Unfortunately, I won’t have access to Vista until Monday morning to test the sample.
-
02-10-2008
#6
Registered User
Ok, i will try to find something until then, but im really lost =(
-
02-12-2008
#7
Registered User
I’ve encountered the same problem as you with Vista Enterprise edition.
Vista has new security enhancements to thwart the malware folks. One feature is Address Space Load Randomization which randomly loads a process into memory. Under Vista, you have a 1 in 256 chance of finding the base address of a process. Whereas, under XP and W2K you knew exactly where in memory a process started as indicated above.
This link will provide a more detailed explanation of Vista Address Space Load Randomization.
BTW, you can create a hack to make the code work. You’ll need Ollydebug to get the base address of the process. then recompile the code with the acquired base address. But every time you reboot, you’ll have to execute Ollydebug for the new base address and recompile the code again with the new address.
-
05-27-2008
#8
Registered User
Hate to resurrect a zombie, but…
this board is high enough on the search engine rankings that I think having an answer to this question would be useful. A lot of queries into the cause of this problem have been made, including Address Randomization (which only applies to system processes) and Vista’s security (which doesn’t apply if running as an administrator and not accessing a protected process). The real problem here is that people have not read the documentation for OpenProcess since Vista came out. OpenProcess is being called with PROCESS_ALL_ACCESS rights requested. On Vista, the size of PROCESS_ALL_ACCESS has changed, and is now 0x1fffff instead of 0x1f0fff, and unless you are using an updated definition for Vista and Server 2008, using PROCESS_ALL_ACCESS will request the incorrect rights, and you won’t get the results you want. If you redefine PROCESS_ALL_ACCESS or use 0x1fffff in the call to OpenProcess instead of 0x1f0fff, your code will now work.
-
05-28-2008
#9
C++まいる!Cをこわせ!
It’s just that many people here are mostly unfamiliar with Vista, it seems.
Originally Posted by Adak
io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
Originally Posted by Salem
You mean it’s included as a crutch to help ancient programmers limp along without them having to relearn too much.
Outside of your DOS world, your header file is meaningless.
-
05-28-2008
#10
Registered User
If
you redefine PROCESS_ALL_ACCESS or use 0x1fffff in the call to OpenProcess instead of 0x1f0fff, your code will now work.
The suggestion didn’t work for me on Vista Enterprise. Out of curiosity, I tried it on XP Pro and it does work.
-
05-28-2008
#11
Registered User
Worked for me on Vista Ultimate, but…
according to the MSN docs, using PROCESS_ALL_ACCESS isn’t recommended procedure on Vista anyway (you should request only those rights you specifically need to do what you’re going to do, piped together of course), which would allow you to accomplish much the same task, although slightly more verbose, definitely works. I got the information from
http://msdn.microsoft.com/en-us/libr…80(VS.85).aspx
in case anyone cares to read up on it more, but remember, you still can’t gain certain rights when trying to use OpenProcess on protected processes anyway. Regardless, I just wanted to share what worked for me, as the issue had been bugging me and I could not find the answer in any easily searchable location, so I hope this helps somebody at least.
|
Authenticator Code |
Thread Tools |
Error 299 when trying to read world offset |
|
#1 |
|||||||||||
ShadowLegion n00bie Join Date: Nov 2018
Reputation: 10 Points: 79, Level: 1 Level up: 20%, 321 Points needed Activity: 9.1% |
Error 299 when trying to read world offset Hi, so right now I’m using the windows api Module32First to get the base address as a DWORD64, however when I go to read the memory using ReadProcessMemory. it returns an error 299. Code: ReadProcessMemory(handle, (LPCVOID) (base + 0x25572B0), &OutValue, sizeof(DWORD64), NULL);
but this always fails and GetLastError just says 299 which I read is because of partial copy. when i look at the address of (base + 0x25572B0) using cheat engine, it gets a valid value. I would very much appreciate it if someone could help me with this or point me in the right direction so I can solve this one thing. I tried multiple addresses and stuff but it always returns error 299. |
|||||||||||
ShadowLegion is offline |
|
#2 |
|||||||||||
GDPR_Anonymous MVP Join Date: Sep 2005
Reputation: 425834 Points: 1, Level: 1 Level up: 0%, 1 Points needed Activity: 0% |
Are you compiling for x64? According to other threads, this can be a symptom — x64 ReadProcessMemory — GetLastError == 299 A bit of other searching says the page guard flag might be set on the page you’re trying to read from — https://stackoverflow.com/questions/…tlasterror-299 For other readers, OP PM’d me with this issue and I referred him to make a thread — he has BE disabled. |
|||||||||||
GDPR_Anonymous is offline |
|
#3 |
|||||||||||
ShadowLegion n00bie
Join Date: Nov 2018
Reputation: 10 Points: 79, Level: 1 Level up: 20%, 321 Points needed Activity: 9.1% |
Quote:
Originally Posted by adamwthe1st Are you compiling for x64? According to other threads, this can be a symptom — x64 ReadProcessMemory — GetLastError == 299 A bit of other searching says the page guard flag might be set on the page you’re trying to read from — https://stackoverflow.com/questions/…tlasterror-299 For other readers, OP PM’d me with this issue and I referred him to make a thread — he has BE disabled. fuck me, I’m stupid. sorry for wasting your time man. yeah I was compiling for x64 but in my memory class that I created for csgo was taking in a DWORD address so even though I using DWORD64 for arma 3, it was getting truncated. I had Code: template<class T> bool MyMem::Readmem(DWORD Address, T& OutValue) { return ReadProcessMemory(_ProcHandle, (LPCVOID)Address, &OutValue, sizeof(T), NULL); } so now i have Code: template<class D, class T> bool MyMem::Readmem(D Address, T& OutValue) { return ReadProcessMemory(_ProcHandle, (LPCVOID)Address, &OutValue, sizeof(T), NULL); } |
|||||||||||
ShadowLegion is offline |
|
#4 |
|||||||||||
GDPR_Anonymous MVP Join Date: Sep 2005
Reputation: 425834 Points: 1, Level: 1 Level up: 0%, 1 Points needed Activity: 0% |
Quote:
Originally Posted by ShadowLegion fuck me, I’m stupid. sorry for wasting your time man. yeah I was compiling for x64 but in my memory class that I created for csgo was taking in a DWORD address so even though I using DWORD64 for arma 3, it was getting truncated. I had Code: template<class T> bool MyMem::Readmem(DWORD Address, T& OutValue) { return ReadProcessMemory(_ProcHandle, (LPCVOID)Address, &OutValue, sizeof(T), NULL); } so now i have Code: template<class D, class T> bool MyMem::Readmem(D Address, T& OutValue) { return ReadProcessMemory(_ProcHandle, (LPCVOID)Address, &OutValue, sizeof(T), NULL); } No worries — happy to help :^) |
|||||||||||
GDPR_Anonymous is offline |
|
#5 |
|||||||||||
ShadowLegion n00bie
Join Date: Nov 2018
Reputation: 10 Points: 79, Level: 1 Level up: 20%, 321 Points needed Activity: 9.1% |
also not 100% sure if it was that since I’m pretty sure i tried changing it before, might have been the launch params for arma3 since i had some changed and i reset them to all default now. |
|||||||||||
ShadowLegion is offline |
Similar Threads |
||||
Thread | Thread Starter | Forum | Replies | Last Post |
[Help] world to screen (2d world) | dropitem | General Programming and Reversing | 0 | 31st May 2018 06:37 PM |
[Help] Stuck on Createtoolhelp32snapshot error 299, invalid handle returned, please help. | Cepg | C and C++ | 1 | 28th March 2015 04:45 PM |
[Coding] RPM Error Code 299 | Jman420 | General Programming and Reversing | 9 | 5th February 2014 07:57 PM |
[Help] WriteProcessMemory returns error 299 | amitsl | Counterstrike Global Offensive | 8 | 21st December 2013 01:09 PM |
[Help] x64 ReadProcessMemory — GetLastError == 299 | Hooch | C and C++ | 3 | 31st October 2013 02:42 PM |
Tags |
base, read, error, dword64, world, basically, returns, address, 0x25572b0, offset |
«
Previous Thread
|
Next Thread
»
Forum Jump |
All times are GMT. The time now is 01:33 AM.
Contact Us —
Toggle Dark Theme
Terms of Use Information Privacy Policy Information
Copyright ©2000-2023, Unknowncheats� UKCS #312436
no new posts
Пытаясь прочитать имя сущности из игровой памяти, указатели на 100% корректны, если использовать ce для проверки.
не имеет проблем с чтением / записью значений типа float / integer
32-битный процесс, игра также — пробовал компилировать код в x64, не помогло.
GetLastError()
возвращает номер 299
ERROR_PARTIAL_COPY
299 (0x12B)
Only part of a ReadProcessMemory or WriteProcessMemory request was completed.
Есть идеи, что может быть причиной?
код ниже
#include <windows.h>
#include <TlHelp32.h>
#include <iostream>
#include <string>
#include <time.h>
#include <tchar.h>using namespace std;
DWORD dwGetModuleBaseAddress(DWORD dwProcessIdentifier, TCHAR *lpszModuleName);
string readName(HANDLE handlez, DWORD base, DWORD bp, DWORD ofset1, DWORD ofset2, DWORD ofsetInc);int main()
{
DWORD baseOfset = 0x60DE90;
DWORD ofset1 = 0x4c4;
DWORD ofset2 = 0x6a0;
DWORD ofset3 = 0x18;HWND window = NULL;//FindWindow(0, _TEXT("Gothic II - 2.6 (pol)"));
DWORD pID = 0;
DWORD dwBP = NULL;
HANDLE handle = NULL;// OpenProcess(PROCESS_ALL_ACCESS, FALSE, pID);
string gameStatus;
int refresher = clock();
gameStatus = "Waiting for game";window = FindWindow(0, _TEXT("Gothic II - 2.6 (pol)")); // window title
if (window)
{
GetWindowThreadProcessId(window, &pID);
if (pID != 0)
{
handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pID);
dwBP = dwGetModuleBaseAddress(pID, _T("Gothic2.exe")); // proc name
if (handle == INVALID_HANDLE_VALUE || handle == NULL || dwBP == NULL)
{
gameStatus = "No handle";
}
else
{
gameStatus = "OK";
}
}
else
{
gameStatus = "No access";
}
}
else
{
gameStatus = "No window";
}while (!GetAsyncKeyState(VK_DELETE))
{
if (clock() - refresher > 1000)
{
refresher = clock();cout << gameStatus << endl;
string elo="a";elo = readName(handle, dwBP, baseOfset, ofset1, ofset2, ofset3);
if (elo == "a")
{
cout << ":(n";
}
cout << "Name: " << elo <<".n";
cout << "Name: " << &elo << ".n" << endl;
system("pause");
}
}CloseHandle(handle);
}
string readName(HANDLE handlez, DWORD base, DWORD bp, DWORD ofset1, DWORD ofset2, DWORD ofsetInc)
{
DWORD adresik;
ReadProcessMemory(handlez, (LPCVOID)(base + bp), &adresik, sizeof(DWORD), NULL); // base adress + base pointer
adresik += ofset1; //1st lvl pointer
ReadProcessMemory(handlez, (LPCVOID)adresik, &adresik, sizeof(DWORD), NULL);
adresik += ofset2; // 2nd lvl pointer
ReadProcessMemory(handlez, (LPCVOID)adresik, &adresik, sizeof(DWORD), NULL);
adresik += ofsetInc; // 3rd lvl pointer this goes up +=20
ReadProcessMemory(handlez, (LPCVOID)adresik, &adresik, sizeof(DWORD), NULL);
adresik += 0x12c; // 4th static pointer
ReadProcessMemory(handlez, (LPCVOID)adresik, &adresik, sizeof(DWORD), NULL);
adresik += 0x0; // 5th static pointer
ReadProcessMemory(handlez, (LPCVOID)adresik, &adresik, sizeof(DWORD), NULL);string papa;
ReadProcessMemory(handlez, (LPCVOID)adresik, &papa, sizeof(string), NULL); // get name
DWORD ero = GetLastError();
cout << ero << endl;
return papa; // return name}DWORD dwGetModuleBaseAddress(DWORD dwProcessIdentifier, TCHAR *lpszModuleName)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwProcessIdentifier);
DWORD dwModuleBaseAddress = 0;
if (hSnapshot != INVALID_HANDLE_VALUE)
{
MODULEENTRY32 ModuleEntry32 = { 0 };
ModuleEntry32.dwSize = sizeof(MODULEENTRY32);
if (Module32First(hSnapshot, &ModuleEntry32))
{
do
{
if (_tcscmp(ModuleEntry32.szModule, lpszModuleName) == 0)
{
dwModuleBaseAddress = (DWORD)ModuleEntry32.modBaseAddr;
break;
}
} while (Module32Next(hSnapshot, &ModuleEntry32));
}
CloseHandle(hSnapshot);
}
return dwModuleBaseAddress;
}
-2
Решение
Вы не можете просто скопировать c-строки в ячейку памяти std :: string.
То, что вы хотите, это, вероятно, что-то вроде этого (при условии, что на самом деле это строка с нулевым окончанием, которую вы читаете):
const int MAX_SIZE = 512;
const char buffer[MAX_SIZE];
string papa;
ReadProcessMemory(handlez, (LPCVOID)adresik, buffer, MAX_SIZE, NULL); // get name
papa = buffer;
Также, если строка находится прямо вокруг границы страницы, вам может понадобиться читать ее побайтно или небольшими кусками, пока вы не найдете завершающий нулевой символ. Так что, если вы можете найти длину строки в любом месте, я бы посоветовал вам прочитать и использовать ее.
1
Другие решения
Ура, приятель, это помогло мне!
ее исправил код readName, на всякий случай;)
максимальный размер изменен до 15, так как ни один NPC / монстр в игре не имеет имени более 15 символов.
строка readName (HANDLE handlez, база DWORD, DWORD bp, DWORD ofset1, DWORD ofset2, DWORD ofsetInc)
{
DWORD adresik;
ReadProcessMemory(handlez, (LPCVOID)(base + bp), &adresik, sizeof(DWORD), NULL); // base adress + base pointer
adresik += ofset1; //1st lvl pointer
ReadProcessMemory(handlez, (LPCVOID)adresik, &adresik, sizeof(DWORD), NULL);
adresik += ofset2; // 2nd lvl pointer
ReadProcessMemory(handlez, (LPCVOID)adresik, &adresik, sizeof(DWORD), NULL);
adresik += ofsetInc; // 3rd lvl pointer this goes up +=20
ReadProcessMemory(handlez, (LPCVOID)adresik, &adresik, sizeof(DWORD), NULL);
adresik += 0x12c; // 4th static pointer
ReadProcessMemory(handlez, (LPCVOID)adresik, &adresik, sizeof(DWORD), NULL);
adresik += 0x0; // 5th static pointerstring papa;
const int max_size = 15;
const char buffer[max_size] = { 'b' };ReadProcessMemory(handlez, (LPCVOID)adresik, (void*)&buffer, sizeof(buffer), NULL); // get name
papa = buffer;
DWORD ero = GetLastError();
cout << ero << endl;
return papa; // return name}
0