Home > OS >  stack smashing when receiving a single message through message queues
stack smashing when receiving a single message through message queues

Time:02-01

I have the following sender:

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <errno.h>

typedef struct message {
    long int mtype;
    int mtext[200];
} message;

int main(int argc, char *argv[]) {
    // msg queue
    int msgid;
    message msg;
    key_t key;
    
    // create msg queue key
    if ((key = ftok("master.c", 'b')) == -1) {
        perror("ftok");
    }

    // create msg queue
    if ((msgid = msgget(key, 0666 | IPC_CREAT)) == -1) {
        perror("msgget");
    }

    msg.mtype=10;
    msg.mtext[0] = 1;
    if ((msgsnd(msgid, &msg, sizeof(message), 0)) == -1) {
        perror("msgsnd");
    }
    sleep(5);

    // TODO: uncomment section
    if (msgctl(msgid, IPC_RMID, NULL) == -1) {
        perror("msgctl");
    }
    
    return 0;
}

And receiver:

#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <errno.h>

typedef struct message {
    long int mtype;
    int mtext[200];
} message;

int main(int argc, char *argv[]) {
    // msg queue
    message msg;
    int msgid;
    key_t key;
    
    // create msg queue key
    if ((key = ftok("master.c", 'b')) == -1) {
        perror("ftok");
    }

    // create msg queue
    if ((msgid = msgget(key, 0666)) == -1) {
        perror("msgget");
    }

    if ((msgrcv(msgid, &msg, sizeof(message), 10, 0)) == -1) {
        perror("msgrcv");
    }
    printf("%d\n", msg.mtext[0]);

    return 0;
}

The problem is that when I run both of them, I am getting

*** stack smashing detected ***: terminated
Aborted (core dumped)

The above phrase is shown after the whole code has executed as intended but still, it means that something is not right. If, though, I place msgrcv in an infinite loop, everything runs as intended and no warning is raised. Since I am both writing and reading the same size of data, where could the error come from?

CodePudding user response:

According to the documentation, the msgsz argument to msgrcv should indicate the size (in bytes) of the .mtext member of the message structure, rather than the size of the entire structure.

That structure will typically be 4 or 8 bytes (depending on how long int is defined) larger than the available buffer, so you are likely writing beyond the available/assigned memory – causing undefined behaviour.

One possible effect of that UB is corruption of the stack allocated for the main function; if that function never returns (as when you add the infinite loop), that stack corruption may not manifest itself.

  •  Tags:  
  • Related