[Csapp notes] [eighth. Abnormal control Flow]

Source: Internet
Author: User
Tags call back switches terminates

Exception Control Flow

    • 控制转移
    • 控制流

The system must be able to respond to changes in the state of the system, which are not captured by internal program variables, or are not necessarily related to the execution of the program.

Modern systems react to these situations by causing mutations in the control flow . We call this mutation 异常控制流 ( exceptional Control Flow, ECF )

异常控制流occur at all levels of the system.

Understanding ECF is important

    • Understanding ECF will help you understand important system concepts.
    • Understanding ECF will help you understand how your application interacts with the operating system
      • trap system call request service to the operating system via the ECF form of a trap () or system call ().
    • Understanding ECF will help you write interesting apps
    • Understanding ECF will help you understand concurrency
    • Understanding ECF will help you understand how software anomalies work.

In this chapter you will understand how to interact with the operating system, all around the ECF

8.1 Exceptions

exceptions are one of the exception control flows , partially implemented by hardware, and partly by the operating system.

    • 异常(exception) is a mutation in the control flow that responds to certain changes in the state of the processor.
    • State change is also called 事件 (event)

      • Event may be related to the current execution instruction
        • Memory pages, arithmetic overflow
        • Except 0
      • may also be irrelevant to the current execution order
        • I/O requests
        • Timer generates signal
    • 异常表an indirect procedure call is made through a Jump table (exception table) to an operating system subroutine specifically designed to handle this event ( 异常处理程序 (exception handler))

    • When exception handling is complete, there are three scenarios depending on the type of event

      • Returns the current instruction, which is the instruction at the time the event occurred.
      • Returns no exception, the next instruction executed
      • Terminate the interrupted program
8.1.1 Exception Handling
    • A non-negative (exception number) is assigned to each exception 异常号

      • Some numbers are assigned by the processor designer
      • Other numbers are assigned by the designer of the operating system kernel.
    • When the system starts, the operating system allocates and initializes a 异常表 jump table called.

      • Entry k contains the address of the handler for the exception K.
    • 异常表The address is placed in a 异常表基址寄存器 special CPU register called. )

    • 异常Similar 过程调用 , but with the following differences

      • A procedure call that jumps to the handler before the processor returns the address into the stack. For exceptions, the return address is the current, or next-hop instruction.
      • The processor will push the additional processor state into the stack.
      • If you control a user program to the kernel, then all of these items will be pushed into the kernel stack instead of the user stack.
      • Exception handlers run in kernel mode , which means they have full access to all system resources.
Categories of 8.1.2 Exceptions

Exceptions fall into four categories: 中断 (Interrupt), ( 陷阱 Trap), 故障 (fault), and 终止 (abort).

  1. Interrupt

    • Interrupt is the result of an async that is a signal from an I/O device outside the processor. hardware interrupts are not caused by any particular instruction, and in this sense it is asynchronous. The exception handler for the
    • hardware interrupt is often referred to as the interrupt handler (interrupt handle)
      • I/O device sends a signal to a pin on the processor chip and puts the exception number in the system total Line to trigger the interrupt.
      • After the current instruction is executed, the processor notices the change in the voltage of the interrupt pin, reads the exception number from the system bus, and invokes the appropriate interrupt handler.
      • When the handler finishes, it controls the return to the next instruction to be executed.

      • The remaining exception type (trap, fault, terminate) is synchronization occurs , which executes the result of the current instruction. We call this type of instruction fault instruction (faulting instruction).
  2. Traps and system calls

    • 陷阱is intentional exception, is the result of executing an instruction. will also return to the next hop to execute the instruction.
    • 陷阱The most important use is to provide a process-like interface between the user program and the kernel, called the system call
      • User programs often need to request services from the kernel.
        • Read file
        • Create process (fork)
        • New Program (EXECVE)
        • Terminates the current process (exit)
      • To run controlled access to these kernel services, the processor provides a special syscall n directive
      • System calls are run in kernel mode, while normal calls are in user mode.
  3. Fault

    • The fault is caused by an error and may be corrected by the fault handler.

      • If it can be corrected, return the command that caused the failure.
      • Otherwise, the routine is returned abort for finalization.
  4. Terminate

    • termination is the result of an unrecoverable fatal error, usually a hardware error, such as DRAM and SRAM being corrupted.
    • The terminating handler never returns control to the application. Returns a abort routine.

