I am trying to access the PMC_PCER0 and enable it for PID14 on an ARM Cortex M3. I am asked to make a void function that reads a button and "returns" (as my professor insists to call it) its value. Anyway, here is the problem:
void readButton( unsigned int *button)
{
do something yo;
}
I have an address for PMC_PCER0 and let's suppose for the sake of the question it is at 0xfff123da and this PMC_PER0 has 32 PIOs, one of which is PID and happens to start at the 14th place, so I need to activate this one.
In order to activate it, do I need to mask PMC_PCER0 using the `or operator?
I know I can define PMC_PCER0 as follows
#define PMC_PCER0 (0xfff123da)
However, this will just give PMC_PCER0 the value of 0xfff123da, but what I want to do is PMC_PCER0 to actually have that address. And later I want to mask it. I'd appreciate it if you explained it in details.
so how do you load or store something at some address in C? You need an array or pointer right? How do you assign a pointer an address?
unsigned int *p;
...
p = (unsigned int *)0x12345678;
And then *p = 10; will write a 10 to that address right? or p[0] = 10;, elementary C language programming, has nothing to do with microcontrollers or operating systems.
The problem you end up with though is optimizers. if *p or p[0] is not used later then there is no reason at all to generate code. even if it does generate code there is no guarantee that it actually does the store or load
void myfun ( unsigned int x )
{
unsigned int *p;
p = (unsigned int *)0x12345678;
*p = x;
}
How do you tell the compiler or how do you use the language to ask the compiler to actually do a memory operation?
volatile unsigned int *p;
p = (unsigned int *)0x12345678;
so try making your define look something like this
#define PMC_PCER0 (*((volatile unsigned int *)0xfff123da))
AND understand that that is still not a guarantee that the 1) compiler will do a bus operation 2) that the bus operation will be the size you desire. if you want to guarantee such things then instead
#define PMC_PCER0 (0xfff123da)
and make a small asm file to link into the project, or put this in your bootstrap.
.thumb_func
.globl PUT32
PUT32:
str r1,[r0]
bx lr
.thumb_func
.globl GET32
GET32:
ldr r0,[r0]
bx lr
and then use it
void myfun ( unsigned int x )
{
PUT32(PMC_PCER0,x);
}
This has a performance cost, but it has significant benefits as well, first off being the compiler if remotely compliant must perform the function calls in order and all of them. so you are insured you get your load or store and you are insured it is of the right size. Second all of your accesses to peripherals and other special addresses are controlled through an abstraction layer that when placed on a chip simulator or on top of a operating system, or when doing your own testing against a handmade test bench (emulator) you already have an abstraction layer at the C function level that is easy to port. if you want to debug what is going on, you can use this abstraction layer to insert breakpoints or printfs or whatever.
Take it or leave it, it took me years to trip up the compiler into not generating the right instructions using the volatile trick. If you dont learn at least a little assembly language, and dont regularly disassemble the tool produced code, you will struggle more than necessary when something goes wrong like the wrong instruction being generated by the compiler or items being loaded to the wrong places by the linker (chip doesnt boot, program hangs, etc). THEN with that how to move the toolchain past the problem.
Yes I know your desired function is a load not a store, I assume you can figure it out from here.
This was all elementary C language programming stuff, possibly why nobody wanted to jump in and answer. Also the libraries that come free for the microcontroller you are using and for all other families and brands uses these kinds of tricks although some of them are a bit scary so take them with a grain of salt (or use them as a reference and not necessarily directly as you may end up owning their issues and maintenance).
Related
#define RegisterX_Address (*((volatile unsigned int*)0x400253FC))
I need to understand what this (*((volatile unsigned int*)0x400253FC)) in C, I understands that is a pointer pointing to the address of one of the registers but why is it written like this???
On whatever platform this is, memory address 0x400253FC contains 1 int worth of data.
If you dereference 0x400253FC, you get that value.
This is likely used for something like:
unsigned int GetCPUTemperature()
{
unsigned int temp;
temp = RegisterX_Address;
return temp;
}
It is not terribly common to have data mapped directly to a specific memory address, but happens in embedded development regularly.
The volatile keyword tells the compiler it cannot cache, store or reuse the value it gets. It must retrieve the value from memory on each access, because whatever is writing data there will update the value regularly and outside the scope of the program.
It's a macro to access a (probably) memory-mapped I/O pin.
The compiler or hardware itself knows that specific addresses of memory have an additional purpose. When your source code reads from that register it's really reading the value off of an input pin, a wire hooked up directly to the processor. That address is special, and these sort of things are typically exclusively tied to that particular hardware. (Which is why you need a shmorgas board of different drivers for different hardware and they're not all conveniently interchangeable). For all the misdirection and generalization that higher levels perform, at some point you need to direct read and writes to actual hardware with actual addresses.
The inner * is declaring it as a pointer. The outer * is dereferencing it. And yeah, pointers in C are one of the most confusing parts of the language. The * symbol has two jobs really; one is during declarations, where it describes a chunk of data. And explicitly casting is declaration: (volatile unsigned int*). That forces the compiler to treat the hex value as a pointer to a volatile unsigned integer. The second, in execution when using this macro: *(myPointer), that pointer is dereferenced, so rather than using the value 0x400253FC, you're looking at the data that lives at ADDRESS 0x400253FC in memory. Which isn't even memory since it's probably mapped to HW. (It depends. Either way it's still called a register in ICDs. I think of registers as the specific registers on the chip, what assembly can use directly as opposed to going through the MMU. But everything is a "register" to the HW guys, they use it like we use "address").
And I'm guessing it's an I/O pin because it's volatile. This a an instruction to the compiler not to make presumptions when optimizing because it's value can change behind it's back. Like when hardware gets a signal. Or when an output line automatically resets low. Volatile variables are also used for shared memory between threads, but on a microcontroller it's typically I/O.
Just try it:
#define RegisterX_Address (*((volatile unsigned int*)0x400253FC))
unsigned int fun ( void )
{
return(RegisterX_Address);
}
gives:
00000000 <fun>:
0: 4b01 ldr r3, [pc, #4] ; (8 <fun+0x8>)
2: 6818 ldr r0, [r3, #0]
4: 4770 bx lr
8: 400253fc
It is simpler to write than:
volatile unsigned int *RegisterX_Address;
RegisterX_Address = (volatile unsigned int *)0x400253FC;
return(*RegisterX_Address);
That is why it is written that way. Plus as written it doesn't consume memory as a variable.
It is written like that because that is what happens to work on the particular compilers used with that particular microcontroller. Most likely, the volatile serves as an indication to the compiler that it shouldn't make optimizations that would result in not actually reading the hardware register.
i have limited RAM in my microController.(using arm gcc)
i should write my code as efficient as possible. consider function blew :
int foo(uint32_t a , float b)
{
.....
return 0;
}
so I have two arguments a and b. now if I change the arguments to *a and *b is the function takes less ram than the first function during execution :
int foo(uint32_t *a,float *b)
{
....
return 0;
}
what if the arguments become String or array ( of int, float ....)??
any references would be great. thanks
You can actually waste memory when using pointers. This is for 2 reasons.
1. Register optimization lost
Code which calls foo must take address of the variable to pass as parameter. If passed variable is local, it could be in register but because you take its address it must be placed on stack. In general, using variable in register is faster than using variable in stack.
2. Value of variable unknown after call
When you give address of variable function, compiler no longer knows if variable is modified, and must refresh it if it's read again.
uint32_t u = 1;
float f = 2.0f;
foo(&u, &f); // 1. Address taken, u and f cannot be register variables
// 2. What is value of u now? It must refreshed from memory before addition happens
u++;
Bottom line: do not take address of primitive types unless you have to.
Strings and arrays are already passed using address, so there is no other option.
ARM's Procedure Call Standard defined in Application Binary Interface (ABI) states that the first four word-sized parameters passed to a function will be transferred in registers R0-R3.
Since pointers are also 32-bit in size, there is not that much difference between these two signatures.
int foo(uint32_t a, float b)
int foo(uint32_t *a, float *b)
Both will have a in r0, b in r1 and return value in r0 again.
ARM is a RISC architecture it has many registers and with trivial functions you may even get away from touching any memory at all.
If you are working with micro controllers it is a better idea to check if you should really use floating points. Since they might not be natively supported by the core you are targeting for.
I would check ARM Cortex-A Series Programmer's Guide (most of it applies to micro controllers as well), especially chapters 15 and 17 to learn more about tricks for ARM application development.
Quick question here regarding the behavior of pointers (I'm working on a project on a PIC32MX270F256D).
I have the following code currently implemented:
void main(void)
{
int size = 15;
int check;
int *ptr;
ptr = &size;
check = *ptr;
while(1); //just so it hangs at the end
}
Now I am stepping through the program with variable watches on. After the declaration of size, I can see in the watch window that size has a value 15, and is at address 0xA000FFC8 (so far so good). After the line ptr = &size;, the watch window shows that ptr has value 0xA000FFC8 (as expected). Now after the final line (check = *ptr;), the watch window says check has the value 0xA000FFC8.
This seems to me like very simple functionality. At the end, while hanging in the while loop, check should have the value 15, no? If yes, is my code incorrect, or is there apparently something wrong with the Microchip IDE? If not, what am I missing to make this work like it should?
Thanks.
-Sean
Note: I'm using MPLAB X and the Microchip's XC32 compiler.
This is probably an optimization issue. Your compiler determined that your code doesn't actually do anything, so it didn't bother generating the code. Specifically, your code doesn't actually use the value you store in check.
You can declare your pointer as volatile to force the compiler not to optimize it away. I.e., int *ptr; becomes volatile int *ptr;.
You could also use the value of check in a meaningful way, like by printing it out.
printf("My pointer %p points to %u.\n", ptr, check);
Or you can look in your compiler documentation and figure out how to turn off optimizations. When debugging, it is often helpful to compile without optimizations so that the compiled code closely matches your source code.
Note: You will at some point want to access hardware or chip registers that have been mapped to memory addresses. When you do this, make sure these pointers to mapped memory are volatile or you will have the same problem!
Like this link http://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Labels-as-Values.html
I can get the memory address of an label, so if I declare a label, get your address, and add your address, i will pass to next instruction? some ilustration >
int main () {
void *ptr;
label:
instruction 1;
instruction 2;
ptr = &&label;
// So if I do it...
ptr = ptr + 1;
// I will get the instruction 2 correct??
Thanks for all answers.
No, I don't think so.
First of, you seem to take the address of a label, which doesn't work. The label is interpreted by the compiler but it does not represent an actual adress in your code.
Second, every statement in C/C++ (in fact any language) can be translated to many machine language instructions, so instruction 1 could be translated to 3, 5, 10 or even more machine instructions.
Third, your pointer points to void. The C compiler does not know how to increment a void pointer. Normally when you increment a pointer, it adds the size of the data type you are pointing to to the address. So incrementing a long-pointer will add 4 bytes; incrementing a char-pointer will add 1 byte. In this case you have a void-pointer, which points to nothing, and thus cannot be incremented.
Fourth, I don't think that all instructions in x86 machine language are represented by the same number of bytes. So you cannot expect from adding something to a pointer that it gets to the next instruction. You might also end up in the middle of the next instruction.
You can't perform arithmetic on a void*, and the compiler wouldn't know what to add to the pointer to have it point to the next 'instruction' anyway - there is no 1 to 1 correspondence between C statement and the machine code emitted by the compiler. Even for CPUs which have a 'regular' instruction set where instructions are the same size (as opposed to something like the x86 where instructions have a variable number of bytes), a single C statement may result in several CPU instructions (or maybe only one - who knows?).
Expanding on an example in the GCC docs, you might be able to get by with something like the following, but it requires a label for each statement you want to target:
void *statements[] = { &&statement1, &&statement2 };
void** ptr;
statement1:
instruction 1;
statement2:
instruction 2;
ptr = statements;
// goto **ptr; // <== this will jump to 'instruction 1'
// goto **(ptr+1); // <== this will jump to 'instruction 2'
Note that the &&label syntax is described under C Extensions section in GCC docs. It's not C, it's GCC.
Plus, void* does not allow pointer arithmetic - it's a catch-all sort of type in C for pointing at anything. The assumption is that the compiler does not know size of the object it points to (but the programmer should :).
Even more, instruction sizes are widely different on different architectures - four bytes on SPARC, but variable length on x86, for example.
I.e. it doesn't work in C. You will have to use inline assembler for this sort of things.
No, because you can't increment void *.
void fcn() { printf("hello, world\n"); }
int main()
{
void (*pt2Function)() = fcn;
pt2Function(); // calls fcn();
// error C2171: '++' : illegal on operands of type 'void (__cdecl *)(void)'
// ++pt2Function;
return 0;
}
This is VC++, but I suspect gcc is similar.
Edited to add
Just for fun, I tried this—it crashed:
int nGlobal = 0;
__declspec(naked) void fcn()
{
// nop is 1-byte instruction that does nothing
_asm { nop }
++nGlobal;
_asm { ret }
}
int main()
{
void (*pt2Function)() = fcn;
// this works, incrementing nGlobal:
pt2Function();
printf("nGlobal: %d", nGlobal);
char *p = (char *) pt2Function;
++p; // point past the NOP?
pt2Function = (void (*)()) p;
// but this crashes...
pt2Function();
printf("nGlobal: %d", nGlobal);
return 0;
}
It crashed because this line doesn't do what I thought it did:
void (*pt2Function)() = fcn;
I thought it would take the address of the first instruction of fcn(), and put it in pt2Function. That way my ++p would make it point to the second instruction (nop is one byte long).
It doesn't. It puts the address of a jmp instruction (found in a big jump table) into pt2Function. When you increment it by one byte, it points to a meaningless location in the jump table.
I assume this is implementation-specific.
I would say "probably not". The value of the pointer will be right, because the compiler knows, but I doubt that the + 1 will know the length of instructions.
Let us suppose there's a way to get the address of a label (that is no an extension of a specific compiler). Then the problem would really be "the next instruction" idea: it can be very hard to know which is the next instruction. It depends on the processor, and on processors like x86 to know the length of an instruction you have to decode it, not fully of course but it is anyway some complex job... on notable RISC architectures, instructions' length is a lot easier and getting the next instruction could be as easy as incrementing the address by 4. But there's no a general way to do it at runtime, while at compile time it could be easier, but to allow it in a C-coherent way, C should have the type "instruction", so that "instruction *" can be a pointer to an instruction, and incrementing such a pointer would point correctly to the next instruction, provided the code is known at compile time (so, such a pointer can't point really to everything pointer can point to in general). At compile time the compiler could implement this feature easily adding another "label" just beyond the generated instruction pointed by the "first" "label". But it would be cheating...
Moreover, let us suppose you get the address of a C label, or C function, or whatever. If you skip the first instruction, likely you won't be able to "use" that address to execute the code (less the first instruction), since without that single instruction the code may become buggy... unless you know for sure you can skip that single instruction and obtain what you want, but you can't be sure... unless you take a look at the code (which can be different from compiler to compiler), and then all the point of doing such a thing from C disappears.
So, briefly, the answer is no, you can't compute the pointer to the next instruction; and if you do someway, the fact that you're pointing to code becomes meaningless since you can't jump to that address and be sure of the final behaviour.
Imagine I have the following simple C program:
int main() {
int a=5, b= 6, c;
c = a +b;
return 0;
}
Now, I would like to know the address of the expression c=a+b, that is the program address
where this addition is carried out. Is there any possibility that I could use printf?
Something along the line:
int main() {
int a=5, b= 6, c;
printf("Address of printf instruction in memory: %x", current_address_pointer_or_something)
c = a +b;
return 0;
}
I know how I could find the address out by using gdb and then info line file.c:line. However, I should know if I could also do that directly with the printf.
In gcc, you can take the address of a label using the && operator. So you could do this:
int main()
{
int a=5, b= 6, c;
sum:
c = a+b;
printf("Address of sum label in memory: %p", &&sum);
return 0;
}
The result of &&sum is the target of the jump instruction that would be emitted if you did a goto sum. So, while it's true that there's no one-to-one address-to-line mapping in C/C++, you can still say "get me a pointer to this code."
Visual C++ has the _ReturnAddress intrinsic, which can be used to get some info here.
For instance:
__declspec(noinline) void PrintCurrentAddress()
{
printf("%p", __ReturnAddress);
}
Which will give you an address close to the expression you're looking at. In the event of some optimizations, like tail folding, this will not be reliable.
Tested in Visual Studio 2008:
int addr;
__asm
{
call _here
_here: pop eax
; eax now holds the PC.
mov [addr], eax
}
printf("%x\n", addr);
Credit to this question.
Here's a sketch of an alternative approach:
Assume that you haven't stripped debug symbols, and in particular you have the line number to address table that a source-level symbolic debugger needs in order to implement things like single step by source line, set a break point at a source line, and so forth.
Most tool chains use reasonably well documented debug data formats, and there are often helper libraries that implement most of the details.
Given that and some help from the preprocessor macro __LINE__ which evaluates to the current line number, it should be possible to write a function which looks up the address of any source line.
Advantages are that no assembly is required, portability can be achieved by calling on platform-specific debug information libraries, and it isn't necessary to directly manipulate the stack or use tricks that break the CPU pipeline.
A big disadvantage is that it will be slower than any approach based on directly reading the program counter.
For x86:
int test()
{
__asm {
mov eax, [esp]
}
}
__declspec(noinline) int main() // or whatever noinline feature your compiler has
{
int a = 5;
int aftertest;
aftertest = test()+3; // aftertest = disasms to 89 45 F8 mov dword ptr [a],eax.
printf("%i", a+9);
printf("%x", test());
return 0;
}
I don't know the details, but there should be a way to make a call to a function that can then crawl the return stack for the address of the caller, and then copy and print that out.
Using gcc on i386 or x86-64:
#include <stdio.h>
#define ADDRESS_HERE() ({ void *p; __asm__("1: mov 1b, %0" : "=r" (p)); p; })
int main(void) {
printf("%p\n", ADDRESS_HERE());
return 0;
}
Note that due to the presence of compiler optimizations, the apparent position of the expression might not correspond to its position in the original source.
The advantage of using this method over the &&foo label method is it doesn't change the control-flow graph of the function. It also doesn't break the return predictor unit like the approaches using call :)
On the other hand, it's very much architecture-dependent... and because it doesn't perturb the CFG there's no guarantee that jumping to the address in question would make any sense at all.
If the compiler is any good this addition happens in registers and is never stored in memory, at least not in the way you are thinking. Actually a good compiler will see that your program does nothing, manipulating values within a function but never sending those values anywhere outside the function can result in no code.
If you were to:
c = a+b;
printf("%u\n",c);
Then a good compiler will also never store that value C in memory it will stay in registers, although it depends on the processor as well. If for example compilers for that processor use the stack to pass variables to functions then the value for c will be computed using registers (a good compiler will see that C is always 11 and just assign it) and the value will be put on the stack while being sent to the printf function. Naturally the printf function may well need temporary storage in memory due to its complexity (cant fit everything it needs to do in registers).
Where I am heading is that there is no answer to your question. It is heavily dependent on the processor, compiler, etc. There is no generic answer. I have to wonder what the root of the question is, if you were hoping to probe with a debugger, then this is not the question to ask.
Bottom line, disassemble your program and look at it, for that compile on that day with those settings, you will be able to see where the compiler has placed intermediate values. Even if the compiler assigns a memory location for the variable that doesnt mean the program will ever store the variable in that location. It depends on optimizations.