undefined reference to `printk' - c

I want to use printk function in my userspace code, but I don't want to write kernel module. Is it any possibility to do that?
I tried use linux/kernel.h header and linux/module.h but it doesn't work
printk("<1>some text");

Simple Answer is No,
You can't use printk in userspace code by any means.
printk is designed for kernel programmers.
If your intention is to write to syslog -> dmesg, then use syslog() ;
It comes in handy!!
Syslog ManPage
Try This:
#include <stdio.h>
#include <unistd.h>
#include <syslog.h>
int main(void) {
openlog("slog", LOG_PID|LOG_CONS, LOG_USER);
syslog(LOG_EMERG, "Hello from my code ");
closelog();
return 0;
}
To Configure syslog for file redirection:
http://www.softpanorama.org/Logs/syslog.shtml
http://linux.die.net/man/5/syslog.conf

Using of kernel headers in userspace makes behavior or program unpredictable.
One of reasons is the memory where kernel is located is not accessible from userspace directly.
Here you can find some information about these cases:
lwn.net/Articles/113349/
kernelnewbies.org/KernelHeaders

Related

Intercepting stat call with LD_PRELOAD

I'm trying to write a shared object that intercepts some filesystem API calls such as open, close, read, write etc., that originate from an application. Interception is done using LD_PRELOAD. I've used strace methodically to find out the APIs called by the application and implement them in the shared library loaded by LD_PRELOAD. When it comes to stat, I found that __xstat and __xstat64 is called instead of stat and I've overridden these two functions. I'm able to trap these API calls. However, in one particular environment, when I use strace I see direct calls to the stat() itself. Like below
25083 03:11:28.424859 close(13) = 0 <0.000045>
>> 25083 03:11:28.424966 stat("/somedir/somefile", 0x7ffe751d2430) = -1 ENOENT (No such file or directory) <0.000050>
25083 03:11:28.425067 clock_gettime(CLOCK_MONOTONIC, {786855, 130369007}) = 0 <0.000029>
The difference I note is that stat is called directly which I don't see in other environments. It is possible that the application calls stat() however I see that stat internally calls __xstat or __xstat64. Another thing I noticed is that stat() isn't even implemented in libc.so library. So this stat() appears to be a direct invocation of the stat() system call. How do I confirm this? And how would an application directly invoke stat() system call?
So this stat() appears to be a direct invocation of the stat() system call. How do I confirm this?
Run the program inside of gdb with catch syscall stat. When the syscall happens, check the call stack with bt and take note of whether you're in libc.so.
And how would an application directly invoke stat() system call?
With inline assembly. Here's an example of it for x86-64:
#include <stdio.h>
#include <sys/stat.h>
#include <sys/syscall.h>
int main(int argc, char **argv) {
if(argc < 2) return 1;
struct stat s;
long rv;
__asm__ volatile(
"syscall"
: "=a"(rv)
: "a"(SYS_stat), "D"(argv[1]), "S"(&s)
: "rcx", "r11", "memory"
);
if(rv) return 1;
printf("%zu\n", s.st_size);
}

How puts standard library function works in C? [duplicate]

This question already has answers here:
Where can I find the source code for all the C standard libraries?
(4 answers)
Closed 11 months ago.
While going through the standard library functions of C (glibc), I found that printf() actually calls puts() functions (_IO_puts). But I am unable to find out how the puts function actually writes to the stdout ?
Does it uses write() system call defined in unistd.h or something else ? One thing I find out that puts() actually calling _IO_xputn through _IO_putn.
Please help. Thank you.
For Unix based systems for which Linux is part, most functions in stdio library are wrappers that are one layer above the standard I/O system calls. You see, the operating system provides a set of APIs called system calls. Applications cannot directly access hardware resources and hence they usually call these "system calls" whenever they need to do any sort of privileged thing like writing to the screen or reading from the keyboard.
In Unix, everything is abstracted as a file so whenever you need to write characters to a screen, all you need to do is open some file that represents the "screen" and write those characters there. The kernel will take care of the rest. Quite simply, this is how you'd do this in C:
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#define BUFF_SIZE 2
int main()
{
int terminal;
char buffer[BUFF_SIZE] = "C\n"; // This will store the character to print + new line
terminal = open("/dev/tty", O_WRONLY); // systemcall to open terminal
if (terminal < 0)
exit(1); // some error happened
dup2(terminal, STDOUT_FILENO); // use our newly opened terminal as default Standard output
if (write(terminal, buffer, BUFF_SIZE) != BUFF_SIZE) // systemcall to write to terminal
exit(1); // We couldn't write anything
}
This just goes to show you that everything in stdio is layered on top of the basic I/O system calls. These system calls are read, write, open, etc. If you want to learn more about system calls and some OS internals, read the book "Three Easy Pieces" by Andrea Arpaci-Dusseau

Kernel Module memory access

I'm new to kernel modules and currently experimenting with it.
I've read that they have the same level access as the kernel itself.
Does this mean they have access to physical memory and can see/overwrite
values of other processes (including the kernel memory space)?
I have written this simple C code to overwrite every memory address but it's not doing anything (expecting the system to just crash, not sure if this is touching physical memory or it's still virtual memory)
I run it with sudo insmod ./test.ko, the code just hangs there (because of the infinite loop of course) but system works fine when I exit manually.
#include <linux/module.h>
#include <linux/kernel.h>
int init_module(void)
{
unsigned char *p = 0x0;
while (true){
*p=0;
p++;
}
return 0;
}
void cleanup_module(void)
{
//
}
Kernel modules run with kernel privileges (including kernel memory and all peripherals). The reason why your code isn´t working is, that you don´t specify the init and exit module. So you can load the module, but the kernel doesn´t call your methods.
Please take a look at this example for a minimal kernel module. Here you will find some explanation about the needed macros.

Memory Monitoring for each process in linux

I would like to implement my kernel to be able to monitoring memory of each process. However, all I can do is to only print out the process and pid. I can't find a function that can help in monitoring memory. Here is the code in the kernel that i Implemented. I use Linux kernel version 4.11.0-rc7.
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/resource.h>
#include <linux/sched.h>
#include <linux/syscalls.h>
asmlinkage long sys_listProcessInfo(void){
struct task_struct *process;
struct rusage usage;
int i = 0;
for_each_process(process){
if(i%10 == 0){
printk("Process %s\n PID: %ld\n",process->comm,(long)task_pid_nr(process));
i++;
}
}
return 0;
}
This one can only view process and pid. I would like to know if there is any function that can look for the memory of the process. Thank you in advance.
For a process other than the current one, use the /proc file system.
char fName[32]; // you should really only need 24
sprintf(fName, "/proc/%d/status", pid);
FILE* status = fopen(fName , "r" );
That file will have information about the process's memory allocation (virtual, resident, etc.) See man7's page on /proc for details.
This is similar but not identical to this post.
This is the standard wrong kernel code (ignoring locking requirements etc.). The function name and intended purpose strongly hint this is just a college assignment. There were several other people coming up with problems of similar quality.
As each time it was clear the person asking is fundamentally not prepared to do this work, each time I ask who gave them the assignment and what material were they provided with.
Can you please answer the above?
Thanks.
EDIT
See this for a general overview what's wrong with code samples of the sort:
http://codingtragedy.blogspot.com/2016/12/bad-kernel-tutorials-for-beginners.html
This website is unsuitable for kernel-related questions (or most lower level stuff from that matter). I'm afraid you will have to consult your fellow students. Preferably though someone would make sure tasks of the sort are not assigned to unprepared students, or even at all.

Make a variable local to a thread [duplicate]

Short version of question: What parameter do I need to pass to the clone system call on x86_64 Linux system if I want to allocate a new TLS area for the thread that I am creating.
Long version:
I am working on a research project and for something I am experimenting with I want to create threads using the clone system call instead of using pthread_create. However, I also want to be able to use thread local storage. I don't plan on creating many threads right now, so it would be fine for me to create a new TLS area for each thread that I create with the clone system call.
I was looking at the man page for clone and it has the following information about the flag for the TLS parameter:
CLONE_SETTLS (since Linux 2.5.32)
The newtls argument is the new TLS (Thread Local Storage) descriptor.
(See set_thread_area(2).)
So I looked at the man page for set_thread_area and noticed the following which looked promising:
When set_thread_area() is passed an entry_number of -1, it uses a
free TLS entry. If set_thread_area() finds a free TLS entry, the value of
u_info->entry_number is set upon return to show which entry was changed.
However, after experimenting with this some it appears that set_thread_area is not implemented in my system (Ubunut 10.04 on an x86_64 platform). When I run the following code I get an error that says: set_thread_area() failed: Function not implemented
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <linux/unistd.h>
#include <asm/ldt.h>
int main()
{
struct user_desc u_info;
u_info.entry_number = -1;
int rc = syscall(SYS_set_thread_area,&u_info);
if(rc < 0) {
perror("set_thread_area() failed");
exit(-1);
}
printf("entry_number is %d",u_info.entry_number);
}
I also saw that when I use strace the see what happens when pthread_create is called that I don't see any calls to set_thread_area. I have also been looking at the nptl pthread source code to try to understand what they do when creating threads. But I don't completely understand it yet and I think it is more complex than what I'm trying to do since I don't need something that is as robust at the pthread implementation. I'm assuming that the set_thread_area system call is for x86 and that there is a different mechanism used for x86_64. But for the moment I have not been able to figure out what it is so I'm hoping this question will help me get some ideas about what I need to look at.
I am working on a research project and for something I am experimenting with I want to create threads using the clone system call instead of using pthread_create
In the exceedingly unlikely scenario where your new thread never calls any libc functions (either directly, or by calling something else which calls libc; this also includes dynamic symbol resolution via PLT), then you can pass whatever TLS storage you desire as the the new_tls parameter to clone.
You should ignore all references to set_thread_area -- they only apply to 32-bit/ix86 case.
If you are planning to use libc in your newly-created thread, you should abandon your approach: libc expects TLS to be set up a certain way, and there is no way for you to arrange for such setup when you call clone directly. Your new thread will intermittently crash when libc discovers that you didn't set up TLS properly. Debugging such crashes is exceedingly difficult, and the only reliable solution is ... to use pthread_create.
The other answer is absolutely correct in that setting up a thread outside of libc's control is guaranteed to cause trouble at a certain point. You can do it, but you can no longer rely on libc's services, definitely not on any of the pthread_* functions or thread-local variables (defined as such using __thread or thread_local).
That being said, you can set one of the segment registers used for TLS (GS and FS) even on x86-64. The system call to look for is prctl(ARCH_SET_GS, ...).
You can see an example comparing setting up TLS registers on i386 and x86-64 in this piece of code.

Resources