8.1.3 exceptions in the LINUX/IA32 system
    • There are up to 256 different kinds of anomalies

      • 0~31 exceptions defined by Intel architects are the same for any IA32 system.
      • 23~255 corresponds to interrupts and traps defined by the operating system.

        1. LINUX/IA32 Failure and termination
      • Division Error

      • General protection failure
      • Page fault
      • Machine Check

        1. LINUX/IA32 system Call

    • In the IA32 system, the system call is done through a int n trap instruction called, where n may be an index of any of the 256 entries in the IA32 exception table, and in history, the system call is provided by exception (0x80).

    • C programs can use syscall functions to invoke any system call directly

      • There's really no need to do this.
      • C Library provides a set of convenient wrapper functions . These wrapper functions package the parameters together, fall into the kernel with the appropriate system call number, and then pass the return state of the system call back to the calling function.
      • We call the system -level functions of the wrapper function associated with them.

It is interesting to study how the program calls the Linux system calls directly using the INT directive. All parameters to a Linux system call are passed through a generic register rather than a stack.

Practice

  • %EAX contains the system call number
  • The%EBX,%ECX,%EDX,%ESI,%EDI,%EBP contains six arbitrary parameters.
  • %ESP cannot be used, and after entering kernel mode, the kernel overwrites it.
    • System-level functions written by Hello World

      int main(){    write(1,"hello,world\n",13);    exit(0);}
    • Hello World written by sinks

      string:        "hello world\n"main:        movl $4,%eax        movl $1,%ebx        movl $String,%ecx        movl $len,%edx        int $0x80        movl $1,%eax        movl $0,%ebx        int $0x80

8.2 Process
    • 异常is one of the 进程 进程 most profound and successful concepts in computer science, which allows the basic construction of the concept provided by the operating system to be fast.
      • Illusion, that our program is the only program running in the system. Our program seems to monopolize the processor and memory.
      • These artifacts are provided to us through the concept of process.
    • 进程Classic definition: An instance of a program in execution.
      • Each program in the system is running in a process 上下文 .
        • The context is made up of the state required for the program to run correctly.
        • This state includes the code and data in the memory, its stack, the general purpose register, the program counter, the environment variable, and so on.
    • 进程The illusion provided
      • An independent 逻辑控制流 .
      • A private one 地址空间 .
8.2.1 Logic Control Flow
    • The sequence of PC values is called 逻辑控制流 , or short逻辑流
8.2.2 Concurrent Streams
    • 逻辑流There are different forms as well.

      • Exception handlers, processes, signal handlers, threads, and Java processes are examples of logical flows.
    • The execution of one logical flow overlaps with another flow in execution, known as 并发流 two streams, which are called concurrently to run .

      • To be more precise, flow x and y are parallel to each other.
    • The general phenomenon of concurrent execution of multiple streams is called 并发 .

      • The notion that a process and other processes are executed in turn is called 多任务 .
      • Each time period a process executes as part of its control flow is called 时间片 .
      • Therefore, multitasking is also called时间分片
    • 并发The idea of running with a stream of processor cores is independent of the number of computers.

      • If two streams overlap in time, even if they run on the same processor, they are also concurrent.
      • A parallel stream is a true subset of concurrent streams.
        • Two streams run concurrently on different processor cores or computers, as we call them 并行流 .
        • They run in parallel and execute in parallel

You eat half of the meal, the phone came, you have been to eat after the time to pick up, which means you do not support 并发 or support 并行 .

You eat half of the meal, the phone came, you stopped to pick up the phone, and then continue to eat after, this shows that you support 并发 .

You eat half of the meal, the phone is coming, you are on the phone while eating, which means you support 并行 .

并发The key is that you have the ability to handle multiple tasks, not necessarily at the same time.

并行The key is that you have the ability to handle multiple tasks at the same time.

8.2.3 Private address space

进程As a program, it seems to monopolize the system address space.

    • One 进程 provides its own private address space for each program.
    • Different systems generally use the same structure.

8.2.4 user mode and kernel mode

