# Rust 1.9

Rust 1.9 發布於 2016-05-26，目前最新修補版為 `1.9.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.9 最大的改變是穩定了 `std::panic` 模組：`catch_unwind` 可以在執行緒內攔下 panic 的堆疊回溯（unwinding），讓 Rust 程式碼安全地透過 C API 對外提供，或讓執行緒池在工作 panic 時不必整個掛掉。函式庫作者也能用 `#[deprecated]` 屬性標記棄用的 API，使用者呼叫時會收到警告。升級要注意：`fn` 項目型別改為零大小且每個函式各自一個型別，對 `fn` 做 `transmute` 會先出現警告、之後變成錯誤；`Once` 的初始化函式失敗時會進入中毒（poisoned）狀態。

### 語言變更

- `#[deprecated]` 屬性讓 API 被使用時產生警告，可以用 `#[allow(deprecated)]` 關閉，詳見 [棄用 API](/deprecations)。
- `fn` 項目型別改為零大小，每個 `fn` 都是獨一無二的型別，詳見 [函式](/basics-functions)。
- 欄位與方法解析會考慮可見性，私有欄位與方法不會擋住同名的公開欄位與方法。
- 解析器把 `PATTERN_WHITE_SPACE` 類別的 Unicode 碼點視為空白。

### 標準庫重點

- `std::panic` 穩定，包含 `catch_unwind`（原名 `recover`）、`resume_unwind`、`AssertUnwindSafe`、`UnwindSafe`，詳見 [std::panic](/pkg-panic)。
- `slice::copy_from_slice` 是安全版的 `memcpy`，詳見 [切片](/pkg-slice)。
- `HashSet` 與 `BTreeSet` 新增 `get`、`take`、`replace`，能取回原本存入的鍵，詳見 [std::collections](/pkg-collections)。
- 原始指標新增 `as_ref`、`as_mut`，空指標轉成 `None`；`ptr::read_volatile`、`write_volatile` 穩定，詳見 [std::ptr](/pkg-ptr)。
- `char::decode_utf16` 把 UTF-16 解碼回字元，詳見 [char](/pkg-char)。
- `TcpStream`、`TcpListener`、`UdpSocket` 新增 `set_nodelay`、`set_ttl`、`set_nonblocking` 等設定方法；`SocketAddr` 新增 `set_ip`、`set_port`，詳見 [std::net](/pkg-net)。
- `OpenOptions::create_new`、`File::try_clone`、`str::is_char_boundary`、`OsString::with_capacity` 等穩定。
- `BufReader` 與 `BufWriter` 的預設緩衝區從 64K 降為 8K；`Instant`、`SystemTime`、`Duration` 支援 `+=` 與 `-=`。
- 大部分型別實作 `fmt::Debug`，libcore 中原本缺少的 `Debug` 也已補上。

### Cargo 與工具

- 多個 Cargo 程序可以同時執行，詳見 [Cargo](/modules-cargo)。
- `RUSTFLAGS` 環境變數的內容會傳給 `rustc`，也能用 `build.rustflags` 設定。
- 頂層覆寫（top-level override）可以在整個相依圖中替換特定版本的 crate。
- 測試執行器加上 `--quiet` 會產生精簡的輸出，詳見 [單元測試](/testing-unit)。
- 型別統一（type unification）比較變數的時間複雜度從 *O*(*n*!) 降到 *O*(*n*)，部分程式編譯大幅加快。

### 相容性注意

- `std::sync::Once` 的初始化函式失敗會使它中毒。
- 在重疊的固有 `impl` 區塊中定義同名方法變成錯誤。
- 常數求值改進後，超出範圍的整數字面值可能產生新的錯誤。

### catch_unwind 攔下 panic

Rust 把錯誤分成兩種：預期中的（找不到檔案）用 `Result` 處理，非預期的 bug（索引越界）則 panic。`catch_unwind` 在執行緒內建立一道「隔離邊界」：閉包裡發生 panic 時回傳 `Err`，外面的程式可以繼續執行。範例用 1.10 起提供的 `panic::set_hook` 關掉預設的 panic 訊息，讓輸出保持乾淨。

範例：

```rust
use std::panic;

fn risky(n: i32) -> i32 {
    if n < 0 {
        panic!("負數不被接受：{}", n);
    }
    n * 2
}

fn main() {
    panic::set_hook(Box::new(|_| {}));

    for n in [5, -1] {
        let result = panic::catch_unwind(|| risky(n));
        match result {
            Ok(v) => println!("{} -> Ok({})", n, v),
            Err(payload) => {
                let msg = payload.downcast_ref::<String>().cloned().unwrap_or_default();
                println!("{} -> 攔到 panic：{}", n, msg);
            }
        }
    }
    println!("程式繼續執行");
}
```

輸出：

```text
5 -> Ok(10)
-1 -> 攔到 panic：負數不被接受：-1
程式繼續執行
```

注意：`catch_unwind` 不是 `try`／`catch` 式的錯誤處理，一般錯誤仍應使用 `Result`，詳見 [panic](/errors-panic)；以 `panic=abort` 編譯時 panic 會直接中止整個行程，`catch_unwind` 攔不到。

### copy_from_slice、HashSet::take 與指標 as_ref

`copy_from_slice` 把來源切片整段複製到目標，兩邊長度不同就 panic。`HashSet::get` 借出集合裡存放的那個值，`take` 則把它移出來，取回所有權。原始指標的 `as_ref` 在指標為空時回傳 `None`，否則回傳 `Some(&T)`。

範例：

