Initialize an int in a struct for shared memory - c

I have an int that keeps track of words in a queue, but I am working with shared memory that should persist across multiple executions. Therefore, I can't simply state
int words = 0;
as a global variable because it will be overwritten each time I run the program. My struct currently looks like this
typedef struct {
/* List of words stored in the FIFO. */
Word list[ MAX_WORDS ];
int words;
} FIFO;
I only need to initialize 'words' to 0 for the first run, and after that the value should persist through shared memory, but I'm not sure how to do this without it being reset to 0 each run.
Any help would be awesome, thanks!

When you create a new shared memory area, it's initialised to zeros automatically. That's the case for both shmget on Linux and CreateFileMapping on Windows. Likely the same on other systems, but you'll have to search in the docs. In practice that means as long as you have proper locking scheme implemented, your app will see only 2 states of the shared memory - either all zeros (you're the first one to open it), or already initialised (another instance opened the shared memory before).
I'm not sure you really want shared memory though. If by "should persist across multiple executions" you mean executions of multiple processes at the same time, then this answer applies. But if you want to run your app, then shut it down, then run it again and have the same FIFO available, then you need to just write it into some file, or an embedded/external database.

Related

How to determine if a pointer is in rodata [duplicate]

This question already has answers here:
How can I prevent (not react to) a segmentation fault?
(3 answers)
Closed 2 years ago.
Can I tell if a pointer is in the rodata section of an executable?
As in, editing that pointer's data would cause a runtime system trap.
Example (using a C character pointer):
void foo(char const * const string) {
if ( in_rodata( string ) ) {
puts("It's in rodata!");
} else {
puts("That ain't in rodata");
}
}
Now I was thinking that, maybe, I could simply compare the pointer to the rodata section.
Something along the lines of:
if ( string > start_of_rodata && string < end_of_rodata ) {
// it's in rodata!
}
Is this a feasible plan/idea?
Does anyone have an idea as to how I could do this?
(Is there any system information that one might need in order to answer this?)
I am executing the program on a Linux platform.
I doubt that it could possibly be portable
If you don't want to mess with linker scripts or using platform-specific memory map query APIs, a proxy approach is fairly portable on platforms with memory protection, if you're willing to just know whether the location is writable, read-only, or neither. The general idea is to do a test read and a test write. If the first succeeds but the second one fails, it's likely .rodata or code segment. This doesn't tell you "it's rodata for sure" - it may be a code segment, or some other read-only page, such as as read-only file memory mapping that has copy-on-write disabled. But that depends on what you had in mind for this test - what was the ultimate purpose.
Another caveat is: For this to be even remotely safe, you must suspend all other threads in the process when you do this test, as there's a chance you may corrupt some state that code executing on another thread may happen to refer to. Doing this from inside a running process may have hard-to-debug corner cases that will stop lurking and show themselves during a customer demo. So, on platforms that support this, it's always preferable to spawn another process that will suspend the first process in its entirety (all threads), probe it, write the result to the process's address space (to some result variable), resume the process and terminate itself. On some platforms, it's not possible to modify a process's address space from outside, and instead you need to suspend the process mostly or completely, inject a probe thread, suspend the remaining other threads, let the probe do its job, write an answer to some agreed-upon variable, terminate, then resume everything else from the safety of an external process.
For simplicity's sake, the below will assume that it's all done from inside the process. Even though "fully capable" self-contained examples that work cross-process would not be very long, writing this stuff is a bit tedious especially if you want it short, elegant and at least mostly correct - I imagine a really full day's worth of work. So, instead, I'll do some rough sketches and let you fill in the blanks (ha).
Windows
Structured exceptions get thrown e.g. due to protection faults or divide by zero. To perform the test, attempt a read from the address in question. If that succeeds, you know it's at least a mapped page (otherwise it'll throw an exception you can catch). Then try writing there - if that fails, then it was read-only. The code is almost boring:
static const int foo;
static int bar;
#if _WIN32
typedef struct ThreadState ThreadState;
ThreadState *suspend_other_threads(void) { ... }
void resume_other_threads(ThreadState *) { ... }
int check_if_maybe_rodata(void *p) {
__try {
(void) *(volatile char *)p;
} __finally {
return false;
}
volatile LONG result = 0;
ThreadState *state = suspend_other_threads();
__try {
InterlockedExchange(&result, 1);
LONG saved = *(volatile LONG*)p;
InterlockedExchange((volatile LONG *)p, saved);
InterlockedExchange(&result, 0); // we succeeded writing there
} __finally {}
resume_other_threads(state);
return result;
}
int main() {
assert(check_if_maybe_rodata(&foo));
assert(!check_if_maybe_rodata(&bar));
}
#endif
Suspending the threads requires traversing the thread list, and suspending each thread that's not the current thread. The list of all suspended threads has to be created and saved, so that later the same list can be traversed to resume all the threads.
There are surely caveats, and WoW64 threads have their own API for suspension and resumption, but it's probably something that would, in controlled circumstances, work OK.
Unix
The idea is to leverage the kernel to check the pointer for us "at arms length" so that no signal is thrown. Handling POSIX signals that result from memory protection faults requires patching the code that caused the fault, inevitably forcing you to modify the protection status of the code's memory. Not so great. Instead, pass a pointer to a syscall you know should succeed in all normal circumstances to read from the pointed-to-address - e.g. open /dev/zero, and write to that file from a buffer pointed-to by the pointer. If that fails with EFAULT, it is due to buf [being] outside your accessible address space. If you can't even read from that address, it's not .rodata for sure.
Then do the converse: from an open /dev/zero, attempt a read to the address you are testing. If the read succeeds, then it wasn't read-only data. If the read fails with EFAULT that most likely means that the area in question was read-only since reading from it succeeded, but writing to it didn't.
In all cases, it'd be most preferable to use native platform APIs to test the mapping status of the page on which the address you try to access resides, or even better - to walk the sections list of the mapped executable (ELF on Linux, PE on Windows), and see exactly what went where. It's not somehow guaranteed that on all systems with memory protection the .rodata section or its equivalent will be mapped read only, thus the executable's image as-mapped into the running process is the ultimate authority. That still does not guarantee that the section is currently mapped read-only. An mprotect or a similar call could have changed it, or parts of it, to be writable, even modified them, and then perhaps changed them back to read-only. You'd then have to either checksum the section if the executable's format provides such data, or mmap the same binary somewhere else in memory and compare the sections.
But I smell a faint smell of an XY problem: what is it that you're actually trying to do? I mean, surely you don't just want to check if an address is in .rodata out of curiosity's sake. You must have some use for that information, and it is this application that would ultimately decide whether even doing this .rodata check should be on the radar. It may be, it may be not. Based on your question alone, it's a solid "who knows?"

