1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/*!
Resources.
*/

use std::{fmt, iter, mem, slice};

use error::{Error, Result};
use image::*;
use util::{Pod, WideStr};

//----------------------------------------------------------------

mod find;
pub use self::find::FindError;

mod art;

pub mod version_info;

//----------------------------------------------------------------

/// Resources filesystem.
#[derive(Copy, Clone)]
pub struct Resources<'a> {
	section: &'a [u8],
	dir: &'a IMAGE_DATA_DIRECTORY,
}
impl<'a> Resources<'a> {
	/// Parse the bytes as PE resources.
	///
	/// No validation or integrity checking is done ahead of time.
	pub fn new(section: &'a [u8], dir: &'a IMAGE_DATA_DIRECTORY) -> Resources<'a> {
		// All offsets _except_ the data entry offsets are relative to the resource directory.
		// Data entry offsets are relative virtual addresses from the PE image.
		// Microsoft... Why would you do this?
		Resources { section, dir }
	}
	/// Gets the root directory.
	pub fn root(&self) -> Result<Directory<'a>> {
		Directory::try_from(*self, 0)
	}
	/// Filesystem consistency check.
	///
	/// Simply walks the filesystem checking all references are valid.
	pub fn fsck(&self) -> Result<()> {
		self.root()?.fsck()
	}

	#[inline]
	fn slice<T>(&self, offset: u32) -> Result<&'a T> where T: Pod {
		let start = offset as usize;
		let end = mem::size_of::<T>().wrapping_add(start);
		// Alignment checking
		if !cfg!(feature = "unsafe_alignment") && start & (mem::align_of::<T>() - 1) != 0 {
			return Err(Error::Misaligned);
		}
		// Range checking done by the indexing operator
		let bytes = self.section.get(start..end).ok_or(Error::Bounds)?;
		// Safe because size and alignment are checked and T is Pod
		Ok(unsafe { &*(bytes.as_ptr() as *const T) })
	}
	#[inline]
	#[allow(dead_code)] // unused for now...
	fn slice_len<T>(&self, offset: u32, len: usize) -> Result<&'a [T]> where T: Pod {
		let start = offset as usize;
		let size_of = mem::size_of::<T>().checked_mul(len).ok_or(Error::Overflow)?;
		let end = start.wrapping_add(size_of);
		// Alignment checking
		if !cfg!(feature = "unsafe_alignment") && start & (mem::align_of::<T>() - 1) != 0 {
			return Err(Error::Misaligned);
		}
		// Range checking done by the indexing operator
		let bytes = self.section.get(start..end).ok_or(Error::Bounds)?;
		Ok(unsafe { slice::from_raw_parts(bytes.as_ptr() as *const T, len) })
	}
	#[inline]
	fn slice_ws(&self, offset: u32) -> Result<&'a WideStr> {
		let offset = offset as usize;
		// Alignment checking
		if !cfg!(feature = "unsafe_alignment") && offset & 1 != 0 {
			return Err(Error::Misaligned);
		}
		// The name is prefixed by its length in words
		let len = self.section.get(offset..offset + 2).ok_or(Error::Bounds)?;
		let len = unsafe { *(len.as_ptr() as *const u16) } as usize;
		// Extract the name given its length
		let name = self.section.get(offset..offset + (len + 1) * 2).ok_or(Error::Bounds)?;
		let name = unsafe { slice::from_raw_parts(name.as_ptr() as *const u16, len + 1) };
		let name = unsafe { WideStr::from_words_unchecked(name) };
		Ok(name)
	}
}
impl<'a> fmt::Debug for Resources<'a> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.write_str("Resources { .. }")
	}
}

//----------------------------------------------------------------

