System call and Module programming

Source: Internet
Author: User
Tags dmesg

Objective

Reprint Please indicate the source http://www.cnblogs.com/dvd0423/p/4183443.html

The best thing about the kernel is that it gives you the feeling of standing on the mountain and seeing the scenery. As the No. 0 post says, whatever it is, it's always good to know why.  

The content of this series revolves around the Linux kernel, which is mainly about the parts I encountered in the process of KVM, Network, Dispatch, KVM and so on. Although it is the bottom of the thing, but the application of the people to look at it is no harm. We all know that the kernel is too large, to fully understand the almost impossible, so we can only according to their own needs to targeted learning. And such a huge project can be organized orderly, hierarchical, so that a beginner to face a monster not to be able to, can only sigh people outside, heavens beyond heavens ah. In fact, the kernel has developed to now, has a lot of depth of different books and documents, there are more and more people to join the community, you have encountered the problems encountered by others, so now the kernel is not so difficult to learn. We have to say that we can quickly start the kernel, mainly because we stand on the head of the giant, forget it or stand on the shoulder.

This series of articles about the kernel will also introduce the Knowledge of UNIX advanced environment programming, and combine the high-level applications I know to know the kernel, so that both the bottom and the high-level are a kind of understanding of the deepening. This article mainly introduces system calls, module programming, and Hook functions. Why don't I start with a compilation installation here? Because I work part-time in the school cluster operation, I now most hate is to build a cluster environment (this part please Baidu).

1 system calls

The kernel is a hair embryo room, after the system call into a fine decoration, and the application is to let the house has three-dimensional furniture. All applications must be called by the system. It's a little exaggerated, but when I hear that, I know why I'm talking about the system call, which is the portal to the user's access to the kernel. High-level applications can create processes, network communications, memory operations, read files, and various shell commands, all of which are the direct credit. And we see the C++/java/pathon and so on a variety of language libraries, are encapsulated system calls, the essence is the same. If we want to deal with the kernel and do not want to drill into the kernel source code, then understand the system calls. Like in Java.

String cmds= "Java-version"= Runtime.getruntime (). exec (CMDS);

These two statements create a Process Execution Cmds command, while a new process is created in POSIX C with fork ()/exec (). But they go deep into the Linux kernel and call Do_fork (). Understanding the virtual machine's friends know that there is a Hypercall interface function, the implementation principle and syscall similar, here no longer extend, will talk about in the future. (thanks to a classmate named "The Sea" in the lab)

For our user program, use the Strace command to track system calls. The command format is:

# Strace–o Log.txt./hello

Let's take the open system invocation as an example to illustrate its rationale. The function prototype for open in the kernel is as follows:

1 Const Char int , Flags, umode_t, mode) 2 {3     if (Force_o_largefile ()) 4         Flags |= o_largefile; 5 6     return do_sys_open (AT_FDCWD, filename, flags, mode); 7 }

In the user space system, the function prototype is called:

Long Open (constcharintint mode);

Of course, you can also call the Syscall () function in a different way, using the method in detail with the man command. The above function is equivalent to:

1 /*2 #define __nr_restart_syscall 03 #define __NR_EXIT 14 #define __nr_fork 25 #define __nr_read 36 #define __nr_write 47 #define __nr_open 58 ...9 */TenSyscall (NUM,Const Char*, filename,int, Flags,int, mode);//num is the call number, followed by the parameter, here is the 5
Syscall

Let's implement our own system calls to deepen our understanding of the system invocation of this tool. The first thing to do is to implement your own system call to add the call number to the system call table/arch/sh/include/uapi/asm/unistd_64.h, plus 1 for the total number of calls.

#define __nr_firstsyscall     380        // added part #define nr_syscalls   381        // originally for 380  

Next , add the corresponding table entry in the system call table SYSCALL_TABLE.S.

 entry (sys_call_table).  long  sys_restart_syscall /*   0-old "Setup ()" System call, * used for restarting  */  ....  long   sys_kcmp.  long   Sys_finit_module  /*   add your own  */  long  sys_firstsyscall 380  */  

The third implementation of the system calls the specific program

int , value) {    PRINTK ("Fuckdw");     return value;}

Finally, the system call is implemented in the user space:

#include <linux/unistd.h><syscall.h><sys/types.h><stdio.h> int Main (intChar* * argv)      {printf ("%ld\n", Syscall (380423));           return 0 ;}

Then the most troublesome thing is to recompile the kernel.

2 Module Programming

Because of the limited energy, I did not understand the modularity in Linux implementation principle, I use it mainly to extract the kernel source of some data structure. This is what it does when it comes to networking and scheduling. To use kernel parameters in your own module, first use the Export_symbol (INIT_NET) macro declaration to make the init_net variable callable.

The following function realizes the function of displaying all network devices, and of course we can randomly extract and change any data structure in the kernel:

1 /*2 *init_net is a global variable that can be called within a module. Here with the Hello World function can replace the Get_devs () function, do not understand it does not matter, this is not the point. 3 *printf corresponding to PRINTK in Inland River4  */5#include <linux/init.h>6#include <linux/module.h>7#include <linux/kernel.h>8#include <linux/netdevice.h>9#include <net/net_namespace.h>Ten#include <linux/netdevice.h> One#include <linux/list.h> A  -Module_license ("GPL");//permission statement, to be added in -  the  - Static intGet_devs (void) - { -     structNet_device *a_dev = Dev_get_by_name (&init_net,"eth0");//Get +     structList_head *p; -     structNet_device *Temp_dev; +     inti =0; A  atList_for_each (P, & (a_dev->dev_list)) { -Temp_dev = List_entry (P,structNet_device, dev_list); -          -Printk"%d\t%s\n", (++i), temp_dev->name); -     } - Dev_put (A_dev); in     return 0; - } to //functions that load module runs + Static int__init Mode4_init (void) - { thePrintk"Module 4 init!\n"); * Get_devs (); $     return 0;Panax Notoginseng } -  the Static void__exit Mode4_exit (void) + { APrintk"Module 4 exit!\n"); the  + } -  $Module_init (Mode4_init);//registering the module $Module_exit (Mode4_exit);
mode4.c

After writing the code, write the makefile file as follows:

1 obj-m + = mode4.o2pwd)3uname -R)/45 all :6     $ (make)-C $ (kdir) m=$ (PWD) modules78  Clean:9     $ (make)-C $ (Kdir) m=$ (PWD) Clean
Makefile

Enter the following command at the command line:

make Insmod Mode4.ko //Load Module # DMESG//Display the following information                              , saved in the directory/VAR/LOG/DMESG  

  

  

  

# rmmod Mode4.ko                 // unload module, display Module 4 exit!   make clean                     // Clear Compile file

We can also pass command-line arguments to the module, implemented with Module_param () or Module_param_array () macros. The specific use of their own view of the source bar.

Programming with modules also allows you to add some of the features you want to the kernel. Module programming is also the beginning of a custom operating system.

3 hook function

This is not good implementation, the principle is probably the user to intercept the kernel message, modified to return to the kernel, the kernel according to the user's settings to choose a different mode of operation. Later in the network module will be mentioned. Many commands use the hook function to make changes to the operating system.

Write it down here today. To tell the truth here and feel not to write, the main reason is that when I understand one thing, I write every word I feel is superfluous, are obviously very simple nonsense. But I think there are some students do not understand, I hope I write can help others. After all, you have been thinking for a long time, the result of someone else a word to help you solve the problem, that mood experienced people understand.

by Sugar Ball

System call and Module programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.