Golang标准库syscall详解(什么是系统调用)
作者:西京刀客 发布时间:2024-05-28 15:23:35
一、什么是系统调用
In computing, a system call is the programmatic way in which a computer program requests a service from the kernel of the operating system it is executed on. This may include hardware-related services (for example, accessing a hard disk drive), 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.
系统调用是程序向操作系统内核请求服务的过程,通常包含硬件相关的服务(例如访问硬盘),创建新进程等。系统调用提供了一个进程和操作系统之间的接口。
二、Golang标准库-syscall
syscall包包含一个指向底层操作系统原语的接口。
注意:该软件包已被锁定。标准以外的代码应该被迁移到golang.org/x/sys存储库中使用相应的软件包。这也是应用新系统或版本所需更新的地方。 Signal , Errno 和 SysProcAttr 在 golang.org/x/sys 中尚不可用,并且仍然必须从 syscall 程序包中引用。有关更多信息,请参见 https://golang.org/s/go1.4-syscall。
https://pkg.go.dev/golang.org/x/sys
该存储库包含用于与操作系统进行低级交互的补充Go软件包。
1. syscall无处不在
举个最常用的例子, fmt.Println(“hello world”), 这里就用到了系统调用 write, 我们翻一下源码。
func Println(a ...interface{}) (n int, err error) {
return Fprintln(os.Stdout, a...)
}
Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
func (f *File) write(b []byte) (n int, err error) {
if len(b) == 0 {
return 0, nil
}
// 实际的write方法,就是调用syscall.Write()
return fixCount(syscall.Write(f.fd, b))
}
2. syscall demo举例:
go版本的strace Strace
strace 是用于查看进程系统调用的工具, 一般使用方法如下:
strace -c 用于统计各个系统调用的次数
[root@localhost ~]# strace -c echo hello
hello
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
0.00 0.000000 0 1 read
0.00 0.000000 0 1 write
0.00 0.000000 0 3 open
0.00 0.000000 0 5 close
0.00 0.000000 0 4 fstat
0.00 0.000000 0 9 mmap
0.00 0.000000 0 4 mprotect
0.00 0.000000 0 2 munmap
0.00 0.000000 0 4 brk
0.00 0.000000 0 1 1 access
0.00 0.000000 0 1 execve
0.00 0.000000 0 1 arch_prctl
------ ----------- ----------- --------- --------- ----------------
100.00 0.000000 36 1 total
[root@localhost ~]#
stace 的实现原理是系统调用 ptrace, 我们来看下 ptrace 是什么。
man page 描述如下:
The ptrace() system call provides a means by which one process (the “tracer”) may observe and control the execution of another process (the “tracee”), and examine and change the tracee's memory and registers. It is primarily used to implement breakpoint debuggingand system call tracing.
简单来说有三大能力:
追踪系统调用
读写内存和寄存器
向被追踪程序传递信号
ptrace接口:
int ptrace(int request, pid_t pid, caddr_t addr, int data);
request包含:
PTRACE_ATTACH
PTRACE_SYSCALL
PTRACE_PEEKTEXT, PTRACE_PEEKDATA
等
tracer 使用 PTRACE_ATTACH 命令,指定需要追踪的PID。紧接着调用 PTRACE_SYSCALL。
tracee 会一直运行,直到遇到系统调用,内核会停止执行。 此时,tracer 会收到 SIGTRAP 信号,tracer 就可以打印内存和寄存器中的信息了。
接着,tracer 继续调用 PTRACE_SYSCALL, tracee 继续执行,直到 tracee退出当前的系统调用。
需要注意的是,这里在进入syscall和退出syscall时,tracer都会察觉。
go版本的strace
了解以上内容后,presenter 现场实现了一个go版本的strace, 需要在 linux amd64 环境编译。
https://github.com/silentred/gosys
// strace.go
package main
import (
"fmt"
"os"
"os/exec"
"syscall"
)
func main() {
var err error
var regs syscall.PtraceRegs
var ss syscallCounter
ss = ss.init()
fmt.Println("Run: ", os.Args[1:])
cmd := exec.Command(os.Args[1], os.Args[2:]...)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.SysProcAttr = &syscall.SysProcAttr{
Ptrace: true,
}
cmd.Start()
err = cmd.Wait()
if err != nil {
fmt.Printf("Wait err %v \n", err)
}
pid := cmd.Process.Pid
exit := true
for {
// 记得 PTRACE_SYSCALL 会在进入和退出syscall时使 tracee 暂停,所以这里用一个变量控制,RAX的内容只打印一遍
if exit {
err = syscall.PtraceGetRegs(pid, ®s)
if err != nil {
break
}
//fmt.Printf("%#v \n",regs)
name := ss.getName(regs.Orig_rax)
fmt.Printf("name: %s, id: %d \n", name, regs.Orig_rax)
ss.inc(regs.Orig_rax)
}
// 上面Ptrace有提到的一个request命令
err = syscall.PtraceSyscall(pid, 0)
if err != nil {
panic(err)
}
// 猜测是等待进程进入下一个stop,这里如果不等待,那么会打印大量重复的调用函数名
_, err = syscall.Wait4(pid, nil, 0, nil)
if err != nil {
panic(err)
}
exit = !exit
}
ss.print()
}
// 用于统计信息的counter, syscallcounter.go
package main
import (
"fmt"
"os"
"text/tabwriter"
"github.com/seccomp/libseccomp-golang"
)
type syscallCounter []int
const maxSyscalls = 303
func (s syscallCounter) init() syscallCounter {
s = make(syscallCounter, maxSyscalls)
return s
}
func (s syscallCounter) inc(syscallID uint64) error {
if syscallID > maxSyscalls {
return fmt.Errorf("invalid syscall ID (%x)", syscallID)
}
s[syscallID]++
return nil
}
func (s syscallCounter) print() {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 8, ' ', tabwriter.AlignRight|tabwriter.Debug)
for k, v := range s {
if v > 0 {
name, _ := seccomp.ScmpSyscall(k).GetName()
fmt.Fprintf(w, "%d\t%s\n", v, name)
}
}
w.Flush()
}
func (s syscallCounter) getName(syscallID uint64) string {
name, _ := seccomp.ScmpSyscall(syscallID).GetName()
return name
}
最后结果:
Run: [echo hello]
Wait err stop signal: trace/breakpoint trap
name: execve, id: 59
name: brk, id: 12
name: access, id: 21
name: mmap, id: 9
name: access, id: 21
name: open, id: 2
name: fstat, id: 5
name: mmap, id: 9
name: close, id: 3
name: access, id: 21
name: open, id: 2
name: read, id: 0
name: fstat, id: 5
name: mmap, id: 9
name: mprotect, id: 10
name: mmap, id: 9
name: mmap, id: 9
name: close, id: 3
name: mmap, id: 9
name: arch_prctl, id: 158
name: mprotect, id: 10
name: mprotect, id: 10
name: mprotect, id: 10
name: munmap, id: 11
name: brk, id: 12
name: brk, id: 12
name: open, id: 2
name: fstat, id: 5
name: mmap, id: 9
name: close, id: 3
name: fstat, id: 5
hello
name: write, id: 1
name: close, id: 3
name: close, id: 3
1|read
1|write
3|open
5|close
4|fstat
7|mmap
4|mprotect
1|munmap
3|brk
3|access
1|execve
1|arch_prctl
三、参考
Golang标准库——syscall
参考URL: https://www.jianshu.com/p/44109d5e045b
Golang 与系统调用
参考URL: https://blog.csdn.net/weixin_33744141/article/details/89033990
来源:https://blog.csdn.net/inthat/article/details/117248718