/// Directory.
#[derive(Copy, Clone)]
pub struct Directory<'a> {
	resources: Resources<'a>,
	image: &'a IMAGE_RESOURCE_DIRECTORY,
}
impl<'a> Directory<'a> {
	fn try_from(resources: Resources<'a>, offset: u32) -> Result<Directory<'a>> {
		let image: &IMAGE_RESOURCE_DIRECTORY = resources.slice(offset)?;
		// Validate the number of directory entries
		// This code has been carefully written to avoid panicking on overflow
		// It also validates the unsafe blocks below cf. size and alignment
		let entries_size = (image.NumberOfNamedEntries as usize + image.NumberOfIdEntries as usize) * mem::size_of::<IMAGE_RESOURCE_DIRECTORY_ENTRY>();
		let entries_offset = offset as usize + mem::size_of::<IMAGE_RESOURCE_DIRECTORY>();
		if entries_size > resources.section.len() - entries_offset {
			return Err(Error::Bounds);
		}
		Ok(Directory { resources, image })
	}
	/// Gets the resources.
	pub fn resources(&self) -> Resources<'a> {
		self.resources
	}
	/// Gets the underlying resource directory image.
	pub fn image(&self) -> &'a IMAGE_RESOURCE_DIRECTORY {
		self.image
	}
	/// Gets the directory entries.
	pub fn entries(&self) -> Entries<'a, impl Clone + FnMut(&'a IMAGE_RESOURCE_DIRECTORY_ENTRY) -> DirectoryEntry<'a>> {
		// Validated by constructor
		let slice = unsafe {
			let p = (self.image as *const IMAGE_RESOURCE_DIRECTORY).offset(1) as *const IMAGE_RESOURCE_DIRECTORY_ENTRY;
			let len = self.image.NumberOfNamedEntries as usize + self.image.NumberOfIdEntries as usize;
			slice::from_raw_parts(p, len)
		};
		let resources = self.resources;
		slice.iter().map(move |image| DirectoryEntry { resources, image })
	}
	/// Gets the named entries in this directory.
	///
	/// Note that while it would be a violation of the format spec, there's no strict safety guarantee that these are only named entries.
	pub fn named_entries(&self) -> Entries<'a, impl Clone + FnMut(&'a IMAGE_RESOURCE_DIRECTORY_ENTRY) -> DirectoryEntry<'a>> {
		// Validated by constructor
		let slice = unsafe {
			// Named entries come first in the array (see chapter "PE File Resources" in "Peering Inside the PE: A Tour of the Win32 Portable Executable File Format")
			let p = (self.image as *const IMAGE_RESOURCE_DIRECTORY).offset(1) as *const IMAGE_RESOURCE_DIRECTORY_ENTRY;
			let len = self.image.NumberOfNamedEntries as usize;
			slice::from_raw_parts(p, len)
		};
		let resources = self.resources;
		slice.iter().map(move |image| DirectoryEntry { resources, image })
	}
	/// Gets the id entries in this directory.
	///
	/// Note that while it would be a violation of the format spec, there's no strict safety guarantee that these are only id entries.
	pub fn id_entries(&self) -> Entries<'a, impl Clone + FnMut(&'a IMAGE_RESOURCE_DIRECTORY_ENTRY) -> DirectoryEntry<'a>> {
		// Validated by the constructor
		let slice = unsafe {
			// Id entries come last in the array
			let p = (self.image as *const IMAGE_RESOURCE_DIRECTORY).offset(1 + self.image.NumberOfNamedEntries as isize) as *const IMAGE_RESOURCE_DIRECTORY_ENTRY;
			let len = self.image.NumberOfIdEntries as usize;
			slice::from_raw_parts(p, len)
		};
		let resources = self.resources;
		slice.iter().map(move |image| DirectoryEntry { resources, image })
	}
	/// Filesystem consistency check.
	///
	/// Simply walks the filesystem checking all references are valid.
	pub fn fsck(&self) -> Result<()> {
		self.entries().try_for_each(|e| e.fsck())
	}
}
impl<'a> fmt::Debug for Directory<'a> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_struct("Directory")
			.field("entries", &self.entries())
			.finish()
	}
}

//----------------------------------------------------------------

/// Iterator over entries in a directory.
pub type Entries<'a, F> = iter::Map<slice::Iter<'a, IMAGE_RESOURCE_DIRECTORY_ENTRY>, F>;

//----------------------------------------------------------------

/// Represents a resource name.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", serde(untagged))]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub enum Name<'a> {
	/// Resource ID.
	///
	/// Technically allows `u32` ids, but some Windows APIs will be unable to use resources with an id which isn't `u16`.
	Id(u32),
	/// UTF-16 named resource.
	Str(&'a WideStr),
}
impl<'a> From<u16> for Name<'a> {
	fn from(id: u16) -> Name<'a> {
		Name::Id(id as u32)
	}
}
impl<'a> From<&'a WideStr> for Name<'a> {
	fn from(ws: &'a WideStr) -> Name<'a> {
		Name::Str(ws)
	}
}

