Information Security System design basics Tenth Week study summary-Lu Songhon

Source: Internet
Author: User
Tags sleep function terminates

Eighth. Abnormal control Flow
    • Smoothing: means that the instructions are contiguous in memory.
    • Mutation: A non-contiguous occurrence, usually caused by instructions such as jumps, calls, and returns.

Exception Control Flow ECF: these mutations.

About ECF:

1.ECF是操作系统用来实现I/O、进程和虚拟存器的基本机制2.应用程序通过使用一个叫做陷阱或者系统调用的ECF形式,向操作系统请求服务3.ECF是计算机系统中实现并发的基本机制4.软件异常机制——C++和Java有try,catch,和throw,C中非本地跳转是setjmp和longjmp
First section exception

exceptions are a form of exception control flow that is implemented by hardware and operating systems . In simple terms, it is the mutation in the control flow .

    • Event: A state change that may or may not be related directly to the execution of the current instruction.
    • How the exception is handled:

      1.处理器检测到有异常发生2.通过异常表,进行间接过程调用,到达异常处理程序3.完成处理后:①返回给当前指令②返回给下一条指令③终止
1. Exception Handling

Several concepts need to be known: Exception number, exception table, exception table base register.

    • Exception number: A unique, non-negative integer assigned by the system for each type of exception.
    • Exception table: When the system starts, the operating system initializes a bar transition so that the entry k contains the address of the handler for the exception K.

Relationship:
The exception number is the index to the exception table, and the starting address of the exception table is placed in the exception table base register.

Exceptions are similar to procedure calls, which differ in:

1.处理器压入栈的返回地址,是当前指令地址或者下一条指令地址。2.处理器也把一些额外的处理器状态压到栈里3.如果控制一个用户程序到内核,所有项目都压到内核栈里。4.异常处理程序运行在内核模式下,对所有的系统资源都有完全的访问权限。
2. Categories of exceptions
    • Fault instruction: Execution of current instruction causes exception
    • Interrupt handlers: Exception handlers for hardware interrupts.

(1) Interrupt
    • Occurs asynchronously
    • The result of a signal from an I/O device outside the processor
    • Return to next instruction
(2) Traps
    • Traps are intentional exceptions.
    • Is the result of executing an instruction
    • The most important use-- system call
(3) fault
    • caused by an error condition and may be corrected by the fault handler
    • The result is either re-executing the instruction (that is, returning the current instruction address) or terminating
    • Typical example: Missing pages Exception
(4) Termination
    • Is the result of unrecoverable fatal error
    • Usually a few hardware errors
Exceptions in the 3.LINUX/IA32 system

There are three different types of anomalies.

(1) LINUX/IA32 failure and termination
    • Division error/Floating-point Exception exception 0 terminating program
    • General Protection Fault/segment fault Exception 13 terminating the program
    • Page fault 14 returns the current address
    • Machine Check Exception 18 Terminate program
(2) LINUX/IA32 system call

Each system call has a unique integer number that corresponds to the offset from a jump table in the kernel.

How to implement a system call:
In IA32, system calls are provided through a trap directive:

int n;//n为异常号

All parameters to the Linux system call are passed through the register . The Convention is as follows:

    • %eax: Contains the system call number
    • %EBX,%ECX,%EDX,%ESI,%EDI,%EBP: Contains a maximum of six arbitrary parameters
    • %ESP: Stack pointer, cannot use
Section II Process

Classic definition of a process: an instance of an executing program.

Each program in the system is running in the context of a process.

※ Context: consists of the state required to run the program correctly.

The key abstraction that a process provides to an application:

    • A separate logical control flow: Exclusive use of the processor
    • A private address space: Exclusive use of the memory system

      1. Logic control Flow (1) meaning

      A series of program counter PC values, respectively, that correspond to instructions in the executable target file containing the sub-program, or the instructions contained in a shared object that is dynamically linked to the program at run time, the sequence of this PC value is called the logical control flow .

(2)

See figure 8-12, the key is:

The process uses the processor in turn. Each process executes its part of the stream, then is preempted and then turns to other processes. However, a process can provide an illusion to each program as if it were using the processor exclusively.

(3) Example of logical flow

Exception handlers, processes, signal handlers, threads, Java processes

2. Concurrent Stream (1) meaning

The execution of one logical stream overlaps with another stream in time. "is not related to the same processor"

