Какая нотация вызовов функций принята в системных вызовах windows

Работа по теме: OS. Глава: Тест по дисциплине «операционные системы, среды и оболочки». ВУЗ: ЕГУ.

Тест по дисциплине «операционные системы, среды и оболочки»

  1. Выберите
    из предложенного списка, что может
    являться критерием эффективности
    вычислительной системы:

  1. пропускная
    способность;

  2. занятость
    оперативной памяти;

  3. загруженность
    центрального процессора;

  1. Системы
    пакетной обработки предназначены для
    решения задач:

  1. вычислительного
    характера

  2. требующих
    постоянного диалога с пользователем

  3. требующих
    решения конкретной задачи за определенный
    промежуток времени

  1. В
    каких системах гарантируется выполнение
    задания за определенный промежуток
    времени:

  1. пакетной
    обработки

  2. разделения
    времени

  3. системах
    реального времени

  1. В
    системах пакетной обработки суммарное
    время выполнения смеси задач:

  1. равно
    сумме времен выполнения всех задач
    смеси

  2. меньше
    или равно суммы времен выполнения всех
    задач смеси

  3. больше
    или равно суммы времен выполнения всех
    задач смеси

  1. В
    системах реального времени

  1. набор
    задач неизвестен заранее

  2. набор
    задач известен заранее

  3. известен
    или нет набор задач зависит от характера
    системы

  1. Самое
    неэффективное использование ресурсов
    вычислительной системы:

  1. в
    системах пакетной обработки

  2. в
    системах разделения времени

  3. В системах реального времени

  1. В
    многопоточных системах поток есть –

  1. заявка
    на ресурсы

  2. заявка
    на ресурс ЦП

  3. заявка
    на ресурс ОП

  1. Потоки
    создаются с целью:

  1. ускорения
    работы процесса

  2. защиты
    областей памяти

  3. улучшения
    межпроцессного взаимодействия

  1. Как
    с точки зрения экономии ресурсов лучше
    распараллелить работу:

  1. создать
    несколько процессов

  2. создать
    несколько потоков

  3. случаи
    a) и b) равнозначны, можно выбирать любой
    из них

  1. Планирование
    потоков игнорирует:

  1. приоритет
    потока

  2. время
    ожидания в очереди

  3. принадлежность
    некоторому процессу

  1. В
    каких системах тип планирования
    статический

  1. реального
    времени

  2. Разделения времени

  3. Пакетной обработки

  1. Состояние,
    которое не определено для потока в
    системе:

  1. выполнение

  2. синхронизация

  3. ожидание

  4. готовность

  1. Каких
    смен состояний не существует в системе:

  1. выполнение
    → готовность

  2. ожидание
    →выполнение

  3. ожидание
    → готовность

  4. готовность
    → ожидание

  1. Какой
    из алгоритмов планирования является
    централизованным:

  1. вытесняющий

  2. невытесняющий

  1. При
    каком кванте времени в системах,
    использующих алгоритм квантования,
    время ожидания потока в очереди не
    зависит от длительности ее выполнения:

  1. при
    маленьком кванте времени

  2. при
    длительном кванте времени

  3. при
    любом кванте времени

  1. Приоритет
    процесса не зависит от:

  1. того,
    является ли процесс системным или
    прикладным

  2. статуса
    пользователя

  3. требуемых
    процессом ресурсов

  1. В
    каких пределах может изменяться
    приоритет потока в системе Windows NT:

  1. от
    базового приоритета процесса до нижней
    границы диапазона приоритета потоков
    реального времени

  2. от
    нуля до базового приоритета процесса

  3. базовый
    приоритет процесса ± 2

  1. Каких
    классов прерываний нет?

  1. аппаратных

  2. асинхронных

  3. внутренних

  4. программных

  1. Какие
    из прерываний можно считать синхронными?

  1. внешние

  2. внутренние

  3. программные

  4. динамические

  1. Память
    с самой высокой стоимостью единицы
    хранения:

  1. дисковая
    память

  2. оперативная
    память

  3. регистры
    процессора

  1. Какая
    функция ОС по управления оперативной
    памятью характерна только для
    мультизадачных ОС:

  1. выделение
    памяти по запросу

  2. освобождение
    памяти по завершению процесса

  3. защита
    памяти

  1. Какая
    стратегия управления памятью определяет,
    какие конкретно данные необходимо
    загружать в память:

  1. выборки

  2. размещения

  3. замещения

  4. загрузки

  1. Виртуальные
    адреса являются результатом работы:

  1. пользователя

  2. транслятора

  3. компоновщика

  4. ассемблера

  1. Какого
    типа адреса могут быть одинаковыми в
    разных процессах:

  1. виртуальные

  2. физические

  3. реальные

  4. сегментные

  1. Недостатки
    распределения памяти фиксированными
    разделами:

  1. сложность
    реализации

  2. сложность
    защиты

  3. ограничение
    на число одновременно выполняющихся
    процессов

  4. фрагментация
    памяти

  1. Какой
    процесс обязательно должен выполняться
    в системе памяти с перемещаемыми
    разделами:

  1. сжатие

  2. перемещение

  3. свопинг

  1. Что
    из ниже перечисленного верно для
    свопинга:

  1. на
    диск выгружается неиспользуемая в
    настоящий момент часть процесса

  2. на
    диск выгружаются неиспользуемые
    процессом данные

  3. на
    диск выгружается не активный процесс

  1. Таблица
    страниц используется для:

  1. преобразования
    виртуального адреса в физический

  2. для
    ускорения работы процесса

  3. для
    реализации свопинга

  1. Объем
    страницы:

  1. выбирается
    по возможности максимальный

  2. выбирается
    минимальным

  3. для
    процессоров х86 стандартно равен 4 кбайта

  1. Кэширование
    – это:

  1. способ
    функционирования дисковых устройств

  2. способ
    работы с ОП

  3. способ
    взаимного функционирования двух типов
    запоминающих устройств

  1. Что
    может выступать в качестве кэша для
    ОП:

  1. дисковые
    устройства

  2. быстродействующая
    статическая память

  3. виртуальная
    память

  1. Атаки
    класса «отказ в обслуживании» направлены
    на:

  1. полный
    или частичный вывод ОС из строя

  2. вывод
    из строя аппаратуры ПК

  3. полное
    или частичное удаление установленного
    ПО

  1. Какой
    вид многозадачности не существует?

  1. Вытесняющая
    многозадачность.

  2. Кооперативная
    (не вытесняющая) многозадачность.

  3. Симметричная
    многозадачность.

  1. Существуют
    ли классификация ядер ОС по особенностям
    выполнения ядра в многопроцессорных
    системах? (учитывая, что такие системы
    ядром поддерживаются)

  1. Да

  2. Нет

  1. Где
    должен располагаться код для обнаружения
    оборудования? (учитывая современные
    устройства)

  1. В
    ядре (или обязательных модулях, серверах
    для немонолитных архитектур).

  2. Вне
    ядра, в драйверах.

  1. Какое
    ядро современных ОС поддерживает
    Multiboot Specification?

  1. Windows

  2. SunOS
    82

  3. MacOS

  4. Linux

  5. Все
    ядра BSD

  1. Что
    означает аббревиатура PIC в контексте
    ОС?

  1. Programmable
    Interrupt Controller

  2. Past
    Implemented Code

  3. Position
    Independent Code

  4. Portable
    Incompatible Code

  1. Какие
    основные преимущества микроядерной
    архитектуры?

  1. Упрощение
    переносимости

  2. Улучшение
    безопасности

  3. Повышенные
    отказоустойчивость и степень
    структурированности

  4. Все
    выше перечисленное

  1. Предшественником
    какого современного семейства ОС была
    ОС Minix Эндрю Таненбаума?

  1. BSD

  2. Windows

  3. Linux

  1. Нашли
    ли экзоядерные ОС широкое применение
    в современной вычислительной технике?

  1. Да

  2. Нет

  1. В
    какой из ОС впервые был реализован стек
    протоколов TCP/IP?

  1. BSD

  2. Windows

  3. Linux

  4. DOS

  1. Выберите
    не подходящее утверждение об отношении
    DOS к первым версиям Windows?

  1. В
    Windows можно было запускать приложения
    DOS

  2. Многие
    функции Windows делегировались соответствующим
    функциям DOS (то есть для этого производилось
    переключение режимов работы ЦПУ)

  3. Поддержка
    приложений DOS была ограниченной и
    неполной (при эмуляции на VDM, в рамках
    режима V86)

  1. В
    какой ОС поддержка графического
    интерфейса пользователя (GUI) интегрирована
    непосредственно в ядро?

  1. Windows

  2. BSD

  3. Linux

  1. Укажите
    типы сообщений, которые могут
    использоваться в микроядерных ОС.

  1. Синхронные
    и асинхронные.

  2. Только
    синхронные.

  3. Только
    асинхронные.

  1. В
    чём главный недостаток монолитных
    ядер?

  1. Их
    нельзя модифицировать во время работы

  2. Со
    временем они настолько разрастаются,
    что резко усложняется внесение каких-либо
    изменений

  3. Они
    занимают слишком много оперативной
    памяти

  1. Укажите
    основное средство межпроцессного
    взаимодействия в микроядерных
    архитектурах.

  1. Потоки

  2. Удалённые
    вызовы
    процедур
    (RPC, Remote Procedure Call)

  3. Сообщения

  1. Какая
    нотация вызовов функций принята в
    системных вызовах Windows?

  1. Смесь
    нотаций языков C и Pascal (обратный порядок
    аргументов, очистка стека функцией)

  2. Нотация
    языка Pascal (прямой порядок аргументов,
    очистка стека функцией)

  3. Нотация
    языка C (обратный порядок аргументов,
    очистка стека вызывающим кодом)

  1. Достаточно
    ли установки антивирусного пакета для
    того, чтобы считать ОС защищенной:

  1. да

  2. нет

  3. зависит
    от конкретных условий работы

  1. Для
    обеспечения безопасности системы
    должны использоваться средства, которые
    при отказе переходят в состояние:

  1. максимальной
    защиты

  2. минимальной
    защиты

  1. При
    организации защиты в системе необходимо
    руководствоваться принципом:

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

  • #
  • #

    09.02.2015881.31 Кб27n1.pdf

  • #
  • #
  • #
  • #

    09.02.2015210.43 Кб100OS.doc

  • #
  • #
  • #
  • #
  • #

