io_uring user_data field is always zero - c

I'm playing around with io_uring, https://kernel.dk/io_uring.pdf, to see if it can be used for async file I/O for logging. This is a simple program that opens a file, stats the file, and then reads the first 4k from the file. This program runs to completion successfully when the file exists and is readable. But the user_data field in the completion queue entry is always zero. The documentation for io_uring says:
user_data is common across op-codes, and is untouched by the kernel. It's simply copied to the completion event, cqe, when a completion event is posted for this request.
Since the completions are not ordered the user_data field is needed to match completions with submissions. If the field is always zero then how can it be used?
#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <liburing.h>
#include <stdlib.h>
int main() {
struct io_uring ring;
// see man io_uring_setup for what this does
auto ret = io_uring_queue_init(64, &ring, 0);
if (ret) {
perror("Failed initialize uring.");
exit(1);
}
std::cout << "I/O uring initialized successfully. " << std::endl;
auto directory_fd = open("/tmp", O_RDONLY);
if (directory_fd < 0) {
perror("Failed to open current directory.");
exit(1);
}
struct io_uring_sqe *submission_queue_entry = io_uring_get_sqe(&ring);
submission_queue_entry->user_data = 100;
io_uring_prep_openat(submission_queue_entry, directory_fd, "stuff", O_RDONLY, 0);
submission_queue_entry = io_uring_get_sqe(&ring);
submission_queue_entry->user_data = 1000;
struct statx statx_info;
io_uring_prep_statx(submission_queue_entry, directory_fd, "stuff", 0, STATX_SIZE, &statx_info);
//TODO: what does this actually return?
auto submit_error = io_uring_submit(&ring);
if (submit_error != 2) {
std::cerr << strerror(submit_error) << std::endl;
exit(2);
}
int file_fd = -1;
uint32_t responses = 0;
while (responses != 2) {
struct io_uring_cqe *completion_queue_entry = 0;
auto wait_return = io_uring_wait_cqe(&ring, &completion_queue_entry);
if (wait_return) {
std::cerr << "Completion queue wait error. " << std::endl;
exit(2);
}
std::cout << "user data " << completion_queue_entry->user_data << " entry ptr " << completion_queue_entry << " ret " << completion_queue_entry->res << std::endl;
std::cout << "size " << statx_info.stx_size << std::endl;
io_uring_cqe_seen(&ring, completion_queue_entry);
if (completion_queue_entry->res > 0) {
file_fd = completion_queue_entry->res;
}
responses++;
}
submission_queue_entry = io_uring_get_sqe(&ring);
submission_queue_entry->user_data = 66666;
char buf[1024 * 4];
io_uring_prep_read(submission_queue_entry, file_fd, buf, 1024 * 4, 0);
io_uring_submit(&ring);
struct io_uring_cqe* read_entry = 0;
auto read_wait_rv = io_uring_wait_cqe(&ring, &read_entry);
if (read_wait_rv) {
std::cerr << "Error waiting for read to complete." << std::endl;
exit(2);
}
std::cout << "Read user data " << read_entry->user_data << " completed with " << read_entry->res << std::endl;
if (read_entry->res < 0) {
std::cout << "Read error " << strerror(-read_entry->res) << std::endl;
}
}
Output
I/O uring initialized successfully.
user data 0 entry ptr 0x7f4e3158c140 ret 5
size 1048576
user data 0 entry ptr 0x7f4e3158c150 ret 0
size 1048576
Read user data 0 completed with 4096

