1
1
% Unsafe
2
2
3
- <!--
4
- Rust’s main draw is its powerful static guarantees about behavior. But safety
5
- checks are conservative by nature: there are some programs that are actually
6
- safe, but the compiler is not able to verify this is true. To write these kinds
7
- of programs, we need to tell the compiler to relax its restrictions a bit. For
8
- this, Rust has a keyword, `unsafe`. Code using `unsafe` has less restrictions
9
- than normal code does.
10
- -->
3
+ <!-- Rust’s main draw is its powerful static guarantees about behavior. But safety -->
4
+ <!-- checks are conservative by nature: there are some programs that are actually -->
5
+ <!-- safe, but the compiler is not able to verify this is true. To write these kinds -->
6
+ <!-- of programs, we need to tell the compiler to relax its restrictions a bit. For -->
7
+ <!-- this, Rust has a keyword, `unsafe`. Code using `unsafe` has fewer restrictions -->
8
+ <!-- than normal code does. -->
11
9
Rustの主たる魅力は、プログラムの動作についての強力で静的な保証です。
12
10
しかしながら、安全性検査は本来保守的なものです。
13
11
すなわち、実際には安全なのに、そのことがコンパイラには検証できないプログラムがいくらか存在します。
14
12
その類のプログラムを書くためには、制約を少し緩和するようコンパイラに対して伝えることが要ります。
15
13
そのために、Rustには ` unsafe ` というキーワードがあります。
16
14
` unsafe ` を使ったコードは、普通のコードよりも制約が少なくなります。
17
15
18
- <!--
19
- Let’s go over the syntax, and then we’ll talk semantics. `unsafe` is used in
20
- four contexts. The first one is to mark a function as unsafe:
21
- -->
16
+ <!-- Let’s go over the syntax, and then we’ll talk semantics. `unsafe` is used in -->
17
+ <!-- four contexts. The first one is to mark a function as unsafe: -->
22
18
まずシンタックスをみて、それからセマンティクスについて話しましょう。
23
19
` unsafe ` は4つの場面で使われます。
24
20
1つめは、関数がアンセーフであることを印付ける場合です。
@@ -30,10 +26,8 @@ unsafe fn danger_will_robinson() {
30
26
}
31
27
```
32
28
33
- <!--
34
- All functions called from [FFI][ffi] must be marked as `unsafe`, for example.
35
- The second use of `unsafe` is an unsafe block:
36
- -->
29
+ <!-- All functions called from [FFI][ffi] must be marked as `unsafe`, for example. -->
30
+ <!-- The second use of `unsafe` is an unsafe block: -->
37
31
たとえば、[ FFI] [ ffi ] から呼び出されるすべての関数は` unsafe ` で印付けることが必要です。
38
32
` unsafe ` の2つめの用途は、アンセーフブロックです。
39
33
@@ -46,37 +40,33 @@ unsafe {
46
40
}
47
41
```
48
42
49
- <!-- The third is for unsafe traits:-->
43
+ <!-- The third is for unsafe traits: -->
50
44
3つめは、アンセーフトレイトです。
51
45
52
46
``` rust
53
47
unsafe trait Scary { }
54
48
```
55
49
56
- <!-- And the fourth is for `impl`ementing one of those traits:-->
50
+ <!-- And the fourth is for `impl`ementing one of those traits: -->
57
51
そして、4つめは、そのアンセーフトレイトを実装する場合です。
58
52
59
53
``` rust
60
54
# unsafe trait Scary { }
61
55
unsafe impl Scary for i32 {}
62
56
```
63
57
64
- <!--
65
- It’s important to be able to explicitly delineate code that may have bugs that
66
- cause big problems. If a Rust program segfaults, you can be sure it’s somewhere
67
- in the sections marked `unsafe`.
68
- -->
58
+ <!-- It’s important to be able to explicitly delineate code that may have bugs that -->
59
+ <!-- cause big problems. If a Rust program segfaults, you can be sure the cause is -->
60
+ <!-- related to something marked `unsafe`. -->
69
61
大きな問題を引き起こすバグがあるかもしれないコードを明示できるのは重要なことです。
70
62
もしRustのプログラムがセグメンテーション違反を起こしても、バグは ` unsafe ` で印付けられた区間のどこかにあると確信できます。
71
63
64
+ <!-- # What does ‘safe’ mean? -->
72
65
# 「安全」とはどういう意味か?
73
- <!-- # What does ‘safe’ mean?-->
74
66
75
- <!--
76
- Safe, in the context of Rust, means ‘doesn’t do anything unsafe’. It’s also
77
- important to know that there are certain behaviors that are probably not
78
- desirable in your code, but are expressly _not_ unsafe:
79
- -->
67
+ <!-- Safe, in the context of Rust, means ‘doesn’t do anything unsafe’. It’s also -->
68
+ <!-- important to know that there are certain behaviors that are probably not -->
69
+ <!-- desirable in your code, but are expressly _not_ unsafe: -->
80
70
Rustの文脈で、安全とは「どのようなアンセーフなこともしない」ことを意味します。
81
71
82
72
> 訳注:
@@ -86,63 +76,55 @@ Rustの文脈で、安全とは「どのようなアンセーフなこともし
86
76
87
77
知っておくべき重要なことに、たいていのコードにおいて望ましくないが、アンセーフ _ ではない_ とされている動作がいくらか存在するということがあります。
88
78
89
- <!--
90
- * Deadlocks
91
- * Leaks of memory or other resources
92
- * Exiting without calling destructors
93
- * Integer overflow
94
- -->
79
+ <!-- * Deadlocks -->
80
+ <!-- * Leaks of memory or other resources -->
81
+ <!-- * Exiting without calling destructors -->
82
+ <!-- * Integer overflow -->
95
83
* デッドロック
96
84
* メモリやその他のリソースのリーク
97
85
* デストラクタを呼び出さないプログラム終了
98
86
* 整数オーバーフロー
99
87
100
- <!--
101
- Rust cannot prevent all kinds of software problems. Buggy code can and will be
102
- written in Rust. These things aren’t great, but they don’t qualify as `unsafe`
103
- specifically.
104
- -->
88
+ <!-- Rust cannot prevent all kinds of software problems. Buggy code can and will be -->
89
+ <!-- written in Rust. These things aren’t great, but they don’t qualify as `unsafe` -->
90
+ <!-- specifically. -->
105
91
Rustはソフトウェアが抱えるすべての種類の問題を防げるわけではありません。
106
92
Rustでバグのあるコードを書くことはできますし、実際に書かれるでしょう。
107
93
これらの動作は良いことではありませんが、特にアンセーフだとは見なされません。
108
94
109
- <!--
110
- In addition, the following are all undefined behaviors in Rust, and must be
111
- avoided, even when writing `unsafe` code:
112
- -->
95
+ <!-- In addition, the following are all undefined behaviors in Rust, and must be -->
96
+ <!-- avoided, even when writing `unsafe` code: -->
113
97
さらに、Rustにおいては、次のものは未定義動作で、 ` unsafe ` コード中であっても、避ける必要があります。
114
98
115
99
> 訳注:
116
- 関数に付いている` unsafe ` は「その関数の処理はアンセーフである」ということを表します。
117
- その一方で、ブロックに付いている` unsafe ` は「ブロック中の個々の操作はアンセーフだが、全体としては安全な処理である」ということを表します。
118
- 避ける必要があるのは、未定義動作が起こりうる処理をアンセーフブロックの中に書くことです。
119
- それは、アンセーフブロックの処理が安全であるために、その内部で未定義動作が決して起こらないことが必要だからです。
120
- アンセーフ関数には安全性の保証が要らないので、未定義動作が起こりうるアンセーフ関数を定義することに問題はありません。
121
-
122
- <!--
123
- * Data races
124
- * Dereferencing a null/dangling raw pointer
125
- * Reads of [undef][undef] (uninitialized) memory
126
- * Breaking the [pointer aliasing rules][aliasing] with raw pointers.
127
- * `&mut T` and `&T` follow LLVM’s scoped [noalias][noalias] model, except if
128
- the `&T` contains an `UnsafeCell<U>`. Unsafe code must not violate these
129
- aliasing guarantees.
130
- * Mutating an immutable value/reference without `UnsafeCell<U>`
131
- * Invoking undefined behavior via compiler intrinsics:
132
- * Indexing outside of the bounds of an object with `std::ptr::offset`
133
- (`offset` intrinsic), with
134
- the exception of one byte past the end which is permitted.
135
- * Using `std::ptr::copy_nonoverlapping_memory` (`memcpy32`/`memcpy64`
136
- intrinsics) on overlapping buffers
137
- * Invalid values in primitive types, even in private fields/locals:
138
- * Null/dangling references or boxes
139
- * A value other than `false` (0) or `true` (1) in a `bool`
140
- * A discriminant in an `enum` not included in its type definition
141
- * A value in a `char` which is a surrogate or above `char::MAX`
142
- * Non-UTF-8 byte sequences in a `str`
143
- * Unwinding into Rust from foreign code or unwinding from Rust into foreign
144
- code.
145
- -->
100
+ > 関数に付いている` unsafe ` は「その関数の処理はアンセーフである」ということを表します。
101
+ > その一方で、ブロックに付いている` unsafe ` は「ブロック中の個々の操作はアンセーフだが、全体としては安全な処理である」ということを表します。
102
+ > 避ける必要があるのは、未定義動作が起こりうる処理をアンセーフブロックの中に書くことです。
103
+ > それは、アンセーフブロックの処理が安全であるために、その内部で未定義動作が決して起こらないことが必要だからです。
104
+ > アンセーフ関数には安全性の保証が要らないので、未定義動作が起こりうるアンセーフ関数を定義することに問題はありません。
105
+
106
+ <!-- * Data races -->
107
+ <!-- * Dereferencing a null/dangling raw pointer -->
108
+ <!-- * Reads of [undef][undef] (uninitialized) memory -->
109
+ <!-- * Breaking the [pointer aliasing rules][aliasing] with raw pointers. -->
110
+ <!-- * `&mut T` and `&T` follow LLVM’s scoped [noalias][noalias] model, except if -->
111
+ <!-- the `&T` contains an `UnsafeCell<U>`. Unsafe code must not violate these -->
112
+ <!-- aliasing guarantees. -->
113
+ <!-- * Mutating an immutable value/reference without `UnsafeCell<U>` -->
114
+ <!-- * Invoking undefined behavior via compiler intrinsics: -->
115
+ <!-- * Indexing outside of the bounds of an object with `std::ptr::offset` -->
116
+ <!-- (`offset` intrinsic), with -->
117
+ <!-- the exception of one byte past the end which is permitted. -->
118
+ <!-- * Using `std::ptr::copy_nonoverlapping_memory` (`memcpy32`/`memcpy64` -->
119
+ <!-- intrinsics) on overlapping buffers -->
120
+ <!-- * Invalid values in primitive types, even in private fields/locals: -->
121
+ <!-- * Null/dangling references or boxes -->
122
+ <!-- * A value other than `false` (0) or `true` (1) in a `bool` -->
123
+ <!-- * A discriminant in an `enum` not included in its type definition -->
124
+ <!-- * A value in a `char` which is a surrogate or above `char::MAX` -->
125
+ <!-- * Non-UTF-8 byte sequences in a `str` -->
126
+ <!-- * Unwinding into Rust from foreign code or unwinding from Rust into foreign -->
127
+ <!-- code. -->
146
128
* データ競合
147
129
* ヌル・ダングリング生ポインタの参照外し
148
130
* [ undef] [ undef ] (未初期化)メモリの読み出し
@@ -165,100 +147,80 @@ avoided, even when writing `unsafe` code:
165
147
[ undef ] : http://llvm.org/docs/LangRef.html#undefined-values
166
148
[ aliasing ] : http://llvm.org/docs/LangRef.html#pointer-aliasing-rules
167
149
150
+ <!-- # Unsafe Superpowers -->
168
151
# アンセーフの能力
169
- <!-- # Unsafe Superpowers-->
170
152
171
- <!--
172
- In both unsafe functions and unsafe blocks, Rust will let you do three things
173
- that you normally can not do. Just three. Here they are:
174
- -->
153
+ <!-- In both unsafe functions and unsafe blocks, Rust will let you do three things -->
154
+ <!-- that you normally can not do. Just three. Here they are: -->
175
155
アンセーフ関数・アンセーフブロックでは、Rustは普段できない3つのことをさせてくれます。たった3つです。それは、
176
156
177
- <!--
178
- 1. Access or update a [static mutable variable][static].
179
- 2. Dereference a raw pointer.
180
- 3. Call unsafe functions. This is the most powerful ability.
181
- -->
157
+ <!-- 1. Access or update a [static mutable variable][static]. -->
158
+ <!-- 2. Dereference a raw pointer. -->
159
+ <!-- 3. Call unsafe functions. This is the most powerful ability. -->
182
160
1 . [ 静的ミュータブル変数] [ static ] のアクセスとアップデート。
183
161
2 . 生ポインタの参照外し。
184
162
3 . アンセーフ関数の呼び出し。これが最も強力な能力です。
185
163
186
- <!--
187
- That’s it. It’s important that `unsafe` does not, for example, ‘turn off the
188
- borrow checker’. Adding `unsafe` to some random Rust code doesn’t change its
189
- semantics, it won’t just start accepting anything. But it will let you write
190
- things that _do_ break some of the rules.
191
- -->
164
+ <!-- That’s it. It’s important that `unsafe` does not, for example, ‘turn off the -->
165
+ <!-- borrow checker’. Adding `unsafe` to some random Rust code doesn’t change its -->
166
+ <!-- semantics, it won’t start accepting anything. But it will let you write -->
167
+ <!-- things that _do_ break some of the rules. -->
192
168
以上です。
193
169
重要なのは、 ` unsafe ` が、たとえば「借用チェッカをオフにする」といったことを行わないことです。
194
- Rustのコードの適当な位置に ` unsafe ` を加えてもセマンティクスは変わらず、何でもただ受理するようになるということにはなりません 。
170
+ Rustのコードの適当な位置に ` unsafe ` を加えてもセマンティクスは変わらず、何でも受理するようになるということにはなりません 。
195
171
それでも、` unsafe ` はルールのいくつかを破るコードを書けるようにはするのです。
196
172
197
- <!--
198
- You will also encounter the `unsafe` keyword when writing bindings to foreign
199
- (non-Rust) interfaces. You're encouraged to write a safe, native Rust interface
200
- around the methods provided by the library.
201
- -->
173
+ <!-- You will also encounter the `unsafe` keyword when writing bindings to foreign -->
174
+ <!-- (non-Rust) interfaces. You're encouraged to write a safe, native Rust interface -->
175
+ <!-- around the methods provided by the library. -->
202
176
また、` unsafe ` キーワードは、Rust以外の言語とのインターフェースを書くときに遭遇するでしょう。
203
177
ライブラリの提供するメソッドの周りに、安全な、Rustネイティブのインターフェースを書くことが推奨されています。
204
178
205
- <!--
206
- Let’s go over the basic three abilities listed, in order.
207
- -->
179
+ <!-- Let’s go over the basic three abilities listed, in order. -->
208
180
これから、その基本的な3つの能力を順番に見ていきましょう。
209
181
182
+ <!-- ## Access or update a `static mut` -->
210
183
## ` static mut ` のアクセスとアップデート。
211
- <!-- ## Access or update a `static mut`-->
212
184
213
- <!--
214
- Rust has a feature called ‘`static mut`’ which allows for mutable global state.
215
- Doing so can cause a data race, and as such is inherently not safe. For more
216
- details, see the [static][static] section of the book.
217
- -->
185
+ <!-- Rust has a feature called ‘`static mut`’ which allows for mutable global state. -->
186
+ <!-- Doing so can cause a data race, and as such is inherently not safe. For more -->
187
+ <!-- details, see the [static][static] section of the book. -->
218
188
Rustには「` static mut ` 」という、ミュータブルでグローバルな状態を実現する機能があります。
219
189
これを使うことはデータレースが起こるおそれがあるので、本質的に安全ではありません。
220
190
詳細は、この本の[ static] [ static ] セクションを参照してください。
221
191
222
192
[ static ] : const-and-static.html#static
223
193
194
+ <!-- ## Dereference a raw pointer -->
224
195
## 生ポインタの参照外し
225
- <!-- ## Dereference a raw pointer-->
226
-
227
- <!--
228
- Raw pointers let you do arbitrary pointer arithmetic, and can cause a number of
229
- different memory safety and security issues. In some senses, the ability to
230
- dereference an arbitrary pointer is one of the most dangerous things you can
231
- do. For more on raw pointers, see [their section of the book][rawpointers].
232
- -->
196
+
197
+ <!-- Raw pointers let you do arbitrary pointer arithmetic, and can cause a number of -->
198
+ <!-- different memory safety and security issues. In some senses, the ability to -->
199
+ <!-- dereference an arbitrary pointer is one of the most dangerous things you can -->
200
+ <!-- do. For more on raw pointers, see [their section of the book][rawpointers]. -->
233
201
生ポインタによって任意のポインタ演算が可能になりますが、いくつもの異なるメモリ安全とセキュリティの問題が起こるおそれがあります。
234
202
ある意味で、任意のポインタを参照外しする能力は行いうる操作のうち最も危険なもののひとつです。
235
203
詳細は、[ この本の生ポインタに関するセクション] [ rawpointers ] を参照してください。
236
204
237
205
[ rawpointers ] : raw-pointers.html
238
206
207
+ <!-- ## Call unsafe functions -->
239
208
## アンセーフ関数の呼び出し
240
- <!-- ## Call unsafe functions-->
241
209
242
- <!--
243
- This last ability works with both aspects of `unsafe`: you can only call
244
- functions marked `unsafe` from inside an unsafe block.
245
- -->
210
+ <!-- This last ability works with both aspects of `unsafe`: you can only call -->
211
+ <!-- functions marked `unsafe` from inside an unsafe block. -->
246
212
この最後の能力は、` unsafe ` の両面とともに働きます。
247
213
すなわち、` unsafe ` で印付けられた関数は、アンセーフブロックの内部からのみ呼び出すことができます。
248
214
249
- <!--
250
- This ability is powerful and varied. Rust exposes some [compiler
251
- intrinsics][intrinsics] as unsafe functions, and some unsafe functions bypass
252
- safety checks, trading safety for speed.
253
- -->
215
+ <!-- This ability is powerful and varied. Rust exposes some [compiler -->
216
+ <!-- intrinsics][intrinsics] as unsafe functions, and some unsafe functions bypass -->
217
+ <!-- safety checks, trading safety for speed. -->
254
218
この能力は強力で多彩です。
255
219
Rustはいくらかの[ compiler intrinsics] [ intrinsics ] をアンセーフ関数として公開しており、また、いくつかのアンセーフ関数は安全性検査を回避することで、安全性とスピードを引き換えています。
256
220
257
- <!--
258
- I’ll repeat again: even though you _can_ do arbitrary things in unsafe blocks
259
- and functions doesn’t mean you should. The compiler will act as though you’re
260
- upholding its invariants, so be careful!
261
- -->
221
+ <!-- I’ll repeat again: even though you _can_ do arbitrary things in unsafe blocks -->
222
+ <!-- and functions doesn’t mean you should. The compiler will act as though you’re -->
223
+ <!-- upholding its invariants, so be careful! -->
262
224
繰り返しになりますが、アンセーフブロックと関数の内部で任意のことが _ できる_ としても、それをすべきだということを意味しません。コンパイラは、あなたが不変量を守っているかのように動作しますから、注意してください!
263
225
264
226
[ intrinsics ] : intrinsics.html
0 commit comments