//----------------------------------------------------------------

/// Data or directory entry.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "serde", serde(untagged))]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub enum Entry<'a> {
	Directory(Directory<'a>),
	DataEntry(DataEntry<'a>),
}
impl<'a> Entry<'a> {
	/// Returns some if the entry is a directory.
	pub fn dir(self) -> Option<Directory<'a>> {
		match self {
			Entry::Directory(dir) => Some(dir),
			Entry::DataEntry(_) => None,
		}
	}
	/// Returns some if the entry is a data entry.
	pub fn data(self) -> Option<DataEntry<'a>> {
		match self {
			Entry::Directory(_) => None,
			Entry::DataEntry(data) => Some(data),
		}
	}
}

//----------------------------------------------------------------

/// Directory child entry.
///
/// Contains a name and a reference to the associated data or directory entry.
#[derive(Copy, Clone)]
pub struct DirectoryEntry<'a> {
	resources: Resources<'a>,
	image: &'a IMAGE_RESOURCE_DIRECTORY_ENTRY,
}
impl<'a> DirectoryEntry<'a> {
	/// Gets the resources.
	pub fn resources(&self) -> Resources<'a> {
		self.resources
	}
	/// Gets the underlying resource directory entry image.
	pub fn image(&self) -> &'a IMAGE_RESOURCE_DIRECTORY_ENTRY {
		self.image
	}
	/// Gets the name for this entry.
	pub fn name(&self) -> Result<Name<'a>> {
		if self.image.Name & 0x80000000 != 0 {
			let offset = self.image.Name & !0x80000000;
			let name = self.resources.slice_ws(offset)?;
			Ok(Name::Str(name))
		}
		else {
			// TODO: What if this doesn't fit in u16...
			Ok(Name::Id(self.image.Name))
		}
	}
	/// Returns if this entry is a directory.
	pub fn is_dir(&self) -> bool {
		self.image.Offset & 0x80000000 != 0
	}
	/// Returns the directory or data entry for this entry.
	pub fn entry(&self) -> Result<Entry<'a>> {
		if self.is_dir() {
			let offset = self.image.Offset & !0x80000000;
			Directory::try_from(self.resources, offset).map(Entry::Directory)
		}
		else {
			let offset = self.image.Offset;
			DataEntry::try_from(self.resources, offset).map(Entry::DataEntry)
		}
	}
	/// Filesystem consistency check.
	///
	/// Simply walks the filesystem checking all references are valid.
	pub fn fsck(&self) -> Result<()> {
		self.name()?;
		match self.entry()? {
			Entry::Directory(dir) => dir.fsck(),
			Entry::DataEntry(data) => data.fsck(),
		}
	}
}
impl<'a> fmt::Debug for DirectoryEntry<'a> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_struct("DirectoryEntry")
			.field("name", &format_args!("{:?}", self.name()))
			.field("entry", &if self.is_dir() { "Directory(..)" } else { "DataEntry(..)" })
			.finish()
	}
}

//----------------------------------------------------------------

/// Data entry.
#[derive(Copy, Clone)]
pub struct DataEntry<'a> {
	resources: Resources<'a>,
	image: &'a IMAGE_RESOURCE_DATA_ENTRY,
}
impl<'a> DataEntry<'a> {
	fn try_from(resources: Resources<'a>, offset: u32) -> Result<DataEntry<'a>> {
		let image = resources.slice(offset)?;
		Ok(DataEntry { resources, image })
	}
	/// Gets the resources.
	pub fn resources(&self) -> Resources<'a> {
		self.resources
	}
	/// Gets the underlying resource data entry image.
	pub fn image(&self) -> &'a IMAGE_RESOURCE_DATA_ENTRY {
		self.image
	}
	/// Gets the actual data.
	pub fn bytes(&self) -> Result<&'a [u8]> {
		let start = u32::checked_sub(self.image.OffsetToData, self.resources.dir.VirtualAddress).ok_or(Error::Overflow)?;
		let end = u32::checked_add(start, self.image.Size).ok_or(Error::Overflow)?;
		self.resources.section.get(start as usize..end as usize).ok_or(Error::Bounds)
	}
	/// Gets the data size.
	pub fn size(&self) -> usize {
		self.image.Size as usize
	}
	/// Gets the code page.
	pub fn code_page(&self) -> u32 {
		self.image.CodePage
	}
	/// Filesystem consistency check.
	///
	/// Simply walks the filesystem checking all references are valid.
	pub fn fsck(&self) -> Result<()> {
		self.bytes()?;
		Ok(())
	}
}
impl<'a> fmt::Debug for DataEntry<'a> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_struct("DataEntry")
			.field("data.len", &self.image.Size)
			.finish()
	}
}