What happens if you try and set user_data after your calls to io_uring_prep_openat()/io_uring_prep_statx()?
I ask this because doing a Google search for io_uring_prep_statx suggests it comes from liburing library.
Searching the liburing source for io_uring_prep_openat leads us to a definition of io_uring_prep_openat() in liburing.h:
static inline void io_uring_prep_openat(struct io_uring_sqe *sqe, int dfd,
const char *path, int flags, mode_t mode)
{
io_uring_prep_rw(IORING_OP_OPENAT, sqe, dfd, path, mode, 0);
sqe->open_flags = flags;
}
Searching the liburing source for io_uring_prep_statx leads to a definition of io_uring_prep_statx():
static inline void io_uring_prep_statx(struct io_uring_sqe *sqe, int dfd,
const char *path, int flags, unsigned mask,
struct statx *statxbuf)
{
io_uring_prep_rw(IORING_OP_STATX, sqe, dfd, path, mask,
(__u64) (unsigned long) statxbuf);
sqe->statx_flags = flags;
}
Chasing the calls gets us to the definition of io_uring_prep_rw:
static inline void io_uring_prep_rw(int op, struct io_uring_sqe *sqe, int fd,
const void *addr, unsigned len,
__u64 offset)
{
sqe->opcode = op;
sqe->flags = 0;
sqe->ioprio = 0;
sqe->fd = fd;
sqe->off = offset;
sqe->addr = (unsigned long) addr;
sqe->len = len;
sqe->rw_flags = 0;
sqe->user_data = 0;
sqe->__pad2[0] = sqe->__pad2[1] = sqe->__pad2[2] = 0;
}
PS: I notice you have a comment that says
//TODO: what does this actually return?
auto submit_error = io_uring_submit(&ring);
Well, if we search the liburing repo for "int io_uring_submit" we come across the following in src/queue.c:
/*
* Submit sqes acquired from io_uring_get_sqe() to the kernel.
*
* Returns number of sqes submitted
*/
int io_uring_submit(struct io_uring *ring)
This ultimately chains calls down to io_uring_enter() syscall (raw man page) so you can read that for more detail.
Update: The questioner says moving the assignment solved their problem so I invested some time thinking about the text they quoted. Upon further reading I have picked up a subtlety (emphasis added):
user_data is common across op-codes, and is untouched by the kernel. It's simply copied to the completion event, cqe, when a completion event is posted for this request.
There's a similar statement earlier in the document (again emphasis added):
The cqe contains a user_data field. This field is carried from the
initial request submission, and can contain any information that the the application needs to identify said request. One common use case is to have it be the pointer of the original request. The kernel will not touch this field, it's simply carried straight from submission to completion event.
The statement applies to io_uring kernel syscalls but io_uring_prep_openat() / io_uring_prep_statx() are liburing functions. liburing is a userspace helper library so the statements above about user_data do not have to apply to all liburing functions.
If the field is always zero then how can it be used?
The field is being zeroed by certain liburing preparation helper functions. In this case it can be only be set (and retain the new value) after those helper function have been called. The io_uring kernel syscalls behave per the quote.

Related

How does /proc/{pid}/stack work in linux? [duplicate]

