Segfault scanf and fprintf - struct

I'm trying to write a small database program which will have 5 functions, the first one is Add() but I get SegFault error on scanf:
void Add();
struct data{
char name[20];
char description[300];
int quantity;
};
typedef struct data dataobj;
dataobj element;
int main()
{
Add();
return 0;
}
Add() {
FILE *database;
database = fopen("database.txt", "a+");
printf("Object: \n");
fgets(element.name,20,stdin);
fprintf(database, element.name);
printf("Description: \n");
fgets(element.description,300,stdin);
fprintf(database, element.description);
printf("Quantity: \n");
scanf("%d",&element.quantity);
fprintf(database, element.quantity);
fclose(database);
}
this is the error: Program received signal SIGSEGV, Segmentation fault.
In ungetwc () (C:\WINDOWS\SysWOW64\msvcrt.dll)
debugger window:
#0 0x77bea965 ungetwc() (C:\WINDOWS\SysWOW64\msvcrt.dll:??)
#1 0x77c21268 msvcrt!_iob() (C:\WINDOWS\SysWOW64\msvcrt.dll:??)
#2 ?? ?? () (??:??)
Also I noticed that if I write fgets after scanf instruction, fgets will not be executed for some reasons.. So, in the prototype I had to keep this order: char char int (for example I couldnt write: char int char)

Solved, I was trying to print the int directly, I should have used:
printf("Quantity: \n");
scanf("%d", &element.quantity);
fprintf(database,"%d", element.quantity);
forgot the %d

Related

printf is producing the segmentation fault?

I'm learning threads and my code runs upto last print statement. Why it is giving segmentation fault at print? I think possible reason could be non-existant address passed as argument to print, but it is not the reason, I'm passing valid address.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *thread (void *vargp) {
int arg = *((int*)vargp);
return &arg;
}
int main () {
pthread_t tid;
int thread_arg = 0x7ffdbc32fa34;
int *ret_value;
pthread_create(&tid, NULL, thread, &thread_arg);
pthread_join(tid, (void **)(&ret_value));
printf("hello\n");
printf("%X\n", *ret_value);
return 0;
}
It is giving following output:
hello
Segmentation fault (core dumped)
Is it because I'm returning an address of a local variable, which gets destroyed once thread is returned? I don't think so, because changing to following code is also giving me segmentation fault!
void *thread (void *vargp) {
int * arg = malloc(sizeof(int));
*arg = *((int*)vargp);
return &arg;
}
Is it because I'm returning an address of a local variable, which gets
destroyed once thread is returned?
Yes, it is.
I don't think so, because changing to following code is also giving me
segmentation fault!
This code is also returning the address of a local variable (return &arg;). Instead, you should be returning the pointer value that malloc() returned (return arg;):
void *thread (void *vargp)
{
int * arg = malloc(sizeof(int));
*arg = *((int*)vargp);
return arg;
}
You also should not be casting the address of ret_value to type void ** in main() - the variable is of type int * not void *, so it shouldn't be written to through a void ** pointer (although, in practice, this will usually work). Instead, you should be using void * variable to hold the return value, then either casting this value to int * or assigning it to a variable of type int *:
void *ret_value;
pthread_create(&tid, NULL, thread, &thread_arg);
pthread_join(tid, &ret_value);
printf("%X\n", *(int *)ret_value);

Why can't kprobe probe some functions in the kernel?

