Golang标准库syscall详解(什么是系统调用)


Posted in Golang onMay 25, 2021

一、什么是系统调用

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, &regs)
            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

以上就是Golang标准库syscall详解(什么是系统调用)的详细内容,更多关于Golang标准库syscall的资料请关注三水点靠木其它相关文章!

Golang 相关文章推荐
Go语言中break label与goto label的区别
Apr 28 Golang
golang slice元素去重操作
Apr 30 Golang
Go语言 go程释放操作(退出/销毁)
Apr 30 Golang
go类型转换及与C的类型转换方式
May 05 Golang
聊聊golang中多个defer的执行顺序
May 08 Golang
Golang实现AES对称加密的过程详解
May 20 Golang
golang内置函数len的小技巧
Jul 25 Golang
Go 通过结构struct实现接口interface的问题
Oct 05 Golang
golang为什么要统一错误处理
Apr 03 Golang
Golang 链表的学习和使用
Apr 19 Golang
Golang实现可重入锁的示例代码
May 25 Golang
go 实现简易端口扫描的示例
May 22 #Golang
go xorm框架的使用
May 22 #Golang
Golang实现AES对称加密的过程详解
May 20 #Golang
go语言基础 seek光标位置os包的使用
May 09 #Golang
Golang 实现获取当前函数名称和文件行号等操作
May 08 #Golang
Golang 获取文件md5校验的方法以及效率对比
May 08 #Golang
GoLang中生成UUID唯一标识的实现
May 08 #Golang
You might like
JavaScript入门教程(6) Window窗口对象
2009/01/31 Javascript
aspx中利用js实现确认删除代码
2010/07/22 Javascript
jquery关于图形报表的运用实现代码
2011/01/06 Javascript
纯JAVASCRIPT图表动画插件Highcharts Examples
2011/04/16 Javascript
jquery点击页面任何区域实现鼠标焦点十字效果
2013/06/21 Javascript
javascript中RegExp保留小数点后几位数的方法分享
2013/08/13 Javascript
JS连接SQL数据库与ACCESS数据库的方法实例
2013/11/21 Javascript
如何判断微信内置浏览器(通过User Agent实现)
2014/09/01 Javascript
基于javascript实现tab切换特效
2016/03/29 Javascript
js中json对象和字符串的理解及相互转化操作实现方法
2017/09/22 Javascript
深入浅析Vue中的 computed 和 watch
2018/06/06 Javascript
vue.js动画中的js钩子函数的实现
2018/07/06 Javascript
详解vue中使用微信jssdk
2019/04/19 Javascript
微信小程序中button去除默认的边框实例代码
2019/08/01 Javascript
基于JS实现视频上传显示进度条
2020/05/12 Javascript
ES6扩展运算符和rest运算符用法实例分析
2020/05/23 Javascript
vue使用自定义事件的表单输入组件用法详解【日期组件与货币组件】
2020/06/01 Javascript
详解JavaScript类型判断的四种方法
2020/10/21 Javascript
javascript实现拼图游戏
2021/01/29 Javascript
Flask框架的学习指南之制作简单blog系统
2016/11/20 Python
Python中PyQt5/PySide2的按钮控件使用实例
2019/08/17 Python
Python命令行参数解析工具 docopt 安装和应用过程详解
2019/09/26 Python
Python PyInstaller库基本使用方法分析
2019/12/12 Python
获取CSDN文章内容并转换为markdown文本的python
2020/09/06 Python
Numpy实现卷积神经网络(CNN)的示例
2020/10/09 Python
带有css3动画效果的兼容多浏览器简单导航条示例
2014/01/26 HTML / CSS
简述synchronized和java.util.concurrent.locks.Lock的异同
2014/12/08 面试题
PPP协议组成及简述协议协商的基本过程
2015/05/28 面试题
应聘自荐信
2013/12/14 职场文书
平面设计专业大学生职业规划书
2014/03/12 职场文书
人事经理岗位职责
2014/04/28 职场文书
教师节演讲稿
2014/05/06 职场文书
少先队大队委竞选口号
2015/12/25 职场文书
MySQL update set 和 and的区别
2021/05/08 MySQL
使用CSS实现黑白格背景效果
2022/06/01 HTML / CSS
Win11远程连接不上怎么办?Win11远程桌面用不了的解决方法
2022/08/05 数码科技