I'm trying to port a program from Windows to Linux.
I encountered a problem when I found out that there isn't a "real" ReadProcessMemory counterpart on Linux; I searched for an alternative and I found ptrace, a powerful process debugger.
I quickly coded two small console applications in C++ to test ptrace, before using it in the program.
TestApp
This is the tracee; it keeps printing two integers every 50 milliseconds while increasing their value by 1 every time.
#include <QCoreApplication>
#include <QThread>
#include <iostream>
using namespace std;
class Sleeper : public QThread
{
public:
static void usleep(unsigned long usecs){QThread::usleep(usecs);}
static void msleep(unsigned long msecs){QThread::msleep(msecs);}
static void sleep(unsigned long secs){QThread::sleep(secs);}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int value = 145;
int i = 0;
do {
cout << "i: " << i << " " << "Value: " << value << endl;
value++;
i++;
Sleeper::msleep(50);
} while (true);
return a.exec();
}
MemoryTest
This is the tracer; it asks for the process name and retrieves the PID using the command pidof -s, then ptrace attaches to the process and retrieves the memory address' value every 500 milliseconds, for 10 times.
#include <QCoreApplication>
#include <QThread>
#include <iostream>
#include <string>
#include <sys/ptrace.h>
#include <errno.h>
using namespace std;
class Sleeper : public QThread
{
public:
static void usleep(unsigned long usecs){QThread::usleep(usecs);}
static void msleep(unsigned long msecs){QThread::msleep(msecs);}
static void sleep(unsigned long secs){QThread::sleep(secs);}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
char process_name[50];
cout << "Process name: ";
cin >> process_name;
char command[sizeof(process_name) + sizeof("pidof -s ")];
snprintf(command, sizeof(command), "pidof -s %s", process_name);
FILE* shell = popen(command, "r");
char pidI[sizeof(shell)];
fgets(pidI, sizeof(pidI), shell);
pclose(shell);
pid_t pid = atoi(pidI);
cout << "The PID is " << pid << endl;
long status = ptrace(PTRACE_ATTACH, pid, NULL, NULL);
cout << "Status: " << status << endl;
cout << "Error: " << errno << endl;
unsigned long addr = 0x012345; // Example address, not the true one
int i = 0;
do {
status = ptrace(PTRACE_PEEKDATA, pid, addr, NULL);
cout << "Status: " << status << endl;
cout << "Error: " << errno << endl;
i++;
Sleeper::msleep(500);
} while (i < 10);
status = ptrace(PTRACE_DETACH, pid, NULL, NULL);
cout << "Status: " << status << endl;
cout << "Error: " << errno << endl;
return a.exec();
}
Everything works fine, but TestApp is paused (SIGSTOP) until ptrace detaches from it.
Also, when it attaches to the process, the status is 0 and the error is 2; the first time it tries to retrieve the memory address value it fails with status -1 and error 3. Is it normal?
Is there a way to prevent ptrace from sending the SIGSTOP signal to the process?
I already tried using PTRACE_SEIZE instead of PTRACE_ATTACH, but it doesn't work: status -1 and error 3.
Update: Using Sleeper in MemoryTest before the "do-while" loop fixes the problem of the first memory address value retrieval, even if the value of seconds, milliseconds or microseconds is 0. Why?
After a lot of research I'm pretty sure that there isn't a way to use ptrace without stopping the process.
I found a real ReadProcessMemory counterpart, called process_vm_readv, which is much more simple.
I'm posting the code in the hope of helping someone who is in my (previous) situation.
Many thanks to mkrautz for his help coding MemoryTest with this beautiful function.
#include <QCoreApplication>
#include <QThread>
#include <sys/uio.h>
#include <stdint.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <iostream>
using namespace std;
class Sleeper : public QThread
{
public:
static void usleep(unsigned long usecs){QThread::usleep(usecs);}
static void msleep(unsigned long msecs){QThread::msleep(msecs);}
static void sleep(unsigned long secs){QThread::sleep(secs);}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
char process_name[50];
cout << "Process name: ";
cin >> process_name;
char command[sizeof(process_name) + sizeof("pidof -s ")];
snprintf(command, sizeof(command), "pidof -s %s", process_name);
FILE* shell = popen(command, "r");
char pidI[sizeof(shell)];
fgets(pidI, sizeof(pidI), shell);
pclose(shell);
pid_t pid = atoi(pidI);
cout << "The PID is " << pid << endl;
if (pid == 0)
return false;
struct iovec in;
in.iov_base = (void *) 0x012345; // Example address, not the true one
in.iov_len = 4;
uint32_t foo;
struct iovec out;
out.iov_base = &foo;
out.iov_len = sizeof(foo);
do {
ssize_t nread = process_vm_readv(pid, &out, 1, &in, 1, 0);
if (nread == -1) {
fprintf(stderr, "error: %s", strerror(errno));
} else if (nread != in.iov_len) {
fprintf(stderr, "error: short read of %li bytes", (ssize_t)nread);
}
cout << foo << endl;
Sleeper::msleep(500);
} while (true);
return a.exec();
}
Davide,
Have you had a look at the /proc filesystem? It contains memory map files that can be used to peek at the full process space. You can also write in the space to set a breakpoint. There is a wealth of other information in /proc as well.
The PTRACE_CONT command can be used to continue a process. Generally, the target will be paused with a PTRACE_ATTACH when the debugger attaches.
The man page says PTRACE_SIEZE should not pause the process. What flavor and version of Linux are you using? PTRACE_SIEZE has been around for quite awhile so I'm not sure why you are having trouble there.
I note the addr value is set to 0x12345. Is this a valid address in the target space? Or was that just an example? How is the stack address of interest (&value) communicated between the two processes?
I'm not too sure about the return codes. Generally a 0 means all is well, the errno may just be a hangover value from the last error.
--Matt

libevent fires send when it receveives packet

