gpt4 book ai didi

go - syscall.Mmap的实现

转载 作者:行者123 更新时间:2023-12-01 21:14:26 26 4
gpt4 key购买 nike

源代码是here

我对我的理解发表了评论

type mmapper struct {
sync.Mutex
active map[*byte][]byte // active mappings; key is last byte in mapping
mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, error)
munmap func(addr uintptr, length uintptr) error
}

func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
if length <= 0 {
return nil, EINVAL
}

// Map the requested memory using a operating-system dependent function
addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset)
if errno != nil {
return nil, errno
}

// Create slice memory layout
var sl = struct {
addr uintptr
len int
cap int
}{addr, length, length}

// Cast it to byte slice
b := *(*[]byte)(unsafe.Pointer(&sl))

// ??
p := &b[cap(b)-1]
m.Lock()
defer m.Unlock()
m.active[p] = b
return b, nil
}

func (m *mmapper) Munmap(data []byte) (err error) {
if len(data) == 0 || len(data) != cap(data) {
return EINVAL
}

// Check if the slice is valid ?
p := &data[cap(data)-1]
m.Lock()
defer m.Unlock()
b := m.active[p]
if b == nil || &b[0] != &data[0] {
return EINVAL
}

// Unmap the memory and update m.
if errno := m.munmap(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))); errno != nil {
return errno
}
delete(m.active, p)
return nil
}

所以我的问题只是关于 mmapper.active字段,我不明白它的用途。

我已经阅读过有关uintptr和垃圾收集器的问题,也许是为了避免它们?
或者,也许只是为了在调用 Munmap时验证 slice ?

最佳答案

它可能是一个 slice 的一个 slice ,那么其支持的指针将不同于原始的指针。此 map 使我们可以检查是否 slice 了 slice 。

b := []byte{1,2,3,4}

fmt.Println(&b[0]) // 0x40e020

b = b[1:]

fmt.Println(&b[0]) // 0x40e021

https://play.golang.org/p/WJogLiMOfj7

关于go - syscall.Mmap的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60329973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com