The two streams run concurrently .

(2) Several concepts
    • Concurrency: Execution of multiple streams concurrency
    • Multitasking: a process and other processes running in turn (also called time shards)
    • Time slices: Each time period a process executes as part of its control flow
(3) Parallel

Two streams run concurrently on different processor cores or computers.

Parallel flow parallel running, parallel execution.

3. Private address space

A process provides the illusion of a program as if it were exclusively using the system address space. In general, the memory byte associated with an address in this space cannot be read or written by other processes.

4. User mode and kernel mode

Simply put, the difference between user mode and kernel mode is the user's permission, which refers to the permission to use the system resources.

The specific difference is that there is no mode bit , there is the kernel mode, you can execute all instructions in the instruction set, access to any memory location in the system, there is no user mode.

The only way the process changes from user mode to kernel mode is through exceptions --interrupts, failures, or a system call.

The smart mechanism of Linux--/proc the file system, outputting the contents of many kernel data structures as a hierarchy of text files that a user program can read.

But I entered in the virtual machine to tell me that permissions are not enough?

This through the last section, it is my input method is not correct, I should enter the cat print instructions, followed by the directory, such as:

5. Context Switches

The operating system kernel uses context switches to achieve multitasking with this higher-level exception control flow. The context-switching mechanism is based on the lower-level exception mechanism.

(1) Context: The kernel restarts the state required by a preempted process.

Consists of the values of some objects:

    • General purpose Registers
    • Floating-point Registers
    • Program counter
    • User stack
    • Status Register
    • Kernel stacks
    • Kernel Data Structures: page tables, process tables, file tables
(2) Scheduling and scheduler

The operating system has spoken.

(3) Context switching mechanism

1. Save the context of the current process

2. Restore the context in which a previously preempted process was saved

3. Pass control to this newly restored process.

(4) Possible reasons for context switching:
    • The kernel performs system tuning on behalf of the user
    • Interrupt
Section three system call error handling

This section is mainly a repeating explanation of the contents of Appendix A, which has been studied in the last week.

The simple summary is that the system uses the error handling wrapper function , the system-level functions are lowercase, their wrapper functions are capitalized, the wrapper function calls the basic function, and any problems are terminated if there is no problem and the basic function is the same.

It is important to note that the idea of checking the wrong!!!

Section fourth Process Control one, get process ID

Each process has a unique positive process ID (PID).

#include <sys/types.h>#include <unistd.h>pid_t getpid(void);返回调用进程的PIDpid_t getppid(void);返回父进程的PID(创建调用进程的进程)
Ii. Creating and terminating processes 1. The process is always in one of the following three states
    • Run
    • STOP: Suspended and not scheduled
    • Terminate: Stop forever. Reason:

      1.收到信号,默认行为为终止进程2.从主程序返回3.调用exit函数
2. Create a process

The parent process creates a new run child process by calling the fork function. The fork function is defined as follows:

#include <sys/types.h>#include <unistd.h>pid_t fork(void);

The fork function is called only once, but is returned two times: the parent process returns the PID of the child process, and the child process returns 0. If failure returns-1.

The code example in Figure 8-15 is:

/* $begin Fork */#Include "Csapp.h"int main  () {pid_t pid; int x = 1; pid = Fork (); //line:ecf:forkreturn if (pid = = 0 {/* child */printf ( "child:x=%d \ n ", ++x); //line:ecf:childprintexit (0);} /* Parent */printf ( "parent:x=%d \ n ",--x); //line:ecf:parentprint exit (0) ;} /* $end fork */           
    • Call once, return two times
    • Concurrent execution, the kernel can alternately execute instructions in their logical control flow in any way
    • Same and different:

      相同:用户栈、本地变量值、堆、全局变量值、代码不同:私有地址空间
    • Shared file: The child process inherits all open files from the parent process. Refer to section 10.6 notes.

Call the fork function n times, producing 2 of the n-th process.

3. Terminating the process

Use the Exit function.

#include <stdlib.h>void exit(int status);

The exit function terminates the process with the status exit state.

Iii. recycling of sub-processes

The process terminates and is also reclaimed by the parent process, otherwise it is in a zombie state.

If the parent process is not reclaimed, the kernel schedules the init process to reclaim them. The PID of the Init process is 1.

A process can wait for its child process to terminate or stop by calling the Waitpid function. The WAITPID function is defined as follows:

#include <sys/types.h>#include <sys/wait.h>pid_t waitpid(pid_t pid, int *status, int options);

The child process PID is returned successfully, and if Wnohang returns 0, the other error returns-1.

1. Judging the members of the waiting set--pid
    • Pid>0: Wait set is a separate subprocess, process ID equals PID
    • Pid=-1: The Wait collection is made up of all the child processes of the parent process
    • Other.
2. Modify the default behavior--options

Set the various combinations of constants Wnohang and wuntraced:

3. Check the exit status of the reclaimed child process--status

Several macros that interpret the status parameter are defined in the Wait.h header file:

    • Wifexited: If a child process terminates normally by calling exit or a return, the true
    • Wexitstatus: Returns the exit status of a normally terminated child process. This state is only defined when wifexited returns to True
    • Wifsignaled: If the child process is terminated because of an uncaught signal, the return True
    • Wtermsig: Returns the number of the signal that caused the child process to terminate. This state is only defined when wifsignaled returns to True
    • Wifstopped: If the child process that caused the return is currently stopped, then the return true
    • Wstopsig: Returns the number of signals that cause the child process to stop. This state is only defined when wifstopped returns to True
4. Error conditions

If the calling process has no child processes, then Waitpid returns-1, and the errno is set to Echild.

If Waitpid is interrupted by a signal, then he returns-1, and sets errno to Eintr.

5.wait function

The wait function is a simple version of the Waitpid function, and wait (&status) is equivalent to Waitpid ( -1,&status,0).

#include <sys/types.h>#include <sys/wait.h>pid_t wait(int *status);

Successfully returned the child process PID, error returned-1

Four, let the process sleep 1.sleep function

The sleep function suspends a process for a specified period of time. Defined as follows:

#include <unistd.h>unsigned int sleep(unsigned int secs);

The return value is the number of seconds left to hibernate if it returns to 0.

2.pause function
#include <unistd.h>int pause(void);

Let the calling function hibernate until the process receives a signal.

V. Load and run the program--execve function
#include <unistd.h>int execve(const char *filename, const char *argv[], const char *envp[]);成功不返回,失败返回-1.

The EXECVE function is called once and never returned.

    • FileName: Executable target file
    • argv: Parameter list
    • ENVP: Environment List

When the new program starts:

Getnev function
#include <stdlib.h>char *getenv(const char *name);若存在则为指向name的指针,无匹配是null

Searches for the string "Name=value" in the environment array, returns a pointer to value if found, otherwise returns NULL.

Setenv and UNSETENV functions
#include <stdlib.h>int setenv(const char *name, const char *newvalue, int overwrite);若成功返回0,错误返回-1void unsetenv(const char *name);无返回值

If the environment array contains a string of "Name=oldvalue", Unsetenv will delete it, SETENV will replace oldvalue with NewValue, only if the overwrite is nonzero.

If name does not exist, Setenv writes "Name=newvalue" into the array.

The difference between the ※fork function and the EXECVE function

    • The fork function is to create a new child process , a copy of the parent process, run the same program in the new child process, the parent process and the child process have the same file table, but the different PID

    • The EXECVE function loads and runs a new program in the context of the current process, overwrites the address space of the current process, but does not create a new process , has the same PID, and inherits the file descriptor.

Fifth Quarter Signal

UNIX signaling: Exceptions in the form of higher-level software allow processes to interrupt other processes.

First, the signal terminology

Two steps to pass a signal to the destination process: send a signal and receive a signal.

Reasons for sending the signal:
1.内核检测到一个系统事件2.一个进程调用了kill函数,显式的要求内核发送一个信号给目的进程。

A process can send signals to itself.

Receive signal:
1.忽略2.终止3.执行信号处理程序,捕获信号
Pending signal:
    • Send only signals that are not received
    • At any one time, a type will have at most one pending signal, and many will be discarded directly.
    • A process can selectively block the acceptance of a signal that is blocked and can still be sent, but will not be received
    • A pending signal can be received at most once.
    • Pending: Set of pending signals
    • Blocked: A set of blocked signals.
Second, send the signal--based on the process group 1. Process Group
    • Each process belongs to only one process group.
    • Process group ID: positive integer
    • A child process and his parent process belong to the same process group.
    • View Process Group Id:getpgrp
    • Modify a process group: Setpgid
2. Send a signal using the/bin/kill program