I am building MQTT broker now.
SO, when I am receiving a MQTT packet from the client.That packet is also being send simultaneously.I can't find out the reason why. I am posting my code snippet below please do point out where am I going wrong .
static void onServEcho(struct bufferevent* bev, void* cbarg) {
EvBufferEvent evbuf(bev);
struct evbuffer *input = bufferevent_get_input(bev);
struct evbuffer *output = bufferevent_get_output(bev);
size_t len = evbuffer_get_length(input);
evutil_socket_t accept_fd = bufferevent_getfd(bev);
// Copy all the data from the input buffer to the output buffer.
char *data;
//data =(char *) malloc(len);
data = new char[len];
// cout<<"dasd"<<data<<endl;
evbuffer_copyout(input, data, len);
// evbuf.copy_data(input, data, len);
char converted[len];
int i;
for (i = 0; i < len; i++) {
sprintf(&converted[i * 2], "%02X", data[i]);
// cout<<"data is"<< data[i]<<endl;
*/
}
// std::stringstream stream;
// char packet[len];
//cout << "the hex data is" << converted << "with size" << len << endl;
// for(i=0;i<(2*len;i=i+2) {
// string connect_char;
// connect_char.insert(0,"0x");
/// connect_char.append(converted,i,2);
//char *buffer=static_cast<char*>(connect_char);
/// unsigned int buffer=strtoul(connect_char.c_str(), NULL, 16);
// char W = static_cast<char>(buffer);
// cout<<"the characterr is "<<W<<endl;
// }
//char *packet=convert(converted,20);
//cout<<"the packet converted is "<<packet<<endl;
string connect_comd;
//connect_comd="0x";
connect_comd.insert(0, "0x");
connect_comd.append(converted, 0, 2);
// strcpy(connect_comd,converted[0]);
// strcpy(connect_comd,converted[1]);
//unsigned int buf = strtoul(connect_comd.c_str(), NULL, 16);
//int buf=0x10;
int message_type = (ToBits(data[0]).to_ulong());
// cout<<"the message type received now is"<<GET_MESSAGE(data[0])<<endl;
//cout << "the connectcommand is" << buf << endl;
cout << "the message flag received now is" << ToBits(data[0]) << endl;
if (GET_MESSAGE(message_type) == CONNECT) {
cout << "connect packet received from mqtt client" << endl;
ConnectPack_Parser(data, len, accept_fd);
} else if (GET_MESSAGE(message_type) == SUBSCRIBE) {
cout << "subscribe packet received from mqtt client" << endl;
SubscribePack_Parser(data, len, accept_fd);
}
// }
// hexify()
//evbuffer_add_buffer(output, input);
evbuffer_add_buffer(output, input);
//evbuffer_remove_buffer(input,output,len);
free(data);
}
edit:
i am not just posting the code for a fix to the code but i am cluless as to how to avoid that send from the server end using lib event .
the line 'evbuffer_add_buffer(output, input);' automatically sends the received packet which i can trace from the wireshark.The thing is this line according to the libevent documentation is needed for optimal performance.
the code is working for now.I am posting it for those who may need it. If you only want the read operation don't use the ' evbuffer_add_buffer(output, input)' code since this instantly writes it to the socket or in other words sends the data to the connected client so the CONNECT packet was send simultaneously

inotify event IN_MODIFY occurring twice for tftp put

I am using inotify to listen to modifications to a file.
When I test file modification, program is working fine.
# echo "test" > /tftpboot/.TEST
Output:
Read 16 data
IN_MODIFY
But when I do tftp put, two events are generated:
tftp> put .TEST
Sent 6 bytes in 0.1 seconds
tftp>
Output:
Read 16 data
IN_MODIFY
Read 16 data
IN_MODIFY
Any idea how to avoid the duplicate notification?
Code is given below:
#include <sys/inotify.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <iostream>
using namespace std;
int main(int argc, const char *argv[])
{
int fd = inotify_init();
if (fd < 0)
{
cout << "inotify_init failed\n";
return 1;
}
int wd = inotify_add_watch(fd, "/tftpboot/.TEST", IN_MODIFY);
if (wd < 0)
{
cout << "inotify_add_watch failed\n";
return 1;
}
while (true)
{
char buffer[sizeof(struct inotify_event) + NAME_MAX + 1] = {0};
ssize_t length;
do
{
length = read( fd, buffer, sizeof(struct inotify_event));
cout << "Read " << length << " data\n";
}while (length < 0);
if (length < 0)
{
cout << "read failed\n";
return 1;
}
struct inotify_event *event = ( struct inotify_event * ) buffer;
if ( event->mask & IN_ACCESS )
cout << "IN_ACCESS\n";
if ( event->mask & IN_CLOSE_WRITE )
cout << "IN_CLOSE_WRITE\n";
if ( event->mask & IN_CLOSE_NOWRITE )
cout << "IN_CLOSE_NOWRITE\n";
if ( event->mask & IN_MODIFY )
cout << "IN_MODIFY \n";
if ( event->mask & IN_OPEN )
cout << "IN_OPEN\n";
}
inotify_rm_watch( fd, wd );
close (fd);
return 0;
}
try using IN_CLOSE_WRITE instead
Q: What is the difference between IN_MODIFY and IN_CLOSE_WRITE?
The
IN_MODIFY event is emitted on a file content change (e.g. via the
write() syscall) while IN_CLOSE_WRITE occurs on closing the changed
file. It means each change operation causes one IN_MODIFY event (it
may occur many times during manipulations with an open file) whereas
IN_CLOSE_WRITE is emitted only once (on closing the file).
Q: Is it better to use IN_MODIFY or IN_CLOSE_WRITE?
It varies from
case to case. Usually it is more suitable to use IN_CLOSE_WRITE
because if emitted the all changes on the appropriate file are safely
written inside the file. The IN_MODIFY event needn't mean that a file
change is finished (data may remain in memory buffers in the
application). On the other hand, many logs and similar files must be
monitored using IN_MODIFY - in such cases where these files are
permanently open and thus no IN_CLOSE_WRITE can be emitted.
source