From Wikipedia, the free encyclopedia

A high-level overview of the Linux kernel’s system call interface, which handles communication between its various components and the userspace

In computing, a system call (commonly abbreviated to syscall) is the programmatic way in which a computer program requests a service from the operating system[a] on which it is executed. This may include hardware-related services (for example, accessing a hard disk drive or accessing the device’s camera), creation and execution of new processes, and communication with integral kernel services such as process scheduling. System calls provide an essential interface between a process and the operating system.

In most systems, system calls can only be made from userspace processes, while in some systems, OS/360 and successors for example, privileged system code also issues system calls.[1]

Privileges[edit]

The architecture of most modern processors, with the exception of some embedded systems, involves a security model. For example, the rings model specifies multiple privilege levels under which software may be executed: a program is usually limited to its own address space so that it cannot access or modify other running programs or the operating system itself, and is usually prevented from directly manipulating hardware devices (e.g. the frame buffer or network devices).

However, many applications need access to these components, so system calls are made available by the operating system to provide well-defined, safe implementations for such operations. The operating system executes at the highest level of privilege, and allows applications to request services via system calls, which are often initiated via interrupts. An interrupt automatically puts the CPU into some elevated privilege level and then passes control to the kernel, which determines whether the calling program should be granted the requested service. If the service is granted, the kernel executes a specific set of instructions over which the calling program has no direct control, returns the privilege level to that of the calling program, and then returns control to the calling program.

