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。
  • fn 項目型別改為零大小,每個 fn 都是獨一無二的型別,詳見 函式。
  • 欄位與方法解析會考慮可見性,私有欄位與方法不會擋住同名的公開欄位與方法。
  • 解析器把 PATTERN_WHITE_SPACE 類別的 Unicode 碼點視為空白。

標準庫重點


  • std::panic 穩定,包含 catch_unwind(原名 recover)、resume_unwind、AssertUnwindSafe、UnwindSafe,詳見 std::panic。
  • slice::copy_from_slice 是安全版的 memcpy,詳見 切片。
  • HashSet 與 BTreeSet 新增 get、take、replace,能取回原本存入的鍵,詳見 std::collections。
  • 原始指標新增 as_ref、as_mut,空指標轉成 None;ptr::read_volatile、write_volatile 穩定,詳見 std::ptr。
  • char::decode_utf16 把 UTF-16 解碼回字元,詳見 char。
  • TcpStream、TcpListener、UdpSocket 新增 set_nodelay、set_ttl、set_nonblocking 等設定方法;SocketAddr 新增 set_ip、set_port,詳見 std::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。
  • RUSTFLAGS 環境變數的內容會傳給 rustc,也能用 build.rustflags 設定。
  • 頂層覆寫(top-level override)可以在整個相依圖中替換特定版本的 crate。
  • 測試執行器加上 --quiet 會產生精簡的輸出,詳見 單元測試。
  • 型別統一(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 訊息,讓輸出保持乾淨。
範例:
  1. use std::panic;
  2. fn risky(n: i32) -> i32 {
  3. if n < 0 {
  4. panic!("負數不被接受:{}", n);
  5. }
  6. n * 2
  7. }
  8. fn main() {
  9. panic::set_hook(Box::new(|_| {}));
  10. for n in [5, -1] {
  11. let result = panic::catch_unwind(|| risky(n));
  12. match result {
  13. Ok(v) => println!("{} -> Ok({})", n, v),
  14. Err(payload) => {
  15. let msg = payload.downcast_ref::<String>().cloned().unwrap_or_default();
  16. println!("{} -> 攔到 panic:{}", n, msg);
  17. }
  18. }
  19. }
  20. println!("程式繼續執行");
  21. }

輸出:
  1. 5 -> Ok(10)
  2. -1 -> 攔到 panic:負數不被接受:-1
  3. 程式繼續執行

注意:catch_unwind 不是 try/catch 式的錯誤處理,一般錯誤仍應使用 Result,詳見 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)。
範例:
  1. use std::collections::HashSet;
  2. fn main() {
  3. let mut buffer = [0u8; 6];
  4. buffer[..3].copy_from_slice(b"abc");
  5. buffer[3..].copy_from_slice(&[1, 2, 3]);
  6. println!("{:?}", buffer);
  7. let mut tags: HashSet<String> = ["rust", "go"].iter().map(|s| s.to_string()).collect();
  8. println!("{:?}", tags.get("rust"));
  9. println!("{:?}", tags.take("go"));
  10. println!("{}", tags.len());
  11. let x = 7;
  12. let p: *const i32 = &x;
  13. let null: *const i32 = std::ptr::null();
  14. unsafe {
  15. println!("{:?} {:?}", p.as_ref(), null.as_ref());
  16. }
  17. }

輸出:
  1. [97, 98, 99, 1, 2, 3]
  2. Some("rust")
  3. Some("go")
  4. 1
  5. Some(7) None

注意:as_ref 只檢查空指標;非空但已失效的指標仍是未定義行為,所以呼叫必須放在 unsafe 區塊,由呼叫者保證指標有效,詳見 unsafe。

本版新增的棄用 API


本版沒有新增棄用 API。

修補版本


本版沒有修補版本。

已知漏洞


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

仍影響 1.9.0


編號元件摘要(官方原文)影響範圍修正於
CVE-2026-5222cargoCargo can be coerced to share credentials between registries早於 1.96.01.96.0
CVE-2026-5223cargoCrates in third party registries can override the cached source of other crates早於 1.96.01.96.0
CVE-2024-43402stdstd::process::Command batch files argument escaping could be bypassed with trailing whitespace or periods早於 1.81.01.81.0
CVE-2024-24576stdstd::process::Command did not properly escape arguments of batch files on Windows早於 1.77.21.77.2
CVE-2023-38497cargoCargo not respecting umask when extracting crate archives早於 1.71.11.71.1
CVE-2022-46176cargoCargo did not verify SSH host keys早於 1.66.11.66.1
CVE-2022-36113cargoExtracting malicious crates can corrupt arbitrary files早於 1.64.01.64.0
CVE-2022-36114cargoExtracting malicious crates can fill the file system早於 1.64.01.64.0
CVE-2022-21658stdRace condition in std::fs::remove_dir_all早於 1.58.11.58.1
CVE-2021-42574rustcrustc and bidirectional-override codepoints in source code早於 1.56.11.56.1
CVE-2021-29922stdImproper Input Validation of octal literals in std::net早於 1.53.01.53.0
CVE-2019-16760cargoCargo prior to Rust 1.26.0 may download the wrong dependency早於 1.26.01.26.0
CVE-2018-1000657stdBuffer overflow vulnerability in VecDeque::reserve()1.3.0 起,早於 1.22.01.22.0
CVE-2018-1000622rustdocUncontrolled search path element vulnerability in rustdoc plugins早於 1.27.11.27.1
CVE-2018-25008stdInsufficient synchronization in Arc::get_mut1.3.0 起,早於 1.29.01.29.0
CVE-2017-20004stdMutexGuard<Cell<i32>> must not be Sync早於 1.19.01.19.0

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

資料來源