|
|
<!DOCTYPE HTML>
|
|
|
<html lang="en" class="light sidebar-visible" dir="ltr">
|
|
|
<head>
|
|
|
<!-- Book generated using mdBook -->
|
|
|
<meta charset="UTF-8">
|
|
|
<title>不安全 Rust - Rust 程序设计语言 简体中文版</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-de23e50b.svg">
|
|
|
<link rel="shortcut icon" href="favicon-8114d1fc.png">
|
|
|
<link rel="stylesheet" href="css/variables-8adf115d.css">
|
|
|
<link rel="stylesheet" href="css/general-2459343d.css">
|
|
|
<link rel="stylesheet" href="css/chrome-ae938929.css">
|
|
|
<link rel="stylesheet" href="css/print-9e4910d8.css" media="print">
|
|
|
|
|
|
<!-- Fonts -->
|
|
|
<link rel="stylesheet" href="fonts/fonts-9644e21d.css">
|
|
|
|
|
|
<!-- Highlight.js Stylesheets -->
|
|
|
<link rel="stylesheet" id="mdbook-highlight-css" href="highlight-493f70e1.css">
|
|
|
<link rel="stylesheet" id="mdbook-tomorrow-night-css" href="tomorrow-night-4c0ae647.css">
|
|
|
<link rel="stylesheet" id="mdbook-ayu-highlight-css" href="ayu-highlight-3fdfc3ac.css">
|
|
|
|
|
|
<!-- Custom theme stylesheets -->
|
|
|
<link rel="stylesheet" href="ferris-d33b75bf.css">
|
|
|
<link rel="stylesheet" href="theme/2018-edition-4e126c62.css">
|
|
|
<link rel="stylesheet" href="theme/semantic-notes-9b5766c0.css">
|
|
|
<link rel="stylesheet" href="theme/listing-cab26221.css">
|
|
|
|
|
|
|
|
|
<!-- Provide site root and default themes to javascript -->
|
|
|
<script>
|
|
|
const path_to_root = "";
|
|
|
const default_light_theme = "light";
|
|
|
const default_dark_theme = "navy";
|
|
|
window.path_to_searchindex_js = "searchindex-7d935aa5.js";
|
|
|
</script>
|
|
|
<!-- Start loading toc.js asap -->
|
|
|
<script src="toc-9d5d6d0e.js"></script>
|
|
|
</head>
|
|
|
<body>
|
|
|
<div id="mdbook-help-container">
|
|
|
<div id="mdbook-help-popup">
|
|
|
<h2 class="mdbook-help-title">Keyboard shortcuts</h2>
|
|
|
<div>
|
|
|
<p>Press <kbd>←</kbd> or <kbd>→</kbd> to navigate between chapters</p>
|
|
|
<p>Press <kbd>S</kbd> or <kbd>/</kbd> to search in the book</p>
|
|
|
<p>Press <kbd>?</kbd> to show this help</p>
|
|
|
<p>Press <kbd>Esc</kbd> to hide this help</p>
|
|
|
</div>
|
|
|
</div>
|
|
|
</div>
|
|
|
<div id="mdbook-body-container">
|
|
|
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
|
|
<script>
|
|
|
try {
|
|
|
let theme = localStorage.getItem('mdbook-theme');
|
|
|
let 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>
|
|
|
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
|
|
|
let theme;
|
|
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
|
|
const html = document.documentElement;
|
|
|
html.classList.remove('light')
|
|
|
html.classList.add(theme);
|
|
|
html.classList.add("js");
|
|
|
</script>
|
|
|
|
|
|
<input type="checkbox" id="mdbook-sidebar-toggle-anchor" class="hidden">
|
|
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
|
<script>
|
|
|
let sidebar = null;
|
|
|
const sidebar_toggle = document.getElementById("mdbook-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 = false;
|
|
|
}
|
|
|
if (sidebar === 'visible') {
|
|
|
sidebar_toggle.checked = true;
|
|
|
} else {
|
|
|
html.classList.remove('sidebar-visible');
|
|
|
}
|
|
|
</script>
|
|
|
|
|
|
<nav id="mdbook-sidebar" class="sidebar" aria-label="Table of contents">
|
|
|
<!-- populated by js -->
|
|
|
<mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
|
|
|
<noscript>
|
|
|
<iframe class="sidebar-iframe-outer" src="toc.html"></iframe>
|
|
|
</noscript>
|
|
|
<div id="mdbook-sidebar-resize-handle" class="sidebar-resize-handle">
|
|
|
<div class="sidebar-resize-indicator"></div>
|
|
|
</div>
|
|
|
</nav>
|
|
|
|
|
|
<div id="mdbook-page-wrapper" class="page-wrapper">
|
|
|
|
|
|
<div class="page">
|
|
|
<div id="mdbook-menu-bar-hover-placeholder"></div>
|
|
|
<div id="mdbook-menu-bar" class="menu-bar sticky">
|
|
|
<div class="left-buttons">
|
|
|
<label id="mdbook-sidebar-toggle" class="icon-button" for="mdbook-sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="mdbook-sidebar">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M0 96C0 78.3 14.3 64 32 64H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 128 0 113.7 0 96zM0 256c0-17.7 14.3-32 32-32H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32c-17.7 0-32-14.3-32-32zM448 416c0 17.7-14.3 32-32 32H32c-17.7 0-32-14.3-32-32s14.3-32 32-32H416c17.7 0 32 14.3 32 32z"/></svg></span>
|
|
|
</label>
|
|
|
<button id="mdbook-theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="mdbook-theme-list">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M371.3 367.1c27.3-3.9 51.9-19.4 67.2-42.9L600.2 74.1c12.6-19.5 9.4-45.3-7.6-61.2S549.7-4.4 531.1 9.6L294.4 187.2c-24 18-38.2 46.1-38.4 76.1L371.3 367.1zm-19.6 25.4l-116-104.4C175.9 290.3 128 339.6 128 400c0 3.9 .2 7.8 .6 11.6c1.8 17.5-10.2 36.4-27.8 36.4H96c-17.7 0-32 14.3-32 32s14.3 32 32 32H240c61.9 0 112-50.1 112-112c0-2.5-.1-5-.2-7.5z"/></svg></span>
|
|
|
</button>
|
|
|
<ul id="mdbook-theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-default_theme">Auto</button></li>
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-light">Light</button></li>
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-rust">Rust</button></li>
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-coal">Coal</button></li>
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-navy">Navy</button></li>
|
|
|
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-ayu">Ayu</button></li>
|
|
|
</ul>
|
|
|
<button id="mdbook-search-toggle" class="icon-button" type="button" title="Search (`/`)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="/ s" aria-controls="mdbook-searchbar">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M416 208c0 45.9-14.9 88.3-40 122.7L502.6 457.4c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L330.7 376c-34.4 25.2-76.8 40-122.7 40C93.1 416 0 322.9 0 208S93.1 0 208 0S416 93.1 416 208zM208 352c79.5 0 144-64.5 144-144s-64.5-144-144-144S64 128.5 64 208s64.5 144 144 144z"/></svg></span>
|
|
|
</button>
|
|
|
</div>
|
|
|
|
|
|
<h1 class="menu-title">Rust 程序设计语言 简体中文版</h1>
|
|
|
|
|
|
<div class="right-buttons">
|
|
|
<a href="print.html" title="Print this book" aria-label="Print this book">
|
|
|
<span class=fa-svg id="print-button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M128 0C92.7 0 64 28.7 64 64v96h64V64H354.7L384 93.3V160h64V93.3c0-17-6.7-33.3-18.7-45.3L400 18.7C388 6.7 371.7 0 354.7 0H128zM384 352v32 64H128V384 368 352H384zm64 32h32c17.7 0 32-14.3 32-32V256c0-35.3-28.7-64-64-64H64c-35.3 0-64 28.7-64 64v96c0 17.7 14.3 32 32 32H64v64c0 35.3 28.7 64 64 64H384c35.3 0 64-28.7 64-64V384zm-16-88c-13.3 0-24-10.7-24-24s10.7-24 24-24s24 10.7 24 24s-10.7 24-24 24z"/></svg></span>
|
|
|
</a>
|
|
|
<a href="https://github.com/KaiserY/trpl-zh-cn/tree/main" title="Git repository" aria-label="Git repository">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span>
|
|
|
</a>
|
|
|
|
|
|
</div>
|
|
|
</div>
|
|
|
|
|
|
<div id="mdbook-search-wrapper" class="hidden">
|
|
|
<form id="mdbook-searchbar-outer" class="searchbar-outer">
|
|
|
<div class="search-wrapper">
|
|
|
<input type="search" id="mdbook-searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="mdbook-searchresults-outer" aria-describedby="searchresults-header">
|
|
|
<div class="spinner-wrapper">
|
|
|
<span class=fa-svg id="fa-spin"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M304 48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zm0 416c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM48 304c26.5 0 48-21.5 48-48s-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48zm464-48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM142.9 437c18.7-18.7 18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zm0-294.2c18.7-18.7 18.7-49.1 0-67.9S93.7 56.2 75 75s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zM369.1 437c18.7 18.7 49.1 18.7 67.9 0s18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9z"/></svg></span>
|
|
|
</div>
|
|
|
</div>
|
|
|
</form>
|
|
|
<div id="mdbook-searchresults-outer" class="searchresults-outer hidden">
|
|
|
<div id="mdbook-searchresults-header" class="searchresults-header"></div>
|
|
|
<ul id="mdbook-searchresults">
|
|
|
</ul>
|
|
|
</div>
|
|
|
</div>
|
|
|
|
|
|
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
|
|
<script>
|
|
|
document.getElementById('mdbook-sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
|
|
document.getElementById('mdbook-sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
|
|
Array.from(document.querySelectorAll('#mdbook-sidebar a')).forEach(function(link) {
|
|
|
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
|
|
});
|
|
|
</script>
|
|
|
|
|
|
<div id="mdbook-content" class="content">
|
|
|
<main>
|
|
|
<h2 id="不安全-rust"><a class="header" href="#不安全-rust">不安全 Rust</a></h2>
|
|
|
<!-- https://github.com/rust-lang/book/blob/main/src/ch20-01-unsafe-rust.md -->
|
|
|
<!-- commit 4b2590f90c1d72002278a8a426a94a9eadd4d498 -->
|
|
|
<p>目前为止讨论过的代码都有 Rust 在编译时会强制执行的内存安全保证。然而,Rust 还隐藏有第二种语言,它不会强制执行这类内存安全保证:这被称为 <strong>不安全 Rust</strong>(<em>unsafe Rust</em>)。它与常规 Rust 代码无异,但是会提供额外的超能力。</p>
|
|
|
<p>不安全 Rust 之所以存在,是因为静态分析本质上是保守的。当编译器尝试确定一段代码是否支持某个保证时,拒绝一些合法的程序比接受无效的程序要好一些。这必然意味着有时代码<strong>可能</strong>是合法的,但如果 Rust 编译器没有足够的信息来确定,它将拒绝该代码。在这种情况下,可以使用不安全代码告诉编译器,“相信我,我知道自己在干什么。” 不过千万注意,使用不安全 Rust 风险自担:如果不安全代码出错了,比如解引用空指针,可能会导致不安全的内存使用。</p>
|
|
|
<p>另一个 Rust 存在不安全一面的原因是底层计算机硬件固有的不安全性。如果 Rust 不允许进行不安全操作,那么有些任务则根本完成不了。Rust 需要能够进行像直接与操作系统交互甚至于编写你自己的操作系统这样的底层系统编程。底层系统编程也是 Rust 语言的目标之一。让我们看看不安全 Rust 能做什么,和怎么做。</p>
|
|
|
<h3 id="不安全的超能力"><a class="header" href="#不安全的超能力">不安全的超能力</a></h3>
|
|
|
<p>要切换到 <code>unsafe Rust</code>,可以使用 <code>unsafe</code> 关键字,然后开启一个包含不安全代码的新块。这里有五类可以在不安全 Rust 中进行而不能用于安全 Rust 的操作,它们称之为<strong>不安全的超能力</strong>(<strong>unsafe superpowers</strong>)。这些超能力包括:</p>
|
|
|
<ul>
|
|
|
<li>解引用裸指针</li>
|
|
|
<li>调用不安全的函数或方法</li>
|
|
|
<li>访问或修改可变静态变量</li>
|
|
|
<li>实现不安全 trait</li>
|
|
|
<li>访问 <code>union</code> 的字段</li>
|
|
|
</ul>
|
|
|
<p>有一点很重要,<code>unsafe</code> 并不会关闭借用检查器或禁用任何其他 Rust 安全检查:如果在不安全代码中使用引用,它仍会被检查。<code>unsafe</code> 关键字只是提供了那五个不会被编译器检查内存安全的功能。你仍然能在不安全块中获得某种程度的安全。</p>
|
|
|
<p>再者,<code>unsafe</code> 不意味着块中的代码就一定是危险的或者必然导致内存安全问题:其意图在于作为程序员,你将会确保 <code>unsafe</code> 块中的代码以有效的方式访问内存。</p>
|
|
|
<p>人难免出错,错误总会发生,不过通过要求这五类不安全操作必须位于标记为 <code>unsafe</code> 的块中,就能够知道任何与内存安全相关的错误必定位于 <code>unsafe</code> 块内。保持 <code>unsafe</code> 块尽可能小;如此当之后调查内存 bug 时就会感谢你自己了。</p>
|
|
|
<p>为了尽可能隔离不安全代码,最好将不安全代码封装进一个安全的抽象并提供安全 API,当我们学习不安全函数和方法时会讨论到。标准库的一部分被实现为在被评审过的不安全代码之上的安全抽象。这个技术防止了 <code>unsafe</code> 泄露到所有你或者用户希望使用由 <code>unsafe</code> 代码实现的功能的地方,因为使用其安全抽象是安全的。</p>
|
|
|
<p>让我们按顺序依次介绍上述五类超能力,同时我们会看到一些提供不安全代码的安全接口的抽象。</p>
|
|
|
<h3 id="解引用裸指针"><a class="header" href="#解引用裸指针">解引用裸指针</a></h3>
|
|
|
<p>回到第四章的<a href="ch04-02-references-and-borrowing.html#悬垂引用dangling-references">“悬垂引用”</a>一节,那里提到了编译器会确保引用总是有效的。不安全 Rust 有两个被称为 <strong>裸指针</strong>(<em>raw pointers</em>)的类似于引用的新类型。和引用一样,裸指针是不可变或可变的,分别写作 <code>*const T</code> 和 <code>*mut T</code>。这里的星号不是解引用运算符;它是类型名称的一部分。在裸指针的上下文中,<strong>不可变</strong> 意味着指针解引用之后不能直接赋值。</p>
|
|
|
<p>裸指针与引用和智能指针的区别在于</p>
|
|
|
<ul>
|
|
|
<li>允许忽略借用规则,可以同时拥有不可变和可变的指针,或多个指向相同位置的可变指针</li>
|
|
|
<li>不保证指向有效的内存</li>
|
|
|
<li>允许为空</li>
|
|
|
<li>不能实现任何自动清理功能</li>
|
|
|
</ul>
|
|
|
<p>通过去掉 Rust 强加的保证,你可以放弃安全保证以换取性能或使用另一个语言或硬件接口的能力,此时 Rust 的保证并不适用。</p>
|
|
|
<p>示例 20-1 展示了如何创建一个不可变裸指针和一个可变裸指针。</p>
|
|
|
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
|
|
</span> let mut num = 5;
|
|
|
|
|
|
let r1 = &raw const num;
|
|
|
let r2 = &raw mut num;
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p><span class="caption">示例 20-1: 通过引用创建裸指针</span></p>
|
|
|
<p>注意这段代码中没有引入 <code>unsafe</code> 关键字。可以在安全代码中创建裸指针;只是不能在不安全块之外解引用裸指针,稍后便会看到。</p>
|
|
|
<p>我们通过使用裸指针借用操作符(raw borrow operators)创建裸指针:<code>&raw const num</code> 会创建一个 <code>*const i32</code> 的不可变裸指针。因为由于我们是直接从一个局部变量创建它们的,因此可以确定这些特定的裸指针是有效的,但是不能对任何裸指针都做出如此假设。</p>
|
|
|
<p>为了演示这一点,接下来我们将创建一个有效性无法确定的裸指针,使用 <code>as</code> 进行类型转换而不是使用裸指针借用操作符。示例 20-2 展示了如何创建一个指向任意内存地址的裸指针。尝试使用任意内存是未定义行为:此地址可能有数据也可能没有,编译器可能会优化掉这个内存访问,或者程序可能因段错误(segmentation fault)而终止。通常在有裸指针借用操作符可用的情况下,没有充分的理由编写这样的代码,但这确实是可行的。</p>
|
|
|
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
|
|
</span> let address = 0x012345usize;
|
|
|
let r = address as *const i32;
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p><span class="caption">示例 20-2: 创建指向任意内存地址的裸指针</span></p>
|
|
|
<p>记得我们说过可以在安全代码中创建裸指针,但不能 <strong>解引用</strong> 裸指针和读取其指向的数据。示例 20-3 中,我们在裸指针上使用了解引用运算符 <code>*</code>,该操作需要一个 <code>unsafe</code> 块:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
|
|
</span> let mut num = 5;
|
|
|
|
|
|
let r1 = &raw const num;
|
|
|
let r2 = &raw mut num;
|
|
|
|
|
|
unsafe {
|
|
|
println!("r1 is: {}", *r1);
|
|
|
println!("r2 is: {}", *r2);
|
|
|
}
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p><span class="caption">示例 20-3: 在 <code>unsafe</code> 块中解引用裸指针</span></p>
|
|
|
<p>创建一个指针不会造成任何危害;只有当访问其指向的值时才有可能遇到无效的值。</p>
|
|
|
<p>还需注意示例 20-1 和 20-3 中创建了同时指向相同内存位置 <code>num</code> 的裸指针 <code>*const i32</code> 和 <code>*mut i32</code>。相反如果尝试同时创建 <code>num</code> 的不可变和可变引用,代码将无法通过编译,因为 Rust 的所有权规则不允许在拥有任何不可变引用的同时再创建可变引用。通过裸指针,就能够同时创建同一地址的可变指针和不可变指针,若通过可变指针修改数据,则可能造成潜在数据竞争。请多加小心!</p>
|
|
|
<p>既然存在这么多的危险,为何还要使用裸指针呢?一个主要的应用场景便是调用 C 代码接口,这在下一部分 <a href="#调用不安全函数或方法">“调用不安全函数或方法”</a> 中会讲到。另一个场景是构建借用检查器无法理解的安全抽象。让我们先介绍不安全函数,接着看一看使用不安全代码的安全抽象的示例。</p>
|
|
|
<h3 id="调用不安全函数或方法"><a class="header" href="#调用不安全函数或方法">调用不安全函数或方法</a></h3>
|
|
|
<p>第二类可以在不安全块中进行的操作是调用不安全函数。不安全函数和方法与常规函数方法十分类似,除了其开头有一个额外的 <code>unsafe</code>。在此上下文中,关键字 <code>unsafe</code> 表示该函数具有调用时需要满足的要求,而 Rust 不会保证满足这些要求。通过在 <code>unsafe</code> 块中调用不安全函数,表明我们已经阅读过此函数的文档并对其是否满足函数自身的契约负责。</p>
|
|
|
<p>如下是一个没有做任何操作的不安全函数 <code>dangerous</code> 的例子:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
|
|
</span> unsafe fn dangerous() {}
|
|
|
|
|
|
unsafe {
|
|
|
dangerous();
|
|
|
}
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p>必须在一个单独的 <code>unsafe</code> 块中调用 <code>dangerous</code> 函数。如果尝试不使用 <code>unsafe</code> 块调用 <code>dangerous</code>,则会得到一个错误:</p>
|
|
|
<pre><code class="language-console">$ cargo run
|
|
|
Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)
|
|
|
error[E0133]: call to unsafe function `dangerous` is unsafe and requires unsafe block
|
|
|
--> src/main.rs:4:5
|
|
|
|
|
|
|
4 | dangerous();
|
|
|
| ^^^^^^^^^^^ call to unsafe function
|
|
|
|
|
|
|
= note: consult the function's documentation for information on how to avoid undefined behavior
|
|
|
|
|
|
For more information about this error, try `rustc --explain E0133`.
|
|
|
error: could not compile `unsafe-example` (bin "unsafe-example") due to 1 previous error
|
|
|
</code></pre>
|
|
|
<p>通过 <code>unsafe</code> 块,我们向 Rust 断言我们已经阅读过函数的文档,理解如何正确使用它,并核实我们履行了该函数的契约。</p>
|
|
|
<p>在不安全函数的函数体内部执行不安全操作时,同样需要使用 <code>unsafe</code> 块,就像在普通函数中一样,如果忘记了编译器会发出警告(warning)。这有助于将 <code>unsafe</code> 块保持得尽可能小,因为 <code>unsafe</code> 操作并不一定需要覆盖整个函数体。</p>
|
|
|
<blockquote>
|
|
|
<p>译注:不安全函数体也是有效的 <code>unsafe</code> 块,所以在不安全函数中进行另一个不安全操作时可以不新增额外的 <code>unsafe</code> 块,但从 2024 edition 开始,<code>#[warn(unsafe_op_in_unsafe_fn)]</code> 是默认开启的,所以此时会产生警告(warning)。参考 <a href="https://rust-lang.github.io/rfcs/2585-unsafe-block-in-unsafe-fn.html">RFC 2585</a>,出于尽量缩小 <code>unsafe</code> 块的动机,不再建议在不安全函数体中直接进行不安全操作,因为未来可能将这种行为视为错误(error)。</p>
|
|
|
</blockquote>
|
|
|
<h4 id="创建不安全代码的安全抽象"><a class="header" href="#创建不安全代码的安全抽象">创建不安全代码的安全抽象</a></h4>
|
|
|
<p>仅仅因为函数包含不安全代码并不意味着整个函数都需要标记为不安全的。事实上,将不安全代码封装进安全函数是一种常见的抽象方式。作为一个例子,了解一下标准库中的函数 <code>split_at_mut</code>,它需要一些不安全代码,让我们探索可以如何实现它。这个安全函数定义于可变 slice 之上:它获取一个 slice 并从给定的索引参数开始将其分割为两个 slice。示例 20-4 展示了如何使用 <code>split_at_mut</code>。</p>
|
|
|
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
|
|
</span> let mut v = vec![1, 2, 3, 4, 5, 6];
|
|
|
|
|
|
let r = &mut v[..];
|
|
|
|
|
|
let (a, b) = r.split_at_mut(3);
|
|
|
|
|
|
assert_eq!(a, &mut [1, 2, 3]);
|
|
|
assert_eq!(b, &mut [4, 5, 6]);
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p><span class="caption">示例 20-4: 使用安全的 <code>split_at_mut</code> 函数</span></p>
|
|
|
<p>这个函数无法只通过安全 Rust 实现。一个尝试可能看起来像示例 20-5,它不能编译。出于简单考虑,我们将 <code>split_at_mut</code> 实现为函数而不是方法,并只处理 <code>i32</code> 值而非泛型 <code>T</code> 的 slice。</p>
|
|
|
<pre><code class="language-rust ignore does_not_compile">fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
|
|
|
let len = values.len();
|
|
|
|
|
|
assert!(mid <= len);
|
|
|
|
|
|
(&mut values[..mid], &mut values[mid..])
|
|
|
}
|
|
|
<span class="boring">
|
|
|
</span><span class="boring">fn main() {
|
|
|
</span><span class="boring"> let mut vector = vec![1, 2, 3, 4, 5, 6];
|
|
|
</span><span class="boring"> let (left, right) = split_at_mut(&mut vector, 3);
|
|
|
</span><span class="boring">}</span></code></pre>
|
|
|
<p><span class="caption">示例 20-5: 尝试只使用安全 Rust 来实现 <code>split_at_mut</code></span></p>
|
|
|
<p>此函数首先获取 slice 的长度,然后通过检查参数是否小于或等于这个长度来断言参数所给定的索引位于 slice 当中。该断言意味着如果传入的索引比要分割的 slice 的索引更大,此函数在尝试使用这个索引前 panic。</p>
|
|
|
<p>之后我们在一个元组中返回两个可变的 slice:一个从原始 slice 的开头直到 <code>mid</code> 索引,另一个从 <code>mid</code> 直到原 slice 的结尾。</p>
|
|
|
<p>如果尝试编译示例 20-5 的代码,会得到一个错误:</p>
|
|
|
<pre><code class="language-console">$ cargo run
|
|
|
Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)
|
|
|
error[E0499]: cannot borrow `*values` as mutable more than once at a time
|
|
|
--> src/main.rs:6:31
|
|
|
|
|
|
|
1 | fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
|
|
|
| - let's call the lifetime of this reference `'1`
|
|
|
...
|
|
|
6 | (&mut values[..mid], &mut values[mid..])
|
|
|
| --------------------------^^^^^^--------
|
|
|
| | | |
|
|
|
| | | second mutable borrow occurs here
|
|
|
| | first mutable borrow occurs here
|
|
|
| returning this value requires that `*values` is borrowed for `'1`
|
|
|
|
|
|
|
= help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices
|
|
|
|
|
|
For more information about this error, try `rustc --explain E0499`.
|
|
|
error: could not compile `unsafe-example` (bin "unsafe-example") due to 1 previous error
|
|
|
</code></pre>
|
|
|
<p>Rust 的借用检查器无法理解我们要借用这个 slice 的两个不同部分:它只知道我们借用了同一个 slice 两次。本质上借用 slice 的不同部分是可以的,因为这两段 slice 不会重叠,不过 Rust 还没有智能到能够理解这些。当我们知道某些事是可以的而 Rust 不知道的时候,就是触及不安全代码的时候了</p>
|
|
|
<p>示例 20-6 展示了如何使用 <code>unsafe</code> 块,裸指针和一些不安全函数调用来实现 <code>split_at_mut</code>:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2024">use std::slice;
|
|
|
|
|
|
fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
|
|
|
let len = values.len();
|
|
|
let ptr = values.as_mut_ptr();
|
|
|
|
|
|
assert!(mid <= len);
|
|
|
|
|
|
unsafe {
|
|
|
(
|
|
|
slice::from_raw_parts_mut(ptr, mid),
|
|
|
slice::from_raw_parts_mut(ptr.add(mid), len - mid),
|
|
|
)
|
|
|
}
|
|
|
}
|
|
|
<span class="boring">
|
|
|
</span><span class="boring">fn main() {
|
|
|
</span><span class="boring"> let mut vector = vec![1, 2, 3, 4, 5, 6];
|
|
|
</span><span class="boring"> let (left, right) = split_at_mut(&mut vector, 3);
|
|
|
</span><span class="boring">}</span></code></pre>
|
|
|
<p><span class="caption">示例 20-6: 在 <code>split_at_mut</code> 函数的实现中使用不安全代码</span></p>
|
|
|
<p>回忆第四章的<a href="ch04-03-slices.html#slice-类型">“Slice 类型” </a>部分,slice 是一个指向一些数据的指针,并带有该 slice 的长度。可以使用 <code>len</code> 方法获取 slice 的长度,使用 <code>as_mut_ptr</code> 方法访问 slice 的裸指针。在这个例子中,因为有一个 <code>i32</code> 值的可变 slice,<code>as_mut_ptr</code> 返回一个 <code>*mut i32</code> 类型的裸指针,并将其存储在 <code>ptr</code> 变量中。</p>
|
|
|
<p>我们保持索引 <code>mid</code> 位于 slice 中的断言。接着是不安全代码:<code>slice::from_raw_parts_mut</code> 函数获取一个裸指针和一个长度来创建一个 slice。这里使用此函数从 <code>ptr</code> 中创建了一个有 <code>mid</code> 个项的 slice。之后在 <code>ptr</code> 上调用 <code>add</code> 方法并使用 <code>mid</code> 作为参数来获取一个从 <code>mid</code> 开始的裸指针,使用这个裸指针并以 <code>mid</code> 之后项的数量为长度创建另一个 slice。</p>
|
|
|
<p><code>slice::from_raw_parts_mut</code> 函数是不安全的因为它获取一个裸指针,并必须确信这个指针是有效的。裸指针上的 <code>add</code> 方法也是不安全的,因为其必须确信此地址偏移量也是有效的指针。因此必须将 <code>slice::from_raw_parts_mut</code> 和 <code>add</code> 放入 <code>unsafe</code> 块中以便能调用它们。通过观察代码,和增加 <code>mid</code> 必然小于等于 <code>len</code> 的断言,我们可以说 <code>unsafe</code> 块中所有的裸指针将是有效的 slice 中数据的指针。这是一个可以接受的 <code>unsafe</code> 的恰当用法。</p>
|
|
|
<p>注意无需将 <code>split_at_mut</code> 函数的结果标记为 <code>unsafe</code>,并可以在安全 Rust 中调用此函数。我们创建了一个不安全代码的安全抽象,其代码以一种安全的方式使用了 <code>unsafe</code> 代码,因为其只从这个函数访问的数据中创建了有效的指针。</p>
|
|
|
<p>与此相对,示例 20-7 中的 <code>slice::from_raw_parts_mut</code> 在使用 slice 时很有可能会崩溃。这段代码获取任意内存地址并创建了一个长度为一万的 slice:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
|
|
</span> use std::slice;
|
|
|
|
|
|
let address = 0x01234usize;
|
|
|
let r = address as *mut i32;
|
|
|
|
|
|
let values: &[i32] = unsafe { slice::from_raw_parts_mut(r, 10000) };
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p><span class="caption">示例 20-7: 通过任意内存地址创建 slice</span></p>
|
|
|
<p>我们并不拥有这个任意地址的内存,也不能保证这段代码创建的 slice 包含有效的 <code>i32</code> 值。试图使用臆测为有效的 <code>values</code> 会导致未定义的行为。</p>
|
|
|
<h4 id="使用-extern-函数调用外部代码"><a class="header" href="#使用-extern-函数调用外部代码">使用 <code>extern</code> 函数调用外部代码</a></h4>
|
|
|
<p>有时你的 Rust 代码可能需要与其他语言编写的代码交互。为此 Rust 有一个关键字,<code>extern</code>,有助于创建和使用 <strong>外部函数接口</strong>(<em>Foreign Function Interface</em>,FFI)。外部函数接口是一个编程语言用以定义函数的方式,其允许不同(外部)编程语言调用这些函数。</p>
|
|
|
<p>示例 20-8 展示了如何集成 C 标准库中的 <code>abs</code> 函数。<code>extern</code> 块中声明的函数在 Rust 代码中通常是不安全的因此 <code>extern</code> 块本身也必须标注 <code>unsafe</code>。之所以如此,是因为其他语言不会强制执行 Rust 的规则,Rust 也无法检查这些约束,因此程序员有责任确保调用的安全性。</p>
|
|
|
<p><span class="filename">文件名:src/main.rs</span></p>
|
|
|
<pre class="playground"><code class="language-rust edition2024">unsafe extern "C" {
|
|
|
fn abs(input: i32) -> i32;
|
|
|
}
|
|
|
|
|
|
fn main() {
|
|
|
unsafe {
|
|
|
println!("Absolute value of -3 according to C: {}", abs(-3));
|
|
|
}
|
|
|
}</code></pre>
|
|
|
<p><span class="caption">示例 20-8: 声明并调用另一个语言中定义的 <code>extern</code> 函数</span></p>
|
|
|
<p>在 <code>unsafe extern "C"</code> 块中,我们列出了希望能够调用的另一个语言中的外部函数的签名和名称。<code>"C"</code> 部分定义了外部函数所使用的 <strong>应用二进制接口</strong>(<em>application binary interface</em>,ABI) —— ABI 定义了如何在汇编语言层面调用此函数。<code>"C"</code> ABI 是最常见的,并遵循 C 编程语言的 ABI。有关 Rust 支持的所有 ABI 的信息请参见 <a href="https://doc.rust-lang.org/reference/items/external-blocks.html#abi">the Rust Reference</a>。</p>
|
|
|
<p><code>unsafe extern</code> 中声明的任何项都隐式地是 <code>unsafe</code> 的。然而,一些 FFI 函数<strong>可以</strong>安全地调用。例如,C 标准库中的 <code>abs</code> 函数没有任何内存安全方面的考量并且我们知道它可以使用任何 <code>i32</code> 调用。在类似这样的例子中,我们可以使用 <code>safe</code> 关键字来表明这个特定的函数即便是在 <code>unsafe extern</code> 块中也是可以安全调用的。一旦我们做出这个修改,调用它不再需要 <code>unsafe</code> 块,如示例 20-9 所示。</p>
|
|
|
<figure class="listing">
|
|
|
<p><span class="file-name">文件名:src/main.rs</span></p>
|
|
|
<pre class="playground"><code class="language-rust edition2024">unsafe extern "C" {
|
|
|
safe fn abs(input: i32) -> i32;
|
|
|
}
|
|
|
|
|
|
fn main() {
|
|
|
println!("Absolute value of -3 according to C: {}", abs(-3));
|
|
|
}</code></pre>
|
|
|
<figcaption>示例 20-9:在 `unsafe extern` 块中显式地标记一个函数为 `safe` 并安全地调用它</figcaption>
|
|
|
</figure>
|
|
|
<p>将一个函数标记为 <code>safe</code> 并不会固有地使其变得安全!相反,这像是一个对 Rust 的承诺表明它<strong>是</strong>安全的。确保履行这个承诺仍然是你的责任!</p>
|
|
|
<blockquote>
|
|
|
<h4 id="从其它语言调用-rust-函数"><a class="header" href="#从其它语言调用-rust-函数">从其它语言调用 Rust 函数</a></h4>
|
|
|
<p>也可以使用 <code>extern</code> 来创建一个允许其它语言调用 Rust 函数的接口。不同于创建整个 <code>extern</code> 块,就在 <code>fn</code> 关键字之前增加 <code>extern</code> 关键字并为相关函数指定所用到的 ABI。还需增加 <code>#[no_mangle]</code> 注解来告诉 Rust 编译器不要 mangle 此函数的名称。<em>Mangling</em> 指编译器将我们命名的函数名更改为包含更多供其他编译过程使用的信息的名称,不过可读性较差。每一个编程语言的编译器都会以稍微不同的方式 mangle 函数名,所以为了使 Rust 函数能在其他语言中指定,必须禁用 Rust 编译器的 name mangling。这是不安全的因为在没有内置 mangling 的时候在库之间可能有命名冲突,所以确保所选的名称可以不用 mangling 地安全导出是我们的责任。</p>
|
|
|
<p>在如下的例子中,一旦其编译为动态库并从 C 语言中链接,<code>call_from_c</code> 函数就能够在 C 代码中访问:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
|
|
|
</span><span class="boring">fn main() {
|
|
|
</span>#[unsafe(no_mangle)]
|
|
|
pub extern "C" fn call_from_c() {
|
|
|
println!("Just called a Rust function from C!");
|
|
|
}
|
|
|
<span class="boring">}</span></code></pre>
|
|
|
<p>这种 <code>extern</code> 用法只在属性中需要 <code>unsafe</code>,而不需要在 <code>extern</code> 块本身使用 <code>unsafe</code>。</p>
|
|
|
</blockquote>
|
|
|
<h3 id="访问或修改可变静态变量"><a class="header" href="#访问或修改可变静态变量">访问或修改可变静态变量</a></h3>
|
|
|
<p>在本书中,我们尚未讨论过 <strong>全局变量</strong>(<em>global variables</em>),Rust 确实支持它们,不过这对于 Rust 的所有权规则来说是有问题的。如果有两个线程访问相同的可变全局变量,则可能会造成数据竞争。</p>
|
|
|
<p>全局变量在 Rust 中被称为 <strong>静态</strong>(<em>static</em>)变量。示例 20-10 展示了一个拥有字符串 slice 值的静态变量的声明和使用:</p>
|
|
|
<p><span class="filename">文件名:src/main.rs</span></p>
|
|
|
<pre class="playground"><code class="language-rust edition2024">static HELLO_WORLD: &str = "Hello, world!";
|
|
|
|
|
|
fn main() {
|
|
|
println!("name is: {HELLO_WORLD}");
|
|
|
}</code></pre>
|
|
|
<p><span class="caption">示例 20-10: 定义和使用一个不可变静态变量</span></p>
|
|
|
<p>静态(<code>static</code>)变量类似于第三章 <a href="ch03-01-variables-and-mutability.html#常量">“变量和常量的区别”</a> 部分讨论的常量。通常静态变量的名称采用 <code>SCREAMING_SNAKE_CASE</code> 写法。静态变量只能储存拥有 <code>'static</code> 生命周期的引用,这意味着 Rust 编译器可以自己计算出其生命周期而无需显式标注。访问不可变静态变量是安全的。</p>
|
|
|
<p>常量与不可变静态变量的一个微妙的区别是静态变量中的值有一个固定的内存地址。使用这个值总是会访问相同的地址。另一方面,常量则允许在任何被用到的时候复制其数据。另一个区别在于静态变量可以是可变的。访问和修改可变静态变量都是 <strong>不安全</strong> 的。示例 20-11 展示了如何声明、访问和修改名为 <code>COUNTER</code> 的可变静态变量:</p>
|
|
|
<p><span class="filename">文件名:src/main.rs</span></p>
|
|
|
<pre class="playground"><code class="language-rust edition2024">static mut COUNTER: u32 = 0;
|
|
|
|
|
|
/// SAFETY: 同时在多个线程调用这个方法是未定义的行为,所以你*必须*保证同一时间只
|
|
|
/// 有一个线程在调用它。
|
|
|
unsafe fn add_to_count(inc: u32) {
|
|
|
unsafe {
|
|
|
COUNTER += inc;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
fn main() {
|
|
|
unsafe {
|
|
|
// SAFETY: 它只在 `main` 这一个线程被调用。
|
|
|
add_to_count(3);
|
|
|
println!("COUNTER: {}", *(&raw const COUNTER));
|
|
|
}
|
|
|
}</code></pre>
|
|
|
<p><span class="caption">示例 20-11: 读取或修改一个可变静态变量是不安全的</span></p>
|
|
|
<p>就像常规变量一样,我们使用 <code>mut</code> 关键字来指定可变性。任何读写 <code>COUNTER</code> 的代码都必须位于 <code>unsafe</code> 块中。这段代码可以编译并如期打印出 <code>COUNTER: 3</code>,因为这是单线程的。拥有多个线程访问 <code>COUNTER</code> 则可能导致数据竞争,所以这是未定义行为。因此,我们需要将整个函数标记为 <code>unsafe</code>,并在文档注释中说明其安全性限制,以便调用者明确哪些操作是安全的、哪些是不安全的。</p>
|
|
|
<p>每当我们编写一个不安全函数,惯常做法是编写一个以 <code>SAFETY</code> 开头的注释并解释调用者需要做什么才可以安全地调用该方法。同理,当我们进行不安全操作时,惯常做法是编写一个以 <code>SAFETY</code> 开头并解释安全性规则是如何维护的。</p>
|
|
|
<p>另外,编译器不会允许你创建一个可变静态变量的引用。你只能通过用裸指针解引用操作符创建的裸指针访问它。这包括引用的创建是不可见的情况,例如这个代码示例中用于 <code>println!</code> 的情况。可变静态变量只能通过裸指针创建的要求有助于确保使用它们的安全要求更为明确。</p>
|
|
|
<p>拥有可以全局访问的可变数据,难以保证不存在数据竞争,这就是为何 Rust 认为可变静态变量是不安全的。在任何可能的情况下,请优先使用第十六章讨论的并发技术和线程安全智能指针,这样编译器就能检测不同线程间的数据访问是否是安全的。</p>
|
|
|
<h3 id="实现不安全-trait"><a class="header" href="#实现不安全-trait">实现不安全 trait</a></h3>
|
|
|
<p>我们可以使用 <code>unsafe</code> 来实现一个不安全 trait。当 trait 中至少有一个方法中包含编译器无法验证的不变式(invariant)时该 trait 就是不安全的。可以在 <code>trait</code> 之前增加 <code>unsafe</code> 关键字将 trait 声明为 <code>unsafe</code>,同时 trait 的实现也必须标记为 <code>unsafe</code>,如示例 20-12 所示:</p>
|
|
|
<pre class="playground"><code class="language-rust edition2024">unsafe trait Foo {
|
|
|
// 方法在这里
|
|
|
}
|
|
|
|
|
|
unsafe impl Foo for i32 {
|
|
|
// 方法实现在这里
|
|
|
}
|
|
|
<span class="boring">
|
|
|
</span><span class="boring">fn main() {}</span></code></pre>
|
|
|
<p><span class="caption">示例 20-12: 定义并实现不安全 trait</span></p>
|
|
|
<p>通过 <code>unsafe impl</code>,我们承诺将保证编译器所不能验证的不变式。</p>
|
|
|
<p>作为一个例子,回忆第十六章 <a href="ch16-04-extensible-concurrency-sync-and-send.html#使用-send-和-sync-trait-的可扩展并发">“使用 <code>Sync</code> 和 <code>Send</code> trait 的可扩展并发”</a> 部分中的 <code>Sync</code> 和 <code>Send</code> 标记 trait:如果我们的类型完全由实现了 <code>Send</code> 与 <code>Sync</code> 的其他类型组成,编译器会自动为其实现这些 trait。如果我们定义的类型包含某些未实现 <code>Send</code> 或 <code>Sync</code> 的类型,例如裸指针,但又想将该类型标记为 <code>Send</code> 或 <code>Sync</code>,就必须使用 <code>unsafe</code>。Rust 不能验证我们的类型保证可以安全的跨线程发送或在多线程间访问,所以需要我们自己进行检查并通过 <code>unsafe</code> 表明。</p>
|
|
|
<h3 id="访问联合体中的字段"><a class="header" href="#访问联合体中的字段">访问联合体中的字段</a></h3>
|
|
|
<p>最后一个只能在 <code>unsafe</code> 块中执行的操作是访问(union)中的字段。<code>union</code> 和 <code>struct</code> 类似,但是在一个实例中同时只能使用一个已声明的字段。联合体主要用于和 C 代码中的联合体进行交互。访问联合体的字段是不安全的,因为 Rust 无法保证当前存储在联合体实例中数据的类型。可以查看 <a href="https://doc.rust-lang.org/reference/items/unions.html">the Rust Reference</a> 了解有关联合体的更多信息。</p>
|
|
|
<h3 id="使用-miri-检查不安全代码"><a class="header" href="#使用-miri-检查不安全代码">使用 miri 检查不安全代码</a></h3>
|
|
|
<p>当编写不安全代码时,你可能会想要检查编写的代码是否真的安全正确。最好的方式之一是使用 Miri,一个用来检测未定义行为的 Rust 官方工具。鉴于借用检查器是一个在编译时工作的<strong>静态</strong>工具,Miri 是一个在运行时工作的<strong>动态</strong>工具。它通过运行程序,或者测试集来检查代码,并检测你是否违反了它理解的 Rust 应该如何工作的规则。</p>
|
|
|
<p>使用 Miri 要求使用 nightly 版本的 Rust(我们在<a href="appendix-07-nightly-rust.html">附录 G:Rust 是如何开发的与 “Nightly Rust”</a>中有更多讨论)。你可以通过输入 <code>rustup +nightly component add miri</code> 来同时安装 nightly 版本的 Rust 和 Miri。这并不会改变你项目正在使用的 Rust 版本;它只是为你的系统增加了这个工具所以你可以在需要的时候使用它。你可以通过输入 <code>cargo +nightly miri run</code> or <code>cargo +nightly miri test</code> 在项目中使用 Miri。</p>
|
|
|
<p>作为一个它是如何有用的例子,考虑一下对示例 20-11 运行它时会发生什么。</p>
|
|
|
<pre><code class="language-console">$ cargo +nightly miri run
|
|
|
Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)
|
|
|
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
|
|
|
Running `/Users/chris/.rustup/toolchains/nightly-aarch64-apple-darwin/bin/cargo-miri runner target/miri/aarch64-apple-darwin/debug/unsafe-example`
|
|
|
warning: creating a shared reference to mutable static is discouraged
|
|
|
--> src/main.rs:14:33
|
|
|
|
|
|
|
14 | println!("COUNTER: {}", COUNTER);
|
|
|
| ^^^^^^^ shared reference to mutable static
|
|
|
|
|
|
|
= note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2024/static-mut-references.html>
|
|
|
= note: shared references to mutable statics are dangerous; it's undefined behavior if the static is mutated or if a mutable reference is created for it while the shared reference lives
|
|
|
= note: `#[warn(static_mut_refs)]` on by default
|
|
|
|
|
|
COUNTER: 3
|
|
|
|
|
|
</code></pre>
|
|
|
<p>Miri 正确地警告了我们共享了可变数据的引用。这里,Miri 只是发出了一个警告因为在这个例子中并不能保证是未定义行为,它也没有告诉我们如何修复问题。但是至少我们知道这里有未定义行为的风险并接着可以思考如何使代码变得安全。在一些例子中,Miri 也可以检测真正的错误 – <strong>确定</strong>是错误的代码模式 – 并提出如何修复这些错误的推荐方案。</p>
|
|
|
<p>Miri 并不能捕获编写不安全代码时可能出现的所有错误。Miri 是一个动态分析工具,因此它只能捕获代码实际运行时出现的问题。这意味着需要将其与良好的测试技术相结合以增强你对所编写的不安全代码的信心。Miri 也不能覆盖代码所有的不可靠的地方。</p>
|
|
|
<p>换句话说:如果 Miri <strong>可以</strong>捕获一个问题,你知道这里有个 bug,不过仅仅是因为 miri <strong>没有</strong>捕获一个 bug 并不意味着这里没有问题。但是它可以捕获很多问题。尝试对本章中的其它不安全代码示例运行它来看看它会说些什么!</p>
|
|
|
<p>你可以在 <a href="https://github.com/rust-lang/miri">Miri 的 GitHub 仓库</a>了解更多信息。</p>
|
|
|
<h3 id="何时使用不安全代码"><a class="header" href="#何时使用不安全代码">何时使用不安全代码</a></h3>
|
|
|
<p>使用 <code>unsafe</code> 来进行这五个操作(超能力)之一是没有问题的,甚至是不需要深思熟虑的,不过使得 <code>unsafe</code> 代码正确也实属不易,因为编译器不能帮助保证内存安全。当有理由使用 <code>unsafe</code> 代码时,是可以这么做的,通过使用显式的 <code>unsafe</code> 标注可以更容易地在错误发生时追踪问题的源头。每当编写不安全代码时,都可以借助 Miri 来更加自信地验证所写代码是否遵循 Rust 的规则。</p>
|
|
|
<p>若想更深入地了解如何高效使用不安全 Rust,请阅读 Rust 关于该主题的官方指南 <a href="https://doc.rust-lang.org/nomicon/">Rustonomicon</a>。</p>
|
|
|
|
|
|
</main>
|
|
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
<a rel="prev" href="ch20-00-advanced-features.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg></span>
|
|
|
</a>
|
|
|
|
|
|
<a rel="next prefetch" href="ch20-02-advanced-traits.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg></span>
|
|
|
</a>
|
|
|
|
|
|
<div style="clear: both"></div>
|
|
|
</nav>
|
|
|
</div>
|
|
|
</div>
|
|
|
|
|
|
<nav class="nav-wide-wrapper" aria-label="Page navigation">
|
|
|
<a rel="prev" href="ch20-00-advanced-features.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg></span>
|
|
|
</a>
|
|
|
|
|
|
<a rel="next prefetch" href="ch20-02-advanced-traits.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
|
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg></span>
|
|
|
</a>
|
|
|
</nav>
|
|
|
|
|
|
</div>
|
|
|
|
|
|
<template id=fa-eye><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M288 32c-80.8 0-145.5 36.8-192.6 80.6C48.6 156 17.3 208 2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6C17.3 304 48.6 356 95.4 399.4C142.5 443.2 207.2 480 288 480s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C433.5 68.8 368.8 32 288 32zM432 256c0 79.5-64.5 144-144 144s-144-64.5-144-144s64.5-144 144-144s144 64.5 144 144zM288 192c0 35.3-28.7 64-64 64c-11.5 0-22.3-3-31.6-8.4c-.2 2.8-.4 5.5-.4 8.4c0 53 43 96 96 96s96-43 96-96s-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6z"/></svg></span></template>
|
|
|
<template id=fa-eye-slash><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2S-1.2 34.7 9.2 42.9l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7L525.6 386.7c39.6-40.6 66.4-86.1 79.9-118.4c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C465.5 68.8 400.8 32 320 32c-68.2 0-125 26.3-169.3 60.8L38.8 5.1zM223.1 149.5C248.6 126.2 282.7 112 320 112c79.5 0 144 64.5 144 144c0 24.9-6.3 48.3-17.4 68.7L408 294.5c5.2-11.8 8-24.8 8-38.5c0-53-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6c0 10.2-2.4 19.8-6.6 28.3l-90.3-70.8zm223.1 298L373 389.9c-16.4 6.5-34.3 10.1-53 10.1c-79.5 0-144-64.5-144-144c0-6.9 .5-13.6 1.4-20.2L83.1 161.5C60.3 191.2 44 220.8 34.5 243.7c-3.3 7.9-3.3 16.7 0 24.6c14.9 35.7 46.2 87.7 93 131.1C174.5 443.2 239.2 480 320 480c47.8 0 89.9-12.9 126.2-32.5z"/></svg></span></template>
|
|
|
<template id=fa-copy><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"/></svg></span></template>
|
|
|
<template id=fa-play><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M73 39c-14.8-9.1-33.4-9.4-48.5-.9S0 62.6 0 80V432c0 17.4 9.4 33.4 24.5 41.9s33.7 8.1 48.5-.9L361 297c14.3-8.7 23-24.2 23-41s-8.7-32.2-23-41L73 39z"/></svg></span></template>
|
|
|
<template id=fa-clock-rotate-left><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M75 75L41 41C25.9 25.9 0 36.6 0 57.9V168c0 13.3 10.7 24 24 24H134.1c21.4 0 32.1-25.9 17-41l-30.8-30.8C155 85.5 203 64 256 64c106 0 192 86 192 192s-86 192-192 192c-40.8 0-78.6-12.7-109.7-34.4c-14.5-10.1-34.4-6.6-44.6 7.9s-6.6 34.4 7.9 44.6C151.2 495 201.7 512 256 512c141.4 0 256-114.6 256-256S397.4 0 256 0C185.3 0 121.3 28.7 75 75zm181 53c-13.3 0-24 10.7-24 24V256c0 6.4 2.5 12.5 7 17l72 72c9.4 9.4 24.6 9.4 33.9 0s9.4-24.6 0-33.9l-65-65V152c0-13.3-10.7-24-24-24z"/></svg></span></template>
|
|
|
|
|
|
|
|
|
|
|
|
<script>
|
|
|
window.playground_copyable = true;
|
|
|
</script>
|
|
|
|
|
|
|
|
|
<script src="elasticlunr-ef4e11c1.min.js"></script>
|
|
|
<script src="mark-09e88c2c.min.js"></script>
|
|
|
<script src="searcher-c2a407aa.js"></script>
|
|
|
|
|
|
<script src="clipboard-1626706a.min.js"></script>
|
|
|
<script src="highlight-abc7f01d.js"></script>
|
|
|
<script src="book-a0b12cfe.js"></script>
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
<script src="ferris-2317480c.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
</body>
|
|
|
</html>
|