The library as an intermediary[edit]

Generally, systems provide a library or API that sits between normal programs and the operating system. On Unix-like systems, that API is usually part of an implementation of the C library (libc), such as glibc, that provides wrapper functions for the system calls, often named the same as the system calls they invoke. On Windows NT, that API is part of the Native API, in the ntdll.dll library; this is an undocumented API used by implementations of the regular Windows API and directly used by some system programs on Windows. The library’s wrapper functions expose an ordinary function calling convention (a subroutine call on the assembly level) for using the system call, as well as making the system call more modular. Here, the primary function of the wrapper is to place all the arguments to be passed to the system call in the appropriate processor registers (and maybe on the call stack as well), and also setting a unique system call number for the kernel to call. In this way the library, which exists between the OS and the application, increases portability.

The call to the library function itself does not cause a switch to kernel mode and is usually a normal subroutine call (using, for example, a «CALL» assembly instruction in some Instruction set architectures (ISAs)). The actual system call does transfer control to the kernel (and is more implementation-dependent and platform-dependent than the library call abstracting it). For example, in Unix-like systems, fork and execve are C library functions that in turn execute instructions that invoke the fork and exec system calls. Making the system call directly in the application code is more complicated and may require embedded assembly code to be used (in C and C++), as well as requiring knowledge of the low-level binary interface for the system call operation, which may be subject to change over time and thus not be part of the application binary interface; the library functions are meant to abstract this away.

