rCore-Tutorial-Book-v3 icon indicating copy to clipboard operation
rCore-Tutorial-Book-v3 copied to clipboard

ch8: 用户态的线程管理一节 spawn 方法中 s_ptr.offset(32) 问题

Open h888866j opened this issue 1 year ago • 0 comments

http://rcore-os.cn/rCore-Tutorial-Book-v3/chapter8/1thread.html#id7 中Comnents中提出的问题未见修复

章节链接:用户态的线程管理 - rCore-Tutorial-Book-v3 3.6.0-alpha.1 文档

当应用要创建一个线程时,会调用 runtime.spawn 函数。这个函数主要完成的功能是:

  • 第4~12行,在线程向量中查找一个状态为 Available 的空闲线程控制块;

  • 第14~20行,初始化该空闲线程的线程控制块;

  • x1 寄存器:老的返回地址 – guard 函数地址

  • nx1 寄存器:新的返回地址 – 输入参数 f 函数地址

  • x2 寄存器:新的栈地址 – available.stack+size

 1    impl Runtime {
 2        pub fn spawn(&mut self, f: fn()) {
 3            let available = self
 4                .tasks
 5                .iter_mut()
 6                .find(|t| t.state == State::Available)
 7                .expect("no available task.");
 8
 9            let size = available.stack.len();
10            unsafe {
11                let s_ptr = available.stack.as_mut_ptr().offset(size as isize);
12                let s_ptr = (s_ptr as usize & !7) as *mut u8;
13
14                available.ctx.x1 = guard as u64;  //ctx.x1  is old return address
15                available.ctx.nx1 = f as u64;     //ctx.nx1 is new return address
16                available.ctx.x2 = s_ptr.offset(32) as u64; //cxt.x2 is sp  <<< clone的仓库代码中这里是 -32
17
18            }
19            available.state = State::Ready;
20        }
21    }

详见comments: https://github.com/rcore-os/rCore-Tutorial-Book-v3/issues/95#issuecomment-1500826664

h888866j avatar Jul 09 '23 13:07 h888866j