How to store nodes of a list into shared memory

I am trying to make many clients communicate with each other via many terminals.I have forks inside my program and I create pipes so the clients can read/write from/to other clients.Because I create many processes I need shared memory to store some infos and in particular i want to store nodes that are created from each kid.How can I do this?
This is my struct:
typedef struct client{
char *numofclient;
struct client *nextclient;
}client;
Before forking anything create a shared memory area using mmap. Read the man page and use the shared flags. If on Windows it's different so look up VirtualAlloc and of course you can't fork.
You'll need a memory allocator for your shared memory. That can be super easy: just increment a char pointer for an allocation and never free anything. Or it can be as complex as you want. You may be able to find a library online.
If you need a mutex create one in the shared memory area and be sure to use the flags for a shared mutex.
Since you are forking you can use pointers because the shared memory will remain mapped in place in each process copy. Otherwise you'd need to use offsets from the map start.
I think you can make the systemV shared memory using shmget, read man pages.
You can decide an upper limit of how many Process are going to be created and provide that much size accordingly to shmget.
So, whenever you child process wants to store list it can just attach to the shared memory and append its data in shared memory.

Accessing static functions/variable from different threads

I use a third side library written in C. It is designed to run as singleton and contains plenty of static functions, variables and user interface. I need to be able to run it with multiple instances so they do not interfere with each other. For example if one threads sets static variable
static int index = 0;
index = 10;
the second thread still sees index = 0.
I am not sure if it is even possible to implement.
What you are asking is not possible.
Let's assume for pedagogical purposes that you are on a unix machine.
Any process (such as the executable ./a.out) has the following Memory layout :
Text
Data
Initialized
Uninitialized
Heap
Stack
When you create a thread, then it shares all these memory segments except the Stack section(basically each thread gets a new stack pointer).
Moreover the static variables are stored in the Data segment (in your case Initialized data segment) which is a shared memory segment, hence when one thread changes it, it changes for all other threads as well.
So threads only have the following things local to themself
Stack pointer
Program Counter
registers
Image source : llnl.gov
Hope it helped :-).

Can i force linux kernel to use particular memory pages for new executable

When i execute binary i want their stack segment to be filled with special data.
All i do is just write program that allocate huge buffer on a stack, call a lot of malloc and mmap and for example fill all this memory with 'A' character. Then i check and see that about 80% of whole memory are used by my program. Then i stop this program and start another program that just go through the stack and check values on stack. By i don't see my 'A' character anyway. Can someone tell me how can i do it?
UPD
Why i do is just because of one ctf. i mention task like.
int func()
{
int i;
if(i == 0xdeadbeef)
system("cat flag");
else
func();
}
int main()
{
func();
}
No, not without making heavy changes to the kernel. New anonymous pages are always zero-filled, and even if you could fill them with something else, there would be no reasonable way you could make them carry over data from old processes. Doing so would be a huge security hole in itself.

Semaphores for different parts of the same shared memory block in C

I have a question on how to set up a shared memory segment for my program.
In my program I want to have a main structure to contain 50 different accounts.
Something that looks like this.
struct list{
struct account[50];
};
Within each account there is just some basic info
struct account{
int x;
char * y;
};
Now, I want my entire list to be located in a shared memory segment as different child processes of my main process will be updating different accounts in the list.
However, I only want a child process to be able to access a certain account in this list. How exactly would I go about setting up a shared memory segment that can be locked down by a child process in different parts? For example, I want a semaphore that can lock down access to account[32] in the shared memory segment. This means that another process could be updating account[29] in the shared memory segment at the same time with no problem.
I am not really looking for concrete code examples (although those would be helpful), but more of a conceptual understanding of the best way to set up shared memory for this program.
Thanks.
If I understood what this is about, I see two alternatives:
The first one is to modify struct account, so there's one extra field, a semaphore. Any process should P() on the semaphore before it accesses the other account's fields, and V() when it's done with it.
The second would be to modify struct list, adding an extra array of semaphores, same size as the array of accounts, assigning each semaphore in the array with the same-indexed account, and using P() and V() on it again, before and after accessing the corresponding account.

Resources