The processor provides a mechanism to limit the instruction that an application can execute and the range of address space it can access. This is 用户模式 and 内核模式 .

  • The
  • Processor provides this functionality through a mode bit in the control register.

    • This register describes the privileges currently enjoyed by the process.
      • when mode bit is set, the process runs in kernel mode (sometimes called superuser mode )
        • kernel-mode processes can execute any of the instruction set command to access all memory locations of the system.
      • The process runs in user mode when mode bit is not set.
        • User mode does not allow programs to execute privileged directives.
          • For example, stop the processor, change the mode bit, and initiate an I/O operation.
        • does not allow user-mode processes to directly reference the kernel area code and data of the address space.
        • Any attempt will result in a protection failure . The
        • user accesses the kernel code and data indirectly through a system call .
    • process How to shift the bit kernel mode from user mode
      • by breaking, failing, and getting caught in a system call exception. The
      • enters kernel mode in the exception handler. After exiting, the user mode is returned.
  • Linux provides a clever mechanism called /proc file systems.

    • Allows user mode to access the contents of the kernel data structure.
    • /procThe file outputs many kernel data structures as a hierarchy of text files that a user program can read.
      • such as CPU type ( /proc/cpuinfo )
      • Memory segments used by special processes ('/proc//maps ')
    • Version 2.6 introduced the Linux kernel into the /sys file system.
      • Output additional underlying information about the system bus and devices.
The 8.2.5 context switch operating system kernel uses a type called Context SwitchesThe higher level of Exception Control FlowTo achieve multi-tasking.
    • The context switching mechanism is based on the lower-level exception mechanism discussed earlier.
The kernel maintains one for each process Context
  • The context is the state required to restart a preempted process.
    • Consists of the values of some objects
      • General purpose Registers
      • Floating-point Registers
      • Program Counter (PC)
      • User stack
      • Status Register
      • Kernel stacks
      • Various kernel data structures
        • page Table depicting the address space
        • The process table containing the information currently in town
        • File Table with process open file information
  • At some point in the process execution, the kernel can decide to preempt the current process and restart a previously preempted process. This decision is called scheduling ( shedule ), which is handled by code called the Scheduler () in the kernel scheduler .

    • When the kernel chooses a new process to run, we say that the kernel dispatched the process.
  • When scheduling a process, use a 上下文切换 mechanism to control the transfer to a new process

    • Save the context of the current process
    • Restores the context in which a previously preempted process was saved
    • Pass control to this newly restored process
  • When will the context switch occur?
    • The kernel executes system calls on behalf of the user.
      • If a system call is blocked because of an event, the kernel can let the current process hibernate and switch to another process.
      • Or you can use sleep a system call to explicitly request that the calling process hibernate.
      • The kernel can decide to perform a context switch even if the system call is not blocked
    • Interrupts can also cause context switching.
      • All systems have a mechanism that generates periodic timer interrupts , typically 1ms, or 10ms.
      • Each time the timer is interrupted, the kernel can tell that the current process is running long enough to switch to a new process .

Cache pollution and exception control flow

In general, the hardware cache memory does not interact well with exception control flows such as interrupts and context switches, and if the current process is temporarily interrupted by an interrupt, the cache is cold for the interrupt handler. If the handler accesses enough table entries from main memory and the interrupted process continues, the cache is also cold for it, and we call the interrupt handler polluting the cache . A similar behavior can occur with context switching .