On exokernel based systems, the library is especially important as an intermediary. On exokernels, libraries shield user applications from the very low level kernel API, and provide abstractions and resource management.

IBM’s OS/360, DOS/360 and TSS/360 implement most system calls through a library of assembly language macros,[b] although there are a few services with a call linkage. This reflects their origin at a time when programming in assembly language was more common than high-level language usage. IBM system calls were therefore not directly executable by high-level language programs, but required a callable assembly language wrapper subroutine. Since then, IBM has added many services that can be called from high level languages in, e.g., z/OS and z/VSE. In more recent release of MVS/SP and in all later MVS versions, some system call macros generate Program Call (PC).

Examples and tools[edit]

On Unix, Unix-like and other POSIX-compliant operating systems, popular system calls are open, read, write, close, wait, exec, fork, exit, and kill. Many modern operating systems have hundreds of system calls. For example, Linux and OpenBSD each have over 300 different calls,[2][3] NetBSD has close to 500,[4] FreeBSD has over 500,[5] Windows has close to 2000, divided between win32k (graphical) and ntdll (core) system calls[6] while Plan 9 has 51.[7]

Tools such as strace, ftrace and truss allow a process to execute from start and report all system calls the process invokes, or can attach to an already running process and intercept any system call made by the said process if the operation does not violate the permissions of the user. This special ability of the program is usually also implemented with system calls such as ptrace or system calls on files in procfs.

Typical implementations[edit]

Implementing system calls requires a transfer of control from user space to kernel space, which involves some sort of architecture-specific feature. A typical way to implement this is to use a software interrupt or trap. Interrupts transfer control to the operating system kernel, so software simply needs to set up some register with the system call number needed, and execute the software interrupt.

This is the only technique provided for many RISC processors, but CISC architectures such as x86 support additional techniques. For example, the x86 instruction set contains the instructions SYSCALL/SYSRET and SYSENTER/SYSEXIT (these two mechanisms were independently created by AMD and Intel, respectively, but in essence they do the same thing). These are «fast» control transfer instructions that are designed to quickly transfer control to the kernel for a system call without the overhead of an interrupt.[8] Linux 2.5 began using this on the x86, where available; formerly it used the INT instruction, where the system call number was placed in the EAX register before interrupt 0x80 was executed.[9][10]

An older mechanism is the call gate; originally used in Multics and later, for example, see call gate on the Intel x86. It allows a program to call a kernel function directly using a safe control transfer mechanism, which the operating system sets up in advance. This approach has been unpopular on x86, presumably due to the requirement of a far call (a call to a procedure located in a different segment than the current code segment[11]) which uses x86 memory segmentation and the resulting lack of portability it causes, and the existence of the faster instructions mentioned above.

For IA-64 architecture, EPC (Enter Privileged Code) instruction is used. The first eight system call arguments are passed in registers, and the rest are passed on the stack.

In the IBM System/360 mainframe family, and its successors, a Supervisor Call instruction (SVC), with the number in the instruction rather than in a register, implements a system call for legacy facilities in most of[c] IBM’s own operating systems, and for all system calls in Linux. In later versions of MVS, IBM uses the Program Call (PC) instruction for many newer facilities. In particular, PC is used when the caller might be in Service Request Block (SRB) mode.

The PDP-11 minicomputer used the EMT and IOT instructions, which, similar to the IBM System/360 SVC and x86 INT, put the code in the instruction; they generate interrupts to specific addresses, transferring control to the operating system. The VAX 32-bit successor to the PDP-11 series used the CHMK, CHME, and CHMS instructions to make system calls to privileged code at various levels; the code is an argument to the instruction.

Categories of system calls[edit]

System calls can be grouped roughly into six major categories:[12]

  1. Process control
    • create process (for example, fork on Unix-like systems, or NtCreateProcess in the Windows NT Native API)
    • terminate process
    • load, execute
    • get/set process attributes
    • wait for time, wait event, signal event
    • allocate and free memory
  2. File management
    • create file, delete file
    • open, close
    • read, write, reposition
    • get/set file attributes
  3. Device management
    • request device, release device
    • read, write, reposition
    • get/set device attributes
    • logically attach or detach devices
  4. Information maintenance
    • get/set total system information (including time, date, computer name, enterprise etc.)
    • get/set process, file, or device metadata (including author, opener, creation time and date, etc.)
  5. Communication
    • create, delete communication connection
    • send, receive messages
    • transfer status information
    • attach or detach remote devices
  6. Protection
    • get/set file permissions