Generate elliptic curve key pairs (EC_KEY_generate_key) in multiple threads using OpenSSL C library

I want to generate many ec key pairs. Speeding up the process a bit, I rewrote my appication to use multiple threads for this job. Here is a code snippet of the way each thread wants to generate the keys:
(...)
EC_KEY* _ec_key = EC_KEY_new();
EC_GROUP* ec_group_new = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
const EC_GROUP* ec_group = ec_group_new;
if (!EC_KEY_set_group(ec_key,ec_group))
DieWithError("Error in initializeCrypto, EC_KEY_set_group failed!");
// Segfault at this position
if(!EC_KEY_generate_key(ec_key))
DieWithError ("Error in generateKeys, EC_KEY_generate_key failed!");
(...)
EC_GROUP_free(ec_group_new);
EC_KEY_free(ec_key);
Ok at the first glance, everything seemed to work fine. The applications ran twice as fast using four threads on my i5 520m. But then after 3-4 E6 key generations it suddenly segfaults. If I lock the EC_KEY_generate_key operation there is no segfault anymore, but the advantage of using multiple threads is gone. Now my questions. Is it possible split the creation of keys into multiple threads without corrupting memory? I didn't found any information using google. The SSL Docu doesn't mention anything about thread-safety, though. Any help is highly appreciated. thx
// Segfault at this position
if(!EC_KEY_generate_key(ec_key))
DieWithError ("Error in generateKeys, EC_KEY_generate_key failed!");
...
... But then after 3-4 E6 key generations it suddenly segfaults.
You are using OpenSSL's random number generator, and its not thread safe. Below is from cryptlib.c around line 125. Notice the random number generators and the elliptic curve gear make the list.
/* real #defines in crypto.h, keep these upto date */
static const char* const lock_names[CRYPTO_NUM_LOCKS] =
{
"<<ERROR>>",
"err",
"ex_data",
"x509",
"x509_info",
"x509_pkey",
"x509_crl",
"x509_req",
...
"ssl_ctx",
"ssl_session",
"ssl",
"ssl_method",
"rand",
"rand2",
...
"ecdsa",
"ec",
"ecdh",
"bn",
"ec_pre_comp",
...
};
You have to explicitly set the locks. See OpenSSL's threads(3).
Is it possible split the creation of keys into multiple threads without corrupting memory?
Yes, but you have to use OpenSSL's locking mechanism.
Here's what my OpenSSL initialization routine looks like in C++. It initializes the locks and sets the callbacks.
pthread_mutex_t s_locks[CRYPTO_NUM_LOCKS] = { };
void Initialize()
{
static once_flag init;
std::call_once(init, []() {
// Standard OpenSSL library init
OPENSSL_no_config();
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_ssl_algorithms();
// Lock setup
LOCK_setup();
CALLBACK_setup();
});
}
void LOCK_setup()
{
ASSERT(CRYPTO_NUM_LOCKS == CRYPTO_num_locks());
if(CRYPTO_NUM_LOCKS != CRYPTO_num_locks())
throw runtime_error("CRYPTO_NUM_LOCKS mismatch");
for(unsigned i = 0; i < CRYPTO_NUM_LOCKS; ++i)
{
int rc = pthread_mutex_init(&s_locks[i], NULL);
ASSERT(rc == 0);
if(!(rc == 0))
throw runtime_error("pthread_mutex_init");
}
}
void CALLBACK_setup()
{
CRYPTO_set_id_callback(&ThreadIdFnc);
CRYPTO_set_locking_callback(&LockingFnc);
}
void LockingFnc(int mode, int idx, const char* file, int line)
{
ASSERT(mode == CRYPTO_LOCK || mode == CRYPTO_UNLOCK);
ASSERT(CRYPTO_NUM_LOCKS == CRYPTO_num_locks());
ASSERT(idx >= 0 && idx < CRYPTO_NUM_LOCKS);
if(!(idx >= 0 && idx < CRYPTO_NUM_LOCKS))
{
ostringstream oss;
oss << "LockingFnc: lock failed with bad index ";
oss << idx << ". File: " << (file ? file : "Unknown");
oss << ", line: " << line;
// Log oss.str()
return;
}
if((mode & CRYPTO_LOCK) == CRYPTO_LOCK)
{
int rc = pthread_mutex_lock(&s_locks[idx]);
int err = errno;
ASSERT(rc == 0);
if(!(rc == 0))
{
ostringstream oss;
oss << "LockingFnc: lock failed with error ";
oss << err << ". File: " << (file ? file : "Unknown");
oss << ", line: " << line;
throw runtime_error(oss.str());
}
}
else if((mode & CRYPTO_UNLOCK) == CRYPTO_UNLOCK)
{
int rc = pthread_mutex_unlock(&s_locks[idx]);
int err = errno;
ASSERT(rc == 0);
if(!(rc == 0))
{
ostringstream oss;
oss << "LockingFnc: unlock failed with error ";
oss << err << ". File: " << (file ? file : "Unknown");
oss << ", line: " << line;
throw runtime_error(oss.str());
}
}
}
unsigned long ThreadIdFnc()
{
#if defined(AC_OS_APPLE)
ASSERT(sizeof(unsigned long) >= sizeof(pid_t));
return static_cast<unsigned long>(pthread_mach_thread_np(pthread_self()));
#elif defined(AC_OS_STARNIX)
ASSERT(sizeof(unsigned long) >= sizeof(pid_t));
return static_cast<unsigned long>(gettid());
#else
# error "Unsupported platform"
#endif
}
If you are not using libssl, then forgo the call to SSL_library_init. All libcrypto needs is the call to OpenSSL_add_all_algorithms to initialize.
The SSL Documentation doesn't mention anything about thread-safety, though.
Yeah, the docs leave something to be desired at times. I know a bunch of folks are working on improving it through a wiki run by the OpenSSL Foundation. Matt Caswell has done a lot of work in simply documenting the elliptic curve stuff at http://wiki.openssl.org/index.php/Elliptic_Curve_Cryptography. He's also responsible for the POD files and MAN pages. Keep in mind that Matt did not write any of the code - he's just documenting it for others.
There's a page on initialization, but it does not have the code for the locks. Its on my TODO list. See http://wiki.openssl.org/index.php/Library_Initialization.

