Linux Kernel Study Notes (3)

Source: Internet
Author: User

 

2. System Call and parameter transfer process
Speaker: Xiao Bai's speech time: 08:36:45

1. How the system calls the function interface to convert it into a command

A system call enters the core State through a command, and then finds the corresponding processing function entry address in the system call table based on the system call number sent to the core. This process is described in detail here.
Take x86 as an example:
Because a running command is a special command and relies on the platform implemented by the operating system, for example, in x86, this command is int 0x80, this is clearly not the statement that the user should use during programming, because it will make the user program difficult to transplant. Therefore, a corresponding system call library needs to be implemented at the upper layer of the operating system. Each system call contains an entry point in the Library (as shown in the fork, open, close, etc.), these functions are visible to the programmer, and the job of these library functions is to use the corresponding system call number as the parameter, the execution is stuck in the Command int 0x80, to get into the core and execute the real system call handler. When a process calls a specific system call library entry point, just as it calls any function, it also needs to create a stack frame for the library function. When a process is executed in a command, it converts the processor state to the core State and executes the core code on the core stack.

Here is an example (Linux/include/ASM/unistd. h ):
# DEFINE _ syscalln (type, name, type1, arg1, type2, arg2 ,...)/
Type name (type1 arg1, type2 arg2 )/
{/
Long _ res ;/
_ ASM _ volatile ("int $0x80 "/
: "= A" (_ res )/
: "0" (_ nR _ # name), "B" (long) (arg1), "C" (long) (arg2 )));/
......
_ Syscall_return (type ,__ res );/
}
When executing a system call entry function defined in the System Call Library, the actual execution is similar to the above Code. Some embedded assembly languages of GCC are involved here. We will not detail them here, but briefly describe their meanings:
Here, _ nR _ # name indicates the system call number. For example, name = IOCTL indicates _ nr_ioctl, it will be placed in the register eax and passed as a parameter to the handler that interrupts 0x80. Other parameters called by the system: arg1, arg2 ,... These parameters are sequentially placed in General registers such as EBX, ECx,... and used as parameters for the system to call the processing function. How these parameters are passed into the core will be described later.

The following is an example:
Int func1 ()
{
Int FD, retval;
FD = open (filename ,......);
......
IOCTL (FD, CMD, ARG );
...
}

Func2 ()
{
Int FD, retval;
FD = open (filename ,......);
......
_ ASM _ volatile __(/
"Int $0x80/n/t "/
: "= A" (retval )/
: "0" (_ nr_ioctl ),/
"B" (FD ),/
"C" (CMD ),/
"D" (ARG ));
}
These two functions run the same result on Linux/x86.
Several database functions can be mapped to the same system call entry point. The system call entry point defines the true syntax and semantics of each system call, but the library function usually provides a more convenient interface. For example, the system calls exec in a set of different calling methods: execl, execle, and so on. They are actually just different interfaces called by the same system. For these calls, their library functions process their respective parameters to achieve their own characteristics, but are eventually mapped to the same core entry point.


2. The parameter passing process after the system call falls into the kernel

When a process executes a system call, it first calls the System Call Library to define a function. This function is usually expanded into the core through int 0x80 in the _ syscalln format mentioned above, its parameters will also be passed to the core through registers.
In this section, we will introduce the processing function system_call of int 0x80.
When you think about it, you will find that the execution state is completely different before and after the call: the former executes the user State Program on the user stack, and the latter executes the core State Code on the core stack. Therefore, to ensure that the user code can be returned to the call point after the system call is executed within the core, a context layer must be added to the core when the core State is saved; A context layer will pop up when returning data from the core so that the user process can continue to run.
How is the context information saved and what context information is saved? The following uses x86 as an example.
When executing the int command, the following operations are actually completed:
(1) Since int commands are transferred between different priorities, the core stack information (SS and ESP) with high priority is obtained from TSS (Task status segment) first );
(2) Keep the low-priority stack information (SS and ESP) to the high-priority stack (that is, the core stack;
(3) Push eflags, external CS, and EIP into the high-priority stack (core stack.
(4) Load CS and EIP through IDT (Control Transfer to interrupt processing function)
Then the handler system_call that interrupts 0x80 is entered. A macro save_all is used in this function. The macro definition is as follows:
# Define save_all/
CLD ;/
Pushl % es ;/
Pushl % Ds ;/
Pushl % eax ;/
Pushl % EBP ;/
Pushl % EDI ;/
Pushl % ESI ;/
Pushl % edX ;/
Pushl % ECx ;/
Pushl % EBX ;/
Movl $ (_ kernel_ds), % edX ;/
Movl % edX, % Ds ;/
Movl % edX, % es;
This macro is used to push the register context to the core stack. For system calls, it is also the input process of system call parameters, because the conversion is controlled between different privileged levels, unlike the Call Command, the int command does not automatically copy the parameters of the outer stack to the inner stack. Therefore, when calling a system call, you must first specify the parameter to each register as mentioned in the previous example, then, after entering the core, use save_all to push the parameters stored in the Register into the core stack in sequence so that the core can use the parameters passed by the user.

The source code of system_call is given below:
Entry (system_call)
Pushl % eax # Save orig_eax
Save_all
Get_current (% EBX)
CMPL $ (nr_syscils), % eax
Jae badsys
Testb $0x20, flags (% EBX) # pf_tracesys
JNE tracesys
Call * symbol_name (sys_call_table) (, % eax, 4)
......
All the work done here is:
I. Save the eax register because the eax register saved in save_all will be overwritten by the called return value;
Ii. Call save_all to save the register context;
Iii. Determine whether the current call is a legal system call (eax is the system call number and it should be smaller than nr_syscils );
IV. If the pf_tracesys flag is set, the system will jump to syscall_trace, where the future will be suspended and the sigtrap will be sent to its parent process. This is mainly designed to set debugging breakpoints;
V. If the pf_tracesys flag is not set, it will jump to the handler function entry called by the system. Here, we use eax (the system call number mentioned above) as the offset. In the system call table sys_call_table, find the processing function entry address and jump to the entry address.

(Additional instructions:
1. get_current macro
# Define get_current (REG )/
Movl % ESP, reg ;/
Andl $-8192, reg;
The function is to obtain the pointer of the task_struct structure of the current process and return it to Reg, because in Linux, the core stack is located at two pages (8192 bytes) after task_struct ), so here we get the task_struct structure pointer from the stack pointer and-8192, and the position offset of 4 in task_struct is the member flags, where the command testb $0x20, flags (% EBX) detects task_struct-> flags .)

 

Int 0x80 ss

Pt_regs
ESP

Sall_all user Stack

 

Call syscall_entry

 

Core Stack

Parameter Analysis in the stack:

As mentioned above, save_all is the input process of system call parameters. When save_all is executed and its processing function is called by the call command, the stack structure should be shown in. At this time, the stack structure looks the same as executing a function call with common parameters. The order of parameters in the stack is (arg1, EBX), (arg2, ECx), (arg3, EDX )......, this is the reverse order of the save_all pressure stack. These parameters are the parameters that users try to send to the core when using the system call. The following are two typical methods to use parameters in the core call handler:
Asmlinkage int sys_fork (struct pt_regs regs );
Asmlinkage int sys_open (const char * filename, int flags, int mode );
In sys_fork, the content of the entire stack is treated as a struct pt_regs type parameter. The structure of this parameter is consistent with that of the stack, so all information in the stack can be used. The filename, flags, and mode parameters in sys_open correspond exactly to the EBX, ECx, and EDX positions in the stack, these registers are the registers that you specify for these parameters when calling the system through the C library.
_ ASM _ volatile __(/
"Int $0x80/n/t "/
: "= A" (retval )/
: "0" (_ nr_open ),/
"B" (filename ),/
"C" (flags ),/
"D" (mode ));

How to Use user space parameters:

When using the System Call, some parameters are pointers. These pointers point to the address in the sub-segment of the user space DS register, and in versions earlier than 2.2, the segment selection in the DS segment register of the core State and the segment Selection Sub-Description of the user State are different (the former is 0xc0000000, and the latter is 0x00000000 ), in this way, these parameters cannot be read to the correct position. Therefore, you need to use special core functions (such as memcpy_fromfs and mencpy_tofs) to read parameters from user space data segments. In these functions, the FS register is used to read parameter segments, the FS register is set to user_ds when the system call enters the core State (DS is set to kernel_ds ). In Versions later than 2.2, the segments of the sub-description selected in the DS section used by the user State and core State are the same (both 0x00000000 ), therefore, you do not need to directly use the parameters after the above cumbersome process.

Memory ing analysis:

Linux divides 4G addresses into two parts: user space and kernel space. In earlier Linux kernel versions (2. 0. X). Generally, 0-3g is the user space, and 3g-4G is the kernel space. This demarcation point can be changed
.
It is the existence of this demarcation point that limits the maximum memory available for Linux to 2 GB. It is also necessary to re-compile the kernel to adjust this demarcation point. In fact, there are still better ways to solve this problem. Because the kernel space does not overlap with the user space, you can use the protection function provided by the segment mechanism to protect kernel-level code.

Some codes of 2.0.x are as follows:
/Usr/src/Linux/ARCH/i386/kernel/entry. s
A:. Quad 0xc0c39a000000ffff/* 0x10 kernel 1 GB code at 0xc0000000 *
B:. Quad 0xc0c392000000ffff/* 0x18 kernel 1 GB Data at 0xc0000000 *
C:. Quad 0x00cbfa000000ffff/* 0x23 user 3 GB code at 0x00000000 *
D:. Quad 0x00cbf2000000ffff/* 0x2b user 3 GB Data at 0x00000000 *

A and B are the descriptor of the kernel code segment and data segment. C and D are user code and Data Segment descriptors.
From the above, we can clearly see that the privileged level of A and B is 0, while that of C and D is 3. When the kernel
When accessing the content of the user space, he uses the FS register to set the content of the FS register to D.
To access the user space.

2.2.x kernel was modified. In this way, the kernel space is expanded to 4 GB, so you can directly copy it.

. Quad 0x00cf9a000000ffff/* 0x10 kernel 4 GB code at 0x00000000 *
. Quad 0x00cf92000000ffff/* 0x18 kernel 4 GB Data at 0x00000000 *
. Quad 0x00cffa000000ffff/* 0x23 user 4 GB code at 0x00000000 *
. Quad 0x00cff2000000ffff/* 0x2b user 4 GB Data at 0x00000000 *

On the surface, the base address of the kernel is changed to 0, but in fact, the kernel is still above 3G. The details are in different connection description files:

In 2.2.x, the user space is changed from intuitive to 0-4 GB, which is confusing: Can it directly access the kernel?
Otherwise, the use of page protection prevents user programs from accessing the kernel space.

In this way, the support of FS and Gs is not required to access the user space. However, in the kernel, the values you set on the macros such as set_fs (x) are retained to verify whether subsequent operations are appropriate. Whether or not the specified X is exceeded. Here, X is no longer a segment descriptor, but a specific value.
There is a trap here: if you set the set_fs value to kernel_ds without returning it, when the user calls a buffer address through the system (should be in the user space) it is set to a kernel space. Before the kernel accesses this address, it determines that the current default threshold value is still user_ds?

Author: Shi Yunfeng
Transferred from: linuxaid

 

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.