Processor mode and context switching[edit]

System calls in most Unix-like systems are processed in kernel mode, which is accomplished by changing the processor execution mode to a more privileged one, but no process context switch is necessary – although a privilege context switch does occur. The hardware sees the world in terms of the execution mode according to the processor status register, and processes are an abstraction provided by the operating system. A system call does not generally require a context switch to another process; instead, it is processed in the context of whichever process invoked it.[13][14]

In a multithreaded process, system calls can be made from multiple threads. The handling of such calls is dependent on the design of the specific operating system kernel and the application runtime environment. The following list shows typical models followed by operating systems:[15][16]

  • Many-to-one model: All system calls from any user thread in a process are handled by a single kernel-level thread. This model has a serious drawback – any blocking system call (like awaiting input from the user) can freeze all the other threads. Also, since only one thread can access the kernel at a time, this model cannot utilize multiple cores of processors.
  • One-to-one model: Every user thread gets attached to a distinct kernel-level thread during a system call. This model solves the above problem of blocking system calls. It is found in all major Linux distributions, macOS, iOS, recent Windows and Solaris versions.
  • Many-to-many model: In this model, a pool of user threads is mapped to a pool of kernel threads. All system calls from a user thread pool are handled by the threads in their corresponding kernel thread pool.
  • Hybrid model: This model implements both many to many and one to one models depending upon the choice made by the kernel. This is found in old versions of IRIX, HP-UX and Solaris.

See also[edit]

  • Linux kernel API
  • VDSO

Notes[edit]

  1. ^ In UNIX-like operating systems, system calls are used only for the kernel
  2. ^ In many but not all cases, IBM documented, e.g., the SVC number, the parameter registers.
  3. ^ The CP components of CP-67 and VM use the Diagnose (DIAG) instruction as a Hypervisor CALL (HVC) from a virtual machine to CP.

References[edit]

  1. ^ IBM (March 1967). «Writing SVC Routines». IBM System/360 Operating System System Programmer’s Guide (PDF). Third Edition. pp. 32–36. C28-6550-2.
  2. ^ «syscalls(2) — Linux manual page».
  3. ^ OpenBSD (14 September 2013). «System call names (kern/syscalls.c)». BSD Cross Reference.
  4. ^ NetBSD (17 October 2013). «System call names (kern/syscalls.c)». BSD Cross Reference.
  5. ^ «FreeBSD syscalls.c, the list of syscall names and IDs».
  6. ^ Mateusz «j00ru» Jurczyk (5 November 2017). «Windows WIN32K.SYS System Call Table (NT/2000/XP/2003/Vista/2008/7/8/10)».
  7. ^ «Plan 9 sys.h, the list of syscall names and IDs».
  8. ^ «SYSENTER (OSDev wiki)».
  9. ^ Anonymous (19 December 2002). «Linux 2.5 gets vsyscalls, sysenter support». KernelTrap. Retrieved 1 January 2008.
  10. ^ Manu Garg (2006). «Sysenter Based System Call Mechanism in Linux 2.6».
  11. ^ «Liberation: x86 Instruction Set Reference». renejeschke.de. Retrieved 4 July 2015.
  12. ^ Silberschatz, Abraham (2018). Operating System Concepts. Peter B Galvin; Greg Gagne (10th ed.). Hoboken, NJ: Wiley. p. 67. ISBN 9781119320913. OCLC 1004849022.
  13. ^ Bach, Maurice J. (1986), The Design of the UNIX Operating System, Prentice Hall, pp. 15–16.
  14. ^ Elliot, John (2011). «Discussion of system call implementation at ProgClub including quote from Bach 1986».
  15. ^ «Threads».
  16. ^ «Threading Models» (PDF).

