|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="zh-CN" class="light" dir="ltr">
|
|
|
|
|
<head>
|
|
|
|
|
<!-- Book generated using mdBook -->
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>内联汇编 - Rust语言圣经(Rust Course)</title>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom HTML head -->
|
|
|
|
|
|
|
|
|
|
<meta name="description" content="">
|
|
|
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
|
|
|
<meta name="theme-color" content="#ffffff">
|
|
|
|
|
|
|
|
|
|
<link rel="icon" href="../../favicon.svg">
|
|
|
|
|
<link rel="shortcut icon" href="../../favicon.png">
|
|
|
|
|
<link rel="stylesheet" href="../../css/variables.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/general.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/chrome.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/print.css" media="print">
|
|
|
|
|
|
|
|
|
|
<!-- Fonts -->
|
|
|
|
|
<link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
|
|
|
|
|
<link rel="stylesheet" href="../../fonts/fonts.css">
|
|
|
|
|
|
|
|
|
|
<!-- Highlight.js Stylesheets -->
|
|
|
|
|
<link rel="stylesheet" href="../../highlight.css">
|
|
|
|
|
<link rel="stylesheet" href="../../tomorrow-night.css">
|
|
|
|
|
<link rel="stylesheet" href="../../ayu-highlight.css">
|
|
|
|
|
|
|
|
|
|
<!-- Custom theme stylesheets -->
|
|
|
|
|
<link rel="stylesheet" href="../../theme/style.css">
|
|
|
|
|
|
|
|
|
|
</head>
|
|
|
|
|
<body class="sidebar-visible no-js">
|
|
|
|
|
<div id="body-container">
|
|
|
|
|
<!-- Provide site root to javascript -->
|
|
|
|
|
<script>
|
|
|
|
|
var path_to_root = "../../";
|
|
|
|
|
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
|
|
|
|
<script>
|
|
|
|
|
try {
|
|
|
|
|
var theme = localStorage.getItem('mdbook-theme');
|
|
|
|
|
var sidebar = localStorage.getItem('mdbook-sidebar');
|
|
|
|
|
|
|
|
|
|
if (theme.startsWith('"') && theme.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
|
|
|
|
}
|
|
|
|
|
} catch (e) { }
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Set the theme before any content is loaded, prevents flash -->
|
|
|
|
|
<script>
|
|
|
|
|
var theme;
|
|
|
|
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|
|
|
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
|
|
|
|
var html = document.querySelector('html');
|
|
|
|
|
html.classList.remove('light')
|
|
|
|
|
html.classList.add(theme);
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
body.classList.remove('no-js')
|
|
|
|
|
body.classList.add('js');
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
|
|
|
|
|
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
|
|
|
<script>
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
var sidebar = null;
|
|
|
|
|
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
|
|
|
|
|
if (document.body.clientWidth >= 1080) {
|
|
|
|
|
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
|
|
|
|
sidebar = sidebar || 'visible';
|
|
|
|
|
} else {
|
|
|
|
|
sidebar = 'hidden';
|
|
|
|
|
}
|
|
|
|
|
sidebar_toggle.checked = sidebar === 'visible';
|
|
|
|
|
body.classList.remove('sidebar-visible');
|
|
|
|
|
body.classList.add("sidebar-" + sidebar);
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
|
|
|
|
<div class="sidebar-scrollbox">
|
|
|
|
|
<ol class="chapter"><li class="chapter-item affix "><a href="../../about-book.html">关于本书</a></li><li class="chapter-item affix "><a href="../../into-rust.html">进入 Rust 编程世界</a></li><li class="chapter-item affix "><a href="../../first-try/sth-you-should-not-do.html">避免从入门到放弃</a></li><li class="chapter-item affix "><a href="../../community.html">社区和锈书</a></li><li class="spacer"></li><li class="chapter-item affix "><a href="../../some-thoughts.html">Xobserve: 一切皆可观测</a></li><li class="chapter-item affix "><a href="../../beat-ai.html">BeatAI: 工程师 AI 入门圣经</a></li><li class="chapter-item affix "><li class="part-title">Rust 语言基础学习</li><li class="spacer"></li><li class="chapter-item "><a href="../../first-try/intro.html"><strong aria-hidden="true">1.</strong> 寻找牛刀,以便小试</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../first-try/installation.html"><strong aria-hidden="true">1.1.</strong> 安装 Rust 环境</a></li><li class="chapter-item "><a href="../../first-try/editor.html"><strong aria-hidden="true">1.2.</strong> 墙推 VSCode!</a></li><li class="chapter-item "><a href="../../first-try/cargo.html"><strong aria-hidden="true">1.3.</strong> 认识 Cargo</a></li><li class="chapter-item "><a href="../../first-try/hello-world.html"><strong aria-hidden="true">1.4.</strong> 不仅仅是 Hello world</a></li><li class="chapter-item "><a href="../../first-try/slowly-downloading.html"><strong aria-hidden="true">1.5.</strong> 下载依赖太慢了?</a></li></ol></li><li class="chapter-item "><a href="../../basic/intro.html"><strong aria-hidden="true">2.</strong> Rust 基础入门</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/variable.html"><strong aria-hidden="true">2.1.</strong> 变量绑定与解构</a></li><li class="chapter-item "><a href="../../basic/base-type/index.html"><strong aria-hidden="true">2.2.</strong> 基本类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/base-type/numbers.html"><strong aria-hidden="true">2.2.1.</strong> 数值类型</a></li><li class="chapter-item "><a href="../../basic/base-type/char-bool.html"><strong aria-hidden="true">2.2.2.</strong> 字符、布尔、单元类型</a></li><li class="chapter-item "><a href="../../basic/base-type/statement-expression.html"><strong aria-hidden="true">2.2.3.</strong> 语句与表达式</a></li><li class="chapter-item "><a href="../../basic/base-type/function.html"><strong aria-hidden="true">2.2.4.</strong> 函数</a></li></ol></li><li class="chapter-item "><a href="../../basic/ownership/index.html"><strong aria-hidden="true">2.3.</strong> 所有权和借用</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/ownership/ownership.html"><strong aria-hidden="true">2.3.1.</strong> 所有权</a></li><li class="chapter-item "><a href="../../basic/ownership/borrowing.html"><strong aria-hidden="true">2.3.2.</strong> 引用与借用</a></li></ol></li><li class="chapter-item "><a href="../../basic/compound-type/intro.html"><strong aria-hidden="true">2.4.</strong> 复合类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/compound-type/string-slice.html"><strong aria-hidden="true">2.4.1.</strong> 字符串与切片</a></li><li class="chapter-item "><a href="../../basic/compound-type/tuple.html"><strong aria-hidden="true">2.4.2.</strong> 元组</a></li><li class="chapter-item "><a href="../../basic/compound-type/struct.html"><strong aria-hidden="true">2.4.3.</strong> 结构体</a></li><li class="chapter-item "><a href="../../basic/compound-type/enum.html"><strong aria-hidden="true">2.4.4.</strong> 枚举</a></li><li class="chapter-item "><a href="../../basic/compound-type/array.html"><strong aria-hidden="true">2.4.5.</strong> 数组</a></l
|
|
|
|
|
</div>
|
|
|
|
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
|
|
|
|
<div class="sidebar-resize-indicator"></div>
|
|
|
|
|
</div>
|
|
|
|
|
</nav>
|
|
|
|
|
|
|
|
|
|
<!-- Track and set sidebar scroll position -->
|
|
|
|
|
<script>
|
|
|
|
|
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
|
|
|
|
|
sidebarScrollbox.addEventListener('click', function(e) {
|
|
|
|
|
if (e.target.tagName === 'A') {
|
|
|
|
|
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
|
|
|
|
|
}
|
|
|
|
|
}, { passive: true });
|
|
|
|
|
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
|
|
|
|
|
sessionStorage.removeItem('sidebar-scroll');
|
|
|
|
|
if (sidebarScrollTop) {
|
|
|
|
|
// preserve sidebar scroll position when navigating via links within sidebar
|
|
|
|
|
sidebarScrollbox.scrollTop = sidebarScrollTop;
|
|
|
|
|
} else {
|
|
|
|
|
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
|
|
|
|
|
var activeSection = document.querySelector('#sidebar .active');
|
|
|
|
|
if (activeSection) {
|
|
|
|
|
activeSection.scrollIntoView({ block: 'center' });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<div id="page-wrapper" class="page-wrapper">
|
|
|
|
|
|
|
|
|
|
<div class="page">
|
|
|
|
|
<div id="menu-bar-hover-placeholder"></div>
|
|
|
|
|
<div id="menu-bar" class="menu-bar sticky">
|
|
|
|
|
<div class="left-buttons">
|
|
|
|
|
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
|
|
|
|
<i class="fa fa-bars"></i>
|
|
|
|
|
</label>
|
|
|
|
|
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
|
|
|
|
<i class="fa fa-paint-brush"></i>
|
|
|
|
|
</button>
|
|
|
|
|
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
|
|
|
|
</ul>
|
|
|
|
|
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
|
|
|
|
<i class="fa fa-search"></i>
|
|
|
|
|
</button>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<h1 class="menu-title">Rust语言圣经(Rust Course)</h1>
|
|
|
|
|
|
|
|
|
|
<div class="right-buttons">
|
|
|
|
|
<a href="../../print.html" title="Print this book" aria-label="Print this book">
|
|
|
|
|
<i id="print-button" class="fa fa-print"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a href="https://github.com/sunface/rust-course" title="Git repository" aria-label="Git repository">
|
|
|
|
|
<i id="git-repository-button" class="fa fa-github"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a href="https://github.com/sunface/rust-course/edit/main/src/advance/unsafe/inline-asm.md" title="Suggest an edit" aria-label="Suggest an edit">
|
|
|
|
|
<i id="git-edit-button" class="fa fa-edit"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div id="search-wrapper" class="hidden">
|
|
|
|
|
<form id="searchbar-outer" class="searchbar-outer">
|
|
|
|
|
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
|
|
|
|
|
</form>
|
|
|
|
|
<div id="searchresults-outer" class="searchresults-outer hidden">
|
|
|
|
|
<div id="searchresults-header" class="searchresults-header"></div>
|
|
|
|
|
<ul id="searchresults">
|
|
|
|
|
</ul>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
|
|
|
|
<script>
|
|
|
|
|
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
|
|
|
|
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
|
|
|
|
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
|
|
|
|
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
|
|
|
|
});
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<div id="content" class="content">
|
|
|
|
|
<!-- Page table of contents -->
|
|
|
|
|
<div class="sidetoc"><nav class="pagetoc"></nav></div>
|
|
|
|
|
<main>
|
|
|
|
|
<h1 id="内联汇编"><a class="header" href="#内联汇编">内联汇编</a></h1>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p>本章内容对于学习 Rust 不是必须的,而且难度很高,大家简单知道有这回事就好,不必非要学会 :D</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<p>Rust 提供了 <code>asm!</code> 宏,可以让大家在 Rust 代码中嵌入汇编代码,对于一些极致高性能或者底层的场景还是非常有用的,例如操作系统内核开发。但通常来说,大家并不应该在自己的项目中使用到该项技术,它为极客而生!</p>
|
|
|
|
|
<p>本章的例子是基于 <code>x86/x86-64</code> 汇编的,但是其它架构也是支持的,目前支持的包括:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li>x86 和 x86-64</li>
|
|
|
|
|
<li>ARM</li>
|
|
|
|
|
<li>AArch64</li>
|
|
|
|
|
<li>RISC-V</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<p>当使用在不支持的平台上时,编译器会给出报错。</p>
|
|
|
|
|
<h2 id="基本用法"><a class="header" href="#基本用法">基本用法</a></h2>
|
|
|
|
|
<p>先从一个简单例子开始:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use std::arch::asm;
|
|
|
|
|
|
|
|
|
|
unsafe {
|
|
|
|
|
asm!("nop");
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>注意 <code>unsafe</code> 语句块依然是必不可少的,因为可能在里面插入危险的指令,最终破坏代码的安全性。</p>
|
|
|
|
|
<p>上面代码将插入一个 <code>NOP</code> 指令( 空操作 ) 到编译器生成的汇编代码中,其中指令作为 <code>asm!</code> 的第一个参数传入。</p>
|
|
|
|
|
<h2 id="输入和输出"><a class="header" href="#输入和输出">输入和输出</a></h2>
|
|
|
|
|
<p>上面的代码有够无聊的,来点实际的:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use std::arch::asm;
|
|
|
|
|
|
|
|
|
|
let x: u64;
|
|
|
|
|
unsafe {
|
|
|
|
|
asm!("mov {}, 5", out(reg) x);
|
|
|
|
|
}
|
|
|
|
|
assert_eq!(x, 5);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>这段代码将 <code>5</code> 赋给 <code>u64</code> 类型的变量 <code>x</code>,值得注意的是 <code>asm!</code> 的指令参数实际上是一个格式化字符串。至于传给格式化字符串的参数,看起来还是比较陌生的:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li>首先,需要说明目标变量是作为内联汇编的输入还是输出,在本例中,是一个输出 <code>out</code></li>
|
|
|
|
|
<li>最后,要指定变量将要使用的寄存器,本例中使用通用寄存器 <code>reg</code>,编译器会自动选择合适的寄存器</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use std::arch::asm;
|
|
|
|
|
|
|
|
|
|
let i: u64 = 3;
|
|
|
|
|
let o: u64;
|
|
|
|
|
unsafe {
|
|
|
|
|
asm!(
|
|
|
|
|
"mov {0}, {1}",
|
|
|
|
|
"add {0}, 5",
|
|
|
|
|
out(reg) o,
|
|
|
|
|
in(reg) i,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
assert_eq!(o, 8);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>上面的代码中进一步使用了输入 <code>in</code>,将 <code>5</code> 加到输入的变量 <code>i</code> 上,然后将结果写到输出变量 <code>o</code>。实际的操作方式是首先将 <code>i</code> 的值拷贝到输出,然后再加上 <code>5</code>。</p>
|
|
|
|
|
<p>上例还能看出几点:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li><code>asm!</code> 允许使用多个格式化字符串,每一个作为单独一行汇编代码存在,看起来跟阅读真实的汇编代码类似</li>
|
|
|
|
|
<li>输入变量通过 <code>in</code> 来声明</li>
|
|
|
|
|
<li>和以前见过的格式化字符串一样,可以使用多个参数,通过 {0}, {1} 来指定,这种方式特别有用,毕竟在代码中,变量是经常复用的,而这种参数的指定方式刚好可以复用</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<p>事实上,还可以进一步优化代码,去掉 <code>mov</code> 指令:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use std::arch::asm;
|
|
|
|
|
|
|
|
|
|
let mut x: u64 = 3;
|
|
|
|
|
unsafe {
|
|
|
|
|
asm!("add {0}, 5", inout(reg) x);
|
|
|
|
|
}
|
|
|
|
|
assert_eq!(x, 8);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>又多出一个 <code>inout</code> 关键字,但是不难猜,它说明 <code>x</code> 即是输入又是输出。与之前的分离方式还有一点很大的区别,这种方式可以保证使用同一个寄存器来完成任务。</p>
|
|
|
|
|
<p>当然,你可以在使用 <code>inout</code> 的情况下,指定不同的输入和输出:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use std::arch::asm;
|
|
|
|
|
|
|
|
|
|
let x: u64 = 3;
|
|
|
|
|
let y: u64;
|
|
|
|
|
unsafe {
|
|
|
|
|
asm!("add {0}, 5", inout(reg) x => y);
|
|
|
|
|
}
|
|
|
|
|
assert_eq!(y, 8);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<h2 id="延迟输出操作数"><a class="header" href="#延迟输出操作数">延迟输出操作数</a></h2>
|
|
|
|
|
<p>Rust 编译器对于操作数分配是较为保守的,它会假设 <code>out</code> 可以在任何时间被写入,因此 <code>out</code> 不会跟其它参数共享它的位置。然而为了保证最佳性能,使用尽量少的寄存器是有必要的,这样它们不必在内联汇编的代码块内保存和重加载。</p>
|
|
|
|
|
<p>为了达成这个目标( 共享位置或者说寄存器,以实现减少寄存器使用的性能优化 ),Rust 提供一个 <code>lateout</code> 关键字,可以用于任何只在所有输入被消费后才被写入的输出,与之类似的还有一个 <code>inlateout</code>。</p>
|
|
|
|
|
<p>但是 <code>inlateout</code> 在某些场景中是无法使用的,例如下面的例子:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use std::arch::asm;
|
|
|
|
|
|
|
|
|
|
let mut a: u64 = 4;
|
|
|
|
|
let b: u64 = 4;
|
|
|
|
|
let c: u64 = 4;
|
|
|
|
|
unsafe {
|
|
|
|
|
asm!(
|
|
|
|
|
"add {0}, {1}",
|
|
|
|
|
"add {0}, {2}",
|
|
|
|
|
inout(reg) a,
|
|
|
|
|
in(reg) b,
|
|
|
|
|
in(reg) c,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
assert_eq!(a, 12);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>一旦用了 <code>inlateout</code> 后,上面的代码就只能运行在 <code>Debug</code> 模式下,原因是 <code>Debug</code> 并没有做任何优化,但是 <code>release</code> 发布不同,为了性能是要做很多编译优化的。</p>
|
|
|
|
|
<p>在编译优化时,编译器可以很容易的为输入 <code>b</code> 和 <code>c</code> 分配同样的是寄存器,因为它知道它们有同样的值。如果这里使用 <code>inlateout</code>, 那么 <code>a</code> 和 <code>c</code> 就可以被分配到相同的寄存器,在这种情况下,第一条指令将覆盖掉 <code>c</code> 的值,最终导致汇编代码产生错误的结果。</p>
|
|
|
|
|
<p>因此这里使用 <code>inout</code>,那么编译器就会为 <code>a</code> 分配一个独立的寄存器.</p>
|
|
|
|
|
<p>但是下面的代码又不同,它是可以使用 <code>inlateout</code> 的:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use std::arch::asm;
|
|
|
|
|
|
|
|
|
|
let mut a: u64 = 4;
|
|
|
|
|
let b: u64 = 4;
|
|
|
|
|
unsafe {
|
|
|
|
|
asm!("add {0}, {1}", inlateout(reg) a, in(reg) b);
|
|
|
|
|
}
|
|
|
|
|
assert_eq!(a, 8);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>原因在于输出只有在所有寄存器都被读取后,才被修改。因此,即使 <code>a</code> 和 <code>b</code> 被分配了同样的寄存器,代码也会正常工作,不存在之前的覆盖问题。</p>
|
|
|
|
|
<h2 id="显式指定寄存器"><a class="header" href="#显式指定寄存器">显式指定寄存器</a></h2>
|
|
|
|
|
<p>一些指令会要求操作数只能存在特定的寄存器中,因此 Rust 的内联汇编提供了一些限制操作符。</p>
|
|
|
|
|
<p>大家应该记得之前出现过的 <code>reg</code> 是适用于任何架构的通用寄存器,意味着编译器可以自己选择合适的寄存器,但是当你需要显式地指定寄存器时,很可能会变成平台相关的代码,适用移植性会差很多。例如 <code>x86</code> 下的寄存器:<code>eax</code>, <code>ebx</code>, <code>ecx</code>, <code>ebp</code>, <code>esi</code> 等等。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use std::arch::asm;
|
|
|
|
|
|
|
|
|
|
let cmd = 0xd1;
|
|
|
|
|
unsafe {
|
|
|
|
|
asm!("out 0x64, eax", in("eax") cmd);
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>上面的例子调用 <code>out</code> 指令将 <code>cmd</code> 变量的值输出到 <code>0x64</code> 内存地址中。由于 <code>out</code> 指令只接收 <code>eax</code> 和它的子寄存器,因此我们需要使用 <code>eax</code> 来指定特定的寄存器。</p>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p>显式寄存器操作数无法用于格式化字符串中,例如我们之前使用的 {},只能直接在字符串中使用 <code>eax</code>。同时,该操作数只能出现在最后,也就是在其它操作数后面出现</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use std::arch::asm;
|
|
|
|
|
|
|
|
|
|
fn mul(a: u64, b: u64) -> u128 {
|
|
|
|
|
let lo: u64;
|
|
|
|
|
let hi: u64;
|
|
|
|
|
|
|
|
|
|
unsafe {
|
|
|
|
|
asm!(
|
|
|
|
|
// The x86 mul instruction takes rax as an implicit input and writes
|
|
|
|
|
// the 128-bit result of the multiplication to rax:rdx.
|
|
|
|
|
"mul {}",
|
|
|
|
|
in(reg) a,
|
|
|
|
|
inlateout("rax") b => lo,
|
|
|
|
|
lateout("rdx") hi
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
((hi as u128) << 64) + lo as u128
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>这段代码使用了 <code>mul</code> 指令,将两个 64 位的输入相乘,生成一个 128 位的结果。</p>
|
|
|
|
|
<p>首先将变量 <code>a</code> 的值存到寄存器 <code>reg</code> 中,其次显式使用寄存器 <code>rax</code>,它的值来源于变量 <code>b</code>。结果的低 64 位存储在 <code>rax</code> 中,然后赋给变量 <code>lo</code> ,而结果的高 64 位则存在 <code>rdx</code> 中,最后赋给 <code>hi</code>。</p>
|
|
|
|
|
<h2 id="clobbered-寄存器"><a class="header" href="#clobbered-寄存器">Clobbered 寄存器</a></h2>
|
|
|
|
|
<p>在很多情况下,无需作为输出的状态都会被内联汇编修改,这个状态被称之为 "clobbered"。</p>
|
|
|
|
|
<p>我们需要告诉编译器相关的情况,因为编译器需要在内联汇编语句块的附近存储和恢复这种状态。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::arch::asm;
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
// three entries of four bytes each
|
|
|
|
|
let mut name_buf = [0_u8; 12];
|
|
|
|
|
// String is stored as ascii in ebx, edx, ecx in order
|
|
|
|
|
// Because ebx is reserved, the asm needs to preserve the value of it.
|
|
|
|
|
// So we push and pop it around the main asm.
|
|
|
|
|
// (in 64 bit mode for 64 bit processors, 32 bit processors would use ebx)
|
|
|
|
|
|
|
|
|
|
unsafe {
|
|
|
|
|
asm!(
|
|
|
|
|
"push rbx",
|
|
|
|
|
"cpuid",
|
|
|
|
|
"mov [rdi], ebx",
|
|
|
|
|
"mov [rdi + 4], edx",
|
|
|
|
|
"mov [rdi + 8], ecx",
|
|
|
|
|
"pop rbx",
|
|
|
|
|
// We use a pointer to an array for storing the values to simplify
|
|
|
|
|
// the Rust code at the cost of a couple more asm instructions
|
|
|
|
|
// This is more explicit with how the asm works however, as opposed
|
|
|
|
|
// to explicit register outputs such as `out("ecx") val`
|
|
|
|
|
// The *pointer itself* is only an input even though it's written behind
|
|
|
|
|
in("rdi") name_buf.as_mut_ptr(),
|
|
|
|
|
// select cpuid 0, also specify eax as clobbered
|
|
|
|
|
inout("eax") 0 => _,
|
|
|
|
|
// cpuid clobbers these registers too
|
|
|
|
|
out("ecx") _,
|
|
|
|
|
out("edx") _,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let name = core::str::from_utf8(&name_buf).unwrap();
|
|
|
|
|
println!("CPU Manufacturer ID: {}", name);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>例子中,我们使用 <code>cpuid</code> 指令来读取 CPU ID,该指令会将值写入到 <code>eax</code> 、<code>edx</code> 和 <code>ecx</code> 中。</p>
|
|
|
|
|
<p>即使 <code>eax</code> 从没有被读取,我们依然需要告知编译器这个寄存器被修改过,这样编译器就可以在汇编代码之前存储寄存器中的值。这个需要通过将输出声明为 <code>_</code> 而不是一个具体的变量名,代表着该输出值被丢弃。</p>
|
|
|
|
|
<p>这段代码也会绕过一个限制: <code>ebx</code> 是一个 LLVM 保留寄存器,意味着 LLVM 会假设它拥有寄存器的全部控制权,并在汇编代码块结束时将寄存器的状态恢复到最开始的状态。由于这个限制,该寄存器无法被用于输入或者输出,除非编译器使用该寄存器的满足一个通用寄存器的需求(例如 <code>in(reg)</code> )。 但这样使用后, <code>reg</code> 操作数就在使用保留寄存器时变得危险起来,原因是我们可能会无意识的破坏输入或者输出,毕竟它们共享同一个寄存器。</p>
|
|
|
|
|
<p>为了解决这个问题,我们使用 <code>rdi</code> 来存储指向输出数组的指针,通过 <code>push</code> 的方式存储 <code>ebx</code>:在汇编代码块的内部读取 <code>ebx</code> 的值,然后写入到输出数组。后面再可以通过 <code>pop</code> 的方式来回复 <code>ebx</code> 到初始的状态。</p>
|
|
|
|
|
<p><code>push</code> 和 <code>pop</code> 使用完成的 64 位 <code>rbx</code> 寄存器,来确保整个寄存器的内容都被保存。如果是在 32 位机器上,代码将使用 <code>ebx</code> 替代。</p>
|
|
|
|
|
<p>还还可以在汇编代码内部使用通用寄存器:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use std::arch::asm;
|
|
|
|
|
|
|
|
|
|
// Multiply x by 6 using shifts and adds
|
|
|
|
|
let mut x: u64 = 4;
|
|
|
|
|
unsafe {
|
|
|
|
|
asm!(
|
|
|
|
|
"mov {tmp}, {x}",
|
|
|
|
|
"shl {tmp}, 1",
|
|
|
|
|
"shl {x}, 2",
|
|
|
|
|
"add {x}, {tmp}",
|
|
|
|
|
x = inout(reg) x,
|
|
|
|
|
tmp = out(reg) _,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
assert_eq!(x, 4 * 6);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<h2 id="总结"><a class="header" href="#总结">总结</a></h2>
|
|
|
|
|
<p>由于这块儿内容过于专业,本书毕竟是通用的 Rust 学习书籍,因此关于内联汇编就不再赘述。事实上,如果你要真的写出可用的汇编代码,要学习的还很多...</p>
|
|
|
|
|
<p>感兴趣的同学可以看看如下英文资料: <a href="https://doc.rust-lang.org/reference/inline-assembly.html">Rust Reference</a> 和 <a href="https://doc.rust-lang.org/rust-by-example/unsafe/asm.html#clobbered-registers">Rust By Example</a>。</p>
|
|
|
|
|
|
|
|
|
|
<div id="giscus-container"></div>
|
|
|
|
|
</main>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
|
<a rel="prev" href="../../advance/unsafe/superpowers.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
|
|
|
<i class="fa fa-angle-left"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
<a rel="next prefetch" href="../../advance/macro.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
|
|
|
<i class="fa fa-angle-right"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
<div style="clear: both"></div>
|
|
|
|
|
</nav>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wide-wrapper" aria-label="Page navigation">
|
|
|
|
|
<a rel="prev" href="../../advance/unsafe/superpowers.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
|
|
|
<i class="fa fa-angle-left"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
<a rel="next prefetch" href="../../advance/macro.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
|
|
|
<i class="fa fa-angle-right"></i>
|
|
|
|
|
</a>
|
|
|
|
|
</nav>
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<script>
|
|
|
|
|
window.playground_copyable = true;
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<script src="../../ace.js"></script>
|
|
|
|
|
<script src="../../editor.js"></script>
|
|
|
|
|
<script src="../../mode-rust.js"></script>
|
|
|
|
|
<script src="../../theme-dawn.js"></script>
|
|
|
|
|
<script src="../../theme-tomorrow_night.js"></script>
|
|
|
|
|
|
|
|
|
|
<script src="../../elasticlunr.min.js"></script>
|
|
|
|
|
<script src="../../mark.min.js"></script>
|
|
|
|
|
<script src="../../searcher.js"></script>
|
|
|
|
|
|
|
|
|
|
<script src="../../clipboard.min.js"></script>
|
|
|
|
|
<script src="../../highlight.js"></script>
|
|
|
|
|
<script src="../../book.js"></script>
|
|
|
|
|
|
|
|
|
|
<script type="text/javascript" charset="utf-8">
|
|
|
|
|
var pagePath = "advance/unsafe/inline-asm.md"
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
|
|
<script src="../../assets/custom.js"></script>
|
|
|
|
|
<script src="../../assets/bigPicture.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|