//----------------------------------------------------------------

/*
	"resources": {
		"version_info": { .. },
		"manifest": "<xml>",
		"root": [
			{
				"name": 12,
				"directory": [
					{
						"name": "IMPORTANT",
						"data": {
							size: 1234,
							code_page: 65001,
							bytes: "base64encoded=",
						}
					}
				]
			}
		]
	}
*/

#[cfg(feature = "serde")]
mod serde {
	use util::serde_helper::*;
	use super::{Resources, Directory, DirectoryEntry, DataEntry};

	impl<'a> Serialize for Resources<'a> {
		fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
			let mut state = serializer.serialize_struct("Resources", 3)?;
			state.serialize_field("version_info", &self.version_info().ok())?;
			state.serialize_field("manifest", &self.manifest().ok())?;
			state.serialize_field("root", &self.root().ok())?;
			state.end()
		}
	}
	impl<'a> Serialize for Directory<'a> {
		fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
			serializer.collect_seq(self.entries())
		}
	}
	impl<'a> Serialize for DirectoryEntry<'a> {
		fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
			let mut state = serializer.serialize_struct("DirectoryEntry", 2)?;
			state.serialize_field("name", &self.name().ok())?;
			state.serialize_field(if self.is_dir() { "directory" } else { "data" }, &self.entry().ok())?;
			state.end()
		}
	}
	impl<'a> Serialize for DataEntry<'a> {
		fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
			let is_human_readable = serializer.is_human_readable();
			let mut state = serializer.serialize_struct("DataEntry", 3)?;
			state.serialize_field("size", &self.size())?;
			state.serialize_field("code_page", &self.code_page())?;
			#[cfg(feature = "data-encoding")]
			(if is_human_readable {
				let string = self.bytes().map(|bytes| ::data_encoding::BASE64.encode(bytes));
				state.serialize_field("bytes", &string.as_ref().ok())
			}
			else {
				state.serialize_field("bytes", &self.bytes().ok())
			})?;
			#[cfg(not(feature = "data-encoding"))]
			state.serialize_field("bytes", &self.bytes().ok())?;
			state.end()
		}
	}
}

//----------------------------------------------------------------

#[cfg(test)]
pub(crate) fn test(resources: Resources<'_>) -> Result<()> {
	fn test_dir(dir: Directory<'_>) {
		let _ = format!("{}", dir);
		let _ = format!("{:?}", dir);

		for entry in dir.entries() {
			let _ = format!("{:?}\n{:?}", entry.name(), entry);

			// Check consistency in id vs named entries
			if let Ok(name) = entry.name() {
				let mut id_entries;
				let mut named_entries;
				let mut entries: &mut Iterator<Item = _> = match name {
					Name::Id(_) => { id_entries = dir.id_entries(); &mut id_entries },
					Name::Str(_) => { named_entries = dir.named_entries(); &mut named_entries },
				};
				assert!((&mut entries).any(|entry| entry.name() == Ok(name)));
			}

			// Inspect the entry recursively
			match entry.entry() {
				Ok(Entry::DataEntry(data)) => {
					assert!(!entry.is_dir());
					let _ = format!("{:?}", data);
					let _size = data.size();
					let _code_page = data.code_page();
					let _bytes = data.bytes();
				},
				Ok(Entry::Directory(dir)) => {
					assert!(entry.is_dir());
					let _ = test_dir(dir);
				},
				Err(_) => (),
			}
		}
	}
	let _ = resources.fsck();
	println!("{}", resources);
	if let Ok(version_info) = resources.version_info() {
		self::version_info::test(version_info)
	}
	resources.root().map(test_dir)
}