External links[edit]

  • A list of modern Unix-like system calls
  • Interactive Linux kernel map with main API functions and structures, PDF version
  • Linux system calls – system calls for Linux kernel 2.2, with IA-32 calling conventions
  • How System Calls Work on Linux/i86 (1996, based on the 1993 0.99.2 kernel)
  • Sysenter Based System Call Mechanism in Linux 2.6 (2006)
  • Kernel command using Linux system calls, IBM developerWorks
  • Choudhary, Amit; HOWTO for Implementing a System Call on Linux 2.6
  • Jorrit N. Herder, Herbert Bos, Ben Gras, Philip Homburg, and Andrew S. Tanenbaum, Modular system programming on Minix 3, ;login: 31, no. 2 (April 2006); 19–28, accessed 5 March 2018
  • A simple open Unix Shell in C language – examples on System Calls under Unix
  • Inside the Native API – Windows NT Native API, including system calls
  • Gulbrandsen, John; System Call Optimization with the SYSENTER Instruction, CodeGuru.com, 8 October 2004

From Wikipedia, the free encyclopedia

A high-level overview of the Linux kernel’s system call interface, which handles communication between its various components and the userspace

In computing, a system call (commonly abbreviated to syscall) is the programmatic way in which a computer program requests a service from the operating system[a] on which it is executed. This may include hardware-related services (for example, accessing a hard disk drive or accessing the device’s camera), creation and execution of new processes, and communication with integral kernel services such as process scheduling. System calls provide an essential interface between a process and the operating system.

In most systems, system calls can only be made from userspace processes, while in some systems, OS/360 and successors for example, privileged system code also issues system calls.[1]

Privileges[edit]

The architecture of most modern processors, with the exception of some embedded systems, involves a security model. For example, the rings model specifies multiple privilege levels under which software may be executed: a program is usually limited to its own address space so that it cannot access or modify other running programs or the operating system itself, and is usually prevented from directly manipulating hardware devices (e.g. the frame buffer or network devices).

However, many applications need access to these components, so system calls are made available by the operating system to provide well-defined, safe implementations for such operations. The operating system executes at the highest level of privilege, and allows applications to request services via system calls, which are often initiated via interrupts. An interrupt automatically puts the CPU into some elevated privilege level and then passes control to the kernel, which determines whether the calling program should be granted the requested service. If the service is granted, the kernel executes a specific set of instructions over which the calling program has no direct control, returns the privilege level to that of the calling program, and then returns control to the calling program.

The library as an intermediary[edit]

Generally, systems provide a library or API that sits between normal programs and the operating system. On Unix-like systems, that API is usually part of an implementation of the C library (libc), such as glibc, that provides wrapper functions for the system calls, often named the same as the system calls they invoke. On Windows NT, that API is part of the Native API, in the ntdll.dll library; this is an undocumented API used by implementations of the regular Windows API and directly used by some system programs on Windows. The library’s wrapper functions expose an ordinary function calling convention (a subroutine call on the assembly level) for using the system call, as well as making the system call more modular. Here, the primary function of the wrapper is to place all the arguments to be passed to the system call in the appropriate processor registers (and maybe on the call stack as well), and also setting a unique system call number for the kernel to call. In this way the library, which exists between the OS and the application, increases portability.

The call to the library function itself does not cause a switch to kernel mode and is usually a normal subroutine call (using, for example, a «CALL» assembly instruction in some Instruction set architectures (ISAs)). The actual system call does transfer control to the kernel (and is more implementation-dependent and platform-dependent than the library call abstracting it). For example, in Unix-like systems, fork and execve are C library functions that in turn execute instructions that invoke the fork and exec system calls. Making the system call directly in the application code is more complicated and may require embedded assembly code to be used (in C and C++), as well as requiring knowledge of the low-level binary interface for the system call operation, which may be subject to change over time and thus not be part of the application binary interface; the library functions are meant to abstract this away.

On exokernel based systems, the library is especially important as an intermediary. On exokernels, libraries shield user applications from the very low level kernel API, and provide abstractions and resource management.

IBM’s OS/360, DOS/360 and TSS/360 implement most system calls through a library of assembly language macros,[b] although there are a few services with a call linkage. This reflects their origin at a time when programming in assembly language was more common than high-level language usage. IBM system calls were therefore not directly executable by high-level language programs, but required a callable assembly language wrapper subroutine. Since then, IBM has added many services that can be called from high level languages in, e.g., z/OS and z/VSE. In more recent release of MVS/SP and in all later MVS versions, some system call macros generate Program Call (PC).

Examples and tools[edit]

