Skip to content

add file and product version get of PE(Portable Executable) #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ anyhow = "1.0"
clap = "3.0.0-beta.2"
chrono = "0.4"
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde = { version = "1.0", features = ["derive"] }
pelite = "0.9.0"
4 changes: 4 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 0.3.0

* add file_version and product_version field

# 0.2.1

* fix symlink with maxdepth(#1)
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ you can get help with `lsx --help`
|file_type|file type("file","dir","link")|
|last_modified|last updated time|
|link_target|target path if the path is symbolic link, or null|
|file_version|Windows file FileVersion if available|
|product_version|Windows file ProductVersion if available|

## examples

Expand All @@ -34,4 +36,6 @@ you can get help with `lsx --help`
* output to file `x.csv`
* `lsx -o x.csv tmp`
* output file as ndjson
* `lsx --output-format ndjson tmp`
* `lsx --output-format ndjson tmp`
* get file version
* `lsx --get-version`
38 changes: 36 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use serde::Serialize;
use std::io::Write;
use std::rc::Rc;

mod pe;

#[derive(Debug, thiserror::Error)]
#[error("unknown format({name})")]
struct UnknownOutputFormat {
Expand Down Expand Up @@ -39,6 +41,8 @@ struct FindOption {
dir_only: bool,
#[clap(long, about = "output total size of directory(bytes)")]
total_size: bool,
#[clap(long, about = "get PE file version if available")]
get_version: bool,
}

enum RecordWriter<T>
Expand Down Expand Up @@ -72,6 +76,8 @@ where
.as_ref()
.unwrap_or(&String::new())
.as_str(),
record.file_version.unwrap_or(String::new()).as_str(),
record.product_version.unwrap_or(String::new()).as_str(),
])?;
}
Self::NdJson(v) => {
Expand All @@ -89,12 +95,15 @@ where
pub fn output_header(&mut self) -> Result<()> {
match self {
Self::Csv(w) => {

w.write_record(&[
"path",
"link_target",
"file_type",
"length",
"last_modified",
"file_version",
"product_version",
])?;
}
Self::NdJson(_) => {},
Expand All @@ -111,6 +120,8 @@ struct FileRecord {
file_type: String,
last_modified: Option<String>,
link_target: Option<String>,
file_version: Option<String>,
product_version: Option<String>,
}

enum OutputStream {
Expand Down Expand Up @@ -145,6 +156,7 @@ struct FindContext<'a> {
match_option: glob::MatchOptions,
dir_only: bool,
output_total: bool,
get_version: bool,
}

fn create_record_writer(
Expand Down Expand Up @@ -199,6 +211,7 @@ impl<'a> FindContext<'a> {
match_option: match_option,
output_total: output_total,
dir_only: dir_only,
get_version: opts.get_version,
})
}
pub fn with_path(mut self, new_path: &std::path::Path) -> Self {
Expand Down Expand Up @@ -238,13 +251,18 @@ fn output_symlink_info<'a>(
None
};
if !ctx.dir_only {
let (file_version, product_version) = if ctx.get_version {
pe::read_version_from_dll(path).unwrap_or((None, None))
} else { (None, None) };
write_record(
&mut ctx.output_stream,
path.to_string_lossy().as_ref(),
Some(link_target),
"link",
Some(len),
modified,
file_version,
product_version
)?;
}
Ok((ctx, len))
Expand Down Expand Up @@ -276,12 +294,17 @@ fn output_symlink_file_info<'a>(
None => (None, None)
};
if !ctx.dir_only {
let (file_version, product_version) = if ctx.get_version {
pe::read_version_from_dll(path).unwrap_or((None, None))
} else { (None, None) };
write_record(ctx.output_stream,
path.to_string_lossy().as_ref(),
Some(link_target.to_string_lossy().as_ref()),
"file",
l,
modified)?;
modified,
file_version,
product_version)?;
}
Ok((ctx.with_path(parent.as_path()), l.unwrap_or(0)))
}
Expand Down Expand Up @@ -323,13 +346,16 @@ fn output_file_info<'a>(
None
};
if !ctx.dir_only {
let (file_version, product_version) = pe::read_version_from_dll(path).unwrap_or((None, None));
write_record(
&mut ctx.output_stream,
path.to_string_lossy().as_ref(),
None,
"file",
len,
modified,
file_version,
product_version
)?;
}
Ok((ctx.with_path(parent.as_path()), len.unwrap_or(0)))
Expand Down Expand Up @@ -361,6 +387,8 @@ fn write_record<T>(
file_type: &str,
length: Option<u64>,
last_write: Option<std::time::SystemTime>,
file_version: Option<String>,
product_version: Option<String>
) -> Result<()>
where
T: std::io::Write,
Expand All @@ -378,6 +406,8 @@ where
file_type: file_type.to_owned(),
length: length,
last_modified: Some(ststr),
file_version: file_version,
product_version: product_version,
})?;
Ok(())
}
Expand Down Expand Up @@ -457,6 +487,8 @@ fn retrieve_symlink<'a>(
"dir",
Some(len),
modified,
None,
None
)?;
}
return Ok((ctx_tmp, len));
Expand Down Expand Up @@ -583,6 +615,8 @@ fn enum_files_recursive<'a>(
"dir",
Some(retval.1),
last_write,
None,
None
)?;
}
current_total += retval.1;
Expand Down Expand Up @@ -622,7 +656,7 @@ fn enum_files(pattern: &FindOption) -> Result<()> {
}
let (root_ctx, root_size) = enum_files_recursive(ctx, rootpath.as_path(), 0)?;
if root_ctx.output_total {
write_record(&mut record_writer, rootpath.as_path().to_string_lossy().as_ref(), None, "dir", Some(root_size), None)?;
write_record(&mut record_writer, rootpath.as_path().to_string_lossy().as_ref(), None, "dir", Some(root_size), None, None, None)?;
}
}
Ok(())
Expand Down
40 changes: 40 additions & 0 deletions src/pe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use std::path::Path;
use anyhow::Result;
use pelite::FileMap;
use pelite::pe64::PeFile as PeFile64;
use pelite::pe64::Pe as Pe64;
use pelite::pe32::PeFile as PeFile32;
use pelite::pe32::Pe as Pe32;
use pelite::Error as PeError;

pub fn read_version_from_dll(p: &Path) -> Result<(Option<String>, Option<String>)> {
let fmap = FileMap::open(p)?;
match PeFile64::from_bytes(&fmap) {
Ok(pe) => {
let resources = pe.resources()?;
return get_versions_from_resource(resources);
},
Err(e) => {
if let PeError::PeMagic = e {
let pe = PeFile32::from_bytes(&fmap)?;
let resources = pe.resources()?;
return get_versions_from_resource(resources);
} else {
return Err(anyhow::Error::from(e));
}
}
};
}

fn get_versions_from_resource(res: pelite::resources::Resources) -> Result<(Option<String>, Option<String>)> {
let verinfo = res.version_info()?;
for lang in verinfo.translation() {
let product = verinfo.value(lang.to_owned(), "ProductVersion");
let file = verinfo.value(lang.to_owned(), "FileVersion");
if product.is_some() || file.is_some() {
return Ok((file.map(|x| x.trim().to_owned()), product.map(|x| x.trim().to_owned())));
}
}
// if no version info
return Ok((None, None));
}