Finding address range of process ( C / Windows )

I am trying to inspect Notepad's memory in real time, so I can detect when a specific string is written there.
I guess step 1 would be to find out what is the memory range of that process.
This is what I have until now :
int main()
{
MEMORY_BASIC_INFORMATION meminfo;
unsigned char *addr = 0;
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,7280);
VirtualQueryEx(hProcess,addr,&meminfo,sizeof(meminfo));
CloseHandle(hProcess);
}
I suppose I need to manipulate meminfo in some way to grab the information from there.
I need to find the full address range so I can iterate trough the addresses and search for the string.
Any help will be much appreciated, I apologize in advance if this is a stupid question but I'm just starting out with C.
Thanks
To get a list of all allocated, valid memory regions you can use VirtualQueryEx in a while loop like so:
#include <iostream>
#include <windows.h>
#include <TlHelp32.h>
#include <tchar.h>
DWORD GetProcId(const TCHAR* procName)
{
DWORD procId = 0;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 procEntry;
procEntry.dwSize = sizeof(procEntry);
if (Process32First(hSnap, &procEntry))
{
do
{
if (!_tcsicmp(procEntry.szExeFile, procName))
{
procId = procEntry.th32ProcessID;
break;
}
} while (Process32Next(hSnap, &procEntry));
}
}
CloseHandle(hSnap);
return procId;
}
int main()
{
DWORD procid = GetProcId("ac_client.exe");
MEMORY_BASIC_INFORMATION meminfo;
unsigned char* addr = 0;
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
MEMORY_BASIC_INFORMATION mbi;
while (VirtualQueryEx(hProc, addr, &mbi, sizeof(mbi)))
{
if (mbi.State != MEM_COMMIT || mbi.Protect == PAGE_NOACCESS)
{
std::cout << "base : 0x" << std::hex << mbi.BaseAddress << " end : 0x" << std::hex << (uintptr_t)mbi.BaseAddress + mbi.RegionSize << "\n";
}
addr += mbi.RegionSize;
}
CloseHandle(hProc);
}

Resources