On Unix, Unix-like and other POSIX-compliant operating systems, popular system calls are open, read, write, close, wait, exec, fork, exit, and kill. Many modern operating systems have hundreds of system calls. For example, Linux and OpenBSD each have over 300 different calls,[2][3] NetBSD has close to 500,[4] FreeBSD has over 500,[5] Windows has close to 2000, divided between win32k (graphical) and ntdll (core) system calls[6] while Plan 9 has 51.[7]

Tools such as strace, ftrace and truss allow a process to execute from start and report all system calls the process invokes, or can attach to an already running process and intercept any system call made by the said process if the operation does not violate the permissions of the user. This special ability of the program is usually also implemented with system calls such as ptrace or system calls on files in procfs.

Typical implementations[edit]

Implementing system calls requires a transfer of control from user space to kernel space, which involves some sort of architecture-specific feature. A typical way to implement this is to use a software interrupt or trap. Interrupts transfer control to the operating system kernel, so software simply needs to set up some register with the system call number needed, and execute the software interrupt.

This is the only technique provided for many RISC processors, but CISC architectures such as x86 support additional techniques. For example, the x86 instruction set contains the instructions SYSCALL/SYSRET and SYSENTER/SYSEXIT (these two mechanisms were independently created by AMD and Intel, respectively, but in essence they do the same thing). These are «fast» control transfer instructions that are designed to quickly transfer control to the kernel for a system call without the overhead of an interrupt.[8] Linux 2.5 began using this on the x86, where available; formerly it used the INT instruction, where the system call number was placed in the EAX register before interrupt 0x80 was executed.[9][10]

An older mechanism is the call gate; originally used in Multics and later, for example, see call gate on the Intel x86. It allows a program to call a kernel function directly using a safe control transfer mechanism, which the operating system sets up in advance. This approach has been unpopular on x86, presumably due to the requirement of a far call (a call to a procedure located in a different segment than the current code segment[11]) which uses x86 memory segmentation and the resulting lack of portability it causes, and the existence of the faster instructions mentioned above.

For IA-64 architecture, EPC (Enter Privileged Code) instruction is used. The first eight system call arguments are passed in registers, and the rest are passed on the stack.

In the IBM System/360 mainframe family, and its successors, a Supervisor Call instruction (SVC), with the number in the instruction rather than in a register, implements a system call for legacy facilities in most of[c] IBM’s own operating systems, and for all system calls in Linux. In later versions of MVS, IBM uses the Program Call (PC) instruction for many newer facilities. In particular, PC is used when the caller might be in Service Request Block (SRB) mode.

The PDP-11 minicomputer used the EMT and IOT instructions, which, similar to the IBM System/360 SVC and x86 INT, put the code in the instruction; they generate interrupts to specific addresses, transferring control to the operating system. The VAX 32-bit successor to the PDP-11 series used the CHMK, CHME, and CHMS instructions to make system calls to privileged code at various levels; the code is an argument to the instruction.

Categories of system calls[edit]

System calls can be grouped roughly into six major categories:[12]

  1. Process control
    • create process (for example, fork on Unix-like systems, or NtCreateProcess in the Windows NT Native API)
    • terminate process
    • load, execute
    • get/set process attributes
    • wait for time, wait event, signal event
    • allocate and free memory
  2. File management
    • create file, delete file
    • open, close
    • read, write, reposition
    • get/set file attributes
  3. Device management
    • request device, release device
    • read, write, reposition
    • get/set device attributes
    • logically attach or detach devices
  4. Information maintenance
    • get/set total system information (including time, date, computer name, enterprise etc.)
    • get/set process, file, or device metadata (including author, opener, creation time and date, etc.)
  5. Communication
    • create, delete communication connection
    • send, receive messages
    • transfer status information
    • attach or detach remote devices
  6. Protection
    • get/set file permissions

Processor mode and context switching[edit]

System calls in most Unix-like systems are processed in kernel mode, which is accomplished by changing the processor execution mode to a more privileged one, but no process context switch is necessary – although a privilege context switch does occur. The hardware sees the world in terms of the execution mode according to the processor status register, and processes are an abstraction provided by the operating system. A system call does not generally require a context switch to another process; instead, it is processed in the context of whichever process invoked it.[13][14]

