There is a constant global variable defined in another module.
I would like to manipulate this variable during run time (as I can't change in the other module and remove the const keyword).
I know that constants are put in ROM ...
The code will be downloaded to a micro controller (leopard powerpc 5643) , so I think that constants will be in the Flash Memory (not the normal PC ROM)
I have tried something like this and the compiler produced an error during compilation:
const int global_Variable = 0;
const int* ptr = &global_Variable;
*ptr = 5;
So , do you know any other way to accomplish this ?
If you know that the constant really is put into ROM (or, more likely, flash) on your platform, then of course you won't be able to modify it, at least not directly.
If it's flash, you might, but you're going to have to dive a bit deeper since reprogramming flash memory is not done by just writing to it, you must erase the relevant portion and there are often block/sector size limitations to deal with. It won't be pretty.
Your actual code fails to compile since you can't write through a const pointer (that's the point of the const, after all). You can cast away that and force the compiler to generate the write, but of course it won't work if the target address points to non-writable memory:
const int global_Variable = 0;
int *ptr = (int *) &global_Variable; /* Cast away the const. */
*ptr = 5; /* Do the write! */
Again, this won't work if global_Variable is in non-writable memory. You will get undefined results.
Lastly, which is so obvious that I didn't even think to write it: what you're doing sounds lika a very bad idea. Obviously the software you're working on was designed with the assumption that global_Variable be constant. You're trying to overthrow that particular part of the design, which very likely will break lots of things if you succeed. In other words: consider not doing this.
If you manage to place global_variable in a memory region that is writeable, here is a way to change its value. Notice that this won't work if global_variable is not physically writeable, e.g. because it sits in the ROM area.
int *ptr = (int*)&global_variable; /* the compiler will warn you about this */
*ptr = 5;
Notice that you might run into other problems down the road as the compiler might assume that the content of a variable declared as const does not change during the runtime of the program. You violate this assertion by altering the variable's value, so expect strange results.
Related
I'm trying to access a certain location in memory and retrieve the contents of that memory location but the program seems to not work when I run it. I don't get any errors it's just a blank console screen. The first thing that came to my mind is that it would probably be a security breach to be able to access a memory location like this. Is that the reason or is my code wrong?
int main()
{
int * pointer = 100;
printf("%d", *pointer);
return 0;
}
Memory mapped registers are an integral part of embedded programming - but you need to know where in memory to prod - random locations are likely to generate random effects (due to undefined behaviour)!
For embedded compilers, usually there is a header file full of lines similar to:
#define GPIO_PORTF_DIR_R (*( ( volatile unsigned int * )0x40025400 ) )
These (a) map registers appropriately and (b) hide the specific implementation.
Note the use of the volatile qualifier - any memory mapped access should be volatile qualified, otherwise there is scope for compiler optimisation to have an effect too!
Now we can use this name inside your code to read and write to that register (wherever it happens to be):
GPIO_PORTF_DIR_R = 0xF0;
data = GPIO_PORTF_DIR_R;
The fact that your code results in "just a blank console screen" means it's not doing what you expect... your random location is causing random (undefined) behaviour.
The const type qualifier causes the compiler to issue an error message in case an attempt to modify an object declared as const,but that is not enough protection.For example the following program modifies both elements of the array declared as const:
#include <stdio.h>
int main(void)
{
const char buf[2] = { 'a','b' };
const char *const ptr = buf;
unsigned long addr = (unsigned long)ptr;
*(char *)addr = 'c';
addr = addr + 1;
*(char *)addr = 'd';
printf("%c\n", buf[0]);
printf("%c\n", buf[1]);
return 0;
}
So,it turns out to be that the compiler is not enough guard to protect the objects from being modified.How can we prevent this sort of thing?
I don't think more protection can nor should be provided.
The C programming language lets you do almost everything you want freely, especially accessing objects from pointers. However, freedom is never free, so C programmers must always be careful (and avoid casting if it isn't necessary).
A standard tool for finding memory overruns is watchpoints, or data breakpoints as they are called in MS Visual Studio.
If you need to protect your object just for debugging, use your debugger to set a watchpoint inside your object. The bug will be discovered at runtime (not compile time) - when your program tries to write to the specified address, the debugger will stop it.
You might be able to set your watchpoints in your code, but their number is limited (the maximum is 4 on x86 platform), so this cannot be a general-purpose feature of your program.
I think the philosophy behind protection is the comfort of one who is using your code as ready library in his own code.
Otherwise if it was possible to make the object completely non-modifiable in C language, there would be some crackers who could modify whatever they want :) :)
This question already has answers here:
Why is volatile needed in C?
(18 answers)
Closed 9 years ago.
I am writing program for ARM with Linux environment. its not a low level program, say app level
Can you clarify me what is the difference between,
int iData;
vs
volatile int iData;
Does it have hardware specific impact ?
Basically, volatile tells the compiler "the value here might be changed by something external to this program".
It's useful when you're (for instance) dealing with hardware registers, that often change "on their own", or when passing data to/from interrupts.
The point is that it tells the compiler that each access of the variable in the C code must generate a "real" access to the relevant address, it can't be buffered or held in a register since then you wouldn't "see" changes done by external parties.
For regular application-level code, volatile should never be needed unless (of course) you're interacting with something a lot lower-level.
The volatile keyword specifies that variable can be modified at any moment not by a program.
If we are talking about embedded, then it can be e.g. hardware state register. The value that it contains may be modified by the hardware at any unpredictable moment.
That is why, from the compiler point of view that means that compiler is forbidden to apply optimizations on this variable, as any kind of assumption is wrong and can cause unpredictable result on the program execution.
By making a variable volatile, every time you access the variable, you force the CPU to fetch it from memory rather than from a cache. This is helpful in multithreaded programs where many threads could reuse the value of a variable in a cache. To prevent such reuse ( in multithreaded program) volatile keyword is used. This ensures that any read or write to an volatile variable is stable (not cached)
Generally speaking, the volatile keyword is intended to prevent the compiler from applying any optimizations on the code that assume values of variables cannot change "on their own."
(from Wikipedia)
Now, what does this mean?
If you have a variable that could have its contents changed at any time, usually due to another thread acting on it while you are possibly referencing this variable in a main thread, then you may wish to mark it as volatile. This is because typically a variable's contents can be "depended on" with certainty for the scope and nature of the context in which the variable is used. But if code outside your scope or thread is also affecting the variable, your program needs to know to expect this and query the variable's true contents whenever necessary, more than the normal.
This is a simplification of what is going on, of course, but I doubt you will need to use volatile in most programming tasks.
In the following example, global_data is not explicitly modified. so when the optimization is done, compiler thinks that, it is not going to modified anyway. so it assigns global_data with 0. And uses 0, whereever global_data is used.
But actually global_data updated through some other process/method(say through ptrace ). by using volatile you can force it to read always from memory. so you can get updated result.
#include <stdio.h>
volatile int global_data = 0;
int main()
{
FILE *fp = NULL;
int data = 0;
printf("\n Address of global_data:%x \n", &global_data);
while(1)
{
if(global_data == 0)
{
continue;
}
else if(global_data == 2)
{
;
break;
}
}
return 0;
}
volatile keyword can be used,
when the object is a memory mapped io port.
An 8 bit memory mapped io port at physical address 0x15 can be declared as
char const ptr = (char *) 0x15;
Suppose that we want to change the value at that port at periodic intervals.
*ptr = 0 ;
while(*ptr){
*ptr = 4;//Setting a value
*ptr = 0; // Clearing after setting
}
It may get optimized as
*ptr = 0 ;
while(0){
}
Volatile supress the compiler optimization and compiler assumes that tha value can
be changed at any time even if no explicit code modify it.
Volatile char *const ptr = (volatile char * )0x15;
Used when the object is a modified by ISR.
Sometimes ISR may change tha values used in the mainline codes
static int num;
void interrupt(void){
++num;
}
int main(){
int val;
val = num;
while(val != num)
val = num;
return val;
}
Here the compiler do some optimizations to the while statement.ie the compiler
produce the code it such a way that the value of num will always read form the cpu
registers instead of reading from the memory.The while statement will always be
false.But in actual scenario the valu of num may get changed in the ISR and it will
reflect in the memory.So if the variable is declared as volatile the compiler will know
that the value should always read from the memory
volatile means that variables value could be change any time by any external source. in GCC if we dont use volatile than it optimize the code which is sometimes gives unwanted behavior.
For example if we try to get real time from an external real time clock and if we don't use volatile there then what compiler do is it will always display the value which is stored in cpu register so it will not work the way we want. if we use volatile keyword there then every time it will read from the real time clock so it will serve our purpose....
But as u said you are not dealing with any low level hardware programming then i don't think you need to use volatile anywhere
thanks
Is it possible to assign a variable the address you want, in the memory?
I tried to do so but I am getting an error as "Lvalue required as left operand of assignment".
int main() {
int i = 10;
&i = 7200;
printf("i=%d address=%u", i, &i);
}
What is wrong with my approach?
Is there any way in C in which we can assign an address we want, to a variable?
Not directly.
You can do this though : int* i = 7200;
.. and then use i (ie. *i = 10) but you will most likely get a crash. This is only meaningful when doing low level development - device drivers, etc... with known memory addreses.
Assuming you are on an x86-type processer on a modern operating system, it is not possible to write to aribtray memory locations; the CPU works in concert with the OS to protect memory so that one process cannot accidentally (or intentionally) overwrite another processes' memory. Allowing this would be a security risk (see: buffer overflow). If you try to anyway, you get the 'Segmentation fault' error as the OS/CPU prevents you from doing this.
For technical details on this, you want to start with 1, 2, and 3.
Instead, you ask the OS to give you a memory location you can write to, using malloc. In this case, the OS kernel (which is generally the only process that is allowed to write to arbitrary memory locations) finds a free area of memory and allocates it to your process. The allocation process also marks that area of memory as belonging to your process, so that you can read it and write it.
However, a different OS/processor architecture/configuration could allow you to write to an arbitrary location. In that case, this code would work:
#include <stdio.h>
void main() {
int *ptr;
ptr = (int*)7000;
*ptr = 10;
printf("Value: %i", *ptr);
}
C language provides you with no means for "attaching" a name to a specific memory address. I.e. you cannot tell the language that a specific variable name is supposed to refer to a lvalue located at a specific address. So, the answer to your question, as stated, is "no". End of story.
Moreover, formally speaking, there's no alternative portable way to work with specific numerical addresses in C. The language itself defines no features that would help you do that.
However, a specific implementation might provide you with means to access specific addresses. In a typical implementation, converting an integral value Ato a pointer type creates a pointer that points to address A. By dereferencing such pointer you can access that memory location.
Not portably. But some compilers (usually for the embedded world) have extensions to do it.
For example on IAR compiler (here for MSP430), you can do this:
static const char version[] # 0x1000 = "v1.0";
This will put object version at memory address 0x1000.
You can do in the windows system with mingw64 setup in visual studio code tool, here is my code
#include<stdio.h>
int main()
{
int *c;
c = (int *)0x000000000061fe14; // Allocating the address 8-bit with respect to your CPU arch.
*c = NULL; // Initializing the null pointer for allocated address
*c = 0x10; // Assign a hex value (you can assign integer also without '0x')
printf("%p\n",c); // Prints the address of the c pointer variable
printf("%x\n",*c); // Prints the assigned value 0x10 -hex
}
It is tested with mentioned environment. Hope this helps Happy coding !!!
No.
Even if you could, 7200 is not a pointer (memory address), it's an int, so that wouldn't work anyway.
There's probably no way to determine which address a variable will have. But as a last hope for you, there is something called "pointer", so you can modify a value on address 7200 (although this address will probably be inaccessible):
int *i = (int *)7200;
*i = 10;
Use ldscript/linker command file. This will however, assign at link time, not run time.
Linker command file syntax depends largely on specific compiler. So you will need to google for linker command file, for your compiler.
Approximate pseudo syntax would be somewhat like this:
In linker command file:
.section start=0x1000 lenth=0x100 myVariables
In C file:
#pragma section myVariables
int myVar=10;
It's not possible, maybe possible with compiler extensions. You could however access memory at an address you want (if the address is accessible to your process):
int addr = 7200;
*((int*)addr) = newVal;
I think '&' in &a evaluates the address of i at the compile time which i think is a virtual address .So it is not a Lvalue according to your compiler. Use pointer instead
I am learning function pointers,I understand that we can point to functions using function pointers.Then I assume that they stay in memory.Do they stay in stack or heap?Can we calculate the size of them?
The space for code is statically allocated by the linker when you build the code. In the case where your code is loaded by an operating system, the OS loader requests that memory from the OS and the code is loaded into it. Similarly static data as its name suggests is allocated at this time, as is an initial stack (though further stacks may be created if additional threads are created).
With respect to determining the size of a function, this information is known to the linker, and in most tool-chains the linker can create a map file that includes the size and location of all static memory objects (i.e. those not instantiated at run-time on the stack or heap).
There is no guaranteed way of determining the size of a function at run-time (and little reason to do so) however if you assume that the linker located functions that are adjacent in the source code sequentially in memory, then the following may give an indication of the size of a function:
int first_function()
{
...
}
void second_function( int arg )
{
...
}
int main( void )
{
int first_function_length = (int)second_function - (int)first_function ;
int second_function_length = (int)main - (int)second_function ;
}
However YMMV; I tried this in VC++ and it only gave valid results in a "Release" build; the results for a "Debug" build made no real sense. I suggest that the exercise is for interest only and has no practical use.
Another way of observing the size of your code of course is to look at the disassembly of the code in your debugger for example.
Functions are part of text segment (which may or may not be 'heap') or its equivalent for the architecture you use. There's no data past compilation regarding their size, at most you can get their entry point from symbol table (which doesn't have to be available). So you can't calculate their size in practice on most C environments you'll encounter.
They're (normally) separate from either the stack or heap.
There are ways to find their size, but none of them is even close to portable. If you think you need/want to know the size, chances are pretty good that you're doing something you probably ought to avoid.
There's an interesting way to discover the size of the function.
#define RETN_empty 0xc3
#define RETN_var 0xc2
typedef unsigned char BYTE;
size_t FunctionSize(void* Func_addr) {
BYTE* Addr = (BYTE*)Func_addr;
size_t function_sz = 0;
size_t instructions_qt = 0;
while(*Addr != (BYTE)RETN_empty && *Addr != (BYTE)RETN_var) {
size_t inst_sz = InstructionLength((BYTE*)Addr);
function_sz += inst_sz;
Addr += inst_sz;
++instructions_qt;
}
return function_sz + 1;
}
But you need a function that returns the size of the instruction. You can find a function that finds the Instruction Length here: Get size of assembly instructions.
This function basically keeps checking the instructions of the function until it finds the instruction to return (RETN)[ 0xc3, 0xc2], and returns the size of the function.
To make it simple, functions usually don't go into the stack or the heap because they are meant to be read-only data, whereas stack and heap are read-write memories.
Do you really need to know its size at runtime? If no, you can get it by a simple objdump -t -i .text a.out where a.out is the name of your binary. The .text is where the linker puts the code, and the loader could choose to make this memory read-only (or even just execute-only). If yes, as it has been replied in previous posts, there are ways to do it, but it's tricky and non-portable... Clifford gave the most straightforward solution, but the linker rarely puts function in such a sequential manner into the final binary. Another solution is to define sections in your linker script with pragmas, and reserve a storage for a global variable which will be filled by the linker with the SIZEOF(...) section containing your function. It's linker dependent and not all linkers provide this function.
As has been said above, function sizes are generated by the compiler at compile time, and all sizes are known to the linker at link time. If you absolutely have to, you can make the linker kick out a map file containing the starting address, the size, and of course the name. You can then parse this at runtime in your code. But I don't think there's a portable, reliable way to calculate them at runtime without overstepping the bounds of C.
The linux kernel makes similar use of this for run-time profiling.
C has no garbage collector. Having a pointer to something doesn't make it stay in memory.
Functions are always in memory, whether or not you use them, whether or not you keep a pointer to them.
Dynamically allocated memory can be freed, but it has nothing to do with keeping a pointer to it. You shouldn't keep pointer to memory you have freed, and you should free it before losing the pointer to it, but the language doesn't do it automatically.
If there is anything like the size of the function it should be its STACK FRAME SIZE. Or better still please try to contemplate what exactly, according to you, should be the size of a function? Do you mean its static size, that is the size of all its opcode when it is loaded into memory?If that is what you mean, then I dont see their is any language provided feature to find that out.May be you look for some hack.There can be plenty.But I haven't tried that.
#include<stdio.h>
int main(){
void demo();
int demo2();
void (*fun)();
fun = demo;
fun();
printf("\n%lu", sizeof(demo));
printf("\n%lu", sizeof(*fun));
printf("\n%lu", sizeof(fun));
printf("\n%lu", sizeof(demo2));
return 0;
}
void demo(){
printf("tired");
}
int demo2(){
printf("int type funciton\n");
return 1;
}
hope you will get your answer, all function stored somewhere
Here the output of the code