# Rust 1.18

Rust 1.18 發布於 2017-06-08，目前最新修補版為 `1.18.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.18 讓 `pub` 可以加上範圍限制：`pub(crate)` 表示「整個 crate 內公開、對外不公開」，`pub(in 路徑)` 只對指定模組樹公開，寫函式庫時更容易劃清內外界線。編譯器也開始自動重排沒有指定 `repr` 的結構欄位以減少填充（padding），許多型別因此變小；同一版線上文件首次收錄《The Rust Programming Language》第二版草稿。升級時要注意：依賴結構欄位順序的 `transmute` 一向是未定義行為，現在更可能真的出錯，與 C 互通的結構要加 `#[repr(C)]`。

### 語言變更

- `pub(crate)`、`pub(in path)` 等受限可見性（restricted visibility）穩定，詳見 [模組系統](/modules-system)。
- 沒有 `repr` 或為 `#[repr(Rust)]` 的元組、列舉變體欄位與結構會重排欄位以減少填充，詳見 [std::mem](/pkg-mem)。
- 新增 Windows 專用的 `#![windows_subsystem = "windows"]` 屬性，圖形介面程式啟動時不會閃出主控台視窗。
- 巨集的 `ty` 片段可以接受 `Write + Send` 這類特徵物件型別，詳見 [宣告式巨集](/macros-declarative)。
- `0e+10` 成為合法的浮點數字面值；把生命週期參數綁定到 `'static` 會產生警告。

### 標準庫重點

- 新增 `HashMap::retain`、`HashSet::retain`，詳見 [HashMap](/pkg-collections-hash-map)。
- 新增 `Child::try_wait`，不阻塞地檢查子行程是否結束，詳見 [std::process](/pkg-process)。
- 新增 `PeekMut::pop`，在 peek 過 `BinaryHeap` 頂端後直接彈出，詳見 [std::collections](/pkg-collections)。
- 新增 `TcpStream::peek`、`UdpSocket::peek`、`UdpSocket::peek_from`，讀取資料但不從緩衝區移除，詳見 [std::net](/pkg-net)。
- 把未消耗過的 `vec::IntoIter` 收集回 `Vec` 時，會直接沿用原本的配置；修正 `fs::create_dir_all` 的競態條件。

### Cargo 與工具

- 新增 `--bins`、`--examples`、`--tests`、`--benches`，一次建置某一類的所有目標，詳見 [Cargo](/start-cargo)。
- `cargo new --vcs pijul` 支援 Pijul 版本控制；Cargo 支援 Android 與 Haiku。
- `rustc` 可以用 `--emit mir` 輸出 MIR；編譯 rustc 本身快了 15%–20%。
- `rustdoc` 新增 `--enable-commonmark`，改用符合 CommonMark 的 Markdown 解析器。

### 相容性注意

- `format!` 的 `0` 旗標改為一律把補零放在正負號之後、數字之前；搭配 `#` 時放在前綴之後，詳見 [std::fmt](/pkg-fmt)。
- 欄位重排後，對沒有 `repr` 的結構使用 `transmute` 更容易壞掉。
- 重疊的固有 `impl`（inherent impl）成為硬錯誤；`PartialOrd` 與 `Ord` 的排序結果必須一致。
- `rustc main.rs -o out --emit=asm,llvm-ir` 會同時輸出 `out.asm` 與 `out.ll`。

### pub(crate) 與 pub(in path)

以前一個項目只有「私有」與 `pub` 兩種選擇，想讓模組間共用、又不想讓函式庫使用者看到，只能靠繞路的模組安排。`pub(crate)` 讓項目在整個 crate 內可見；`pub(in crate::shop)` 則只在 `shop` 模組底下可見，`main` 呼叫不到。

範例：

```rust
mod shop {
    pub mod cart {
        pub(crate) fn total(prices: &[u32]) -> u32 {
            prices.iter().sum::<u32>() + super::tax::fee()
        }
    }

    mod tax {
        pub(in crate::shop) fn fee() -> u32 {
            30
        }
    }

    pub fn checkout(prices: &[u32]) -> String {
        format!("應付 {} 元（含手續費 {}）", cart::total(prices), tax::fee())
    }
}

fn main() {
    println!("{}", shop::cart::total(&[100, 250]));
    println!("{}", shop::checkout(&[100, 250]));
}
```

輸出：

```text
380
應付 380 元（含手續費 30）
```

注意：`pub(in path)` 的路徑必須是目前模組的祖先模組；在 `main` 裡直接呼叫 `shop::tax::fee()` 會編譯失敗。

### 自動重排結構欄位

CPU 讀取資料時要求對齊（alignment），`u16` 要放在 2 的倍數位址，編譯器會在欄位之間塞填充位元組。`(u8, u16, u8)` 照順序擺要 6 bytes，重排成 `(u8, u8, u16)` 只要 4 bytes。Rust 從未承諾預設的記憶體佈局，因此這版開始由編譯器自動重排；需要固定順序（例如傳給 C）時加 `#[repr(C)]`，詳見 [FFI](/lowlevel-ffi)。

以下數值為 64 位元平台的結果。

範例：

```rust
use std::mem::size_of;

#[allow(dead_code)]
struct Suboptimal(u8, u16, u8);

#[allow(dead_code)]
#[repr(C)]
struct CLayout(u8, u16, u8);

fn main() {
    println!("Suboptimal：{} bytes", size_of::<Suboptimal>());
    println!("CLayout：{} bytes", size_of::<CLayout>());
    println!("(u8, u32, u8)：{} bytes", size_of::<(u8, u32, u8)>());
}
```

輸出：

```text
Suboptimal：4 bytes
CLayout：6 bytes
(u8, u32, u8)：8 bytes
```

注意：預設佈局沒有任何保證，可能隨編譯器版本改變；不要在 `unsafe` 程式碼裡假設欄位的位移，詳見 [unsafe](/lowlevel-unsafe)。

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.18.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-28878](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28878) | std | Zip may call __iterator_get_unchecked twice with the same index | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28879](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28879) | std | Zip can cause buffer overflow when a consumed Zip iterator is used again | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28876](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28876) | std | Panic safety issue in Zip specialization | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28877](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28877) | std | TrustedRandomAccess specialization composes incorrectly for nested iter::Zips | 1.11.0 起，早於 1.51.0 | [1.51.0](/rust-1-51) |
| [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-2019-1010299](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-1010299) | std | vec_deque::Iter has unsound Debug implementation | 1.18.0 起，早於 1.30.0 | [1.30.0](/rust-1-30) |
| [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.18 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1180-2017-06-08)
- [Rust 1.18 發布公告](https://blog.rust-lang.org/releases/1.18.0/)
- [rust-lang/rust 原始碼 1.18.0](https://github.com/rust-lang/rust/tree/1.18.0)
