Hi all I might have a hard time explaining this, but I will try my best.
I am creating a DLL that will be injected into a program. In order to access the data I want from inside the DLL I mapped the data to a "base address" in which is a pointer to another address. From there I have to increment that address by 0x34 in order to access my data. I figured i could use structs to my advantage but it doesnt seem to be working. The problem is that I can't seem to figure out how to increment the second address to obtain the final pointer to my data.
What I have is this
typedef unsigned char BYTE;
typedef struct
{
DWORD Some_Int;
//big struct of DWORDS simulating what is in the applicaiton.
//shortened for posting
}DATA;
typedef struct
{
BYTE Unknown[0x34];
DATA *p_data;
}VARBASE;
DWORD WINAPI function()
{
VARBASE *Stats = (VARBASE*)0x00BBC9CC;
char lol[1000];
sprintf(lol, "stats pointer: %p | DATA pointer: %p", Stats, Stats->p_data);
SomeFunction(lol); //wrapper for MessageBoxA()
return NULL;
}
Stats points to the right address, but I cant manage to read 0x34 bytes of data (or increment the pointer 0x34) in order to get the second pointer to my data set. When I use this current code p_data gets set to 0000155A or something similar, when it should be in the 0A0*** range, which causes a segfault when read. I know my math is correct because Ive opened the application up in a memory mapper like CheatEngine and I can specifically add the base pointer -> address + 0x34 -> my data from inside CheatEngine.
Is there a easier way to go about this rather then using a base structure to point to my data? Basically its pointer->pointer+0x34->data and the problem I am facing is that I cannot increment the second pointer and set it so I can access my data.
Are you aware that padding may exist between the two members of your struct? This is one example of "How do I do something the wrong way?". Perhaps you'd be better off telling us which problem your program is to solve.
If you're certain that 0x00BBC9CC + 34 is suitably aligned to point to a DWORD *, then why not jump straight to the point: DWORD **some_int = 0x00BBC9CC + 34;..? Where are you getting this address from, by the way? Unfortunately, Win32 C programmers rarely actually produce C programs.
I fixed the problem. I needed to deference the base address pointer and pass that value to my VARBASE structure.
DWORD WINAPI function()
{
FILE *fp;
fp = fopen("testaddr.txt", "a+");
DWORD *ptr = (DWORD*)0x00BBC9CC;
VARBASE *Stats = (VARBASE*)*ptr;
//removed debug output to file
fclose(fp);
return NULL;
}
Related
I'm trying to understand some sample C code that I got with my microcontroller board. I have a really hard time to understand that whole pointer thing. I read a lot of posts in this forum and I also read several tutorials and slowly I get the hang of it :) But...
In my sample code there is the following line of code, which I could not decrypt with any information that I have found yet.
#define SOMENAME ((uint32_t *)0x130010f0)
I understood, that #define simply replaces all occurrences of SOMENAME in the compiled code with the respective statement (don't know if this is correctly explained, but I really think I got what this is doing).
Now, what I could imagine, what the rest of the statement means is the following:
SOMENAME is now a pointer to the address 0x130010f0 but without being an actual variable.
Is this correct? And I could kind of use it for example as: printf("value at address 0x130010f0: %p",SOMENAME) because the compiler would replace it with printf("value at address 0x130010f0: %p",((uint32_t *)0x130010f0)) and this gives the value stored at that address? What would be the print statement if I want the address of that pointer? I can't, right? Because the pointer does not have an address as it is not a variable? Very confusing...
The example is quite complex and this definition is also part of other definitions which are pointers to structs of structs of structs, therefore this "simple" example. Below you can find the "whole" structure:
#define ROM_API_TREE ((uint32_t *)0x130010f0)
#define BOOTLOADER_POINTER ((bootloader_tree_t *)ROM_API_TREE)
flash_driver_interface_t *FLASH_API_TREE
#define FLASH_API_TREE BOOTLOADER_POINTER->flashDriver
typedef struct BootloaderTree{
...
const flash_driver_interface_t *flashDriver;
} bootloader_tree_t
typedef struct FlashDriverInterface{
...
status_t (*ffr_get_uuid)(flash_config_t *config, uint8_t *uuid);
} flash_driver_interface_t
/*
* I actually want to understand that statement, but as I fail
* already at the beginning, I posted this question
*/
status_t = FLASH_API_TREE->ffr_get_uuid(config,uuid);
You are correct that SOMENAME get replaced by the preprocessor with ((uint32_t *)0x130010f0). What this gives you is a pointer to a uint32_t, and the value of that pointer is 0x130010f0.
When you then do this:
printf("value at address 0x130010f0: %p",SOMENAME);
You'll actually print the value of the pointer, i.e. 0x130010f0, not what it points to. For that you would need to dereference it, i.e.:
printf("value at address 0x130010f0: %u", *SOMENAME);
This however assumes that 0x130010f0 is a valid address that can be dereferenced and read. This will typically only be the case in some particular embedded environment where the implementation allows it.
As i saw, you basically could understand many things behind the Pointers. The SOMENAME is a macro not a variable right. Before i get to the code, a pointer in general is nothing else but a variable that contains an adress instead of having a value.
printf("value at address 0x130010f0: %p",SOMENAME); is wrong because the %p expects a value not an Adress and you are passing the adress to it, so you all you have to do is to dereference it using the *.
When you write (uint32_t *)0x130010f0 you are casting the adress to the type writteb between parentheses.
Whenever it gets complicated while using pointers try to remember this small example:
int a = 10;
int *p = &a;// declare pointer of type integer. This is valid, adress of an integer variable contains adress of integer variable
int *j; //declare pointer of type integer
j = &a; //correct, because j expects an adress.
*j = &a; //wrong *j expects a value
printf("value of p: %p", *p);
printf("adress of p: %p", p); //or &p
This shows that your microcontroller board has a program accessible 32-bit device.
I say 'accessible' because this device could be readable, writable or both.
I use the kinda general term 'device' because it could be all kinds of things. Quite often it's a register that simply stores a value, but it could also be a FIFO chip returning the next stored value at every read.
Assuming it's a register: These registers often consist of separate bits or small groups of bits to represent some function. In that case you'd see bitfield struct declarations that look like this (two 16-bit fields as example):
struct {
uint32_t someField : 16;
uint32_t otherField : 16;
} fields;
Suppose I am given a (void*) ptr (my basic understanding is, it represents a pointer to a region of unknown data type) passed through the parameter of a function. I am trying to figure out how to access and check if a struct exists a few addresses behind.
To clarify, I am working with a big char array (not malloced) and the ptr passed into the function should point to an address of an unspecified data type within the array. Located before this data is a struct for which I am trying to access.
void function(void *ptr)
{
void *structPtr = (void*)((void*)ptr - sizeof(struct block));
}
Would this work to get me a pointer to the address of the struct located behind the initial "ptr"? And if so, how could I check if it is the block struct?
Apologizes in advance, I know this code is not specific as I am fairly new to the concepts entirely but also, I am in the process of coming up with an algorithm and not yet implementing it. Any references to possibly useful information are much appreciated.
what you are trying to do is risky as you must be sure that you address a correct place in memory. Usually, we add some magic number in struct block so that we can test here that we are not going anywhere.
This pattern is generally used in memory allocators,
have a look to https://sourceware.org/glibc/wiki/MallocInternals for an example.
The usual way of writing this is something like:
...function(void *ptr) {
struct block *hdr = (struct block *)ptr - 1;
relying on pointer arithmetic automatically scaling by the size of the pointed at type. As long as all the pointers passed in here were originally created by taking a pointer to a valid struct block and adding 1 to it (to get the memory after it), you should be fine.
We have a structure in C say
struct info{
int no;
char first_name[20];
char last_name[20];
char status;
}
At runtime when we try to access these members by their name, say info_var.no or info_var.first_name, or we use a pointer to the structure, info_ptr->no or info_ptr->first_name, how are these individual members accessed?
I mean, the structure will be stored as member by member along with some necessary padding, but how does the runtime or maybe the compiler, if replacement happens at compile time, access those individual members by their name?
I know a lot of it is implementation dependent but if anybody could throw some light on any implementation or just give an overview it would be really nice.
In C, the work is done by the compiler. It compiles the data members of the structs to memory offsets and applies them to the base address of the struct.
There is no dynamic lookup for variable names as in e.g Python
Accessing by a pointer or an object makes no difference, actually info_ptr->no is equivalent to (*info_ptr).no.
Actual member access is compiler-specific.
Say you have:
class A
{
public:
char c;
int x;
A() {};
};
The following is the access code:
A a;
004113BE lea ecx,[a]
004113C1 call A::A (4110E1h)
int y = a.x;
004113C6 mov eax,dword ptr [ebp-8]
004113C9 mov dword ptr [y],eax
So the compiler, in this case, generates the binary knowing where x is stored in memory relative to a - that is 8 bytes into the A instance. This is because of padding.
EDIT: I just saw that the question is about C. Regardless, should be the same :).
There is a big difference between accessing a structure directly and via a pointer.
If you access it directly, the code will access the memory address directly, using a simplified assembler syntax, of a fictitious architecture. The examples below access the member status, which is stored at offset 44 in the structure:
MOVB varno+44, reg2
On the other hand, if you would access it via a local pointer, the pointer would typically be stored in a register. So the code would look something like:
MOVB 44[reg1], reg2
The worst scenario is if the pointer itself is a global pointer, then the code must first read the value of the pointer:
MOVL info_ptr, reg1
MOVB 44[reg1], reg2
The compiler can, in some cases, cache the pointer when performing multiple accesses. However, if the accesses are writes (to pointers or to characters), then compiler must assume that the pointer itself might have been changed and thus re-read it from memory.
I would strongly recommend using a one global structure, if your application only contains one.
Each field has a pre-determined offset from the start of the struct. The offset is determined at compile time. The machine code simply adds the field's offset to go from the address of the struct to the address of the field.
When you say "At runtime when we try to access these members by their name", it is important to note that all of the work having to do with the name is done at compile time.
about the code:
tp is a pointer to a certain struct which contains a table.
the table is a pointer to a pointer of a differnt struct,used as an array.
size is just the size of the table.
im sending these veriables to a function in order to initialize all the cells in the
array to NULL.
this line:
initArr(tp->table,tp->size);
sends them to this function:
void initArr(ObjectP* array,int size)
{
int i;
for (i = 0; i < size; ++i)
{
array[i]=NULL;
}
}
using the eclipse debugger i can see that the objects in the array are infact
being initialized to NULL, but when the method ends,
tp->table is NULL.
pointers gone wild?
help please.
the structs:
table:
typedef struct Table
{
size_t size;
hashFcn hash;
printFcn print;
comparisonFcn comp;
ObjectP* table;
int duplicated;
}Table;
object:
typedef struct Object
{
void *key;
ObjectP pointsTo;
}Object;
Arrays and pointers are similar but different.
An array of pointers can be represented as a number of continuous pointers in memory (with an address of where the first pointer in the array resides).
Under such a circumstance tp->table is exactly the same as tp->table[0], but the [0] is assumed (because it has the same address). In systems that are implemented in this manner, the tp->table specifies an address, and the offset from that address (to get to the element of the array) is represented as a value times the datatype size (or one pointer's size in your case).
tp->table (the base address 0x00000100)
tp->table[0] (the address 0x00000100 + 0 * sizeof(... pointer ...) = 0x00000100)
tp->table[1] (the address 0x00000100 + 1 * sizeof(... pointer ...) = 0x00000104 (some systems only))
tp->table[2] (the address 0x00000100 + 2 * sizeof(... pointer ...) = 0x00000108 (some systems only))
So your debugger might actually be printing out tp->table which is exactly equivalent to tp->table[0] depending on your compiler's implementation.
The code as presented seems wrong (you are returning something from a void function!), but I'm going to take a wild guess and assume that in your actual code, you are trying to set "array" to something (probably via malloc) inside initArr, in which case we have a classic gotcha: You are passing tp->table by value, so it does not get changed by initArr: initArr operates on a local copy of tp->table, which is discarded when initArr ends :)
Edit:
Doh - now you've posted the update, it looks like my guess was wrong. :/ Imagine the kudos if I'd got it right! :)
OK, I hope I explain this one correctly.
I have a struct:
typedef struct _MyData
{
char Data[256];
int Index;
} MyData;
Now, I run into a problem. Most of the time MyData.Data is OK with 256, but in some cases I need to expand the amount of chars it can hold to different sizes.
I can't use a pointer.
Is there any way to resize Data at run time? How?
Code is appreciated.
EDIT 1:
While I am very thankful for all the comments, the "maybe try this..." or "do that", or "what you are dong is wrong..." comments are not helping. Code is the help here. Please, if you know the answer post the code.
Please note that:
I cannot use pointers. Please don't try to figure out why, I just can't.
The struct is being injected into another program's memory that's why no pointers can be used.
Sorry for being a bit rough here but I asked the question here because I already tried all the different approaches that thought might work.
Again, I am looking for code. At this point I am not interested in "might work..." or " have you considered this..."
Thank you and my apologies again.
EDIT 2
Why was this set as answered?
You can use a flexible array member
typedef struct _MyData
{
int Index;
char Data[];
} MyData;
So that you can then allocate the right amount of space
MyData *d = malloc(sizeof *d + sizeof(char[100]));
d->Data[0..99] = ...;
Later, you can free, and allocate another chunk of memory and make a pointer to MyData point to it, at which time you will have more / less elements in the flexible array member (realloc). Note that you will have to save the length somewhere, too.
In Pre-C99 times, there isn't a flexible array member: char Data[] is simply regarded as an array with incomplete type, and the compiler would moan about that. Here i recommend you two possible ways out there
Using a pointer: char *Data and make it point to the allocated memory. This won't be as convenient as using the embedded array, because you will possibly need to have two allocations: One for the struct, and one for the memory pointed to by the pointer. You can also have the struct allocated on the stack instead, if the situation in your program allows this.
Using a char Data[1] instead, but treat it as if it were bigger, so that it overlays the whole allocated object. This is formally undefined behavior, but is a common technique, so it's probably safe to use with your compiler.
The problem here is your statement "I can't use a pointer". You will have to, and it will make everything much easier. Hey, realloc even copies your existing data, what do you want more?
So why do you think you can't use a pointer? Better try to fix that.
You would re-arrange the structure like that
typedef struct _MyData
{
int Index;
char Data[256];
} MyData;
And allocate instances with malloc/realloc like that:
my_data = (MyData*) malloc ( sizeof(MyData) + extra_space_needed );
This is an ugly approach and I would not recommend it (I would use pointers), but is an answer to your question how to do it without a pointer.
A limitation is that it allows for only one variable size member per struct, and has to be at the end.
Let me sum up two important points I see in this thread:
The structure is used to interact between two programs through some IPC mechanism
The destination program cannot be changed
You cannot therefore change that structure in any way, because the destination program is stuck trying to read it as currently defined. I'm afraid you are stuck.
You can try to find ways to get the equivalent behavior, or find some evil hack to force the destination program to read a new structure (e.g., modifying the binary offsets in the executable). That's all pretty application specific so I can't give much better guidance than that.
You might consider writing a third program to act as an interface between the two. It can take the "long" messages and do something with them, and pass the "short" messages onward to the old program. You can inject that in between the IPC mechanisms fairly easily.
You may be able to do this like this, without allocating a pointer for the array:
typedef struct _MyData
{
int Index;
char Data[1];
} MyData;
Later, you allocate like this:
int bcount = 256;
MyData *foo;
foo = (MyData *)malloc(sizeof(*foo) + bcount);
realloc:
int newbcount = 512;
MyData *resized_foo;
resized_foo = realloc((void *)foo, sizeof(*foo) + newbcount);
It looks like from what you're saying that you definitely have to keep MyData as a static block of data. In which case I think the only option open to you is to somehow (optionally) chain these data structures together in a way that can be re-assembled be the other process.
You'd need and additional member in MyData, eg.
typedef struct _MyData
{
int Sequence;
char Data[256];
int Index;
} MyData;
Where Sequence identifies the descending sequence in which to re-assemble the data (a sequence number of zero would indicate the final data buffer).
The problem is in the way you're putting the question. Don't think about C semantics: instead, think like a hacker. Explain exactly how you are currently getting your data into the other process at the right time, and also how the other program knows where the data begins and ends. Is the other program expecting a null-terminated string? If you declare your struct with a char[300] does the other program crash?
You see, when you say "passing data" to the other program, you might be [a] tricking the other process into copying what you put in front of it, [b] tricking the other program into letting you overwrite its normally 'private' memory, or [c] some other approach. No matter which is the case, if the other program can take your larger data, there is a way to get it to them.
I find KIV's trick quite usable. Though, I would suggest investigating the pointer issue first.
If you look at the malloc implementations
(check this IBM article, Listing 5: Pseudo-code for the main allocator),
When you allocate, the memory manager allocates a control header and
then free space following it based on your requested size.
This is very much like saying,
typedef struct _MyData
{
int size;
char Data[1]; // we are going to break the array-bound up-to size length
} MyData;
Now, your problem is,
How do you pass such a (mis-sized?) structure to this other process?
That brings us the the question,
How does the other process figure out the size of this data?
I would expect a length field as part of the communication.
If you have all that, whats wrong with passing a pointer to the other process?
Will the other process identify the difference between a pointer to a
structure and that to a allocated memory?
You cant reacolate manualy.
You can do some tricks wich i was uning when i was working aon simple data holding sistem. (very simple filesystem).
typedef struct
{
int index ;
char x[250];
} data_ztorage_250_char;
typedef struct
{
int index;
char x[1000];
} data_ztorage_1000_char;
int main(void)
{
char just_raw_data[sizeof(data_ztorage_1000_char)];
data_ztorage_1000_char* big_struct;
data_ztorage_250_char* small_struct;
big_struct = (data_ztorage_1000_char*)big_struct; //now you have bigg struct
// notice that upper line is same as writing
// big_struct = (data_ztorage_1000_char*)(&just_raw_data[0]);
small_struct = (data_ztorage_250_char*)just_raw_data;//now you have small struct
//both structs starts at same locations and they share same memory
//addresing data is
small_struct -> index = 250;
}
You don't state what the Index value is for.
As I understand it you are passing data to another program using the structure shown.
Is there a reason why you can't break your data to send into chunks of 256bytes and then set the index value accordingly? e.g.
Data is 512 bytes so you send one struct with the first 256 bytes and index=0, then another with the next 256 bytes in your array and Index=1.
How about a really, really simple solution? Could you do:
typedef struct _MyData
{
char Data[1024];
int Index;
} MyData;
I have a feeling I know your response will be "No, because the other program I don't have control over expects 256 bytes"... And if that is indeed your answer to my answer, then my answer becomes: this is impossible.