|
| 1 | +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution and at |
| 3 | +// http://rust-lang.org/COPYRIGHT. |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 7 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 8 | +// option. This file may not be copied, modified, or distributed |
| 9 | +// except according to those terms. |
| 10 | + |
| 11 | +use io; |
| 12 | +use sys::c; |
| 13 | +use libc::c_char; |
| 14 | +use path::PathBuf; |
| 15 | +use fs::{OpenOptions, File}; |
| 16 | +use sys::ext::fs::OpenOptionsExt; |
| 17 | +use sys::handle::Handle; |
| 18 | +use super::super::{fill_utf16_buf, os2path, to_u16s, wide_char_to_multi_byte}; |
| 19 | + |
| 20 | +fn query_full_process_image_name() -> io::Result<PathBuf> { |
| 21 | + unsafe { |
| 22 | + let process_handle = Handle::new(c::OpenProcess(c::PROCESS_QUERY_INFORMATION, |
| 23 | + c::FALSE, |
| 24 | + c::GetCurrentProcessId())); |
| 25 | + fill_utf16_buf(|buf, mut sz| { |
| 26 | + if c::QueryFullProcessImageNameW(process_handle.raw(), 0, buf, &mut sz) == 0 { |
| 27 | + 0 |
| 28 | + } else { |
| 29 | + sz |
| 30 | + } |
| 31 | + }, os2path) |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +fn lock_and_get_executable_filename() -> io::Result<(PathBuf, File)> { |
| 36 | + // We query the current image name, open the file without FILE_SHARE_DELETE so it |
| 37 | + // can't be moved and then get the current image name again. If the names are the |
| 38 | + // same than we have successfully locked the file |
| 39 | + let image_name1 = query_full_process_image_name()?; |
| 40 | + let file = OpenOptions::new() |
| 41 | + .read(true) |
| 42 | + .share_mode(c::FILE_SHARE_READ | c::FILE_SHARE_WRITE) |
| 43 | + .open(&image_name1)?; |
| 44 | + let image_name2 = query_full_process_image_name()?; |
| 45 | + |
| 46 | + if image_name1 != image_name2 { |
| 47 | + return Err(io::Error::new(io::ErrorKind::Other, |
| 48 | + "executable moved while trying to lock it")); |
| 49 | + } |
| 50 | + |
| 51 | + Ok((image_name1, file)) |
| 52 | +} |
| 53 | + |
| 54 | +// Get the executable filename for libbacktrace |
| 55 | +// This returns the path in the ANSI code page and a File which should remain open |
| 56 | +// for as long as the path should remain valid |
| 57 | +pub fn get_executable_filename() -> io::Result<(Vec<c_char>, File)> { |
| 58 | + let (executable, file) = lock_and_get_executable_filename()?; |
| 59 | + let u16_executable = to_u16s(executable.into_os_string())?; |
| 60 | + Ok((wide_char_to_multi_byte(c::CP_ACP, c::WC_NO_BEST_FIT_CHARS, |
| 61 | + &u16_executable, true)?, file)) |
| 62 | +} |
0 commit comments