The/bin/kill program can send arbitrary signals to other processes in the form of:

/bin/kill -n mn是信号,m是进程或进程组

When n>0, send signal N to process M

When n<0, causes the signal |n| to be sent to all processes in the process group m.

3. Send a signal from the keyboard

This part of the main reading, do not repeat, note figure 8-27, understanding the process group PID is taken from the job of a parent process

There is also an abstract concept- job : A process created to evaluate a command line.

4. Send a signal using the Kill function

The process sends a signal to other processes by calling the kill function.

Specifically with this section 2.

5. Send a signal using the alarm function

A process can send a SIGALRM signal to itself by calling the alarm function.

#include <unistd.h>unsigned int alarm(unsigned int secs);返回前一次闹钟剩余的秒数,若没有返回0.

For specific control examples, see Fig. 509, figure 8-29.

=========== Sorry teacher I really can't read the book ... I went to see the video ... ===========

Statement

Declaration of variables in C language:

    • Type
    • Declarator

      Array of pointers

      is an array, the elements in the array are pointers

      int *daytab[13]

      Array pointers

      is a pointer to an array that has a fixed type and number of elements

      int (*DAYTAB1) [13]

      Pointer functions

      is a function, the return value type is a pointer

      int *comp ()

      function pointers

      Is the pointer, pointer to the function, function name is the function pointer

      Int (*COMP1) ()

      How do I identify a type? --Right and left method

      Do not cross parentheses over each analysis, and the parentheses and brackets on the right have higher precedence.

      1. The array must tell the number of elements and the data type
      2. Function must be a tangible parameter and return value type
      3. Array pointers, function pointers, *, and pointers to surround them.
      Analysis:

      1. char ((x ()) []) ()
        Simplified:

      typedef char (f) ();
      typedef f g[];
      X can be simplified to G
      x (), so X is a function that returns a pointer to type G.

G is an array of pointers, the elements within the array are pointers, and the type of the pointer is a function pointer that returns a value of char.

    1. char ((x[3)) ()) [5]

Simplified

(*A)[5],这是一个数组指针,指向一个有五个char型元素的数组A是(*x[3])(),相当于(*B)(),这是一个函数指针,指向函数BB是x[3],是一个数组。
Signal Processing

Inter-process communication between Linux

The signal does not carry any data, only as a notification of what happened to a process.

I. Introduction of the Signal 1. Basic concepts

Signal is an inter-process communication method, which is applied to the processing of asynchronous events , in essence, soft interrupts.

At the software level .

2.kill-l, viewing signal information

or Man 7 signal

Each signal has a number and a macro definition name. See above for specific tables.

3. Signal Life cycle

Signal generation, signal registration, signal cancellation, signal processing

(1) Signal generation-four types
    • The user generates-CTRL+C.

Stty-a to see which keys can generate a signal

    • Hardware generation-except for 0 errors
    • Process generates-kill instructions
    • Kernel Generation-Alarm timeout
(2) Signal processing-Three ways
    • Perform the default action
    • Ignore signal
    • Capture signal: Perform signal processing function, switch to user state.

Snapping: Signal functions

Ignore signal: sig_ign

Default action: SIG_DFL

(3) Multi-signal processing

Processing method:

1. Recursive, call the same handler function

2. Ignoring a second signal

3. Block the second signal until the first one is processed

Sixth section non-local jump

The C language, the user-level exception control flow form, is provided through the setjmp and LONGJMP functions.

The Setjump function saves the current calling environment in the env buffer for use by subsequent longjmp and returns 0.

Calling Environment: program counter, stack pointer, general purpose register

The LONGJMP function resumes the calling environment from the env buffer and then triggers a return from the setjmp call that was last initialized with Env. The setjmp is then returned with a non-zero return value of retval.

Note:

The SETJMP function is called only once, but returns multiple times;

The LONGJMP function is called once but never returned.

Section seventh tools for manipulating processes

STRACE: Prints a running program and traces of every system call that his subroutine calls

PS: Lists the processes in the current system, including zombie processes

TOP: Print out information about the current process resource usage

PMAP: Display memory mappings for a process

Resources:

1. "In-depth understanding of computer systems"

2. Kang Jiaxin Blog: http://www.cnblogs.com/20135202yjx/p/4985230.html

Information Security System design basics Tenth Week study summary-Lu Songhon

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.