In a multithreaded process, system calls can be made from multiple threads. The handling of such calls is dependent on the design of the specific operating system kernel and the application runtime environment. The following list shows typical models followed by operating systems:[15][16]

  • Many-to-one model: All system calls from any user thread in a process are handled by a single kernel-level thread. This model has a serious drawback – any blocking system call (like awaiting input from the user) can freeze all the other threads. Also, since only one thread can access the kernel at a time, this model cannot utilize multiple cores of processors.
  • One-to-one model: Every user thread gets attached to a distinct kernel-level thread during a system call. This model solves the above problem of blocking system calls. It is found in all major Linux distributions, macOS, iOS, recent Windows and Solaris versions.
  • Many-to-many model: In this model, a pool of user threads is mapped to a pool of kernel threads. All system calls from a user thread pool are handled by the threads in their corresponding kernel thread pool.
  • Hybrid model: This model implements both many to many and one to one models depending upon the choice made by the kernel. This is found in old versions of IRIX, HP-UX and Solaris.

See also[edit]

  • Linux kernel API
  • VDSO

Notes[edit]

  1. ^ In UNIX-like operating systems, system calls are used only for the kernel
  2. ^ In many but not all cases, IBM documented, e.g., the SVC number, the parameter registers.
  3. ^ The CP components of CP-67 and VM use the Diagnose (DIAG) instruction as a Hypervisor CALL (HVC) from a virtual machine to CP.

References[edit]

  1. ^ IBM (March 1967). «Writing SVC Routines». IBM System/360 Operating System System Programmer’s Guide (PDF). Third Edition. pp. 32–36. C28-6550-2.
  2. ^ «syscalls(2) — Linux manual page».
  3. ^ OpenBSD (14 September 2013). «System call names (kern/syscalls.c)». BSD Cross Reference.
  4. ^ NetBSD (17 October 2013). «System call names (kern/syscalls.c)». BSD Cross Reference.
  5. ^ «FreeBSD syscalls.c, the list of syscall names and IDs».
  6. ^ Mateusz «j00ru» Jurczyk (5 November 2017). «Windows WIN32K.SYS System Call Table (NT/2000/XP/2003/Vista/2008/7/8/10)».
  7. ^ «Plan 9 sys.h, the list of syscall names and IDs».
  8. ^ «SYSENTER (OSDev wiki)».
  9. ^ Anonymous (19 December 2002). «Linux 2.5 gets vsyscalls, sysenter support». KernelTrap. Retrieved 1 January 2008.
  10. ^ Manu Garg (2006). «Sysenter Based System Call Mechanism in Linux 2.6».
  11. ^ «Liberation: x86 Instruction Set Reference». renejeschke.de. Retrieved 4 July 2015.
  12. ^ Silberschatz, Abraham (2018). Operating System Concepts. Peter B Galvin; Greg Gagne (10th ed.). Hoboken, NJ: Wiley. p. 67. ISBN 9781119320913. OCLC 1004849022.
  13. ^ Bach, Maurice J. (1986), The Design of the UNIX Operating System, Prentice Hall, pp. 15–16.
  14. ^ Elliot, John (2011). «Discussion of system call implementation at ProgClub including quote from Bach 1986».
  15. ^ «Threads».
  16. ^ «Threading Models» (PDF).

External links[edit]

  • A list of modern Unix-like system calls
  • Interactive Linux kernel map with main API functions and structures, PDF version
  • Linux system calls – system calls for Linux kernel 2.2, with IA-32 calling conventions
  • How System Calls Work on Linux/i86 (1996, based on the 1993 0.99.2 kernel)
  • Sysenter Based System Call Mechanism in Linux 2.6 (2006)
  • Kernel command using Linux system calls, IBM developerWorks
  • Choudhary, Amit; HOWTO for Implementing a System Call on Linux 2.6
  • Jorrit N. Herder, Herbert Bos, Ben Gras, Philip Homburg, and Andrew S. Tanenbaum, Modular system programming on Minix 3, ;login: 31, no. 2 (April 2006); 19–28, accessed 5 March 2018
  • A simple open Unix Shell in C language – examples on System Calls under Unix
  • Inside the Native API – Windows NT Native API, including system calls
  • Gulbrandsen, John; System Call Optimization with the SYSENTER Instruction, CodeGuru.com, 8 October 2004

Понравилась статья? Поделить с друзьями:
  • Какая платформа не поддерживается windows icd
  • Какая нормальная оценка производительности windows 7
  • Какая версия vmware поддерживает windows 7
  • Какая песня больше ассоциируется с русифицированной системой windows
  • Какая нормальная нагрузка на память windows 10