猜你喜欢
- 针对border边框属性在浏览器中的渲染方式很早以前就开始在QQ群中看到大家在讨论,而我也一直以border:0 none;的方式处理。其中
- 这篇文章中的内容是来源于去年我用美国的VPS搭建博客的初始阶段,那是有很多恶意访问,我就根据access log中的源IP来进行了很多统计,
- rs.open sql,conn,A,B A: ADOPenforwardonly (=0) 只读,且当前数据记录只能向下移动。 ADOPe
- 折线图是数据分析中非常常用的图形。其中,折线图主要是以折线的上升或下降来表示统计数量的增减变化的统计图。用于分析自变量和因变量之间的趋势关系
- 1.我在一行结束后按回车键,就跳到隔一行的段落上,如何避免隔行跳到下一段落? A.在一行结束后先按着[Shift]键,再按回车就可以不隔行跳
- 简介Python Fire是谷歌开源的一个第三方库,用于从任何Python对象自动生成命令行接口(CLI),可用于如快速拓展成命令行等形式。
- 瞬间设计是什么?良好的用户体验,全在于那些完美的瞬间。在第一个瞬间,假设当一位用户从购物搜索结果页面跳转到某个店铺的时候,他此刻可能是想看看
- 浏览器中某些计算和处理要比其他的昂贵的多。例如,DOM操作比起非DOM交互需要更多的内存和CPU时间。连续尝试进行过多的DOM相关操作可能会
- 上次我重新修改了UBB的转换后,又很多朋友反映日文显示的时候出错了。我在本地测试了一下,结果出现了 Invalid procedure ca
- 前言本文给大家深入的解答了关于Python的11道基本面试题,通过这些面试题大家能对python进一步的了解和学习,下面话不多说,来看看详细
- 自定义模板403<!DOCTYPE html><html lang="en"><head&
- 本文实例讲述了Python数据分析之双色球统计单个红和蓝球哪个比例高的方法。分享给大家供大家参考,具体如下:统计单个红球和蓝球,哪个组合最多
- 在 Python 中,函数可以通过以下语法定义和使用:def function_name(parameter1, parameter2, .
- 方法一、使用在父模板中使用{include file="child.tpl"}直接将子模板包含进来优点:1、有利于模块的
- 本文实例讲述了JavaScript实现彩虹文字效果的方法。分享给大家供大家参考。具体如下:<HTML><HEAD>&
- 这是支持的下载版本,去官网下载2020.3及以上(2021-03-18测试破解有效)官网下载地址:https://www.jetbrains
- Django框架中的URL分发采用正则表达式匹配来进行,以下是正则表达式的基本规则:官方演示代码:from django.conf.urls
- 环境:window7 x64、python3.4、django1.10一、pip install xadmin安装报错1、使用pip ins
- 说明:几个简单的基本的sql语句 选择:select * from table1 where 范围 插入:insert into table
- 优化查询使用Explain语句分析查询语句Explain 用来分析 SELECT 查询语句,开发人员可以通过分析 Explain 结果来优化