```rust
use std::collections::HashSet;

fn main() {
    let mut buffer = [0u8; 6];
    buffer[..3].copy_from_slice(b"abc");
    buffer[3..].copy_from_slice(&[1, 2, 3]);
    println!("{:?}", buffer);

    let mut tags: HashSet<String> = ["rust", "go"].iter().map(|s| s.to_string()).collect();
    println!("{:?}", tags.get("rust"));
    println!("{:?}", tags.take("go"));
    println!("{}", tags.len());

    let x = 7;
    let p: *const i32 = &x;
    let null: *const i32 = std::ptr::null();
    unsafe {
        println!("{:?} {:?}", p.as_ref(), null.as_ref());
    }
}
```

輸出：

```text
[97, 98, 99, 1, 2, 3]
Some("rust")
Some("go")
1
Some(7) None
```

注意：`as_ref` 只檢查空指標；非空但已失效的指標仍是未定義行為，所以呼叫必須放在 `unsafe` 區塊，由呼叫者保證指標有效，詳見 [unsafe](/lowlevel-unsafe)。

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

影響 `1.9.0` 的已知漏洞共 16 個；在本版修正的共 0 個；仍影響最新修補版 `1.9.0` 的共 16 個。官方未公布影響範圍的漏洞只列在修正它的版本，不計入其他版本。

### 仍影響 `1.9.0`

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [CVE-2026-5222](https://github.com/rust-lang/cargo/security/advisories/GHSA-p688-r7jv-fm6f) | cargo | Cargo can be coerced to share credentials between registries | 早於 1.96.0 | [1.96.0](/rust-1-96) |
| [CVE-2026-5223](https://github.com/rust-lang/cargo/security/advisories/GHSA-jq42-7mfv-hm57) | cargo | Crates in third party registries can override the cached source of other crates | 早於 1.96.0 | [1.96.0](/rust-1-96) |
| [CVE-2024-43402](https://github.com/rust-lang/rust/security/advisories/GHSA-2xg3-7mm6-98jj) | std | `std::process::Command` batch files argument escaping could be bypassed with trailing whitespace or periods | 早於 1.81.0 | [1.81.0](/rust-1-81) |
| [CVE-2024-24576](https://github.com/rust-lang/rust/security/advisories/GHSA-q455-m56c-85mh) | std | `std::process::Command` did not properly escape arguments of batch files on Windows | 早於 1.77.2 | [1.77.2](/rust-1-77) |
| [CVE-2023-38497](https://github.com/rust-lang/cargo/security/advisories/GHSA-j3xp-wfr4-hx87) | cargo | Cargo not respecting umask when extracting crate archives | 早於 1.71.1 | [1.71.1](/rust-1-71) |
| [CVE-2022-46176](https://github.com/rust-lang/cargo/security/advisories/GHSA-r5w3-xm58-jv6j) | cargo | Cargo did not verify SSH host keys | 早於 1.66.1 | [1.66.1](/rust-1-66) |
| [CVE-2022-36113](https://github.com/rust-lang/cargo/security/advisories/GHSA-rfj2-q3h3-hm5j) | cargo | Extracting malicious crates can corrupt arbitrary files | 早於 1.64.0 | [1.64.0](/rust-1-64) |
| [CVE-2022-36114](https://github.com/rust-lang/cargo/security/advisories/GHSA-2hvr-h6gw-qrxp) | cargo | Extracting malicious crates can fill the file system | 早於 1.64.0 | [1.64.0](/rust-1-64) |
| [CVE-2022-21658](https://github.com/rust-lang/rust/security/advisories/GHSA-r9cc-f5pr-p3j2) | std | Race condition in std::fs::remove_dir_all | 早於 1.58.1 | [1.58.1](/rust-1-58) |
| [CVE-2021-42574](https://github.com/rust-lang/rust/security/advisories/GHSA-rcv6-wg5m-24v6) | rustc | rustc and bidirectional-override codepoints in source code | 早於 1.56.1 | [1.56.1](/rust-1-56) |
| [CVE-2021-29922](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-29922) | std | Improper Input Validation of octal literals in `std::net` | 早於 1.53.0 | [1.53.0](/rust-1-53) |
| [CVE-2019-16760](https://github.com/rust-lang/rust/security/advisories/GHSA-phjm-8x66-qw4r) | cargo | Cargo prior to Rust 1.26.0 may download the wrong dependency | 早於 1.26.0 | [1.26.0](/rust-1-26) |
| [CVE-2018-1000657](https://github.com/rust-lang/rust/issues/44800) | std | Buffer overflow vulnerability in VecDeque::reserve() | 1.3.0 起，早於 1.22.0 | [1.22.0](/rust-1-22) |
| [CVE-2018-1000622](https://groups.google.com/forum/#!topic/rustlang-security-announcements/4ybxYLTtXuM) | rustdoc | Uncontrolled search path element vulnerability in rustdoc plugins | 早於 1.27.1 | [1.27.1](/rust-1-27) |
| [CVE-2018-25008](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-25008) | std | Insufficient synchronization in `Arc::get_mut` | 1.3.0 起，早於 1.29.0 | [1.29.0](/rust-1-29) |
| [CVE-2017-20004](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-20004) | std | MutexGuard\<Cell\<i32\>\> must not be Sync | 早於 1.19.0 | [1.19.0](/rust-1-19) |

本版已停止支援，不會再修正這些漏洞；請升級到 `1.100.1`。

## 資料來源

- [Rust 1.9 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-190-2016-05-26)
- [Rust 1.9 發布公告](https://blog.rust-lang.org/releases/1.9.0/)
- [rust-lang/rust 原始碼 1.9.0](https://github.com/rust-lang/rust/tree/1.9.0)
