misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Crash reports: Linux stacks read from the program's start, a C-runtime stall is a busy computer (#661, #663) (#669)
Ahmed Nefzaouid45f3f5ba28c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex db9b191e..ba2242c4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,8 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Fixed+- Linux: freeze and crash reports show MDM's own functions, files and lines again, and the right ones. When MDM's code began a page after the start of the program in memory (as 0.5.0's did), the report read the whole stack at the wrong place: it showed only system libraries (`freeze in libc.so.6+…`), named other functions of MDM once the release's symbols were fetched, and couldn't find an existing issue for the same problem. A `.dmp` from such a report reads right too ([#661](https://github.com/anefzaoui/misterdownloadmanager/issues/661)).+- Windows: a freeze report whose window thread hardly ran and stopped in the C runtime's memory routines (`VCRUNTIME140.dll`, comparing the first bytes of an icon) now says the computer was too busy to run MDM or slow to load it from disk, with the page faults counted meanwhile, instead of a deadlock; those routines never wait ([#663](https://github.com/anefzaoui/misterdownloadmanager/issues/663)).- Torrents: magnet links without trackers find peers through the DHT again where its first nodes didn't answer. MDM asked only two public routers to join the DHT; where neither answered (one name pointing at an old address, or a network blocking one), the DHT stayed empty and the log said "error in bootstrap" every minute or two. It now asks four together (`dht.libtorrent.org`, `dht.transmissionbt.com`, `router.bittorrent.com`, `router.utorrent.com`), any one that answers is enough, and the others are asked no more once one has. The nodes it knows are kept for the next start, the IPv6 ones too ([#650](https://github.com/anefzaoui/misterdownloadmanager/issues/650)).- Torrents: with the **Port** box empty in Torrent settings, MDM keeps the port it picked and listens on it again at the next start (another one if a program has taken it), so peers that learned it, and a router's or firewall's rule for it, still reach MDM; it was a new port at each start. MDM's log says where it listens: one socket for IPv4 and IPv6, which Windows' `netstat -p tcp` (IPv4 only) doesn't list ([#650](https://github.com/anefzaoui/misterdownloadmanager/issues/650)).- macOS: YouTube videos that need yt-dlp's JavaScript runtime load when MDM is opened from Finder or the Dock. MDM found Homebrew's yt-dlp, but the helpers it started didn't get Homebrew's folders on their PATH, so yt-dlp found neither Deno nor ffmpeg ("Requested format is not available"); they now look there too, after the folders of their own PATH ([#659](https://github.com/anefzaoui/misterdownloadmanager/issues/659)).diff --git a/ROADMAP.md b/ROADMAP.mdindex b4eef43d..28922512 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -501,6 +501,13 @@ Bug fixes from the first days of 0.5.0, a Safari extension, and more file types.These ship in the next version.+- ✅ Linux freeze and crash reports name MDM's functions again, and the right ones: the stack of+ a program whose code begins a page after its start (0.5.0's) was read at the wrong place, so+ reports showed only system libraries, or names from elsewhere in MDM+ ([#661](https://github.com/anefzaoui/misterdownloadmanager/issues/661))+- ✅ Windows: a freeze in the C runtime's memory routines, where the window hardly ran, is+ reported as a computer too busy or slow to load MDM from disk, not as a deadlock+ ([#663](https://github.com/anefzaoui/misterdownloadmanager/issues/663))- ✅ macOS: helpers opened from Finder find Homebrew's Deno and ffmpeg, so YouTube formatsload ([#659](https://github.com/anefzaoui/misterdownloadmanager/issues/659))- ✅ The website is named as the official one in the README, the browser add-on and thediff --git a/crates/app/src/crash.rs b/crates/app/src/crash.rsindex 3dbef4c9..8c319ac6 100644--- a/crates/app/src/crash.rs+++ b/crates/app/src/crash.rs@@ -291,10 +291,10 @@ fn watchdog() {});if let Some(b) = busy {tracing::warn!(- "the window thread ran {} of {} ms meanwhile ({:?} page faults)",+ "the window thread ran {} of {} ms meanwhile ({} page faults)",b.cpu_ms,b.wall_ms,- b.faults+ b.faults.map_or("unknown".to_owned(), |n| n.to_string()));}mdm_crash::logs::flush(LOG_FOR_A_REPORT);diff --git a/crates/crash/src/analyze.rs b/crates/crash/src/analyze.rsindex ad5a12fb..e7fd15c8 100644--- a/crates/crash/src/analyze.rs+++ b/crates/crash/src/analyze.rs@@ -74,7 +74,9 @@ impl Analysis {/// Read `dump` with the `.sym` folders in `symbols` and, failing them, each module's own debug/// info.pub fn analyze(dump: &Path, symbols: &[PathBuf]) -> Result<Analysis, String> {- let dump = minidump::Minidump::read_path(dump).map_err(|e| e.to_string())?;+ let bytes = std::fs::read(dump).map_err(|e| e.to_string())?;+ // A Linux program listed as two modules is one again first (#661, modules.rs).+ let dump = minidump::Minidump::read(crate::modules::mend(bytes)).map_err(|e| e.to_string())?;let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()diff --git a/crates/crash/src/lib.rs b/crates/crash/src/lib.rsindex fff8c6db..3320a6f5 100644--- a/crates/crash/src/lib.rs+++ b/crates/crash/src/lib.rs@@ -8,6 +8,7 @@//! - `client`: the app's side (start the monitor, messages, dump requests).//! - `monitor`: the monitor's side (the dump server and its events).//! - `analyze`: a dump made readable (stacks with function, file and line).+//! - `modules`: a Linux dump's module list mended first (a program split in two by a gap).//! - `report`: the report's text and the problem's signature.//! - `github`: the issue form and the search for one already filed.//! - `symbols`: the release's symbols, fetched on demand.@@ -17,6 +18,7 @@ pub mod analyze;pub mod client;pub mod github;pub mod logs;+mod modules;pub mod monitor;pub mod protocol;pub mod report;diff --git a/crates/crash/src/modules.rs b/crates/crash/src/modules.rsnew file mode 100644index 00000000..d03e67e4--- /dev/null+++ b/crates/crash/src/modules.rs@@ -0,0 +1,268 @@+//! A Linux dump's module list mended before it is read (#661).+//!+//! The Linux dump writer (minidump-writer) makes one module of a program's mappings only when+//! they follow each other in memory. A program linked by lld can leave an unmapped page between+//! its first, read-only mapping (the ELF header, at file offset 0) and its code, whenever the+//! code segment happens to start on a page of its own (MDM 0.5.0's did). The writer then lists+//! the code as a module of its own, based where the code starts instead of where the program+//! starts. Every address in the code was then read 0xd96000 too low: the release's symbols named+//! the wrong functions, unwinding found no unwind tables, and the report's own offsets+//! (`misterdownloadmanager + 0x…`) couldn't be looked up either.+//!+//! The dump also holds the process's `/proc/self/maps`, which says which part of the file each+//! mapping holds. A module whose mapping doesn't start the file is joined here to the mapping of+//! the same file that does (offset 0, just below it): one module, based where the program+//! starts, as the symbols (and every other reader) expect.++/// The module list stream (MINIDUMP_STREAM_TYPE ModuleListStream).+const MODULE_LIST: u32 = 4;+/// Breakpad's `/proc/self/maps` stream (MD_LINUX_MAPS).+const LINUX_MAPS: u32 = 0x4767_0009;+/// MINIDUMP_MODULE's size: base u64, size u32, checksum u32, time stamp u32, name RVA u32,+/// VS_FIXEDFILEINFO (52), CodeView and misc locations (8 each), two reserved u64.+const MODULE_SIZE: usize = 108;++/// One line of `/proc/self/maps`: where, and which part of which file.+struct Mapping<'a> {+ start: u64,+ offset: u64,+ path: &'a str,+}++/// `dump` with every module split from its program joined back to it. Unchanged when there is+/// nothing to mend, or the dump isn't one this understands (a Windows or macOS dump has no+/// maps stream).+pub fn mend(mut dump: Vec<u8>) -> Vec<u8> {+ if let Some(fixed) = mended(&dump) {+ for (at, bytes) in fixed {+ dump[at..at + bytes.len()].copy_from_slice(&bytes);+ }+ }+ dump+}++/// The bytes to write over (where, what), or None.+fn mended(dump: &[u8]) -> Option<Vec<(usize, Vec<u8>)>> {+ if dump.get(..4)? != b"MDMP" {+ return None;+ }+ let streams = u32_at(dump, 8)? as usize;+ let dir = u32_at(dump, 12)? as usize;+ let (mut list, mut maps) = (None, None);+ for i in 0..streams {+ let e = dir + i * 12;+ let (kind, size, rva) = (u32_at(dump, e)?, u32_at(dump, e + 4)?, u32_at(dump, e + 8)?);+ match kind {+ MODULE_LIST => list = Some((e, rva as usize)),+ LINUX_MAPS => {+ maps = Some(dump.get(rva as usize..(rva as usize).checked_add(size as usize)?)?)+ }+ _ => {}+ }+ }+ let ((entry, list), maps) = (list?, std::str::from_utf8(maps?).ok()?);+ let maps: Vec<Mapping> = maps.lines().filter_map(mapping).collect();+ let count = u32_at(dump, list)? as usize;+ let mut modules: Vec<(u64, u64)> = (0..count)+ .map(|i| {+ let at = list + 4 + i * MODULE_SIZE;+ Some((u64_at(dump, at)?, u64::from(u32_at(dump, at + 8)?)))+ })+ .collect::<Option<_>>()?;+ let mut keep = vec![true; count];+ let mut changed = false;+ for i in 0..count {+ let (base, size) = modules[i];+ let Some(m) = maps.iter().find(|m| m.start == base) else {+ continue;+ };+ if m.offset == 0 || !m.path.starts_with('/') {+ continue;+ }+ // The same file's mapping from its start, the closest below.+ let Some(start) = maps+ .iter()+ .filter(|s| s.path == m.path && s.offset == 0 && s.start < base)+ .map(|s| s.start)+ .max()+ else {+ continue;+ };+ let end = base + size;+ match (0..count).find(|&j| keep[j] && j != i && modules[j].0 == start) {+ // Listed already (the writer lists the read-only start too): it grows to cover the+ // code, and the code's own entry goes.+ Some(j) => {+ let (b, s) = modules[j];+ modules[j].1 = end.max(b + s) - b;+ keep[i] = false;+ }+ // Not listed: the code's entry starts where the program does.+ None => modules[i] = (start, end - start),+ }+ changed = true;+ }+ if !changed {+ return None;+ }+ // The list rewritten: the entries kept, in their order, each based and sized anew; the+ // stream's size follows its new count (what is left after it is no longer read).+ let mut out = Vec::new();+ let mut bytes = Vec::with_capacity(4 + count * MODULE_SIZE);+ let kept: Vec<usize> = (0..count).filter(|&i| keep[i]).collect();+ bytes.extend_from_slice(&(kept.len() as u32).to_le_bytes());+ for &i in &kept {+ let at = list + 4 + i * MODULE_SIZE;+ let mut raw = dump.get(at..at + MODULE_SIZE)?.to_vec();+ let (base, size) = modules[i];+ raw[..8].copy_from_slice(&base.to_le_bytes());+ raw[8..12].copy_from_slice(&u32::try_from(size).ok()?.to_le_bytes());+ bytes.extend_from_slice(&raw);+ }+ let new_size = bytes.len() as u32;+ out.push((list, bytes));+ out.push((entry + 4, new_size.to_le_bytes().to_vec()));+ Some(out)+}++/// `start-end perms offset dev inode [path]`.+fn mapping(line: &str) -> Option<Mapping<'_>> {+ let mut parts = line.splitn(6, ' ');+ let (start, _) = parts.next()?.split_once('-')?;+ let _perms = parts.next()?;+ let offset = parts.next()?;+ let (_dev, _inode) = (parts.next()?, parts.next()?);+ Some(Mapping {+ start: u64::from_str_radix(start, 16).ok()?,+ offset: u64::from_str_radix(offset, 16).ok()?,+ path: parts.next().unwrap_or("").trim(),+ })+}++fn u32_at(b: &[u8], at: usize) -> Option<u32> {+ Some(u32::from_le_bytes(+ b.get(at..at.checked_add(4)?)?.try_into().ok()?,+ ))+}++fn u64_at(b: &[u8], at: usize) -> Option<u64> {+ Some(u64::from_le_bytes(+ b.get(at..at.checked_add(8)?)?.try_into().ok()?,+ ))+}++#[cfg(test)]+mod tests {+ use super::*;+ use minidump::Module;++ /// A dump with a module list and a maps stream, as minidump-writer writes them.+ fn dump(modules: &[(u64, u32, &str)], maps: &str) -> Vec<u8> {+ let mut d = vec![0u8; 32];+ d[..4].copy_from_slice(b"MDMP");+ d[4..8].copy_from_slice(&0xa793u32.to_le_bytes());+ d[8..12].copy_from_slice(&2u32.to_le_bytes());+ d[12..16].copy_from_slice(&32u32.to_le_bytes());+ // The directory (2 entries), filled in below.+ d.extend_from_slice(&[0; 24]);+ // The modules' names (MINIDUMP_STRING: byte length, UTF-16).+ let mut names = Vec::new();+ for (_, _, name) in modules {+ names.push(d.len() as u32);+ let utf16: Vec<u16> = name.encode_utf16().collect();+ d.extend_from_slice(&((utf16.len() * 2) as u32).to_le_bytes());+ for c in utf16 {+ d.extend_from_slice(&c.to_le_bytes());+ }+ d.extend_from_slice(&[0, 0]);+ }+ while !d.len().is_multiple_of(4) {+ d.push(0);+ }+ let list = d.len() as u32;+ d.extend_from_slice(&(modules.len() as u32).to_le_bytes());+ for (i, (base, size, _)) in modules.iter().enumerate() {+ let mut raw = [0u8; MODULE_SIZE];+ raw[..8].copy_from_slice(&base.to_le_bytes());+ raw[8..12].copy_from_slice(&size.to_le_bytes());+ raw[20..24].copy_from_slice(&names[i].to_le_bytes());+ d.extend_from_slice(&raw);+ }+ let list_size = d.len() as u32 - list;+ let maps_at = d.len() as u32;+ d.extend_from_slice(maps.as_bytes());+ let dir = [+ (MODULE_LIST, list_size, list),+ (LINUX_MAPS, maps.len() as u32, maps_at),+ ];+ for (i, (kind, size, rva)) in dir.iter().enumerate() {+ let e = 32 + i * 12;+ d[e..e + 4].copy_from_slice(&kind.to_le_bytes());+ d[e + 4..e + 8].copy_from_slice(&size.to_le_bytes());+ d[e + 8..e + 12].copy_from_slice(&rva.to_le_bytes());+ }+ d+ }++ fn modules(d: Vec<u8>) -> Vec<(u64, u64, String)> {+ let dump = minidump::Minidump::read(d).unwrap();+ let list: minidump::MinidumpModuleList = dump.get_stream().unwrap();+ list.iter()+ .map(|m| (m.base_address(), m.size(), m.code_file().into_owned()))+ .collect()+ }++ const EXE: &str = "/usr/bin/misterdownloadmanager";+ const LIBC: &str = "/usr/lib64/libc.so.6";++ /// MDM 0.5.0's layout (#661): the header's mapping, a page unmapped, then the code with the+ /// rest of the program after it.+ fn split_maps() -> String {+ format!(+ "5c0000000000-5c0000d95000 r--p 00000000 08:02 7 {EXE}\n\+ 5c0000d96000-5c0002670000 r-xp 00d95000 08:02 7 {EXE}\n\+ 7f0000000000-7f0000028000 r--p 00000000 08:02 9 {LIBC}\n\+ 7f0000028000-7f00001b0000 r-xp 00028000 08:02 9 {LIBC}\n"+ )+ }++ #[test]+ fn a_program_split_by_a_gap_is_one_module_again() {+ let d = dump(+ &[+ (0x5c00_0000_0000, 0xd95000, EXE),+ (0x5c00_00d9_6000, 0x18da000, EXE),+ (0x7f00_0000_0000, 0x1b0000, LIBC),+ ],+ &split_maps(),+ );+ assert_eq!(+ modules(mend(d)),+ vec![+ (0x5c00_0000_0000, 0x2670000, EXE.to_owned()),+ (0x7f00_0000_0000, 0x1b0000, LIBC.to_owned()),+ ]+ );+ }++ #[test]+ fn code_listed_without_its_start_is_based_at_the_start() {+ let d = dump(&[(0x5c00_00d9_6000, 0x18da000, EXE)], &split_maps());+ assert_eq!(+ modules(mend(d)),+ vec![(0x5c00_0000_0000, 0x2670000, EXE.to_owned())]+ );+ }++ #[test]+ fn whole_modules_and_other_dumps_are_left_alone() {+ // Merged by the writer already (no gap): listed from the file's start.+ let d = dump(&[(0x7f00_0000_0000, 0x1b0000, LIBC)], &split_maps());+ assert_eq!(mend(d.clone()), d);+ // No maps stream (Windows, macOS), or not a dump at all.+ let mut no_maps = d.clone();+ no_maps[32 + 12..32 + 16].copy_from_slice(&0u32.to_le_bytes());+ assert_eq!(mend(no_maps.clone()), no_maps);+ assert_eq!(mend(b"not a dump".to_vec()), b"not a dump".to_vec());+ }+}diff --git a/crates/crash/src/report.rs b/crates/crash/src/report.rsindex 955fdece..e0e09c85 100644--- a/crates/crash/src/report.rs+++ b/crates/crash/src/report.rs@@ -447,10 +447,20 @@ pub fn stuck(// thread hardly ran is almost always a wait (the system's waits live there).None if share > STARVED_SHARE => None,None if main.is_some() && top.module.as_deref() == main => Some(Stuck::Starved),+ // The C runtime's copies and compares (memcmp of an icon's first bytes, #663): never a+ // wait, so a thread that hardly ran there waited for its memory, loaded from disk.+ None if top.module.as_deref().is_some_and(is_memory_routines) => Some(Stuck::Starved),None => top.module.is_some().then_some(Stuck::Waiting),}}+/// A module of the C runtime's memory and string routines only (memcpy, memcmp, memset): no+/// wait lives there. Windows' VCRUNTIME140.dll and VCRUNTIME140_1.dll; not ucrtbase.dll, nor+/// Linux's libc, which hold the waits as well.+fn is_memory_routines(module: &str) -> bool {+ module.to_ascii_lowercase().starts_with("vcruntime")+}+/// A function a thread waits in: the system's waits and sleeps, locks, I/O.fn is_wait(function: &str) -> bool {const WAITS: &[&str] = &[@@ -840,6 +850,16 @@ mod tests {stuck(&f, bare.threads[0].frames.first(), main),Some(Stuck::Waiting));+ // #663: in the C runtime's memcmp, under MDM's own code: no wait there, so starved.+ bare.threads[0].frames[0].module = Some("VCRUNTIME140.dll".into());+ assert_eq!(+ stuck(&f, bare.threads[0].frames.first(), main),+ Some(Stuck::Starved)+ );+ assert_eq!(+ signature(Kind::Freeze, &freeze_with(&bare, 100)),+ "freeze while the computer was busy"+ );}/// #355, as reported: the dump was written 7 s after it was asked for, when the window thread