8.3 System invoke error handling
    • When UNIX system-level functions encounter errors, they typically return-1, and set global variables errno to indicate what went wrong.

      if((pid=fork()<0){        fprintf(stderr,"fork error: %s\n", strerror(errno));        exit(0);}
    • The Strerror function returns a text string that describes an error associated with one of the errno values.
8.4 Process Control 8.4.1 get process ID
#include<sys/types.h>#include<unistd.h>pid_t getpid(void);pid_t getppid(void);
    • The PID is the only positive number per process.
    • getpid()Returns the PID of the calling process, getppid() returning the PID of its parent process.
    • Returns the value of a type pid_t that is defined as an int under the Linux system in Type.h
8.4.2 Creating and terminating processes

The process is always in the following three states

    • Run. The process either executes in the CPU, waits for execution, and is eventually dispatched by the kernel.
    • Stop it. The execution of the process is suspended and is not scheduled.

      • Receive SIGSTOP , SIGTSTP SIDTTIN or SIGTTOU signal, the process will stop.
      • Until a signal is received SIGCONT , at this point, the process begins to run again.
      • 信号is a form of software interruption .
    • Terminate. The process stops forever.

      • Receive a signal. The default behavior of the signal is to terminate the process.
      • Returning from the main program
      • Call the Exit function
        • Exit function to status退出状态 terminate the process (another way to set return in main)
Child process

The parent process fork creates a new run child process by calling the function

#include<sys/types.h>#include<unistd.h>pid_t fork(void);返回:子进程返回0,父进程返回子进程的PID,如果出错,返回-1;

The newly created child process is almost but not exactly the same as the parent process.

    • The child process obtains the same (but independent) copy of the parent process's user-level virtual address space.

      • Includes text, data and BSS segments, heaps, and user stacks. The child process also obtains the same copy as any open file descriptor of the parent process.
      • means that when the parent process calls fork, the child process can read and write to any file that is open in the parent process.
      • The biggest difference between a parent process and a newly created child process is that there is a different PID.
    • fork()The function is called for the first time, returned two times, once in the parent process, once in the child process.

      • The return value is used to explicitly execute in the parent process or in the child process.

    • called once and returned two times .
      • The need for multiple fork instances is carefully scrutinized.
    • Concurrent execution

      • Parent and child processes are independent processes that run concurrently.
      • The kernel may feel like executing their order in any way.
      • You cannot make any assumptions about the alternating execution of instructions in different processes.
    • The same but separate address space

      • Almost everything is the same when you just call.
      • But they all have their own private space, and then the changes to X are independent of each other.
    • Share files

      • Both the parent and child processes display their output on the screen.
      • The child process inherits all open files from the parent process.

Drawing a process diagram will help.

8.4.3 Recycling sub-processes

When a process terminates for some reason, the kernel does not immediately purge it from the system. Instead, the process is kept in an end state, known to be reclaimed by its parent process ( reap ).

When the parent process recycles the terminated child process, the kernel passes the child process's exit state to the parent process, and then discards the terminated process.

A process that has been terminated but not yet recycled is called a zombie process .

If the parent process is not recycled and terminated, the kernel schedules the init process to reclaim them.

    • initPID bit 1 of the process, created by the kernel when the system is initialized.
    • Long-running programs, such as shells, servers, should always recycle their dead child processes

A process can wait for its child process to terminate or stop by calling the Waitpid function

#include<sys/types.h>#include<sys/wait.h>pid_t waitpid(pid_t pid ,int *status, int options);返回:如果成功,则为子进程的PID,如果WNOHANG,则为0,如果其他错误,则为-1.

waitpidThe function is a bit complicated. By default ( option=0 ), the execution of the waitpid calling process is suspended, knowing that it waits for a child process in the collection to terminate, and returns immediately if a child process waiting on the collection has terminated at the time of the call waitpid . In both cases, it returns the waitpid waitpid terminated child process that caused the return PID and removes the terminated child process from the system.

    • Judging the members of a waiting set

      The members of the waiting set are determined by the parameter PID

      • If pid>0 , then the wait set is a separate child process, its process ID equalsPID
      • If pid=-1 so, the wait set is made up of all the child processes of the parent process.
      • waitpidThe function also supports other types of wait collections, including UNIX process groups, and no discussion.
    • Modify the default behavior ( there is a problem in the book, the function is reversed )

      You can options WHOHANG WUNTRACED Modify the default behavior by setting the various combinations to constants and.

      • Whohang: Returns immediately if no child processes in the collection have been terminated (the return value is 0)
        • The default behavior returns a child process that has been terminated.
        • This option is useful when you want to check for aborted and stopped child processes.
      • wuntraced: Suspends execution of the calling process, knowing that a process in the waiting set becomes either terminated or stopped.
        • The returned PID is the resulting aborted or stopped child process PID ·
        • The default behavior is to suspend the calling process until a child process terminates.
      • whohang| wuntraced: Returns immediately, if no child processes in the collection are stopped or terminated, then
    • Check the exit status of the reclaimed child process

[Csapp notes] [eighth. Abnormal control Flow]

Related Article

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.