I tried to probe a simple function (e.g. myfunc) which I added in the kernel as following:
I created a file (myfile.c) under ~/source/kernel/ i.e. ~/source/kernel/myfile.c
I added a simple system call mysyscall and a local function myfunc in this file.
mysyscall function calls myfunc function.
I can get the address of the function using
cat /proc/kallsyms | grep myfunc
But the kprobe handler doesn't get called when I call the myfunc.
I can probe the system call 'mysyscall'. But when I try to probe 'myfunc', the handler doesn't get called.
Can anyone please explain why this is the behavior? Thanks.
As asked by Eugene, below is the code for kprobe and, mysyscall & myfunc.
The kprobe handler doesn't get called in the following code. But if i uncomment Line B and comment A in kprobe code given below, then kprobe handler gets called.
I used kernel version 4.8.
I added ~/source/kernel/myfile.c to write mysyscall and myfunc as given below:
#include <linux/linkage.h>
#include <linux/export.h>
#include <linux/time.h>
#include <asm/uaccess.h>
#include <linux/printk.h>
#include <linux/slab.h>
extern int myfunc(int ax)
{
int x = 6;
return x;
}
asmlinkage int* sys_mysyscall(int bx){
int *retval;
int ret = 0;
printk(KERN_ALERT "Hello World!\n");
ret = myfunc(10);
retval = kmalloc(sizeof(int), GFP_KERNEL);
*retval = 55;
printk("sum: %d\n", *retval);
printk("myfunc return value: %d\n", ret);
return retval;
}
EXPORT_SYMBOL(sys_mysyscall);
kprobe module code is as below:
#include<linux/module.h>
#include<linux/version.h>
#include<linux/kernel.h>
#include<linux/init.h>
#include<linux/kprobes.h>
//Line A
static const char *probed_func = "myfunc";
//Line B
//static const char *probed_func = "sys_mysyscall";
static unsigned int counter = 0;
int Pre_Handler(struct kprobe *p, struct pt_regs *regs){
printk("Pre_Handler: counter=%u\n",counter++);
return 0;
}
void Post_Handler(struct kprobe *p, struct pt_regs *regs, unsigned long flags){
printk("Post_Handler: counter=%u\n",counter++);
}
static struct kprobe kp;
int myinit(void)
{
int error;
printk("module inserted\n ");
kp.pre_handler = Pre_Handler;
kp.post_handler = Post_Handler;
kp.addr = (kprobe_opcode_t *)kallsyms_lookup_name(probed_func);
error = register_kprobe(&kp);
if(error)
{
pr_err("can't register_kprobe :(\n");
return error;
}
else
{
printk("probe registration successful\n");
}
return 0;
}
void myexit(void)
{
unregister_kprobe(&kp);
printk("module removed\n ");
}
module_init(myinit);
module_exit(myexit);
MODULE_AUTHOR("psin");
MODULE_DESCRIPTION("KPROBE MODULE");
MODULE_LICENSE("GPL");
I use a kernel module to call mysyscall as below:
sys_mysyscall(12);//12 is some random integer as parameter

IOCTL Method - Linux

I have an exam question and I can't quite see how to solve it.
A driver that needs the ioctl method to be implemented and tested.
I have to write the ioctl() method, the associated test program as well as the common IOCTL definitions.
The ioctl() method should only handle one command. In this command, I need to transmit a data structure from user space to kernel space.
Below is the structure shown:
struct data
{
     char label [10];
     int value;
}
The driver must print the IOCTL command data, using printk();
Device name is "/dev/mydevice"
The test program must validate driver mode using an initialized data structure.
Hope there are some that can help
thanks in advance
My suggestion:
static int f_on_ioctl(struct inode *inode, struct file *file, unsigned int cmd,
unsigned long arg)
{
int ret;
switch (cmd)
{
case PASS_STRUCT:
struct data pass_data;
ret = copy_from_user(&pass_data, arg, sizeof(*pass_data));
if(ret < 0)
{
printk("PASS_STRUCT\n");
return -1;
}
printk(KERN ALERT "Message PASS_STRUCT : %d and %c\n",pass_data.value, pass_data.label);
break;
default:
return ENOTTY;
}
return 0;
}
Definitions:
Common.h
#define SYSLED_IOC_MAGIC 'k'
#define PASS_STRUCT _IOW(SYSLED_IOC_MAGIC, 1, struct data)
The test program:
int main()
{
int fd = open("/dev/mydevice", O_RDWR);
data data_pass;
data_pass.value = 2;
data_pass.label = "hej";
ioctl(fd, PASS_STRUCT, &data_pass);
close(fd);
return 0;
}
Is this completely wrong??

Initial assignment a Char Array using a Function in C

as we know it in C, a string defining is,
char string[] = "Hello World";
That is OK,
But I want to use a function and at initial same up,
I tried those, For example;
char * to_string()
{
return "Hello World";
}
Or;
char * to_String(void) // Function
{
char buff[16];
sprintf(buff, "%s", "Hello World");
return buff;
}
main() // main function
{
char Initial_String[] = to_String();
}
How to make this or any idea same another way.
I find what I dont send address of char Initial_String[] to fill into. No. is there Another method.
Thanks.
When you compile this, atleast in GCC, it will give you the following warning:
b.c:9: warning: function returns address of local variable
Why? Because buff[] is a local variable of function to_string(). Its scope is only inside the function to_string(). main() does not have any access to this variable. Try making buff[] a global variable instead.
Second problem: char Initial_String[] = to_String(); cannot be assigned value in this way. to_string() returns a char pointer, hence assign the value thus:
char *Initial_String = to_String();
The code below will work:
char buff[16];
char* to_String(void) // Function
{
//char buff[16]; /*this is a local variable*/
sprintf(buff, "%s", "Hello World");
return buff;
}
int main(void) // main function
{
char *Initial_String = to_String();
printf("%s", Initial_String);
return 0;
}
Yes You are right about local buffer mismake,
But This is not my wanting,
if I edit some differently,
char buff[16];
char* to_String(void) // Function
{
//char buff[16]; /*this is a local variable*/
sprintf(buff, "%s", "Hello World");
return buff;
}
int main(void) // main function
{
char *Initial_String_1 = to_String();
char *Initial_String_2 = to_String();
char *Initial_String_3 = to_String();
printf("%s", Initial_String_1 );
printf("%s", Initial_String_2 );
printf("%s", Initial_String_3 );
in this case, all strings will be same, because They have same buffer address,
I want to open the topic little more.
struct
{
long aaa;
short bbb;
int ccc;
char ddd;
.
.
. // the list goes on
}elements;
typedef struct
{
int lengt;
int *adress;
char name[10];
}_list;
char* to_String(long variable) // Function
{
sprintf(buff, "%ld", variable);
return buff;
}
int main (void)
{
_list My_List[] = {
{ sizeof(elements.aaa), &elements.aaa , to_string( elements.aaa) },
{ sizeof(elements.bbb), &elements.bbb , to_string( elements.bbb) },
{ sizeof(elements.ccc), &elements.ccc , to_string( elements.ddd) },
.
.
. //// the list goes on
};
I do not know, Do I make myself clear.
Here, string must be filled into name array, without assigning it the address.
I may have syntax mistake. the code is not tested with compiler. the idea is for illustrative purposes only.
I am trying to find a method for The purpose.
Thanks.

Backtracing on Linux 64 bit from Signal Handler with malloc/free on callstack

Below is an example of source I want to use on a machine running "Red Hat Enterprise Linux 5.5 (Tikanga) Kernel 2.6.18-194.el5xen x86_64" OS.
The general idea is that I want to have backtrace of some thread, so I am raising a SIGUSR1 signal for that thread and a handler does a backtrace() call.
In my scenario as below, FrameTwo function calls malloc and free in a loop. Whenever the signal is raised for this particular thread and free or malloc is on the callstack, the progream crashes when the signal handler calls backtrace().
(gdb) where (stack from gdb)
0 0x0000003e67207638 in ?? ()
1 0x0000003e672088bb in _Unwind_Backtrace
2 0x00000037ba0e5fa8 in backtrace ()
3 0x000000000040071a in handler ()
4 <signal handler called>
5 0x00000037ba071fac in _int_free ()
6 0x0000000a33605000 in ?? ()
7 0x000000004123b130 in ?? ()
8 0x00000000004007d4 in ThreadFunction ()
9 0x000000001f039020 in ?? ()
10 0x000000004123b940 in ?? ()
11 0x0000000000000001 in ?? ()
12 0x0000000000000000 in ?? ()
I learned from other sources that backtrace shouldn't be called from a signal handler, so I have written my own function grok_and_print_thread_stack() for this case.
It uses the RBP register to navigate the stack (RBP contains the base pointer of the current frame points to the previous frame's base pointer), but this algorithm does not work in this case either: when _int_free () is on the callstack, the RBP register navigation algorithm breaks, because the RBP of _int_free is some value like 0x20 which is not a valid frame's base pointer.
Does anyone know how a callstack can be navigated from the registers? Or how can I use backtrace for my purpose?
#include "stdio.h"
#include "stdlib.h"
#include "pthread.h"
#include "signal.h"
#include "syscall.h"
#include "string.h"
#include "inttypes.h"
//####################################################################
//gcc BacktraceTestProgram.c -o backtracetest -lpthread
//./backtracetest
//gdb -c core backtracetest
//####################################################################
volatile sig_atomic_t flag = 1;
int thlist[6] = {0};
int cnt = 0;
int *memory = NULL;
//####################################################################
void raiseUserSignal(int tid)
{
union sigval value;
value.sival_int = 1;
sigqueue(tid,SIGUSR1, value);
}
//####################################################################
int grok_and_print_thread_stack()
{
int ret = 0;
register uint64_t* rbp asm("rbp");
/*if buffer was built before, add separator */
uint64_t *previous_bp;
/*save pointers*/
previous_bp = rbp;
/* stack Traversal */
while(previous_bp)
{
uint64_t *next_bp;
next_bp = (uint64_t*)*previous_bp;
printf("Read BP: %lx \n", next_bp);
if ( NULL == (void*)next_bp )
{
printf("Reached the top of the stack\n");
fflush(stdout);
break;
}
previous_bp = next_bp;
}
return ret;
}
//####################################################################
void handler(int signum, siginfo_t *info, void *context)
{
int nptrs = 0 ;
void *buffer[100] = {NULL};
char **strings = NULL;
nptrs = backtrace(buffer, 100);
flag = 1;
}
//####################################################################
void FrameTwo(const char A)
{
do{
if( memory == NULL)
memory = (int *)malloc(sizeof(int) *5);
if(memory != NULL) {
free(memory);
memory = NULL;
}
}while(1);
}
//####################################################################
void FrameOne(int no)
{
FrameTwo('A');
}
//####################################################################
void *ThreadFunction( void *ptr )
{
int tid = syscall(SYS_gettid);
thlist[cnt++] = tid;
FrameOne(10);
}
//####################################################################
void RegisterSignalHandler()
{
/* Register a Signal Handler */
struct sigaction usrsig_action;
usrsig_action.sa_flags = SA_SIGINFO;
usrsig_action.sa_sigaction = &handler;
sigaction (SIGUSR1, &usrsig_action, NULL);
}
//####################################################################
int main(int no , char *argc[] )
{
int iret1;
pthread_t thread1;
RegisterSignalHandler();
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, ThreadFunction, NULL);
while(cnt == 0);
while(1) {
if(flag == 1){
flag = 0;
raiseUserSignal(thlist[0]);
}
}
pthread_join( thread1, NULL);
return 0;
}
In general x86_64 programs are likely to have been built with -fomit-frame-pointer as it is the default when optimisation is on.
What that means is that RBP is not usable for unwinding the stack and you will either need to use the DWARF unwind information (if you have debugging information available) or the exception unwind table.
You may want to look at the libunwind project.
The primary goal of [libunwind] is to define a portable and efficient C programming interface (API) to determine the call-chain of a program. [...] As such, the API is useful in a number of applications. Some examples include:
debuggers
The libunwind API makes it trivial for debuggers to generate the call-chain (backtrace) of the threads in a running program/
In particular, have a look at the local unwinding section of their documentation, it contains explanations and the following code example (with you need to link with -lunwind) that prints the backtrace of the current function:
#define UNW_LOCAL_ONLY
#include <libunwind.h>
void show_backtrace (void) {
unw_cursor_t cursor; unw_context_t uc;
unw_word_t ip, sp;
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
while (unw_step(&cursor) > 0) {
unw_get_reg(&cursor, UNW_REG_IP, &ip);
unw_get_reg(&cursor, UNW_REG_SP, &sp);
printf ("ip = %lx, sp = %lx\n", (long) ip, (long) sp);
}
}

Resources