Owner
stringclasses 774
values | Repo
stringclasses 979
values | SolutionFilePath
stringlengths 32
160
| ProjectFilePath
stringlengths 47
196
| FilePath
stringlengths 43
230
| Namespace
stringlengths 5
182
⌀ | ClassDeclaration
stringlengths 2
78
| ClassFields
stringlengths 2
458k
| UsingStatements
stringlengths 9
3.14k
| TestFramework
stringclasses 4
values | LanguageFramework
stringclasses 236
values | ClassBody
stringlengths 100
627k
| ClassBodyStartPos
int64 16
176k
| ClassBodyEndPos
int64 179
636k
| SourceBody
stringlengths 32
3.67M
⌀ |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\AsmResolver.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\Collections\BitListTest.cs | AsmResolver.Tests.Collections
| BitListTest | [] | ['System.Linq', 'AsmResolver.Collections', 'Xunit'] | xUnit | net8.0 | public class BitListTest
{
[Fact]
public void Add()
{
var list = new BitList
{
true,
false,
true,
true,
false,
};
Assert.Equal(new[]
{
true,
false,
true,
true,
false
}, list.ToArray());
}
[Fact]
public void Insert()
{
var list = new BitList
{
true,
false,
true,
true,
false,
};
list.Insert(1, true);
Assert.Equal(new[]
{
true,
true,
false,
true,
true,
false
}, list.ToArray());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void InsertIntoLarge(bool parity)
{
var list = new BitList();
for (int i = 0; i < 100; i++)
list.Add(i % 2 == 0 == parity);
list.Insert(0, !parity);
Assert.Equal(101, list.Count);
bool[] expected = Enumerable.Range(0, 101).Select(i => i % 2 == 1 == parity).ToArray();
Assert.Equal(expected, list.ToArray());
}
[Fact]
public void RemoveAt()
{
var list = new BitList
{
true,
false,
true,
true,
false,
};
list.RemoveAt(3);
Assert.Equal(new[]
{
true,
false,
true,
false,
}, list.ToArray());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void RemoveAtLarge(bool parity)
{
var list = new BitList();
for (int i = 0; i < 100; i++)
list.Add(i % 2 == 0 == parity);
list.RemoveAt(0);
Assert.Equal(99, list.Count);
bool[] expected = Enumerable.Range(0, 99).Select(i => i % 2 == 1 == parity).ToArray();
Assert.Equal(expected, list.ToArray());
}
} | 116 | 2,607 | using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace AsmResolver.Collections
{
/// <summary>
/// Represents a bit vector that can be resized dynamically.
/// </summary>
public class BitList : IList<bool>
{
private const int WordSize = sizeof(int) * 8;
private uint[] _words;
private int _version;
/// <summary>
/// Creates a new bit list.
/// </summary>
public BitList()
{
_words = new uint[1];
}
/// <summary>
/// Creates a new bit list.
/// </summary>
/// <param name="capacity">The initial number of bits that the buffer should at least be able to store.</param>
public BitList(int capacity)
{
_words = new uint[((uint) capacity).Align(WordSize)];
}
/// <inheritdoc />
public int Count
{
get;
private set;
}
/// <inheritdoc />
public bool IsReadOnly => false;
/// <inheritdoc />
public bool this[int index]
{
get
{
if (index < 0 || index >= Count)
throw new IndexOutOfRangeException();
(int wordIndex, int bitIndex) = SplitWordBitIndex(index);
return (_words[wordIndex] >> bitIndex & 1) != 0;
}
set
{
if (index < 0 || index >= Count)
throw new IndexOutOfRangeException();
(int wordIndex, int bitIndex) = SplitWordBitIndex(index);
_words[wordIndex] = (_words[wordIndex] & ~(1u << bitIndex)) | (value ? 1u << bitIndex : 0u);
_version++;
}
}
private static (int wordIndex, int bitIndex) SplitWordBitIndex(int index)
{
int wordIndex = Math.DivRem(index, WordSize, out int offset);
return (wordIndex, offset);
}
/// <inheritdoc />
public void Add(bool item)
{
EnsureCapacity(Count + 1);
Count++;
this[Count - 1] = item;
_version++;
}
/// <inheritdoc />
public void Clear() => Count = 0;
/// <inheritdoc />
public bool Contains(bool item) => IndexOf(item) != -1;
/// <inheritdoc />
public void CopyTo(bool[] array, int arrayIndex)
{
for (int i = 0; i < Count; i++)
array[arrayIndex + i] = this[i];
}
/// <inheritdoc />
public bool Remove(bool item)
{
int index = IndexOf(item);
if (index == -1)
return false;
RemoveAt(index);
return true;
}
/// <inheritdoc />
public int IndexOf(bool item)
{
for (int i = 0; i < Count; i++)
{
(int wordIndex, int bitIndex) = SplitWordBitIndex(i);
if ((_words[wordIndex] >> bitIndex & 1) != 0 == item)
return i;
}
return -1;
}
/// <inheritdoc />
public void Insert(int index, bool item)
{
if (index < 0 || index > Count)
throw new IndexOutOfRangeException();
EnsureCapacity(Count++);
(int wordIndex, int bitIndex) = SplitWordBitIndex(index);
uint carry = _words[wordIndex] & (1u << (WordSize - 1));
// Insert bit into current word.
uint lowerMask = (1u << bitIndex) - 1;
uint upperMask = ~lowerMask;
_words[wordIndex] = (_words[wordIndex] & upperMask) << 1 // Shift left-side of the bit index by one
| (item ? 1u << bitIndex : 0u) // Insert bit.
| (_words[wordIndex] & lowerMask); // Keep right-side of the bit.
for (int i = wordIndex + 1; i < _words.Length; i++)
{
uint nextCarry = _words[i] & (1u << (WordSize - 1));
_words[i] = (_words[i] << 1) | (carry >> (WordSize - 1));
carry = nextCarry;
}
_version++;
}
/// <inheritdoc />
public void RemoveAt(int index)
{
Count--;
(int wordIndex, int bitIndex) = SplitWordBitIndex(index);
// Note we check both word count and actual bit count. Words in the buffer might contain garbage data for
// every bit index i >= Count. Also, there might be exactly enough words allocated for Count bits, i.e.
// there might not be a "next" word.
uint borrow = wordIndex + 1 < _words.Length && ((uint) index).Align(WordSize) < Count
? _words[wordIndex + 1] & 1
: 0;
uint lowerMask = (1u << bitIndex) - 1;
uint upperMask = ~((1u << (bitIndex + 1)) - 1);
_words[wordIndex] = (_words[wordIndex] & upperMask) >> 1 // Shift left-side of the bit index by one
| (_words[wordIndex] & lowerMask) // Keep right-side of the bit.
| borrow << (WordSize - 1); // Copy first bit of next word into last bit of current.
for (int i = wordIndex + 1; i < _words.Length; i++)
{
uint nextBorrow = i + 1 < _words.Length && ((uint) index).Align(WordSize) < Count
? _words[i + 1] & 1
: 0;
_words[i] = (_words[i] >> 1) | (borrow << (WordSize - 1));
borrow = nextBorrow;
}
_version++;
}
/// <summary>
/// Ensures the provided number of bits can be stored in the bit list.
/// </summary>
/// <param name="capacity">The number of bits to store in the list.</param>
public void EnsureCapacity(int capacity)
{
if (capacity < WordSize * _words.Length)
return;
int newWordCount = (int) (((uint) capacity).Align(WordSize) / 8);
Array.Resize(ref _words, newWordCount);
}
/// <summary>
/// Returns an enumerator for all bits in the bit vector.
/// </summary>
/// <returns>The enumerator.</returns>
public Enumerator GetEnumerator() => new(this);
/// <inheritdoc />
IEnumerator<bool> IEnumerable<bool>.GetEnumerator() => GetEnumerator();
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Represents an enumerator that iterates over all bits in a bit list.
/// </summary>
public struct Enumerator : IEnumerator<bool>
{
private readonly BitList _list;
private readonly int _version;
private int _index = -1;
/// <summary>
/// Creates a new bit enumerator.
/// </summary>
/// <param name="list">The list to enumerate.</param>
public Enumerator(BitList list)
{
_version = list._version;
_list = list;
}
/// <inheritdoc />
public bool MoveNext()
{
if (_version != _list._version)
throw new InvalidOperationException("Collection was modified.");
if (_index >= _list.Count)
return false;
_index++;
return true;
}
/// <inheritdoc />
public void Reset() => _index = -1;
/// <inheritdoc />
public bool Current => _list[_index];
/// <inheritdoc />
object IEnumerator.Current => Current;
/// <inheritdoc />
public void Dispose()
{
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\AsmResolver.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\Collections\LazyListTest.cs | AsmResolver.Tests.Collections
| LazyListTest | ['public bool InitializeMethodCalled\n {\n get;\n private set;\n }', 'private readonly IList<int> _items;'] | ['System.Collections.Generic', 'AsmResolver.Collections', 'Xunit'] | xUnit | net8.0 | public class LazyListTest
{
private class DummyLazyList : LazyList<int>
{
private readonly IList<int> _items;
public bool InitializeMethodCalled
{
get;
private set;
}
public DummyLazyList(IList<int> items)
{
_items = items;
}
protected override void Initialize()
{
foreach (var item in _items)
Items.Add(item);
InitializeMethodCalled = true;
}
}
[Fact]
public void EnumeratorShouldEnumerateAllItems()
{
var actualItems = new[]
{
1,
2,
3
};
var list = new DummyLazyList(actualItems);
Assert.Equal(actualItems, list);
}
[Fact]
public void EnumeratorWithNoMoveNextShouldNotInitializeList()
{
var actualItems = new[]
{
1,
2,
3
};
var list = new DummyLazyList(actualItems);
var enumerator = list.GetEnumerator();
Assert.False(list.InitializeMethodCalled);
}
} | 131 | 1,487 | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace AsmResolver.Collections
{
/// <summary>
/// Provides a base for lists that are lazy initialized.
/// </summary>
/// <typeparam name="TItem">The type of elements the list stores.</typeparam>
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
public abstract class LazyList<TItem> : IList<TItem>
{
private readonly List<TItem> _items;
/// <summary>
/// Creates a new, empty, uninitialized list.
/// </summary>
public LazyList()
{
_items = new List<TItem>();
}
/// <summary>
/// Creates a new, empty, uninitialized list.
/// </summary>
/// <param name="capacity">The initial number of elements the list can store.</param>
public LazyList(int capacity)
{
_items = new List<TItem>(capacity);
}
/// <inheritdoc />
public TItem this[int index]
{
get
{
EnsureIsInitialized();
return Items[index];
}
set
{
lock (_items)
{
EnsureIsInitialized();
OnSetItem(index, value);
}
}
}
/// <inheritdoc />
public virtual int Count
{
get
{
EnsureIsInitialized();
return Items.Count;
}
}
/// <summary>
/// Gets or sets the total number of elements the list can contain before it has to resize its internal buffer.
/// </summary>
public int Capacity
{
get => _items.Capacity;
set => _items.Capacity = value;
}
/// <inheritdoc />
public bool IsReadOnly => false;
/// <summary>
/// Gets a value indicating the list is initialized or not.
/// </summary>
protected bool IsInitialized
{
get;
private set;
}
/// <summary>
/// Gets the underlying list.
/// </summary>
protected IList<TItem> Items => _items;
/// <summary>
/// Initializes the list. This method is called in a thread-safe manner.
/// </summary>
protected abstract void Initialize();
/// <summary>
/// Performs any final adjustments to the collection after all initial items were added to the underlying list.
/// </summary>
/// <remarks>
/// Upon calling this method, the <see cref="IsInitialized"/> has already been set to <c>true</c>, but the
/// initialization lock has not been released yet. This means that any element in the list is guaranteed
/// to be still in its initial state. It is therefore safe to access elements, as well as adding or removing
/// items from <see cref="Items"/>.
/// </remarks>
protected virtual void PostInitialize()
{
}
private void EnsureIsInitialized()
{
if (!IsInitialized)
{
lock (_items)
{
if (!IsInitialized)
{
Initialize();
IsInitialized = true;
PostInitialize();
}
}
}
}
/// <inheritdoc />
public void Add(TItem item) => Insert(Count, item);
/// <summary>
/// Appends the elements of a collection to the end of the <see cref="LazyList{TItem}"/>.
/// </summary>
/// <param name="items">The items to append.</param>
public void AddRange(IEnumerable<TItem> items) => InsertRange(Count, items);
/// <inheritdoc />
public void Clear()
{
lock (_items)
{
OnClearItems();
IsInitialized = true;
}
}
/// <inheritdoc />
public bool Contains(TItem item)
{
EnsureIsInitialized();
return Items.Contains(item);
}
/// <inheritdoc />
public void CopyTo(TItem[] array, int arrayIndex)
{
EnsureIsInitialized();
Items.CopyTo(array, arrayIndex);
}
/// <inheritdoc />
public bool Remove(TItem item)
{
lock (_items)
{
EnsureIsInitialized();
int index = Items.IndexOf(item);
if (index == -1)
return false;
OnRemoveItem(index);
}
return true;
}
/// <inheritdoc />
public int IndexOf(TItem item)
{
EnsureIsInitialized();
return Items.IndexOf(item);
}
/// <inheritdoc />
public void Insert(int index, TItem item)
{
lock (_items)
{
EnsureIsInitialized();
OnInsertItem(index, item);
}
}
/// <summary>
/// Inserts the elements of a collection into the <see cref="LazyList{TItem}"/> at the provided index.
/// </summary>
/// <param name="index">The starting index to insert the items in.</param>
/// <param name="items">The items to insert.</param>
private void InsertRange(int index, IEnumerable<TItem> items)
{
lock (_items)
{
EnsureIsInitialized();
OnInsertRange(index, items);
}
}
/// <inheritdoc />
public void RemoveAt(int index)
{
lock (_items)
{
EnsureIsInitialized();
OnRemoveItem(index);
}
}
/// <summary>
/// The method that gets called upon replacing an item in the list.
/// </summary>
/// <param name="index">The index that is being replaced.</param>
/// <param name="item">The new item.</param>
protected virtual void OnSetItem(int index, TItem item) => _items[index] = item;
/// <summary>
/// The method that gets called upon inserting a new item in the list.
/// </summary>
/// <param name="index">The index where the item is inserted at.</param>
/// <param name="item">The new item.</param>
protected virtual void OnInsertItem(int index, TItem item) => _items.Insert(index, item);
/// <summary>
/// The method that gets called upon inserting a collection of new items in the list.
/// </summary>
/// <param name="index">The index where the item is inserted at.</param>
/// <param name="items">The new items.</param>
protected virtual void OnInsertRange(int index, IEnumerable<TItem> items) => _items.InsertRange(index, items);
/// <summary>
/// The method that gets called upon removing an item.
/// </summary>
/// <param name="index">The index of the element to remove.</param>
protected virtual void OnRemoveItem(int index) => _items.RemoveAt(index);
/// <summary>
/// The method that gets called upon clearing the entire list.
/// </summary>
protected virtual void OnClearItems() => _items.Clear();
/// <summary>
/// Returns an enumerator that enumerates the lazy list.
/// </summary>
/// <returns>The enumerator.</returns>
/// <remarks>
/// This enumerator only ensures the list is initialized upon calling the <see cref="Enumerator.MoveNext"/> method.
/// </remarks>
public Enumerator GetEnumerator() => new(this);
/// <inheritdoc />
IEnumerator<TItem> IEnumerable<TItem>.GetEnumerator() => GetEnumerator();
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Represents an enumerator that enumerates all items in a lazy initialized list.
/// </summary>
/// <remarks>
/// The enumerator only initializes the list when it is needed. If no calls to <see cref="MoveNext"/> were
/// made, and the lazy list was not initialized yet, it will remain uninitialized.
/// </remarks>
public struct Enumerator : IEnumerator<TItem?>
{
private readonly LazyList<TItem> _list;
private List<TItem>.Enumerator _enumerator;
private bool hasEnumerator;
/// <summary>
/// Creates a new instance of the enumerator.
/// </summary>
/// <param name="list">The list to enumerate.</param>
public Enumerator(LazyList<TItem> list)
{
_list = list;
_enumerator = default;
hasEnumerator = false;
}
/// <inheritdoc />
public TItem? Current => hasEnumerator ? _enumerator.Current : default;
/// <inheritdoc />
object? IEnumerator.Current => Current;
/// <inheritdoc />
public bool MoveNext()
{
if (!hasEnumerator)
{
_list.EnsureIsInitialized();
_enumerator = _list._items.GetEnumerator();
hasEnumerator = true;
}
return _enumerator.MoveNext();
}
/// <inheritdoc />
public void Reset() => throw new NotSupportedException();
/// <inheritdoc />
public void Dispose()
{
if (hasEnumerator)
_enumerator.Dispose();
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\AsmResolver.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\Collections\RefListTest.cs | AsmResolver.Tests.Collections
| RefListTest | [] | ['System', 'AsmResolver.Collections', 'Xunit'] | xUnit | net8.0 | public class RefListTest
{
[Fact]
public void EmptyList()
{
Assert.Empty(new RefList<int>());
}
[Fact]
public void SetCapacityToCount()
{
var list = new RefList<int>
{
1,
2,
3
};
list.Capacity = 3;
Assert.True(list.Capacity >= 3);
}
[Fact]
public void SetCapacityToLargerThanCount()
{
var list = new RefList<int>
{
1,
2,
3
};
list.Capacity = 6;
Assert.True(list.Capacity >= 6);
}
[Fact]
public void SetCapacityToSmallerThanCountShouldThrow()
{
var list = new RefList<int>
{
1,
2,
3
};
Assert.Throws<ArgumentException>(() => list.Capacity = 2);
}
[Fact]
public void AddItemShouldUpdateVersion()
{
var list = new RefList<int>();
int version = list.Version;
list.Add(1);
Assert.Equal(1, Assert.Single(list));
Assert.NotEqual(version, list.Version);
}
[Fact]
public void InsertItemShouldUpdateVersion()
{
var list = new RefList<int> { 1, 2, 3 };
int version = list.Version;
list.Insert(1, 4);
Assert.Equal(new[] { 1, 4, 2, 3 }, list);
Assert.NotEqual(version, list.Version);
}
[Fact]
public void RemoveItemShouldUpdateVersion()
{
var list = new RefList<int> { 1, 2, 3 };
int version = list.Version;
list.RemoveAt(1);
Assert.Equal(new[] { 1, 3 }, list);
Assert.NotEqual(version, list.Version);
}
[Fact]
public void UpdateElementFromRefShouldUpdateList()
{
var list = new RefList<int> { 1, 2, 3 };
ref int element = ref list.GetElementRef(1);
element = 1337;
Assert.Equal(new[] { 1, 1337, 3 }, list);
}
} | 111 | 2,424 | using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace AsmResolver.Collections
{
/// <summary>
/// Provides an implementation of a collection for which the raw elements can be accessed by-reference.
/// This allows for dynamically sized lists that work on mutable structs.
/// </summary>
/// <typeparam name="T">The type of elements to store.</typeparam>
/// <remarks>
/// This list should be regarded as a mutable array that is not thread-safe.
/// </remarks>
public class RefList<T> : ICollection, IList<T>, IReadOnlyList<T>
where T : struct
{
/// <summary>
/// Gets the default capacity of a ref-list.
/// </summary>
public const int DefaultCapacity = 4;
private T[] _items;
private int _count;
private int _version;
/// <summary>
/// Creates a new empty list with the default capacity.
/// </summary>
public RefList()
: this(DefaultCapacity)
{
}
/// <summary>
/// Creates a new empty list with the provided capacity.
/// </summary>
/// <param name="capacity">The capacity of the list.</param>
public RefList(int capacity)
{
_items = new T[capacity];
}
/// <inheritdoc cref="ICollection{T}.Count" />
public int Count => _count;
/// <summary>
/// Gets or sets the total number of elements that the underlying array can store.
/// </summary>
public int Capacity
{
get => _items.Length;
set
{
if (value == _items.Length)
return;
if (value < _count)
throw new ArgumentException("Capacity must be equal or larger than the current number of elements in the list.");
EnsureCapacity(value);
IncrementVersion();
}
}
/// <summary>
/// Gets a number indicating the current version of the list.
/// </summary>
/// <remarks>
/// This number is incremented each time the underlying array is resized or when an element is replaced.
/// It can also be used to verify that the reference returned by <see cref="GetElementRef(int, out int)"/> is
/// still referencing an element in the current array.
/// </remarks>
public int Version => _version;
/// <inheritdoc />
bool ICollection<T>.IsReadOnly => false;
/// <inheritdoc />
bool ICollection.IsSynchronized => false;
/// <inheritdoc />
object ICollection.SyncRoot => this;
/// <summary>
/// Gets or sets an individual element within the list.
/// </summary>
/// <param name="index">The index of the element to access.</param>
/// <exception cref="IndexOutOfRangeException">
/// Occurs when <paramref name="index"/> is not a valid index within the array.
/// </exception>
public T this[int index]
{
get
{
AssertIsValidIndex(index);
return _items[index];
}
set
{
AssertIsValidIndex(index);
_items[index] = value;
IncrementVersion();
}
}
/// <summary>
/// Gets an element within the list by reference.
/// </summary>
/// <param name="index">The index of the element to access.</param>
/// <returns>A reference to the element.</returns>
/// <exception cref="IndexOutOfRangeException">
/// Occurs when <paramref name="index"/> is not a valid index within the array.
/// </exception>
public ref T GetElementRef(int index)
{
AssertIsValidIndex(index);
return ref _items[index];
}
/// <summary>
/// Gets an element within the list by reference.
/// </summary>
/// <param name="index">The index of the element to access.</param>
/// <param name="version">The version of the list upon obtaining the reference.</param>
/// <returns>A reference to the element.</returns>
/// <exception cref="IndexOutOfRangeException">
/// Occurs when <paramref name="index"/> is not a valid index within the array.
/// </exception>
public ref T GetElementRef(int index, out int version)
{
AssertIsValidIndex(index);
version = _version;
return ref _items[index];
}
/// <summary>
/// Adds an element to the end of the list.
/// </summary>
/// <param name="item">The element.</param>
public void Add(in T item)
{
EnsureCapacity(_count + 1);
_items[_count] = item;
_count++;
IncrementVersion();
}
/// <inheritdoc />
void ICollection<T>.Add(T item) => Add(item);
/// <inheritdoc />
public void Clear()
{
Array.Clear(_items, 0, _items.Length);
_count = 0;
IncrementVersion();
}
/// <inheritdoc />
bool ICollection<T>.Contains(T item) => IndexOf(item) >= 0;
/// <summary>
/// Determines whether an item is present in the reference list.
/// </summary>
/// <param name="item">The item.</param>
/// <returns><c>true</c> if the element is present, <c>false</c> otherwise.</returns>
public bool Contains(in T item) => IndexOf(item) >= 0;
/// <inheritdoc />
public void CopyTo(T[] array, int arrayIndex) => _items.CopyTo(array, arrayIndex);
/// <inheritdoc />
public void CopyTo(Array array, int index) => _items.CopyTo(array, index);
/// <summary>
/// Removes an element from the list.
/// </summary>
/// <param name="item">The element to remove.</param>
/// <returns><c>true</c> if the element was removed successfully, <c>false</c> otherwise.</returns>
public bool Remove(in T item)
{
int index = IndexOf(item);
if (index > 0)
{
RemoveAt(index);
return true;
}
return false;
}
/// <inheritdoc />
bool ICollection<T>.Remove(T item) => Remove(item);
/// <summary>
/// Determines the first index within the list that contains the provided element.
/// </summary>
/// <param name="item">The element to search.</param>
/// <returns>The index, or -1 if the element is not present in the list.</returns>
public int IndexOf(in T item) => Array.IndexOf(_items, item, 0, _count);
/// <summary>
/// Inserts an element into the list at the provided index.
/// </summary>
/// <param name="index">The index to insert into.</param>
/// <param name="item">The element to insert.</param>
public void Insert(int index, in T item)
{
EnsureCapacity(_count + 1);
if (index < _count)
Array.Copy(_items, index, _items, index + 1, _count - index);
_items[index] = item;
_count++;
IncrementVersion();
}
/// <inheritdoc />
void IList<T>.Insert(int index, T item) => Insert(index, item);
/// <inheritdoc />
public int IndexOf(T item) => Array.IndexOf(_items, item, 0, _count);
/// <summary>
/// Removes a single element from the list at the provided index.
/// </summary>
/// <param name="index">The index of the element to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">Occurs when the provided index is invalid.</exception>
public void RemoveAt(int index)
{
if (index < 0 || index >= _count)
throw new ArgumentOutOfRangeException(nameof(index));
_count--;
if (index < _count)
Array.Copy(_items, index + 1, _items, index, _count - index);
_items[_count] = default!;
IncrementVersion();
}
/// <summary>
/// Returns an enumerator that iterates all elements in the list.
/// </summary>
public Enumerator GetEnumerator() => new(this);
/// <inheritdoc />
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private void AssertIsValidIndex(int index)
{
if (index < 0 || index >= Count)
throw new IndexOutOfRangeException();
}
private void EnsureCapacity(int requiredCount)
{
if (_items.Length >= requiredCount)
return;
int newCapacity = _items.Length == 0 ? 1 : _items.Length * 2;
if (newCapacity < requiredCount)
newCapacity = requiredCount;
Array.Resize(ref _items, newCapacity);
}
private void IncrementVersion()
{
unchecked
{
_version++;
}
}
/// <summary>
/// Provides an implementation for an enumerator that iterates elements in a ref-list.
/// </summary>
public struct Enumerator : IEnumerator<T>
{
private readonly RefList<T> _list;
private readonly int _version;
private int _index;
/// <summary>
/// Creates a new instance of a ref-list enumerator.
/// </summary>
/// <param name="list">The list to enumerate.</param>
public Enumerator(RefList<T> list)
{
_list = list;
_version = list._version;
_index = -1;
}
/// <inheritdoc />
public T Current => _index >= 0 && _index < _list._count
? _list[_index]
: default;
/// <inheritdoc />
object IEnumerator.Current => Current;
/// <inheritdoc />
public bool MoveNext()
{
if (_version != _list._version)
throw new InvalidOperationException("Collection was modified.");
_index++;
return _index >= 0 && _index < _list._count;
}
/// <inheritdoc />
public void Reset() => throw new NotSupportedException();
/// <inheritdoc />
void IDisposable.Dispose()
{
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\AsmResolver.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\IO\BinaryStreamReaderTest.cs | AsmResolver.Tests.IO
| BinaryStreamReaderTest | [] | ['System', 'System.IO', 'System.Text', 'AsmResolver.IO', 'Xunit'] | xUnit | net8.0 | public class BinaryStreamReaderTest
{
[Fact]
public void EmptyArray()
{
var reader = new BinaryStreamReader(new byte[0]);
Assert.Equal(0u, reader.Length);
Assert.Throws<EndOfStreamException>(() => reader.ReadByte());
Assert.Equal(0, reader.ReadBytes(new byte[10], 0, 10));
}
[Fact]
public void ReadByte()
{
var reader = new BinaryStreamReader(new byte[]
{
0x80,
0x80
});
Assert.Equal((byte) 0x80, reader.ReadByte());
Assert.Equal(1u, reader.Offset);
Assert.Equal((sbyte) -128, reader.ReadSByte());
Assert.Throws<EndOfStreamException>(() => reader.ReadByte());
}
[Fact]
public void ReadInt16()
{
var reader = new BinaryStreamReader(new byte[]
{
0x01, 0x80,
0x02, 0x80
});
Assert.Equal((ushort) 0x8001, reader.ReadUInt16());
Assert.Equal(2u, reader.Offset);
Assert.Equal((short) -32766, reader.ReadInt16());
Assert.Equal(4u, reader.Offset);
}
[Fact]
public void ReadInt32()
{
var reader = new BinaryStreamReader(new byte[]
{
0x04, 0x03, 0x02, 0x81,
0x08, 0x07, 0x06, 0x85
});
Assert.Equal(0x81020304u, reader.ReadUInt32());
Assert.Equal(4u, reader.Offset);
Assert.Equal(-2063202552, reader.ReadInt32());
Assert.Equal(8u, reader.Offset);
}
[Fact]
public void ReadInt64()
{
var reader = new BinaryStreamReader(new byte[]
{
0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x80,
0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x88,
});
Assert.Equal(0x8001020304050607ul, reader.ReadUInt64());
Assert.Equal(8u, reader.Offset);
Assert.Equal(-8644366967197856241, reader.ReadInt64());
Assert.Equal(16u, reader.Offset);
}
[Theory]
[InlineData(new byte[] {0x03}, 3)]
[InlineData(new byte[] {0x7f}, 0x7f)]
[InlineData(new byte[] {0x80, 0x80}, 0x80)]
[InlineData(new byte[] {0xAE, 0x57}, 0x2E57)]
[InlineData(new byte[] {0xBF, 0xFF}, 0x3FFF)]
[InlineData(new byte[] {0xC0, 0x00, 0x40, 0x00}, 0x4000)]
[InlineData(new byte[] {0xDF, 0x12, 0x34, 0x56}, 0x1F123456)]
[InlineData(new byte[] {0xDF, 0xFF, 0xFF, 0xFF}, 0x1FFFFFFF)]
public void ReadCompressedUInt32(byte[] data, uint expected)
{
var reader = new BinaryStreamReader(data);
Assert.Equal(expected, reader.ReadCompressedUInt32());
}
[Theory]
[InlineData(new byte[] {0x06}, 3)]
[InlineData(new byte[] {0x7B}, -3)]
[InlineData(new byte[] {0x80, 0x80}, 64)]
[InlineData(new byte[] {0x01}, -64)]
[InlineData(new byte[] {0xC0, 0x00, 0x40, 0x00}, 8192)]
[InlineData(new byte[] {0x80, 0x01}, -8192)]
[InlineData(new byte[] {0xDF, 0xFF, 0xFF, 0xFE}, 0xFFFFFFF)]
[InlineData(new byte[] {0xC0, 0x00, 0x00, 0x01}, -0x10000000)]
public void ReadCompressedInt32(byte[] data, int value)
{
var reader = new BinaryStreamReader(data);
Assert.Equal(value, reader.ReadCompressedInt32());
}
[Theory]
[InlineData("")]
[InlineData("Hello, world!")]
[InlineData("0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789")]
public void ReadBinaryFormatterString(string value)
{
using var stream = new MemoryStream();
var writer = new BinaryWriter(stream, Encoding.UTF8);
writer.Write(value);
var reader = new BinaryStreamReader(stream.ToArray());
Assert.Equal(value, reader.ReadBinaryFormatterString());
}
[Fact]
public void NewForkSubRange()
{
var reader = new BinaryStreamReader(new byte[]
{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
});
var fork = reader.ForkAbsolute(2, 3);
Assert.Equal(2u, fork.StartOffset);
Assert.Equal(2u, fork.Offset);
Assert.Equal(3u, fork.Length);
}
[Fact]
public void NewForkInvalidStart()
{
var reader = new BinaryStreamReader(new byte[]
{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
});
Assert.Throws<ArgumentOutOfRangeException>(() => reader.ForkAbsolute(9, 3));
}
[Fact]
public void NewForkTooLong()
{
var reader = new BinaryStreamReader(new byte[]
{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
});
Assert.Throws<EndOfStreamException>(() => reader.ForkAbsolute(6, 4));
}
[Fact]
public void ForkReadsSameData()
{
var reader = new BinaryStreamReader(new byte[]
{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
});
var fork = reader.ForkAbsolute(0, 2);
Assert.Equal(0x0201, fork.ReadUInt16());
}
[Fact]
public void ForkMovesIndependentOfOriginal()
{
var reader = new BinaryStreamReader(new byte[]
{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
});
var fork = reader.ForkAbsolute(0, 2);
fork.ReadUInt16();
Assert.Equal(0u, reader.Offset);
Assert.Equal(2u, fork.Offset);
}
[Fact]
public void ForkStartAtMiddle()
{
var reader = new BinaryStreamReader(new byte[]
{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
});
var fork = reader.ForkAbsolute(4, 2);
Assert.Equal(0x0605, fork.ReadUInt16());
}
[Fact]
public void ForkOfFork()
{
var reader = new BinaryStreamReader(new byte[]
{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
});
var fork = reader.ForkAbsolute(2, 4);
var fork2 = fork.ForkAbsolute(3, 2);
Assert.Equal(0x04, fork2.ReadByte());
}
} | 131 | 7,233 | using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace AsmResolver.IO
{
/// <summary>
/// Provides methods for reading binary data from a data source.
/// </summary>
[DebuggerDisplay("[{StartOffset}..{EndOffset}) at {Offset} ({RelativeOffset})")]
public struct BinaryStreamReader
{
[ThreadStatic]
private static int[]? _buffer;
/// <summary>
/// Creates a new binary stream reader on the provided data source.
/// </summary>
/// <param name="data">The data to read from.</param>
public BinaryStreamReader(byte[] data)
: this(new ByteArrayDataSource(data))
{
}
/// <summary>
/// Creates a new binary stream reader on the provided data source.
/// </summary>
/// <param name="dataSource">The object to get the data from.</param>
public BinaryStreamReader(IDataSource dataSource)
: this(dataSource, 0, 0, (uint) dataSource.Length)
{
}
/// <summary>
/// Creates a new binary stream reader on the provided data source.
/// </summary>
/// <param name="dataSource">The object to get the data from.</param>
/// <param name="offset">The raw offset to start at.</param>
/// <param name="rva">The relative virtual address associated to the offset.</param>
/// <param name="length">The maximum number of bytes to read.</param>
/// <exception cref="ArgumentNullException">Occurs when <paramref name="dataSource"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Occurs when <paramref name="offset"/> is not a valid offset.</exception>
/// <exception cref="EndOfStreamException">Occurs when too many bytes are specified by <paramref name="length"/>.</exception>
public BinaryStreamReader(IDataSource dataSource, ulong offset, uint rva, uint length)
{
if (dataSource is null)
throw new ArgumentNullException(nameof(dataSource));
if (length > 0)
{
if (!dataSource.IsValidAddress(offset))
throw new ArgumentOutOfRangeException(nameof(offset));
if (!dataSource.IsValidAddress(offset + length - 1))
{
throw new EndOfStreamException(
"Offset and address reach outside of the boundaries of the data source.");
}
}
DataSource = dataSource;
StartOffset = Offset = offset;
StartRva = rva;
Length = length;
}
/// <summary>
/// Gets the data source the reader is reading from.
/// </summary>
public IDataSource DataSource
{
get;
}
/// <summary>
/// Gets the raw offset this reader started from.
/// </summary>
public ulong StartOffset
{
get;
}
/// <summary>
/// Gets the relative virtual address this reader started from.
/// </summary>
public uint StartRva
{
get;
}
/// <summary>
/// Gets the number of bytes that can be read by the reader.
/// </summary>
public uint Length
{
get;
private set;
}
/// <summary>
/// Gets the raw address indicating the end of the stream.
/// </summary>
public ulong EndOffset => StartOffset + Length;
/// <summary>
/// Gets the relative virtual address indicating the end of the stream.
/// </summary>
public ulong EndRva => StartRva + Length;
/// <summary>
/// Gets or sets the current raw offset to read from.
/// </summary>
public ulong Offset
{
get;
set;
}
/// <summary>
/// Gets or sets the current offset relative to the beginning of <see cref="StartOffset"/> to read from.
/// </summary>
public uint RelativeOffset
{
get => (uint) (Offset - StartOffset);
set => Offset = value + StartOffset;
}
/// <summary>
/// Gets the remaining number of bytes that can be read from the stream.
/// </summary>
public uint RemainingLength => Length - RelativeOffset;
/// <summary>
/// Gets or sets the current virtual address (relative to the image base) to read from.
/// </summary>
public uint Rva
{
get => RelativeOffset + StartRva;
set => RelativeOffset = value - StartRva;
}
/// <summary>
/// Gets a value indicating whether the reader is in a valid state.
/// </summary>
public bool IsValid => DataSource is not null;
/// <summary>
/// Determines whether the provided number of bytes can be read from the current position.
/// </summary>
/// <param name="count">The number of bytes to read.</param>
/// <returns><c>true</c> if the provided number of byte can be read, <c>false</c> otherwise.</returns>
public bool CanRead(uint count) => RelativeOffset + count <= Length;
private void AssertCanRead(uint count)
{
if (!CanRead(count))
throw new EndOfStreamException();
}
/// <summary>
/// Peeks a single byte from the input stream.
/// </summary>
/// <returns>The read byte, or <c>-1</c> if no byte could be read.</returns>
public int PeekByte() => CanRead(1)
? DataSource[Offset]
: -1;
/// <summary>
/// Reads a single byte from the input stream, and advances the current offset by one.
/// </summary>
/// <returns>The consumed value.</returns>
public byte ReadByte()
{
AssertCanRead(sizeof(byte));
return DataSource[Offset++];
}
/// <summary>
/// Reads a single unsigned 16-bit integer from the input stream, and advances the current offset by two.
/// </summary>
/// <returns>The consumed value.</returns>
public ushort ReadUInt16()
{
AssertCanRead(2);
ushort value = (ushort) (DataSource[Offset]
| (DataSource[Offset + 1] << 8));
Offset += 2;
return value;
}
/// <summary>
/// Reads a single unsigned 32-bit integer from the input stream, and advances the current offset by four.
/// </summary>
/// <returns>The consumed value.</returns>
public uint ReadUInt32()
{
AssertCanRead(4);
uint value = unchecked((uint) (DataSource[Offset]
| (DataSource[Offset + 1] << 8)
| (DataSource[Offset + 2] << 16)
| (DataSource[Offset + 3] << 24)));
Offset += 4;
return value;
}
/// <summary>
/// Reads a single unsigned 64-bit integer from the input stream, and advances the current offset by eight.
/// </summary>
/// <returns>The consumed value.</returns>
public ulong ReadUInt64()
{
AssertCanRead(8);
ulong value = unchecked((ulong) (DataSource[Offset]
| ( (long) DataSource[Offset + 1] << 8)
| ( (long) DataSource[Offset + 2] << 16)
| ( (long) DataSource[Offset + 3] << 24)
| ( (long) DataSource[Offset + 4] << 32)
| ( (long) DataSource[Offset + 5] << 40)
| ( (long) DataSource[Offset + 6] << 48)
| ( (long) DataSource[Offset + 7] << 56)));
Offset += 8;
return value;
}
/// <summary>
/// Reads a single signed byte from the input stream, and advances the current offset by one.
/// </summary>
/// <returns>The consumed value.</returns>
public sbyte ReadSByte()
{
AssertCanRead(1);
return unchecked((sbyte) DataSource[Offset++]);
}
/// <summary>
/// Reads a single signed 16-bit integer from the input stream, and advances the current offset by two.
/// </summary>
/// <returns>The consumed value.</returns>
public short ReadInt16()
{
AssertCanRead(2);
short value = (short) (DataSource[Offset]
| (DataSource[Offset + 1] << 8));
Offset += 2;
return value;
}
/// <summary>
/// Reads a single signed 32-bit integer from the input stream, and advances the current offset by four.
/// </summary>
/// <returns>The consumed value.</returns>
public int ReadInt32()
{
AssertCanRead(4);
int value = DataSource[Offset]
| (DataSource[Offset + 1] << 8)
| (DataSource[Offset + 2] << 16)
| (DataSource[Offset + 3] << 24);
Offset += 4;
return value;
}
/// <summary>
/// Reads a single signed 64-bit integer from the input stream, and advances the current offset by eight.
/// </summary>
/// <returns>The consumed value.</returns>
public long ReadInt64()
{
AssertCanRead(8);
long value = DataSource[Offset]
| ((long) DataSource[Offset + 1] << 8)
| ((long) DataSource[Offset + 2] << 16)
| ((long) DataSource[Offset + 3] << 24)
| ((long) DataSource[Offset + 4] << 32)
| ((long) DataSource[Offset + 5] << 40)
| ((long) DataSource[Offset + 6] << 48)
| ((long) DataSource[Offset + 7] << 56);
Offset += 8;
return value;
}
/// <summary>
/// Reads a single signed 32-bit single precision floating point number from the input stream, and advances the
/// current offset by four.
/// </summary>
/// <returns>The consumed value.</returns>
public unsafe float ReadSingle()
{
uint raw = ReadUInt32();
return *(float*) &raw;
}
/// <summary>
/// Reads a single signed 64-bit double precision floating point number from the input stream, and advances the
/// current offset by four.
/// </summary>
/// <returns>The consumed value.</returns>
public unsafe double ReadDouble()
{
ulong raw = ReadUInt64();
return *(double*) &raw;
}
/// <summary>
/// Reads a single 128-bit decimal value from the input stream, and advances the current offset by 16.
/// </summary>
/// <returns>The consumed value.</returns>
public decimal ReadDecimal()
{
AssertCanRead(4 * sizeof(int));
_buffer ??= new int[4];
for (int i = 0; i < 4; i++)
_buffer[i] = ReadInt32();
return new decimal(_buffer);
}
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
/// <summary>
/// Attempts to read the provided amount of bytes from the input stream.
/// </summary>
/// <param name="buffer">The buffer that receives the read bytes.</param>
/// <returns>The number of bytes that were read.</returns>
public int ReadBytes(Span<byte> buffer)
{
int actualLength = DataSource.ReadBytes(Offset, buffer);
Offset += (uint) actualLength;
return actualLength;
}
#endif
/// <summary>
/// Attempts to read the provided amount of bytes from the input stream.
/// </summary>
/// <param name="buffer">The buffer that receives the read bytes.</param>
/// <param name="index">The index into the buffer to start writing into.</param>
/// <param name="count">The number of bytes to read.</param>
/// <returns>The number of bytes that were read.</returns>
public int ReadBytes(byte[] buffer, int index, int count)
{
int actualLength = DataSource.ReadBytes(Offset, buffer, index, count);
Offset += (uint) actualLength;
return actualLength;
}
/// <summary>
/// Creates a segment containing data from the input data source, starting at the current position of the input
/// stream. The reader then advances the current offset by the provided number of bytes.
/// </summary>
/// <param name="count">The number of bytes the segment should contain.</param>
/// <returns>The read segment.</returns>
public IReadableSegment ReadSegment(uint count)
{
var segment = new DataSourceSegment(DataSource, Offset, Rva, count);
Offset += count;
return segment;
}
/// <summary>
/// Consumes the remainder of the input stream.
/// </summary>
/// <returns>The remaining bytes.</returns>
public byte[] ReadToEnd()
{
byte[] buffer = new byte[RemainingLength];
ReadBytes(buffer, 0, buffer.Length);
return buffer;
}
/// <summary>
/// Reads bytes from the input stream until the provided delimiter byte is reached.
/// </summary>
/// <param name="delimiter">The delimiter byte to stop at.</param>
/// <returns>The read bytes, including the delimiter if it was found.</returns>
public byte[] ReadBytesUntil(byte delimiter) => ReadBytesUntil(delimiter, true);
/// <summary>
/// Reads bytes from the input stream until the provided delimiter byte is reached.
/// </summary>
/// <param name="delimiter">The delimiter byte to stop at.</param>
/// <param name="includeDelimiterInReturn">
/// <c>true</c> if the final delimiter should be included in the return value, <c>false</c> otherwise.
/// </param>
/// <returns>The read bytes.</returns>
/// <remarks>
/// This function always consumes the delimiter from the input stream if it is present, regardless of the value
/// of <paramref name="includeDelimiterInReturn"/>.
/// </remarks>
public byte[] ReadBytesUntil(byte delimiter, bool includeDelimiterInReturn)
{
var lookahead = Fork();
bool hasConsumedDelimiter = lookahead.AdvanceUntil(delimiter, includeDelimiterInReturn);
byte[] buffer = new byte[lookahead.RelativeOffset - RelativeOffset];
ReadBytes(buffer, 0, buffer.Length);
if (hasConsumedDelimiter)
ReadByte();
return buffer;
}
/// <summary>
/// Advances the reader until the provided delimiter byte is reached.
/// </summary>
/// <param name="delimiter">The delimiter byte to stop at.</param>
/// <param name="consumeDelimiter">
/// <c>true</c> if the final delimiter should be consumed if available, <c>false</c> otherwise.
/// </param>
/// <returns><c>true</c> if the delimiter byte was found and consumed, <c>false</c> otherwise.</returns>
public bool AdvanceUntil(byte delimiter, bool consumeDelimiter)
{
while (RelativeOffset < Length)
{
byte b = ReadByte();
if (b == delimiter)
{
if (!consumeDelimiter)
{
RelativeOffset--;
return true;
}
return false;
}
}
return false;
}
/// <summary>
/// Reads a null-terminated ASCII string from the input stream.
/// </summary>
/// <returns>The read ASCII string, excluding the null terminator.</returns>
public string ReadAsciiString() => Encoding.ASCII.GetString(ReadBytesUntil(0, false));
/// <summary>
/// Reads a zero-terminated Unicode string from the stream.
/// </summary>
/// <returns>The string that was read from the stream.</returns>
public string ReadUnicodeString()
{
var builder = new StringBuilder();
while (true)
{
char nextChar = (char) ReadUInt16();
if (nextChar is '\0')
break;
builder.Append(nextChar);
}
return builder.ToString();
}
/// <summary>
/// Reads a null-terminated UTF-8 string from the input stream.
/// </summary>
/// <returns>The read UTF-8 string, excluding the null terminator.</returns>
public Utf8String ReadUtf8String()
{
byte[] data = ReadBytesUntil(0, false);
return data.Length != 0
? new Utf8String(data)
: Utf8String.Empty;
}
/// <summary>
/// Reads either a 32-bit or a 64-bit number from the input stream.
/// </summary>
/// <param name="is32Bit">Indicates the integer to be read is 32-bit or 64-bit.</param>
/// <returns>The read number, zero extended if necessary.</returns>
public ulong ReadNativeInt(bool is32Bit) => is32Bit ? ReadUInt32() : ReadUInt64();
/// <summary>
/// Reads a compressed unsigned integer from the stream.
/// </summary>
/// <returns>The unsigned integer that was read from the stream.</returns>
public uint ReadCompressedUInt32()
{
byte firstByte = ReadByte();
if ((firstByte & 0x80) == 0)
return firstByte;
if ((firstByte & 0x40) == 0)
return (uint)(((firstByte & 0x7F) << 8) | ReadByte());
return (uint) (((firstByte & 0x3F) << 0x18) |
(ReadByte() << 0x10) |
(ReadByte() << 0x08) |
ReadByte());
}
/// <summary>
/// Reads a compressed unsigned integer from the stream.
/// </summary>
/// <returns>The signed integer that was read from the stream.</returns>
public int ReadCompressedInt32()
{
byte firstByte = ReadByte();
uint rotated;
int mask;
if ((firstByte & 0x80) == 0)
{
rotated = firstByte;
mask = (rotated & 1) != 0 ? -0x40 : 0;
}
else if ((firstByte & 0x40) == 0)
{
rotated = (uint) ((firstByte & 0x3F) << 8 | ReadByte());
mask = (rotated & 1) != 0 ? -0x2000 : 0;
}
else
{
rotated = (uint) (
(firstByte & 0x1F) << 0x18
| ReadByte() << 0x10
| ReadByte() << 0x08
| ReadByte()
);
mask = (rotated & 1) != 0 ? -0x1000_0000 : 0;
}
return (int) (rotated >> 1) | mask;
}
/// <summary>
/// Tries to reads a compressed unsigned integer from the stream.
/// </summary>
/// <param name="value">The unsigned integer that was read from the stream.</param>
/// <returns><c>True</c> if the method succeeded, false otherwise.</returns>
public bool TryReadCompressedUInt32(out uint value)
{
value = 0;
if (!CanRead(sizeof(byte)))
return false;
byte firstByte = ReadByte();
Offset--;
if ((firstByte & 0x80) == 0 && CanRead(sizeof(byte))
|| (firstByte & 0x40) == 0 && CanRead(sizeof(ushort))
|| CanRead(sizeof(uint)))
{
value = ReadCompressedUInt32();
return true;
}
return false;
}
/// <summary>
/// Tries to reads a compressed signed integer from the stream.
/// </summary>
/// <param name="value">The signed integer that was read from the stream.</param>
/// <returns><c>True</c> if the method succeeded, false otherwise.</returns>
public bool TryReadCompressedInt32(out int value)
{
value = 0;
if (!CanRead(sizeof(byte)))
return false;
byte firstByte = ReadByte();
Offset--;
if ((firstByte & 0x80) == 0 && CanRead(sizeof(byte))
|| (firstByte & 0x40) == 0 && CanRead(sizeof(ushort))
|| CanRead(sizeof(uint)))
{
value = ReadCompressedInt32();
return true;
}
return true;
}
/// <summary>
/// Reads a 7-bit encoded 32-bit integer from the stream.
/// </summary>
/// <returns>The integer.</returns>
/// <exception cref="FormatException">Occurs when an invalid 7-bit encoding was encountered.</exception>
public int Read7BitEncodedInt32()
{
int result = 0;
byte currentByte;
for (int i = 0; i < 4; i++)
{
currentByte = ReadByte();
result |= (currentByte & 0x7F) << (i * 7);
if ((currentByte & 0x80) == 0)
return result;
}
currentByte = ReadByte();
if (currentByte > 0b11111)
throw new FormatException("Invalid 7-bit encoded integer.");
return result | (currentByte << (4 * 7));
}
/// <summary>
/// Reads a short or a long index from the stream.
/// </summary>
/// <param name="size">The size of the index to read.</param>
/// <returns>The index, zero extended to 32 bits if necessary.</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public uint ReadIndex(IndexSize size)
{
switch (size)
{
case IndexSize.Short:
return ReadUInt16();
case IndexSize.Long:
return ReadUInt32();
default:
throw new ArgumentOutOfRangeException(nameof(size));
}
}
/// <summary>
/// Reads a serialized UTF8 string from the stream.
/// </summary>
/// <returns>The string that was read from the stream.</returns>
public Utf8String? ReadSerString()
{
if (!CanRead(1) || DataSource[Offset] == 0xFF)
{
Offset++;
return null;
}
if (!TryReadCompressedUInt32(out uint length))
return null;
byte[] data = new byte[length];
length = (uint) ReadBytes(data, 0, (int) length);
return new Utf8String(data, 0, (int)length);
}
/// <summary>
/// Reads a serialized UTF-8 string that is prefixed by a 7-bit encoded length header.
/// </summary>
/// <returns>The string.</returns>
/// <exception cref="FormatException">Occurs when the 7-bit encoded header is invalid.</exception>
public string ReadBinaryFormatterString() => ReadBinaryFormatterString(Encoding.UTF8);
/// <summary>
/// Reads a serialized string that is prefixed by a 7-bit encoded length header.
/// </summary>
/// <param name="encoding">The encoding to use for decoding the bytes into a string.</param>
/// <returns>The string.</returns>
/// <exception cref="FormatException">Occurs when the 7-bit encoded header is invalid.</exception>
public string ReadBinaryFormatterString(Encoding encoding)
{
int length = Read7BitEncodedInt32();
switch (length)
{
case < 0:
throw new FormatException("Negative string length.");
case 0:
return string.Empty;
case > 0:
byte[] bytes = new byte[length];
int actualLength = ReadBytes(bytes, 0, length);
return encoding.GetString(bytes, 0, actualLength);
}
}
/// <summary>
/// Aligns the reader to a specified boundary.
/// </summary>
/// <param name="alignment">The boundary to use.</param>
public void Align(uint alignment) => Offset = Offset.Align(alignment);
/// <summary>
/// Aligns the reader to a specified boundary.
/// </summary>
/// <param name="alignment">The boundary to use.</param>
public void AlignRelative(uint alignment) => RelativeOffset = RelativeOffset.Align(alignment);
/// <summary>
/// Creates an exact copy of the reader.
/// </summary>
/// <returns>The copied reader.</returns>
/// <remarks>This method does not copy the underlying buffer.</remarks>
public readonly BinaryStreamReader Fork() => this;
/// <summary>
/// Creates a copy of the reader, and moves the offset of the copied reader to the provided file offset.
/// </summary>
/// <param name="offset">The file offset.</param>
/// <returns>The new reader.</returns>
/// <remarks>This method does not copy the underlying buffer.</remarks>
public readonly BinaryStreamReader ForkAbsolute(ulong offset)
{
return ForkAbsolute(offset, (uint) (Length - (offset - StartOffset)));
}
/// <summary>
/// Creates a copy of the reader, moves the offset of the copied reader to the provided file offset, and resizes
/// the copied reader to the provided number of bytes.
/// </summary>
/// <param name="offset">The file offset.</param>
/// <param name="size">The number of bytes to read.</param>
/// <returns>The new reader.</returns>
/// <remarks>This method does not copy the underlying buffer.</remarks>
public readonly BinaryStreamReader ForkAbsolute(ulong offset, uint size)
{
return new(DataSource, offset, (uint) (StartRva + (offset - StartOffset)), size);
}
/// <summary>
/// Creates a copy of the reader, and moves to the provided relative offset of the copied reader.
/// </summary>
/// <param name="relativeOffset">The displacement.</param>
/// <returns>The new reader.</returns>
/// <remarks>This method does not copy the underlying buffer.</remarks>
public readonly BinaryStreamReader ForkRelative(uint relativeOffset)
{
return ForkRelative(relativeOffset, Length - relativeOffset);
}
/// <summary>
/// Creates a copy of the reader, moves the copied reader to the provided relative offset, and resizes the
/// copied reader to the provided number of bytes.
/// </summary>
/// <param name="relativeOffset">The displacement.</param>
/// <param name="size">The number of bytes to read.</param>
/// <returns>The new reader.</returns>
/// <remarks>This method does not copy the underlying buffer.</remarks>
public readonly BinaryStreamReader ForkRelative(uint relativeOffset, uint size)
{
return new(DataSource, StartOffset + relativeOffset, StartRva + relativeOffset, size);
}
/// <summary>
/// Resizes the current reader to a new number of bytes.
/// </summary>
/// <param name="newSize">The new number of bytes.</param>
/// <exception cref="EndOfStreamException">
/// Occurs when the provided size reaches outside of the input stream's length.
/// </exception>
public void ChangeSize(uint newSize)
{
if (newSize > Length)
throw new EndOfStreamException();
Length = newSize;
}
/// <summary>
/// Consumes and copies the remainder of the contents to the provided output stream.
/// </summary>
/// <param name="writer">The output stream.</param>
public void WriteToOutput(BinaryStreamWriter writer)
{
byte[] buffer = new byte[4096];
while (RelativeOffset < Length)
{
int blockSize = (int) Math.Min(buffer.Length, Length - RelativeOffset);
int actualSize = ReadBytes(buffer, 0, blockSize);
if (actualSize == 0)
{
writer.WriteZeroes((int) (Length - RelativeOffset));
return;
}
writer.WriteBytes(buffer, 0, actualSize);
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\AsmResolver.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\IO\BinaryStreamWriterTest.cs | AsmResolver.Tests.IO
| BinaryStreamWriterTest | [] | ['System.IO', 'System.Text', 'AsmResolver.IO', 'Xunit'] | xUnit | net8.0 | public class BinaryStreamWriterTest
{
[Fact]
public void WriteByte()
{
using var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
writer.WriteByte(0x80);
writer.WriteSByte(-1);
Assert.Equal(new byte[]
{
0x80,
0xFF
}, stream.ToArray());
}
[Fact]
public void WriteInt16()
{
using var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
writer.WriteUInt16(0x8001);
writer.WriteInt16(-32766);
Assert.Equal(new byte[]
{
0x01, 0x80,
0x02, 0x80
}, stream.ToArray());
}
[Fact]
public void WriteInt32()
{
using var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
writer.WriteUInt32(0x81020304u);
writer.WriteInt32(-2063202552);
Assert.Equal(new byte[]
{
0x04, 0x03, 0x02, 0x81,
0x08, 0x07, 0x06, 0x85
}, stream.ToArray());
}
[Fact]
public void WriteInt64()
{
using var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
writer.WriteUInt64(0x8001020304050607ul);
writer.WriteInt64(-8644366967197856241);
Assert.Equal(new byte[]
{
0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x80,
0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x88,
}, stream.ToArray());
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
[InlineData(5)]
[InlineData(8)]
[InlineData(16)]
[InlineData(45)]
[InlineData(100)]
public void WriteZeroes(int count)
{
using var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
writer.WriteZeroes(count);
Assert.Equal(new byte[count], stream.ToArray());
}
[Theory]
[InlineData(new byte[] {0x03}, 3)]
[InlineData(new byte[] {0x7f}, 0x7f)]
[InlineData(new byte[] {0x80, 0x80}, 0x80)]
[InlineData(new byte[] {0xAE, 0x57}, 0x2E57)]
[InlineData(new byte[] {0xBF, 0xFF}, 0x3FFF)]
[InlineData(new byte[] {0xC0, 0x00, 0x40, 0x00}, 0x4000)]
[InlineData(new byte[] {0xDF, 0x12, 0x34, 0x56}, 0x1F123456)]
[InlineData(new byte[] {0xDF, 0xFF, 0xFF, 0xFF}, 0x1FFFFFFF)]
public void WriteCompressedUInt32(byte[] expected, uint value)
{
using var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
writer.WriteCompressedUInt32(value);
Assert.Equal(expected, stream.ToArray());
}
[Theory]
[InlineData(new byte[] {0x06}, 3)]
[InlineData(new byte[] {0x7B}, -3)]
[InlineData(new byte[] {0x80, 0x80}, 64)]
[InlineData(new byte[] {0x01}, -64)]
[InlineData(new byte[] {0xC0, 0x00, 0x40, 0x00}, 8192)]
[InlineData(new byte[] {0x80, 0x01}, -8192)]
[InlineData(new byte[] {0xDF, 0xFF, 0xFF, 0xFE}, 0xFFFFFFF)]
[InlineData(new byte[] {0xC0, 0x00, 0x00, 0x01}, -0x10000000)]
public void WriteCompressedInt32(byte[] expected, int value)
{
using var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
writer.WriteCompressedInt32(value);
Assert.Equal(expected, stream.ToArray());
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(0b1000_0000)]
[InlineData(0b100000_0000_0000)]
[InlineData(int.MaxValue)]
public void Write7BitEncodedInt32(int value)
{
using var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
writer.Write7BitEncodedInt32(value);
var reader = new BinaryStreamReader(stream.ToArray());
Assert.Equal(value, reader.Read7BitEncodedInt32());
}
[Theory]
[InlineData("")]
[InlineData("Hello, world!")]
[InlineData("0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789")]
public void WriteBinaryFormatterString(string value)
{
using var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
writer.WriteBinaryFormatterString(value);
stream.Position = 0;
var reader = new BinaryReader(stream, Encoding.UTF8);
Assert.Equal(value, reader.ReadString());
}
} | 116 | 5,536 | using System;
using System.IO;
using System.Text;
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
using System.Buffers.Binary;
#endif
namespace AsmResolver.IO
{
/// <summary>
/// Provides methods for writing data to an output stream.
/// </summary>
public sealed class BinaryStreamWriter
{
private const int ZeroBufferLength = 16;
private static readonly byte[] ZeroBuffer = new byte[ZeroBufferLength];
// Buffer to reduce individual IO ops.
// Initialize this buffer in reverse order to prevent JIT emitting range checks for every byte.
private readonly byte[] _buffer = new byte[8];
/// <summary>
/// Creates a new binary stream writer using the provided output stream.
/// </summary>
/// <param name="stream">The stream to write to.</param>
public BinaryStreamWriter(Stream stream)
{
BaseStream = stream ?? throw new ArgumentNullException(nameof(stream));
}
/// <summary>
/// Gets the stream this writer writes to.
/// </summary>
public Stream BaseStream
{
get;
}
/// <summary>
/// Gets or sets the current position of the
/// </summary>
public ulong Offset
{
get => (uint) BaseStream.Position;
set
{
// Check if position actually changed before actually setting. If we don't do this, this can cause
// performance issues on some systems. See https://github.com/Washi1337/AsmResolver/issues/232
if (BaseStream.Position != (long) value)
BaseStream.Position = (long) value;
}
}
/// <summary>
/// Gets or sets the current length of the stream.
/// </summary>
public uint Length => (uint) BaseStream.Length;
/// <summary>
/// Writes a buffer of data to the stream.
/// </summary>
/// <param name="buffer">The buffer to write to the stream.</param>
/// <param name="startIndex">The index to start reading from the buffer.</param>
/// <param name="count">The amount of bytes of the buffer to write.</param>
public void WriteBytes(byte[] buffer, int startIndex, int count)
{
BaseStream.Write(buffer, startIndex, count);
}
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
/// <summary>
/// Writes a buffer of data to the stream.
/// </summary>
/// <param name="buffer">The buffer to write to the stream.</param>
public void WriteBytes(ReadOnlySpan<byte> buffer)
{
BaseStream.Write(buffer);
}
#endif
/// <summary>
/// Writes a single byte to the stream.
/// </summary>
/// <param name="value">The byte to write.</param>
public void WriteByte(byte value)
{
BaseStream.WriteByte(value);
}
/// <summary>
/// Writes an unsigned 16-bit integer to the stream.
/// </summary>
/// <param name="value">The unsigned 16-bit integer to write.</param>
public void WriteUInt16(ushort value)
{
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
BinaryPrimitives.WriteUInt16LittleEndian(_buffer, value);
#else
_buffer[1] = (byte) ((value >> 8) & 0xFF);
_buffer[0] = (byte) (value & 0xFF);
#endif
BaseStream.Write(_buffer, 0, 2);
}
/// <summary>
/// Writes an unsigned 32-bit integer to the stream.
/// </summary>
/// <param name="value">The unsigned 32-bit integer to write.</param>
public void WriteUInt32(uint value)
{
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
BinaryPrimitives.WriteUInt32LittleEndian(_buffer, value);
#else
_buffer[3] = (byte) ((value >> 24) & 0xFF);
_buffer[2] = (byte) ((value >> 16) & 0xFF);
_buffer[1] = (byte) ((value >> 8) & 0xFF);
_buffer[0] = (byte) (value & 0xFF);
#endif
BaseStream.Write(_buffer, 0, 4);
}
/// <summary>
/// Writes an unsigned 64-bit integer to the stream.
/// </summary>
/// <param name="value">The unsigned 64-bit integer to write.</param>
public void WriteUInt64(ulong value)
{
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
BinaryPrimitives.WriteUInt64LittleEndian(_buffer, value);
#else
_buffer[7] = (byte) ((value >> 56) & 0xFF);
_buffer[6] = (byte) ((value >> 48) & 0xFF);
_buffer[5] = (byte) ((value >> 40) & 0xFF);
_buffer[4] = (byte) ((value >> 32) & 0xFF);
_buffer[3] = (byte) ((value >> 24) & 0xFF);
_buffer[2] = (byte) ((value >> 16) & 0xFF);
_buffer[1] = (byte) ((value >> 8) & 0xFF);
_buffer[0] = (byte) (value & 0xFF);
#endif
BaseStream.Write(_buffer, 0, 8);
}
/// <summary>
/// Writes an signed byte to the stream.
/// </summary>
/// <param name="value">The signed byte to write.</param>
public void WriteSByte(sbyte value)
{
BaseStream.WriteByte(unchecked((byte) value));
}
/// <summary>
/// Writes a signed 16-bit integer to the stream.
/// </summary>
/// <param name="value">The signed 16-bit integer to write.</param>
public void WriteInt16(short value)
{
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
BinaryPrimitives.WriteInt16LittleEndian(_buffer, value);
#else
_buffer[1] = (byte) ((value >> 8) & 0xFF);
_buffer[0] = (byte) (value & 0xFF);
#endif
BaseStream.Write(_buffer, 0, 2);
}
/// <summary>
/// Writes a signed 32-bit integer to the stream.
/// </summary>
/// <param name="value">The signed 32-bit integer to write.</param>
public void WriteInt32(int value)
{
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
BinaryPrimitives.WriteInt32LittleEndian(_buffer, value);
#else
_buffer[3] = (byte) ((value >> 24) & 0xFF);
_buffer[2] = (byte) ((value >> 16) & 0xFF);
_buffer[1] = (byte) ((value >> 8) & 0xFF);
_buffer[0] = (byte) (value & 0xFF);
#endif
BaseStream.Write(_buffer, 0, 4);
}
/// <summary>
/// Writes a signed 64-bit integer to the stream.
/// </summary>
/// <param name="value">The signed 64-bit integer to write.</param>
public void WriteInt64(long value)
{
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
BinaryPrimitives.WriteInt64LittleEndian(_buffer, value);
#else
_buffer[7] = (byte) ((value >> 56) & 0xFF);
_buffer[6] = (byte) ((value >> 48) & 0xFF);
_buffer[5] = (byte) ((value >> 40) & 0xFF);
_buffer[4] = (byte) ((value >> 32) & 0xFF);
_buffer[3] = (byte) ((value >> 24) & 0xFF);
_buffer[2] = (byte) ((value >> 16) & 0xFF);
_buffer[1] = (byte) ((value >> 8) & 0xFF);
_buffer[0] = (byte) (value & 0xFF);
#endif
BaseStream.Write(_buffer, 0, 8);
}
/// <summary>
/// Writes a 32-bit floating point number to the stream.
/// </summary>
/// <param name="value">The 32-bit floating point number to write.</param>
public unsafe void WriteSingle(float value)
{
WriteUInt32(*(uint*) &value);
}
/// <summary>
/// Writes a 64-bit floating point number to the stream.
/// </summary>
/// <param name="value">The 64-bit floating point number to write.</param>
public unsafe void WriteDouble(double value)
{
WriteUInt64(*(ulong*) &value);
}
/// <summary>
/// Writes a 128-bit decimal value to the stream.
/// </summary>
/// <param name="value">The 128-bit decimal value to write.</param>
public void WriteDecimal(decimal value)
{
int[] bits = decimal.GetBits(value);
WriteInt32(bits[0]);
WriteInt32(bits[1]);
WriteInt32(bits[2]);
WriteInt32(bits[3]);
}
/// <summary>
/// Writes either a 32-bit or a 64-bit number to the output stream.
/// </summary>
/// <param name="value">The value to write.</param>
/// <param name="is32Bit">Indicates the integer to be written is 32-bit or 64-bit.</param>
/// <returns>The read number, zero extended if necessary.</returns>
public void WriteNativeInt(ulong value, bool is32Bit)
{
if (is32Bit)
WriteUInt32((uint) value);
else
WriteUInt64(value);
}
/// <summary>
/// Writes a buffer of data to the stream.
/// </summary>
/// <param name="buffer">The data to write.</param>
public void WriteBytes(byte[] buffer)
{
WriteBytes(buffer, 0, buffer.Length);
}
/// <summary>
/// Writes a specified number of zero bytes to the stream.
/// </summary>
/// <param name="count">The number of zeroes to write.</param>
public void WriteZeroes(int count)
{
while (count >= ZeroBufferLength)
{
BaseStream.Write(ZeroBuffer, 0, ZeroBufferLength);
count -= ZeroBufferLength;
}
if (count > 0)
BaseStream.Write(ZeroBuffer, 0, Math.Min(count, ZeroBufferLength));
}
/// <summary>
/// Writes an ASCII string to the stream.
/// </summary>
/// <param name="value">The string to write.</param>
public void WriteAsciiString(string value)
{
WriteBytes(Encoding.ASCII.GetBytes(value));
}
/// <summary>
/// Aligns the writer to a specified boundary.
/// </summary>
/// <param name="align">The boundary to use.</param>
public void Align(uint align) => AlignRelative(align, 0);
/// <summary>
/// Aligns the writer to a specified boundary, relative to the provided start offset..
/// </summary>
/// <param name="align">The boundary to use.</param>
/// <param name="startOffset">The starting offset to consider the alignment boundaries from.</param>
public void AlignRelative(uint align, ulong startOffset)
{
ulong currentPosition = Offset - startOffset;
WriteZeroes((int) (currentPosition.Align(align) - currentPosition));
}
/// <summary>
/// Writes a single index to the output stream.
/// </summary>
/// <param name="value">The index to write.</param>
/// <param name="size"></param>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public void WriteIndex(uint value, IndexSize size)
{
switch (size)
{
case IndexSize.Short:
WriteUInt16((ushort) value);
break;
case IndexSize.Long:
WriteUInt32(value);
break;
default:
throw new ArgumentOutOfRangeException(nameof(size), size, null);
}
}
/// <summary>
/// Compresses and writes an unsigned integer to the stream.
/// </summary>
/// <param name="value">The value to write.</param>
public void WriteCompressedUInt32(uint value)
{
switch (value)
{
case < 0x80:
WriteByte((byte) value);
break;
case < 0x4000:
_buffer[1] = (byte) value;
_buffer[0] = (byte) (0x80 | value >> 8);
BaseStream.Write(_buffer, 0, 2);
break;
default:
_buffer[3] = (byte) value;
_buffer[2] = (byte) (value >> 0x08);
_buffer[1] = (byte) (value >> 0x10);
_buffer[0] = (byte) (0x80 | 0x40 | value >> 0x18);
BaseStream.Write(_buffer, 0, 4);
break;
}
}
/// <summary>
/// Compresses and writes a signed integer to the stream.
/// </summary>
/// <param name="value">The value to write.</param>
public void WriteCompressedInt32(int value)
{
uint sign = (uint) value >> 31;
uint rotated;
switch (value)
{
case >= -0x40 and < 0x40:
rotated = ((uint) (value & 0x3F) << 1) | sign;
WriteByte((byte) rotated);
break;
case >= -0x2000 and < 0x2000:
rotated = ((uint) (value & 0x1FFF) << 1) | sign;
_buffer[1] = (byte) rotated;
_buffer[0] = (byte) (0x80 | rotated >> 8);
BaseStream.Write(_buffer, 0, 2);
break;
default:
rotated = ((uint) (value & 0x0FFF_FFFF) << 1) | sign;
_buffer[3] = (byte) rotated;
_buffer[2] = (byte) (rotated >> 0x08);
_buffer[1] = (byte) (rotated >> 0x10);
_buffer[0] = (byte)(0x80 | 0x40 | rotated >> 0x18);
BaseStream.Write(_buffer, 0, 4);
break;
}
}
/// <summary>
/// Writes a single 7-bit encoded 32-bit integer to the output stream.
/// </summary>
/// <param name="value">The value to write.</param>
public void Write7BitEncodedInt32(int value)
{
uint x = unchecked((uint) value);
do
{
byte b = (byte) (x & 0x7F);
if (x > 0x7F)
b |= 0x80;
WriteByte(b);
x >>= 7;
} while (x != 0);
}
/// <summary>
/// Writes an UTF8 string to the stream.
/// </summary>
/// <param name="value">The string to write.</param>
public void WriteSerString(string? value)
{
if (value is null)
{
WriteByte(0xFF);
return;
}
byte[] bytes = Encoding.UTF8.GetBytes(value);
WriteCompressedUInt32((uint)bytes.Length);
WriteBytes(bytes);
}
/// <summary>
/// Writes a serialized string using the UTF-8 encoding that is prefixed by a 7-bit encoded length header.
/// </summary>
/// <param name="value">The string to write.</param>
public void WriteBinaryFormatterString(string value) => WriteBinaryFormatterString(value, Encoding.UTF8);
/// <summary>
/// Writes a serialized string that is prefixed by a 7-bit encoded length header.
/// </summary>
/// <param name="value">The string to write.</param>
/// <param name="encoding">The encoding to use.</param>
public void WriteBinaryFormatterString(string value, Encoding encoding)
{
byte[] data = encoding.GetBytes(value);
Write7BitEncodedInt32(data.Length);
WriteBytes(data);
}
/// <summary>
/// Writes an UTF8 string to the stream.
/// </summary>
/// <param name="value">The string to write.</param>
public void WriteSerString(Utf8String? value)
{
if (value is null)
{
WriteByte(0xFF);
return;
}
byte[] bytes = value.GetBytesUnsafe();
WriteCompressedUInt32((uint)bytes.Length);
WriteBytes(bytes);
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\AsmResolver.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\IO\DataSourceSliceTest.cs | AsmResolver.Tests.IO
| DataSourceSliceTest | ['private readonly IDataSource _source = new ByteArrayDataSource(new byte[]\n {\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n });'] | ['System', 'System.Linq', 'AsmResolver.IO', 'Xunit'] | xUnit | net8.0 | public class DataSourceSliceTest
{
private readonly IDataSource _source = new ByteArrayDataSource(new byte[]
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
});
[Fact]
public void EmptySlice()
{
var slice = new DataSourceSlice(_source, 0, 0);
Assert.Equal(0ul, slice.Length);
}
[Fact]
public void SliceStart()
{
var slice = new DataSourceSlice(_source, 0, 5);
Assert.Equal(5ul, slice.Length);
Assert.All(Enumerable.Range(0, 5), i => Assert.Equal(slice[(ulong) i], _source[(ulong) i]));
Assert.Throws<IndexOutOfRangeException>(() => slice[5]);
}
[Fact]
public void SliceMiddle()
{
var slice = new DataSourceSlice(_source, 3, 5);
Assert.Equal(5ul, slice.Length);
Assert.All(Enumerable.Range(3, 5), i => Assert.Equal(slice[(ulong) i], _source[(ulong) i]));
Assert.Throws<IndexOutOfRangeException>(() => slice[3 - 1]);
Assert.Throws<IndexOutOfRangeException>(() => slice[3 + 5]);
}
[Fact]
public void SliceEnd()
{
var slice = new DataSourceSlice(_source, 5, 5);
Assert.Equal(5ul, slice.Length);
Assert.All(Enumerable.Range(5, 5), i => Assert.Equal(slice[(ulong) i], _source[(ulong) i]));
Assert.Throws<IndexOutOfRangeException>(() => slice[5 - 1]);
}
[Fact]
public void ReadSlicedShouldReadUpToSliceAmountOfBytes()
{
var slice = new DataSourceSlice(_source, 3, 5);
byte[] data1 = new byte[7];
int originalCount = _source.ReadBytes(3, data1, 0, data1.Length);
Assert.Equal(7, originalCount);
byte[] data2 = new byte[3];
int newCount = slice.ReadBytes(3, data2, 0, data2.Length);
Assert.Equal(3, newCount);
Assert.Equal(data1.Take(3), data2.Take(3));
byte[] data3 = new byte[7];
int newCount2 = slice.ReadBytes(3, data3, 0, data3.Length);
Assert.Equal(5, newCount2);
Assert.Equal(data1.Take(5), data3.Take(5));
}
} | 113 | 2,401 | using System;
namespace AsmResolver.IO
{
/// <summary>
/// Represents a data source that only exposes a part (slice) of another data source.
/// </summary>
public class DataSourceSlice : IDataSource
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
, ISpanDataSource
#endif
{
private readonly IDataSource _source;
/// <summary>
/// Creates a new data source slice.
/// </summary>
/// <param name="source">The original data source to slice.</param>
/// <param name="start">The starting address.</param>
/// <param name="length">The number of bytes.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Occurs when <paramref name="start"/> and/or <paramref name="length"/> result in addresses that are invalid
/// in the original data source.
/// </exception>
public DataSourceSlice(IDataSource source, ulong start, ulong length)
{
_source = source;
if (!source.IsValidAddress(start))
throw new ArgumentOutOfRangeException(nameof(start));
if (length > 0 && !source.IsValidAddress(start + length - 1))
throw new ArgumentOutOfRangeException(nameof(length));
BaseAddress = start;
Length = length;
}
/// <inheritdoc />
public ulong BaseAddress
{
get;
}
/// <inheritdoc />
public ulong Length
{
get;
}
/// <inheritdoc />
public byte this[ulong address]
{
get
{
if (!IsValidAddress(address))
throw new IndexOutOfRangeException();
return _source[address];
}
}
/// <inheritdoc />
public bool IsValidAddress(ulong address) => address >= BaseAddress && address - BaseAddress < Length;
/// <inheritdoc />
public int ReadBytes(ulong address, byte[] buffer, int index, int count)
{
int maxCount = Math.Max(0, (int) (Length - (address - BaseAddress)));
return _source.ReadBytes(address, buffer, index, Math.Min(maxCount, count));
}
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
/// <inheritdoc />
public int ReadBytes(ulong address, Span<byte> buffer)
{
int maxCount = Math.Max(0, (int) (Length - (address - BaseAddress)));
return _source.ReadBytes(address, buffer[..Math.Min(maxCount, buffer.Length)]);
}
#endif
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\AsmResolver.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\IO\UnmanagedDataSourceTest.cs | AsmResolver.Tests.IO
| UnmanagedDataSourceTest | ['private readonly IntPtr _pointer;', 'private readonly UnmanagedDataSource _source;'] | ['System', 'System.Runtime.InteropServices', 'AsmResolver.IO', 'Xunit'] | xUnit | net8.0 | public unsafe class UnmanagedDataSourceTest : IDisposable
{
private readonly IntPtr _pointer;
private readonly UnmanagedDataSource _source;
public UnmanagedDataSourceTest()
{
const int testDataLength = 100;
_pointer = Marshal.AllocHGlobal(testDataLength);
for (int i = 0; i < testDataLength; i++)
((byte*) _pointer)[i] = (byte) (i & 0xFF);
_source = new UnmanagedDataSource(_pointer.ToPointer(), testDataLength);
}
[Fact]
public void ValidAddresses()
{
Assert.False(_source.IsValidAddress(0));
Assert.True(_source.IsValidAddress(_source.BaseAddress));
Assert.True(_source.IsValidAddress(_source.BaseAddress + _source.Length - 1));
Assert.False(_source.IsValidAddress(_source.BaseAddress + _source.Length));
}
[Fact]
public void ReadSingleValidByte()
{
Assert.Equal(((byte*) _pointer)[0], _source[_source.BaseAddress]);
Assert.Equal(((byte*) _pointer)[_source.Length - 1], _source[_source.BaseAddress + _source.Length - 1]);
}
[Fact]
public void ReadSingleInvalidByte()
{
Assert.ThrowsAny<ArgumentOutOfRangeException>(() => _source[0]);
Assert.ThrowsAny<ArgumentOutOfRangeException>(() => _source[_source.BaseAddress + _source.Length]);
}
[Fact]
public void ReadMultipleBytesFullyValid()
{
byte[] expected = new byte[50];
Marshal.Copy(_pointer, expected, 0, expected.Length);
byte[] actual = new byte[50];
Assert.Equal(actual.Length, _source.ReadBytes(_source.BaseAddress, actual, 0, actual.Length));
Assert.Equal(expected, actual);
}
[Fact]
public void ReadMultipleBytesHalfValid()
{
byte[] expected = new byte[50];
Marshal.Copy(
(IntPtr) ((ulong) _pointer + _source.Length - (ulong) (expected.Length / 2)), expected,
0,
expected.Length / 2);
byte[] actual = new byte[50];
Assert.Equal(actual.Length / 2,
_source.ReadBytes(
_source.BaseAddress + _source.Length - (ulong) (expected.Length / 2),
actual,
0,
actual.Length));
Assert.Equal(expected, actual);
}
/// <inheritdoc />
public void Dispose()
{
Marshal.FreeHGlobal(_pointer);
}
} | 132 | 2,830 | using System;
using System.Runtime.InteropServices;
namespace AsmResolver.IO
{
/// <summary>
/// Represents a data source that obtains its data from a block of unmanaged memory.
/// </summary>
public sealed unsafe class UnmanagedDataSource : IDataSource
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
, ISpanDataSource
#endif
{
private readonly void* _basePointer;
/// <summary>
/// Creates a new instance of the <see cref="UnmanagedDataSource"/> class.
/// </summary>
/// <param name="basePointer">The base pointer to start reading from.</param>
/// <param name="length">The total length of the data source.</param>
public UnmanagedDataSource(IntPtr basePointer, ulong length)
: this(basePointer.ToPointer(), length)
{
}
/// <summary>
/// Creates a new instance of the <see cref="UnmanagedDataSource"/> class.
/// </summary>
/// <param name="basePointer">The base pointer to start reading from.</param>
/// <param name="length">The total length of the data source.</param>
public UnmanagedDataSource(void* basePointer, ulong length)
{
_basePointer = basePointer;
Length = length;
}
/// <inheritdoc />
public ulong BaseAddress => (ulong) _basePointer;
/// <inheritdoc />
public byte this[ulong address]
{
get
{
if (!IsValidAddress(address))
throw new ArgumentOutOfRangeException(nameof(address));
return *(byte*) address;
}
}
/// <inheritdoc />
public ulong Length
{
get;
}
/// <inheritdoc />
public bool IsValidAddress(ulong address) => address >= (ulong) _basePointer
&& address - (ulong) _basePointer < Length;
/// <inheritdoc />
public int ReadBytes(ulong address, byte[] buffer, int index, int count)
{
if (!IsValidAddress(address))
return 0;
ulong relativeIndex = address - (ulong) _basePointer;
int actualLength = (int) Math.Min((ulong) count, Length - relativeIndex);
Marshal.Copy((IntPtr) address, buffer, index, actualLength);
return actualLength;
}
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
/// <inheritdoc />
public int ReadBytes(ulong address, Span<byte> buffer)
{
if (!IsValidAddress(address))
return 0;
ulong relativeIndex = address - (ulong) _basePointer;
int actualLength = (int) Math.Min((uint) buffer.Length, Length - relativeIndex);
new ReadOnlySpan<byte>((byte*) address, actualLength).CopyTo(buffer);
return actualLength;
}
#endif
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\AsmResolver.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\OffsetRangeTest.cs | AsmResolver.Tests
| OffsetRangeTest | [] | ['Xunit'] | xUnit | net8.0 | public class OffsetRangeTest
{
[Theory]
[InlineData(0, 100, 10, true)]
[InlineData(0, 100, 100, false)]
[InlineData(0, 100, 101, false)]
public void ContainsOffset(uint start, uint end, uint offset, bool expected)
{
var range = new OffsetRange(start, end);
Assert.Equal(expected, range.Contains(offset));
}
[Theory]
[InlineData(0, 100, 0, 0, true)]
[InlineData(0, 100, 99, 99, true)]
[InlineData(0, 100, 25, 75, true)]
[InlineData(0, 100, 25, 125, false)]
[InlineData(50, 100, 25, 75, false)]
[InlineData(0, 100, 100, 125, false)]
public void ContainsRange(uint start, uint end, uint subStart, uint subEnd, bool expected)
{
var range = new OffsetRange(start, end);
var subRange = new OffsetRange(subStart, subEnd);
Assert.Equal(expected, range.Contains(subRange));
}
[Theory]
[InlineData(0, 100, 0, 0, true)]
[InlineData(0, 100, 99, 99, true)]
[InlineData(0, 100, 25, 75, true)]
[InlineData(0, 100, 25, 125, true)]
[InlineData(50, 100, 25, 75, true)]
[InlineData(0, 100, 100, 125, true)]
[InlineData(0, 100, 101, 125, false)]
[InlineData(0, 100, 200, 225, false)]
public void IntersectsRange(uint start, uint end, uint subStart, uint subEnd, bool expected)
{
var range = new OffsetRange(start, end);
var subRange = new OffsetRange(subStart, subEnd);
Assert.Equal(expected, range.Intersects(subRange));
}
[Theory]
[InlineData(0, 100, 25, 75, 25, 75)]
[InlineData(0, 100, 25, 125, 25, 100)]
[InlineData(25, 125, 0, 100, 25, 100)]
public void Intersection(uint start1, uint end1, uint start2, uint end2, uint expectedStart, uint expectedEnd)
{
var range = new OffsetRange(start1, end1);
var subRange = new OffsetRange(start2, end2);
Assert.Equal((expectedStart, expectedEnd), range.Intersect(subRange));
}
} | 52 | 2,263 | using System;
namespace AsmResolver
{
/// <summary>
/// Represents an offset range determined by a start and end offset.
/// </summary>
public readonly struct OffsetRange
{
/// <summary>
/// Converts a value tuple of unsigned integers to an offset range.
/// </summary>
/// <param name="tuple">The tuple to convert.</param>
/// <returns>The constructed offset range.</returns>
public static implicit operator OffsetRange((ulong Start, ulong End) tuple) =>
new OffsetRange(tuple.Start, tuple.End);
/// <summary>
/// Creates a new offset range.
/// </summary>
/// <param name="start">The start offset.</param>
/// <param name="end">The end offset, this offset is exclusive.</param>
/// <exception cref="ArgumentException">Occurs when the provided start offset is bigger than the end offset.</exception>
public OffsetRange(ulong start, ulong end)
{
if (start > end)
throw new ArgumentException("Start offset must be smaller or equal to end offset.");
Start = start;
End = end;
}
/// <summary>
/// Gets the start offset.
/// </summary>
public ulong Start
{
get;
}
/// <summary>
/// Gets the end offset. This offset is exclusive.
/// </summary>
public ulong End
{
get;
}
/// <summary>
/// Gets the length of the range.
/// </summary>
public int Length => (int) (End - Start);
/// <summary>
/// Gets a value indicating whether the range is empty.
/// </summary>
public bool IsEmpty => Start == End;
/// <summary>
/// Determines whether the provided offset falls within the range.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns><c>true</c> if the offset falls within the range, <c>false</c> otherwise.</returns>
public bool Contains(ulong offset) => Start <= offset && End > offset;
/// <summary>
/// Determines whether the provided range is a subset of the range.
/// </summary>
/// <param name="range">The range.</param>
/// <returns><c>true</c> if the range is a subset, <c>false</c> otherwise.</returns>
public bool Contains(OffsetRange range) => Contains(range.Start) && Contains(range.End);
/// <summary>
/// Obtains the intersection between two ranges.
/// </summary>
/// <param name="other">The other range.</param>
/// <returns>The intersection.</returns>
public bool Intersects(OffsetRange other) => Contains(other.Start)
|| Contains(other.End)
|| other.Contains(Start)
|| other.Contains(End);
/// <summary>
/// Determines whether the current range intersects with the provided range.
/// </summary>
/// <param name="other">The other range.</param>
/// <returns><c>true</c> if the range intersects, <c>false</c> otherwise.</returns>
public OffsetRange Intersect(OffsetRange other)
{
if (!Intersects(other))
return new OffsetRange(0, 0);
return new OffsetRange(
Math.Max(Start, other.Start),
Math.Min(End, other.End));
}
/// <summary>
/// Determines the resulting ranges after excluding the provided range.
/// </summary>
/// <param name="other">The range to exclude.</param>
/// <returns>The resulting ranges.</returns>
public (OffsetRange left, OffsetRange right) Exclude(OffsetRange other)
{
var intersection = Intersect(other);
if (intersection.IsEmpty)
return (this, (End, End));
if (Contains(other))
return ((Start, other.Start), (other.End, End));
if (Contains(other.Start))
return (new OffsetRange(Start, other.Start), new OffsetRange(other.End, other.End));
return ((other.Start, other.Start), (other.Start, End));
}
/// <summary>
/// Deconstructs an offset range into its individual components.
/// </summary>
/// <param name="start">The start offset.</param>
/// <param name="end">The exclusive end offset.</param>
public void Deconstruct(out ulong start, out ulong end)
{
start = Start;
end = End;
}
/// <inheritdoc />
public override string ToString() => $"[{Start:X8}, {End:X8})";
}
} |
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\AsmResolver.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\Patching\PatchedSegmentTest.cs | AsmResolver.Tests.Patching
| PatchedSegmentTest | ['private readonly DataSegment _input = new(Enumerable\n .Range(0, 1000)\n .Select(x => (byte) (x & 0xFF))\n .ToArray());'] | ['System', 'System.Linq', 'AsmResolver.Patching', 'Xunit'] | xUnit | net8.0 | public class PatchedSegmentTest
{
private readonly DataSegment _input = new(Enumerable
.Range(0, 1000)
.Select(x => (byte) (x & 0xFF))
.ToArray());
[Fact]
public void SimpleBytesPatch()
{
var patched = new PatchedSegment(_input);
uint relativeOffset = 10;
byte[] newData = {0xFF, 0xFE, 0xFD, 0xFC};
patched.Patches.Add(new BytesPatch(relativeOffset, newData));
byte[] expected = _input.ToArray();
Buffer.BlockCopy(newData, 0, expected, (int) relativeOffset, newData.Length);
byte[] result = patched.WriteIntoArray();
Assert.Equal(expected, result);
}
[Fact]
public void DoublePatchedSegmentShouldReturnSameInstance()
{
var x = _input.AsPatchedSegment();
var y = x.AsPatchedSegment();
Assert.Same(x, y);
}
[Fact]
public void SimpleBytesPatchFluent()
{
uint relativeOffset = 10;
byte[] newData = {0xFF, 0xFE, 0xFD, 0xFC};
var patched = _input
.AsPatchedSegment()
.Patch(10, newData);
byte[] expected = _input.ToArray();
Buffer.BlockCopy(newData, 0, expected, (int) relativeOffset, newData.Length);
byte[] result = patched.WriteIntoArray();
Assert.Equal(expected, result);
}
} | 125 | 1,650 | using System;
using System.Collections.Generic;
using System.Diagnostics;
using AsmResolver.IO;
namespace AsmResolver.Patching
{
/// <summary>
/// Provides a wrapper around an instance of a <see cref="ISegment"/> that patches its binary representation
/// while it is being serialized to an output stream.
/// </summary>
[DebuggerDisplay("Patched {Contents} (Count = {Patches.Count})")]
public class PatchedSegment : IReadableSegment
{
private ulong _imageBase;
/// <summary>
/// Wraps a segment into a new instance of the <see cref="PatchedSegment"/> class.
/// </summary>
/// <param name="contents">The segment to patch.</param>
public PatchedSegment(ISegment contents)
{
Contents = contents;
}
/// <summary>
/// Gets the original segment that is being patched.
/// </summary>
public ISegment Contents
{
get;
}
/// <summary>
/// Gets a list of patches to apply to the segment.
/// </summary>
public IList<IPatch> Patches
{
get;
} = new List<IPatch>();
/// <inheritdoc />
public ulong Offset => Contents.Offset;
/// <inheritdoc />
public uint Rva => Contents.Rva;
/// <inheritdoc />
public bool CanUpdateOffsets => Contents.CanUpdateOffsets;
/// <inheritdoc />
public uint GetPhysicalSize() => Contents.GetPhysicalSize();
/// <inheritdoc />
public uint GetVirtualSize() => Contents.GetVirtualSize();
/// <inheritdoc />
public void UpdateOffsets(in RelocationParameters parameters)
{
Contents.UpdateOffsets(in parameters);
_imageBase = parameters.ImageBase;
foreach (var patch in Patches)
patch.UpdateOffsets(parameters);
}
/// <inheritdoc />
public BinaryStreamReader CreateReader(ulong fileOffset, uint size) => Contents is IReadableSegment segment
? segment.CreateReader(fileOffset, size)
: throw new InvalidOperationException("Segment is not readable.");
/// <inheritdoc />
public void Write(BinaryStreamWriter writer)
{
Contents.Write(writer);
ApplyPatches(writer);
}
private void ApplyPatches(BinaryStreamWriter writer)
{
ulong offset = writer.Offset;
for (int i = 0; i < Patches.Count; i++)
Patches[i].Apply(new PatchContext(Contents, _imageBase, writer));
writer.Offset = offset;
}
/// <summary>
/// Adds a patch to the list of patches to apply.
/// </summary>
/// <param name="patch">The patch to apply.</param>
/// <returns>The current <see cref="PatchedSegment"/> instance.</returns>
public PatchedSegment Patch(IPatch patch)
{
Patches.Add(patch);
return this;
}
/// <summary>
/// Adds a bytes patch to the list of patches to apply.
/// </summary>
/// <param name="relativeOffset">The offset to start patching at, relative to the start of the segment.</param>
/// <param name="newData">The new data to write.</param>
/// <returns>The current <see cref="PatchedSegment"/> instance.</returns>
public PatchedSegment Patch(uint relativeOffset, byte[] newData)
{
Patches.Add(new BytesPatch(relativeOffset, newData));
return this;
}
/// <summary>
/// Adds a segment patch to the list of patches to apply.
/// </summary>
/// <param name="relativeOffset">The offset to start patching at, relative to the start of the base segment.</param>
/// <param name="newSegment">The new segment to write.</param>
/// <returns>The current <see cref="PatchedSegment"/> instance.</returns>
public PatchedSegment Patch(uint relativeOffset, ISegment newSegment)
{
Patches.Add(new SegmentPatch(relativeOffset, newSegment));
return this;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\AsmResolver.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\SegmentBuilderTest.cs | AsmResolver.Tests
| SegmentBuilderTest | [] | ['System.IO', 'AsmResolver.IO', 'Xunit'] | xUnit | net8.0 | public class SegmentBuilderTest
{
private static byte[] ToBytes(ISegment segment)
{
using var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
segment.Write(writer);
return stream.ToArray();
}
[Fact]
public void EmptyNoAlignment()
{
var collection = new SegmentBuilder();
collection.UpdateOffsets(new RelocationParameters(0x400000, 0x400, 0x1000, false));
Assert.Equal(0x400u, collection.Offset);
Assert.Equal(0x1000u, collection.Rva);
Assert.Equal(0u, collection.GetPhysicalSize());
Assert.Equal(0u, collection.GetVirtualSize());
Assert.Empty(ToBytes(collection));
}
[Fact]
public void SingleItemNoAlignment()
{
var segment = new DataSegment(new byte[] {1, 2, 3, 4});
var collection = new SegmentBuilder {segment};
collection.UpdateOffsets(new RelocationParameters(0x400000, 0x400, 0x1000, false));
Assert.Equal(0x400u, segment.Offset);
Assert.Equal(0x1000u, segment.Rva);
Assert.Equal(4u, collection.GetPhysicalSize());
Assert.Equal(4u, collection.GetVirtualSize());
Assert.Equal(new byte[]
{
1, 2, 3, 4
}, ToBytes(collection));
}
[Fact]
public void MultipleItemsNoAlignment()
{
var segment1 = new DataSegment(new byte[] {1, 2, 3, 4});
var segment2 = new DataSegment(new byte[] {1, 2, 3 });
var segment3 = new DataSegment(new byte[] {1, 2, 3, 4, 5});
var collection = new SegmentBuilder {segment1, segment2, segment3};
collection.UpdateOffsets(new RelocationParameters(0x400000, 0x400, 0x1000, false));
Assert.Equal(0x400u, segment1.Offset);
Assert.Equal(0x1000u, segment1.Rva);
Assert.Equal(0x404u, segment2.Offset);
Assert.Equal(0x1004u, segment2.Rva);
Assert.Equal(0x407u, segment3.Offset);
Assert.Equal(0x1007u, segment3.Rva);
Assert.Equal(12u, collection.GetPhysicalSize());
Assert.Equal(12u, collection.GetVirtualSize());
Assert.Equal(new byte[]
{
1, 2, 3, 4,
1, 2, 3,
1, 2, 3, 4, 5
}, ToBytes(collection));
}
[Fact]
public void SingleItemAlignment()
{
var segment = new DataSegment(new byte[] {1, 2, 3, 4});
var builder = new SegmentBuilder {segment};
builder.UpdateOffsets(new RelocationParameters(0x400000, 0x400, 0x1000, false));
Assert.Equal(0x400u, segment.Offset);
Assert.Equal(4u, builder.GetPhysicalSize());
Assert.Equal(4u, builder.GetVirtualSize());
Assert.Equal(new byte[]
{
1, 2, 3, 4
}, ToBytes(builder));
}
[Fact]
public void MultipleItemsAlignment()
{
var segment1 = new DataSegment(new byte[] {1, 2, 3, 4});
var segment2 = new DataSegment(new byte[] {1, 2, 3 });
var segment3 = new DataSegment(new byte[] {1, 2, 3, 4, 5});
var builder = new SegmentBuilder
{
{segment1, 8},
{segment2, 8},
{segment3, 8}
};
builder.UpdateOffsets(new RelocationParameters(0x400000, 0x400, 0x1000, false));
Assert.Equal(0x400u, segment1.Offset);
Assert.Equal(0x1000u, segment1.Rva);
Assert.Equal(0x408u, segment2.Offset);
Assert.Equal(0x1008u, segment2.Rva);
Assert.Equal(0x410u, segment3.Offset);
Assert.Equal(0x1010u, segment3.Rva);
Assert.Equal(0x15u, builder.GetPhysicalSize());
Assert.Equal(0x15u, builder.GetVirtualSize());
Assert.Equal(new byte[]
{
1, 2, 3, 4, 0, 0, 0, 0,
1, 2, 3, 0, 0, 0, 0, 0,
1, 2, 3, 4, 5
}, ToBytes(builder));
}
} | 93 | 4,459 | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using AsmResolver.IO;
namespace AsmResolver
{
/// <summary>
/// Represents a collection of segments concatenated (and aligned) after each other.
/// </summary>
public class SegmentBuilder : ISegment, IEnumerable<ISegment>
{
private readonly List<AlignedSegment> _items = new();
private uint _physicalSize;
private uint _virtualSize;
/// <summary>
/// Gets the number of sub segments that are stored into the segment.
/// </summary>
public int Count => _items.Count;
/// <inheritdoc />
public ulong Offset
{
get;
private set;
}
/// <inheritdoc />
public uint Rva
{
get;
private set;
}
/// <inheritdoc />
public bool CanUpdateOffsets => true;
/// <summary>
/// Gets a value indicating whether the collection of concatenated segments is empty.
/// </summary>
public bool IsEmpty => _items.Count == 0;
/// <summary>
/// Adds the provided segment with no alignment.
/// </summary>
/// <param name="segment">The segment to add.</param>
public void Add(ISegment segment) => Add(segment, 1);
/// <summary>
/// Adds the provided segment to the offset that is the next multiple of the provided alignment.
/// </summary>
/// <param name="segment">The segment to add.</param>
/// <param name="alignment">The alignment of the segment.</param>
public void Add(ISegment segment, uint alignment)
{
_items.Add(new AlignedSegment(segment, alignment));
}
/// <inheritdoc />
public void UpdateOffsets(in RelocationParameters parameters)
{
Offset = parameters.Offset;
Rva = parameters.Rva;
var current = parameters;
foreach (var item in _items)
{
current.Align(item.Alignment);
item.Segment.UpdateOffsets(current);
uint physicalSize = item.Segment.GetPhysicalSize();
uint virtualSize = item.Segment.GetVirtualSize();
current.Advance(physicalSize, virtualSize);
}
_physicalSize = (uint) (current.Offset - parameters.Offset);
_virtualSize = current.Rva - parameters.Rva;
}
/// <inheritdoc />
public uint GetPhysicalSize() => _physicalSize;
/// <inheritdoc />
public uint GetVirtualSize() => _virtualSize;
/// <inheritdoc />
public void Write(BinaryStreamWriter writer)
{
for (int i = 0; i < _items.Count; i++)
{
var current = _items[i];
writer.Align(current.Alignment);
current.Segment.Write(writer);
}
}
/// <summary>
/// Returns an object that enumerates all segments in the segment builder.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<ISegment> GetEnumerator() => _items.Select(s => s.Segment).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
[DebuggerDisplay(nameof(Segment) + ", Alignment: " + nameof(Alignment))]
private readonly struct AlignedSegment
{
public AlignedSegment(ISegment segment, uint alignment)
{
Segment = segment;
Alignment = alignment;
}
public ISegment Segment
{
get;
}
public uint Alignment
{
get;
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\AsmResolver.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Tests\Utf8StringTest.cs | AsmResolver.Tests
| Utf8StringTest | [] | ['System', 'System.Linq', 'Xunit'] | xUnit | net8.0 | public class Utf8StringTest
{
[Fact]
public void ConvertFromString()
{
const string text = "Hello, World";
Utf8String utf8 = text;
Assert.Equal(text, utf8.Value);
}
[Theory]
[InlineData(new byte[] { 0x41, 0x42, 0x43 }, 3)]
[InlineData(new byte[] { 0x80, 0x42, 0x43 }, 3)]
public void LengthBeforeAndAfterValueAccessShouldBeConsistentProperty(byte[] data, int expected)
{
var s1 = new Utf8String(data);
Assert.Equal(expected, s1.Length);
_ = s1.Value;
Assert.Equal(expected, s1.Length);
}
[Theory]
[InlineData("ABC", "ABC")]
[InlineData("ABC", "DEF")]
public void StringEquality(string a, string b)
{
var s1 = new Utf8String(a);
var s2 = new Utf8String(b);
Assert.Equal(a == b, s1 == s2);
}
[Theory]
[InlineData(new byte[] { 1, 2, 3 }, new byte[] { 1, 2, 3 })]
[InlineData(new byte[] { 1, 2, 3 }, new byte[] { 4, 5, 6 })]
public void ByteEquality(byte[] a, byte[] b)
{
var s1 = new Utf8String(a);
var s2 = new Utf8String(b);
Assert.Equal(ByteArrayEqualityComparer.Instance.Equals(a, b), s1 == s2);
}
[Theory]
[InlineData("")]
[InlineData("Hello")]
public void StringNullOrEmpty(string x)
{
var s1 = new Utf8String(x);
Assert.Equal(string.IsNullOrEmpty(x), Utf8String.IsNullOrEmpty(s1));
}
[Theory]
[InlineData("Hello, ", "World")]
[InlineData("", "World")]
[InlineData("Hello", "")]
[InlineData("", null)]
[InlineData(null, "")]
[InlineData(null, null)]
[InlineData("", "")]
public void StringConcat(string? a, string? b)
{
Utf8String? s1 = a;
Utf8String? s2 = b;
Assert.Equal(a + b, s1 + s2);
}
[Theory]
[InlineData(new byte[] { 0x41, 0x42 }, new byte[] { 0x43, 0x44 })]
[InlineData(new byte[] { 0x41, 0x42 }, new byte[0])]
[InlineData(new byte[0], new byte[] { 0x43, 0x44 })]
[InlineData(new byte[0], null)]
[InlineData(null, new byte[0])]
[InlineData(null, null)]
[InlineData(new byte[0], new byte[0])]
public void ByteConcat(byte[]? a, byte[]? b)
{
Utf8String? s1 = a;
Utf8String? s2 = b;
Assert.Equal((a ?? Array.Empty<byte>()).Concat(b ?? Array.Empty<byte>()), (s1 + s2).GetBytes());
}
[Theory]
[InlineData("0123456789", '0', 0)]
[InlineData("0123456789", '5', 5)]
[InlineData("0123456789", 'a', -1)]
public void IndexOfChar(string haystack, char needle, int expected)
{
Assert.Equal(expected, new Utf8String(haystack).IndexOf(needle));
}
[Theory]
[InlineData("012345678901234567890123456789", '0', 0, 0)]
[InlineData("012345678901234567890123456789", '0', 1, 10)]
[InlineData("012345678901234567890123456789", '0', 11, 20)]
[InlineData("012345678901234567890123456789", '0', 21, -1)]
public void IndexOfCharStartingAtIndex(string haystack, char needle, int startIndex, int expected)
{
Assert.Equal(expected, new Utf8String(haystack).IndexOf(needle, startIndex));
}
[Theory]
[InlineData("01234567890123456789", '0', 10)]
[InlineData("01234567890123456789", '5', 15)]
[InlineData("01234567890123456789", 'a', -1)]
public void LastIndexOfChar(string haystack, char needle, int expected)
{
Assert.Equal(expected, new Utf8String(haystack).LastIndexOf(needle));
}
[Theory]
[InlineData("012345678901234567890123456789", '0', 29, 20)]
[InlineData("012345678901234567890123456789", '0', 19, 10)]
[InlineData("012345678901234567890123456789", '0', 9, 0)]
[InlineData("012345678901234567890123456789", 'a', 20, -1)]
public void LastIndexOfCharStartingAtIndex(string haystack, char needle, int startIndex, int expected)
{
Assert.Equal(expected, new Utf8String(haystack).LastIndexOf(needle, startIndex));
}
[Theory]
[InlineData("0123456789", "01", 0)]
[InlineData("0123456789", "56", 5)]
[InlineData("0123456789", "ab", -1)]
public void IndexOfString(string haystack, string needle, int expected)
{
Assert.Equal(expected, new Utf8String(haystack).IndexOf(needle));
}
[Theory]
[InlineData("012345678901234567890123456789", "01", 0, 0)]
[InlineData("012345678901234567890123456789", "01", 1, 10)]
[InlineData("012345678901234567890123456789", "01", 11, 20)]
[InlineData("012345678901234567890123456789", "01", 21, -1)]
public void IndexOfStringStartingAtIndex(string haystack, string needle, int startIndex, int expected)
{
Assert.Equal(expected, new Utf8String(haystack).IndexOf(needle, startIndex));
}
} | 87 | 5,423 | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using AsmResolver.Collections;
using AsmResolver.Shims;
namespace AsmResolver
{
/// <summary>
/// Represents an immutable UTF-8 encoded string. This class supports preserving invalid UTF-8 code sequences.
/// </summary>
[DebuggerDisplay("{DebugDisplay}")]
public sealed class Utf8String :
IEquatable<Utf8String>,
IEquatable<string>,
IEquatable<byte[]>,
IComparable<Utf8String>,
IEnumerable<char>
{
/// <summary>
/// Represents the empty UTF-8 string.
/// </summary>
public static readonly Utf8String Empty = new(ArrayShim.Empty<byte>());
private readonly byte[] _data;
private string? _cachedString;
/// <summary>
/// Creates a new UTF-8 string from the provided raw data.
/// </summary>
/// <param name="data">The raw UTF-8 data.</param>
public Utf8String(byte[] data)
: this(data, 0, data.Length)
{
}
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
/// <summary>
/// Creates a new UTF-8 string from the provided raw data.
/// </summary>
/// <param name="data">The raw UTF-8 data.</param>
public Utf8String(ReadOnlySpan<byte> data)
{
_data = data.ToArray();
}
/// <summary>
/// Creates a new UTF-8 string from the provided <see cref="System.ReadOnlySpan{Char}"/>.
/// </summary>
/// <param name="value">The string value to encode as UTF-8.</param>
public Utf8String(ReadOnlySpan<char> value)
{
_data = new byte[Encoding.UTF8.GetByteCount(value)];
Encoding.UTF8.GetBytes(value, _data.AsSpan());
}
#endif
/// <summary>
/// Creates a new UTF-8 string from the provided raw data.
/// </summary>
/// <param name="data">The raw UTF-8 data.</param>
/// <param name="index">The starting index to read from.</param>
/// <param name="count">The number of bytes to read..</param>
public Utf8String(byte[] data, int index, int count)
{
// Copy data to enforce immutability.
_data = new byte[count];
Buffer.BlockCopy(data, index, _data,0, count);
}
/// <summary>
/// Creates a new UTF-8 string from the provided <see cref="System.String"/>.
/// </summary>
/// <param name="value">The string value to encode as UTF-8.</param>
public Utf8String(string value)
{
_data = Encoding.UTF8.GetBytes(value);
_cachedString = value;
}
/// <summary>
/// Gets the string value represented by the UTF-8 bytes.
/// </summary>
public string Value => _cachedString ??= Encoding.UTF8.GetString(_data);
/// <summary>
/// Gets the number of bytes used by the string.
/// </summary>
public int ByteCount => _data.Length;
/// <summary>
/// Gets the number of characters in the string.
/// </summary>
public int Length => _cachedString is null ? Encoding.UTF8.GetCharCount(_data) : Value.Length;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal string DebugDisplay => Value.CreateEscapedString();
/// <summary>
/// Gets a single character in the string.
/// </summary>
/// <param name="index">The character index.</param>
public char this[int index] => Value[index];
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
/// <summary>
/// Creates a new read-only span over the string.
/// </summary>
/// <returns>The read-only span representation of the string.</returns>
public ReadOnlySpan<byte> AsSpan()
{
return _data.AsSpan();
}
/// <summary>
/// Creates a new read-only span over the string.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <returns>The read-only span representation of the string.</returns>
public ReadOnlySpan<byte> AsSpan(int start)
{
return _data.AsSpan(start);
}
/// <summary>
/// Creates a new read-only span over the string.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice.</param>
/// <returns>The read-only span representation of the string.</returns>
public ReadOnlySpan<byte> AsSpan(int start, int length)
{
return _data.AsSpan(start, length);
}
#endif
/// <summary>
/// Gets the raw UTF-8 bytes of the string.
/// </summary>
/// <returns>The bytes.</returns>
public byte[] GetBytes()
{
byte[] copy = new byte[_data.Length];
GetBytes(copy, 0, copy.Length);
return copy;
}
/// <summary>
/// Obtains the raw UTF-8 bytes of the string, and writes it into the provided buffer.
/// </summary>
/// <param name="buffer">The output buffer to receive the bytes in.</param>
/// <param name="index">The index into the output buffer to start writing at.</param>
/// <param name="length">The number of bytes to write.</param>
/// <returns>The actual number of bytes that were written.</returns>
public int GetBytes(byte[] buffer, int index, int length)
{
length = Math.Min(length, ByteCount);
Buffer.BlockCopy(_data, 0, buffer,index, length);
return length;
}
/// <summary>
/// Gets the underlying byte array of this string.
/// </summary>
/// <remarks>
/// This method should only be used if performance is critical. Modifying the returning array
/// <strong>will</strong> change the internal state of the string.
/// </remarks>
/// <returns>The bytes.</returns>
public byte[] GetBytesUnsafe() => _data;
/// <summary>
/// Produces a new string that is the concatenation of the current string and the provided string.
/// </summary>
/// <param name="other">The other string to append..</param>
/// <returns>The new string.</returns>
public Utf8String Concat(Utf8String? other) => !IsNullOrEmpty(other)
? Concat(other._data)
: this;
/// <summary>
/// Produces a new string that is the concatenation of the current string and the provided string.
/// </summary>
/// <param name="other">The other string to append..</param>
/// <returns>The new string.</returns>
public Utf8String Concat(string? other) => !string.IsNullOrEmpty(other)
? Concat(Encoding.UTF8.GetBytes(other!))
: this;
/// <summary>
/// Produces a new string that is the concatenation of the current string and the provided byte array.
/// </summary>
/// <param name="other">The byte array to append.</param>
/// <returns>The new string.</returns>
public Utf8String Concat(byte[]? other)
{
if (other is null || other.Length == 0)
return this;
byte[] result = new byte[Length + other.Length];
Buffer.BlockCopy(_data, 0, result, 0, _data.Length);
Buffer.BlockCopy(other, 0, result, _data.Length, other.Length);
return result;
}
/// <summary>
/// Gets the zero-based index of the first occurrence of the provided character in the string.
/// </summary>
/// <param name="needle">The character to search.</param>
/// <returns>The index, or -1 if the character is not present.</returns>
public int IndexOf(char needle) => Value.IndexOf(needle);
/// <summary>
/// Gets the zero-based index of the first occurrence of the provided character in the string.
/// </summary>
/// <param name="needle">The character to search.</param>
/// <param name="startIndex">The index to start searching at.</param>
/// <returns>The index, or -1 if the character is not present.</returns>
public int IndexOf(char needle, int startIndex) => Value.IndexOf(needle, startIndex);
/// <summary>
/// Gets the zero-based index of the first occurrence of the provided string in the string.
/// </summary>
/// <param name="needle">The string to search.</param>
/// <returns>The index, or -1 if the string is not present.</returns>
public int IndexOf(string needle) => Value.IndexOf(needle);
/// <summary>
/// Gets the zero-based index of the first occurrence of the provided string in the string.
/// </summary>
/// <param name="needle">The string to search.</param>
/// <param name="startIndex">The index to start searching at.</param>
/// <returns>The index, or -1 if the string is not present.</returns>
public int IndexOf(string needle, int startIndex) => Value.IndexOf(needle, startIndex);
/// <summary>
/// Gets the zero-based index of the first occurrence of the provided string in the string.
/// </summary>
/// <param name="needle">The string to search.</param>
/// <param name="comparison">The comparison algorithm to use.</param>
/// <returns>The index, or -1 if the string is not present.</returns>
public int IndexOf(string needle, StringComparison comparison) => Value.IndexOf(needle, comparison);
/// <summary>
/// Gets the zero-based index of the first occurrence of the provided string in the string.
/// </summary>
/// <param name="needle">The string to search.</param>
/// <param name="startIndex">The index to start searching at.</param>
/// <param name="comparison">The comparison algorithm to use.</param>
/// <returns>The index, or -1 if the string is not present.</returns>
public int IndexOf(string needle, int startIndex, StringComparison comparison) => Value.IndexOf(needle, startIndex, comparison);
/// <summary>
/// Gets the zero-based index of the last occurrence of the provided character in the string.
/// </summary>
/// <param name="needle">The character to search.</param>
/// <returns>The index, or -1 if the character is not present.</returns>
public int LastIndexOf(char needle) => Value.LastIndexOf(needle);
/// <summary>
/// Gets the zero-based index of the last occurrence of the provided character in the string.
/// </summary>
/// <param name="needle">The character to search.</param>
/// <param name="startIndex">The index to start searching at.</param>
/// <returns>The index, or -1 if the character is not present.</returns>
public int LastIndexOf(char needle, int startIndex) => Value.LastIndexOf(needle, startIndex);
/// <summary>
/// Gets the zero-based index of the last occurrence of the provided string in the string.
/// </summary>
/// <param name="needle">The string to search.</param>
/// <returns>The index, or -1 if the string is not present.</returns>
public int LastIndexOf(string needle) => Value.LastIndexOf(needle);
/// <summary>
/// Gets the zero-based index of the first occurrence of the provided string in the string.
/// </summary>
/// <param name="needle">The string to search.</param>
/// <param name="startIndex">The index to start searching at.</param>
/// <returns>The index, or -1 if the string is not present.</returns>
public int LastIndexOf(string needle, int startIndex) => Value.LastIndexOf(needle, startIndex);
/// <summary>
/// Gets the zero-based index of the last occurrence of the provided string in the string.
/// </summary>
/// <param name="needle">The string to search.</param>
/// <param name="comparison">The comparison algorithm to use.</param>
/// <returns>The index, or -1 if the string is not present.</returns>
public int LastIndexOf(string needle, StringComparison comparison) => Value.LastIndexOf(needle, comparison);
/// <summary>
/// Gets the zero-based index of the last occurrence of the provided string in the string.
/// </summary>
/// <param name="needle">The string to search.</param>
/// <param name="startIndex">The index to start searching at.</param>
/// <param name="comparison">The comparison algorithm to use.</param>
/// <returns>The index, or -1 if the string is not present.</returns>
public int LastIndexOf(string needle, int startIndex, StringComparison comparison) => Value.LastIndexOf(needle, startIndex, comparison);
/// <summary>
/// Determines whether the string contains the provided string.
/// </summary>
/// <param name="needle">The string to search.</param>
/// <returns><c>true</c> if the string is present, <c>false</c> otherwise.</returns>
public bool Contains(string needle) => IndexOf(needle) >= 0;
/// <summary>
/// Determines whether the provided string is <c>null</c> or the empty string.
/// </summary>
/// <param name="value">The string to verify.</param>
/// <returns><c>true</c> if the string is <c>null</c> or empty, <c>false</c> otherwise.</returns>
public static bool IsNullOrEmpty([NotNullWhen(false)] Utf8String? value) =>
value is null || value.ByteCount == 0;
/// <summary>
/// Determines whether two strings are considered equal.
/// </summary>
/// <param name="other">The other string.</param>
/// <returns><c>true</c> if the strings are considered equal, <c>false</c> otherwise.</returns>
/// <remarks>
/// This operation performs a byte-level comparison of the two strings.
/// </remarks>
public bool Equals(Utf8String? other) =>
other is not null && ByteArrayEqualityComparer.Instance.Equals(_data, other._data);
/// <inheritdoc />
/// <remarks>
/// This operation performs a byte-level comparison of the two strings.
/// </remarks>
public bool Equals(byte[]? other) => other is not null && ByteArrayEqualityComparer.Instance.Equals(_data, other);
/// <inheritdoc />
/// <remarks>
/// This operation performs a byte-level comparison of the two strings.
/// </remarks>
public bool Equals(string? other) =>other is not null && Value.Equals(other);
/// <inheritdoc />
public int CompareTo(Utf8String? other) => other is not null
? ByteArrayEqualityComparer.Instance.Compare(_data, other._data)
: 1;
/// <inheritdoc />
public IEnumerator<char> GetEnumerator() => Value.GetEnumerator();
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <inheritdoc />
/// <remarks>
/// This operation performs a byte-level comparison of the two strings.
/// </remarks>
public override bool Equals(object? obj) => ReferenceEquals(this, obj) || obj is Utf8String other && Equals(other);
/// <inheritdoc />
public override int GetHashCode() => ByteArrayEqualityComparer.Instance.GetHashCode(_data);
/// <inheritdoc />
public override string ToString() => Value;
/// <summary>
/// Converts a <see cref="Utf8String"/> into a <see cref="System.String"/>.
/// </summary>
/// <param name="value">The UTF-8 string value to convert.</param>
/// <returns>The string.</returns>
[return: NotNullIfNotNull("value")]
public static implicit operator string?(Utf8String? value)
{
if (value is null)
return null;
if (value.ByteCount == 0)
return string.Empty;
return value.Value;
}
/// <summary>
/// Converts a <see cref="System.String"/> into an <see cref="Utf8String"/>.
/// </summary>
/// <param name="value">The string value to convert.</param>
/// <returns>The new UTF-8 encoded string.</returns>
[return: NotNullIfNotNull("value")]
public static implicit operator Utf8String?(string? value)
{
if (value is null)
return null;
if (value.Length == 0)
return Empty;
return new Utf8String(value);
}
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER
/// <summary>
/// Converts a raw sequence of bytes into an <see cref="Utf8String"/>.
/// </summary>
/// <param name="data">The raw data to convert.</param>
/// <returns>The new UTF-8 encoded string.</returns>
public static implicit operator Utf8String(ReadOnlySpan<byte> data)
{
if (data.IsEmpty)
return Empty;
return new Utf8String(data);
}
/// <summary>
/// Converts a <see cref="System.ReadOnlySpan{Char}"/> into an <see cref="Utf8String"/>.
/// </summary>
/// <param name="data">The string value to convert.</param>
/// <returns>The new UTF-8 encoded string.</returns>
public static implicit operator Utf8String(ReadOnlySpan<char> data)
{
if (data.IsEmpty)
return Empty;
return new Utf8String(data);
}
/// <summary>
/// Converts a <see cref="Utf8String"/> into a <see cref="System.ReadOnlySpan{Byte}"/>.
/// </summary>
/// <param name="value">The UTF-8 string value to convert.</param>
/// <returns>The span.</returns>
public static implicit operator ReadOnlySpan<byte>(Utf8String? value)
{
if (value is null)
return ReadOnlySpan<byte>.Empty;
return value._data;
}
/// <summary>
/// Converts a <see cref="Utf8String"/> into a <see cref="System.ReadOnlySpan{Char}"/>.
/// </summary>
/// <param name="value">The UTF-8 string value to convert.</param>
/// <returns>The span.</returns>
public static implicit operator ReadOnlySpan<char>(Utf8String? value)
{
if (value is null)
return ReadOnlySpan<char>.Empty;
return value.Value;
}
#endif
/// <summary>
/// Converts a raw sequence of bytes into an <see cref="Utf8String"/>.
/// </summary>
/// <param name="data">The raw data to convert.</param>
/// <returns>The new UTF-8 encoded string.</returns>
[return: NotNullIfNotNull("data")]
public static implicit operator Utf8String?(byte[]? data)
{
if (data is null)
return null;
if (data.Length == 0)
return Empty;
return new Utf8String(data);
}
/// <summary>
/// Determines whether two UTF-8 encoded strings are considered equal.
/// </summary>
/// <param name="a">The first string.</param>
/// <param name="b">The second string.</param>
/// <returns><c>true</c> if the strings are considered equal, <c>false</c> otherwise.</returns>
/// <remarks>
/// This operation performs a byte-level comparison of the two strings.
/// </remarks>
public static bool operator ==(Utf8String? a, Utf8String? b)
{
if (ReferenceEquals(a, b))
return true;
if (a is null || b is null)
return false;
return a.Equals(b);
}
/// <summary>
/// Determines whether two UTF-8 encoded strings are not considered equal.
/// </summary>
/// <param name="a">The first string.</param>
/// <param name="b">The second string.</param>
/// <returns><c>true</c> if the strings are not considered equal, <c>false</c> otherwise.</returns>
/// <remarks>
/// This operation performs a byte-level comparison of the two strings.
/// </remarks>
public static bool operator !=(Utf8String? a, Utf8String? b) => !(a == b);
/// <summary>
/// Determines whether an UTF-8 encoded string is considered equal to the provided <see cref="System.String"/>.
/// </summary>
/// <param name="a">The first string.</param>
/// <param name="b">The second string.</param>
/// <returns><c>true</c> if the strings are considered equal, <c>false</c> otherwise.</returns>
/// <remarks>
/// This operation performs a string-level comparison.
/// </remarks>
public static bool operator ==(Utf8String? a, string? b)
{
if (a is null)
return b is null;
return b is not null && a.Equals(b);
}
/// <summary>
/// Determines whether an UTF-8 encoded string is not equal to the provided <see cref="System.String"/>.
/// </summary>
/// <param name="a">The first string.</param>
/// <param name="b">The second string.</param>
/// <returns><c>true</c> if the strings are not considered equal, <c>false</c> otherwise.</returns>
/// <remarks>
/// This operation performs a string-level comparison.
/// </remarks>
public static bool operator !=(Utf8String? a, string? b) => !(a == b);
/// <summary>
/// Determines whether the underlying bytes of an UTF-8 encoded string is equal to the provided byte array.
/// </summary>
/// <param name="a">The UTF-8 string.</param>
/// <param name="b">The byte array.</param>
/// <returns><c>true</c> if the byte arrays are considered equal, <c>false</c> otherwise.</returns>
/// <remarks>
/// This operation performs a byte-level comparison.
/// </remarks>
public static bool operator ==(Utf8String? a, byte[]? b)
{
if (a is null)
return b is null;
return b is not null && a.Equals(b);
}
/// <summary>
/// Determines whether the underlying bytes of an UTF-8 encoded string is not equal to the provided byte array.
/// </summary>
/// <param name="a">The UTF-8 string.</param>
/// <param name="b">The byte array.</param>
/// <returns><c>true</c> if the byte arrays are not considered equal, <c>false</c> otherwise.</returns>
/// <remarks>
/// This operation performs a byte-level comparison.
/// </remarks>
public static bool operator !=(Utf8String? a, byte[]? b) => !(a == b);
/// <summary>
/// Concatenates two UTF-8 encoded strings together.
/// </summary>
/// <param name="a">The first string.</param>
/// <param name="b">The second string.</param>
/// <returns>The newly produced string.</returns>
public static Utf8String operator +(Utf8String? a, Utf8String? b)
{
if (IsNullOrEmpty(a))
return IsNullOrEmpty(b) ? Utf8String.Empty : b;
return a.Concat(b);
}
/// <summary>
/// Concatenates two UTF-8 encoded strings together.
/// </summary>
/// <param name="a">The first string.</param>
/// <param name="b">The second string.</param>
/// <returns>The newly produced string.</returns>
public static Utf8String operator +(Utf8String? a, string? b)
{
if (IsNullOrEmpty(a))
return string.IsNullOrEmpty(b) ? Empty : b!;
return a.Concat(b);
}
/// <summary>
/// Concatenates an UTF-8 encoded string together with a byte array.
/// </summary>
/// <param name="a">The string.</param>
/// <param name="b">The byte array.</param>
/// <returns>The newly produced string.</returns>
public static Utf8String operator +(Utf8String? a, byte[]? b)
{
if (IsNullOrEmpty(a))
return b is null || b.Length == 0 ? Empty : b;
return a.Concat(b);
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.File.Tests\AsmResolver.PE.File.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.File.Tests\PEFileTest.cs | AsmResolver.PE.File.Tests
| PEFileTest | ['private readonly TemporaryDirectoryFixture _fixture;'] | ['System', 'System.IO', 'System.Linq', 'System.Text', 'AsmResolver.IO', 'AsmResolver.Tests.Runners', 'Xunit'] | xUnit | net8.0 | public class PEFileTest : IClassFixture<TemporaryDirectoryFixture>
{
private readonly TemporaryDirectoryFixture _fixture;
public PEFileTest(TemporaryDirectoryFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void ValidRvaToFileOffset()
{
var peFile = PEFile.FromBytes(Properties.Resources.HelloWorld);
Assert.Equal(0x0000088Eu, peFile.RvaToFileOffset(0x0000268Eu));
}
[Fact]
public void InvalidRvaToFileOffset()
{
var peFile = PEFile.FromBytes(Properties.Resources.HelloWorld);
Assert.Throws<ArgumentOutOfRangeException>(() => peFile.RvaToFileOffset(0x3000));
}
[Fact]
public void ValidFileOffsetToRva()
{
var peFile = PEFile.FromBytes(Properties.Resources.HelloWorld);
Assert.Equal(0x0000268Eu, peFile.FileOffsetToRva(0x0000088Eu));
}
[Fact]
public void InvalidFileOffsetToRva()
{
var peFile = PEFile.FromBytes(Properties.Resources.HelloWorld);
Assert.Throws<ArgumentOutOfRangeException>(() => peFile.FileOffsetToRva(0x2000));
}
[Fact]
public void RebuildNetPENoChange()
{
var peFile = PEFile.FromBytes(Properties.Resources.HelloWorld);
_fixture
.GetRunner<FrameworkPERunner>()
.RebuildAndRun(peFile, "HelloWorld", "Hello World!\n");
}
[Fact]
public void RebuildNetPEAddSection()
{
const string fileName = "HelloWorld";
const string sectionName = ".test";
var sectionData = new byte[] {1, 3, 3, 7};
var peFile = PEFile.FromBytes(Properties.Resources.HelloWorld);
// Add a new section.
peFile.Sections.Add(new PESection(sectionName, SectionFlags.MemoryRead | SectionFlags.ContentInitializedData)
{
Contents = new DataSegment(sectionData)
});
// Rebuild and check if file is still runnable.
_fixture
.GetRunner<FrameworkPERunner>()
.RebuildAndRun(peFile, fileName, "Hello World!\n");
// Read the new file.
var newPEFile = PEFile.FromFile(_fixture
.GetRunner<FrameworkPERunner>()
.GetTestExecutablePath(nameof(PEFileTest), nameof(RebuildNetPEAddSection), fileName));
// Verify the section and its data is present:
var newSection = newPEFile.Sections.First(s => s.Name == sectionName);
var newData = new byte[sectionData.Length];
Assert.Equal(sectionData.Length, newSection
.CreateReader()
.ReadBytes(newData, 0, newData.Length));
Assert.Equal(sectionData, newData);
}
[Fact]
public void RoundTripPE()
{
// This test validates that a PE can be loaded, copied, and written, without altering the data
var originalBytes = Properties.Resources.NativeMemoryDemos;
var peFile = PEFile.FromBytes(originalBytes);
var msOutput = new MemoryStream();
var output = new PEFile(peFile.DosHeader, peFile.FileHeader, peFile.OptionalHeader);
foreach (var section in peFile.Sections)
{
var newSection = new PESection(section);
output.Sections.Add(newSection);
}
output.Write(new BinaryStreamWriter(msOutput));
Assert.Equal(originalBytes, msOutput.ToArray());
}
[Fact]
public void InsertSectionShouldPersistOtherSectionContents()
{
var peFile = PEFile.FromBytes(Properties.Resources.HelloWorld);
var section = peFile.Sections[0];
byte[] contents = ((IReadableSegment) section.Contents).ToArray();
peFile.Sections.Insert(0, new PESection(".test",
SectionFlags.MemoryRead | SectionFlags.MemoryWrite | SectionFlags.ContentInitializedData,
new DataSegment(new byte[] {1, 2, 3, 4})));
peFile.UpdateHeaders();
byte[] contents2 = ((IReadableSegment) section.Contents).ToArray();
Assert.Equal(contents, contents2);
}
[Fact]
public void RemoveSectionShouldPersistOtherSectionContents()
{
var peFile = PEFile.FromBytes(Properties.Resources.HelloWorld);
var section = peFile.Sections[1];
byte[] contents = ((IReadableSegment) section.Contents).ToArray();
peFile.Sections.RemoveAt(0);
peFile.UpdateHeaders();
byte[] contents2 = ((IReadableSegment) section.Contents).ToArray();
Assert.Equal(contents, contents2);
}
[Fact]
public void SectionsInMappedBinaryShouldUseVirtualAddressesAsOffset()
{
var physicalFile = PEFile.FromBytes(Properties.Resources.HelloWorld);
var memoryFile = PEFile.FromDataSource(
new ByteArrayDataSource(Properties.Resources.HelloWorldDump),
PEMappingMode.Mapped);
Assert.Equal(physicalFile.Sections.Count, memoryFile.Sections.Count);
for (int i = 0; i < physicalFile.Sections.Count; i++)
{
var physicalSection = physicalFile.Sections[i];
var memorySection = memoryFile.Sections[i];
Assert.NotEqual(physicalSection.Offset, memorySection.Offset);
Assert.Equal(physicalSection.Rva, memorySection.Rva);
byte[] expected = new byte[20];
physicalSection.CreateReader().ReadBytes(expected, 0, expected.Length);
byte[] actual = new byte[20];
memorySection.CreateReader().ReadBytes(actual, 0, actual.Length);
Assert.Equal(expected, actual);
}
}
[Fact]
public void PEWithNoEofData()
{
var file = PEFile.FromBytes(Properties.Resources.HelloWorld);
Assert.Null(file.EofData);
}
[Fact]
public void ReadEofData()
{
var file = PEFile.FromBytes(Properties.Resources.HelloWorld_EOF);
byte[] data = Assert.IsAssignableFrom<IReadableSegment>(file.EofData).ToArray();
Assert.Equal(Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwxyz"), data);
}
[Fact]
public void ReadEofDataFromFileOffset()
{
var file = PEFile.FromBytes(Properties.Resources.HelloWorld_EOF);
Assert.NotNull(file.EofData);
Assert.True(file.TryCreateReaderAtFileOffset((uint) file.EofData.Offset, out var reader));
byte[] data = reader.ReadToEnd();
Assert.Equal(Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwxyz"), data);
}
[Fact]
public void AddNewEofData()
{
byte[] expected = { 1, 2, 3, 4 };
var file = PEFile.FromBytes(Properties.Resources.HelloWorld);
Assert.Null(file.EofData);
file.EofData = new DataSegment(expected);
using var stream = new MemoryStream();
file.Write(stream);
byte[] newFileBytes = stream.ToArray();
Assert.Equal(expected, newFileBytes[^expected.Length..]);
var newFile = PEFile.FromBytes(newFileBytes);
var readable = Assert.IsAssignableFrom<IReadableSegment>(newFile.EofData);
Assert.Equal(expected, readable.ToArray());
}
[Fact]
public void ModifyExistingEofData()
{
var file = PEFile.FromBytes(Properties.Resources.HelloWorld_EOF);
byte[] data = Assert.IsAssignableFrom<IReadableSegment>(file.EofData).ToArray();
Array.Reverse(data);
file.EofData = new DataSegment(data);
using var stream = new MemoryStream();
file.Write(stream);
byte[] newFileBytes = stream.ToArray();
Assert.Equal(data, newFileBytes[^data.Length..]);
var newFile = PEFile.FromBytes(newFileBytes);
byte[] newData = Assert.IsAssignableFrom<IReadableSegment>(newFile.EofData).ToArray();
Assert.Equal(data, newData);
}
[Fact]
public void RemoveExistingEofData()
{
var file = PEFile.FromBytes(Properties.Resources.HelloWorld_EOF);
byte[] originalData = Assert.IsAssignableFrom<IReadableSegment>(file.EofData).ToArray();
file.EofData = null;
using var stream = new MemoryStream();
file.Write(stream);
byte[] newFileBytes = stream.ToArray();
Assert.NotEqual(originalData, newFileBytes[^originalData.Length..]);
var newFile = PEFile.FromBytes(newFileBytes);
Assert.Null(newFile.EofData);
}
[Fact]
public void ReadSections()
{
var file = PEFile.FromBytes(Properties.Resources.HelloWorld);
Assert.Equal(new[] {".text", ".rsrc", ".reloc"}, file.Sections.Select(x => x.Name.Value));
}
[Fact]
public void ReadInvalidSectionName()
{
var file = PEFile.FromBytes(Properties.Resources.HelloWorld_InvalidSectionName);
Assert.Equal(new[] {".text", ".rsrc", ".reloc"}, file.Sections.Select(x => x.Name.Value));
}
[Fact]
public void ReadExtraSectionData()
{
var file = PEFile.FromBytes(Properties.Resources.HelloWorld_ExtraSectionData);
var reader = Assert.IsAssignableFrom<IReadableSegment>(file.ExtraSectionData).CreateReader();
Assert.Equal("Hello, world", reader.ReadAsciiString());
}
[Fact]
public void PersistExtraSectionData()
{
var file = PEFile.FromBytes(Properties.Resources.HelloWorld);
file.ExtraSectionData = new DataSegment(Encoding.ASCII.GetBytes("Hello, mars"));
using var stream = new MemoryStream();
file.Write(stream);
var newFile = PEFile.FromBytes(stream.ToArray());
var reader = Assert.IsAssignableFrom<IReadableSegment>(newFile.ExtraSectionData).CreateReader();
Assert.Equal("Hello, mars", reader.ReadAsciiString());
}
[Fact]
public void PersistLargeExtraSectionData()
{
byte[] data = Enumerable.Range(0, 255).Select(x => (byte) x).ToArray();
var file = PEFile.FromBytes(Properties.Resources.HelloWorld);
file.ExtraSectionData = new DataSegment(data);
using var stream = new MemoryStream();
file.Write(stream);
var newFile = PEFile.FromBytes(stream.ToArray());
var reader = Assert.IsAssignableFrom<IReadableSegment>(newFile.ExtraSectionData).CreateReader();
byte[] actualBytes = new byte[data.Length];
Assert.Equal(data.Length, reader.ReadBytes(actualBytes, 0, actualBytes.Length));
Assert.Equal(data, actualBytes);
}
} | 190 | 11,677 | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using AsmResolver.IO;
namespace AsmResolver.PE.File
{
/// <summary>
/// Models a file using the portable executable (PE) file format. It provides access to various PE headers, as well
/// as the raw contents of each section present in the file.
/// </summary>
public class PEFile : ISegmentReferenceFactory, IOffsetConverter
{
/// <summary>
/// Indicates a valid NT header signature.
/// </summary>
public const uint ValidPESignature = 0x4550; // "PE\0\0"
private readonly LazyVariable<PEFile, ISegment?> _extraSectionData;
private readonly LazyVariable<PEFile, ISegment?> _eofData;
private IList<PESection>? _sections;
/// <summary>
/// Creates a new empty portable executable file.
/// </summary>
public PEFile()
: this(new DosHeader(), new FileHeader(), new OptionalHeader())
{
}
/// <summary>
/// Creates a new portable executable file.
/// </summary>
/// <param name="dosHeader">The DOS header to add.</param>
/// <param name="fileHeader">The COFF header to add.</param>
/// <param name="optionalHeader">The optional header to add.</param>
public PEFile(DosHeader dosHeader, FileHeader fileHeader, OptionalHeader optionalHeader)
{
DosHeader = dosHeader ?? throw new ArgumentNullException(nameof(dosHeader));
FileHeader = fileHeader ?? throw new ArgumentNullException(nameof(fileHeader));
OptionalHeader = optionalHeader ?? throw new ArgumentNullException(nameof(optionalHeader));
_extraSectionData = new LazyVariable<PEFile, ISegment?>(x =>x.GetExtraSectionData());
_eofData = new LazyVariable<PEFile, ISegment?>(x =>x.GetEofData());
MappingMode = PEMappingMode.Unmapped;
}
/// <summary>
/// When this PE file was read from the disk, gets the file path to the PE file.
/// </summary>
public string? FilePath
{
get;
protected set;
}
/// <summary>
/// Gets or sets the DOS header of the PE file.
/// </summary>
public DosHeader DosHeader
{
get;
set;
}
/// <summary>
/// Gets or sets the COFF file header of the portable executable (PE) file.
/// </summary>
public FileHeader FileHeader
{
get;
set;
}
/// <summary>
/// Gets or sets the optional header of the portable executable (PE) file.
/// </summary>
public OptionalHeader OptionalHeader
{
get;
set;
}
/// <summary>
/// Gets a collection of sections present in the portable executable (PE) file.
/// </summary>
public IList<PESection> Sections
{
get
{
if (_sections is null)
Interlocked.CompareExchange(ref _sections, GetSections(), null);
return _sections;
}
}
/// <summary>
/// Gets a value indicating the mapping mode of the PE file. If the PE file is in its mapped form,
/// then every offset of all segments in the PE file will be equal to the physical memory address.
/// If the file is in its unmapped form, the offsets will be equal to the file offset.
/// </summary>
public PEMappingMode MappingMode
{
get;
protected set;
}
/// <summary>
/// Gets or sets the padding data in between the last section header and the first section.
/// </summary>
public ISegment? ExtraSectionData
{
get => _extraSectionData.GetValue(this);
set => _extraSectionData.SetValue(value);
}
/// <summary>
/// Gets or sets the data appended to the end of the file (EoF), if available.
/// </summary>
public ISegment? EofData
{
get => _eofData.GetValue(this);
set => _eofData.SetValue(value);
}
/// <summary>
/// Reads an unmapped PE file from the disk.
/// </summary>
/// <param name="path">The file path to the PE file.</param>
/// <returns>The PE file that was read.</returns>
/// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception>
public static PEFile FromFile(string path) => FromFile(UncachedFileService.Instance.OpenFile(path));
/// <summary>
/// Reads an unmapped PE file.
/// </summary>
/// <param name="file">The file representing the PE.</param>
/// <returns>The PE file that was read.</returns>
/// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception>
public static PEFile FromFile(IInputFile file)
{
var result = FromReader(file.CreateReader());
result.FilePath = file.FilePath;
return result;
}
/// <summary>
/// Reads an unmapped PE file from memory.
/// </summary>
/// <param name="raw">The raw bytes representing the contents of the PE file to read.</param>
/// <returns>The PE file that was read.</returns>
/// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception>
public static PEFile FromBytes(byte[] raw) => FromReader(new BinaryStreamReader(raw));
/// <summary>
/// Reads a mapped PE file starting at the provided module base address (HINSTANCE).
/// </summary>
/// <param name="hInstance">The HINSTANCE or base address of the module.</param>
/// <returns>The PE file that was read.</returns>
/// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception>
public static PEFile FromModuleBaseAddress(IntPtr hInstance) => FromModuleBaseAddress(hInstance, PEMappingMode.Mapped);
/// <summary>
/// Reads a PE file starting at the provided module base address (HINSTANCE).
/// </summary>
/// <param name="hInstance">The HINSTANCE or base address of the module.</param>
/// <param name="mode">Indicates how the input PE file is mapped.</param>
/// <returns>The PE file that was read.</returns>
/// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception>
public static unsafe PEFile FromModuleBaseAddress(IntPtr hInstance, PEMappingMode mode)
{
// Perform some minimal parsing to get the size of the image from the optional header.
uint nextHeaderOffset = *(uint*) ((byte*) hInstance + DosHeader.NextHeaderFieldOffset);
uint sizeOfImage = *(uint*) ((byte*) hInstance
+ nextHeaderOffset
+ sizeof(uint)
+ FileHeader.FileHeaderSize
+ OptionalHeader.OptionalHeaderSizeOfImageFieldOffset);
return FromDataSource(new UnmanagedDataSource(hInstance, sizeOfImage), mode);
}
/// <summary>
/// Reads a PE file from the provided data source.
/// </summary>
/// <param name="dataSource">The data source to read from.</param>
/// <param name="mode">Indicates how the input PE file is mapped.</param>
/// <returns>The PE file that was read.</returns>
/// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception>
public static PEFile FromDataSource(IDataSource dataSource, PEMappingMode mode = PEMappingMode.Unmapped) =>
FromReader(new BinaryStreamReader(dataSource, dataSource.BaseAddress, 0, (uint) dataSource.Length), mode);
/// <summary>
/// Reads a PE file from the provided input stream.
/// </summary>
/// <param name="reader">The input stream to read from.</param>
/// <param name="mode">Indicates how the input PE file is mapped.</param>
/// <returns>The PE file that was read.</returns>
/// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception>
public static PEFile FromReader(in BinaryStreamReader reader, PEMappingMode mode = PEMappingMode.Unmapped) =>
new SerializedPEFile(reader, mode);
/// <inheritdoc />
public ISegmentReference GetReferenceToRva(uint rva) => rva != 0
? new PESegmentReference(this, rva)
: SegmentReference.Null;
/// <inheritdoc />
public uint FileOffsetToRva(ulong fileOffset) =>
GetSectionContainingOffset(fileOffset).FileOffsetToRva(fileOffset);
/// <inheritdoc />
public ulong RvaToFileOffset(uint rva) => GetSectionContainingRva(rva).RvaToFileOffset(rva);
/// <summary>
/// Finds the section containing the provided file offset.
/// </summary>
/// <param name="fileOffset">The file offset.</param>
/// <returns>The section containing the file offset.</returns>
/// <exception cref="ArgumentOutOfRangeException">Occurs when the file offset does not fall within any of the sections.</exception>
public PESection GetSectionContainingOffset(ulong fileOffset)
{
if (!TryGetSectionContainingOffset(fileOffset, out var section))
throw new ArgumentOutOfRangeException(nameof(fileOffset));
return section;
}
/// <summary>
/// Attempts to find the section containing the provided file offset.
/// </summary>
/// <param name="fileOffset">The file offset.</param>
/// <param name="section">The section that was found.</param>
/// <returns><c>true</c> if the section was found, <c>false</c> otherwise.</returns>
public bool TryGetSectionContainingOffset(ulong fileOffset, [NotNullWhen(true)] out PESection? section)
{
var sections = Sections;
for (int i = 0; i < sections.Count; i++)
{
if (sections[i].ContainsFileOffset(fileOffset))
{
section = sections[i];
return true;
}
}
section = null;
return false;
}
/// <summary>
/// Finds the section containing the provided virtual address.
/// </summary>
/// <param name="rva">The virtual address.</param>
/// <returns>The section containing the virtual address.</returns>
/// <exception cref="ArgumentOutOfRangeException">Occurs when the virtual address does not fall within any of the sections.</exception>
public PESection GetSectionContainingRva(uint rva)
{
if (!TryGetSectionContainingRva(rva, out var section))
throw new ArgumentOutOfRangeException(nameof(rva));
return section;
}
/// <summary>
/// Attempts to find the section containing the provided virtual address.
/// </summary>
/// <param name="rva">The virtual address.</param>
/// <param name="section">The section that was found.</param>
/// <returns><c>true</c> if the section was found, <c>false</c> otherwise.</returns>
public bool TryGetSectionContainingRva(uint rva, [NotNullWhen(true)] out PESection? section)
{
var sections = Sections;
for (int i = 0; i < sections.Count; i++)
{
if (sections[i].ContainsRva(rva))
{
section = sections[i];
return true;
}
}
section = null;
return false;
}
/// <summary>
/// Obtains a reader that spans the provided data directory.
/// </summary>
/// <param name="dataDirectory">The data directory to read.</param>
/// <returns>The reader.</returns>
public BinaryStreamReader CreateDataDirectoryReader(DataDirectory dataDirectory)
{
var section = GetSectionContainingRva(dataDirectory.VirtualAddress);
ulong fileOffset = section.RvaToFileOffset(dataDirectory.VirtualAddress);
return section.CreateReader(fileOffset, dataDirectory.Size);
}
/// <summary>
/// Attempts to create a reader that spans the provided data directory.
/// </summary>
/// <param name="dataDirectory">The data directory to read.</param>
/// <param name="reader">The reader that was created.</param>
/// <returns><c>true</c> if the reader was created successfully, <c>false</c> otherwise.</returns>
public bool TryCreateDataDirectoryReader(DataDirectory dataDirectory, out BinaryStreamReader reader)
{
if (TryGetSectionContainingRva(dataDirectory.VirtualAddress, out var section))
{
ulong fileOffset = section.RvaToFileOffset(dataDirectory.VirtualAddress);
reader = section.CreateReader(fileOffset, dataDirectory.Size);
return true;
}
reader = default;
return false;
}
/// <summary>
/// Creates a new reader at the provided file offset.
/// </summary>
/// <param name="fileOffset">The file offset to start reading at.</param>
/// <returns>The reader.</returns>
public BinaryStreamReader CreateReaderAtFileOffset(uint fileOffset)
{
return !TryCreateReaderAtFileOffset(fileOffset, out var reader)
? throw new ArgumentOutOfRangeException(nameof(fileOffset))
: reader;
}
/// <summary>
/// Attempts to create a new reader at the provided file offset.
/// </summary>
/// <param name="fileOffset">The file offset to start reading at.</param>
/// <param name="reader">The reader that was created.</param>
/// <returns><c>true</c> if the reader was created successfully, <c>false</c> otherwise.</returns>
public bool TryCreateReaderAtFileOffset(uint fileOffset, out BinaryStreamReader reader)
{
if (TryGetSectionContainingOffset(fileOffset, out var section))
{
reader = section.CreateReader(fileOffset);
return true;
}
if (EofData is IReadableSegment eofData
&& fileOffset >= eofData.Offset
&& fileOffset < eofData.Offset + eofData.GetPhysicalSize())
{
reader = eofData.CreateReader(fileOffset);
return true;
}
reader = default;
return false;
}
/// <summary>
/// Creates a new reader of a chunk of data at the provided file offset.
/// </summary>
/// <param name="fileOffset">The file offset to start reading at.</param>
/// <param name="size">The number of bytes in the chunk.</param>
/// <returns>The reader.</returns>
public BinaryStreamReader CreateReaderAtFileOffset(uint fileOffset, uint size)
{
var section = GetSectionContainingOffset(fileOffset);
return section.CreateReader(fileOffset, size);
}
/// <summary>
/// Attempts to create a new reader of a chunk of data at the provided file offset.
/// </summary>
/// <param name="fileOffset">The file offset to start reading at.</param>
/// <param name="size">The number of bytes in the chunk.</param>
/// <param name="reader">The reader that was created.</param>
/// <returns><c>true</c> if the reader was created successfully, <c>false</c> otherwise.</returns>
public bool TryCreateReaderAtFileOffset(uint fileOffset, uint size, out BinaryStreamReader reader)
{
if (TryGetSectionContainingOffset(fileOffset, out var section))
{
reader = section.CreateReader(fileOffset, size);
return true;
}
if (EofData is IReadableSegment eofData
&& fileOffset >= eofData.Offset
&& fileOffset < eofData.Offset + eofData.GetPhysicalSize())
{
reader = eofData.CreateReader(fileOffset, size);
return true;
}
reader = default;
return false;
}
/// <summary>
/// Creates a new reader at the provided virtual address.
/// </summary>
/// <param name="rva">The virtual address to start reading at.</param>
/// <returns>The reader.</returns>
public BinaryStreamReader CreateReaderAtRva(uint rva)
{
var section = GetSectionContainingRva(rva);
return section.CreateReader(section.RvaToFileOffset(rva));
}
/// <summary>
/// Attempts to create a new reader at the provided virtual address.
/// </summary>
/// <param name="rva">The virtual address to start reading at.</param>
/// <param name="reader">The reader that was created.</param>
/// <returns><c>true</c> if the reader was created successfully, <c>false</c> otherwise.</returns>
public bool TryCreateReaderAtRva(uint rva, out BinaryStreamReader reader)
{
if (TryGetSectionContainingRva(rva, out var section))
{
reader = section.CreateReader(section.RvaToFileOffset(rva));
return true;
}
reader = default;
return false;
}
/// <summary>
/// Creates a new reader of a chunk of data at the provided virtual address.
/// </summary>
/// <param name="rva">The virtual address to start reading at.</param>
/// <param name="size">The number of bytes in the chunk.</param>
/// <returns>The reader.</returns>
public BinaryStreamReader CreateReaderAtRva(uint rva, uint size)
{
var section = GetSectionContainingRva(rva);
return section.CreateReader(section.RvaToFileOffset(rva), size);
}
/// <summary>
/// Attempts to create a new reader of a chunk of data at the provided virtual address.
/// </summary>
/// <param name="rva">The virtual address to start reading at.</param>
/// <param name="size">The number of bytes in the chunk.</param>
/// <param name="reader">The reader that was created.</param>
/// <returns><c>true</c> if the reader was created successfully, <c>false</c> otherwise.</returns>
public bool TryCreateReaderAtRva(uint rva, uint size, out BinaryStreamReader reader)
{
if (TryGetSectionContainingRva(rva, out var section))
{
reader = section.CreateReader(section.RvaToFileOffset(rva), size);
return true;
}
reader = default;
return false;
}
/// <summary>
/// Recomputes file offsets and sizes in the file, optional and section headers.
/// </summary>
/// <remarks>
/// Affected fields in the file header include:
/// <list type="bullet">
/// <item>
/// <term>SizeOfOptionalHeader</term>
/// </item>
/// </list>
/// Affected fields in the optional header include:
/// <list type="bullet">
/// <item>
/// <term>SizeOfHeaders</term>
/// <term>SizeOfImage</term>
/// <term>Data directories</term>
/// </item>
/// </list>
/// Affected fields in the section header include:
/// <list type="bullet">
/// <item>
/// <term>VirtualAddress</term>
/// <term>VirtualSize</term>
/// <term>PointerToRawData</term>
/// <term>SizeOfRawData</term>
/// </item>
/// </list>
/// </remarks>
public void UpdateHeaders()
{
var relocation = new RelocationParameters(OptionalHeader.ImageBase, 0, 0,
OptionalHeader.Magic == OptionalHeaderMagic.PE32);
// Update offsets of PE headers.
FileHeader.UpdateOffsets(
relocation.WithAdvance(DosHeader.NextHeaderOffset + sizeof(uint))
);
OptionalHeader.UpdateOffsets(
relocation.WithAdvance((uint) FileHeader.Offset + FileHeader.GetPhysicalSize())
);
// Sync file header fields with actual observed values.
FileHeader.NumberOfSections = (ushort) Sections.Count;
FileHeader.SizeOfOptionalHeader = (ushort) OptionalHeader.GetPhysicalSize();
// Compute headers size, and update offsets of extra data.
uint peHeadersSize = (uint) OptionalHeader.Offset
+ FileHeader.SizeOfOptionalHeader
+ SectionHeader.SectionHeaderSize * (uint) Sections.Count;
ExtraSectionData?.UpdateOffsets(relocation.WithAdvance(peHeadersSize));
uint totalHeadersSize = peHeadersSize + (ExtraSectionData?.GetPhysicalSize() ?? 0);
OptionalHeader.SizeOfHeaders = totalHeadersSize.Align(OptionalHeader.FileAlignment);
// Re-align sections and directories.
var oldSections = Sections.Select(x => x.CreateHeader()).ToList();
AlignSections();
AlignDataDirectoryEntries(oldSections);;
// Determine full size of image.
var lastSection = Sections[Sections.Count - 1];
OptionalHeader.SizeOfImage = lastSection.Rva
+ lastSection.GetVirtualSize().Align(OptionalHeader.SectionAlignment);
// Update EOF data offsets.
EofData?.UpdateOffsets(relocation.WithOffsetRva(
lastSection.Offset + lastSection.GetPhysicalSize(),
OptionalHeader.SizeOfImage));
}
/// <summary>
/// Aligns all sections according to the file and section alignment properties in the optional header.
/// </summary>
public void AlignSections()
{
var relocation = new RelocationParameters(
OptionalHeader.ImageBase,
OptionalHeader.SizeOfHeaders.Align(OptionalHeader.FileAlignment),
OptionalHeader.SizeOfHeaders.Align(OptionalHeader.SectionAlignment),
OptionalHeader.Magic == OptionalHeaderMagic.PE32);
for (int i = 0; i < Sections.Count; i++)
{
var section = Sections[i];
section.UpdateOffsets(relocation);
relocation.Advance(
section.GetPhysicalSize().Align(OptionalHeader.FileAlignment),
section.GetVirtualSize().Align(OptionalHeader.SectionAlignment));
}
}
/// <summary>
/// Aligns all data directories' virtual address according to the section header's ones.
/// </summary>
public void AlignDataDirectoryEntries(IList<SectionHeader> oldHeaders)
{
var dataDirectoryEntries = OptionalHeader.DataDirectories;
for (int j = 0; j < dataDirectoryEntries.Count; j++)
{
var dataDirectory = dataDirectoryEntries[j];
if (dataDirectory.IsPresentInPE)
{
uint virtualAddress = dataDirectory.VirtualAddress;
for(int i = 0; i < oldHeaders.Count; i++)
{
var header = oldHeaders[i];
// Locate section containing image directory.
if (header.VirtualAddress <= virtualAddress && header.VirtualAddress + header.SizeOfRawData > virtualAddress)
{
// Calculate the delta between the new section.rva and the old one.
if (Sections[i].Rva >= header.VirtualAddress)
{
uint sectionRvaDelta = Sections[i].Rva - header.VirtualAddress;
virtualAddress += sectionRvaDelta;
}
else
{
uint sectionRvaDelta = header.VirtualAddress - Sections[i].Rva;
virtualAddress -= sectionRvaDelta;
}
dataDirectoryEntries[j] = new DataDirectory(virtualAddress, dataDirectory.Size);
break;
}
}
}
}
}
/// <summary>
/// Writes the PE file to a file on the disk.
/// </summary>
/// <param name="filePath">The path of the file.</param>
public void Write(string filePath)
{
using var stream = System.IO.File.Create(filePath);
Write(stream);
}
/// <summary>
/// Writes the PE file to the provided output stream.
/// </summary>
/// <param name="stream">The output stream to write to.</param>
public void Write(Stream stream) => Write(new BinaryStreamWriter(stream));
/// <summary>
/// Writes the PE file to the provided output stream.
/// </summary>
/// <param name="writer">The output stream to write to.</param>
public void Write(BinaryStreamWriter writer)
{
UpdateHeaders();
// Dos header.
DosHeader.Write(writer);
// NT headers
writer.Offset = DosHeader.NextHeaderOffset;
writer.WriteUInt32(ValidPESignature);
FileHeader.Write(writer);
OptionalHeader.Write(writer);
// Section headers.
writer.Offset = OptionalHeader.Offset + FileHeader.SizeOfOptionalHeader;
for (int i = 0; i < Sections.Count; i++)
Sections[i].CreateHeader().Write(writer);
// Data between section headers and sections.
ExtraSectionData?.Write(writer);
// Sections.
writer.Offset = OptionalHeader.SizeOfHeaders;
for (int i = 0; i < Sections.Count; i++)
{
var section = Sections[i];
writer.Offset = section.Offset;
section.Contents?.Write(writer);
writer.Align(OptionalHeader.FileAlignment);
}
// EOF Data.
EofData?.Write(writer);
}
/// <summary>
/// Obtains the sections in the portable executable file.
/// </summary>
/// <returns>The section.</returns>
/// <remarks>
/// This method is called upon the initialization of the <see cref="Sections"/> property.
/// </remarks>
protected virtual IList<PESection> GetSections() => new PESectionCollection(this);
/// <summary>
/// Obtains the padding data in between the last section header and the first section.
/// </summary>
/// <returns>The extra padding data.</returns>
/// <remarks>
/// This method is called upon the initialization of the <see cref="ExtraSectionData"/> property.
/// </remarks>
protected virtual ISegment? GetExtraSectionData() => null;
/// <summary>
/// Obtains any data appended to the end of the file (EoF).
/// </summary>
/// <returns>The extra data.</returns>
/// <remarks>
/// This method is called upon the initialization of the <see cref="EofData"/> property.
/// </remarks>
protected virtual ISegment? GetEofData() => null;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Builder\ManagedPEFileBuilderTest.cs | AsmResolver.PE.Tests.Builder
| ManagedPEFileBuilderTest | ['private readonly TemporaryDirectoryFixture _fixture;'] | ['System.IO', 'AsmResolver.PE.Builder', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'AsmResolver.PE.File', 'AsmResolver.Tests.Runners', 'Xunit'] | xUnit | net8.0 | public class ManagedPEFileBuilderTest : IClassFixture<TemporaryDirectoryFixture>
{
private readonly TemporaryDirectoryFixture _fixture;
public ManagedPEFileBuilderTest(TemporaryDirectoryFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void HelloWorldRebuild32BitNoChange()
{
// Read image
var image = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Rebuild
var builder = new ManagedPEFileBuilder();
var peFile = builder.CreateFile(image);
// Verify
_fixture
.GetRunner<FrameworkPERunner>()
.RebuildAndRun(peFile, "HelloWorld", "Hello World!\n");
}
[Fact]
public void HelloWorldRebuild64BitNoChange()
{
// Read image
var image = PEImage.FromBytes(Properties.Resources.HelloWorld_X64, TestReaderParameters);
// Rebuild
var builder = new ManagedPEFileBuilder();
var peFile = builder.CreateFile(image);
// Verify
_fixture
.GetRunner<FrameworkPERunner>()
.RebuildAndRun(peFile, "HelloWorld", "Hello World!\n");
}
[Fact]
public void HelloWorld32BitTo64Bit()
{
// Read image
var image = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Change machine type and pe kind to 64-bit
image.MachineType = MachineType.Amd64;
image.PEKind = OptionalHeaderMagic.PE32Plus;
// Rebuild
var builder = new ManagedPEFileBuilder();
var peFile = builder.CreateFile(image);
// Verify
_fixture
.GetRunner<FrameworkPERunner>()
.RebuildAndRun(peFile, "HelloWorld", "Hello World!\n");
}
[Fact]
public void HelloWorld64BitTo32Bit()
{
// Read image
var image = PEImage.FromBytes(Properties.Resources.HelloWorld_X64, TestReaderParameters);
// Change machine type and pe kind to 32-bit
image.MachineType = MachineType.I386;
image.PEKind = OptionalHeaderMagic.PE32;
// Rebuild
var builder = new ManagedPEFileBuilder();
var peFile = builder.CreateFile(image);
// Verify
_fixture
.GetRunner<FrameworkPERunner>()
.RebuildAndRun(peFile, "HelloWorld", "Hello World!\n");
}
[Fact]
public void UpdateFieldRvaRowsUnchanged()
{
var image = PEImage.FromBytes(Properties.Resources.FieldRvaTest, TestReaderParameters);
using var stream = new MemoryStream();
var file = new ManagedPEFileBuilder(EmptyErrorListener.Instance).CreateFile(image);
file.Write(stream);
var newImage = PEImage.FromBytes(stream.ToArray(), TestReaderParameters);
var table = newImage.DotNetDirectory!.Metadata!
.GetStream<TablesStream>()
.GetTable<FieldRvaRow>();
byte[] data = new byte[16];
table[0].Data.CreateReader().ReadBytes(data, 0, data.Length);
Assert.Equal(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, data);
Assert.Equal(0x12345678u, table[1].Data.Rva);
}
} | 259 | 3,859 | using System;
using System.Collections.Generic;
using System.Linq;
using AsmResolver.PE.DotNet;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.File;
using AsmResolver.PE.Imports;
using AsmResolver.PE.Relocations;
namespace AsmResolver.PE.Builder;
/// <summary>
/// Provides a mechanism for constructing PE files from images containing .NET metadata.
/// </summary>
/// <remarks>
/// <para>
/// This PE builder is focused on .NET images only, and assumes that every input PE image is either a fully .NET
/// image with only architecture independent code (CIL), or contains native methods that are fully well-defined,
/// i.e. they are represented by a single segment. Any method definition in the metadata table that references a
/// native method body of which the size is not explicitly defined will cause an exception. This class also might
/// replace rows in the method and/or field RVA metadata tables with new ones containing the updated references to
/// method bodies and/or field data. All remaining metadata in the tables stream and in the other metadata streams
/// is written as-is without any change or verification.
/// </para>
/// <para>
/// This class might modify the final imports directory (exposed by the <see cref="PEImage.Imports"/> property),
/// as well as the base relocations directory (exposed by the <see cref="PEImage.Relocations"/> property). In
/// particular, it might add or remove the entry to <c>mscoree.dll!_CorExeMain</c> or <c>mscoree.dll!_CorDllMain</c>,
/// depending on the machine type specified by the <see cref="PEImage.MachineType"/> property.
/// </para>
/// <para>
/// This class builds up at most four PE sections; <c>.text</c>, <c>.sdata</c>, <c>.rsrc</c> and <c>.reloc</c>,
/// similar to what a normal .NET language compiler would emit. Almost everything is put into the .text section,
/// including the import and debug directories. The win32 resources are put into <c>.rsrc</c> section, and this
/// section will only be added if there is at least one entry in the root resource directory of the
/// <see cref="PEImage.Resources"/> property. Similarly, the <c>.sdata</c> section is only added if at least
/// one unmanaged export is added to the PE image. Finally, the <c>.reloc</c> section is only added if at least
/// one base relocation was put into the directory, or when the CLR bootstrapper requires one.
/// </para>
/// </remarks>
public class ManagedPEFileBuilder : PEFileBuilder
{
/// <summary>
/// Creates a new managed PE file builder with default settings.
/// </summary>
public ManagedPEFileBuilder()
: this(ThrowErrorListener.Instance)
{
}
/// <summary>
/// Creates a new managed PE file builder with the provided error listener.
/// </summary>
public ManagedPEFileBuilder(IErrorListener errorListener)
{
ErrorListener = errorListener;
}
/// <summary>
/// Gets or sets the object responsible for recording diagnostic information during the building process.
/// </summary>
public IErrorListener ErrorListener
{
get;
set;
}
/// <inheritdoc />
protected override IEnumerable<PESection> CreateSections(PEFileBuilderContext context)
{
var image = context.Image;
if (image.DotNetDirectory is null)
ErrorListener.RegisterException(new ArgumentException("PE image does not contain a valid .NET data directory."));
var sections = new List<PESection>();
// Always create .text section.
sections.Add(CreateTextSection(context));
// Add .sdata section when necessary.
if (!context.ExportDirectory.IsEmpty || image.DotNetDirectory?.VTableFixups is not null)
sections.Add(CreateSDataSection(context));
// Add .rsrc section when necessary.
if (!context.ResourceDirectory.IsEmpty)
sections.Add(CreateRsrcSection(context));
// Add .reloc section when necessary.
if (!context.RelocationsDirectory.IsEmpty)
sections.Add(CreateRelocSection(context));
return sections;
}
/// <summary>
/// Builds up the main text section (.text) of the new .NET PE file.
/// </summary>
/// <param name="context">The working space of the builder.</param>
/// <returns>The .text section.</returns>
protected virtual PESection CreateTextSection(PEFileBuilderContext context)
{
var contents = new SegmentBuilder();
if (!context.ImportDirectory.IsEmpty)
contents.Add(context.ImportDirectory.ImportAddressDirectory);
contents.Add(CreateDotNetSegment(context));
if (!context.ImportDirectory.IsEmpty)
contents.Add(context.ImportDirectory);
if (!context.ExportDirectory.IsEmpty)
contents.Add(context.ExportDirectory);
if (!context.DebugDirectory.IsEmpty)
{
contents.Add(context.DebugDirectory);
contents.Add(context.DebugDirectory.ContentsTable);
}
if (context.ClrBootstrapper.HasValue)
contents.Add(context.ClrBootstrapper.Value.Segment);
if (context.Image.Exports is { Entries: { Count: > 0 } entries })
{
for (int i = 0; i < entries.Count; i++)
{
var export = entries[i];
if (export.Address.IsBounded && export.Address.GetSegment() is { } segment)
contents.Add(segment, (uint) context.Platform.PointerSize);
}
}
return new PESection(
".text",
SectionFlags.ContentCode | SectionFlags.MemoryExecute | SectionFlags.MemoryRead,
contents
);
}
private static ISegment CreateDotNetSegment(PEFileBuilderContext context)
{
var dotNetDirectory = context.Image.DotNetDirectory!;
var result = new SegmentBuilder
{
dotNetDirectory,
context.FieldRvaTable,
context.MethodBodyTable,
};
AddIfPresent(dotNetDirectory.Metadata);
AddIfPresent(dotNetDirectory.DotNetResources);
AddIfPresent(dotNetDirectory.StrongName);
if (dotNetDirectory.VTableFixups?.Count > 0)
result.Add(dotNetDirectory.VTableFixups);
AddIfPresent(dotNetDirectory.ExportAddressTable);
AddIfPresent(dotNetDirectory.ManagedNativeHeader);
return result;
void AddIfPresent(ISegment? segment)
{
if (segment is not null)
result.Add(segment, 4);
}
}
/// <summary>
/// Creates the .sdata section containing the exports and vtables directory of the new .NET PE file.
/// </summary>
/// <param name="context">The working space of the builder.</param>
/// <returns>The section.</returns>
protected virtual PESection CreateSDataSection(PEFileBuilderContext context)
{
var image = context.Image;
var contents = new SegmentBuilder();
if (image.DotNetDirectory?.VTableFixups is { } fixups)
{
for (int i = 0; i < fixups.Count; i++)
contents.Add(fixups[i].Tokens, (uint) context.Platform.PointerSize);
}
if (image.Exports is { Entries.Count: > 0 })
contents.Add(context.ExportDirectory, (uint) context.Platform.PointerSize);
return new PESection(
".sdata",
SectionFlags.MemoryRead | SectionFlags.MemoryWrite | SectionFlags.ContentInitializedData,
contents
);
}
/// <summary>
/// Creates the win32 resources section (.rsrc) of the new .NET PE file.
/// </summary>
/// <param name="context">The working space of the builder.</param>
/// <returns>The resources section.</returns>
protected virtual PESection CreateRsrcSection(PEFileBuilderContext context)
{
return new PESection(
".rsrc",
SectionFlags.MemoryRead | SectionFlags.ContentInitializedData,
context.ResourceDirectory
);
}
/// <summary>
/// Creates the base relocations section (.reloc) of the new .NET PE file.
/// </summary>
/// <param name="context">The working space of the builder.</param>
/// <returns>The base relocations section.</returns>
protected virtual PESection CreateRelocSection(PEFileBuilderContext context)
{
return new PESection(
".reloc",
SectionFlags.MemoryRead | SectionFlags.ContentInitializedData | SectionFlags.MemoryDiscardable,
context.RelocationsDirectory
);
}
/// <inheritdoc />
protected override void CreateDataDirectoryBuffers(PEFileBuilderContext context)
{
CreateDotNetDirectories(context);
base.CreateDataDirectoryBuffers(context);
}
/// <inheritdoc />
protected override void CreateImportDirectory(PEFileBuilderContext context)
{
var image = context.Image;
bool includeClrBootstrapper = image.DotNetDirectory is not null
&& (
context.Platform.IsClrBootstrapperRequired
|| (image.DotNetDirectory?.Flags & DotNetDirectoryFlags.ILOnly) == 0
);
string clrEntryPointName = (image.Characteristics & Characteristics.Dll) != 0
? "_CorDllMain"
: "_CorExeMain";
var modules = CollectImportedModules(
image,
includeClrBootstrapper,
clrEntryPointName,
out var entryPointSymbol
);
foreach (var module in modules)
context.ImportDirectory.AddModule(module);
if (includeClrBootstrapper)
{
if (entryPointSymbol is null)
throw new InvalidOperationException("Entry point symbol was required but not imported.");
context.ClrBootstrapper = context.Platform.CreateThunkStub(entryPointSymbol);
}
}
private static List<ImportedModule> CollectImportedModules(
PEImage image,
bool requireClrEntryPoint,
string clrEntryPointName,
out ImportedSymbol? clrEntryPoint)
{
clrEntryPoint = null;
var modules = image.Imports.ToList();
if (requireClrEntryPoint)
{
// Add mscoree.dll if it wasn't imported yet.
if (modules.FirstOrDefault(x => x.Name == "mscoree.dll") is not { } mscoreeModule)
{
mscoreeModule = new ImportedModule("mscoree.dll");
modules.Add(mscoreeModule);
}
// Add entry point sumbol if it wasn't imported yet.
clrEntryPoint = mscoreeModule.Symbols.FirstOrDefault(x => x.Name == clrEntryPointName);
if (clrEntryPoint is null)
{
clrEntryPoint = new ImportedSymbol(0, clrEntryPointName);
mscoreeModule.Symbols.Add(clrEntryPoint);
}
}
else
{
// Remove mscoree.dll!_CorXXXMain and entry of mscoree.dll.
if (modules.FirstOrDefault(x => x.Name == "mscoree.dll") is { } mscoreeModule)
{
if (mscoreeModule.Symbols.FirstOrDefault(x => x.Name == clrEntryPointName) is { } entry)
mscoreeModule.Symbols.Remove(entry);
if (mscoreeModule.Symbols.Count == 0)
modules.Remove(mscoreeModule);
}
}
return modules;
}
/// <inheritdoc />
protected override void CreateRelocationsDirectory(PEFileBuilderContext context)
{
// Since the PE is rebuild in its entirety, all relocations that were originally in the PE are invalidated.
// Therefore, we filter out all relocations that were added by the reader.
AddRange(context.Image.Relocations.Where(x => x.Location is not PESegmentReference));
// Add relocations of the bootstrapper stub if necessary.
if (context.ClrBootstrapper is { } bootstrapper)
AddRange(bootstrapper.Relocations);
return;
void AddRange(IEnumerable<BaseRelocation> relocations)
{
foreach (var relocation in relocations)
context.RelocationsDirectory.Add(relocation);
}
}
private void CreateDotNetDirectories(PEFileBuilderContext context) => ProcessRvasInMetadataTables(context);
/// <inheritdoc />
protected override void AssignDataDirectories(PEFileBuilderContext context, PEFile outputFile)
{
var header = outputFile.OptionalHeader;
header.DataDirectories.Clear();
header.EnsureDataDirectoryCount(OptionalHeader.DefaultNumberOfRvasAndSizes);
if (!context.ImportDirectory.IsEmpty)
{
header.SetDataDirectory(DataDirectoryIndex.ImportDirectory, context.ImportDirectory);
header.SetDataDirectory(DataDirectoryIndex.IatDirectory, context.ImportDirectory.ImportAddressDirectory);
}
if (!context.ExportDirectory.IsEmpty)
header.SetDataDirectory(DataDirectoryIndex.ExportDirectory, context.ExportDirectory);
if (!context.DebugDirectory.IsEmpty)
header.SetDataDirectory(DataDirectoryIndex.DebugDirectory, context.DebugDirectory);
if (!context.ResourceDirectory.IsEmpty)
header.SetDataDirectory(DataDirectoryIndex.ResourceDirectory, context.ResourceDirectory);
if (context.Image.DotNetDirectory is not null)
header.SetDataDirectory(DataDirectoryIndex.ClrDirectory, context.Image.DotNetDirectory);
if (!context.RelocationsDirectory.IsEmpty)
header.SetDataDirectory(DataDirectoryIndex.BaseRelocationDirectory, context.RelocationsDirectory);
}
/// <inheritdoc />
protected override uint GetEntryPointAddress(PEFileBuilderContext context, PEFile outputFile)
=> context.ClrBootstrapper?.Segment.Rva ?? 0;
private void ProcessRvasInMetadataTables(PEFileBuilderContext context)
{
var tablesStream = context.Image.DotNetDirectory?.Metadata?.GetStream<TablesStream>();
if (tablesStream is null)
{
ErrorListener.RegisterException(new ArgumentException("Image does not have a .NET metadata tables stream."));
return;
}
AddMethodBodiesToTable(context, tablesStream);
AddFieldRvasToTable(context, tablesStream);
}
private void AddMethodBodiesToTable(PEFileBuilderContext context, TablesStream tablesStream)
{
var methodTable = tablesStream.GetTable<MethodDefinitionRow>();
for (uint rid = 1; rid <= methodTable.Count; rid++)
{
ref var methodRow = ref methodTable.GetRowRef(rid);
var bodySegment = GetMethodBodySegment(methodRow);
if (bodySegment is CilRawMethodBody cilBody)
context.MethodBodyTable.AddCilBody(cilBody);
else if (bodySegment is not null)
context.MethodBodyTable.AddNativeBody(bodySegment, (uint) context.Platform.PointerSize);
else
continue;
methodRow.Body = bodySegment.ToReference();
}
}
private ISegment? GetMethodBodySegment(MethodDefinitionRow methodRow)
{
if (methodRow.Body.IsBounded)
return methodRow.Body.GetSegment();
if (methodRow.Body.CanRead)
{
if ((methodRow.ImplAttributes & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.IL)
{
var reader = methodRow.Body.CreateReader();
return CilRawMethodBody.FromReader(ThrowErrorListener.Instance, ref reader);
}
ErrorListener.NotSupported("Native unbounded method bodies are not supported.");
}
return null;
}
private void AddFieldRvasToTable(PEFileBuilderContext context, TablesStream tablesStream)
{
var directory = context.Image.DotNetDirectory!;
var fieldRvaTable = tablesStream.GetTable<FieldRvaRow>(TableIndex.FieldRva);
if (fieldRvaTable.Count == 0)
return;
var table = context.FieldRvaTable;
var reader = context.FieldRvaDataReader;
for (uint rid = 1; rid <= fieldRvaTable.Count; rid++)
{
ref var row = ref fieldRvaTable.GetRowRef(rid);
var data = reader.ResolveFieldData(
ErrorListener,
context.Platform,
directory,
row
);
if (data is null)
continue;
table.Add(data);
row.Data = data.ToReference();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Builder\UnmanagedPEFileBuilderTest.cs | AsmResolver.PE.Tests.Builder | UnmanagedPEFileBuilderTest | ['private readonly TemporaryDirectoryFixture _fixture;'] | ['System', 'System.IO', 'System.Linq', 'AsmResolver.PE.Builder', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.File', 'AsmResolver.PE.Imports', 'AsmResolver.Tests.Runners', 'Xunit'] | xUnit | net8.0 | public class UnmanagedPEFileBuilderTest : IClassFixture<TemporaryDirectoryFixture>
{
private readonly TemporaryDirectoryFixture _fixture;
public UnmanagedPEFileBuilderTest(TemporaryDirectoryFixture fixture)
{
_fixture = fixture;
}
[Theory]
[InlineData(MachineType.I386)]
[InlineData(MachineType.Amd64)]
public void RoundTripNativePE(MachineType machineType)
{
var image = PEImage.FromBytes(
machineType switch
{
MachineType.I386 => Properties.Resources.NativeHelloWorldC_X86,
MachineType.Amd64 => Properties.Resources.NativeHelloWorldC_X64,
_ => throw new ArgumentOutOfRangeException(nameof(machineType))
},
TestReaderParameters
);
var file = image.ToPEFile(new UnmanagedPEFileBuilder());
_fixture.GetRunner<NativePERunner>().RebuildAndRun(
file,
$"NativeHelloWorldC.{machineType}.exe",
"hello world!\n"
);
}
[Theory]
[InlineData(MachineType.I386)]
[InlineData(MachineType.Amd64)]
public void TrampolineImportsInCPE(MachineType machineType)
{
var image = PEImage.FromBytes(
machineType switch
{
MachineType.I386 => Properties.Resources.NativeHelloWorldC_X86,
MachineType.Amd64 => Properties.Resources.NativeHelloWorldC_X64,
_ => throw new ArgumentOutOfRangeException(nameof(machineType))
},
TestReaderParameters
);
var file = image.ToPEFile(new UnmanagedPEFileBuilder
{
TrampolineImports = true
});
_fixture.GetRunner<NativePERunner>().RebuildAndRun(
file,
$"NativeHelloWorldC.{machineType}.exe",
"hello world!\n"
);
}
[Theory]
[InlineData(MachineType.I386)]
[InlineData(MachineType.Amd64)]
public void TrampolineImportsInCppPE(MachineType machineType)
{
var image = PEImage.FromBytes(
machineType switch
{
MachineType.I386 => Properties.Resources.NativeHelloWorldCpp_X86,
MachineType.Amd64 => Properties.Resources.NativeHelloWorldCpp_X64,
_ => throw new ArgumentOutOfRangeException(nameof(machineType))
},
TestReaderParameters
);
var file = image.ToPEFile(new UnmanagedPEFileBuilder
{
TrampolineImports = true,
ImportedSymbolClassifier = new DelegatedSymbolClassifier(x => x.Name switch
{
"?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A" => ImportedSymbolType.Data,
_ => ImportedSymbolType.Function
})
});
_fixture.GetRunner<NativePERunner>().RebuildAndRun(
file,
$"NativeHelloWorldCpp.{machineType}.exe",
"Hello, world!\n"
);
}
[Theory]
[InlineData(MachineType.I386)]
[InlineData(MachineType.Amd64)]
public void ScrambleImportsNativePE(MachineType machineType)
{
// Load image.
var image = PEImage.FromBytes(
machineType switch
{
MachineType.I386 => Properties.Resources.NativeHelloWorldC_X86,
MachineType.Amd64 => Properties.Resources.NativeHelloWorldC_X64,
_ => throw new ArgumentOutOfRangeException(nameof(machineType))
},
TestReaderParameters
);
// Reverse order of all imports
foreach (var module in image.Imports)
{
var reversed = module.Symbols.Reverse().ToArray();
module.Symbols.Clear();
foreach (var symbol in reversed)
module.Symbols.Add(symbol);
}
// Build with trampolines.
var file = image.ToPEFile(new UnmanagedPEFileBuilder
{
TrampolineImports = true
});
_fixture.GetRunner<NativePERunner>().RebuildAndRun(
file,
$"NativeHelloWorldC.{machineType}.exe",
"hello world!\n"
);
}
[Fact]
public void RoundTripMixedModeAssembly()
{
var image = PEImage.FromBytes(Properties.Resources.MixedModeHelloWorld, TestReaderParameters);
var file = image.ToPEFile(new UnmanagedPEFileBuilder());
_fixture.GetRunner<NativePERunner>().RebuildAndRun(
file,
"MixedModeHelloWorld.exe",
"Hello\n1 + 2 = 3\n"
);
}
[Fact]
public void TrampolineVTableFixupsInMixedModeAssembly()
{
// Load image.
var image = PEImage.FromBytes(Properties.Resources.MixedModeCallIntoNative, TestReaderParameters);
// Rebuild
var file = image.ToPEFile(new UnmanagedPEFileBuilder
{
TrampolineVTableFixups = true
});
_fixture.GetRunner<NativePERunner>().RebuildAndRun(
file,
"MixedModeHelloWorld.exe",
"Hello, World!\nResult: 3\n"
);
}
[Fact]
public void ScrambleVTableFixupsInMixedModeAssembly()
{
// Load image.
var image = PEImage.FromBytes(Properties.Resources.MixedModeCallIntoNative, TestReaderParameters);
// Reverse all vtable tokens.
foreach (var fixup in image.DotNetDirectory!.VTableFixups!)
{
var reversed = fixup.Tokens.Reverse().ToArray();
fixup.Tokens.Clear();
foreach (var symbol in reversed)
fixup.Tokens.Add(symbol);
}
// Rebuild
var file = image.ToPEFile(new UnmanagedPEFileBuilder
{
TrampolineVTableFixups = true
});
_fixture.GetRunner<NativePERunner>().RebuildAndRun(
file,
"MixedModeHelloWorld.exe",
"Hello, World!\nResult: 3\n"
);
}
[Fact]
public void AddMetadataToMixedModeAssembly()
{
const string name = "#Test";
byte[] data = [1, 2, 3, 4];
var image = PEImage.FromBytes(Properties.Resources.MixedModeHelloWorld, TestReaderParameters);
image.DotNetDirectory!.Metadata!.Streams.Add(new CustomMetadataStream(
name, new DataSegment(data)
));
var file = image.ToPEFile(new UnmanagedPEFileBuilder());
using var stream = new MemoryStream();
file.Write(stream);
var newImage = PEImage.FromBytes(stream.ToArray(), TestReaderParameters);
var metadataStream = Assert.IsAssignableFrom<CustomMetadataStream>(
newImage.DotNetDirectory!.Metadata!.Streams.First(x => x.Name == name)
);
Assert.Equal(data, metadataStream.Contents.WriteIntoArray());
_fixture.GetRunner<NativePERunner>().RebuildAndRun(
file,
"MixedModeHelloWorld.exe",
"Hello\n1 + 2 = 3\n"
);
}
} | 275 | 7,443 | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.File;
using AsmResolver.PE.Imports;
using AsmResolver.PE.Tls;
namespace AsmResolver.PE.Builder;
/// <summary>
/// Provides a mechanism for constructing PE files containing unmanaged code or metadata, based on a template PE file.
/// </summary>
/// <remarks>
/// <para>
/// This PE file builder attempts to preserve as much data as possible in the original executable file, and is well
/// suited for input binaries that contain unmanaged code and/or depend on raw offsets, RVAs or similar. However, it
/// may therefore not necessarily produce the most space-efficient output binaries, and may leave in original data
/// directories or sometimes entire PE sections that are no longer in use.
/// </para>
/// <para>
/// This class might modify the final imports directory (exposed by the <see cref="PEImage.Imports"/> property),
/// as well as the base relocations directory (exposed by the <see cref="PEImage.Relocations"/> property). In
/// particular, it might add or remove the entry to <c>mscoree.dll!_CorExeMain</c> or <c>mscoree.dll!_CorDllMain</c>,
/// and it may also add a reference to <c>kernel32.dll!VirtualProtect</c> in case dynamic initializers need to be
/// injected to initialize reconstructed some parts of the original import address tables (IATs).
/// </para>
/// <para>
/// By default, the Import Address Table (IATs) and .NET's VTable Fixup Table are not reconstructed and are preserved.
/// When changing any imports or VTable fixups in the PE image, set the appropriate <see cref="TrampolineImports"/> or
/// <see cref="TrampolineVTableFixups"/> properties to <c>true</c>. This will instruct the builder to patch the original
/// address tables and trampoline them to their new layout. This may also result in the builder injecting additional
/// initializer code to be inserted in <c>.auxtext</c>, depending on the type of imports that are present. This
/// initialization code is added as a TLS callback to the final PE file.
/// </para>
/// <para>
/// This class will add at most 5 new auxiliary sections to the final output PE file, next to the sections that were
/// already present in the input PE file, to fit in reconstructed data directories that did not fit in the original
/// location.
/// </para>
/// </remarks>
public class UnmanagedPEFileBuilder : PEFileBuilder<UnmanagedPEFileBuilder.BuilderContext>
{
private static readonly IImportedSymbolClassifier DefaultSymbolClassifier =
new DelegatedSymbolClassifier(_ => ImportedSymbolType.Function);
/// <summary>
/// Creates a new unmanaged PE file builder.
/// </summary>
public UnmanagedPEFileBuilder()
: this(ThrowErrorListener.Instance, null)
{
}
/// <summary>
/// Creates a new unmanaged PE file builder using the provided error listener.
/// </summary>
/// <param name="errorListener">The error listener to use.</param>
public UnmanagedPEFileBuilder(IErrorListener errorListener)
: this(errorListener, null)
{
}
/// <summary>
/// Creates a new unmanaged PE file builder using the provided error listener and base PE file.
/// </summary>
/// <param name="errorListener">The error listener to use.</param>
/// <param name="baseFile">The template file to base the resulting file on.</param>
public UnmanagedPEFileBuilder(IErrorListener errorListener, PEFile? baseFile)
{
ErrorListener = errorListener;
BaseFile = baseFile;
}
/// <summary>
/// Gets or sets the service used for registering exceptions that occur during the construction of the PE.
/// </summary>
public IErrorListener ErrorListener
{
get;
set;
}
/// <summary>
/// Gets or sets the template file to base the resulting file on.
/// </summary>
public PEFile? BaseFile
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the imports directory of the new file is supposed to be reconstructed
/// and that the old, existing imports directory should be patched and rewired via trampolines.
/// </summary>
public bool TrampolineImports
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the VTable fixups directory of the new file is supposed to be
/// reconstructed and that the old, existing VTable fixups directory should be patched and rewired via trampolines.
/// </summary>
public bool TrampolineVTableFixups
{
get;
set;
}
/// <summary>
/// Gets or sets the service that is used for determining whether an imported symbol is a function or a data symbol.
/// This is required when <see cref="TrampolineImports"/> is set to <c>true</c> and the IAT is reconstructed.
/// </summary>
public IImportedSymbolClassifier ImportedSymbolClassifier
{
get;
set;
} = DefaultSymbolClassifier;
/// <inheritdoc />
protected override BuilderContext CreateContext(PEImage image)
{
var baseFile = BaseFile ?? image.PEFile;
var baseImage = baseFile is not null
? PEImage.FromFile(baseFile, new PEReaderParameters(EmptyErrorListener.Instance))
: null;
return new BuilderContext(image, baseImage);
}
/// <inheritdoc />
protected override IEnumerable<PESection> CreateSections(BuilderContext context)
{
var sections = new List<PESection>();
// Import all existing sections.
sections.AddRange(context.ClonedSections);
// Add .auxtext section when necessary.
if (CreateAuxTextSection(context) is { } auxTextSection)
sections.Add(auxTextSection);
// Add .rdata section when necessary.
if (CreateAuxRDataSection(context) is { } auxRDataSection)
sections.Add(auxRDataSection);
// Add .auxdata section when necessary.
if (CreateAuxDataSection(context) is { } auxDataSection)
sections.Add(auxDataSection);
// Add .auxrsrc section when necessary.
if (CreateAuxRsrcSection(context) is { } auxRsrcSection)
sections.Add(auxRsrcSection);
// Add .reloc section when necessary.
if (CreateAuxRelocSection(context) is { } auxRelocSection)
sections.Add(auxRelocSection);
return sections;
}
/// <inheritdoc />
protected override uint GetEntryPointAddress(BuilderContext context, PEFile outputFile)
{
return context.Image.PEFile?.OptionalHeader.AddressOfEntryPoint
?? context.ClrBootstrapper?.Segment.Rva
?? 0;
}
/// <inheritdoc />
protected override void AssignDataDirectories(BuilderContext context, PEFile outputFile)
{
var header = outputFile.OptionalHeader;
// Import all existing data directories.
if (context.Image.PEFile is { } originalFile)
{
header.DataDirectories.Clear();
foreach (var directory in originalFile.OptionalHeader.DataDirectories)
header.DataDirectories.Add(directory);
}
header.EnsureDataDirectoryCount(OptionalHeader.DefaultNumberOfRvasAndSizes);
if (!context.ImportDirectory.IsEmpty)
{
header.SetDataDirectory(DataDirectoryIndex.ImportDirectory, context.ImportDirectory);
header.SetDataDirectory(DataDirectoryIndex.IatDirectory, context.ImportDirectory.ImportAddressDirectory);
}
if (!context.ExportDirectory.IsEmpty)
header.SetDataDirectory(DataDirectoryIndex.ExportDirectory, context.ExportDirectory);
if (!context.DebugDirectory.IsEmpty)
header.SetDataDirectory(DataDirectoryIndex.DebugDirectory, context.DebugDirectory);
if (!context.ResourceDirectory.IsEmpty)
header.SetDataDirectory(DataDirectoryIndex.ResourceDirectory, context.ResourceDirectory);
if (context.Image.DotNetDirectory is not null)
header.SetDataDirectory(DataDirectoryIndex.ClrDirectory, context.Image.DotNetDirectory);
if (context.Image.TlsDirectory is not null)
header.SetDataDirectory(DataDirectoryIndex.TlsDirectory, context.Image.TlsDirectory);
if (!context.RelocationsDirectory.IsEmpty)
header.SetDataDirectory(DataDirectoryIndex.BaseRelocationDirectory, context.RelocationsDirectory);
}
/// <summary>
/// Builds up an auxiliary main text section (.auxtext) of the new .NET PE file when necessary.
/// </summary>
/// <param name="context">The working space of the builder.</param>
/// <returns>The new .text section, or <c>null</c> if no auxiliary text section was required.</returns>
protected virtual PESection? CreateAuxTextSection(BuilderContext context)
{
var contents = new SegmentBuilder();
// Reconstructed IAT.
if (TrampolineImports && !context.ImportDirectory.IsEmpty)
contents.Add(context.ImportDirectory.ImportAddressDirectory);
// .NET metadata etc.
if (CreateAuxDotNetSegment(context) is { } auxSegment)
contents.Add(auxSegment);
// Reconstructed ILT.
if (TrampolineImports && !context.ImportDirectory.IsEmpty)
contents.Add(context.ImportDirectory);
// Reconstructed exports.
if (!context.ExportDirectory.IsEmpty)
contents.Add(context.ExportDirectory);
// Reconstructed debug directory.
if (!context.DebugDirectory.IsEmpty)
{
if (!TryPatchDataDirectory(context, context.DebugDirectory, DataDirectoryIndex.DebugDirectory))
contents.Add(context.DebugDirectory);
contents.Add(context.DebugDirectory.ContentsTable);
}
// New CLR bootstrapper
if (context.ClrBootstrapper.HasValue)
contents.Add(context.ClrBootstrapper.Value.Segment);
// Import trampolines.
if (TrampolineImports)
{
contents.Add(context.ImportTrampolines);
context.ImportTrampolines.ApplyPatches(context.ClonedSections);
}
// Code for newly added exports.
if (context.Image.Exports is { Entries: { Count: > 0 } entries })
{
for (int i = 0; i < entries.Count; i++)
{
var export = entries[i];
if (export.Address.IsBounded && export.Address.GetSegment() is { } segment)
contents.Add(segment, (uint) context.Platform.PointerSize);
}
}
if (contents.Count == 0)
return null;
return new PESection(
".auxtext",
SectionFlags.ContentCode | SectionFlags.MemoryExecute | SectionFlags.MemoryRead,
contents
);
}
private ISegment? CreateAuxDotNetSegment(BuilderContext context)
{
var dotNetDirectory = context.Image.DotNetDirectory;
if (dotNetDirectory is null)
return null;
var result = new SegmentBuilder();
// IMAGE_COR20_HEADER
AddOrPatch(dotNetDirectory, context.BaseImage?.DotNetDirectory);
// Field RVA data.
if (!context.FieldRvaTable.IsEmpty)
result.Add(context.FieldRvaTable);
// Managed and new unmanaged method bodies.
if (!context.MethodBodyTable.IsEmpty)
result.Add(context.MethodBodyTable);
// All .NET metadata.
AddOrPatch(dotNetDirectory.Metadata, context.BaseImage?.DotNetDirectory?.Metadata);
AddOrPatch(dotNetDirectory.DotNetResources, context.BaseImage?.DotNetDirectory?.DotNetResources);
AddOrPatch(dotNetDirectory.StrongName, context.BaseImage?.DotNetDirectory?.StrongName);
// VTable fixup tables.
if (TrampolineVTableFixups && dotNetDirectory.VTableFixups?.Count > 0)
{
// NOTE: We cannot safely patch the existing tables here as we need to trampoline the slots.
result.Add(dotNetDirectory.VTableFixups);
result.Add(context.VTableTrampolines);
context.VTableTrampolines.ApplyPatches(context.ClonedSections);
}
// Other managed native headers.
AddOrPatch(dotNetDirectory.ExportAddressTable, context.BaseImage?.DotNetDirectory?.ExportAddressTable);
AddOrPatch(dotNetDirectory.ManagedNativeHeader, context.BaseImage?.DotNetDirectory?.ManagedNativeHeader);
return result.Count > 0
? result
: null;
void AddOrPatch(ISegment? segment, ISegment? originalSegment)
{
if (segment is not null && !TryPatchSegment(context, segment, originalSegment))
result.Add(segment, (uint) context.Platform.PointerSize);
}
}
/// <summary>
/// Creates an auxiliary .rdata section containing a TLS data directory, its template data and callback function
/// table (when present in the image).
/// </summary>
/// <param name="context">The working space of the builder.</param>
/// <returns>The new .rdata section.</returns>
protected virtual PESection? CreateAuxRDataSection(BuilderContext context)
{
var image = context.Image;
var contents = new SegmentBuilder();
// Add TLS data directory and contents.
if (image.TlsDirectory is { } directory)
{
var originalDirectory = context.BaseImage?.TlsDirectory;
AddOrPatch(directory, originalDirectory);
if (directory.TemplateData is not null)
AddOrPatch(directory.TemplateData, originalDirectory?.TemplateData);
if (directory.CallbackFunctions.Count > 0)
AddOrPatch(directory.CallbackFunctions, originalDirectory?.CallbackFunctions);
}
if (contents.Count == 0)
return null;
return new PESection(
".rdata",
SectionFlags.MemoryRead | SectionFlags.ContentInitializedData,
contents
);
void AddOrPatch(ISegment? newSegment, ISegment? originalSegment)
{
if (newSegment is null)
return;
if (originalSegment is null || !TryPatchSegment(context, originalSegment, newSegment))
contents.Add(newSegment, (uint) context.Platform.PointerSize);
}
}
/// <summary>
/// Creates the .sdata section containing the exports, vtable fixup tokens, and the TLS index.
/// </summary>
/// <param name="context">The working space of the builder.</param>
/// <returns>The section.</returns>
protected virtual PESection? CreateAuxDataSection(BuilderContext context)
{
var image = context.Image;
var contents = new SegmentBuilder();
// Add VTable fixups
if (TrampolineVTableFixups && image.DotNetDirectory?.VTableFixups is { } fixups)
{
for (int i = 0; i < fixups.Count; i++)
contents.Add(fixups[i].Tokens, (uint) context.Platform.PointerSize);
}
// Add export directory.
if (image.Exports is { Entries.Count: > 0 })
contents.Add(context.ExportDirectory, (uint) context.Platform.PointerSize);
if (image.TlsDirectory is { } directory)
{
// Add TLS index segment.
if (directory.Index is not PESegmentReference
&& directory.Index.IsBounded
&& directory.Index.GetSegment() is { } indexSegment)
{
if (context.BaseImage?.TlsDirectory?.Index is not { } index
|| !TryPatchSegment(context, indexSegment, index.Rva, sizeof(uint)))
{
contents.Add(indexSegment);
}
}
}
if (contents.Count == 0)
return null;
return new PESection(
".auxdata",
SectionFlags.MemoryRead | SectionFlags.MemoryWrite | SectionFlags.ContentInitializedData,
contents
);
}
/// <summary>
/// Creates the win32 resources section (.rsrc) of the new .NET PE file.
/// </summary>
/// <param name="context">The working space of the builder.</param>
/// <returns>The resources section.</returns>
protected virtual PESection? CreateAuxRsrcSection(BuilderContext context)
{
// Do we have any resources to add?
if (context.ResourceDirectory.IsEmpty)
return null;
// Try fitting the data in the original data directory.
if (TryPatchDataDirectory(context, context.ResourceDirectory, DataDirectoryIndex.ResourceDirectory))
return null;
// Otherwise, create a new section.
return new PESection(
".auxrsrc",
SectionFlags.MemoryRead | SectionFlags.ContentInitializedData,
context.ResourceDirectory
);
}
/// <summary>
/// Creates the base relocations section (.reloc) of the new .NET PE file.
/// </summary>
/// <param name="context">The working space of the builder.</param>
/// <returns>The base relocations section.</returns>
protected virtual PESection? CreateAuxRelocSection(BuilderContext context)
{
// Do we have any base relocations to add?
if (context.RelocationsDirectory.IsEmpty)
return null;
// Try fitting the data in the original data directory.
if (TryPatchDataDirectory(context, context.RelocationsDirectory, DataDirectoryIndex.BaseRelocationDirectory))
return null;
return new PESection(
".reloc",
SectionFlags.MemoryRead | SectionFlags.ContentInitializedData | SectionFlags.MemoryDiscardable,
context.RelocationsDirectory
);
}
/// <inheritdoc />
protected override void CreateDataDirectoryBuffers(BuilderContext context)
{
CreateDotNetDirectories(context);
base.CreateDataDirectoryBuffers(context);
}
/// <inheritdoc />
protected override void CreateImportDirectory(BuilderContext context)
{
if (!TrampolineImports
|| context.BaseImage?.Imports is not { } baseDirectory
|| context.Image.Imports is not { } newDirectory)
{
return;
}
// Try to map all symbols stored in the original directory to symbols in the new directory.
foreach (var module in baseDirectory)
{
foreach (var original in module.Symbols)
{
if (FindNewImportedSymbol(original) is not { } newSymbol)
continue;
switch (ImportedSymbolClassifier.Classify(newSymbol))
{
case ImportedSymbolType.Function:
context.ImportTrampolines.AddFunctionTableSlotTrampoline(original, newSymbol);
break;
case ImportedSymbolType.Data:
context.ImportTrampolines.VirtualProtect ??= GetOrCreateVirtualProtect();
context.ImportTrampolines.AddDataSlotInitializer(original, newSymbol);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
// If we have a data slot initializer, then inject it as a TLS callback to ensure the original IAT data slots
// are initialized before any other user-code is called.
if (context.ImportTrampolines.DataInitializerSymbol is { } initializerSymbol)
{
var tls = context.Image.TlsDirectory ??= new TlsDirectory();
tls.UpdateOffsets(new RelocationParameters(0, 0, 0, context.Platform.Is32Bit));
if (tls.Index == SegmentReference.Null)
tls.Index = new ZeroesSegment(sizeof(ulong)).ToReference();
tls.CallbackFunctions.Insert(0, initializerSymbol.GetReference()!);
}
// Rebuild import directory as normal.
base.CreateImportDirectory(context);
return;
ImportedSymbol? FindNewImportedSymbol(ImportedSymbol symbol)
{
// We consider a slot to be equal if the tokens match.
foreach (var newModule in newDirectory)
{
if (symbol.DeclaringModule!.Name != newModule.Name)
continue;
foreach (var newSymbol in newModule.Symbols)
{
if (symbol.IsImportByName && newSymbol.IsImportByName && newSymbol.Name == symbol.Name)
return newSymbol;
if (symbol.IsImportByOrdinal && newSymbol.IsImportByOrdinal && newSymbol.Ordinal == symbol.Ordinal)
return newSymbol;
}
}
return null;
}
ImportedSymbol GetOrCreateVirtualProtect()
{
bool addModule = false;
// Find or create a new kernel32.dll module import.
var kernel32 = context.Image.Imports.FirstOrDefault(
x => x.Name?.Equals("kernel32.dll", StringComparison.OrdinalIgnoreCase) ?? false);
if (kernel32 is null)
{
kernel32 = new ImportedModule("KERNEL32.dll");
addModule = true;
}
// Find or create a new VirtualProtect module import.
var virtualProtect = kernel32.Symbols.FirstOrDefault(x => x.Name == "VirtualProtect");
if (virtualProtect is null)
{
virtualProtect = new ImportedSymbol(0, "VirtualProtect");
kernel32.Symbols.Add(virtualProtect);
}
// Add the new module if kernel32.dll wasn't added yet.
if (addModule)
context.ImportDirectory.AddModule(kernel32);
return virtualProtect;
}
}
/// <inheritdoc />
protected override void CreateRelocationsDirectory(BuilderContext context)
{
base.CreateRelocationsDirectory(context);
// We may have some extra relocations for the newly generated code of our trampolines and TLS-backed initializers.
foreach (var reloc in context.ImportTrampolines.GetRequiredBaseRelocations())
context.RelocationsDirectory.Add(reloc);
foreach (var reloc in context.VTableTrampolines.GetRequiredBaseRelocations())
context.RelocationsDirectory.Add(reloc);
if (context.Image.TlsDirectory is { } tls)
{
foreach (var reloc in tls.GetRequiredBaseRelocations())
context.RelocationsDirectory.Add(reloc);
}
}
private void CreateDotNetDirectories(BuilderContext context)
{
ProcessRvasInMetadataTables(context);
AddVTableFixupTrampolines(context);
}
private void ProcessRvasInMetadataTables(BuilderContext context)
{
var tablesStream = context.Image.DotNetDirectory?.Metadata?.GetStream<TablesStream>();
if (tablesStream is null)
return;
AddMethodBodiesToTable(context, tablesStream);
AddFieldRvasToTable(context, tablesStream);
}
private void AddMethodBodiesToTable(BuilderContext context, TablesStream tablesStream)
{
var methodTable = tablesStream.GetTable<MethodDefinitionRow>();
for (uint rid = 1; rid <= methodTable.Count; rid++)
{
ref var methodRow = ref methodTable.GetRowRef(rid);
var bodySegment = GetMethodBodySegment(methodRow);
if (bodySegment is CilRawMethodBody cilBody)
context.MethodBodyTable.AddCilBody(cilBody); // TODO: try reuse CIL bodies when possible.
else if (bodySegment is not null)
context.MethodBodyTable.AddNativeBody(bodySegment, (uint)context.Platform.PointerSize);
else
continue;
methodRow.Body = bodySegment.ToReference();
}
}
private static ISegment? GetMethodBodySegment(MethodDefinitionRow methodRow)
{
var body = methodRow.Body;
// If method body is well-defined, use the existing segment.
if (body.IsBounded)
return body.GetSegment();
// IL method bodies are parseable, reconstruct the segment on-the-fly.
if (body.CanRead && (methodRow.ImplAttributes & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.IL)
{
var reader = body.CreateReader();
return CilRawMethodBody.FromReader(ThrowErrorListener.Instance, ref reader);
}
// Otherwise, assume it is an entry point of existing native code that we need to preserve.
return null;
}
private void AddFieldRvasToTable(BuilderContext context, TablesStream tablesStream)
{
var directory = context.Image.DotNetDirectory!;
var fieldRvaTable = tablesStream.GetTable<FieldRvaRow>(TableIndex.FieldRva);
if (fieldRvaTable.Count == 0)
return;
var table = context.FieldRvaTable;
var reader = context.FieldRvaDataReader;
for (uint rid = 1; rid <= fieldRvaTable.Count; rid++)
{
ref var row = ref fieldRvaTable.GetRowRef(rid);
// Preserve existing RVAs.
if (row.Data is PESegmentReference)
continue;
var data = reader.ResolveFieldData(
ErrorListener,
context.Platform,
directory,
row
);
if (data is null)
continue;
table.Add(data);
row.Data = data.ToReference();
}
}
private void AddVTableFixupTrampolines(BuilderContext context)
{
if (!TrampolineVTableFixups
|| context.BaseImage?.DotNetDirectory?.VTableFixups is not { } baseDirectory
|| context.Image.DotNetDirectory?.VTableFixups is not { } newDirectory)
{
return;
}
// Try to map all tokens stored in the original directory to slots in the new directory.
foreach (var originalFixup in baseDirectory)
{
for (int i = 0; i < originalFixup.Tokens.Count; i++)
{
if (FindNewTokenSlot(originalFixup.Tokens[i]) is not { } newSlot)
continue;
var originalSlot = new Symbol(originalFixup.Tokens.GetReferenceToIndex(i));
context.VTableTrampolines.AddFunctionTableSlotTrampoline(originalSlot, newSlot);
}
}
return;
ISymbol? FindNewTokenSlot(MetadataToken token)
{
// We consider a slot to be equal if the tokens match.
foreach (var fixup in newDirectory)
{
for (int j = 0; j < fixup.Tokens.Count; j++)
{
if (fixup.Tokens[j] == token)
return new Symbol(fixup.Tokens.GetReferenceToIndex(j));
}
}
return null;
}
}
private static bool TryPatchDataDirectory(BuilderContext context, ISegment? segment, DataDirectoryIndex directoryIndex)
{
if (segment is null || context.BaseImage?.PEFile is not { } peFile)
return false;
var directory = peFile.OptionalHeader.GetDataDirectory(directoryIndex);
return TryPatchSegment(context, segment, directory.VirtualAddress, directory.Size);
}
private static bool TryPatchSegment(BuilderContext context, ISegment? segment, ISegment? originalSegment)
{
if (segment is null || originalSegment is null)
return false;
return TryPatchSegment(context, segment, originalSegment.Rva, originalSegment.GetPhysicalSize());
}
private static bool TryPatchSegment(BuilderContext context, ISegment? segment, uint rva, uint size)
{
if (segment is null || context.BaseImage?.PEFile is not { } peFile)
return false;
// Before we can measure size, we need to update offsets.
segment.UpdateOffsets(new RelocationParameters(
context.Image.ImageBase,
peFile.RvaToFileOffset(rva),
rva,
context.Platform.Is32Bit
));
// Do we fit in the existing segment?
if (segment.GetPhysicalSize() <= size
&& context.TryGetSectionContainingRva(rva, out var section)
&& section.Contents is not null)
{
uint relativeOffset = rva - section.Rva;
section.Contents = section.Contents.AsPatchedSegment().Patch(relativeOffset, segment);
return true;
}
return false;
}
/// <summary>
/// Provides a workspace for <see cref="UnmanagedPEFileBuilder"/>.
/// </summary>
public class BuilderContext : PEFileBuilderContext
{
/// <summary>
/// Creates a new builder context.
/// </summary>
/// <param name="image">The image to build a PE file for.</param>
/// <param name="baseImage">The template image to base the file on.</param>
public BuilderContext(PEImage image, PEImage? baseImage)
: base(image)
{
BaseImage = baseImage;
if (baseImage?.PEFile is not null)
{
foreach (var section in baseImage.PEFile.Sections)
ClonedSections.Add(new PESection(section));
}
ImportTrampolines = new TrampolineTableBuffer(Platform);
VTableTrampolines = new TrampolineTableBuffer(Platform);
}
/// <summary>
/// Gets a collection of sections that were cloned from the template file.
/// </summary>
public List<PESection> ClonedSections { get; } = new();
/// <summary>
/// Gets the template image to base the file on.
/// </summary>
public PEImage? BaseImage { get; }
/// <summary>
/// Gets the trampolines table for all imported symbols.
/// </summary>
public TrampolineTableBuffer ImportTrampolines { get; }
/// <summary>
/// Gets the trampolines table for all fixed up managed method addresses.
/// </summary>
public TrampolineTableBuffer VTableTrampolines { get; }
/// <summary>
/// Searches for a cloned section containing the provided RVA.
/// </summary>
/// <param name="rva">The RVA.</param>
/// <param name="section">The section.</param>
/// <returns><c>true</c> if the section was found, <c>false</c> otherwise.</returns>
public bool TryGetSectionContainingRva(uint rva, [NotNullWhen(true)] out PESection? section)
{
foreach (var candidate in ClonedSections)
{
if (candidate.ContainsRva(rva))
{
section = candidate;
return true;
}
}
section = null;
return false;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Certificates\CertificateCollectionTest.cs | AsmResolver.PE.Tests.Certificates
| CertificateCollectionTest | [] | ['System.IO', 'AsmResolver.PE.Certificates', 'AsmResolver.PE.File', 'Xunit'] | xUnit | net8.0 | public class CertificateCollectionTest
{
[Fact]
public void ReadHeader()
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld_Signed, TestReaderParameters);
var certificate = Assert.Single(image.Certificates);
Assert.Equal(CertificateRevision.Revision_v2_0, certificate.Revision);
Assert.Equal(CertificateType.PkcsSignedData, certificate.Type);
Assert.Equal(0x580u, certificate.CreateContentReader().Length);
}
[Fact]
public void RebuildExistingSignature()
{
var file = PEFile.FromBytes(Properties.Resources.HelloWorld_Signed);
var image = PEImage.FromFile(file, TestReaderParameters);
var certificate = Assert.Single(image.Certificates);
file.EofData = image.Certificates;
using var stream = new MemoryStream();
file.Write(stream);
var newImage = PEImage.FromBytes(stream.ToArray(), TestReaderParameters);
var newCertificate = Assert.Single(newImage.Certificates);
Assert.Equal(certificate.Revision, newCertificate.Revision);
Assert.Equal(certificate.Type, newCertificate.Type);
Assert.Equal(certificate.CreateContentReader().ReadToEnd(), newCertificate.CreateContentReader().ReadToEnd());
Assert.Equal(certificate.WriteIntoArray(), newCertificate.WriteIntoArray());
}
} | 150 | 1,643 | using System.Collections.ObjectModel;
using AsmResolver.IO;
namespace AsmResolver.PE.Certificates
{
/// <summary>
/// Represents the collection of attribute certificates that are stored in a signed portable executable file.
/// </summary>
public class CertificateCollection : Collection<AttributeCertificate>, ISegment
{
/// <inheritdoc />
public ulong Offset
{
get;
private set;
}
/// <inheritdoc />
public uint Rva
{
get;
private set;
}
/// <inheritdoc />
public bool CanUpdateOffsets => true;
/// <inheritdoc />
public void UpdateOffsets(in RelocationParameters parameters)
{
Offset = parameters.Offset;
Rva = parameters.Rva;
var current = parameters;
for (int i = 0; i < Items.Count; i++)
{
var certificate = Items[i];
certificate.UpdateOffsets(current);
current.Advance(certificate.GetPhysicalSize().Align(8));
}
}
/// <inheritdoc />
public uint GetPhysicalSize()
{
uint size = 0;
for (int i = 0; i < Items.Count; i++)
size += Items[i].GetPhysicalSize().Align(8);
return size;
}
/// <inheritdoc />
public uint GetVirtualSize() => GetPhysicalSize();
/// <inheritdoc />
public void Write(BinaryStreamWriter writer)
{
for (int i = 0; i < Items.Count; i++)
{
Items[i].Write(writer);
writer.Align(8);
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Code\AddressFixupTest.cs | AsmResolver.PE.Tests.Code
| AddressFixupTest | ['private readonly DataSegment _input = new(Enumerable\n .Range(0, 1000)\n .Select(x => (byte) (x & 0xFF))\n .ToArray());', 'private readonly ISymbol _dummySymbol = new Symbol(new VirtualAddress(0x0000_2000));'] | ['System', 'System.Linq', 'AsmResolver.Patching', 'AsmResolver.PE.Code', 'Xunit'] | xUnit | net8.0 | public class AddressFixupTest
{
private readonly DataSegment _input = new(Enumerable
.Range(0, 1000)
.Select(x => (byte) (x & 0xFF))
.ToArray());
private readonly ISymbol _dummySymbol = new Symbol(new VirtualAddress(0x0000_2000));
[Fact]
public void PatchAbsolute32BitAddress()
{
var patched = new PatchedSegment(_input);
patched.Patches.Add(new AddressFixupPatch(
new AddressFixup(10, AddressFixupType.Absolute32BitAddress, _dummySymbol)));
patched.UpdateOffsets(new RelocationParameters(0x0040_0000, 0, 0, true));
byte[] expected = _input.ToArray();
Buffer.BlockCopy(BitConverter.GetBytes(0x0040_2000), 0, expected, 10, sizeof(int));
byte[] actual = patched.WriteIntoArray();
Assert.Equal(expected, actual);
}
[Fact]
public void PatchAbsolute32BitAddressFluent()
{
var patched = _input
.AsPatchedSegment()
.Patch(10, AddressFixupType.Absolute32BitAddress, _dummySymbol);
patched.UpdateOffsets(new RelocationParameters(0x0040_0000, 0, 0, true));
byte[] expected = _input.ToArray();
Buffer.BlockCopy(BitConverter.GetBytes(0x0040_2000), 0, expected, 10, sizeof(int));
byte[] actual = patched.WriteIntoArray();
Assert.Equal(expected, actual);
}
[Fact]
public void PatchAbsolute64BitAddress()
{
var patched = new PatchedSegment(_input);
patched.Patches.Add(new AddressFixupPatch(
new AddressFixup(10, AddressFixupType.Absolute64BitAddress, _dummySymbol)));
patched.UpdateOffsets(new RelocationParameters(0x0000_0001_0000_0000, 0, 0, true));
byte[] expected = _input.ToArray();
Buffer.BlockCopy(BitConverter.GetBytes(0x0000_0001_0000_2000), 0, expected, 10, sizeof(ulong));
byte[] actual = patched.WriteIntoArray();
Assert.Equal(expected, actual);
}
[Fact]
public void PatchAbsolute64BitAddressFluent()
{
var patched = _input
.AsPatchedSegment()
.Patch(10, AddressFixupType.Absolute64BitAddress, _dummySymbol);
patched.UpdateOffsets(new RelocationParameters(0x0000_0001_0000_0000, 0, 0, true));
byte[] expected = _input.ToArray();
Buffer.BlockCopy(BitConverter.GetBytes(0x0000_0001_0000_2000), 0, expected, 10, sizeof(ulong));
byte[] actual = patched.WriteIntoArray();
Assert.Equal(expected, actual);
}
[Fact]
public void PatchRelative32BitAddress()
{
var patched = new PatchedSegment(_input);
patched.Patches.Add(new AddressFixupPatch(
new AddressFixup(10, AddressFixupType.Relative32BitAddress, _dummySymbol)));
patched.UpdateOffsets(new RelocationParameters(0x0040_0000, 0, 0, true));
byte[] expected = _input.ToArray();
Buffer.BlockCopy(BitConverter.GetBytes(0x2000 - 10 - 4), 0, expected, 10, sizeof(int));
byte[] actual = patched.WriteIntoArray();
Assert.Equal(expected, actual);
}
} | 152 | 3,574 | using System;
using System.Diagnostics;
namespace AsmResolver.PE.Code
{
/// <summary>
/// Provides information about a symbol referenced within a segment for which the final RVA is yet to be determined.
/// </summary>
[DebuggerDisplay("Patch {Offset} with &{Symbol} as {Type}")]
public readonly struct AddressFixup
{
/// <summary>
/// Creates a new instance of the <see cref="AddressFixup"/> structure.
/// </summary>
/// <param name="offset">The offset relative to the start of the code segment pointing to the reference.</param>
/// <param name="type">The type of fixup to apply at the offset.</param>
/// <param name="referencedObject">The reference to write the RVA for.</param>
public AddressFixup(uint offset, AddressFixupType type, ISymbol referencedObject)
{
Offset = offset;
Symbol = referencedObject ?? throw new ArgumentNullException(nameof(referencedObject));
Type = type;
}
/// <summary>
/// Gets the offset relative to the start of the code segment pointing to the reference.
/// </summary>
public uint Offset
{
get;
}
/// <summary>
/// Gets the type of fixup to apply at the offset.
/// </summary>
public AddressFixupType Type
{
get;
}
/// <summary>
/// Gets the object that is referenced at the offset.
/// </summary>
public ISymbol Symbol
{
get;
}
/// <inheritdoc />
public override string ToString() => $"+{Offset:X8} <{Symbol}> ({Type})";
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Debug\DebugDataEntryTest.cs | AsmResolver.PE.Tests.Debug
| DebugDataEntryTest | [] | ['System.IO', 'System.Linq', 'AsmResolver.IO', 'AsmResolver.PE.Builder', 'AsmResolver.PE.Debug', 'Xunit'] | xUnit | net8.0 | public class DebugDataEntryTest
{
private static PEImage RebuildAndReloadManagedPE(PEImage image)
{
// Build.
using var tempStream = new MemoryStream();
var builder = new ManagedPEFileBuilder();
var newPeFile = builder.CreateFile(image);
newPeFile.Write(new BinaryStreamWriter(tempStream));
// Reload.
var newImage = PEImage.FromBytes(tempStream.ToArray(), TestReaderParameters);
return newImage;
}
[Fact]
public void ReadEntries()
{
var image = PEImage.FromBytes(Properties.Resources.SimpleDll, TestReaderParameters);
Assert.Equal(new[]
{
DebugDataType.CodeView,
DebugDataType.VcFeature
}, image.DebugData.Select(d => d.Contents!.Type));
}
[Fact]
public void PersistentEntries()
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var newImage = RebuildAndReloadManagedPE(image);
Assert.Equal(
image.DebugData
.Where(e => e.Contents != null)
.Select(e => e.Contents!.Type),
newImage.DebugData
.Where(e => e.Contents != null)
.Select(e => e.Contents!.Type));
}
} | 182 | 1,646 | using AsmResolver.IO;
namespace AsmResolver.PE.Debug
{
/// <summary>
/// Represents a single entry in the debug data directory.
/// </summary>
public class DebugDataEntry : SegmentBase
{
/// <summary>
/// Gets the static size of a single debug data entry header.
/// </summary>
public const uint DebugDataEntryHeaderSize =
sizeof(uint) // Characteristics
+ sizeof(uint) // TimeDateStamp
+ sizeof(ushort) // MajorVersion
+ sizeof(ushort) // MinorVersion
+ sizeof(DebugDataType) // Type
+ sizeof(uint) // SizeOfData
+ sizeof(uint) // AddressOfRawData
+ sizeof(uint) // PointerToRawData
;
private readonly LazyVariable<DebugDataEntry, IDebugDataSegment?> _contents;
/// <summary>
/// Initializes an empty <see cref="DebugDataEntry"/> instance.
/// </summary>
protected DebugDataEntry()
{
_contents = new LazyVariable<DebugDataEntry, IDebugDataSegment?>(x => x.GetContents());
}
/// <summary>
/// Creates a new instance of the <see cref="DebugDataEntry"/> class.
/// </summary>
/// <param name="contents">The contents.</param>
public DebugDataEntry(IDebugDataSegment contents)
{
_contents = new LazyVariable<DebugDataEntry, IDebugDataSegment?>(contents);
}
/// <summary>
/// Reserved, must be zero.
/// </summary>
public uint Characteristics
{
get;
set;
}
/// <summary>
/// Gets or sets the time and date that the debug data was created.
/// </summary>
public uint TimeDateStamp
{
get;
set;
}
/// <summary>
/// Gets or sets the major version number of the debug data format.
/// </summary>
public ushort MajorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the minor version number of the debug data format.
/// </summary>
public ushort MinorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the raw contents of the debug data entry.
/// </summary>
public IDebugDataSegment? Contents
{
get => _contents.GetValue(this);
set => _contents.SetValue(value);
}
/// <summary>
/// Obtains the contents of the entry.
/// </summary>
/// <returns>The contents.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Contents"/> property.
/// </remarks>
protected virtual IDebugDataSegment? GetContents() => null;
/// <inheritdoc />
public override uint GetPhysicalSize() => DebugDataEntryHeaderSize;
/// <inheritdoc />
public override void Write(BinaryStreamWriter writer)
{
writer.WriteUInt32(Characteristics);
writer.WriteUInt32(TimeDateStamp);
writer.WriteUInt16(MajorVersion);
writer.WriteUInt16(MinorVersion);
writer.WriteUInt32((uint) (Contents?.Type ?? 0));
writer.WriteUInt32(Contents?.GetPhysicalSize() ?? 0);
writer.WriteUInt32(Contents?.Rva ?? 0);
writer.WriteUInt32((uint) (Contents?.Offset ?? 0));
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Cil\CilAssemblerTest.cs | AsmResolver.PE.Tests.DotNet.Cil
| CilAssemblerTest | [] | ['System', 'System.IO', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class CilAssemblerTest
{
[Theory]
[InlineData(CilCode.Ldc_I4, 1234L)]
[InlineData(CilCode.Ldc_I4_S, 1234)]
[InlineData(CilCode.Ldc_I8, 1234)]
public void InvalidPrimitiveOperandShouldThrow(CilCode code, object operand)
{
var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
var assembler = new CilAssembler(writer, new MockOperandBuilder());
Assert.ThrowsAny<ArgumentException>(() =>
assembler.WriteInstruction(new CilInstruction(code.ToOpCode(), operand)));
}
[Fact]
public void BranchTooFarAwayShouldThrow()
{
var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
var assembler = new CilAssembler(writer, new MockOperandBuilder());
Assert.ThrowsAny<OverflowException>(() =>
assembler.WriteInstruction(new CilInstruction(CilOpCodes.Br_S, new CilOffsetLabel(0x12345))));
assembler.WriteInstruction(new CilInstruction(CilOpCodes.Br, new CilOffsetLabel(0x12345)));
}
[Fact]
public void TooLargeLocalShouldThrow()
{
var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
var assembler = new CilAssembler(writer, new MockOperandBuilder());
Assert.ThrowsAny<OverflowException>(() =>
assembler.WriteInstruction(new CilInstruction(CilOpCodes.Ldloc_S, 0x12345)));
assembler.WriteInstruction(new CilInstruction(CilOpCodes.Ldloc, 0x12345));
}
private sealed class MockOperandBuilder : ICilOperandBuilder
{
/// <inheritdoc />
public int GetVariableIndex(object? operand) => Convert.ToInt32(operand);
/// <inheritdoc />
public int GetArgumentIndex(object? operand) => Convert.ToInt32(operand);
/// <inheritdoc />
public uint GetStringToken(object? operand) => Convert.ToUInt32(operand);
/// <inheritdoc />
public MetadataToken GetMemberToken(object? operand) =>
operand is MetadataToken token
? token
: MetadataToken.Zero;
}
} | 202 | 2,581 | using System;
using System.Collections.Generic;
using System.Linq;
using AsmResolver.IO;
using AsmResolver.Shims;
namespace AsmResolver.PE.DotNet.Cil
{
/// <summary>
/// Provides a mechanism for encoding CIL instructions to an output stream.
/// </summary>
public class CilAssembler
{
private readonly BinaryStreamWriter _writer;
private readonly ICilOperandBuilder _operandBuilder;
private readonly Func<string?>? _getMethodBodyName;
private readonly IErrorListener _errorListener;
private string? _diagnosticPrefix;
/// <summary>
/// Creates a new CIL instruction encoder.
/// </summary>
/// <param name="writer">The output stream to write the encoded instructions to.</param>
/// <param name="operandBuilder">The object to use for creating raw operands.</param>
public CilAssembler(BinaryStreamWriter writer, ICilOperandBuilder operandBuilder)
: this(writer, operandBuilder, default(string), ThrowErrorListener.Instance)
{
}
/// <summary>
/// Creates a new CIL instruction encoder.
/// </summary>
/// <param name="writer">The output stream to write the encoded instructions to.</param>
/// <param name="operandBuilder">The object to use for creating raw operands.</param>
/// <param name="methodBodyName">The name of the method that is being serialized.</param>
/// <param name="errorListener">The object used for recording error listener.</param>
public CilAssembler(
BinaryStreamWriter writer,
ICilOperandBuilder operandBuilder,
string? methodBodyName,
IErrorListener errorListener)
{
_writer = writer ?? throw new ArgumentNullException(nameof(writer));
_errorListener = errorListener ?? throw new ArgumentNullException(nameof(errorListener));
_operandBuilder = operandBuilder ?? throw new ArgumentNullException(nameof(operandBuilder));
_diagnosticPrefix = !string.IsNullOrEmpty(methodBodyName)
? $"[In {methodBodyName}]: "
: null;
}
/// <summary>
/// Creates a new CIL instruction encoder.
/// </summary>
/// <param name="writer">The output stream to write the encoded instructions to.</param>
/// <param name="operandBuilder">The object to use for creating raw operands.</param>
/// <param name="getMethodBodyName">A delegate that is used for lazily obtaining the name of the method body.</param>
/// <param name="errorListener">The object used for recording error listener.</param>
public CilAssembler(
BinaryStreamWriter writer,
ICilOperandBuilder operandBuilder,
Func<string?>? getMethodBodyName,
IErrorListener errorListener)
{
_writer = writer ?? throw new ArgumentNullException(nameof(writer));
_errorListener = errorListener ?? throw new ArgumentNullException(nameof(errorListener));
_operandBuilder = operandBuilder ?? throw new ArgumentNullException(nameof(operandBuilder));
_getMethodBodyName = getMethodBodyName;
}
private string? DiagnosticPrefix
{
get
{
if (_diagnosticPrefix is null && _getMethodBodyName is not null)
{
string? name = _getMethodBodyName();
if (!string.IsNullOrEmpty(name))
_diagnosticPrefix = $"[In {name}]: ";
}
return _diagnosticPrefix;
}
}
/// <summary>
/// Writes a collection of CIL instructions to the output stream.
/// </summary>
/// <param name="instructions">The instructions to write.</param>
public void WriteInstructions(IList<CilInstruction> instructions)
{
for (int i = 0; i < instructions.Count; i++)
WriteInstruction(instructions[i]);
}
/// <summary>
/// Writes a single instruction to the output stream.
/// </summary>
/// <param name="instruction">The instruction to write.</param>
public void WriteInstruction(CilInstruction instruction)
{
WriteOpCode(instruction.OpCode);
WriteOperand(instruction);
}
private void WriteOpCode(CilOpCode opCode)
{
_writer.WriteByte(opCode.Byte1);
if (opCode.IsLarge)
_writer.WriteByte(opCode.Byte2);
}
private void WriteOperand(CilInstruction instruction)
{
switch (instruction.OpCode.OperandType)
{
case CilOperandType.InlineNone:
break;
case CilOperandType.ShortInlineI:
_writer.WriteSByte(OperandToSByte(instruction));
break;
case CilOperandType.InlineI:
_writer.WriteInt32(OperandToInt32(instruction));
break;
case CilOperandType.InlineI8:
_writer.WriteInt64(OperandToInt64(instruction));
break;
case CilOperandType.ShortInlineR:
_writer.WriteSingle(OperandToFloat32(instruction));
break;
case CilOperandType.InlineR:
_writer.WriteDouble(OperandToFloat64(instruction));
break;
case CilOperandType.ShortInlineVar:
_writer.WriteByte((byte) OperandToLocalIndex(instruction));
break;
case CilOperandType.InlineVar:
_writer.WriteUInt16(OperandToLocalIndex(instruction));
break;
case CilOperandType.ShortInlineArgument:
_writer.WriteByte((byte) OperandToArgumentIndex(instruction));
break;
case CilOperandType.InlineArgument:
_writer.WriteUInt16(OperandToArgumentIndex(instruction));
break;
case CilOperandType.ShortInlineBrTarget:
_writer.WriteSByte((sbyte) OperandToBranchDelta(instruction));
break;
case CilOperandType.InlineBrTarget:
_writer.WriteInt32(OperandToBranchDelta(instruction));
break;
case CilOperandType.InlineSwitch:
var labels = instruction.Operand as IList<ICilLabel> ?? ArrayShim.Empty<ICilLabel>();
_writer.WriteInt32(labels.Count);
int baseOffset = (int) _writer.Offset + labels.Count * sizeof(int);
for (int i = 0; i < labels.Count; i++)
_writer.WriteInt32(labels[i].Offset - baseOffset);
break;
case CilOperandType.InlineString:
_writer.WriteUInt32(_operandBuilder.GetStringToken(instruction.Operand));
break;
case CilOperandType.InlineField:
case CilOperandType.InlineMethod:
case CilOperandType.InlineSig:
case CilOperandType.InlineTok:
case CilOperandType.InlineType:
_writer.WriteUInt32(_operandBuilder.GetMemberToken(instruction.Operand).ToUInt32());
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private int OperandToBranchDelta(CilInstruction instruction)
{
bool isShort = instruction.OpCode.OperandType == CilOperandType.ShortInlineBrTarget;
int delta;
switch (instruction.Operand)
{
case sbyte x:
delta = x;
break;
case int x:
delta = x;
break;
case ICilLabel label:
int operandSize = isShort ? sizeof(sbyte) : sizeof(int);
delta = label.Offset - (int) (_writer.Offset + (ulong) operandSize);
break;
default:
return ThrowInvalidOperandType<sbyte>(instruction, typeof(ICilLabel), typeof(sbyte));
}
if (isShort && delta is < sbyte.MinValue or > sbyte.MaxValue)
{
_errorListener.RegisterException(new OverflowException(
$"{DiagnosticPrefix}Branch target at IL_{instruction.Offset:X4} is too far away for a ShortInlineBr instruction."));
}
return delta;
}
private ushort OperandToLocalIndex(CilInstruction instruction)
{
int variableIndex = _operandBuilder.GetVariableIndex(instruction.Operand);
if (instruction.OpCode.OperandType == CilOperandType.ShortInlineVar && variableIndex > byte.MaxValue)
{
_errorListener.RegisterException(new OverflowException(
$"{DiagnosticPrefix}Local index at IL_{instruction.Offset:X4} is too large for a ShortInlineVar instruction."));
}
return unchecked((ushort) variableIndex);
}
private ushort OperandToArgumentIndex(CilInstruction instruction)
{
int variableIndex = _operandBuilder.GetArgumentIndex(instruction.Operand);
if (instruction.OpCode.OperandType == CilOperandType.ShortInlineArgument && variableIndex > byte.MaxValue)
{
_errorListener.RegisterException(new OverflowException(
$"{DiagnosticPrefix}Argument index at IL_{instruction.Offset:X4} is too large for a ShortInlineArgument instruction."));
}
return unchecked((ushort) variableIndex);
}
private sbyte OperandToSByte(CilInstruction instruction)
{
if (instruction.Operand is sbyte x)
return x;
return ThrowInvalidOperandType<sbyte>(instruction, typeof(sbyte));
}
private int OperandToInt32(CilInstruction instruction)
{
if (instruction.Operand is int x)
return x;
return ThrowInvalidOperandType<int>(instruction, typeof(int));
}
private long OperandToInt64(CilInstruction instruction)
{
if (instruction.Operand is long x)
return x;
return ThrowInvalidOperandType<long>(instruction, typeof(long));
}
private float OperandToFloat32(CilInstruction instruction)
{
if (instruction.Operand is float x)
return x;
return ThrowInvalidOperandType<float>(instruction, typeof(float));
}
private double OperandToFloat64(CilInstruction instruction)
{
if (instruction.Operand is double x)
return x;
return ThrowInvalidOperandType<double>(instruction, typeof(double));
}
private T? ThrowInvalidOperandType<T>(CilInstruction instruction, Type expectedOperand)
{
string found = instruction.Operand?.GetType().Name ?? "null";
_errorListener.RegisterException(new ArgumentOutOfRangeException(
$"{DiagnosticPrefix}Expected a {expectedOperand.Name} operand at IL_{instruction.Offset:X4}, but found {found}."));
return default;
}
private T? ThrowInvalidOperandType<T>(CilInstruction instruction, params Type[] expectedOperands)
{
string[] names = expectedOperands
.Select(o => o.Name)
.ToArray();
string operandTypesString = expectedOperands.Length > 1
? $"{StringShim.Join(", ", names.Take(names.Length - 1))} or {names[names.Length - 1]}"
: names[0];
string found = instruction.Operand?.GetType().Name ?? "null";
_errorListener.RegisterException(new ArgumentOutOfRangeException(
$"{DiagnosticPrefix}Expected a {operandTypesString} operand at IL_{instruction.Offset:X4}, but found {found}."));
return default;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Cil\CilDisassemblerTest.cs | AsmResolver.PE.Tests.DotNet.Cil
| CilDisassemblerTest | [] | ['System.Linq', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class CilDisassemblerTest
{
[Fact]
public void InlineNone()
{
var rawCode = new DataSegment(new byte[]
{
0x00, // nop
0x17, // ldc.i4.1
0x18, // ldc.i4.2
0x58, // add
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Nop),
new CilInstruction(1, CilOpCodes.Ldc_I4_1),
new CilInstruction(2, CilOpCodes.Ldc_I4_2),
new CilInstruction(3, CilOpCodes.Add),
new CilInstruction(4, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void ShortInlineI()
{
var rawCode = new DataSegment(new byte[]
{
0x1F, 0x12, // ldc.i4.s 0x12
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Ldc_I4_S, (sbyte) 0x12),
new CilInstruction(2, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void InlineI()
{
var rawCode = new DataSegment(new byte[]
{
0x20, 0x04, 0x03, 0x02, 0x01, // ldc.i4 0x01020304
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Ldc_I4, 0x01020304),
new CilInstruction(5, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void InlineI8()
{
var rawCode = new DataSegment(new byte[]
{
0x21, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, // ldc.i8 0x0102030405060708
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Ldc_I8, 0x0102030405060708),
new CilInstruction(9, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void InlineBrTarget()
{
var rawCode = new DataSegment(new byte[]
{
0x38, 0x02, 0x00, 0x00, 0x00, // br IL_0007
0x00, // nop
0x00, // nop
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Br, new CilOffsetLabel(0x0007)),
new CilInstruction(5, CilOpCodes.Nop),
new CilInstruction(6, CilOpCodes.Nop),
new CilInstruction(7, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void ShortInlineBrTarget()
{
var rawCode = new DataSegment(new byte[]
{
0x2B, 0x02, // br IL_0004
0x00, // nop
0x00, // nop
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Br_S, new CilOffsetLabel(0x0004)),
new CilInstruction(2, CilOpCodes.Nop),
new CilInstruction(3, CilOpCodes.Nop),
new CilInstruction(4, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void InlineMethod()
{
var rawCode = new DataSegment(new byte[]
{
0x28, 0x01, 0x00, 0x00, 0x0A, // call 0x0A000001
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Call, new MetadataToken(0x0A000001)),
new CilInstruction(5, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void InlineField()
{
var rawCode = new DataSegment(new byte[]
{
0x7E, 0x02, 0x00, 0x00, 0x0A, // ldsfld 0x0A000002
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Ldsfld, new MetadataToken(0x0A000002)),
new CilInstruction(5, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void InlineType()
{
var rawCode = new DataSegment(new byte[]
{
0x02, // ldarg.0
0x74, 0x02, 0x00, 0x00, 0x01, // castclass 0x01000002
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Ldarg_0),
new CilInstruction(1, CilOpCodes.Castclass, new MetadataToken(0x01000002)),
new CilInstruction(6, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void InlineTok()
{
var rawCode = new DataSegment(new byte[]
{
0xD0, 0x02, 0x00, 0x00, 0x01, // ldtoken 0x01000002
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Ldtoken, new MetadataToken(0x01000002)),
new CilInstruction(5, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void InlineSig()
{
var rawCode = new DataSegment(new byte[]
{
0x02, // ldarg.0
0xD0, 0x02, 0x00, 0x00, 0x11, // calli 0x11000002
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Ldarg_0),
new CilInstruction(1, CilOpCodes.Ldtoken, new MetadataToken(0x11000002)),
new CilInstruction(6, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void InlineArgument()
{
var rawCode = new DataSegment(new byte[]
{
0xFE, 0x09, 0x01, 0x00, // ldarg 1
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Ldarg, (ushort) 1),
new CilInstruction(4, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void ShortInlineArgument()
{
var rawCode = new DataSegment(new byte[]
{
0x0E, 0x01, // ldarg.s 1
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Ldarg_S, (byte) 1),
new CilInstruction(2, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void InlineVariable()
{
var rawCode = new DataSegment(new byte[]
{
0xFE, 0x0C, 0x01, 0x00, // ldloc 1
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Ldloc, (ushort) 1),
new CilInstruction(4, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void ShortInlineVariable()
{
var rawCode = new DataSegment(new byte[]
{
0x11, 0x01, // ldloc.s 1
0x2A // ret
});
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Ldloc_S, (byte) 1),
new CilInstruction(2, CilOpCodes.Ret),
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
[Fact]
public void InlineSwitch()
{
var rawCode = new DataSegment(new byte[]
{
0x45, 0x03, 0x00, 0x00, 0x00, // switch
0x02, 0x00, 0x00, 0x00, // IL_0013
0x04, 0x00, 0x00, 0x00, // IL_0015
0x06, 0x00, 0x00, 0x00, // IL_0017
0x00, // nop
0x00, // nop
0x00, // nop
0x00, // nop
0x00, // nop
0x00, // nop
0x2A // ret
});
var expectedLabels = new[] { 0x0013, 0x0015, 0x0017 }
.Select(offset => new CilOffsetLabel(offset))
.Cast<ICilLabel>()
.ToArray();
var expected = new[]
{
new CilInstruction(0, CilOpCodes.Switch, expectedLabels),
new CilInstruction(17, CilOpCodes.Nop),
new CilInstruction(18, CilOpCodes.Nop),
new CilInstruction(19, CilOpCodes.Nop),
new CilInstruction(20, CilOpCodes.Nop),
new CilInstruction(21, CilOpCodes.Nop),
new CilInstruction(22, CilOpCodes.Nop),
new CilInstruction(23, CilOpCodes.Ret)
};
var disassembler = new CilDisassembler(rawCode.CreateReader());
Assert.Equal(expected, disassembler.ReadInstructions());
}
} | 166 | 12,534 | using System;
using System.Collections.Generic;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.PE.DotNet.Cil
{
/// <summary>
/// Provides a mechanism for decoding CIL instructions from an input stream.
/// </summary>
public class CilDisassembler
{
private readonly ICilOperandResolver _operandResolver;
private BinaryStreamReader _reader;
/// <summary>
/// Creates a new CIL disassembler using the provided input stream.
/// </summary>
/// <param name="reader">The input stream to read the code from.</param>
public CilDisassembler(in BinaryStreamReader reader)
{
_reader = reader;
_operandResolver = EmptyOperandResolver.Instance;
}
/// <summary>
/// Creates a new CIL disassembler using the provided input stream.
/// </summary>
/// <param name="reader">The input stream to read the code from.</param>
/// <param name="operandResolver">The object responsible for resolving operands.</param>
public CilDisassembler(in BinaryStreamReader reader, ICilOperandResolver operandResolver)
{
_reader = reader;
_operandResolver = operandResolver ?? throw new ArgumentNullException(nameof(operandResolver));
}
/// <summary>
/// Gets or sets a value indicating whether branch targets should be resolved to
/// <see cref="CilInstructionLabel"/> where possible.
/// </summary>
public bool ResolveBranchTargets
{
get;
set;
} = true;
/// <summary>
/// Reads all instructions from the input stream.
/// </summary>
/// <returns>The instructions.</returns>
public IList<CilInstruction> ReadInstructions()
{
List<CilInstruction>? branches = null;
List<CilInstruction>? switches = null;
var instructions = new List<CilInstruction>();
while (_reader.Offset < _reader.StartOffset + _reader.Length)
{
var instruction = ReadInstruction();
instructions.Add(instruction);
if (ResolveBranchTargets)
{
switch (instruction.OpCode.OperandType)
{
case CilOperandType.ShortInlineBrTarget:
case CilOperandType.InlineBrTarget:
branches ??= new List<CilInstruction>();
branches.Add(instruction);
break;
case CilOperandType.InlineSwitch:
switches ??= new List<CilInstruction>();
switches.Add(instruction);
break;
}
}
}
if (ResolveBranchTargets)
{
if (branches is not null)
{
foreach (var branch in branches)
branch.Operand = TryResolveLabel(instructions, (ICilLabel) branch.Operand!);
}
if (switches is not null)
{
foreach (var @switch in switches)
{
var labels = (IList<ICilLabel>) @switch.Operand!;
for (int i = 0; i < labels.Count; i++)
labels[i] = TryResolveLabel(instructions, labels[i]);
}
}
}
return instructions;
}
private static ICilLabel TryResolveLabel(IList<CilInstruction> instructions, ICilLabel label)
{
int index = instructions.GetIndexByOffset(label.Offset);
if (index != -1)
label = instructions[index].CreateLabel();
return label;
}
/// <summary>
/// Reads the next instruction from the input stream.
/// </summary>
/// <returns>The instruction.</returns>
private CilInstruction ReadInstruction()
{
int offset = (int) _reader.RelativeOffset;
var code = ReadOpCode();
object? operand = ReadOperand(code.OperandType);
return new CilInstruction(offset, code, operand);
}
private CilOpCode ReadOpCode()
{
byte op = _reader.ReadByte();
return op == 0xFE
? CilOpCodes.MultiByteOpCodes[_reader.ReadByte()]
: CilOpCodes.SingleByteOpCodes[op];
}
private object? ReadOperand(CilOperandType operandType)
{
switch (operandType)
{
case CilOperandType.InlineNone:
return null;
case CilOperandType.ShortInlineI:
return _reader.ReadSByte();
case CilOperandType.ShortInlineBrTarget:
return new CilOffsetLabel(_reader.ReadSByte() + (int) _reader.RelativeOffset);
case CilOperandType.ShortInlineVar:
byte shortLocalIndex = _reader.ReadByte();
return _operandResolver.ResolveLocalVariable(shortLocalIndex) ?? shortLocalIndex;
case CilOperandType.ShortInlineArgument:
byte shortArgIndex = _reader.ReadByte();
return _operandResolver.ResolveParameter(shortArgIndex) ?? shortArgIndex;
case CilOperandType.InlineVar:
ushort longLocalIndex = _reader.ReadUInt16();
return _operandResolver.ResolveLocalVariable(longLocalIndex) ?? longLocalIndex;
case CilOperandType.InlineArgument:
ushort longArgIndex = _reader.ReadUInt16();
return _operandResolver.ResolveParameter(longArgIndex) ?? longArgIndex;
case CilOperandType.InlineI:
return _reader.ReadInt32();
case CilOperandType.InlineBrTarget:
return new CilOffsetLabel(_reader.ReadInt32() + (int) _reader.RelativeOffset);
case CilOperandType.ShortInlineR:
return _reader.ReadSingle();
case CilOperandType.InlineI8:
return _reader.ReadInt64();
case CilOperandType.InlineR:
return _reader.ReadDouble();
case CilOperandType.InlineString:
var stringToken = new MetadataToken(_reader.ReadUInt32());
return _operandResolver.ResolveString(stringToken) ?? stringToken;
case CilOperandType.InlineField:
case CilOperandType.InlineMethod:
case CilOperandType.InlineSig:
case CilOperandType.InlineTok:
case CilOperandType.InlineType:
var memberToken = new MetadataToken(_reader.ReadUInt32());
return _operandResolver.ResolveMember(memberToken) ?? memberToken;
case CilOperandType.InlinePhi:
throw new NotSupportedException();
case CilOperandType.InlineSwitch:
return ReadSwitchTable();
default:
throw new ArgumentOutOfRangeException(nameof(operandType), operandType, null);
}
}
private IList<ICilLabel> ReadSwitchTable()
{
int count = _reader.ReadInt32();
int nextOffset = (int) _reader.RelativeOffset + count * sizeof(int);
var offsets = new List<ICilLabel>(count);
for (int i = 0; i < count; i++)
offsets.Add(new CilOffsetLabel(nextOffset + _reader.ReadInt32()));
return offsets;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Cil\CilInstructionTest.cs | AsmResolver.PE.Tests.DotNet.Cil
| CilInstructionTest | [] | ['AsmResolver.PE.DotNet.Cil', 'Xunit'] | xUnit | net8.0 | public class CilInstructionTest
{
[Theory]
[InlineData(CilCode.Ldc_I4, 1234, 1234)]
[InlineData(CilCode.Ldc_I4_M1, null, -1)]
[InlineData(CilCode.Ldc_I4_0, null, 0)]
[InlineData(CilCode.Ldc_I4_1, null, 1)]
[InlineData(CilCode.Ldc_I4_2, null, 2)]
[InlineData(CilCode.Ldc_I4_3, null, 3)]
[InlineData(CilCode.Ldc_I4_4, null, 4)]
[InlineData(CilCode.Ldc_I4_5, null, 5)]
[InlineData(CilCode.Ldc_I4_6, null, 6)]
[InlineData(CilCode.Ldc_I4_7, null, 7)]
[InlineData(CilCode.Ldc_I4_8, null, 8)]
[InlineData(CilCode.Ldc_I4_S, (sbyte) -10, -10)]
public void GetLdcI4ConstantTest(CilCode code, object? operand, int expectedValue)
{
var instruction = new CilInstruction(code.ToOpCode(), operand);
Assert.Equal(expectedValue, instruction.GetLdcI4Constant());
}
[Fact]
public void ReplaceWithOperand()
{
var instruction = new CilInstruction(CilOpCodes.Ldstr, "Hello, world!");
Assert.NotNull(instruction.Operand);
instruction.ReplaceWith(CilOpCodes.Ldc_I4, 1337);
Assert.Equal(CilOpCodes.Ldc_I4, instruction.OpCode);
Assert.Equal(1337, instruction.Operand);
}
[Fact]
public void ReplaceWithoutOperandShouldRemoveOperand()
{
var instruction = new CilInstruction(CilOpCodes.Ldstr, "Hello, world!");
Assert.NotNull(instruction.Operand);
instruction.ReplaceWith(CilOpCodes.Ldnull);
Assert.Equal(CilOpCodes.Ldnull, instruction.OpCode);
Assert.Null(instruction.Operand);
}
[Fact]
public void ReplaceWithNop()
{
var instruction = new CilInstruction(CilOpCodes.Ldstr, "Hello, world!");
instruction.ReplaceWithNop();
Assert.Equal(CilOpCodes.Nop, instruction.OpCode);
Assert.Null(instruction.Operand);
}
} | 100 | 2,172 | using System;
using System.Collections.Generic;
using System.Linq;
namespace AsmResolver.PE.DotNet.Cil
{
/// <summary>
/// Represents a single instruction in a managed CIL method body.
/// </summary>
public class CilInstruction
{
/// <summary>
/// Creates a new CIL instruction with no operand.
/// </summary>
/// <param name="opCode">The operation to perform.</param>
/// <remarks>
/// This constructor does not do any verification on the correctness of the instruction.
/// </remarks>
public CilInstruction(CilOpCode opCode)
: this(0, opCode, null)
{
}
/// <summary>
/// Creates a new CIL instruction with no operand.
/// </summary>
/// <param name="offset">The offset of the instruction, relative to the start of the method body's code.</param>
/// <param name="opCode">The operation to perform.</param>
/// <remarks>
/// This constructor does not do any verification on the correctness of the instruction.
/// </remarks>
public CilInstruction(int offset, CilOpCode opCode)
: this(offset, opCode, null)
{
}
/// <summary>
/// Creates a new CIL instruction with an operand..
/// </summary>
/// <param name="opCode">The operation to perform.</param>
/// <param name="operand">The operand.</param>
/// <remarks>
/// This constructor does not do any verification on the correctness of the instruction.
/// </remarks>
public CilInstruction(CilOpCode opCode, object? operand)
: this(0, opCode, operand)
{
}
/// <summary>
/// Creates a new CIL instruction with an operand..
/// </summary>
/// <param name="offset">The offset of the instruction, relative to the start of the method body's code.</param>
/// <param name="opCode">The operation to perform.</param>
/// <param name="operand">The operand.</param>
/// <remarks>
/// This constructor does not do any verification on the correctness of the instruction.
/// </remarks>
public CilInstruction(int offset, CilOpCode opCode, object? operand)
{
Offset = offset;
OpCode = opCode;
Operand = operand;
}
/// <summary>
/// Gets or sets the offset to the start of the instruction, relative to the start of the code.
/// </summary>
public int Offset
{
get;
set;
}
/// <summary>
/// Gets or sets the operation to perform.
/// </summary>
public CilOpCode OpCode
{
get;
set;
}
/// <summary>
/// Gets or sets the operand of the instruction, if available.
/// </summary>
public object? Operand
{
get;
set;
}
/// <summary>
/// Gets the size in bytes of the CIL instruction.
/// </summary>
public int Size => OpCode.Size + GetOperandSize();
/// <summary>
/// Create a new instruction pushing the provided integer value, using the smallest possible operation code and
/// operand size.
/// </summary>
/// <param name="value">The constant to push.</param>
/// <returns>The instruction.</returns>
public static CilInstruction CreateLdcI4(int value)
{
var (code, operand) = GetLdcI4OpCodeOperand(value);
return new CilInstruction(code, operand);
}
/// <summary>
/// Determines the smallest possible operation code and operand required to push the provided integer constant.
/// </summary>
/// <param name="value">The constant to push.</param>
/// <returns>The operation code and operand.</returns>
public static (CilOpCode code, object? operand) GetLdcI4OpCodeOperand(int value)
{
CilOpCode code;
object? operand = null;
switch (value)
{
case -1:
code = CilOpCodes.Ldc_I4_M1;
break;
case 0:
code = CilOpCodes.Ldc_I4_0;
break;
case 1:
code = CilOpCodes.Ldc_I4_1;
break;
case 2:
code = CilOpCodes.Ldc_I4_2;
break;
case 3:
code = CilOpCodes.Ldc_I4_3;
break;
case 4:
code = CilOpCodes.Ldc_I4_4;
break;
case 5:
code = CilOpCodes.Ldc_I4_5;
break;
case 6:
code = CilOpCodes.Ldc_I4_6;
break;
case 7:
code = CilOpCodes.Ldc_I4_7;
break;
case 8:
code = CilOpCodes.Ldc_I4_8;
break;
case var x and <= sbyte.MaxValue and >= sbyte.MinValue:
code = CilOpCodes.Ldc_I4_S;
operand = (sbyte) x;
break;
default:
code = CilOpCodes.Ldc_I4;
operand = value;
break;
}
return (code, operand);
}
private int GetOperandSize() => OpCode.OperandType switch
{
CilOperandType.InlineNone => 0,
CilOperandType.ShortInlineI => sizeof(sbyte),
CilOperandType.ShortInlineArgument => sizeof(sbyte),
CilOperandType.ShortInlineBrTarget => sizeof(sbyte),
CilOperandType.ShortInlineVar => sizeof(sbyte),
CilOperandType.InlineVar => sizeof(ushort),
CilOperandType.InlineArgument => sizeof(ushort),
CilOperandType.InlineBrTarget => sizeof(uint),
CilOperandType.InlineI => sizeof(uint),
CilOperandType.InlineField => sizeof(uint),
CilOperandType.InlineMethod => sizeof(uint),
CilOperandType.InlineSig => sizeof(uint),
CilOperandType.InlineString => sizeof(uint),
CilOperandType.InlineTok => sizeof(uint),
CilOperandType.InlineType => sizeof(uint),
CilOperandType.InlineI8 => sizeof(ulong),
CilOperandType.ShortInlineR => sizeof(float),
CilOperandType.InlineR => sizeof(double),
CilOperandType.InlineSwitch when Operand is IList<ICilLabel> targets => (targets.Count + 1) * sizeof(int),
CilOperandType.InlineSwitch => sizeof(uint),
CilOperandType.InlinePhi => throw new NotSupportedException(),
_ => throw new ArgumentOutOfRangeException()
};
/// <inheritdoc />
public override string ToString() => CilInstructionFormatter.Instance.FormatInstruction(this);
/// <summary>
/// Determines whether the provided instruction is considered equal to the current instruction.
/// </summary>
/// <param name="other">The instruction to compare against.</param>
/// <returns><c>true</c> if the instructions are equal, <c>false</c> otherwise.</returns>
protected bool Equals(CilInstruction other)
{
if (Offset != other.Offset || !OpCode.Equals(other.OpCode))
return false;
if (OpCode.Code == CilCode.Switch
&& Operand is IEnumerable<ICilLabel> list1
&& other.Operand is IEnumerable<ICilLabel> list2)
{
return list1.SequenceEqual(list2);
}
return Equals(Operand, other.Operand);
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != GetType())
return false;
return Equals((CilInstruction) obj);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = Offset;
hashCode = (hashCode * 397) ^ OpCode.GetHashCode();
hashCode = (hashCode * 397) ^ (Operand is not null ? Operand.GetHashCode() : 0);
return hashCode;
}
}
/// <summary>
/// Creates a new label to the current instruction.
/// </summary>
/// <returns>The label.</returns>
public ICilLabel CreateLabel() => new CilInstructionLabel(this);
/// <summary>
/// Determines whether the instruction is using a variant of the ldloc opcodes.
/// </summary>
public bool IsLdloc()
{
switch (OpCode.Code)
{
case CilCode.Ldloc:
case CilCode.Ldloc_0:
case CilCode.Ldloc_1:
case CilCode.Ldloc_2:
case CilCode.Ldloc_3:
case CilCode.Ldloc_S:
return true;
default:
return false;
}
}
/// <summary>
/// Determines whether the instruction is using a variant of the stloc opcodes.
/// </summary>
public bool IsStloc()
{
switch (OpCode.Code)
{
case CilCode.Stloc:
case CilCode.Stloc_0:
case CilCode.Stloc_1:
case CilCode.Stloc_2:
case CilCode.Stloc_3:
case CilCode.Stloc_S:
return true;
default:
return false;
}
}
/// <summary>
/// Determines whether the instruction is using a variant of the ldarg opcodes.
/// </summary>
public bool IsLdarg()
{
switch (OpCode.Code)
{
case CilCode.Ldarg:
case CilCode.Ldarg_0:
case CilCode.Ldarg_1:
case CilCode.Ldarg_2:
case CilCode.Ldarg_3:
case CilCode.Ldarg_S:
return true;
default:
return false;
}
}
/// <summary>
/// Determines whether the instruction is using a variant of the starg opcodes.
/// </summary>
public bool IsStarg()
{
switch (OpCode.Code)
{
case CilCode.Starg:
case CilCode.Starg_S:
return true;
default:
return false;
}
}
/// <summary>
/// Determines whether the instruction is a branching instruction (either conditional or unconditional).
/// </summary>
public bool IsBranch() => OpCode.FlowControl is CilFlowControl.Branch or CilFlowControl.ConditionalBranch;
/// <summary>
/// Determines whether the instruction is an unconditional branch instruction.
/// </summary>
public bool IsUnconditionalBranch() => OpCode.FlowControl == CilFlowControl.Branch;
/// <summary>
/// Determines whether the instruction is a conditional branch instruction.
/// </summary>
public bool IsConditionalBranch() => OpCode.FlowControl == CilFlowControl.ConditionalBranch;
/// <summary>
/// Determines whether the instruction is an instruction pushing an int32 constant onto the stack.
/// </summary>
public bool IsLdcI4()
{
switch (OpCode.Code)
{
case CilCode.Ldc_I4:
case CilCode.Ldc_I4_S:
case CilCode.Ldc_I4_0:
case CilCode.Ldc_I4_1:
case CilCode.Ldc_I4_2:
case CilCode.Ldc_I4_3:
case CilCode.Ldc_I4_4:
case CilCode.Ldc_I4_5:
case CilCode.Ldc_I4_6:
case CilCode.Ldc_I4_7:
case CilCode.Ldc_I4_8:
case CilCode.Ldc_I4_M1:
return true;
default:
return false;
}
}
/// <summary>
/// When this instruction is an ldc.i4 variant, gets the in32 constant that is being pushed onto the stack.
/// </summary>
public int GetLdcI4Constant() => OpCode.Code switch
{
CilCode.Ldc_I4 => (int) (Operand ?? 0),
CilCode.Ldc_I4_S => (sbyte) (Operand ?? (sbyte) 0),
CilCode.Ldc_I4_0 => 0,
CilCode.Ldc_I4_1 => 1,
CilCode.Ldc_I4_2 => 2,
CilCode.Ldc_I4_3 => 3,
CilCode.Ldc_I4_4 => 4,
CilCode.Ldc_I4_5 => 5,
CilCode.Ldc_I4_6 => 6,
CilCode.Ldc_I4_7 => 7,
CilCode.Ldc_I4_8 => 8,
CilCode.Ldc_I4_M1 => -1,
_ => throw new ArgumentOutOfRangeException()
};
/// <summary>
/// Replaces the operation code used by the instruction with a new one, and clears the operand.
/// </summary>
/// <param name="opCode">The new operation code.</param>
/// <remarks>
/// This method may be useful when patching a method body, where reusing the instruction object is favourable.
/// This can prevent breaking any references to the instruction (e.g. branch or exception handler targets).
/// </remarks>
public void ReplaceWith(CilOpCode opCode) => ReplaceWith(opCode, null);
/// <summary>
/// Replaces the operation code and operand used by the instruction with new ones.
/// </summary>
/// <param name="opCode">The new operation code.</param>
/// <param name="operand">The new operand.</param>
/// <remarks>
/// This method may be useful when patching a method body, where reusing the instruction object is favourable.
/// This can prevent breaking any references to the instruction (e.g. branch or exception handler targets).
/// </remarks>
public void ReplaceWith(CilOpCode opCode, object? operand)
{
OpCode = opCode;
Operand = operand;
}
/// <summary>
/// Clears the operand and replaces the operation code with a <see cref="CilOpCodes.Nop"/> (No-Operation).
/// </summary>
/// <remarks>
/// This method may be useful when patching a method body, where reusing the instruction object is favourable.
/// This can prevent breaking any references to the instruction (e.g. branch or exception handler targets).
/// </remarks>
public void ReplaceWithNop() => ReplaceWith(CilOpCodes.Nop);
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Cil\CilRawMethodBodyTest.cs | AsmResolver.PE.Tests.DotNet.Cil
| CilRawMethodBodyTest | [] | ['AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class CilRawMethodBodyTest
{
[Fact]
public void DetectTinyMethodBody()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var methodTable = peImage.DotNetDirectory!.Metadata!
.GetStream<TablesStream>()
.GetTable<MethodDefinitionRow>();
var reader = methodTable[0].Body.CreateReader();
var methodBody = CilRawMethodBody.FromReader(ThrowErrorListener.Instance, ref reader);
Assert.NotNull(methodBody);
Assert.False(methodBody!.IsFat);
Assert.Equal(new byte[]
{
0x72, 0x01, 0x00, 0x00, 0x70, // ldstr "Hello, world!"
0x28, 0x0B, 0x00, 0x00, 0x0A, // call void [mscorlib] System.Console::WriteLine(string)
0x2A // ret
}, methodBody.Code.ToArray());
}
} | 185 | 1,158 | using System;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Cil
{
/// <summary>
/// When overridden from this class, represents a chunk of CIL code that implements a method body.
/// </summary>
public abstract class CilRawMethodBody : SegmentBase
{
/// <inheritdoc />
protected CilRawMethodBody(IReadableSegment code)
{
Code = code;
}
/// <summary>
/// Gets a value indicating whether the method body is using the fat format.
/// </summary>
public abstract bool IsFat
{
get;
}
/// <summary>
/// Gets or sets the raw bytes that make up the CIL code of the method body.
/// </summary>
public IReadableSegment Code
{
get;
set;
}
/// <summary>
/// Reads a raw method body from the given binary input stream.
/// </summary>
/// <param name="reader">The binary input stream to read from.</param>
/// <returns>The raw method body.</returns>
/// <exception cref="NotSupportedException">Occurs when the method header indicates an invalid or unsupported
/// method body format.</exception>
public static CilRawMethodBody? FromReader(ref BinaryStreamReader reader) =>
FromReader(ThrowErrorListener.Instance, ref reader);
/// <summary>
/// Reads a raw method body from the given binary input stream.
/// </summary>
/// <param name="errorListener">The object responsible for recording parser errors.</param>
/// <param name="reader">The binary input stream to read from.</param>
/// <returns>The raw method body.</returns>
/// <exception cref="NotSupportedException">Occurs when the method header indicates an invalid or unsupported
/// method body format.</exception>
public static CilRawMethodBody? FromReader(IErrorListener errorListener, ref BinaryStreamReader reader)
{
var flag = (CilMethodBodyAttributes) reader.ReadByte();
reader.Offset--;
if ((flag & CilMethodBodyAttributes.Fat) == CilMethodBodyAttributes.Fat)
return CilRawFatMethodBody.FromReader(errorListener, ref reader);
if ((flag & CilMethodBodyAttributes.Tiny) == CilMethodBodyAttributes.Tiny)
return CilRawTinyMethodBody.FromReader(errorListener, ref reader);
throw new NotSupportedException("Invalid or unsupported method body format.");
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\BlobStreamTest.cs | AsmResolver.PE.Tests.DotNet.Metadata
| BlobStreamTest | [] | ['AsmResolver.PE.DotNet.Metadata', 'Xunit'] | xUnit | net8.0 | public class BlobStreamTest
{
private static void AssertDoesNotHaveBlob(byte[] streamData, byte[] needle)
{
var stream = new SerializedBlobStream(streamData);
Assert.False(stream.TryFindBlobIndex(needle, out _));
}
private static void AssertHasBlob(byte[] streamData, byte[]? needle)
{
var stream = new SerializedBlobStream(streamData);
Assert.True(stream.TryFindBlobIndex(needle, out uint actualIndex));
Assert.Equal(needle, stream.GetBlobByIndex(actualIndex));
}
[Fact]
public void FindNullBlob() => AssertHasBlob(new byte[]
{
0x00, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06
},
null);
[Fact]
public void FindSmallExistingBlob() => AssertHasBlob(new byte[]
{
0x00, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06
},
new byte[]
{
0x01, 0x02, 0x03, 0x04, 0x05
});
[Fact]
public void FindSmallExistingBlobAfterSimilarBlob() => AssertHasBlob(new byte[]
{
0x00, 0x05, 0x01, 0x02, 0x03, 0x04, 0x06, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06
},
new byte[]
{
0x01, 0x02, 0x03, 0x04, 0x05
});
[Fact]
public void FindSmallOverlappingBlob() => AssertHasBlob(new byte[]
{
0x00, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06
},
new byte[]
{
0x02
});
[Fact]
public void FindSmallOverlappingBlob2() => AssertHasBlob(new byte[]
{
0x00, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06
},
new byte[]
{
0x03, 0x04
});
[Fact]
public void FindSmallIncompleteBlobShouldReturnFalse() => AssertDoesNotHaveBlob(new byte[]
{
0x00, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06
},
new byte[]
{
0x04, 0x05, 0x06, 0x07
});
[Fact]
public void FindSmallBlobAfterCorruptedHeader() => AssertHasBlob(new byte[]
{
0x00, 0x80, 0x03, 0x03, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06
},
new byte[]
{
0x01, 0x02, 0x03
});
} | 110 | 2,682 | using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata
{
/// <summary>
/// Represents the metadata stream containing blob signatures referenced by entries in the tables stream.
/// </summary>
/// <remarks>
/// Like most metadata streams, the blob stream does not necessarily contain just valid blobs. It can contain
/// (garbage) data that is never referenced by any of the tables in the tables stream. The only guarantee that the
/// blob heap provides, is that any blob index in the tables stream is the start address (relative to the start of
/// the blob stream) of a blob signature that is prefixed by a length.
/// </remarks>
public abstract class BlobStream : MetadataHeap
{
/// <summary>
/// The default name of a blob stream, as described in the specification provided by ECMA-335.
/// </summary>
public const string DefaultName = "#Blob";
/// <summary>
/// Initializes the blob stream with its default name.
/// </summary>
protected BlobStream()
: base(DefaultName)
{
}
/// <summary>
/// Initializes the blob stream with a custom name.
/// </summary>
/// <param name="name">The name of the stream.</param>
protected BlobStream(string name)
: base(name)
{
}
/// <summary>
/// Gets a blob by its blob index.
/// </summary>
/// <param name="index">The offset into the heap to start reading.</param>
/// <returns>
/// The blob, excluding the bytes encoding the length of the blob, or <c>null</c> if the index was invalid.
/// </returns>
public abstract byte[]? GetBlobByIndex(uint index);
/// <summary>
/// Gets a blob binary reader by its blob index.
/// </summary>
/// <param name="index">The offset into the heap to start reading.</param>
/// <param name="reader">When this method returns <c>true</c>, this parameter contains the created binary reader.</param>
/// <returns>
/// <c>true</c> if a blob reader could be created at the provided index, <c>false</c> otherwise.
/// </returns>
public abstract bool TryGetBlobReaderByIndex(uint index, out BinaryStreamReader reader);
/// <summary>
/// Searches the stream for the provided blob.
/// </summary>
/// <param name="blob">The blob to search for.</param>
/// <param name="index">When the function returns <c>true</c>, contains the index at which the blob was found.</param>
/// <returns><c>true</c> if the blob index was found, <c>false</c> otherwise.</returns>
public abstract bool TryFindBlobIndex(byte[]? blob, out uint index);
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\FieldRvaDataReaderTest.cs | AsmResolver.PE.Tests.DotNet.Metadata
| FieldRvaDataReaderTest | [] | ['AsmResolver.DotNet.TestCases.Fields', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'AsmResolver.PE.Platforms', 'Xunit'] | xUnit | net8.0 | public class FieldRvaDataReaderTest
{
private static FieldRvaRow FindFieldRvaRow(TablesStream tablesStream, MetadataToken cctorToken, MetadataToken fieldToken)
{
var reader = tablesStream
.GetTable<MethodDefinitionRow>(TableIndex.Method)
.GetByRid(cctorToken.Rid)
.Body.CreateReader();
var body = CilRawMethodBody.FromReader(ThrowErrorListener.Instance, ref reader)!;
var disassembler = new CilDisassembler(body.Code.CreateReader());
var initialValueFieldToken = MetadataToken.Zero;
var instructions = disassembler.ReadInstructions();
for (int i = 0; i < instructions.Count; i++)
{
if (instructions[i].OpCode.Code == CilCode.Ldtoken
&& instructions[i + 2].OpCode.Code == CilCode.Stsfld
&& (MetadataToken) instructions[i + 2].Operand! == fieldToken)
{
initialValueFieldToken = (MetadataToken) instructions[i].Operand!;
break;
}
}
Assert.NotEqual(MetadataToken.Zero, initialValueFieldToken);
Assert.True(tablesStream
.GetTable<FieldRvaRow>(TableIndex.FieldRva)
.TryGetRowByKey(1, initialValueFieldToken.Rid, out var fieldRvaRow));
return fieldRvaRow;
}
[Fact]
public void ReadByteArray()
{
// Open image.
var image = PEImage.FromFile(typeof(InitialValues).Assembly.Location, TestReaderParameters);
var directory = image.DotNetDirectory!;
// Get token of field.
var cctorToken = (MetadataToken) typeof(InitialValues)
.TypeInitializer
!.MetadataToken;
var fieldToken = (MetadataToken) typeof(InitialValues)
.GetField(nameof(InitialValues.ByteArray))
!.MetadataToken;
// Find associated field rva row.
var fieldRvaRow = FindFieldRvaRow(directory.Metadata!.GetStream<TablesStream>(), cctorToken, fieldToken);
// Read the data.
var dataReader = new FieldRvaDataReader();
var segment = dataReader.ResolveFieldData(
ThrowErrorListener.Instance,
Platform.Get(image.MachineType),
directory,
fieldRvaRow) as IReadableSegment;
Assert.NotNull(segment);
Assert.Equal(InitialValues.ByteArray, segment.ToArray());
}
} | 267 | 2,926 | using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.File;
using AsmResolver.PE.Platforms;
namespace AsmResolver.PE.DotNet.Metadata
{
/// <summary>
/// Provides a default implementation of the <see cref="IFieldRvaDataReader"/> interface.
/// </summary>
public class FieldRvaDataReader : IFieldRvaDataReader
{
/// <summary>
/// Gets the singleton instance of the <see cref="FieldRvaDataReader"/> class.
/// </summary>
public static FieldRvaDataReader Instance { get; } = new();
/// <inheritdoc />
public ISegment? ResolveFieldData(
IErrorListener listener,
Platform platform,
DotNetDirectory directory,
in FieldRvaRow fieldRvaRow)
{
if (fieldRvaRow.Data.IsBounded)
return fieldRvaRow.Data.GetSegment();
var metadata = directory.Metadata;
if (metadata is null)
{
listener.BadImage(".NET directory does not contain a metadata directory.");
return null;
}
if (!metadata.TryGetStream<TablesStream>(out var tablesStream))
{
listener.BadImage("Metadata does not contain a tables stream.");
return null;
}
var table = tablesStream.GetTable<FieldDefinitionRow>(TableIndex.Field);
if (fieldRvaRow.Field > table.Count)
{
listener.BadImage("FieldRva row has an invalid Field column value.");
return null;
}
var field = table.GetByRid(fieldRvaRow.Field);
int valueSize = DetermineFieldSize(listener, platform, directory, field);
if (fieldRvaRow.Data.CanRead)
{
var reader = fieldRvaRow.Data.CreateReader();
return DataSegment.FromReader(ref reader, valueSize);
}
if (fieldRvaRow.Data is PESegmentReference {IsValidAddress: true})
{
// We are reading from a virtual segment that is resized at runtime, assume zeroes.
var segment = new ZeroesSegment((uint) valueSize);
segment.UpdateOffsets(new RelocationParameters(fieldRvaRow.Data.Offset, fieldRvaRow.Data.Rva));
return segment;
}
listener.NotSupported("FieldRva row has an invalid or unsupported data column.");
return null;
}
private int DetermineFieldSize(IErrorListener listener, Platform platform, DotNetDirectory directory, in FieldDefinitionRow field)
{
if (!directory.Metadata!.TryGetStream<BlobStream>(out var blobStream)
|| !blobStream.TryGetBlobReaderByIndex(field.Signature, out var reader))
{
return 0;
}
reader.ReadByte(); // calling convention attributes.
while (true)
{
switch ((ElementType)reader.ReadByte())
{
case ElementType.Boolean:
return sizeof(bool);
case ElementType.Char:
return sizeof(char);
case ElementType.I1:
return sizeof(sbyte);
case ElementType.U1:
return sizeof(byte);
case ElementType.I2:
return sizeof(short);
case ElementType.U2:
return sizeof(ushort);
case ElementType.I4:
return sizeof(int);
case ElementType.U4:
return sizeof(uint);
case ElementType.I8:
return sizeof(long);
case ElementType.U8:
return sizeof(ulong);
case ElementType.R4:
return sizeof(float);
case ElementType.R8:
return sizeof(double);
case ElementType.ValueType:
return GetCustomTypeSize(directory.Metadata, ref reader);
case ElementType.I:
case ElementType.U:
case ElementType.Ptr:
case ElementType.FnPtr:
return directory.Flags.IsLoadedAs32Bit(platform) ? sizeof(uint) : sizeof(ulong);
case ElementType.CModReqD:
case ElementType.CModOpt:
if (!reader.TryReadCompressedUInt32(out _))
return listener.BadImageAndReturn<int>("Invalid field signature.");
break;
}
}
}
private int GetCustomTypeSize(MetadataDirectory metadataDirectory, ref BinaryStreamReader reader)
{
if (!reader.TryReadCompressedUInt32(out uint codedIndex)
|| !metadataDirectory.TryGetStream<TablesStream>(out var tablesStream))
{
return 0;
}
var typeToken = tablesStream
.GetIndexEncoder(CodedIndex.TypeDefOrRef)
.DecodeIndex(codedIndex);
if (typeToken.Table == TableIndex.TypeDef)
{
var classLayoutTable = tablesStream.GetTable<ClassLayoutRow>(TableIndex.ClassLayout);
if (classLayoutTable.TryGetRowByKey(2, typeToken.Rid, out var row))
return (int) row.ClassSize;
}
return 0;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\GuidStreamTest.cs | AsmResolver.PE.Tests.DotNet.Metadata
| GuidStreamTest | ['private readonly GuidStream _guidStream;'] | ['System', 'AsmResolver.PE.DotNet.Metadata', 'Xunit'] | xUnit | net8.0 | public class GuidStreamTest
{
private readonly GuidStream _guidStream;
public GuidStreamTest()
{
_guidStream = new SerializedGuidStream(GuidStream.DefaultName, new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F
});
}
[Fact]
public void IndexZeroGivesZeroGuid()
{
Assert.Equal(Guid.Empty, _guidStream.GetGuidByIndex(0));
}
[Fact]
public void IndexOneGivesFirstGuidInArray()
{
Assert.Equal(new Guid(new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
}), _guidStream.GetGuidByIndex(1));
}
[Fact]
public void IndexTwoGivesSecondGuidInArray()
{
Assert.Equal(new Guid(new byte[]
{
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
}), _guidStream.GetGuidByIndex(2));
}
[Fact]
public void IndexThreeGivesThirdGuidInArray()
{
Assert.Equal(new Guid(new byte[]
{
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
}), _guidStream.GetGuidByIndex(3));
}
private void AssertDoesNotHaveGuid(Guid needle)
{
Assert.False(_guidStream.TryFindGuidIndex(needle, out _));
}
private void AssertHasGuid(Guid needle)
{
Assert.True(_guidStream.TryFindGuidIndex(needle, out uint actualIndex));
Assert.Equal(needle, _guidStream.GetGuidByIndex(actualIndex));
}
[Theory]
[InlineData(new byte[]
{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F})]
[InlineData(new byte[]
{0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F})]
[InlineData(new byte[]
{0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F})]
public void FindExistingGuid(byte[] guidData) => AssertHasGuid(new Guid(guidData));
[Theory]
[InlineData(new byte[]
{0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17})]
[InlineData(new byte[]
{0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})]
public void FindNonExistingGuid(byte[] guidData) => AssertDoesNotHaveGuid(new Guid(guidData));
} | 125 | 3,180 | namespace AsmResolver.PE.DotNet.Metadata
{
/// <summary>
/// Represents the metadata stream containing GUIDs referenced by entries in the tables stream.
/// </summary>
/// <remarks>
/// Like most metadata streams, the GUID stream does not necessarily contain just valid strings. It can contain
/// (garbage) data that is never referenced by any of the tables in the tables stream. The only guarantee that the
/// GUID heap provides, is that any blob index in the tables stream is the start address (relative to the start of
/// the GUID stream) of a GUID.
/// </remarks>
public abstract class GuidStream : MetadataHeap
{
/// <summary>
/// The size of a single GUID in the GUID stream.
/// </summary>
public const int GuidSize = 16;
/// <summary>
/// The default name of a GUID stream, as described in the specification provided by ECMA-335.
/// </summary>
public const string DefaultName = "#GUID";
/// <summary>
/// Initializes the GUID stream with its default name.
/// </summary>
protected GuidStream()
: base(DefaultName)
{
}
/// <summary>
/// Initializes the GUID stream with a custom name.
/// </summary>
/// <param name="name">The name of the stream.</param>
protected GuidStream(string name)
: base(name)
{
}
/// <summary>
/// Gets a GUID by its GUID index.
/// </summary>
/// <param name="index">The offset into the heap to start reading.</param>
/// <returns>The GUID.</returns>
public abstract System.Guid GetGuidByIndex(uint index);
/// <summary>
/// Searches the stream for the provided GUID.
/// </summary>
/// <param name="guid">The GUID to search for.</param>
/// <param name="index">When the function returns <c>true</c>, contains the index at which the GUID was found.</param>
/// <returns><c>true</c> if the GUID index was found, <c>false</c> otherwise.</returns>
public abstract bool TryFindGuidIndex(System.Guid guid, out uint index);
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\MetadataDirectoryTest.cs | AsmResolver.PE.Tests.DotNet.Metadata
| MetadataDirectoryTest | [] | ['System.IO', 'System.Linq', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'AsmResolver.PE.File', 'Xunit'] | xUnit | net8.0 | public class MetadataDirectoryTest
{
[Fact]
public void CorrectHeader()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
Assert.Equal(1, metadata.MajorVersion);
Assert.Equal(1, metadata.MinorVersion);
Assert.Equal(0u, metadata.Reserved);
Assert.Contains("v4.0.30319", metadata.VersionString);
Assert.Equal(0u, metadata.Flags);
Assert.Equal(5, metadata.Streams.Count);
}
[Fact]
public void CorrectStreamHeaders()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
string[] expectedNames = new[] {"#~", "#Strings", "#US", "#GUID", "#Blob"};
Assert.Equal(expectedNames, metadata.Streams.Select(s => s.Name));
}
[Fact]
public void CorrectStreamHeadersUnalignedMetadataDirectory()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld_UnalignedMetadata, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
string[] expectedNames = new[] {"#~", "#Strings", "#US", "#GUID", "#Blob"};
Assert.Equal(expectedNames, metadata.Streams.Select(s => s.Name));
}
[Fact]
public void DetectStringsStream()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
var stream = metadata.GetStream(StringsStream.DefaultName);
Assert.NotNull(stream);
Assert.IsAssignableFrom<StringsStream>(stream);
}
[Fact]
public void DetectUserStringsStream()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
var stream = metadata.GetStream(UserStringsStream.DefaultName);
Assert.NotNull(stream);
Assert.IsAssignableFrom<UserStringsStream>(stream);
}
[Fact]
public void DetectBlobStream()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
var stream = metadata.GetStream(BlobStream.DefaultName);
Assert.NotNull(stream);
Assert.IsAssignableFrom<BlobStream>(stream);
}
[Fact]
public void DetectGuidStream()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
var stream = metadata.GetStream(GuidStream.DefaultName);
Assert.NotNull(stream);
Assert.IsAssignableFrom<GuidStream>(stream);
}
[Fact]
public void DetectCompressedTableStream()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
var stream = metadata.GetStream(TablesStream.CompressedStreamName);
Assert.NotNull(stream);
Assert.IsAssignableFrom<TablesStream>(stream);
}
[Fact]
public void PreserveMetadataNoChange()
{
var peFile = PEFile.FromBytes(Properties.Resources.HelloWorld);
var peImage = PEImage.FromFile(peFile, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
using var tempStream = new MemoryStream();
metadata.Write(new BinaryStreamWriter(tempStream));
var reader = new BinaryStreamReader(tempStream.ToArray());
var context = MetadataReaderContext.FromReaderContext(new PEReaderContext(peFile));
var newMetadata = new SerializedMetadataDirectory(context, ref reader);
Assert.Equal(metadata.MajorVersion, newMetadata.MajorVersion);
Assert.Equal(metadata.MinorVersion, newMetadata.MinorVersion);
Assert.Equal(metadata.Reserved, newMetadata.Reserved);
Assert.Equal(metadata.VersionString, newMetadata.VersionString);
Assert.Equal(metadata.Flags, newMetadata.Flags);
Assert.Equal(metadata.Streams.Count, newMetadata.Streams.Count);
Assert.All(Enumerable.Range(0, metadata.Streams.Count), i =>
{
var oldStream = metadata.Streams[i];
var newStream = newMetadata.Streams[i];
Assert.Equal(oldStream.Name, newStream.Name);
var oldData = oldStream.CreateReader().ReadToEnd();
var newData = newStream.CreateReader().ReadToEnd();
Assert.Equal(oldData, newData);
});
}
private void AssertCorrectStreamIsSelected<TStream>(byte[] assembly, bool isEnC)
where TStream : class, IMetadataStream
{
AssertCorrectStreamIsSelected<TStream>(PEImage.FromBytes(assembly, TestReaderParameters), isEnC);
}
private void AssertCorrectStreamIsSelected<TStream>(PEImage peImage, bool isEnC)
where TStream : class, IMetadataStream
{
var metadata = peImage.DotNetDirectory!.Metadata!;
var allStreams = metadata.Streams
.OfType<TStream>()
.ToArray();
var dominantStream = metadata.GetStream<TStream>();
int expectedIndex = isEnC ? 0 : allStreams.Length - 1;
Assert.Equal(allStreams[expectedIndex], dominantStream);
}
[Fact]
public void SelectLastBlobStreamInNormalMetadata()
{
AssertCorrectStreamIsSelected<BlobStream>(Properties.Resources.HelloWorld_DoubleBlobStream, false);
}
[Fact]
public void SelectLastGuidStreamInNormalMetadata()
{
AssertCorrectStreamIsSelected<GuidStream>(Properties.Resources.HelloWorld_DoubleGuidStream, false);
}
[Fact]
public void SelectLastStringsStreamInNormalMetadata()
{
AssertCorrectStreamIsSelected<StringsStream>(Properties.Resources.HelloWorld_DoubleStringsStream, false);
}
[Fact]
public void SelectLastUserStringsStreamInNormalMetadata()
{
AssertCorrectStreamIsSelected<UserStringsStream>(Properties.Resources.HelloWorld_DoubleUserStringsStream, false);
}
[Fact]
public void SelectFirstBlobStreamInEnCMetadata()
{
AssertCorrectStreamIsSelected<BlobStream>(Properties.Resources.HelloWorld_DoubleBlobStream_EnC, true);
}
[Fact]
public void SelectFirstGuidStreamInEnCMetadata()
{
AssertCorrectStreamIsSelected<GuidStream>(Properties.Resources.HelloWorld_DoubleGuidStream_EnC, true);
}
[Fact]
public void SelectFirstStringsStreamInEnCMetadata()
{
AssertCorrectStreamIsSelected<StringsStream>(Properties.Resources.HelloWorld_DoubleStringsStream_EnC, true);
}
[Fact]
public void SelectFirstUserStringsStreamInEnCMetadata()
{
AssertCorrectStreamIsSelected<UserStringsStream>(Properties.Resources.HelloWorld_DoubleUserStringsStream_EnC, true);
}
[Fact]
public void SchemaStreamShouldForceEnCMetadata()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld_SchemaStream, TestReaderParameters);
AssertCorrectStreamIsSelected<BlobStream>(peImage, true);
AssertCorrectStreamIsSelected<GuidStream>(peImage, true);
AssertCorrectStreamIsSelected<StringsStream>(peImage, true);
AssertCorrectStreamIsSelected<UserStringsStream>(peImage, true);
}
[Fact]
public void UseCaseInsensitiveComparisonForHeapNamesInEnCMetadata()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld_LowerCaseHeapsWithEnC, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
Assert.True(metadata.TryGetStream(out BlobStream? blobStream));
Assert.Equal("#blob", blobStream.Name);
Assert.True(metadata.TryGetStream(out GuidStream? guidStream));
Assert.Equal("#guid", guidStream.Name);
Assert.True(metadata.TryGetStream(out StringsStream? stringsStream));
Assert.Equal("#strings", stringsStream.Name);
Assert.True(metadata.TryGetStream(out UserStringsStream? userStringsStream));
Assert.Equal("#us", userStringsStream.Name);
}
[Fact]
public void UseCaseSensitiveComparisonForHeapNamesInNormalMetadata()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld_LowerCaseHeapsNormalMetadata, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
Assert.True(metadata.TryGetStream(out BlobStream? blobStream));
Assert.Equal("#Blob", blobStream.Name);
Assert.True(metadata.TryGetStream(out GuidStream? guidStream));
Assert.Equal("#GUID", guidStream.Name);
Assert.True(metadata.TryGetStream(out StringsStream? stringsStream));
Assert.Equal("#Strings", stringsStream.Name);
Assert.True(metadata.TryGetStream(out UserStringsStream? userStringsStream));
Assert.Equal("#US", userStringsStream.Name);
}
[Fact]
public void UseLargeTableIndicesWhenJTDStreamIsPresentInEnCMetadata()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld_JTDStream, TestReaderParameters);
var metadata = peImage.DotNetDirectory!.Metadata!;
var tablesStream = metadata.GetStream<TablesStream>();
Assert.True(tablesStream.ForceLargeColumns);
var tableIndices = Enumerable.Range((int)TableIndex.Module, (int)TableIndex.Max).Select(x => (TableIndex)x)
.Where(x => x.IsValidTableIndex());
Assert.All(tableIndices, index => Assert.Equal(IndexSize.Long, tablesStream.GetTableIndexSize(index)));
var codedIndices = Enumerable
.Range((int)CodedIndex.TypeDefOrRef, CodedIndex.HasCustomDebugInformation - CodedIndex.TypeDefOrRef + 1)
.Select(x => (CodedIndex)x);
Assert.All(codedIndices, index => Assert.Equal(IndexSize.Long, tablesStream.GetIndexEncoder(index).IndexSize));
Assert.Equal(IndexSize.Long, tablesStream.StringIndexSize);
Assert.Equal(IndexSize.Long, tablesStream.GuidIndexSize);
Assert.Equal(IndexSize.Long, tablesStream.BlobIndexSize);
}
} | 245 | 11,546 | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.PE.DotNet.Metadata
{
/// <summary>
/// Represents a data directory containing metadata for a managed executable, including fields from the metadata
/// header, as well as the streams containing metadata tables and blob signatures.
/// </summary>
public class MetadataDirectory : SegmentBase
{
private IList<IMetadataStream>? _streams;
/// <summary>
/// Gets or sets the major version of the metadata directory format.
/// </summary>
/// <remarks>
/// This field is usually set to 1.
/// </remarks>
public ushort MajorVersion
{
get;
set;
} = 1;
/// <summary>
/// Gets or sets the minor version of the metadata directory format.
/// </summary>
/// <remarks>
/// This field is usually set to 1.
/// </remarks>
public ushort MinorVersion
{
get;
set;
} = 1;
/// <summary>
/// Reserved for future use.
/// </summary>
public uint Reserved
{
get;
set;
}
/// <summary>
/// Gets or sets the string containing the runtime version that the .NET binary was built for.
/// </summary>
public string VersionString
{
get;
set;
} = "v4.0.30319";
/// <summary>
/// Reserved for future use.
/// </summary>
public ushort Flags
{
get;
set;
}
/// <summary>
/// Gets a value indicating whether the metadata directory is loaded as Edit-and-Continue metadata.
/// </summary>
public bool IsEncMetadata
{
get;
set;
}
/// <summary>
/// Gets a collection of metadata streams that are defined in the metadata header.
/// </summary>
public IList<IMetadataStream> Streams
{
get
{
if (_streams is null)
Interlocked.CompareExchange(ref _streams, GetStreams(), null);
return _streams;
}
}
/// <summary>
/// Reads a .NET metadata directory from a file.
/// </summary>
/// <param name="path">The path to the file.</param>
/// <returns>The read metadata.</returns>
public static MetadataDirectory FromFile(string path) => FromBytes(System.IO.File.ReadAllBytes(path));
/// <summary>
/// Interprets the provided binary data as a .NET metadata directory.
/// </summary>
/// <param name="data">The raw data.</param>
/// <returns>The read metadata.</returns>
public static MetadataDirectory FromBytes(byte[] data) => FromReader(new BinaryStreamReader(data));
/// <summary>
/// Reads a .NET metadata directory from a file.
/// </summary>
/// <param name="file">The file to read.</param>
/// <returns>The read metadata.</returns>
public static MetadataDirectory FromFile(IInputFile file) => FromReader(file.CreateReader());
/// <summary>
/// Interprets the provided binary stream as a .NET metadata directory.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <returns>The read metadata.</returns>
public static MetadataDirectory FromReader(BinaryStreamReader reader)
{
return FromReader(reader, new MetadataReaderContext(VirtualAddressFactory.Instance));
}
/// <summary>
/// Interprets the provided binary stream as a .NET metadata directory.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <param name="context">The context in which the reader is situated in.</param>
/// <returns>The read metadata.</returns>
public static MetadataDirectory FromReader(BinaryStreamReader reader, MetadataReaderContext context)
{
return new SerializedMetadataDirectory(context, ref reader);
}
/// <inheritdoc />
public override uint GetPhysicalSize()
{
return (uint) (sizeof(uint) // Signature
+ 2 * sizeof(ushort) // Version
+ sizeof(uint) // Reserved
+ sizeof(uint) // Version length
+ ((uint) VersionString.Length).Align(4) // Version
+ sizeof(ushort) // Flags
+ sizeof(ushort) // Stream count
+ GetSizeOfStreamHeaders() // Stream headers
+ Streams.Sum(s => s.GetPhysicalSize())); // Streams
}
/// <inheritdoc />
public override void Write(BinaryStreamWriter writer)
{
ulong start = writer.Offset;
writer.WriteUInt32((uint) MetadataSignature.Bsjb);
writer.WriteUInt16(MajorVersion);
writer.WriteUInt16(MinorVersion);
writer.WriteUInt32(Reserved);
var versionBytes = new byte[((uint) VersionString.Length).Align(4)];
Encoding.UTF8.GetBytes(VersionString, 0, VersionString.Length, versionBytes, 0);
writer.WriteInt32(versionBytes.Length);
writer.WriteBytes(versionBytes);
writer.WriteUInt16(Flags);
writer.WriteUInt16((ushort) Streams.Count);
ulong end = writer.Offset;
WriteStreamHeaders(writer, GetStreamHeaders((uint) (end - start)));
WriteStreams(writer);
}
/// <summary>
/// Constructs new metadata stream headers for all streams in the metadata directory.
/// </summary>
/// <param name="offset">The offset of the first stream header.</param>
/// <returns>A list of stream headers.</returns>
protected virtual MetadataStreamHeader[] GetStreamHeaders(uint offset)
{
uint sizeOfHeaders = GetSizeOfStreamHeaders();
offset += sizeOfHeaders;
var result = new MetadataStreamHeader[Streams.Count];
for (int i = 0; i < result.Length; i++)
{
uint size = Streams[i].GetPhysicalSize();
result[i] = new MetadataStreamHeader(offset, size, Streams[i].Name);
offset += size;
}
return result;
}
private uint GetSizeOfStreamHeaders()
{
uint sizeOfHeaders = (uint) (Streams.Count * 2 * sizeof(uint)
+ Streams.Sum(s => ((uint) s.Name.Length + 1).Align(4)));
return sizeOfHeaders;
}
/// <summary>
/// Writes a collection of stream headers to an output stream.
/// </summary>
/// <param name="writer">The output stream to write to.</param>
/// <param name="headers">The headers to write.</param>
protected virtual void WriteStreamHeaders(BinaryStreamWriter writer, MetadataStreamHeader[] headers)
{
for (int i = 0; i < headers.Length; i++)
{
var header = headers[i];
writer.WriteUInt32(header.Offset);
writer.WriteUInt32(header.Size);
ulong nameOffset = writer.Offset;
writer.WriteAsciiString(header.Name);
writer.WriteByte(0);
writer.AlignRelative(4, nameOffset);
}
}
/// <summary>
/// Writes the contents of all streams to an output stream.
/// </summary>
/// <param name="writer">The output stream to write to.</param>
protected virtual void WriteStreams(BinaryStreamWriter writer)
{
for (int i = 0; i < Streams.Count; i++)
Streams[i].Write(writer);
}
/// <summary>
/// Gets a stream by its name.
/// </summary>
/// <param name="name">The name of the stream to search.</param>
/// <returns>The stream</returns>
/// <exception cref="KeyNotFoundException">Occurs when the stream is not present in the metadata directory.</exception>
public virtual IMetadataStream GetStream(string name)
{
return TryGetStream(name, out var stream)
? stream
: throw new KeyNotFoundException($"Metadata directory does not contain a stream called {name}.");
}
/// <summary>
/// Gets a stream by its type.
/// </summary>
/// <typeparam name="TStream">The type of the stream.</typeparam>
/// <returns>The stream</returns>
/// <exception cref="KeyNotFoundException">Occurs when the stream is not present in the metadata directory.</exception>
public TStream GetStream<TStream>()
where TStream : class, IMetadataStream
{
return TryGetStream(out TStream? stream)
? stream
: throw new KeyNotFoundException(
$"Metadata directory does not contain a stream of type {typeof(TStream).FullName}.");
}
/// <summary>
/// Gets a stream by its name.
/// </summary>
/// <param name="name">The name of the stream to search.</param>
/// <param name="stream">The found stream, or <c>null</c> if no match was found.</param>
/// <returns><c>true</c> if a match was found, <c>false</c> otherwise.</returns>
public bool TryGetStream(string name, [NotNullWhen(true)] out IMetadataStream? stream)
{
bool heapRequested = name is not (TablesStream.CompressedStreamName
or TablesStream.EncStreamName
or TablesStream.UncompressedStreamName);
return TryFindStream((c, s) => c.Name == s as string, name, heapRequested, out stream);
}
/// <summary>
/// Gets a stream by its name.
/// </summary>
/// <typeparam name="TStream">The type of the stream.</typeparam>
/// <param name="stream">The found stream, or <c>null</c> if no match was found.</param>
/// <returns><c>true</c> if a match was found, <c>false</c> otherwise.</returns>
public bool TryGetStream<TStream>([NotNullWhen(true)] out TStream? stream)
where TStream : class, IMetadataStream
{
bool heapRequested = !typeof(TablesStream).IsAssignableFrom(typeof(TStream));
if (TryFindStream((c, _) => c is TStream, null, heapRequested, out var candidate))
{
stream = (TStream) candidate;
return true;
}
stream = null;
return false;
}
private bool TryFindStream(
Func<IMetadataStream, object?, bool> condition,
object? state,
bool heapRequested,
[NotNullWhen(true)] out IMetadataStream? stream)
{
var streams = Streams;
bool reverseOrder = heapRequested && !IsEncMetadata;
if (reverseOrder)
{
for (int i = streams.Count - 1; i >= 0; i--)
{
if (condition(streams[i], state))
{
stream = streams[i];
return true;
}
}
}
else
{
for (int i = 0; i < streams.Count; i++)
{
if (condition(streams[i], state))
{
stream = streams[i];
return true;
}
}
}
stream = null;
return false;
}
/// <summary>
/// Obtains the list of streams defined in the data directory.
/// </summary>
/// <returns>The streams.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Streams"/> property.
/// </remarks>
protected virtual IList<IMetadataStream> GetStreams() => new List<IMetadataStream>();
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\PdbStreamTest.cs | AsmResolver.PE.Tests.DotNet.Metadata
| PdbStreamTest | [] | ['System.IO', 'System.Linq', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class PdbStreamTest
{
private static MetadataDirectory GetMetadata(bool rebuild)
{
var metadata = MetadataDirectory.FromBytes(Properties.Resources.TheAnswerPortablePdb);
if (rebuild)
{
using var stream = new MemoryStream();
metadata.Write(new BinaryStreamWriter(stream));
metadata = MetadataDirectory.FromBytes(stream.ToArray());
}
return metadata;
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Id(bool rebuild)
{
var metadata = GetMetadata(rebuild);
Assert.Equal(new byte[]
{
0x95, 0x26, 0xB5, 0xAC, 0xA7, 0xB, 0xB1, 0x4D, 0x9B, 0xF3,
0xCD, 0x31, 0x73, 0xB, 0xE9, 0x64, 0xBE, 0xFE, 0x11, 0xFC
}, metadata.GetStream<PdbStream>().Id);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TypeSystemRowCounts(bool rebuild)
{
var metadata = GetMetadata(rebuild);
var pdbStream = metadata.GetStream<PdbStream>();
var tablesStream = metadata.GetStream<TablesStream>();
Assert.Equal(new uint[]
{
1, 17, 2, 0, 0, 0, 5, 0, 3, 0, 16, 0, 12, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 1,
0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}, pdbStream.TypeSystemRowCounts);
Assert.True(tablesStream.HasExternalRowCounts);
Assert.Equal(
tablesStream.ExternalRowCounts.Take((int) TableIndex.MaxTypeSystemTableIndex),
pdbStream.TypeSystemRowCounts.Take((int) TableIndex.MaxTypeSystemTableIndex));
}
} | 217 | 2,097 | using System;
using System.Linq;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.PE.DotNet.Metadata
{
/// <summary>
/// Represents the metadata stream containing Portable PDB debug data that is associated to a .NET module.
/// </summary>
public class PdbStream : SegmentBase, IMetadataStream
{
/// <summary>
/// The default name of a PDB stream, as described in the specification provided by Portable PDB v1.0.
/// </summary>
public const string DefaultName = "#Pdb";
/// <inheritdoc />
public string Name
{
get;
set;
} = DefaultName;
/// <inheritdoc />
public virtual bool CanRead => false;
/// <summary>
/// Gets the unique identifier representing the debugging metadata blob content.
/// </summary>
public byte[] Id
{
get;
} = new byte[20];
/// <summary>
/// Gets or sets the token of the entry point method, or 9 if not applicable.
/// </summary>
/// <remarks>
/// This should be the same value as stored in the metadata header.
/// </remarks>
public MetadataToken EntryPoint
{
get;
set;
}
/// <summary>
/// Gets an array of row counts of every portable PDB table in the tables stream.
/// </summary>
public uint[] TypeSystemRowCounts
{
get;
} = new uint[(int) TableIndex.Max];
/// <summary>
/// Synchronizes the row counts stored in <see cref="TypeSystemRowCounts"/> with the tables in the provided
/// tables stream.
/// </summary>
/// <param name="stream">The tables stream to pull the data from.</param>
public void UpdateRowCounts(TablesStream stream)
{
for (TableIndex i = 0; i < TableIndex.MaxTypeSystemTableIndex; i++)
{
if (i.IsValidTableIndex())
TypeSystemRowCounts[(int) i] = (uint) stream.GetTable(i).Count;
}
}
/// <summary>
/// Synchronizes the row counts stored in <see cref="TypeSystemRowCounts"/> with the tables in the provided
/// tables stream row counts.
/// </summary>
/// <param name="rowCounts">The tables stream row counts to pull in.</param>
public void UpdateRowCounts(uint[] rowCounts)
{
for (TableIndex i = 0; i < TableIndex.MaxTypeSystemTableIndex && (int) i < rowCounts.Length; i++)
{
if (i.IsValidTableIndex())
TypeSystemRowCounts[(int) i] = rowCounts[(int) i];
}
}
/// <summary>
/// Computes the valid bitmask for the type system table rows referenced by this pdb stream.
/// </summary>
/// <returns>The bitmask.</returns>
public ulong ComputeReferencedTypeSystemTables()
{
ulong result = 0;
for (int i = 0; i < TypeSystemRowCounts.Length; i++)
{
if (TypeSystemRowCounts[i] != 0)
result |= 1UL << i;
}
return result;
}
/// <inheritdoc />
public virtual BinaryStreamReader CreateReader() => throw new NotSupportedException();
/// <inheritdoc />
public override uint GetPhysicalSize()
{
return 20 // ID
+ sizeof(uint) // EntryPoint
+ sizeof(ulong) // ReferencedTypeSystemTables
+ 4 * (uint) TypeSystemRowCounts.Count(c => c != 0); // TypeSystemTableRows.
}
/// <inheritdoc />
public override void Write(BinaryStreamWriter writer)
{
writer.WriteBytes(Id);
writer.WriteUInt32(EntryPoint.ToUInt32());
writer.WriteUInt64(ComputeReferencedTypeSystemTables());
foreach (uint count in TypeSystemRowCounts)
{
if (count != 0)
writer.WriteUInt32(count);
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\Tables\AssemblyDefinitionRowTest.cs | AsmResolver.PE.Tests.DotNet.Metadata.Tables
| AssemblyDefinitionRowTest | [] | ['AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class AssemblyDefinitionRowTest
{
[Fact]
public void ReadRow_SmallBlob_SmallString()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
var assemblyTable = tablesStream.GetTable<AssemblyDefinitionRow>();
Assert.Single(assemblyTable);
Assert.Equal(
new AssemblyDefinitionRow(
(AssemblyHashAlgorithm) 0x00008004,
0x0001,
0x0000,
0x0000,
0x0000,
0x00000000,
0x0000,
0x0013,
0x0000),
assemblyTable[0]);
}
[Fact]
public void WriteRow_SmallBlob_SmallString()
{
RowTestUtils.AssertWriteThenReadIsSame(
new AssemblyDefinitionRow(
(AssemblyHashAlgorithm) 0x00008004,
0x0001,
0x0000,
0x0000,
0x0000,
0x00000000,
0x0000,
0x0013,
0x0000),
AssemblyDefinitionRow.FromReader);
}
[Fact]
public void RowEnumerationTest()
{
var rawRow = new uint[] {0x00008004, 0x0001, 0x0000, 0x0000, 0x0000, 0x00000000, 0x0000, 0x0013, 0x0000};
var row = new AssemblyDefinitionRow((AssemblyHashAlgorithm) rawRow[0],
(ushort) rawRow[1], (ushort) rawRow[2], (ushort) rawRow[3], (ushort) rawRow[4],
(AssemblyAttributes) rawRow[5], rawRow[6], rawRow[7], rawRow[8]);
RowTestUtils.VerifyRowColumnEnumeration(rawRow, row);
}
} | 163 | 2,101 | using System;
using System.Collections;
using System.Collections.Generic;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata.Tables
{
/// <summary>
/// Represents a single row in the assembly definition metadata table.
/// </summary>
public struct AssemblyDefinitionRow : IMetadataRow
{
/// <summary>
/// Reads a single assembly definition row from an input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <param name="layout">The layout of the assembly definition table.</param>
/// <returns>The row.</returns>
public static AssemblyDefinitionRow FromReader(ref BinaryStreamReader reader, TableLayout layout)
{
return new AssemblyDefinitionRow(
(AssemblyHashAlgorithm) reader.ReadUInt32(),
reader.ReadUInt16(),
reader.ReadUInt16(),
reader.ReadUInt16(),
reader.ReadUInt16(),
(AssemblyAttributes) reader.ReadUInt32(),
reader.ReadIndex((IndexSize) layout.Columns[6].Size),
reader.ReadIndex((IndexSize) layout.Columns[7].Size),
reader.ReadIndex((IndexSize) layout.Columns[8].Size));
}
/// <summary>
/// Creates a new row for the assembly definition table.
/// </summary>
/// <param name="hashAlgorithm">The hashing algorithm used to sign the assembly.</param>
/// <param name="majorVersion">The major version number of the assembly.</param>
/// <param name="minorVersion">The minor version number of the assembly.</param>
/// <param name="buildNumber">The build version number of the assembly.</param>
/// <param name="revisionNumber">The revision version number of the assembly.</param>
/// <param name="attributes">The attributes associated to the assembly.</param>
/// <param name="publicKey">The index into the #Blob stream referencing the public key of the assembly to use
/// for verification of a signature, or 0 if the assembly was not signed.</param>
/// <param name="name">The index into the #Strings stream referencing the name of the assembly.</param>
/// <param name="culture">The index into the #Strings stream referencing the locale string of the assembly.</param>
public AssemblyDefinitionRow(AssemblyHashAlgorithm hashAlgorithm,
ushort majorVersion, ushort minorVersion, ushort buildNumber, ushort revisionNumber,
AssemblyAttributes attributes, uint publicKey, uint name, uint culture)
{
HashAlgorithm = hashAlgorithm;
MajorVersion = majorVersion;
MinorVersion = minorVersion;
BuildNumber = buildNumber;
RevisionNumber = revisionNumber;
Attributes = attributes;
PublicKey = publicKey;
Name = name;
Culture = culture;
}
/// <inheritdoc />
public TableIndex TableIndex => TableIndex.Assembly;
/// <inheritdoc />
public int Count => 9;
/// <inheritdoc />
public uint this[int index] => index switch
{
0 => (uint) HashAlgorithm,
1 => MajorVersion,
2 => MinorVersion,
3 => BuildNumber,
4 => RevisionNumber,
5 => (uint) Attributes,
6 => PublicKey,
7 => Name,
8 => Culture,
_ => throw new IndexOutOfRangeException()
};
/// <summary>
/// Gets or sets the hashing algorithm that was used to sign the assembly.
/// </summary>
public AssemblyHashAlgorithm HashAlgorithm
{
get;
set;
}
/// <summary>
/// Gets or sets the major version number of the assembly.
/// </summary>
public ushort MajorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the minor version number of the assembly.
/// </summary>
public ushort MinorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the build number of the assembly.
/// </summary>
public ushort BuildNumber
{
get;
set;
}
/// <summary>
/// Gets or sets the revision number of the assembly.
/// </summary>
public ushort RevisionNumber
{
get;
set;
}
/// <summary>
/// Gets or sets the attributes associated to the assembly.
/// </summary>
public AssemblyAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Blob stream referencing the public key of the assembly to use for verification of
/// a signature.
/// </summary>
/// <remarks>
/// When this field is set to zero, no public key is stored.
/// </remarks>
public uint PublicKey
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings stream referencing the name of the assembly.
/// </summary>
public uint Name
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings stream referencing the locale string of the assembly.
/// </summary>
/// <remarks>
/// When this field is set to zero, the default culture is used.
/// </remarks>
public uint Culture
{
get;
set;
}
/// <inheritdoc />
public void Write(BinaryStreamWriter writer, TableLayout layout)
{
writer.WriteUInt32((uint) HashAlgorithm);
writer.WriteUInt16(MajorVersion);
writer.WriteUInt16(MinorVersion);
writer.WriteUInt16(BuildNumber);
writer.WriteUInt16(RevisionNumber);
writer.WriteUInt32((uint) Attributes);
writer.WriteIndex(PublicKey, (IndexSize) layout.Columns[6].Size);
writer.WriteIndex(Name, (IndexSize) layout.Columns[7].Size);
writer.WriteIndex(Culture, (IndexSize) layout.Columns[8].Size);
}
/// <summary>
/// Determines whether this row is considered equal to the provided assembly definition row.
/// </summary>
/// <param name="other">The other row.</param>
/// <returns><c>true</c> if the rows are equal, <c>false</c> otherwise.</returns>
public bool Equals(AssemblyDefinitionRow other)
{
return HashAlgorithm == other.HashAlgorithm
&& MajorVersion == other.MajorVersion
&& MinorVersion == other.MinorVersion
&& BuildNumber == other.BuildNumber
&& RevisionNumber == other.RevisionNumber
&& Attributes == other.Attributes
&& PublicKey == other.PublicKey
&& Name == other.Name
&& Culture == other.Culture;
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is AssemblyDefinitionRow other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = (int) HashAlgorithm;
hashCode = (hashCode * 397) ^ MajorVersion.GetHashCode();
hashCode = (hashCode * 397) ^ MinorVersion.GetHashCode();
hashCode = (hashCode * 397) ^ BuildNumber.GetHashCode();
hashCode = (hashCode * 397) ^ RevisionNumber.GetHashCode();
hashCode = (hashCode * 397) ^ (int) Attributes;
hashCode = (hashCode * 397) ^ (int) PublicKey;
hashCode = (hashCode * 397) ^ (int) Name;
hashCode = (hashCode * 397) ^ (int) Culture;
return hashCode;
}
}
/// <inheritdoc />
public override string ToString()
{
return $"({(int) HashAlgorithm:X8}, {MajorVersion:X4}, {MinorVersion:X4}, {BuildNumber:X4}, {RevisionNumber:X4}, {(int) Attributes:X8}, {PublicKey:X8}, {Name:X8}, {Culture:X8})";
}
/// <inheritdoc />
public IEnumerator<uint> GetEnumerator()
{
return new MetadataRowColumnEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\Tables\AssemblyReferenceRowTest.cs | AsmResolver.PE.Tests.DotNet.Metadata.Tables
| AssemblyReferenceRowTest | [] | ['AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class AssemblyReferenceRowTest
{
[Fact]
public void ReadRow_SmallBlob_SmallString()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
var assemblyTable = tablesStream.GetTable<AssemblyReferenceRow>();
Assert.Single(assemblyTable);
Assert.Equal(
new AssemblyReferenceRow(
0x0004,
0x0000,
0x0000,
0x0000,
0x00000000,
0x001A,
0x000A,
0x0000,
0x0000),
assemblyTable[0]);
}
[Fact]
public void WriteRow_SmallBlob_SmallString()
{
RowTestUtils.AssertWriteThenReadIsSame(
new AssemblyReferenceRow(
0x0004,
0x0000,
0x0000,
0x0000,
0x00000000,
0x001A,
0x000A,
0x0000,
0x0000),
AssemblyReferenceRow.FromReader);
}
[Fact]
public void RowEnumerationTest()
{
var rawRow = new uint[] {0x0004, 0x0000, 0x0000, 0x0000, 0x00000000, 0x001A, 0x000A, 0x0000, 0x0000};
var row = new AssemblyReferenceRow((ushort) rawRow[0],
(ushort) rawRow[1], (ushort) rawRow[2], (ushort) rawRow[3], (AssemblyAttributes) rawRow[4],
rawRow[5], rawRow[6], rawRow[7], rawRow[8]);
RowTestUtils.VerifyRowColumnEnumeration(rawRow, row);
}
} | 163 | 2,009 | using System;
using System.Collections;
using System.Collections.Generic;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata.Tables
{
/// <summary>
/// Represents a single row in the assembly definition metadata table.
/// </summary>
public struct AssemblyReferenceRow : IMetadataRow
{
/// <summary>
/// Reads a single assembly definition row from an input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <param name="layout">The layout of the assembly definition table.</param>
/// <returns>The row.</returns>
public static AssemblyReferenceRow FromReader(ref BinaryStreamReader reader, TableLayout layout)
{
return new AssemblyReferenceRow(
reader.ReadUInt16(),
reader.ReadUInt16(),
reader.ReadUInt16(),
reader.ReadUInt16(),
(AssemblyAttributes) reader.ReadUInt32(),
reader.ReadIndex((IndexSize) layout.Columns[5].Size),
reader.ReadIndex((IndexSize) layout.Columns[6].Size),
reader.ReadIndex((IndexSize) layout.Columns[7].Size),
reader.ReadIndex((IndexSize) layout.Columns[8].Size));
}
/// <summary>
/// Creates a new row for the assembly reference table.
/// </summary>
/// <param name="majorVersion">The major version number of the assembly.</param>
/// <param name="minorVersion">The minor version number of the assembly.</param>
/// <param name="buildNumber">The build version number of the assembly.</param>
/// <param name="revisionNumber">The revision version number of the assembly.</param>
/// <param name="attributes">The attributes associated to the assembly.</param>
/// <param name="publicKeyOrToken">The index into the #Blob stream referencing the public key or token of the
/// assembly to use for verification of a signature, or 0 if the assembly was not signed.</param>
/// <param name="name">The index into the #Strings stream referencing the name of the assembly.</param>
/// <param name="culture">The index into the #Strings stream referencing the locale string of the assembly.</param>
/// <param name="hashValue">The index into the #Blob stream referencing the hash value of the assembly reference.</param>
public AssemblyReferenceRow(ushort majorVersion, ushort minorVersion, ushort buildNumber, ushort revisionNumber,
AssemblyAttributes attributes, uint publicKeyOrToken, uint name, uint culture, uint hashValue)
{
MajorVersion = majorVersion;
MinorVersion = minorVersion;
BuildNumber = buildNumber;
RevisionNumber = revisionNumber;
Attributes = attributes;
PublicKeyOrToken = publicKeyOrToken;
Name = name;
Culture = culture;
HashValue = hashValue;
}
/// <inheritdoc />
public TableIndex TableIndex => TableIndex.Assembly;
/// <inheritdoc />
public int Count => 9;
/// <inheritdoc />
public uint this[int index] => index switch
{
0 => MajorVersion,
1 => MinorVersion,
2 => BuildNumber,
3 => RevisionNumber,
4 => (uint) Attributes,
5 => PublicKeyOrToken,
6 => Name,
7 => Culture,
8 => HashValue,
_ => throw new IndexOutOfRangeException()
};
/// <summary>
/// Gets or sets the major version number of the assembly.
/// </summary>
public ushort MajorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the minor version number of the assembly.
/// </summary>
public ushort MinorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the build number of the assembly.
/// </summary>
public ushort BuildNumber
{
get;
set;
}
/// <summary>
/// Gets or sets the revision number of the assembly.
/// </summary>
public ushort RevisionNumber
{
get;
set;
}
/// <summary>
/// Gets or sets the attributes associated to the assembly.
/// </summary>
public AssemblyAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Blob stream referencing the public key or token of the assembly to use for
/// verification of a signature.
/// </summary>
/// <remarks>
/// When this field is set to zero, no public key or token is stored.
/// </remarks>
public uint PublicKeyOrToken
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings stream referencing the name of the assembly.
/// </summary>
public uint Name
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings stream referencing the locale string of the assembly.
/// </summary>
/// <remarks>
/// When this field is set to zero, the default culture is used.
/// </remarks>
public uint Culture
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Blob stream referencing the hash value of the assembly reference.
/// </summary>
public uint HashValue
{
get;
set;
}
/// <inheritdoc />
public void Write(BinaryStreamWriter writer, TableLayout layout)
{
writer.WriteUInt16(MajorVersion);
writer.WriteUInt16(MinorVersion);
writer.WriteUInt16(BuildNumber);
writer.WriteUInt16(RevisionNumber);
writer.WriteUInt32((uint) Attributes);
writer.WriteIndex(PublicKeyOrToken, (IndexSize) layout.Columns[5].Size);
writer.WriteIndex(Name, (IndexSize) layout.Columns[6].Size);
writer.WriteIndex(Culture, (IndexSize) layout.Columns[7].Size);
writer.WriteIndex(HashValue, (IndexSize) layout.Columns[8].Size);
}
/// <summary>
/// Determines whether this row is considered equal to the provided assembly reference row.
/// </summary>
/// <param name="other">The other row.</param>
/// <returns><c>true</c> if the rows are equal, <c>false</c> otherwise.</returns>
public bool Equals(AssemblyReferenceRow other)
{
return MajorVersion == other.MajorVersion
&& MinorVersion == other.MinorVersion
&& BuildNumber == other.BuildNumber
&& RevisionNumber == other.RevisionNumber
&& Attributes == other.Attributes
&& PublicKeyOrToken == other.PublicKeyOrToken
&& Name == other.Name
&& Culture == other.Culture
&& HashValue == other.HashValue;
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is AssemblyReferenceRow other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = MajorVersion.GetHashCode();
hashCode = (hashCode * 397) ^ MinorVersion.GetHashCode();
hashCode = (hashCode * 397) ^ BuildNumber.GetHashCode();
hashCode = (hashCode * 397) ^ RevisionNumber.GetHashCode();
hashCode = (hashCode * 397) ^ (int) Attributes;
hashCode = (hashCode * 397) ^ (int) PublicKeyOrToken;
hashCode = (hashCode * 397) ^ (int) Name;
hashCode = (hashCode * 397) ^ (int) Culture;
hashCode = (hashCode * 397) ^ (int) HashValue;
return hashCode;
}
}
/// <inheritdoc />
public override string ToString()
{
return $"({MajorVersion:X4}, {MinorVersion:X4}, {BuildNumber:X4}, {RevisionNumber:X4}, {(int) Attributes:X8}, {PublicKeyOrToken:X8}, {Name:X8}, {Culture:X8})";
}
/// <inheritdoc />
public IEnumerator<uint> GetEnumerator()
{
return new MetadataRowColumnEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\Tables\CustomAttributeRowTest.cs | AsmResolver.PE.Tests.DotNet.Metadata.Tables
| CustomAttributeRowTest | [] | ['AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class CustomAttributeRowTest
{
[Fact]
public void ReadRow_SmallHasCA_SmallCAType_SmallBlob()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
var customAttributeTable = tablesStream.GetTable<CustomAttributeRow>();
Assert.Equal(10, customAttributeTable.Count);
Assert.Equal(
new CustomAttributeRow(
0x002E,
0x000B,
0x0029),
customAttributeTable[0]);
Assert.Equal(
new CustomAttributeRow(
0x002E,
0x0053,
0x00A2),
customAttributeTable[customAttributeTable.Count - 1]);
}
[Fact]
public void WriteRow_SmallHasCA_SmallCAType_SmallBlob()
{
RowTestUtils.AssertWriteThenReadIsSame(
new CustomAttributeRow(
0x002E,
0x000B,
0x0029),
CustomAttributeRow.FromReader);
}
[Fact]
public void RowEnumerationTest()
{
var rawRow = new uint[] { 0x002E, 0x000B, 0x0029 };
var row = new CustomAttributeRow(rawRow[0], rawRow[1], rawRow[2]);
RowTestUtils.VerifyRowColumnEnumeration(rawRow, row);
}
} | 163 | 1,714 | using System;
using System.Collections;
using System.Collections.Generic;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata.Tables
{
/// <summary>
/// Represents a single row in the custom attribute metadata table.
/// </summary>
public struct CustomAttributeRow : IMetadataRow
{
/// <summary>
/// Reads a single custom attribute row from an input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <param name="layout">The layout of the custom attribute table.</param>
/// <returns>The row.</returns>
public static CustomAttributeRow FromReader(ref BinaryStreamReader reader, TableLayout layout)
{
return new CustomAttributeRow(
reader.ReadIndex((IndexSize) layout.Columns[0].Size),
reader.ReadIndex((IndexSize) layout.Columns[1].Size),
reader.ReadIndex((IndexSize) layout.Columns[2].Size));
}
/// <summary>
/// Creates a new row for the custom attribute metadata table.
/// </summary>
/// <param name="parent">The HasCustomAttribute index that this attribute is assigned to.</param>
/// <param name="type">The CustomAttributeType index (an index into either the Method or MemberRef table) defining the
/// constructor to call when initializing the custom attribute.</param>
/// <param name="value">The index into the #Blob stream containing the arguments of the constructor call.</param>
public CustomAttributeRow(uint parent, uint type, uint value)
{
Parent = parent;
Type = type;
Value = value;
}
/// <inheritdoc />
public TableIndex TableIndex => TableIndex.CustomAttribute;
/// <inheritdoc />
public int Count => 3;
/// <inheritdoc />
public uint this[int index] => index switch
{
0 => Parent,
1 => Type,
2 => Value,
_ => throw new IndexOutOfRangeException()
};
/// <summary>
/// Gets a HasCustomAttribute index (an index into either the Method, Field, TypeRef, TypeDef,
/// Param, InterfaceImpl, MemberRef, Module, DeclSecurity, Property, Event, StandAloneSig, ModuleRef,
/// TypeSpec, Assembly, AssemblyRef, File, ExportedType, ManifestResource, GenericParam, GenericParamConstraint,
/// or MethodSpec table) that this attribute is assigned to.
/// </summary>
public uint Parent
{
get;
set;
}
/// <summary>
/// Gets a CustomAttributeType index (an index into either the Method or MemberRef table) defining the
/// constructor to call when initializing the custom attribute.
/// </summary>
public uint Type
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Blob stream containing the arguments of the constructor call.
/// </summary>
public uint Value
{
get;
set;
}
/// <summary>
/// Determines whether this row is considered equal to the provided custom attribute row.
/// </summary>
/// <param name="other">The other row.</param>
/// <returns><c>true</c> if the rows are equal, <c>false</c> otherwise.</returns>
public bool Equals(CustomAttributeRow other)
{
return Parent == other.Parent
&& Type == other.Type
&& Value == other.Value;
}
/// <inheritdoc />
public void Write(BinaryStreamWriter writer, TableLayout layout)
{
writer.WriteIndex(Parent, (IndexSize) layout.Columns[0].Size);
writer.WriteIndex(Type, (IndexSize) layout.Columns[1].Size);
writer.WriteIndex(Value, (IndexSize) layout.Columns[2].Size);
}
/// <inheritdoc />
public override bool Equals(object? obj) => obj is CustomAttributeRow other && Equals(other);
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = (int) Parent;
hashCode = (hashCode * 397) ^ (int) Type;
hashCode = (hashCode * 397) ^ (int) Value;
return hashCode;
}
}
/// <inheritdoc />
public override string ToString() => $"({Parent:X8}, {Type:X8}, {Value:X8})";
/// <inheritdoc />
public IEnumerator<uint> GetEnumerator()
{
return new MetadataRowColumnEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\Tables\MemberReferenceRowTest.cs | AsmResolver.PE.Tests.DotNet.Metadata.Tables
| MemberReferenceRowTest | [] | ['AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class MemberReferenceRowTest
{
[Fact]
public void ReadRow_SmallMemberRefParent_SmallString_SmallBlob()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
var memberRefTable = tablesStream.GetTable<MemberReferenceRow>();
Assert.Equal(12, memberRefTable.Count);
Assert.Equal(
new MemberReferenceRow(
0x0009,
0x0195,
0x0001),
memberRefTable[0]);
Assert.Equal(
new MemberReferenceRow(
0x0061,
0x0195,
0x0006),
memberRefTable[memberRefTable.Count - 1]);
}
[Fact]
public void WriteRow_SmallMemberRefParent_SmallString_SmallBlob()
{
RowTestUtils.AssertWriteThenReadIsSame(
new MemberReferenceRow(
0x0009,
0x0195,
0x0001),
MemberReferenceRow.FromReader);
}
[Fact]
public void RowEnumerationTest()
{
var rawRow = new uint[] {0x0009, 0x0195, 0x0001};
var row = new MemberReferenceRow(rawRow[0], rawRow[1], rawRow[2]);
RowTestUtils.VerifyRowColumnEnumeration(rawRow, row);
}
} | 163 | 1,702 | using System;
using System.Collections;
using System.Collections.Generic;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata.Tables
{
/// <summary>
/// Represents a single row in the member reference metadata table.
/// </summary>
public struct MemberReferenceRow : IMetadataRow
{
/// <summary>
/// Reads a single member reference row from an input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <param name="layout">The layout of the member reference table.</param>
/// <returns>The row.</returns>
public static MemberReferenceRow FromReader(ref BinaryStreamReader reader, TableLayout layout)
{
return new MemberReferenceRow(
reader.ReadIndex((IndexSize) layout.Columns[0].Size),
reader.ReadIndex((IndexSize) layout.Columns[1].Size),
reader.ReadIndex((IndexSize) layout.Columns[2].Size));
}
/// <summary>
/// Creates a new row for the member reference metadata table.
/// </summary>
/// <param name="parent">The MemberRefParent index indicating the parent member reference or definition that
/// defines or can resolve the member reference.</param>
/// <param name="name">The index into the #Strings heap containing the name of the member reference.</param>
/// <param name="signature">The index into the #Blob heap containing the signature of the member.</param>
public MemberReferenceRow(uint parent, uint name, uint signature)
{
Parent = parent;
Name = name;
Signature = signature;
}
/// <inheritdoc />
public TableIndex TableIndex => TableIndex.MemberRef;
/// <inheritdoc />
public int Count => 3;
/// <inheritdoc />
public uint this[int index] => index switch
{
0 => Parent,
1 => Name,
2 => Signature,
_ => throw new IndexOutOfRangeException()
};
/// <summary>
/// Gets a MemberRefParent index (an index into either the TypeDef, TypeRef, ModuleRef, Method or TypeSpec table)
/// indicating the parent member reference or definition that defines or can resolve the member reference.
/// </summary>
public uint Parent
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings heap containing the name of the member reference.
/// </summary>
/// <remarks>
/// This value should always index a non-empty string.
/// </remarks>
public uint Name
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Blob heap containing the signature of the member.
/// </summary>
/// <remarks>
/// This value should always index a valid member signature. This value can also be used to determine whether
/// the member reference is a field or a method.
/// </remarks>
public uint Signature
{
get;
set;
}
/// <inheritdoc />
public void Write(BinaryStreamWriter writer, TableLayout layout)
{
writer.WriteIndex(Parent, (IndexSize) layout.Columns[0].Size);
writer.WriteIndex(Name, (IndexSize) layout.Columns[1].Size);
writer.WriteIndex(Signature, (IndexSize) layout.Columns[2].Size);
}
/// <summary>
/// Determines whether this row is considered equal to the provided member reference row.
/// </summary>
/// <param name="other">The other row.</param>
/// <returns><c>true</c> if the rows are equal, <c>false</c> otherwise.</returns>
public bool Equals(MemberReferenceRow other)
{
return Parent == other.Parent && Name == other.Name && Signature == other.Signature;
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is MemberReferenceRow other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = (int) Parent;
hashCode = (hashCode * 397) ^ (int) Name;
hashCode = (hashCode * 397) ^ (int) Signature;
return hashCode;
}
}
/// <inheritdoc />
public override string ToString()
{
return $"({Parent:X8}, {Name:X8}, {Signature:X8})";
}
/// <inheritdoc />
public IEnumerator<uint> GetEnumerator()
{
return new MetadataRowColumnEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\Tables\MetadataRangeTest.cs | AsmResolver.PE.Tests.DotNet.Metadata.Tables
| MetadataRangeTest | [] | ['System.Linq', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class MetadataRangeTest
{
[Fact]
public void ContinuousRangeEmpty()
{
var range = new MetadataRange(TableIndex.Method, 3, 3);
Assert.Equal(0, range.Count);
Assert.Empty(range);
}
[Fact]
public void ContinuousRangeSingleItem()
{
var range = new MetadataRange(TableIndex.Method, 3, 4);
Assert.Equal(1, range.Count);
Assert.Single(range);
Assert.Equal(new MetadataToken(TableIndex.Method, 3), range.First());
}
[Fact]
public void ContinuousRangeMultipleItems()
{
var range = new MetadataRange(TableIndex.Method, 3, 10);
Assert.Equal(7, range.Count);
Assert.Equal(new[]
{
new MetadataToken(TableIndex.Method, 3),
new MetadataToken(TableIndex.Method, 4),
new MetadataToken(TableIndex.Method, 5),
new MetadataToken(TableIndex.Method, 6),
new MetadataToken(TableIndex.Method, 7),
new MetadataToken(TableIndex.Method, 8),
new MetadataToken(TableIndex.Method, 9)
}, range);
}
[Fact]
public void RedirectedRangeEmpty()
{
var stream = new TablesStream();
var redirectTable = stream.GetTable<MethodPointerRow>();
var range = new MetadataRange(redirectTable, TableIndex.Method, 3, 3);
Assert.Equal(0, range.Count);
Assert.Empty(range);
}
[Fact]
public void RedirectedRangeSingleItem()
{
var stream = new TablesStream();
var redirectTable = stream.GetTable<MethodPointerRow>();
redirectTable.Add(new MethodPointerRow(1));
redirectTable.Add(new MethodPointerRow(2));
redirectTable.Add(new MethodPointerRow(5));
redirectTable.Add(new MethodPointerRow(4));
redirectTable.Add(new MethodPointerRow(3));
var range = new MetadataRange(redirectTable, TableIndex.Method, 3, 4);
Assert.Equal(1, range.Count);
Assert.Single(range);
Assert.Equal(new MetadataToken(TableIndex.Method, 5), range.First());
}
[Fact]
public void RedirectedRangeMultipleItems()
{
var stream = new TablesStream();
var redirectTable = stream.GetTable<MethodPointerRow>();
redirectTable.Add(new MethodPointerRow(1));
redirectTable.Add(new MethodPointerRow(2));
redirectTable.Add(new MethodPointerRow(5));
redirectTable.Add(new MethodPointerRow(4));
redirectTable.Add(new MethodPointerRow(3));
redirectTable.Add(new MethodPointerRow(9));
redirectTable.Add(new MethodPointerRow(8));
redirectTable.Add(new MethodPointerRow(10));
var range = new MetadataRange(redirectTable, TableIndex.Method, 3, 8);
Assert.Equal(5, range.Count);
Assert.Equal(new[]
{
new MetadataToken(TableIndex.Method, 5),
new MetadataToken(TableIndex.Method, 4),
new MetadataToken(TableIndex.Method, 3),
new MetadataToken(TableIndex.Method, 9),
new MetadataToken(TableIndex.Method, 8)
}, range);
}
} | 183 | 3,711 | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace AsmResolver.PE.DotNet.Metadata.Tables
{
/// <summary>
/// Represents a range of metadata tokens, indicated by a starting and ending row identifier within a metadata table.
/// </summary>
public readonly struct MetadataRange : IEnumerable<MetadataToken>, IEquatable<MetadataRange>
{
/// <summary>
/// Represents the empty metadata range.
/// </summary>
public static readonly MetadataRange Empty = new(TableIndex.Module, 1, 1);
/// <summary>
/// Initializes the range.
/// </summary>
/// <param name="table">The table.</param>
/// <param name="startRid">The starting row identifier.</param>
/// <param name="endRid">The ending row identifier. This identifier is exclusive.</param>
public MetadataRange(TableIndex table, uint startRid, uint endRid)
{
Table = table;
StartRid = startRid;
EndRid = endRid;
RedirectionTable = null;
}
/// <summary>
/// Initializes the range.
/// </summary>
/// <param name="redirectionTable">The table that is used for translating raw indices.</param>
/// <param name="table">The table.</param>
/// <param name="startRid">The starting row identifier.</param>
/// <param name="endRid">The ending row identifier. This identifier is exclusive.</param>
public MetadataRange(IMetadataTable redirectionTable, TableIndex table, uint startRid, uint endRid)
{
Table = table;
StartRid = startRid;
EndRid = endRid;
RedirectionTable = redirectionTable;
}
/// <summary>
/// Gets the index of the metadata table this range is targeting.
/// </summary>
public TableIndex Table
{
get;
}
/// <summary>
/// Gets the first row identifier that this range includes.
/// </summary>
public uint StartRid
{
get;
}
/// <summary>
/// Gets the row identifier indicating the end of the range. The range excludes this row identifier.
/// </summary>
public uint EndRid
{
get;
}
/// <summary>
/// Gets the number of metadata rows this range spans.
/// </summary>
public int Count => (int) (EndRid - StartRid);
/// <summary>
/// Gets a value indicating whether the range is empty or not.
/// </summary>
public bool IsEmpty => EndRid == StartRid;
/// <summary>
/// Gets the table that is used for translating raw indices.
/// </summary>
public IMetadataTable? RedirectionTable
{
get;
}
/// <summary>
/// Gets a value indicating whether the range is associated to a redirection table.
/// </summary>
[MemberNotNullWhen(true, nameof(RedirectionTable))]
public bool IsRedirected => RedirectionTable is not null;
/// <summary>
/// Obtains an enumerator that enumerates all metadata tokens within the range.
/// </summary>
/// <returns></returns>
public Enumerator GetEnumerator() => new(this);
/// <inheritdoc />
IEnumerator<MetadataToken> IEnumerable<MetadataToken>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <inheritdoc />
public override string ToString()
{
var start = new MetadataToken(Table, StartRid);
var end = new MetadataToken(Table, EndRid);
return $"[0x{start.ToString()}..0x{end.ToString()})";
}
/// <inheritdoc />
public bool Equals(MetadataRange other)
{
if (IsEmpty && other.IsEmpty)
return true;
return Table == other.Table
&& StartRid == other.StartRid
&& EndRid == other.EndRid
&& Equals(RedirectionTable, other.RedirectionTable);
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is MetadataRange other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
if (IsEmpty)
return 0;
unchecked
{
int hashCode = (int) Table;
hashCode = (hashCode * 397) ^ (int) StartRid;
hashCode = (hashCode * 397) ^ (int) EndRid;
hashCode = (hashCode * 397) ^ (RedirectionTable is not null ? RedirectionTable.GetHashCode() : 0);
return hashCode;
}
}
/// <summary>
/// Represents an enumerator that enumerates all metadata tokens within a token range.
/// </summary>
public struct Enumerator : IEnumerator<MetadataToken>
{
private readonly MetadataRange _range;
private uint _currentRid;
/// <summary>
/// Initializes a new token enumerator.
/// </summary>
/// <param name="range">The range to enumerate from.</param>
public Enumerator(MetadataRange range)
{
_range = range;
_currentRid = range.StartRid - 1;
}
/// <inheritdoc />
public MetadataToken Current
{
get
{
uint actualRid;
if (!_range.IsRedirected)
actualRid = _currentRid;
else
_range.RedirectionTable.TryGetCell(_currentRid, 0, out actualRid);
return new MetadataToken(_range.Table, actualRid);
}
}
/// <inheritdoc />
object IEnumerator.Current => Current;
/// <inheritdoc />
public bool MoveNext()
{
if (_currentRid < _range.EndRid - 1)
{
_currentRid++;
return true;
}
return false;
}
/// <inheritdoc />
public void Reset() => _currentRid = 0;
/// <inheritdoc />
public void Dispose()
{
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\Tables\MethodDefinitionRowTest.cs | AsmResolver.PE.Tests.DotNet.Metadata.Tables
| MethodDefinitionRowTest | [] | ['AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class MethodDefinitionRowTest
{
[Fact]
public void ReadRow_SmallString_SmallBlob_SmallParam()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
var methodTable = tablesStream.GetTable<MethodDefinitionRow>();
Assert.Equal(2, methodTable.Count);
Assert.Equal(
new MethodDefinitionRow(
new VirtualAddress( 0x00002050),
0x0000,
(MethodAttributes) 0x0091,
0x017E,
0x0023,
0x0001),
methodTable[0]);
Assert.Equal(
new MethodDefinitionRow(
new VirtualAddress( 0x0000205C),
0x0000,
(MethodAttributes) 0x1886,
0x0195,
0x0006,
0x0002),
methodTable[1]);
}
[Fact]
public void WriteRow_SmallStrinmg_SmallBlob_SmallParam()
{
RowTestUtils.AssertWriteThenReadIsSame(new MethodDefinitionRow(
new VirtualAddress( 0x00002050),
0x0000,
(MethodAttributes) 0x0091,
0x017E,
0x0023,
0x0001),
MethodDefinitionRow.FromReader);
}
[Fact]
public void RowEnumerationTest()
{
var rawRow = new uint[] {0x00002050, 0x0000, 0x0091, 0x017E, 0x0023, 0x0001};
var row = new MethodDefinitionRow(
new VirtualAddress(rawRow[0]),
(MethodImplAttributes) rawRow[1],
(MethodAttributes) rawRow[2],
rawRow[3],
rawRow[4],
rawRow[5]);
RowTestUtils.VerifyRowColumnEnumeration(rawRow, row);
}
} | 163 | 2,255 | using System;
using System.Collections;
using System.Collections.Generic;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata.Tables
{
/// <summary>
/// Represents a single row in the method definition metadata table.
/// </summary>
public struct MethodDefinitionRow : IMetadataRow
{
/// <summary>
/// Reads a single method definition row from an input stream.
/// </summary>
/// <param name="context">The reader context.</param>
/// <param name="reader">The input stream.</param>
/// <param name="layout">The layout of the method definition table.</param>
/// <returns>The row.</returns>
public static MethodDefinitionRow FromReader(MetadataReaderContext context, ref BinaryStreamReader reader, TableLayout layout)
{
return new MethodDefinitionRow(
context.ReferenceFactory.GetReferenceToRva(reader.ReadUInt32()),
(MethodImplAttributes) reader.ReadUInt16(),
(MethodAttributes) reader.ReadUInt16(),
reader.ReadIndex((IndexSize) layout.Columns[3].Size),
reader.ReadIndex((IndexSize) layout.Columns[4].Size),
reader.ReadIndex((IndexSize) layout.Columns[5].Size));
}
/// <summary>
/// Creates a new row for the method definition metadata table.
/// </summary>
/// <param name="body">The reference to the beginning of the method body. </param>
/// <param name="implAttributes">The characteristics of the implementation of the method body.</param>
/// <param name="attributes">The attributes associated to the method.</param>
/// <param name="name">The index into the #Strings heap containing the name of the type reference.</param>
/// <param name="signature">The index into the #Blob heap containing the signature of the method.</param>
/// <param name="parameterList">The index into the Param (or ParamPtr) table, representing the first parameter
/// that this method defines.</param>
public MethodDefinitionRow(ISegmentReference body, MethodImplAttributes implAttributes, MethodAttributes attributes,
uint name, uint signature, uint parameterList)
{
Body = body;
ImplAttributes = implAttributes;
Attributes = attributes;
Name = name;
Signature = signature;
ParameterList = parameterList;
}
/// <inheritdoc />
public TableIndex TableIndex => TableIndex.Method;
/// <inheritdoc />
public int Count => 6;
/// <inheritdoc />
public uint this[int index] => index switch
{
0 => Body?.Rva ?? 0,
1 => (uint) ImplAttributes,
2 => (uint) Attributes,
3 => Name,
4 => Signature,
5 => ParameterList,
_ => throw new IndexOutOfRangeException()
};
/// <summary>
/// Gets a reference to the beginning of the method body.
/// </summary>
/// <remarks>
/// This field deviates from the original specification as described in ECMA-335. It replaces the RVA column of
/// the method definition row. Only the RVA of this reference is only considered when comparing two method definition
/// rows for equality.
///
/// If this value is null, the method does not define any method body.
/// </remarks>
public ISegmentReference Body
{
get;
set;
}
/// <summary>
/// Gets or sets the characteristics of the implementation of the method body.
/// </summary>
/// <remarks>
/// These attributes dictate the format of <see cref="Body"/>.
/// </remarks>
public MethodImplAttributes ImplAttributes
{
get;
set;
}
/// <summary>
/// Gets or sets the attributes associated to the method.
/// </summary>
public MethodAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings heap containing the name of the type reference.
/// </summary>
/// <remarks>
/// This value should always index a non-empty string.
/// </remarks>
public uint Name
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Blob heap containing the signature of the method. This includes the return type,
/// as well as parameter types.
/// </summary>
/// <remarks>
/// This value should always index a valid method signature.
/// </remarks>
public uint Signature
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the Param (or ParamPtr) table, representing the first parameter that this method defines.
/// </summary>
public uint ParameterList
{
get;
set;
}
/// <inheritdoc />
public void Write(BinaryStreamWriter writer, TableLayout layout)
{
writer.WriteUInt32(Body?.Rva ?? 0);
writer.WriteUInt16((ushort) ImplAttributes);
writer.WriteUInt16((ushort) Attributes);
writer.WriteIndex(Name, (IndexSize) layout.Columns[3].Size);
writer.WriteIndex(Signature, (IndexSize) layout.Columns[4].Size);
writer.WriteIndex(ParameterList, (IndexSize) layout.Columns[5].Size);
}
/// <summary>
/// Determines whether this row is considered equal to the provided method definition row.
/// </summary>
/// <param name="other">The other row.</param>
/// <returns><c>true</c> if the rows are equal, <c>false</c> otherwise.</returns>
/// <remarks>
/// When comparing both method bodies, only the RVA is considered in this equality test. The exact type is ignored.
/// </remarks>
public bool Equals(MethodDefinitionRow other)
{
return Body?.Rva == other.Body?.Rva
&& ImplAttributes == other.ImplAttributes
&& Attributes == other.Attributes
&& Name == other.Name
&& Signature == other.Signature
&& ParameterList == other.ParameterList;
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is MethodDefinitionRow other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = (int) (Body?.Rva ?? 0);
hashCode = (hashCode * 397) ^ (int) ImplAttributes;
hashCode = (hashCode * 397) ^ (int) Attributes;
hashCode = (hashCode * 397) ^ (int) Name;
hashCode = (hashCode * 397) ^ (int) Signature;
hashCode = (hashCode * 397) ^ (int) ParameterList;
return hashCode;
}
}
/// <inheritdoc />
public override string ToString()
{
return $"({Body?.Rva ?? 0:X8}, {(int)ImplAttributes:X4}, {(int) Attributes:X4}, {Name:X8}, {Signature:X8}, {ParameterList:X8})";
}
/// <inheritdoc />
public IEnumerator<uint> GetEnumerator()
{
return new MetadataRowColumnEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\Tables\ModuleDefinitionRowTest.cs | AsmResolver.PE.Tests.DotNet.Metadata.Tables
| ModuleDefinitionRowTest | [] | ['AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class ModuleDefinitionRowTest
{
[Fact]
public void ReadRow_SmallString_SmallGuid()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
var moduleTable = tablesStream.GetTable<ModuleDefinitionRow>();
Assert.Single(moduleTable);
Assert.Equal(
new ModuleDefinitionRow(
0x0000,
0x0146,
0x0001,
0x0000, 0x0000),
moduleTable[0]);
}
[Fact]
public void WriteRow_SmallString_SmallGuid()
{
RowTestUtils.AssertWriteThenReadIsSame(new ModuleDefinitionRow(
0x0000,
0x0146,
0x0001,
0x0000, 0x0000),
ModuleDefinitionRow.FromReader);
}
[Fact]
public void RowEnumerationTest()
{
var rawRow = new uint[]
{
0x0000, 0x0146, 0x0001, 0x0000, 0x0000
};
var row = new ModuleDefinitionRow((ushort) rawRow[0], rawRow[1], rawRow[2],
rawRow[3], rawRow[4]);
RowTestUtils.VerifyRowColumnEnumeration(rawRow, row);
}
} | 163 | 1,581 | using System;
using System.Collections;
using System.Collections.Generic;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata.Tables
{
/// <summary>
/// Represents a single row in the module definition metadata table.
/// </summary>
public struct ModuleDefinitionRow : IMetadataRow
{
/// <summary>
/// Reads a single module definition row from an input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <param name="layout">The layout of the module definition table.</param>
/// <returns>The row.</returns>
public static ModuleDefinitionRow FromReader(ref BinaryStreamReader reader, TableLayout layout)
{
return new ModuleDefinitionRow(
reader.ReadUInt16(),
reader.ReadIndex((IndexSize) layout.Columns[1].Size),
reader.ReadIndex((IndexSize) layout.Columns[2].Size),
reader.ReadIndex((IndexSize) layout.Columns[3].Size),
reader.ReadIndex((IndexSize) layout.Columns[4].Size));
}
/// <summary>
/// Creates a new row for the module definition metadata table.
/// </summary>
/// <param name="generation">The generation number of the module.</param>
/// <param name="name">The index into the #Strings heap containing the name of the module. </param>
/// <param name="mvid">The index into the #GUID heap containing the unique identifier to distinguish
/// between two versions of the same module.</param>
/// <param name="encId"></param>
/// <param name="encBaseId"></param>
public ModuleDefinitionRow(ushort generation, uint name, uint mvid, uint encId, uint encBaseId)
{
Generation = generation;
Name = name;
Mvid = mvid;
EncId = encId;
EncBaseId = encBaseId;
}
/// <inheritdoc />
public TableIndex TableIndex => TableIndex.Module;
/// <inheritdoc />
public int Count => 5;
/// <inheritdoc />
public uint this[int index] => index switch
{
0 => Generation,
1 => Name,
2 => Mvid,
3 => EncId,
4 => EncBaseId,
_ => throw new IndexOutOfRangeException()
};
/// <summary>
/// Gets or sets the generation number of the module.
/// </summary>
/// <remarks>
/// This value is reserved and should be set to zero.
/// </remarks>
public ushort Generation
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings heap containing the name of the module.
/// </summary>
public uint Name
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #GUID heap containing the unique identifier to distinguish between two versions
/// of the same module.
/// </summary>
public uint Mvid
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #GUID heap containing the unique identifier to distinguish between two
/// edit-and-continue generations.
/// </summary>
public uint EncId
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #GUID heap containing the base identifier of an edit-and-continue generation.
/// </summary>
public uint EncBaseId
{
get;
set;
}
/// <inheritdoc />
public void Write(BinaryStreamWriter writer, TableLayout layout)
{
writer.WriteUInt16(Generation);
writer.WriteIndex(Name, (IndexSize) layout.Columns[1].Size);
writer.WriteIndex(Mvid, (IndexSize) layout.Columns[2].Size);
writer.WriteIndex(EncId, (IndexSize) layout.Columns[3].Size);
writer.WriteIndex(EncBaseId, (IndexSize) layout.Columns[4].Size);
}
/// <inheritdoc />
public override string ToString()
{
return $"({Generation:X4}, {Name:X8}, {Mvid:X8}, {EncId:X8}, {EncBaseId:X8})";
}
/// <summary>
/// Determines whether this row is considered equal to the provided module row.
/// </summary>
/// <param name="other">The other row.</param>
/// <returns><c>true</c> if the rows are equal, <c>false</c> otherwise.</returns>
public bool Equals(ModuleDefinitionRow other)
{
return Generation == other.Generation
&& Name == other.Name
&& Mvid == other.Mvid
&& EncId == other.EncId
&& EncBaseId == other.EncBaseId;
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is ModuleDefinitionRow other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = Generation.GetHashCode();
hashCode = (hashCode * 397) ^ (int) Name;
hashCode = (hashCode * 397) ^ (int) Mvid;
hashCode = (hashCode * 397) ^ (int) EncId;
hashCode = (hashCode * 397) ^ (int) EncBaseId;
return hashCode;
}
}
/// <inheritdoc />
public IEnumerator<uint> GetEnumerator()
{
return new MetadataRowColumnEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\Tables\ParameterDefinitionRowTest.cs | AsmResolver.PE.Tests.DotNet.Metadata.Tables
| ParameterDefinitionRowTest | [] | ['AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class ParameterDefinitionRowTest
{
[Fact]
public void ReadRow_SmallString()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
var paramTable = tablesStream.GetTable<ParameterDefinitionRow>();
Assert.Single(paramTable);
Assert.Equal(
new ParameterDefinitionRow(0x0000, 0x001, 0x01DD),
paramTable[0]);
}
[Fact]
public void WriteRow_SmallString()
{
RowTestUtils.AssertWriteThenReadIsSame(
new ParameterDefinitionRow(0x0000, 0x001, 0x01DD),
ParameterDefinitionRow.FromReader);
}
[Fact]
public void RowEnumerationTest()
{
var rawRow = new uint[] { 0x0000, 0x001, 0x01DD };
var row = new ParameterDefinitionRow((ParameterAttributes) rawRow[0], (ushort) rawRow[1], rawRow[2]);
RowTestUtils.VerifyRowColumnEnumeration(rawRow, row);
}
} | 163 | 1,329 | using System;
using System.Collections;
using System.Collections.Generic;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata.Tables
{
/// <summary>
/// Represents a single row in the parameter definition metadata table.
/// </summary>
public struct ParameterDefinitionRow : IMetadataRow
{
/// <summary>
/// Reads a single parameter definition row from an input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <param name="layout">The layout of the parameter definition table.</param>
/// <returns>The row.</returns>
public static ParameterDefinitionRow FromReader(ref BinaryStreamReader reader, TableLayout layout)
{
return new ParameterDefinitionRow(
(ParameterAttributes) reader.ReadUInt16(),
reader.ReadUInt16(),
reader.ReadIndex((IndexSize) layout.Columns[2].Size));
}
/// <summary>
/// Creates a new row for the parameter definition metadata table.
/// </summary>
/// <param name="attributes">The attributes associated to the parameter.</param>
/// <param name="sequence">The index of the parameter definition.</param>
/// <param name="name">The index into the #Strings heap containing the name of the type reference.</param>
public ParameterDefinitionRow(ParameterAttributes attributes, ushort sequence, uint name)
{
Attributes = attributes;
Sequence = sequence;
Name = name;
}
/// <inheritdoc />
public TableIndex TableIndex => TableIndex.Param;
/// <inheritdoc />
public int Count => 3;
/// <inheritdoc />
public uint this[int index] => index switch
{
0 => (uint) Attributes,
1 => Sequence,
2 => Name,
_ => throw new IndexOutOfRangeException()
};
/// <summary>
/// Gets or sets the attributes associated to the parameter.
/// </summary>
public ParameterAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets the index of the parameter definition.
/// </summary>
public ushort Sequence
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings heap containing the name of the type reference.
/// </summary>
/// <remarks>
/// If this value is zero, the parameter name is considered <c>null</c>.
/// </remarks>
public uint Name
{
get;
set;
}
/// <inheritdoc />
public void Write(BinaryStreamWriter writer, TableLayout layout)
{
writer.WriteUInt16((ushort) Attributes);
writer.WriteUInt16(Sequence);
writer.WriteIndex(Name, (IndexSize) layout.Columns[2].Size);
}
/// <summary>
/// Determines whether this row is considered equal to the provided parameter definition row.
/// </summary>
/// <param name="other">The other row.</param>
/// <returns><c>true</c> if the rows are equal, <c>false</c> otherwise.</returns>
public bool Equals(ParameterDefinitionRow other)
{
return Attributes == other.Attributes && Sequence == other.Sequence && Name == other.Name;
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is ParameterDefinitionRow other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = (int) Attributes;
hashCode = (hashCode * 397) ^ Sequence.GetHashCode();
hashCode = (hashCode * 397) ^ (int) Name;
return hashCode;
}
}
/// <inheritdoc />
public override string ToString()
{
return $"({(int) Attributes:X4}, {Sequence:X4}, {Name:X8})";
}
/// <inheritdoc />
public IEnumerator<uint> GetEnumerator()
{
return new MetadataRowColumnEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\Tables\TablesStreamTest.cs | AsmResolver.PE.Tests.DotNet.Metadata.Tables
| TablesStreamTest | [] | ['System.IO', 'System.Linq', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'AsmResolver.PE.File', 'Xunit'] | xUnit | net8.0 | public class TablesStreamTest
{
[Fact]
public void DetectNoExtraData()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
Assert.False(tablesStream.HasExtraData);
}
[Fact]
public void DetectExtraData()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld_TablesStream_ExtraData, TestReaderParameters);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
Assert.True(tablesStream.HasExtraData);
Assert.Equal(12345678u, tablesStream.ExtraData);
}
[Fact]
public void PreserveTableStreamNoChange()
{
var peFile = PEFile.FromBytes(Properties.Resources.HelloWorld);
var peImage = PEImage.FromFile(peFile);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
AssertEquivalentAfterRebuild(tablesStream);
}
[Fact]
public void SmallExternalIndicesShouldHaveSmallIndicesInTablesStream()
{
var pdbMetadata = PE.DotNet.Metadata.MetadataDirectory.FromBytes(Properties.Resources.TheAnswerPortablePdb);
var stream = pdbMetadata.GetStream<TablesStream>();
Assert.Equal(IndexSize.Short, stream.GetIndexEncoder(CodedIndex.HasCustomAttribute).IndexSize);
}
[Fact]
public void LargeExternalIndicesShouldHaveLargeIndicesInTablesStream()
{
var pdbMetadata = PE.DotNet.Metadata.MetadataDirectory.FromBytes(Properties.Resources.LargeIndicesPdb);
var stream = pdbMetadata.GetStream<TablesStream>();
Assert.Equal(IndexSize.Long, stream.GetIndexEncoder(CodedIndex.HasCustomAttribute).IndexSize);
}
[Fact]
public void PreservePdbTableStreamWithSmallExternalIndicesNoChange()
{
var pdbMetadata = PE.DotNet.Metadata.MetadataDirectory.FromBytes(Properties.Resources.TheAnswerPortablePdb);
AssertEquivalentAfterRebuild(pdbMetadata.GetStream<TablesStream>());
}
[Fact]
public void PreservePdbTableStreamWithLargeExternalIndicesNoChange()
{
var pdbMetadata = PE.DotNet.Metadata.MetadataDirectory.FromBytes(Properties.Resources.LargeIndicesPdb);
AssertEquivalentAfterRebuild(pdbMetadata.GetStream<TablesStream>());
}
[Fact]
public void GetImpliedTableRowCountFromNonPdbMetadataShouldGetLocalRowCount()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var stream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
Assert.Equal((uint) stream.GetTable(TableIndex.TypeDef).Count, stream.GetTableRowCount(TableIndex.TypeDef));
}
[Fact]
public void GetImpliedTableRowCountFromPdbMetadataShouldGetExternalRowCount()
{
var pdbMetadata = PE.DotNet.Metadata.MetadataDirectory.FromBytes(Properties.Resources.TheAnswerPortablePdb);
var stream = pdbMetadata.GetStream<TablesStream>();
Assert.Equal(2u, stream.GetTableRowCount(TableIndex.TypeDef));
Assert.Equal(0u ,(uint) stream.GetTable(TableIndex.TypeDef).Count);
}
private static void AssertEquivalentAfterRebuild(TablesStream tablesStream)
{
using var tempStream = new MemoryStream();
tablesStream.Write(new BinaryStreamWriter(tempStream));
var context = new MetadataReaderContext(VirtualAddressFactory.Instance);
var newTablesStream = new SerializedTableStream(context, tablesStream.Name, tempStream.ToArray());
var metadata = new PE.DotNet.Metadata.MetadataDirectory();
if (tablesStream.HasExternalRowCounts)
{
var pdbStream = new PdbStream();
pdbStream.UpdateRowCounts(tablesStream.ExternalRowCounts);
metadata.Streams.Add(pdbStream);
}
newTablesStream.Initialize(metadata);
Assert.Equal(tablesStream.Reserved, newTablesStream.Reserved);
Assert.Equal(tablesStream.MajorVersion, newTablesStream.MajorVersion);
Assert.Equal(tablesStream.MinorVersion, newTablesStream.MinorVersion);
Assert.Equal(tablesStream.Flags, newTablesStream.Flags);
Assert.Equal(tablesStream.Log2LargestRid, newTablesStream.Log2LargestRid);
Assert.Equal(tablesStream.ExtraData, newTablesStream.ExtraData);
Assert.All(Enumerable.Range(0, (int) TableIndex.Max), i =>
{
var tableIndex = (TableIndex) i;
if (!tableIndex.IsValidTableIndex())
return;
var oldTable = tablesStream.GetTable(tableIndex);
var newTable = newTablesStream.GetTable(tableIndex);
Assert.Equal(oldTable.IsSorted, newTable.IsSorted);
Assert.Equal(oldTable.Count, newTable.Count);
Assert.All(Enumerable.Range(0, oldTable.Count), j => Assert.Equal(oldTable[j], newTable[j]));
});
}
} | 252 | 5,710 | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.PE.DotNet.Metadata
{
/// <summary>
/// Represents the metadata stream containing tables defining each member in a .NET assembly.
/// </summary>
public partial class TablesStream : SegmentBase, IMetadataStream
{
/// <summary>
/// The default name of a table stream using the compressed format.
/// </summary>
public const string CompressedStreamName = "#~";
/// <summary>
/// The default name of a table stream using the Edit-and-Continue, uncompressed format.
/// </summary>
public const string EncStreamName = "#-";
/// <summary>
/// The default name of a table stream using the minimal format.
/// </summary>
public const string MinimalStreamName = "#JTD";
/// <summary>
/// The default name of a table stream using the uncompressed format.
/// </summary>
public const string UncompressedStreamName = "#Schema";
private readonly Dictionary<CodedIndex, IndexEncoder> _indexEncoders;
private readonly LazyVariable<TablesStream, IList<IMetadataTable?>> _tables;
private readonly LazyVariable<TablesStream, IList<TableLayout>> _layouts;
/// <summary>
/// Creates a new, empty tables stream.
/// </summary>
public TablesStream()
{
_layouts = new LazyVariable<TablesStream, IList<TableLayout>>(x => x.GetTableLayouts());
_tables = new LazyVariable<TablesStream, IList<IMetadataTable?>>(x => x.GetTables());
_indexEncoders = CreateIndexEncoders();
}
/// <inheritdoc />
public string Name
{
get;
set;
} = CompressedStreamName;
/// <inheritdoc />
public virtual bool CanRead => false;
/// <summary>
/// Reserved, for future use.
/// </summary>
/// <remarks>
/// This field must be set to 0 by the CoreCLR implementation of the runtime.
/// </remarks>
public uint Reserved
{
get;
set;
}
/// <summary>
/// Gets or sets the major version number of the schema.
/// </summary>
public byte MajorVersion
{
get;
set;
} = 2;
/// <summary>
/// Gets or sets the minor version number of the schema.
/// </summary>
public byte MinorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the flags of the tables stream.
/// </summary>
public TablesStreamFlags Flags
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating each string index in the tables stream is a 4 byte integer instead of a
/// 2 byte integer.
/// </summary>
public IndexSize StringIndexSize
{
get => GetStreamIndexSize(0);
set => SetStreamIndexSize(0, value);
}
/// <summary>
/// Gets or sets a value indicating each GUID index in the tables stream is a 4 byte integer instead of a
/// 2 byte integer.
/// </summary>
public IndexSize GuidIndexSize
{
get => GetStreamIndexSize(1);
set => SetStreamIndexSize(1, value);
}
/// <summary>
/// Gets or sets a value indicating each blob index in the tables stream is a 4 byte integer instead of a
/// 2 byte integer.
/// </summary>
public IndexSize BlobIndexSize
{
get => GetStreamIndexSize(2);
set => SetStreamIndexSize(2, value);
}
/// <summary>
/// Gets or sets a value indicating the tables were created with an extra bit in columns.
/// </summary>
public bool HasPaddingBit
{
get => (Flags & TablesStreamFlags.LongBlobIndices) != 0;
set => Flags = (Flags & ~TablesStreamFlags.LongBlobIndices)
| (value ? TablesStreamFlags.LongBlobIndices : 0);
}
/// <summary>
/// Gets or sets a value indicating the tables stream contains only deltas.
/// </summary>
public bool HasDeltaOnly
{
get => (Flags & TablesStreamFlags.DeltaOnly) != 0;
set => Flags = (Flags & ~TablesStreamFlags.DeltaOnly)
| (value ? TablesStreamFlags.DeltaOnly : 0);
}
/// <summary>
/// Gets or sets a value indicating the tables stream persists an extra 4 bytes of data.
/// </summary>
public bool HasExtraData
{
get => (Flags & TablesStreamFlags.ExtraData) != 0;
set => Flags = (Flags & ~TablesStreamFlags.ExtraData)
| (value ? TablesStreamFlags.ExtraData : 0);
}
/// <summary>
/// Gets or sets a value indicating the tables stream may contain _Delete tokens.
/// This only occurs in ENC metadata.
/// </summary>
public bool HasDeletedTokens
{
get => (Flags & TablesStreamFlags.HasDelete) != 0;
set => Flags = (Flags & ~TablesStreamFlags.HasDelete)
| (value ? TablesStreamFlags.HasDelete : 0);
}
/// <summary>
/// Gets the bit-length of the largest relative identifier (RID) in the table stream.
/// </summary>
/// <remarks>
/// This value is ignored by the CoreCLR implementation of the runtime, and the standard compilers always set
/// this value to 1.
/// </remarks>
public byte Log2LargestRid
{
get;
protected set;
} = 1;
/// <summary>
/// Gets or sets the extra 4 bytes data that is persisted after the row counts of the tables stream.
/// </summary>
/// <remarks>
/// This value is not specified by the ECMA-335 and is only present when <see cref="HasExtraData"/> is
/// set to <c>true</c>. Writing to this value does not automatically update <see cref="HasExtraData"/>,
/// and is only persisted in the final output if <see cref="HasExtraData"/> is set to <c>true</c>.
/// </remarks>
public uint ExtraData
{
get;
set;
}
/// <summary>
/// Gets a value indicating whether the tables stream is assigned with row counts that originate from an
/// external .NET metadata file.
/// </summary>
/// <remarks>
/// This value is typically set to <c>false</c>, except for Portable PDB metadata table streams.
/// </remarks>
[MemberNotNullWhen(true, nameof(ExternalRowCounts))]
public bool HasExternalRowCounts => ExternalRowCounts is not null;
/// <summary>
/// Gets or sets an array of row counts originating from an external .NET metadata file that this table stream
/// should consider when encoding indices.
/// </summary>
/// <remarks>
/// This value is typically <c>null</c>, except for Portable PDB metadata table streams.
/// </remarks>
public uint[]? ExternalRowCounts
{
get;
set;
}
/// <summary>
/// Gets or sets a value whether to force large columns in the tables stream.
/// </summary>
/// <remarks>
/// This value is typically <c>false</c>, it is intended to be <c>true</c> for cases when
/// EnC metadata is used and a stream with the <see cref="MinimalStreamName"/> name is present.
/// </remarks>
public bool ForceLargeColumns
{
get;
set;
}
/// <summary>
/// Gets a collection of all tables in the tables stream.
/// </summary>
/// <remarks>
/// This collection always contains all tables, in the same order as <see cref="TableIndex"/> defines, regardless
/// of whether a table actually has elements or not.
/// </remarks>
protected IList<IMetadataTable?> Tables => _tables.GetValue(this);
/// <summary>
/// Gets the layout of all tables in the stream.
/// </summary>
protected IList<TableLayout> TableLayouts => _layouts.GetValue(this);
/// <inheritdoc />
public virtual BinaryStreamReader CreateReader() => throw new NotSupportedException();
/// <summary>
/// Obtains the implied table row count for the provided table index.
/// </summary>
/// <param name="table">The table index.</param>
/// <returns>The row count.</returns>
/// <remarks>
/// This method takes any external row counts from <see cref="ExternalRowCounts"/> into account.
/// </remarks>
public uint GetTableRowCount(TableIndex table)
{
return HasExternalRowCounts && (int) table < ExternalRowCounts.Length
? ExternalRowCounts[(int) table]
: (uint) GetTable(table).Count;
}
/// <summary>
/// Obtains the implied table index size for the provided table index.
/// </summary>
/// <param name="table">The table index.</param>
/// <returns>The index size.</returns>
/// <remarks>
/// This method takes any external row counts from <see cref="ExternalRowCounts"/> into account.
/// </remarks>
public IndexSize GetTableIndexSize(TableIndex table)
{
if (ForceLargeColumns)
return IndexSize.Long;
return GetTableRowCount(table) > 0xFFFF
? IndexSize.Long
: IndexSize.Short;
}
/// <summary>
/// Updates the layouts of each metadata table, according to the <see cref="Flags"/> property.
/// </summary>
/// <remarks>
/// This method should be called after updating any of the index sizes in any of the <see cref="Flags"/>,
/// <see cref="StringIndexSize"/>, <see cref="BlobIndexSize"/> or <see cref="GuidIndexSize"/> properties.
/// </remarks>
protected void SynchronizeTableLayoutsWithFlags()
{
var layouts = GetTableLayouts();
for (int i = 0; i < Tables.Count; i++)
Tables[i]?.UpdateTableLayout(layouts[i]);
}
/// <inheritdoc />
public override uint GetPhysicalSize()
{
SynchronizeTableLayoutsWithFlags();
ulong validBitmask = ComputeValidBitmask();
return (uint) (sizeof(uint)
+ 4 * sizeof(byte)
+ sizeof(ulong)
+ sizeof(ulong)
+ GetTablesCount(validBitmask) * sizeof(uint)
+ (HasExtraData ? sizeof(ulong) : 0)
+ GetTablesSize(validBitmask))
+ sizeof(uint);
}
/// <inheritdoc />
public override void Write(BinaryStreamWriter writer)
{
SynchronizeTableLayoutsWithFlags();
writer.WriteUInt32(Reserved);
writer.WriteByte(MajorVersion);
writer.WriteByte(MinorVersion);
writer.WriteByte((byte) Flags);
writer.WriteByte(Log2LargestRid);
ulong validBitmask = ComputeValidBitmask();
writer.WriteUInt64(validBitmask);
writer.WriteUInt64(ComputeSortedBitmask());
WriteRowCounts(writer, validBitmask);
if (HasExtraData)
writer.WriteUInt32(ExtraData);
WriteTables(writer, validBitmask);
writer.WriteUInt32(0);
}
/// <summary>
/// Computes the valid bitmask of the tables stream, which is a 64-bit integer where each bit specifies whether
/// a table is present in the stream or not.
/// </summary>
/// <returns>The valid bitmask.</returns>
protected virtual ulong ComputeValidBitmask()
{
// TODO: make more configurable (maybe add IMetadataTable.IsPresent property?).
ulong result = 0;
for (int i = 0; i < Tables.Count; i++)
{
if (Tables[i]?.Count > 0)
result |= 1UL << i;
}
return result;
}
/// <summary>
/// Computes the sorted bitmask of the tables stream, which is a 64-bit integer where each bit specifies whether
/// a table is sorted or not.
/// </summary>
/// <returns>The valid bitmask.</returns>
protected virtual ulong ComputeSortedBitmask()
{
ulong result = 0;
bool containsTypeSystemData = false;
bool containsPdbData = false;
// Determine which tables are marked as sorted.
for (int i = 0; i < Tables.Count; i++)
{
if (Tables[i] is not { } table)
continue;
if (table.IsSorted)
result |= 1UL << i;
if (table.Count > 0)
{
if (i <= (int) TableIndex.MaxTypeSystemTableIndex)
containsTypeSystemData = true;
else
containsPdbData = true;
}
}
const ulong typeSystemMask = (1UL << (int) TableIndex.MaxTypeSystemTableIndex + 1) - 1;
const ulong pdbMask = ((1UL << (int) TableIndex.Max) - 1) & ~typeSystemMask;
// Backwards compatibility: Ensure that only the bits are set in the sorted mask if the metadata
// actually contains the type system and/or pdb tables.
if (!containsTypeSystemData)
result &= ~typeSystemMask;
if (!containsPdbData)
result &= ~pdbMask;
return result;
}
/// <summary>
/// Gets a value indicating the total number of tables in the stream.
/// </summary>
/// <param name="validBitmask">The valid bitmask, indicating all present tables in the stream.</param>
/// <returns>The number of tables.</returns>
protected virtual int GetTablesCount(ulong validBitmask)
{
int count = 0;
for (TableIndex i = 0; i < TableIndex.Max; i++)
{
if (HasTable(validBitmask, i))
count++;
}
return count;
}
/// <summary>
/// Computes the total amount of bytes that each table combined needs.
/// </summary>
/// <param name="validBitmask">The valid bitmask, indicating all present tables in the stream.</param>
/// <returns>The total amount of bytes.</returns>
protected virtual uint GetTablesSize(ulong validBitmask)
{
long size = 0;
for (TableIndex i = 0; i < (TableIndex) Tables.Count; i++)
{
if (HasTable(validBitmask, i))
{
var table = GetTable(i);
size += table.Count * table.Layout.RowSize;
}
}
return (uint) size;
}
/// <summary>
/// Writes for each present table the row count to the output stream.
/// </summary>
/// <param name="writer">The output stream to write to.</param>
/// <param name="validBitmask">The valid bitmask, indicating all present tables in the stream.</param>
protected virtual void WriteRowCounts(BinaryStreamWriter writer, ulong validBitmask)
{
for (TableIndex i = 0; i <= TableIndex.Max; i++)
{
if (HasTable(validBitmask, i))
writer.WriteInt32(GetTable(i).Count);
}
}
/// <summary>
/// Writes each present table to the output stream.
/// </summary>
/// <param name="writer">The output stream to write to.</param>
/// <param name="validBitmask">The valid bitmask, indicating all present tables in the stream.</param>
protected virtual void WriteTables(BinaryStreamWriter writer, ulong validBitmask)
{
for (TableIndex i = 0; i < (TableIndex) Tables.Count; i++)
{
if (HasTable(validBitmask, i))
GetTable(i).Write(writer);
}
}
/// <summary>
/// Determines whether a table is present in the tables stream, based on a valid bitmask.
/// </summary>
/// <param name="validMask">The valid bitmask, indicating all present tables in the stream.</param>
/// <param name="table">The table to verify existence of.</param>
/// <returns><c>true</c> if the table is present, <c>false</c> otherwise.</returns>
protected static bool HasTable(ulong validMask, TableIndex table)
{
return ((validMask >> (int) table) & 1) != 0;
}
/// <summary>
/// Determines whether a table is sorted in the tables stream, based on a sorted bitmask.
/// </summary>
/// <param name="sortedMask">The sorted bitmask, indicating all sorted tables in the stream.</param>
/// <param name="table">The table to verify.</param>
/// <returns><c>true</c> if the table is sorted, <c>false</c> otherwise.</returns>
protected static bool IsSorted(ulong sortedMask, TableIndex table)
{
return ((sortedMask >> (int) table) & 1) != 0;
}
/// <summary>
/// Gets a table by its table index.
/// </summary>
/// <param name="index">The table index.</param>
/// <returns>The table.</returns>
public virtual IMetadataTable GetTable(TableIndex index) =>
Tables[(int) index] ?? throw new ArgumentOutOfRangeException(nameof(index));
/// <summary>
/// Gets a table by its row type.
/// </summary>
/// <typeparam name="TRow">The type of rows the table stores.</typeparam>
/// <returns>The table.</returns>
public virtual MetadataTable<TRow> GetTable<TRow>()
where TRow : struct, IMetadataRow
{
return Tables.OfType<MetadataTable<TRow>>().First();
}
/// <summary>
/// Gets a table by its row type.
/// </summary>
/// <typeparam name="TRow">The type of rows the table stores.</typeparam>
/// <param name="index">The table index.</param>
/// <returns>The table.</returns>
public virtual MetadataTable<TRow> GetTable<TRow>(TableIndex index)
where TRow : struct, IMetadataRow
{
return (MetadataTable<TRow>) (Tables[(int) index] ?? throw new ArgumentOutOfRangeException(nameof(index)));
}
private IndexSize GetStreamIndexSize(int bitIndex)
{
if (ForceLargeColumns)
return IndexSize.Long;
return (IndexSize)(((((int)Flags >> bitIndex) & 1) + 1) * 2);
}
private void SetStreamIndexSize(int bitIndex, IndexSize newSize)
{
Flags = (TablesStreamFlags) (((int) Flags & ~(1 << bitIndex))
| (newSize == IndexSize.Long ? 1 << bitIndex : 0));
}
/// <summary>
/// Gets a value indicating the size of a column in a table.
/// </summary>
/// <param name="columnType">The column type to verify.</param>
/// <returns>The column size.</returns>
protected virtual uint GetColumnSize(ColumnType columnType)
{
if (_layouts.IsInitialized)
{
switch (columnType)
{
case <= ColumnType.CustomDebugInformation:
return (uint) GetTableIndexSize((TableIndex) columnType);
case <= ColumnType.HasCustomDebugInformation:
return (uint) GetIndexEncoder((CodedIndex) columnType).IndexSize;
}
}
return columnType switch
{
ColumnType.Blob => (uint) BlobIndexSize,
ColumnType.String => (uint) StringIndexSize,
ColumnType.Guid => (uint) GuidIndexSize,
ColumnType.Byte => sizeof(byte),
ColumnType.UInt16 => sizeof(ushort),
ColumnType.UInt32 => sizeof(uint),
_ => sizeof(uint)
};
}
/// <summary>
/// Gets an encoder/decoder for a particular coded index.
/// </summary>
/// <param name="index">The type of coded index to encode/decode.</param>
/// <returns>The encoder.</returns>
public IndexEncoder GetIndexEncoder(CodedIndex index) => _indexEncoders[index];
/// <summary>
/// Gets the range of metadata tokens referencing fields that a type defines.
/// </summary>
/// <param name="typeDefRid">The row identifier of the type definition to obtain the fields from.</param>
/// <returns>The range of metadata tokens.</returns>
public MetadataRange GetFieldRange(uint typeDefRid) =>
GetMemberRange<TypeDefinitionRow>(TableIndex.TypeDef, typeDefRid, 4,
TableIndex.Field, TableIndex.FieldPtr);
/// <summary>
/// Gets the range of metadata tokens referencing methods that a type defines.
/// </summary>
/// <param name="typeDefRid">The row identifier of the type definition to obtain the methods from.</param>
/// <returns>The range of metadata tokens.</returns>
public MetadataRange GetMethodRange(uint typeDefRid) =>
GetMemberRange<TypeDefinitionRow>(TableIndex.TypeDef, typeDefRid, 5,
TableIndex.Method, TableIndex.MethodPtr);
/// <summary>
/// Gets the range of metadata tokens referencing parameters that a method defines.
/// </summary>
/// <param name="methodDefRid">The row identifier of the method definition to obtain the parameters from.</param>
/// <returns>The range of metadata tokens.</returns>
public MetadataRange GetParameterRange(uint methodDefRid) =>
GetMemberRange<MethodDefinitionRow>(TableIndex.Method, methodDefRid, 5,
TableIndex.Param, TableIndex.ParamPtr);
/// <summary>
/// Gets the range of metadata tokens referencing properties that a property map row defines.
/// </summary>
/// <param name="propertyMapRid">The row identifier of the property map to obtain the properties from.</param>
/// <returns>The range of metadata tokens.</returns>
public MetadataRange GetPropertyRange(uint propertyMapRid) =>
GetMemberRange<PropertyMapRow>(TableIndex.PropertyMap, propertyMapRid, 1,
TableIndex.Property, TableIndex.PropertyPtr);
/// <summary>
/// Gets the range of metadata tokens referencing events that a event map row defines.
/// </summary>
/// <param name="eventMapRid">The row identifier of the event map to obtain the events from.</param>
/// <returns>The range of metadata tokens.</returns>
public MetadataRange GetEventRange(uint eventMapRid) =>
GetMemberRange<EventMapRow>(TableIndex.EventMap, eventMapRid, 1,
TableIndex.Event, TableIndex.EventPtr);
private MetadataRange GetMemberRange<TOwnerRow>(
TableIndex ownerTableIndex,
uint ownerRid,
int ownerColumnIndex,
TableIndex memberTableIndex,
TableIndex redirectTableIndex)
where TOwnerRow : struct, IMetadataRow
{
int index = (int) (ownerRid - 1);
// Check if valid owner RID.
var ownerTable = GetTable<TOwnerRow>(ownerTableIndex);
if (index < 0 || index >= ownerTable.Count)
return MetadataRange.Empty;
// Obtain boundaries.
uint startRid = ownerTable[index][ownerColumnIndex];
uint endRid = index < ownerTable.Count - 1
? ownerTable[index + 1][ownerColumnIndex]
: (uint) GetTable(memberTableIndex).Count + 1;
// Check if redirect table is present.
var redirectTable = GetTable(redirectTableIndex);
if (redirectTable.Count > 0)
return new MetadataRange(redirectTable, memberTableIndex, startRid, endRid);
// If not, its a simple range.
return new MetadataRange(memberTableIndex, startRid, endRid);
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\Tables\TypeDefinitionRowTest.cs | AsmResolver.PE.Tests.DotNet.Metadata.Tables
| TypeDefinitionRowTest | [] | ['AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class TypeDefinitionRowTest
{
[Fact]
public void ReadRow_SmallString_Small_Extends_SmallField_SmallMethod()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
var typeDefTable = tablesStream.GetTable<TypeDefinitionRow>();
Assert.Equal(2, typeDefTable.Count);
Assert.Equal(
new TypeDefinitionRow(0, 0x0001, 0x0000, 0x0000, 0x0001, 0x0001),
typeDefTable[0]);
Assert.Equal(
new TypeDefinitionRow((TypeAttributes) 0x00100001, 0x016F, 0x013, 0x0031, 0x0001, 0x0001),
typeDefTable[^1]);
}
[Fact]
public void WriteRow_SmallString_Small_Extends_SmallField_SmallMethod()
{
RowTestUtils.AssertWriteThenReadIsSame(
new TypeDefinitionRow(0, 0x0001, 0x0000, 0x0000, 0x0001, 0x0001),
TypeDefinitionRow.FromReader);
}
[Fact]
public void RowEnumerationTest()
{
var rawRow = new uint[] { 0, 0x0001, 0x0000, 0x0000, 0x0001, 0x0001 };
var row = new TypeDefinitionRow((TypeAttributes) rawRow[0], rawRow[1], rawRow[2],
rawRow[3], rawRow[4], rawRow[5]);
RowTestUtils.VerifyRowColumnEnumeration(rawRow, row);
}
} | 163 | 1,656 | using System;
using System.Collections;
using System.Collections.Generic;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata.Tables
{
/// <summary>
/// Represents a single row in the type definition metadata table.
/// </summary>
public struct TypeDefinitionRow : IMetadataRow
{
/// <summary>
/// Reads a single type definition row from an input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <param name="layout">The layout of the type definition table.</param>
/// <returns>The row.</returns>
public static TypeDefinitionRow FromReader(ref BinaryStreamReader reader, TableLayout layout)
{
return new TypeDefinitionRow(
(TypeAttributes) reader.ReadUInt32(),
reader.ReadIndex((IndexSize) layout.Columns[1].Size),
reader.ReadIndex((IndexSize) layout.Columns[2].Size),
reader.ReadIndex((IndexSize) layout.Columns[3].Size),
reader.ReadIndex((IndexSize) layout.Columns[4].Size),
reader.ReadIndex((IndexSize) layout.Columns[5].Size));
}
/// <summary>
/// Creates a new row for the type definition metadata table.
/// </summary>
/// <param name="attributes">The attributes associated to the type.</param>
/// <param name="name">The index into the #Strings heap containing the name of the type reference.</param>
/// <param name="ns">The index into the #Strings heap containing the namespace of the type reference.</param>
/// <param name="extends">The TypeDefOrRef coded index representing the base type of this type.</param>
/// <param name="fieldList">The index into the Field (or FieldPtr) table, representing the first field defined
/// in the type. </param>
/// <param name="methodList">The index into the Method (or MethodPtr) table, representing the first method defined
/// in the type. </param>
public TypeDefinitionRow(TypeAttributes attributes, uint name, uint ns, uint extends, uint fieldList, uint methodList)
{
Attributes = attributes;
Name = name;
Namespace = ns;
Extends = extends;
FieldList = fieldList;
MethodList = methodList;
}
/// <inheritdoc />
public TableIndex TableIndex => TableIndex.TypeDef;
/// <inheritdoc />
public int Count => 6;
/// <inheritdoc />
public uint this[int index] => index switch
{
0 => (uint) Attributes,
1 => Name,
2 => Namespace,
3 => Extends,
4 => FieldList,
5 => MethodList,
_ => throw new IndexOutOfRangeException()
};
/// <summary>
/// Gets or sets the attributes associated to the type.
/// </summary>
public TypeAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings heap containing the name of the type reference.
/// </summary>
/// <remarks>
/// This value should always index a non-empty string.
/// </remarks>
public uint Name
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings heap containing the namespace of the type reference.
/// </summary>
/// <remarks>
/// This value can be zero. If it is not, it should always index a non-empty string.
/// </remarks>
public uint Namespace
{
get;
set;
}
/// <summary>
/// Gets a TypeDefOrRef coded index (an index to a row in either the TypeRef, TypeDef or TypeSpec table)
/// representing the base type of this type.
/// </summary>
public uint Extends
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the Field (or FieldPtr) table, representing the first field defined in the type.
/// </summary>
public uint FieldList
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the Method (or MethodPtr) table, representing the first method defined in the type.
/// </summary>
public uint MethodList
{
get;
set;
}
/// <inheritdoc />
public void Write(BinaryStreamWriter writer, TableLayout layout)
{
writer.WriteUInt32((uint) Attributes);
writer.WriteIndex(Name, (IndexSize) layout.Columns[1].Size);
writer.WriteIndex(Namespace, (IndexSize) layout.Columns[2].Size);
writer.WriteIndex(Extends, (IndexSize) layout.Columns[3].Size);
writer.WriteIndex(FieldList, (IndexSize) layout.Columns[4].Size);
writer.WriteIndex(MethodList, (IndexSize) layout.Columns[5].Size);
}
/// <inheritdoc />
public override string ToString()
{
return $"({(uint) Attributes:X8}, {Name:X8}, {Namespace:X8}, {Extends:X8}, {FieldList:X8}, {MethodList:X8})";
}
/// <summary>
/// Determines whether this row is considered equal to the provided type definition row.
/// </summary>
/// <param name="other">The other row.</param>
/// <returns><c>true</c> if the rows are equal, <c>false</c> otherwise.</returns>
public bool Equals(TypeDefinitionRow other)
{
return Attributes == other.Attributes
&& Name == other.Name
&& Namespace == other.Namespace
&& Extends == other.Extends
&& FieldList == other.FieldList
&& MethodList == other.MethodList;
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is TypeDefinitionRow other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = (int) Attributes;
hashCode = (hashCode * 397) ^ (int) Name;
hashCode = (hashCode * 397) ^ (int) Namespace;
hashCode = (hashCode * 397) ^ (int) Extends;
hashCode = (hashCode * 397) ^ (int) FieldList;
hashCode = (hashCode * 397) ^ (int) MethodList;
return hashCode;
}
}
/// <inheritdoc />
public IEnumerator<uint> GetEnumerator()
{
return new MetadataRowColumnEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\Tables\TypeReferenceRowTest.cs | AsmResolver.PE.Tests.DotNet.Metadata.Tables
| TypeReferenceRowTest | [] | ['AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class TypeReferenceRowTest
{
[Fact]
public void ReadRow_SmallResolutionScope_SmallStrings()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var tablesStream = peImage.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
var typeRefTable = tablesStream.GetTable<TypeReferenceRow>();
Assert.Equal(13, typeRefTable.Count);
Assert.Equal(
new TypeReferenceRow(0x0006, 0x00D6, 0x01AE),
typeRefTable[0]);
Assert.Equal(
new TypeReferenceRow(0x0006, 0x001E, 0x0177),
typeRefTable[^1]);
}
[Fact]
public void WriteRow_SmallResolutionScope_SmallStrings()
{
RowTestUtils.AssertWriteThenReadIsSame(
new TypeReferenceRow(0x0006, 0x00D6, 0x01AE),
TypeReferenceRow.FromReader);
}
[Fact]
public void RowEnumerationTest()
{
var rawRow = new uint[] { 0x0006, 0x00D6, 0x01AE };
var row = new TypeReferenceRow(rawRow[0], rawRow[1], rawRow[2]);
RowTestUtils.VerifyRowColumnEnumeration(rawRow, row);
}
} | 163 | 1,452 | using System;
using System.Collections;
using System.Collections.Generic;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata.Tables
{
/// <summary>
/// Represents a single row in the type reference metadata table.
/// </summary>
public struct TypeReferenceRow : IMetadataRow
{
/// <summary>
/// Reads a single type reference row from an input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <param name="layout">The layout of the type reference table.</param>
/// <returns>The row.</returns>
public static TypeReferenceRow FromReader(ref BinaryStreamReader reader, TableLayout layout)
{
return new TypeReferenceRow(
reader.ReadIndex((IndexSize) layout.Columns[0].Size),
reader.ReadIndex((IndexSize) layout.Columns[1].Size),
reader.ReadIndex((IndexSize) layout.Columns[2].Size));
}
/// <summary>
/// Creates a new row for the type reference metadata table.
/// </summary>
/// <param name="resolutionScope">The ResolutionScope coded index containing the scope that can resolve this
/// type reference. </param>
/// <param name="name">The index into the #Strings heap containing the name of the type reference.</param>
/// <param name="ns">The index into the #Strings heap containing the namespace of the type reference.</param>
public TypeReferenceRow(uint resolutionScope, uint name, uint ns)
{
ResolutionScope = resolutionScope;
Name = name;
Namespace = ns;
}
/// <inheritdoc />
public TableIndex TableIndex => TableIndex.TypeRef;
/// <inheritdoc />
public int Count => 3;
/// <inheritdoc />
public uint this[int index] => index switch
{
0 => ResolutionScope,
1 => Name,
2 => Namespace,
_ => throw new IndexOutOfRangeException()
};
/// <summary>
/// Gets a ResolutionScope coded index (an index to a row in either the Module, ModuleRef, AssemblyRef or TypeRef table)
/// containing the scope that can resolve this type reference.
/// </summary>
public uint ResolutionScope
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings heap containing the name of the type reference.
/// </summary>
/// <remarks>
/// This value should always index a non-empty string.
/// </remarks>
public uint Name
{
get;
set;
}
/// <summary>
/// Gets or sets an index into the #Strings heap containing the namespace of the type reference.
/// </summary>
/// <remarks>
/// This value can be zero. If it is not, it should always index a non-empty string.
/// </remarks>
public uint Namespace
{
get;
set;
}
/// <inheritdoc />
public void Write(BinaryStreamWriter writer, TableLayout layout)
{
writer.WriteIndex(ResolutionScope, (IndexSize) layout.Columns[0].Size);
writer.WriteIndex(Name, (IndexSize) layout.Columns[1].Size);
writer.WriteIndex(Namespace, (IndexSize) layout.Columns[2].Size);
}
/// <inheritdoc />
public override string ToString()
{
return $"({ResolutionScope:X8}, {Name:X8}, {Namespace:X8})";
}
/// <summary>
/// Determines whether this row is considered equal to the provided type reference row.
/// </summary>
/// <param name="other">The other row.</param>
/// <returns><c>true</c> if the rows are equal, <c>false</c> otherwise.</returns>
public bool Equals(TypeReferenceRow other)
{
return ResolutionScope == other.ResolutionScope
&& Name == other.Name
&& Namespace == other.Namespace;
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is TypeReferenceRow other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hashCode = (int) ResolutionScope;
hashCode = (hashCode * 397) ^ (int) Name;
hashCode = (hashCode * 397) ^ (int) Namespace;
return hashCode;
}
}
/// <inheritdoc />
public IEnumerator<uint> GetEnumerator()
{
return new MetadataRowColumnEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\TypeReferenceHashTest.cs | AsmResolver.PE.Tests.DotNet.Metadata
| TypeReferenceHashTest | [] | ['AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class TypeReferenceHashTest
{
[Fact]
public void HelloWorldTypeRefHash()
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
byte[] hash = image.GetTypeReferenceHash();
Assert.Equal(new byte[]
{
0xa4, 0xb5, 0xdb, 0x27, 0x28, 0x6e, 0xc3, 0x6c, 0xb2, 0xd2, 0xcc, 0x9b, 0xbe, 0x60, 0x6c, 0xe7, 0xe4,
0x7b, 0x61, 0x95, 0x22, 0x5c, 0xb4, 0x72, 0x81, 0xc7, 0xb9, 0xc3, 0xdb, 0xdd, 0x16, 0xca
}, hash);
}
[Fact]
public void TheAnswerTypeRefHash()
{
var image = PEImage.FromBytes(Properties.Resources.TheAnswer_NetCore, TestReaderParameters);
byte[] hash = image.GetTypeReferenceHash();
Assert.Equal(new byte[]
{
0xe0, 0xb6, 0x02, 0xb7, 0x71, 0x1c, 0xc3, 0x49, 0x77, 0x72, 0x6d, 0xf0, 0x97, 0x5f, 0xf1, 0xf2, 0xeb,
0x47, 0xbe, 0x77, 0xec, 0x73, 0x50, 0x4b, 0x29, 0xe3, 0xa8, 0x1e, 0x3d, 0x96, 0x33, 0x10,
}, hash);
}
} | 117 | 1,256 | using System;
using System.Linq;
using System.Security.Cryptography;
namespace AsmResolver.PE.DotNet.Metadata.Tables
{
/// <summary>
/// Provides an implementation for the Type Reference Hash (TRH) as introduced by GData.
/// This hash is used as an alternative to the ImpHash to identify malware families based on
/// the type references imported by the .NET image.
///
/// Reference:
/// https://www.gdatasoftware.com/blog/2020/06/36164-introducing-the-typerefhash-trh
/// </summary>
public static class TypeReferenceHash
{
/// <summary>
/// If the provided image is a .NET image, computes the Type Reference Hash (TRH) as introduced by GData to
/// identify malware based on its imported type references.
/// </summary>
/// <param name="image">The image to get the TRH from.</param>
/// <returns>The hash.</returns>
/// <exception cref="ArgumentException">Occurs when the provided image does not contain .NET metadata.</exception>
public static byte[] GetTypeReferenceHash(this PEImage image)
{
var metadata = image.DotNetDirectory?.Metadata;
if (metadata is null)
throw new ArgumentException("Portable executable does not contain a .NET image.");
return metadata.GetTypeReferenceHash();
}
/// <summary>
/// Computes the Type Reference Hash (TRH) as introduced by GData to identify malware based on its
/// imported type references.
/// </summary>
/// <param name="metadata">The metadata directory to get the TRH from.</param>
/// <returns>The hash.</returns>
/// <exception cref="ArgumentException">Occurs when the provided image does not contain .NET metadata.</exception>
public static byte[] GetTypeReferenceHash(this MetadataDirectory metadata)
{
var tablesStream = metadata.GetStream<TablesStream>();
var stringsStream = metadata.GetStream<StringsStream>();
var table = tablesStream.GetTable<TypeReferenceRow>(TableIndex.TypeRef);
string[] elements = table
.OrderBy(row => stringsStream.GetStringByIndex(row.Namespace))
.ThenBy(row => stringsStream.GetStringByIndex(row.Name))
.Select(row =>
$"{stringsStream.GetStringByIndex(row.Namespace)}-{stringsStream.GetStringByIndex(row.Name)}")
.ToArray();
string fullString = string.Join(",", elements);
using var sha256 = SHA256.Create();
return sha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(fullString));
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Metadata\UserStringsStreamTest.cs | AsmResolver.PE.Tests.DotNet.Metadata
| UserStringsStreamTest | [] | ['AsmResolver.PE.DotNet.Metadata', 'Xunit'] | xUnit | net8.0 | public class UserStringsStreamTest
{
private static void AssertDoesNotHaveString(byte[] streamData, string needle)
{
var stream = new SerializedUserStringsStream(streamData);
Assert.False(stream.TryFindStringIndex(needle, out _));
}
private static void AssertHasString(byte[] streamData, string needle)
{
var stream = new SerializedUserStringsStream(streamData);
Assert.True(stream.TryFindStringIndex(needle, out uint actualIndex));
Assert.Equal(needle, stream.GetStringByIndex(actualIndex));
}
[Theory]
[InlineData("")]
[InlineData("ABC")]
[InlineData("DEF")]
public void FindExistingString(string value) => AssertHasString(new byte[]
{
0x00,
0x07, 0x41, 0x00, 0x42, 0x00, 0x43, 0x00, 0x00,
0x07, 0x44, 0x00, 0x45, 0x00, 0x46, 0x00, 0x00,
},
value);
[Theory]
[InlineData("BC")]
[InlineData("F")]
public void FindOverlappingExistingString(string value) => AssertHasString(new byte[]
{
0x00,
0x07, 0x41, 0x05, 0x42, 0x00, 0x43, 0x00, 0x00,
0x07, 0x44, 0x00, 0x45, 0x03, 0x46, 0x00, 0x00,
},
value);
[Theory]
[InlineData("ABC")]
[InlineData("DEF")]
public void FindExistingStringButNotZeroTerminated(string value) => AssertDoesNotHaveString(new byte[]
{
0x00,
0x07, 0x41, 0x00, 0x42, 0x00, 0x43, 0x00, 0xff,
0x07, 0x44, 0x00, 0x45, 0x00, 0x46, 0x00, 0xff,
},
value);
[Fact]
public void FindExistingIncompleteString() => AssertDoesNotHaveString(new byte[]
{
0x00,
0x07, 0x41, 0x00, 0x42, 0x00,
},
"ABC");
[Theory]
[InlineData("CDE")]
[InlineData("XXX")]
public void FindNonExistingString(string value) => AssertDoesNotHaveString(new byte[]
{
0x00,
0x07, 0x41, 0x00, 0x42, 0x00, 0x43, 0x00, 0xff,
0x07, 0x44, 0x00, 0x45, 0x00, 0x46, 0x00, 0xff,
},
value);
} | 110 | 2,508 | using System.Collections.Concurrent;
using System.Text;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Metadata
{
/// <summary>
/// Provides an implementation of a user-strings stream that obtains strings from a readable segment in a file.
/// </summary>
public class SerializedUserStringsStream : UserStringsStream
{
private readonly ConcurrentDictionary<uint, string?> _cachedStrings = new();
private readonly BinaryStreamReader _reader;
/// <summary>
/// Creates a new user-strings stream with the provided byte array as the raw contents of the stream.
/// </summary>
/// <param name="rawData">The raw contents of the stream.</param>
public SerializedUserStringsStream(byte[] rawData)
: this(DefaultName, new BinaryStreamReader(rawData))
{
}
/// <summary>
/// Creates a new user-strings stream with the provided byte array as the raw contents of the stream.
/// </summary>
/// <param name="name">The name of the stream.</param>
/// <param name="rawData">The raw contents of the stream.</param>
public SerializedUserStringsStream(string name, byte[] rawData)
: this(name, new BinaryStreamReader(rawData))
{
}
/// <summary>
/// Creates a new user-strings stream with the provided file segment reader as the raw contents of the stream.
/// </summary>
/// <param name="name">The name of the stream.</param>
/// <param name="reader">The raw contents of the stream.</param>
public SerializedUserStringsStream(string name, BinaryStreamReader reader)
: base(name)
{
_reader = reader;
Offset = reader.Offset;
Rva = reader.Rva;
}
/// <inheritdoc />
public override bool CanRead => true;
/// <inheritdoc />
public override BinaryStreamReader CreateReader() => _reader.Fork();
/// <inheritdoc />
public override uint GetPhysicalSize() => _reader.Length;
/// <inheritdoc />
public override void Write(BinaryStreamWriter writer) => _reader.Fork().WriteToOutput(writer);
/// <inheritdoc />
public override string? GetStringByIndex(uint index)
{
index &= 0x00FFFFFF;
if (!_cachedStrings.TryGetValue(index, out string? value) && index < _reader.Length)
{
var stringsReader = _reader.ForkRelative(index);
// Try read length.
if (stringsReader.TryReadCompressedUInt32(out uint length))
{
if (length == 0)
return string.Empty;
// Read unicode bytes.
byte[] data = new byte[length];
int actualLength = stringsReader.ReadBytes(data, 0, (int) length);
// Exclude the terminator byte.
value = Encoding.Unicode.GetString(data, 0, actualLength - 1);
}
_cachedStrings.TryAdd(index, value);
}
return value;
}
/// <inheritdoc />
public override bool TryFindStringIndex(string value, out uint index)
{
if (value == string.Empty)
{
index = 0;
return true;
}
uint byteCount = (uint) (value.Length * sizeof(ushort)) + sizeof(byte);
uint totalLength = byteCount.GetCompressedSize() + byteCount;
var reader = _reader.Fork();
while (reader.CanRead(totalLength))
{
index = reader.RelativeOffset;
if (reader.TryReadCompressedUInt32(out uint length) && length == byteCount && reader.CanRead(length))
{
int i = 0;
for (; i < value.Length; i++)
{
if (value[i] != reader.ReadUInt16())
break;
}
if (i == value.Length && reader.CanRead(sizeof(byte)) && reader.ReadByte() is 0x00 or 0x01)
return true;
}
reader.RelativeOffset = index + 1;
}
index = 0;
return false;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\ReadyToRun\MethodEntryPointTest.cs | AsmResolver.PE.Tests.DotNet.ReadyToRun
| MethodEntryPointTest | [] | ['AsmResolver.IO', 'AsmResolver.PE.DotNet.ReadyToRun', 'Xunit'] | xUnit | net8.0 | public class MethodEntryPointTest
{
[Fact]
public void NoFixups()
{
var entryPoint = new MethodEntryPoint(1337);
entryPoint.UpdateOffsets(new RelocationParameters(0, 0));
var reader = new BinaryStreamReader(entryPoint.WriteIntoArray());
var newEntryPoint = MethodEntryPoint.FromReader(ref reader);
Assert.Equal(1337u, newEntryPoint.RuntimeFunctionIndex);
Assert.Empty(newEntryPoint.Fixups);
}
[Theory]
[InlineData(0, 0)]
[InlineData(1337, 0)]
[InlineData(0, 1337)]
[InlineData(1337, 1338)]
public void SingleFixup(uint importIndex, uint slotIndex)
{
var entryPoint = new MethodEntryPoint(1234);
entryPoint.Fixups.Add(new MethodFixup(importIndex, slotIndex));
entryPoint.UpdateOffsets(new RelocationParameters(0, 0));
var reader = new BinaryStreamReader(entryPoint.WriteIntoArray());
var newEntryPoint = MethodEntryPoint.FromReader(ref reader);
Assert.Equal(1234u, newEntryPoint.RuntimeFunctionIndex);
Assert.Equal(entryPoint.Fixups, newEntryPoint.Fixups);
}
[Fact]
public void MultipleFixups()
{
var entryPoint = new MethodEntryPoint(1234);
entryPoint.Fixups.Add(new MethodFixup(1337, 1));
entryPoint.Fixups.Add(new MethodFixup(1337, 2));
entryPoint.Fixups.Add(new MethodFixup(1337, 3));
entryPoint.Fixups.Add(new MethodFixup(1339, 11));
entryPoint.Fixups.Add(new MethodFixup(1339, 12));
entryPoint.Fixups.Add(new MethodFixup(1339, 13));
entryPoint.UpdateOffsets(new RelocationParameters(0, 0));
var reader = new BinaryStreamReader(entryPoint.WriteIntoArray());
var newEntryPoint = MethodEntryPoint.FromReader(ref reader);
Assert.Equal(1234u, newEntryPoint.RuntimeFunctionIndex);
Assert.Equal(entryPoint.Fixups, newEntryPoint.Fixups);
}
} | 137 | 2,270 | using System.Collections.Generic;
using System.IO;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.ReadyToRun
{
/// <summary>
/// Provides information about a native entry point for a managed method that was compiled ahead-of-time.
/// </summary>
public class MethodEntryPoint : SegmentBase
{
private byte[]? _serialized;
/// <summary>
/// Constructs a new entry point for a method.
/// </summary>
/// <param name="functionIndex">The index of the <c>RUNTIME_FUNCTION</c> this method starts at.</param>
public MethodEntryPoint(uint functionIndex)
{
RuntimeFunctionIndex = functionIndex;
}
/// <summary>
/// Gets or sets the index to the <c>RUNTIME_FUNCTION</c> the method starts at.
/// </summary>
public uint RuntimeFunctionIndex
{
get;
set;
}
/// <summary>
/// Gets a collection of fixups that need to be applied before the method can be executed natively.
/// </summary>
public IList<MethodFixup> Fixups
{
get;
} = new List<MethodFixup>();
/// <summary>
/// Reads a single method entry point metadata segment from the provided input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <returns>The read entry point metadata</returns>
public static MethodEntryPoint FromReader(ref BinaryStreamReader reader)
{
ulong offset = reader.Offset;
uint rva = reader.Rva;
uint header = NativeFormat.DecodeUnsigned(ref reader);
bool hasFixups = (header & 1) != 0;
MethodEntryPoint result;
if (!hasFixups)
{
result = new MethodEntryPoint(header >> 1);
}
else
{
result = new MethodEntryPoint(header >> 2);
ReadFixups(result, reader);
}
result.Offset = offset;
result.Rva = rva;
return result;
}
private static void ReadFixups(MethodEntryPoint entryPoint, BinaryStreamReader reader)
{
var nibbleReader = new NibbleReader(reader);
uint importIndex = nibbleReader.Read3BitEncodedUInt();
while (true)
{
uint slotIndex = nibbleReader.Read3BitEncodedUInt();
while (true)
{
entryPoint.Fixups.Add(new MethodFixup(importIndex, slotIndex));
uint slotDelta = nibbleReader.Read3BitEncodedUInt();
if (slotDelta == 0)
break;
slotIndex += slotDelta;
}
uint importDelta = nibbleReader.Read3BitEncodedUInt();
if (importDelta == 0)
break;
importIndex += importDelta;
}
}
private uint GetHeader() => Fixups.Count > 0
? RuntimeFunctionIndex << 2 | 1
: RuntimeFunctionIndex << 1;
/// <inheritdoc />
public override void UpdateOffsets(in RelocationParameters parameters)
{
base.UpdateOffsets(in parameters);
_serialized = Serialize();
}
/// <inheritdoc />
public override uint GetPhysicalSize()
{
_serialized ??= Serialize();
return (uint) _serialized.Length;
}
/// <inheritdoc />
public override void Write(BinaryStreamWriter writer)
{
_serialized ??= Serialize();
writer.WriteBytes(_serialized);
}
private byte[] Serialize()
{
using var stream = new MemoryStream();
var writer = new BinaryStreamWriter(stream);
// Write header.
NativeFormat.EncodeUnsigned(writer, GetHeader());
if (Fixups.Count == 0)
return stream.ToArray();
var nibbleWriter = new NibbleWriter(writer);
// Write fixups.
uint lastImportIndex = 0;
uint lastSlotIndex = 0;
for (int i = 0; i < Fixups.Count; i++)
{
var fixup = Fixups[i];
uint importDelta = fixup.ImportIndex - lastImportIndex;
if (importDelta != 0 || i == 0)
{
// We're entering a new chunk of fixups with a different import index.
// Close of previous import chunk with a 0 slot delta.
if (i > 0)
nibbleWriter.Write3BitEncodedUInt(0);
// Start new import chunk.
nibbleWriter.Write3BitEncodedUInt(importDelta);
lastSlotIndex = 0;
}
// Write current slot.
uint slotDelta = fixup.SlotIndex - lastSlotIndex;
nibbleWriter.Write3BitEncodedUInt(slotDelta);
lastImportIndex = fixup.ImportIndex;
lastSlotIndex = fixup.SlotIndex;
}
// Close off last slot list.
nibbleWriter.Write3BitEncodedUInt(0);
// Close off last import list.
nibbleWriter.Write3BitEncodedUInt(0);
nibbleWriter.Flush();
return stream.ToArray();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\ReadyToRun\NativeArrayTest.cs | AsmResolver.PE.Tests.DotNet.ReadyToRun | NativeArrayTest | ['public readonly int Value;'] | ['System.Diagnostics', 'System.Linq', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.ReadyToRun', 'Xunit'] | xUnit | net8.0 | public class NativeArrayTest
{
[DebuggerDisplay("{Value}")]
private readonly struct IntValue : IWritable
{
public readonly int Value;
public IntValue(int value) => Value = value;
public uint GetPhysicalSize() => sizeof(uint);
public void Write(BinaryStreamWriter writer) => writer.WriteInt32(Value);
public static implicit operator IntValue(int value) => new(value);
public static implicit operator int(IntValue value) => value.Value;
}
[Theory]
[InlineData(new[] {1337})]
[InlineData(new[] {1337, 1338})]
[InlineData(new[] {1337, 1338, 1339})]
[InlineData(new[] {1337, 1338, 1339, 1340})]
[InlineData(new[] {1337, 1338, 1339, 1340, 1341})]
[InlineData(new[] {
1337, 1338, 1339, 1340,
1341, 1342, 1343, 1344,
1345, 1346, 1347, 1348,
1349, 1350, 1351, 1352,
1353, 1354 // count > 16 -> extra root.
})]
public void AddElements(int[] elements)
{
var array = new NativeArray<IntValue>();
for (int i = 0; i < elements.Length; i++)
array.Add(elements[i]);
array.UpdateOffsets(new RelocationParameters(0, 0));
byte[] raw = array.WriteIntoArray();
var view = NativeArray<IntValue>.FromReader(new BinaryStreamReader(raw), reader => reader.ReadInt32());
Assert.All(Enumerable.Range(0, elements.Length), i => Assert.Equal(elements[i], view[i].Value));
}
} | 180 | 1,675 | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.ReadyToRun
{
/// <summary>
/// Represents a sparse list of elements stored in the native file format as specified by the ReadyToRun file format.
/// </summary>
/// <typeparam name="T">The type of elements to store in the array.</typeparam>
public class NativeArray<T> : Collection<T?>, ISegment
where T : IWritable
{
private readonly List<Node> _roots = new();
private uint _entryIndexSize = 2;
private uint _totalSize;
/// <inheritdoc />
public bool CanUpdateOffsets => true;
/// <inheritdoc />
public ulong Offset
{
get;
private set;
}
/// <inheritdoc />
public uint Rva
{
get;
private set;
}
private uint Header => (uint) (Items.Count << 2) | _entryIndexSize;
/// <summary>
/// Reads a sparse array in the native file format from the provided input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <param name="readElement">The function to use for reading individual elements.</param>
/// <returns>The read array.</returns>
public static NativeArray<T> FromReader(BinaryStreamReader reader, Func<BinaryStreamReader, T> readElement)
{
var result = new NativeArray<T>();
uint header = NativeFormat.DecodeUnsigned(ref reader);
int count = (int) (header >> 2);
result._entryIndexSize = (byte) (header & 3);
reader = reader.ForkAbsolute(reader.Offset);
for (int i = 0; i < count; i++)
{
result.Add(NativeFormat.TryGetArrayElement(reader, result._entryIndexSize, i, out var elementReader)
? readElement(elementReader)
: default);
}
return result;
}
private void RebuildTree()
{
_roots.Clear();
for (int i = 0; i < Items.Count; i++)
{
var item = Items[i];
if (item is not null)
InsertNode(i, item);
}
// TODO: optimize for entry size.
_entryIndexSize = 2;
}
private void UpdateTreeOffsets(in RelocationParameters parameters)
{
Offset = parameters.Offset;
Rva = parameters.Rva;
var current = parameters;
current.Advance(NativeFormat.GetEncodedUnsignedSize(Header));
current.Advance((uint) _roots.Count * (1u << (int) _entryIndexSize));
foreach (var root in _roots)
{
root.UpdateOffsets(current);
current.Advance(root.GetPhysicalSize());
}
_totalSize = (uint) (current.Offset - parameters.Offset);
}
private void InsertNode(int index, T? value)
{
int rootIndex = index / NativeFormat.ArrayBlockSize;
while (rootIndex >= _roots.Count)
_roots.Add(new Node(NativeFormat.ArrayBlockSize >> 1));
// TODO: truncate trees.
var current = _roots[rootIndex];
uint bit = NativeFormat.ArrayBlockSize >> 1;
while (bit > 0)
{
if ((index & bit) != 0)
{
current.Right ??= new Node(current.Depth >> 1);
current = current.Right;
}
else
{
current.Left ??= new Node(current.Depth >> 1);
current = current.Left;
}
bit >>= 1;
}
current.Index = (uint) index;
current.Value = value;
}
/// <inheritdoc />
public void UpdateOffsets(in RelocationParameters parameters)
{
RebuildTree();
UpdateTreeOffsets(parameters);
}
/// <inheritdoc />
public uint GetPhysicalSize() => _totalSize;
/// <inheritdoc />
public uint GetVirtualSize() => GetPhysicalSize();
/// <inheritdoc />
public void Write(BinaryStreamWriter writer)
{
uint header = Header;
uint headerSize = NativeFormat.GetEncodedUnsignedSize(header);
NativeFormat.EncodeUnsigned(writer, header);
foreach (var root in _roots)
WriteRootNodeHeader(writer, root, headerSize);
foreach (var root in _roots)
root.Write(writer);
}
private void WriteRootNodeHeader(BinaryStreamWriter writer, Node root, uint headerSize)
{
uint offset = (uint) (root.Offset - headerSize - Offset);
switch (_entryIndexSize)
{
case 0:
writer.WriteByte((byte) offset);
break;
case 1:
writer.WriteUInt16((ushort) offset);
break;
case 2:
writer.WriteUInt32(offset);
break;
default:
throw new ArgumentOutOfRangeException(nameof(_entryIndexSize));
}
}
private sealed class Node : SegmentBase
{
public uint Index;
public T? Value;
public Node? Left;
public Node? Right;
public readonly int Depth;
private uint _size;
public Node(int depth, uint index = 0, T? value = default)
{
Depth = depth;
Index = index;
Value = value;
}
public uint Header
{
get
{
uint tag = 0;
if (Left is not null)
tag |= 0b01;
if (Right is not null)
tag |= 0b10;
uint value;
if (Right is not null)
value = (uint) (Right.Offset - Offset);
else if (Left is not null)
value = 0;
else
value = Index;
return tag | (value << 2);
}
}
[MemberNotNullWhen(true, nameof(Value))]
public bool IsLeaf => Left is null && Right is null;
public override void UpdateOffsets(in RelocationParameters parameters)
{
base.UpdateOffsets(in parameters);
var current = parameters;
if (Depth > 0)
{
// TODO: optimize header for size.
// current.Advance(NativeArrayView.GetEncodedUnsignedSize(Header));
current.Advance(5);
}
if (IsLeaf)
{
if (Value is ISegment segment)
segment.UpdateOffsets(current);
current.Advance(Value.GetPhysicalSize());
}
else
{
if (Left is not null)
{
Left.UpdateOffsets(current);
current.Advance(Left.GetPhysicalSize());
}
if (Right is not null)
{
Right.UpdateOffsets(current);
current.Advance(Right.GetPhysicalSize());
}
}
_size = (uint) (current.Offset - parameters.Offset);
}
public override uint GetPhysicalSize() => _size;
public override void Write(BinaryStreamWriter writer)
{
System.Diagnostics.Debug.Assert(writer.Offset == Offset);
if (Depth > 0)
{
// TODO: optimize header for size.
// NativeArrayView.EncodeUnsigned(writer, Header);
writer.WriteByte(0b00001111);
writer.WriteUInt32(Header);
}
if (IsLeaf)
{
Value.Write(writer);
}
else
{
Left?.Write(writer);
Right?.Write(writer);
}
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\ReadyToRun\ReadyToRunDirectoryTest.cs | AsmResolver.PE.Tests.DotNet.ReadyToRun
| ReadyToRunDirectoryTest | [] | ['System.Collections.Generic', 'System.Linq', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.ReadyToRun', 'Xunit'] | xUnit | net8.0 | public class ReadyToRunDirectoryTest
{
private static T GetSection<T>(PEImage image, bool rebuild)
where T : class, IReadyToRunSection
{
var serializedImage = (SerializedPEImage) image;
var directory = Assert.IsAssignableFrom<ReadyToRunDirectory>(image.DotNetDirectory!.ManagedNativeHeader);
var section = directory.GetSection<T>();
if (rebuild)
{
section.UpdateOffsets(new RelocationParameters(0, 0));
var reader = new BinaryStreamReader(section.WriteIntoArray());
var context = serializedImage.ReaderContext;
section = (T) context.Parameters.ReadyToRunSectionReader.ReadSection(context, section.Type, ref reader);
}
return section;
}
[Fact]
public void ReadBasicHeader()
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld_ReadyToRun, TestReaderParameters);
var header = Assert.IsAssignableFrom<ReadyToRunDirectory>(image.DotNetDirectory!.ManagedNativeHeader);
Assert.Equal(5, header.MajorVersion);
Assert.Equal(4, header.MinorVersion);
Assert.Equal(ReadyToRunAttributes.NonSharedPInvokeStubs, header.Attributes);
}
[Fact]
public void ReadSections()
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld_ReadyToRun, TestReaderParameters);
var header = Assert.IsAssignableFrom<ReadyToRunDirectory>(image.DotNetDirectory!.ManagedNativeHeader);
Assert.Equal(new[]
{
ReadyToRunSectionType.CompilerIdentifier,
ReadyToRunSectionType.ImportSections,
ReadyToRunSectionType.RuntimeFunctions,
ReadyToRunSectionType.MethodDefEntryPoints,
ReadyToRunSectionType.DebugInfo,
ReadyToRunSectionType.DelayLoadMethodCallThunks,
ReadyToRunSectionType.AvailableTypes,
ReadyToRunSectionType.InstanceMethodEntryPoints,
ReadyToRunSectionType.ManifestMetadata,
ReadyToRunSectionType.InliningInfo2,
ReadyToRunSectionType.ManifestAssemblyMvids,
}, header.Sections.Select(x => x.Type));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void CompilerIdentifierSection(bool rebuild)
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld_ReadyToRun, TestReaderParameters);
var section = GetSection<CompilerIdentifierSection>(image, rebuild);
Assert.Equal("Crossgen2 6.0.2223.42425", section.Identifier);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ImportSections(bool rebuild)
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld_ReadyToRun, TestReaderParameters);
var section = GetSection<ImportSectionsSection>(image, rebuild);
Assert.Equal(new[]
{
ImportSectionType.StubDispatch,
ImportSectionType.Unknown,
ImportSectionType.Unknown,
ImportSectionType.StubDispatch,
ImportSectionType.Unknown,
ImportSectionType.StringHandle
}, section.Sections.Select(x => x.Type));
}
[Theory]
[InlineData(false)]
// TODO: [InlineData(true)]
public void ImportSectionSlots(bool rebuild)
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld_ReadyToRun, TestReaderParameters);
var section = GetSection<ImportSectionsSection>(image, rebuild);
Assert.Equal(new[]
{
(0x00000000u, 0x0000A0D4u, ReadyToRunFixupKind.CheckInstructionSetSupport),
(0x00000000u, 0x0000A0DBu, ReadyToRunFixupKind.Helper),
(0x00000000u, 0x0000A0DDu, ReadyToRunFixupKind.Helper),
(0x00000000u, 0x0000A0DFu, ReadyToRunFixupKind.Helper),
(0x00000000u, 0x0000A0E2u, ReadyToRunFixupKind.Helper),
}, ReadTestData(section.Sections[1]));
Assert.Equal(new[]
{
(0x0009594u, 0x0000A0D9u, ReadyToRunFixupKind.MethodEntryRefToken),
}, ReadTestData(section.Sections[3]));
Assert.Equal(new[]
{
(0x00000000u, 0x0000A0E5u, ReadyToRunFixupKind.StringHandle),
}, ReadTestData(section.Sections[5]));
return;
IEnumerable<(uint, uint, ReadyToRunFixupKind)> ReadTestData(ImportSection import)
{
for (int i = 0; i < import.Slots.Count; i++)
{
yield return (
import.Slots[i].Rva,
import.Signatures[i].Rva,
(ReadyToRunFixupKind) import.Signatures[i].CreateReader().ReadByte()
);
}
}
}
[Fact]
public void X64RuntimeFunctions()
{
var image = PEImage.FromBytes(Properties.Resources.ReadyToRunTest, TestReaderParameters);
var header = Assert.IsAssignableFrom<ReadyToRunDirectory>(image.DotNetDirectory!.ManagedNativeHeader);
var section = header.GetSection<RuntimeFunctionsSection>();
Assert.Equal(new[]
{
(0x00001840u, 0x00001870u),
(0x00001870u, 0x0000188au),
(0x00001890u, 0x000018cdu),
(0x000018CDu, 0x000018f2u),
(0x00001900u, 0x0000191au),
}, section.GetFunctions().Select(x => (x.Begin.Rva, x.End.Rva)));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void MethodDefEntryPoints(bool rebuild)
{
var image = PEImage.FromBytes(Properties.Resources.ReadyToRunTest, TestReaderParameters);
var section = GetSection<MethodEntryPointsSection>(image, rebuild);
Assert.Equal(
new uint?[] {0u, null, 1u, 2u, 4u},
section.EntryPoints.Select(x => x?.RuntimeFunctionIndex)
);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void MethodDefEntryPointFixups(bool rebuild)
{
var image = PEImage.FromBytes(Properties.Resources.ReadyToRunTest, TestReaderParameters);
var section = GetSection<MethodEntryPointsSection>(image, rebuild);
Assert.Equal(new[]
{
(5u, 0u),
(5u, 4u),
}, section.EntryPoints[0]!.Fixups.Select(x => (x.ImportIndex, x.SlotIndex)));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void DebugInfoBound(bool rebuild)
{
var image = PEImage.FromBytes(Properties.Resources.ReadyToRunTest, TestReaderParameters);
var section = GetSection<DebugInfoSection>(image, rebuild);
Assert.NotNull(section.Entries[0]);
Assert.Equal(new DebugInfoBounds[]
{
new(0x0, DebugInfoBounds.PrologOffset, DebugInfoAttributes.StackEmpty),
new(0x4, 0x0, DebugInfoAttributes.StackEmpty),
new(0x14, 0xA, DebugInfoAttributes.StackEmpty),
new(0x1A, 0xF, DebugInfoAttributes.StackEmpty),
new(0x2A, 0x14, DebugInfoAttributes.StackEmpty),
new(0x2A, DebugInfoBounds.EpilogOffset, DebugInfoAttributes.StackEmpty),
}, section.Entries[0]!.Bounds);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void DebugInfoBoundLookBack(bool rebuild)
{
var image = PEImage.FromBytes(Properties.Resources.ReadyToRunTest, TestReaderParameters);
var section = GetSection<DebugInfoSection>(image, rebuild);
Assert.NotNull(section.Entries[4]);
Assert.Equal(new DebugInfoBounds[]
{
new(0x0, DebugInfoBounds.PrologOffset, DebugInfoAttributes.StackEmpty),
new(0x4, 0x0, DebugInfoAttributes.StackEmpty),
new(0x14, 0xA, DebugInfoAttributes.StackEmpty),
new(0x14, DebugInfoBounds.EpilogOffset, DebugInfoAttributes.StackEmpty),
}, section.Entries[4]!.Bounds);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void DebugInfoVariables(bool rebuild)
{
var image = PEImage.FromBytes(Properties.Resources.ReadyToRunTestLoop, TestReaderParameters);
var section = GetSection<DebugInfoSection>(image, rebuild);
Assert.NotNull(section.Entries[0]);
Assert.Equal(new DebugInfoVariable[]
{
new(0, 6, 0, new(DebugInfoVariableLocationType.Register, 1)),
new(0x17, 0x2B, 1, new(DebugInfoVariableLocationType.Register, 6)),
new(0x19, 0x2B, 2, new(DebugInfoVariableLocationType.Register, 7)),
}, section.Entries[0]!.Variables);
}
} | 192 | 9,689 | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using AsmResolver.IO;
using AsmResolver.PE.File;
namespace AsmResolver.PE.DotNet.ReadyToRun
{
/// <summary>
/// Represents a managed native header of a .NET portable executable file that is in the ReadyToRun format.
/// </summary>
public class ReadyToRunDirectory : SegmentBase, IManagedNativeHeader
{
private IList<IReadyToRunSection>? _sections;
/// <inheritdoc />
public ManagedNativeHeaderSignature Signature => ManagedNativeHeaderSignature.Rtr;
/// <summary>
/// Gets the major version of the file format that is used.
/// </summary>
public ushort MajorVersion
{
get;
set;
} = 5;
/// <summary>
/// Gets the minor version of the file format that is used.
/// </summary>
public ushort MinorVersion
{
get;
set;
} = 4;
/// <summary>
/// Gets or sets the flags associated with the ReadyToRun module.
/// </summary>
public ReadyToRunAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets the individual sections referenced by the ReadyToRun directory.
/// </summary>
public IList<IReadyToRunSection> Sections
{
get
{
if (_sections is null)
Interlocked.CompareExchange(ref _sections, GetSections(), null);
return _sections;
}
}
/// <summary>
/// Obtains the sections referenced by the directory.
/// </summary>
/// <returns>The sections.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Sections"/> property.
/// </remarks>
protected virtual IList<IReadyToRunSection> GetSections() => new List<IReadyToRunSection>();
/// <summary>
/// Gets a section by its section type.
/// </summary>
/// <param name="type">The type of section.</param>
/// <returns>The section.</returns>
/// <exception cref="ArgumentException">
/// Occurs when there is no section of the provided type present in the directory.
/// </exception>
public IReadyToRunSection GetSection(ReadyToRunSectionType type)
{
return TryGetSection(type, out var section)
? section
: throw new ArgumentException($"Directory does not contain a section of type {type}.");
}
/// <summary>
/// Gets a section by its section type.
/// </summary>
/// <typeparam name="TSection">The type of section.</typeparam>
/// <returns>The section.</returns>
/// <exception cref="ArgumentException">
/// Occurs when there is no section of the provided type present in the directory.
/// </exception>
public TSection GetSection<TSection>()
where TSection : class, IReadyToRunSection
{
return TryGetSection<TSection>(out var section)
? section
: throw new ArgumentException($"Directory does not contain a section of type {typeof(TSection).Name}.");
}
/// <summary>
/// Attempts to get a section by its section type.
/// </summary>
/// <param name="type">The type of the section.</param>
/// <param name="section">The section, or <c>null</c> if none was found.</param>
/// <returns><c>true</c> if the section was found, <c>false</c> otherwise.</returns>
public bool TryGetSection(ReadyToRunSectionType type, [NotNullWhen(true)] out IReadyToRunSection? section)
{
for (int i = 0; i < Sections.Count; i++)
{
if (Sections[i].Type == type)
{
section = Sections[i];
return true;
}
}
section = null;
return false;
}
/// <summary>
/// Attempts to get a section by its section type.
/// </summary>
/// <typeparam name="TSection">The type of section.</typeparam>
/// <param name="section">The section, or <c>null</c> if none was found.</param>
/// <returns><c>true</c> if the section was found, <c>false</c> otherwise.</returns>
public bool TryGetSection<TSection>([NotNullWhen(true)] out TSection? section)
where TSection : class, IReadyToRunSection
{
for (int i = 0; i < Sections.Count; i++)
{
if (Sections[i] is TSection s)
{
section = s;
return true;
}
}
section = null;
return false;
}
/// <inheritdoc />
public override uint GetPhysicalSize()
{
return sizeof(ManagedNativeHeaderSignature) // Signature
+ sizeof(ushort) // MajorVersion
+ sizeof(ushort) // MinorVersion
+ sizeof(ReadyToRunAttributes) // Flags
+ sizeof(uint) // NumberOfSections
+ (uint) Sections.Count * (sizeof(ReadyToRunSectionType) + DataDirectory.DataDirectorySize) //Sections
;
}
/// <inheritdoc />
public override void Write(BinaryStreamWriter writer)
{
writer.WriteUInt32((uint) Signature);
writer.WriteUInt16(MajorVersion);
writer.WriteUInt16(MinorVersion);
writer.WriteUInt32((uint) Attributes);
writer.WriteInt32(Sections.Count);
foreach (var section in Sections)
{
writer.WriteUInt32((uint) section.Type);
writer.WriteUInt32(section.Rva);
writer.WriteUInt32(section.GetPhysicalSize());
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\Resources\DotNetResourcesDirectoryTest.cs | AsmResolver.PE.Tests.DotNet.Resources
| DotNetResourcesDirectoryTest | [] | ['System.Linq', 'System.Text', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit', 'AsmResolver.DotNet.TestCases.Resources.Resources'] | xUnit | net8.0 | public class DotNetResourcesDirectoryTest
{
private static ManifestResourceRow FindResourceRow(MetadataDirectory metadata, string name)
{
var stringsStream = metadata.GetStream<StringsStream>();
var tablesStream = metadata.GetStream<TablesStream>();
var table = tablesStream.GetTable<ManifestResourceRow>(TableIndex.ManifestResource);
var resource = table.First(t => stringsStream.GetStringByIndex(t.Name) == name);
return resource;
}
[Fact]
public void ReadEmbeddedResource1Data()
{
var image = PEImage.FromFile(typeof(TestCaseResources).Assembly.Location, TestReaderParameters);
var metadata = image.DotNetDirectory!.Metadata!;
var resource = FindResourceRow(metadata, "AsmResolver.DotNet.TestCases.Resources.Resources.EmbeddedResource1");
byte[]? data = image.DotNetDirectory.DotNetResources!.GetManifestResourceData(resource.Offset);
Assert.NotNull(data);
Assert.Equal(TestCaseResources.GetEmbeddedResource1Data(), Encoding.ASCII.GetString(data!));
}
[Fact]
public void ReadEmbeddedResource2Data()
{
var image = PEImage.FromFile(typeof(TestCaseResources).Assembly.Location, TestReaderParameters);
var metadata = image.DotNetDirectory!.Metadata!;
var resource = FindResourceRow(metadata, "AsmResolver.DotNet.TestCases.Resources.Resources.EmbeddedResource2");
byte[]? data = image.DotNetDirectory.DotNetResources!.GetManifestResourceData(resource.Offset);
Assert.NotNull(data);
Assert.Equal(TestCaseResources.GetEmbeddedResource2Data(), Encoding.ASCII.GetString(data!));
}
} | 274 | 2,090 | using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.Resources
{
/// <summary>
/// Represents a data directory containing the data of all manifest resources stored in a .NET module.
/// </summary>
public abstract class DotNetResourcesDirectory : SegmentBase
{
/// <summary>
/// Gets the manifest resource data by its offset.
/// </summary>
/// <param name="offset">The offset of the resource data, relative to the start of the data directory.</param>
/// <returns>The data, or <c>null</c> if the offset is not a valid offset.</returns>
public abstract byte[]? GetManifestResourceData(uint offset);
/// <summary>
/// Gets a reader starting at the beginning of the resource data referenced by the provided offset.
/// </summary>
/// <param name="offset">The offset of the resource data, relative to the start of the data directory.</param>
/// <param name="reader">When this method returns <c>true</c>, this parameter contains the created binary reader.</param>
/// <returns>
/// <c>true</c> if a blob reader could be created at the provided offset, <c>false</c> otherwise.
/// </returns>
public abstract bool TryCreateManifestResourceReader(uint offset, out BinaryStreamReader reader);
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\StrongName\StrongNamePublicKeyTest.cs | AsmResolver.PE.Tests.DotNet.StrongName
| StrongNamePublicKeyTest | [] | ['System.IO', 'System.Security.Cryptography', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.StrongName', 'Xunit'] | xUnit | net8.0 | public class StrongNamePublicKeyTest
{
[Fact]
public void PersistentStrongNamePublicKey()
{
using var rsa = RSA.Create();
var rsaParameters = rsa.ExportParameters(true);
var publicKey = new StrongNamePublicKey(rsaParameters);
using var tempStream = new MemoryStream();
publicKey.Write(new BinaryStreamWriter(tempStream));
var reader = new BinaryStreamReader(tempStream.ToArray());
var newPublicKey = StrongNamePublicKey.FromReader(ref reader);
Assert.Equal(publicKey.Modulus, newPublicKey.Modulus);
Assert.Equal(publicKey.PublicExponent, newPublicKey.PublicExponent);
}
} | 192 | 932 | using System;
using System.IO;
using System.Security.Cryptography;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.PE.DotNet.StrongName
{
// Reference
// https://docs.microsoft.com/en-us/windows/win32/seccrypto/rsa-schannel-key-blobs
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-rsapubkey
/// <summary>
/// Represents the public key in a RSA crypto system.
/// </summary>
public class StrongNamePublicKey : StrongNameKeyStructure
{
/// <summary>
/// Reads a private key from an input file.
/// </summary>
/// <param name="path">The path to the strong-name key file.</param>
/// <returns>The private key.</returns>
/// <exception cref="FormatException">Occurs when the input stream is not in the correct format.</exception>
/// <exception cref="NotSupportedException">Occurs when an invalid or unsupported algorithm is specified.</exception>
public static StrongNamePublicKey FromFile(string path)
{
var reader = new BinaryStreamReader(System.IO.File.ReadAllBytes(path));
return FromReader(ref reader);
}
/// <summary>
/// Reads a private key from an input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <returns>The private key.</returns>
/// <exception cref="FormatException">Occurs when the input stream is not in the correct format.</exception>
/// <exception cref="NotSupportedException">Occurs when an invalid or unsupported algorithm is specified.</exception>
public static StrongNamePublicKey FromReader(ref BinaryStreamReader reader)
{
// Read BLOBHEADER
ReadBlobHeader(ref reader, StrongNameKeyStructureType.PublicKeyBlob, 2, SignatureAlgorithm.RsaSign);
// Read RSAPUBKEY
if ((RsaPublicKeyMagic) reader.ReadUInt32() != RsaPublicKeyMagic.Rsa1)
throw new FormatException("Input stream does not contain a valid RSA public key header magic.");
uint bitLength = reader.ReadUInt32();
var result = new StrongNamePublicKey(new byte[bitLength / 8], reader.ReadUInt32());
reader.ReadBytes(result.Modulus, 0, result.Modulus.Length);
return result;
}
private byte[] CopyReversed(byte[] data)
{
var result = new byte[data.Length];
for (int i = 0; i < data.Length; i++)
result[result.Length - i - 1] = data[i];
return result;
}
/// <summary>
/// Creates a new strong name public key.
/// </summary>
/// <param name="modulus">The modulus to use in the RSA crypto system.</param>
/// <param name="publicExponent">The public exponent to use in the RSA crypto system.</param>
public StrongNamePublicKey(byte[] modulus, uint publicExponent)
{
Modulus = modulus ?? throw new ArgumentNullException(nameof(modulus));
PublicExponent = publicExponent;
}
/// <summary>
/// Imports a public key from an instance of <see cref="RSAParameters"/>.
/// </summary>
/// <param name="parameters">The RSA parameters to import.</param>
public StrongNamePublicKey(in RSAParameters parameters)
{
if (parameters.Modulus is null)
throw new ArgumentException("RSA parameters does not define a modulus.");
if (parameters.Exponent is null)
throw new ArgumentException("RSA parameters does not define an exponent.");
Modulus = CopyReversed(parameters.Modulus);
uint exponent = 0;
for (int i = 0; i < Math.Min(sizeof(uint), parameters.Exponent.Length); i++)
exponent |= (uint) (parameters.Exponent[i] << (8 * i));
PublicExponent = exponent;
}
/// <inheritdoc />
public override StrongNameKeyStructureType Type => StrongNameKeyStructureType.PublicKeyBlob;
/// <inheritdoc />
public override byte Version => 2;
/// <inheritdoc />
public override SignatureAlgorithm SignatureAlgorithm => SignatureAlgorithm.RsaSign;
/// <summary>
/// Gets the magic header number defining the type of RSA public key structure.
/// </summary>
public virtual RsaPublicKeyMagic Magic => RsaPublicKeyMagic.Rsa1;
/// <summary>
/// Gets the number of bits used by the modulus parameter.
/// </summary>
public int BitLength => Modulus.Length * 8;
/// <summary>
/// Gets or sets the public exponent used in the RSA crypto system.
/// </summary>
public uint PublicExponent
{
get;
set;
}
/// <summary>
/// Gets or sets the modulus used in the RSA crypto system.
/// </summary>
public byte[] Modulus
{
get;
set;
}
/// <summary>
/// Prepares a blob signature containing the full public key of an assembly.
/// </summary>
/// <param name="hashAlgorithm">The hash algorithm that is used to hash the PE file.</param>
/// <returns>The blob signature.</returns>
public byte[] CreatePublicKeyBlob(AssemblyHashAlgorithm hashAlgorithm)
{
using var tempStream = new MemoryStream();
var writer = new BinaryStreamWriter(tempStream);
writer.WriteUInt32((uint) SignatureAlgorithm);
writer.WriteUInt32((uint) hashAlgorithm);
writer.WriteUInt32((uint) (0x14 + Modulus.Length));
writer.WriteByte((byte) StrongNameKeyStructureType.PublicKeyBlob);
writer.WriteByte(2);
writer.WriteUInt16(0);
writer.WriteUInt32((uint) SignatureAlgorithm);
writer.WriteUInt32((uint) RsaPublicKeyMagic.Rsa1);
writer.WriteUInt32((uint) BitLength);
writer.WriteUInt32(PublicExponent);
writer.WriteBytes(CopyReversed(Modulus));
return tempStream.ToArray();
}
/// <summary>
/// Translates the strong name parameters to an instance of <see cref="RSAParameters"/>.
/// </summary>
/// <returns>The converted RSA parameters.</returns>
public virtual RSAParameters ToRsaParameters()
{
return new RSAParameters
{
Modulus = Modulus,
Exponent = BitConverter.GetBytes(PublicExponent)
};
}
/// <inheritdoc />
public override uint GetPhysicalSize()
{
return base.GetPhysicalSize() // _PUBLICKEYSTRUC (BLOBHEADER)
+ sizeof(RsaPublicKeyMagic) // magic
+ sizeof(uint) // bitlen
+ sizeof(uint) // pubexp
+ (uint) Modulus.Length / 8 // modulus
;
}
/// <inheritdoc />
public override void Write(BinaryStreamWriter writer)
{
base.Write(writer);
writer.WriteUInt32((uint) Magic);
writer.WriteUInt32((uint) BitLength);
writer.WriteUInt32(PublicExponent);
writer.WriteBytes(Modulus);
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\DotNet\VTableFixups\VTableFixupsDirectoryTest.cs | AsmResolver.PE.Tests.DotNet.VTableFixups
| VTableFixupsDirectoryTest | [] | ['System.IO', 'AsmResolver.IO', 'AsmResolver.PE.Builder', 'AsmResolver.PE.DotNet.VTableFixups', 'Xunit'] | xUnit | net8.0 | public class VTableFixupsDirectoryTest
{
private static PEImage RebuildAndReloadManagedPE(PEImage image)
{
// Build.
using var tempStream = new MemoryStream();
var builder = new ManagedPEFileBuilder();
var newPeFile = builder.CreateFile(image);
newPeFile.Write(new BinaryStreamWriter(tempStream));
// Reload.
var newImage = PEImage.FromBytes(tempStream.ToArray(), TestReaderParameters);
return newImage;
}
[Theory]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public void ReadVTableTokens(bool is32Bit, bool rebuild)
{
var peImage = PEImage.FromBytes(
is32Bit
? Properties.Resources.UnmanagedExports_x32
: Properties.Resources.UnmanagedExports_x64,
TestReaderParameters
);
if (rebuild)
peImage = RebuildAndReloadManagedPE(peImage);
var fixups = peImage.DotNetDirectory!.VTableFixups!;
int token = 0x06000001;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++, token++)
{
Assert.Equal(token, fixups[i].Tokens[j]);
}
}
}
[Theory]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public void ReadVTableFixupsDirectory(bool is32Bit, bool rebuild)
{
var peImage = PEImage.FromBytes(
is32Bit
? Properties.Resources.UnmanagedExports_x32
: Properties.Resources.UnmanagedExports_x64,
TestReaderParameters
);
if (rebuild)
peImage = RebuildAndReloadManagedPE(peImage);
var fixups = peImage.DotNetDirectory!.VTableFixups!;
Assert.Equal(2, fixups.Count);
Assert.Equal(3, fixups[0].Tokens.Count);
Assert.Equal(3, fixups[1].Tokens.Count);
var entrySize = is32Bit ? VTableType.VTable32Bit : VTableType.VTable64Bit;
Assert.Equal(entrySize | VTableType.VTableFromUnmanaged, fixups[0].Tokens.Type);
Assert.Equal(entrySize | VTableType.VTableFromUnmanaged, fixups[1].Tokens.Type);
}
} | 190 | 2,768 | using System.Collections.ObjectModel;
using System.Linq;
using AsmResolver.IO;
namespace AsmResolver.PE.DotNet.VTableFixups
{
/// <summary>
/// Represents the VTable fixups directory in the Cor20 header.
/// </summary>
public class VTableFixupsDirectory : Collection<VTableFixup>, ISegment
{
/// <inheritdoc />
public ulong Offset
{
get;
private set;
}
/// <inheritdoc />
public uint Rva
{
get;
private set;
}
/// <inheritdoc />
public bool CanUpdateOffsets => true;
/// <inheritdoc />
public void UpdateOffsets(in RelocationParameters parameters)
{
Offset = parameters.Offset;
Rva = parameters.Rva;
}
/// <inheritdoc />
public uint GetPhysicalSize() => (uint) this.Sum(v => v.GetPhysicalSize());
/// <inheritdoc />
public void Write(BinaryStreamWriter writer)
{
for (int i = 0; i < Count; i++)
this[i].Write(writer);
}
/// <inheritdoc />
public uint GetVirtualSize() => (uint) this.Sum(v => v.GetVirtualSize());
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Exceptions\X64ExceptionDirectoryTest.cs | AsmResolver.PE.Tests.Exceptions
| X64ExceptionDirectoryTest | [] | ['AsmResolver.PE.Exceptions', 'Xunit'] | xUnit | net8.0 | public class X64ExceptionDirectoryTest
{
[Fact]
public void ReadSEHTable()
{
var image = PEImage.FromBytes(Properties.Resources.SEHSamples, TestReaderParameters);
var exceptions = Assert.IsAssignableFrom<ExceptionDirectory<X64RuntimeFunction>>(image.Exceptions);
Assert.Equal(0x1010u, exceptions.Entries[0].Begin.Rva);
Assert.Equal(0x1065u, exceptions.Entries[0].End.Rva);
Assert.Equal(0x1E0Cu, exceptions.Entries[^1].Begin.Rva);
Assert.Equal(0x1E24u, exceptions.Entries[^1].End.Rva);
}
} | 100 | 714 | using System;
using System.Collections.Generic;
using AsmResolver.IO;
namespace AsmResolver.PE.Exceptions
{
internal class X64ExceptionDirectory : ExceptionDirectory<X64RuntimeFunction>
{
private readonly PEReaderContext _context;
private readonly BinaryStreamReader _reader;
public X64ExceptionDirectory(PEReaderContext context, in BinaryStreamReader reader)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_reader = reader;
}
/// <inheritdoc />
protected override IList<X64RuntimeFunction> GetEntries()
{
var reader = _reader.Fork();
var result = new List<X64RuntimeFunction>();
while (reader.CanRead(X64RuntimeFunction.EntrySize))
{
var function = X64RuntimeFunction.FromReader(_context, ref reader);
if (function is null)
break;
result.Add(function);
}
return result;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Exports\ExportDirectoryTest.cs | AsmResolver.PE.Tests.Exports
| ExportDirectoryTest | ['private readonly TemporaryDirectoryFixture _fixture;'] | ['System', 'System.IO', 'System.Linq', 'AsmResolver.IO', 'AsmResolver.PE.Builder', 'AsmResolver.PE.Exports', 'AsmResolver.PE.Exports.Builder', 'AsmResolver.PE.File', 'AsmResolver.Tests.Runners', 'Xunit'] | xUnit | net8.0 | public class ExportDirectoryTest : IClassFixture<TemporaryDirectoryFixture>
{
private readonly TemporaryDirectoryFixture _fixture;
public ExportDirectoryTest(TemporaryDirectoryFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void ReadName()
{
var image = PEImage.FromBytes(Properties.Resources.SimpleDll_Exports, TestReaderParameters);
Assert.Equal("SimpleDll.dll", image.Exports?.Name);
}
[Fact]
public void ReadExportNames()
{
var image = PEImage.FromBytes(Properties.Resources.SimpleDll_Exports, TestReaderParameters);
Assert.Equal(new[]
{
"NamedExport1",
"NamedExport2",
}, image.Exports?.Entries.Select(e => e.Name) ?? Array.Empty<string>());
}
[Fact]
public void ReadExportAddresses()
{
var image = PEImage.FromBytes(Properties.Resources.SimpleDll_Exports, TestReaderParameters);
Assert.NotNull(image.Exports);
Assert.Equal(new[]
{
0x000111DBu,
0x00011320u,
}, image.Exports.Entries.Select(e => e.Address.Rva));
}
[Fact]
public void ReadOrdinals()
{
var image = PEImage.FromBytes(Properties.Resources.SimpleDll_Exports, TestReaderParameters);
Assert.NotNull(image.Exports);
Assert.Equal(new[]
{
1u,
2u,
}, image.Exports.Entries.Select(e => e.Ordinal));
}
[Fact]
public void ChangeBaseOrdinalShouldUpdateAllOrdinals()
{
var image = PEImage.FromBytes(Properties.Resources.SimpleDll_Exports, TestReaderParameters);
image.Exports!.BaseOrdinal = 10;
Assert.Equal(new[]
{
10u,
11u,
}, image.Exports.Entries.Select(e => e.Ordinal));
}
[Fact]
public void RemoveExportShouldUpdateOrdinals()
{
var image = PEImage.FromBytes(Properties.Resources.SimpleDll_Exports, TestReaderParameters);
var export = image.Exports!.Entries[0];
image.Exports.Entries.RemoveAt(0);
Assert.Equal(0u, export.Ordinal);
Assert.Equal(1u, image.Exports.Entries[0].Ordinal);
}
[Fact]
public void InsertExportShouldUpdateOrdinals()
{
var image = PEImage.FromBytes(Properties.Resources.SimpleDll_Exports, TestReaderParameters);
image.Exports!.Entries.Insert(0, new ExportedSymbol(new VirtualAddress(0x1234), "NewExport"));
Assert.Equal(new[]
{
1u,
2u,
3u,
}, image.Exports.Entries.Select(e => e.Ordinal));
}
private static PEImage RebuildAndReloadManagedPE(PEImage image)
{
// Build.
using var tempStream = new MemoryStream();
var builder = new ManagedPEFileBuilder();
var newPeFile = builder.CreateFile(image);
newPeFile.Write(new BinaryStreamWriter(tempStream));
// Reload.
var newImage = PEImage.FromBytes(tempStream.ToArray(), TestReaderParameters);
return newImage;
}
[Fact]
public void PersistentExportLibraryName()
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
image.Exports = new ExportDirectory("HelloWorld.dll")
{
Entries = {new ExportedSymbol(new VirtualAddress(0x12345678), "TestExport")}
};
var newImage = RebuildAndReloadManagedPE(image);
Assert.Equal(image.Exports.Name, newImage.Exports?.Name);
}
[Fact]
public void PersistentExportedSymbol()
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Prepare mock.
var exportDirectory = new ExportDirectory("HelloWorld.dll");
var exportedSymbol = new ExportedSymbol(new VirtualAddress(0x12345678), "TestExport");
exportDirectory.Entries.Add(exportedSymbol);
image.Exports = exportDirectory;
// Rebuild.
var newImage = RebuildAndReloadManagedPE(image);
// Verify.
Assert.Single(newImage.Exports!.Entries);
var newExportedSymbol = newImage.Exports.Entries[0];
Assert.Equal(exportedSymbol.Name, newExportedSymbol.Name);
Assert.Equal(exportedSymbol.Ordinal, newExportedSymbol.Ordinal);
Assert.Equal(exportedSymbol.Address.Rva, newExportedSymbol.Address.Rva);
}
[Fact]
public void PersistentExportedSymbolByOrdinal()
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Prepare mock.
var exportDirectory = new ExportDirectory("HelloWorld.dll");
var exportedSymbol = new ExportedSymbol(new VirtualAddress(0x12345678));
exportDirectory.Entries.Add(exportedSymbol);
image.Exports = exportDirectory;
// Rebuild.
var newImage = RebuildAndReloadManagedPE(image);
// Verify.
Assert.Single(newImage.Exports!.Entries);
var newExportedSymbol = newImage.Exports.Entries[0];
Assert.True(exportedSymbol.IsByOrdinal);
Assert.Equal(exportedSymbol.Ordinal, newExportedSymbol.Ordinal);
Assert.Equal(exportedSymbol.Address.Rva, newExportedSymbol.Address.Rva);
}
[Fact]
public void PersistentExportedSymbolMany()
{
var image = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Prepare mock.
var exportDirectory = new ExportDirectory("HelloWorld.dll");
var namedSymbol1 = new ExportedSymbol(new VirtualAddress(0x12345678), "TestExport1");
var unnamedSymbol1 = new ExportedSymbol(new VirtualAddress(0x11112222));
var namedSymbol2 = new ExportedSymbol(new VirtualAddress(0xabcdef00), "TestExport2");
var unnamedSymbol2 = new ExportedSymbol(new VirtualAddress(0x33334444));
var namedSymbol3 = new ExportedSymbol(new VirtualAddress(0x1337c0de), "TestExport3");
var unnamedSymbol3 = new ExportedSymbol(new VirtualAddress(0x55556666));
exportDirectory.Entries.Add(namedSymbol1);
exportDirectory.Entries.Add(unnamedSymbol1);
exportDirectory.Entries.Add(namedSymbol2);
exportDirectory.Entries.Add(unnamedSymbol2);
exportDirectory.Entries.Add(namedSymbol3);
exportDirectory.Entries.Add(unnamedSymbol3);
image.Exports = exportDirectory;
// Rebuild.
var newImage = RebuildAndReloadManagedPE(image);
// Verify.
Assert.Equal(6, newImage.Exports!.Entries.Count);
var newSymbol = newImage.Exports.Entries[0];
Assert.Equal(namedSymbol1.Name, newSymbol.Name);
Assert.Equal(namedSymbol1.Ordinal, newSymbol.Ordinal);
Assert.Equal(namedSymbol1.Address.Rva, newSymbol.Address.Rva);
newSymbol = newImage.Exports.Entries[1];
Assert.True(newSymbol.IsByOrdinal);
Assert.Equal(unnamedSymbol1.Ordinal, newSymbol.Ordinal);
Assert.Equal(unnamedSymbol1.Address.Rva, newSymbol.Address.Rva);
newSymbol = newImage.Exports.Entries[2];
Assert.Equal(namedSymbol2.Name, newSymbol.Name);
Assert.Equal(namedSymbol2.Ordinal, newSymbol.Ordinal);
Assert.Equal(namedSymbol2.Address.Rva, newSymbol.Address.Rva);
newSymbol = newImage.Exports.Entries[3];
Assert.True(newSymbol.IsByOrdinal);
Assert.Equal(unnamedSymbol2.Ordinal, newSymbol.Ordinal);
Assert.Equal(unnamedSymbol2.Address.Rva, newSymbol.Address.Rva);
newSymbol = newImage.Exports.Entries[4];
Assert.Equal(namedSymbol3.Name, newSymbol.Name);
Assert.Equal(namedSymbol3.Ordinal, newSymbol.Ordinal);
Assert.Equal(namedSymbol3.Address.Rva, newSymbol.Address.Rva);
newSymbol = newImage.Exports.Entries[5];
Assert.True(newSymbol.IsByOrdinal);
Assert.Equal(unnamedSymbol3.Ordinal, newSymbol.Ordinal);
Assert.Equal(unnamedSymbol3.Address.Rva, newSymbol.Address.Rva);
}
[Fact]
public void ReadForwarderSymbol()
{
var exports = PEImage.FromBytes(Properties.Resources.ForwarderDlls_ProxyDll, TestReaderParameters).Exports!;
var bar = exports.Entries.First(x => x.Name == "Bar");
var baz = exports.Entries.First(x => x.Name == "Baz");
Assert.True(bar.IsForwarder);
Assert.Equal("ActualDll.Foo", bar.ForwarderName);
Assert.False(baz.IsForwarder);
}
[Fact]
public void RebuildForwarderSymbol()
{
var file = PEFile.FromBytes(Properties.Resources.ForwarderDlls_ProxyDll);
// Update a forwarder name.
var exports = PEImage.FromFile(file, TestReaderParameters).Exports!;
var bar = exports.Entries.First(x => x.Name == "Bar");
bar.ForwarderName = "ActualDll.Bar";
// Rebuild export directory.
var buffer = new ExportDirectoryBuffer();
buffer.AddDirectory(exports);
var section = new PESection(
".export",
SectionFlags.MemoryRead | SectionFlags.ContentInitializedData,
buffer);
// Rebuild.
file.Sections.Add(section);
file.UpdateHeaders();
file.OptionalHeader.SetDataDirectory(
DataDirectoryIndex.ExportDirectory,
new DataDirectory(section.Rva, section.GetPhysicalSize()));
using var stream = new MemoryStream();
file.Write(stream);
// Verify new forwarder symbol is present.
var newExports = PEImage.FromBytes(stream.ToArray(), TestReaderParameters).Exports!;
var newBar = newExports.Entries.First(x => x.Name == "Bar");
Assert.Equal("ActualDll.Bar", newBar.ForwarderName);
// Try running it.
var runner = _fixture.GetRunner<NativePERunner>();
string basePath = runner.GetTestDirectory(nameof(ExportDirectoryTest), nameof(RebuildForwarderSymbol));
string exePath = Path.Combine(basePath, "ForwarderTest.exe");
System.IO.File.WriteAllBytes(
Path.Combine(basePath, "ActualDll.dll"),
Properties.Resources.ForwarderDlls_ActualDll);
System.IO.File.WriteAllBytes(
exePath,
Properties.Resources.ForwarderDlls_ForwarderTest);
System.IO.File.WriteAllBytes(
Path.Combine(basePath, "ProxyDll.dll"),
stream.ToArray());
string output = runner.RunAndCaptureOutput(exePath);
Assert.Equal("ActualDLL::Bar\nProxyDll::Baz\nHello World!\n", output);
}
} | 302 | 11,966 | using System;
using System.Collections.Generic;
using System.Threading;
using AsmResolver.Collections;
namespace AsmResolver.PE.Exports
{
/// <summary>
/// Represents the data directory containing exported symbols that other images can access through dynamic linking.
/// </summary>
public class ExportDirectory
{
private readonly LazyVariable<ExportDirectory, string?> _name;
private IList<ExportedSymbol>? _exports;
/// <summary>
/// Initializes a new empty symbol export directory.
/// </summary>
protected ExportDirectory()
{
_name = new LazyVariable<ExportDirectory, string?>(x => x.GetName());
}
/// <summary>
/// Creates a new symbol export directory.
/// </summary>
/// <param name="name">The name of the library exporting the symbols.</param>
public ExportDirectory(string name)
{
_name = new LazyVariable<ExportDirectory, string?>(name ?? throw new ArgumentNullException(nameof(name)));
}
/// <summary>
/// Gets or sets the flags associated to the export directory.
/// </summary>
/// <remarks>
/// This field is reserved and should be zero.
/// </remarks>
public uint ExportFlags
{
get;
set;
}
/// <summary>
/// Gets or sets the time and date that the exports data was created.
/// </summary>
public uint TimeDateStamp
{
get;
set;
} = 0xFFFFFFFF;
/// <summary>
/// Gets or sets the user major version number.
/// </summary>
public ushort MajorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the user minor version number.
/// </summary>
public ushort MinorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the name of the exports directory.
/// </summary>
public string? Name
{
get => _name.GetValue(this);
set => _name.SetValue(value);
}
/// <summary>
/// Gets or sets the base ordinal of the exports directory.
/// </summary>
public uint BaseOrdinal
{
get;
set;
} = 1;
/// <summary>
/// Gets an ordered list of symbols that are exported by the portable executable (PE) image.
/// </summary>
public IList<ExportedSymbol> Entries
{
get
{
if (_exports is null)
Interlocked.CompareExchange(ref _exports, GetExports(), null);
return _exports;
}
}
/// <summary>
/// Obtains the name of the library that is exporting symbols.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual string? GetName() => null;
/// <summary>
/// Obtains the list of exported symbols defined by the export directory.
/// </summary>
/// <returns>The exported symbols..</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Entries"/> property.
/// </remarks>
protected virtual IList<ExportedSymbol> GetExports() =>
new ExportedSymbolCollection(this);
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Imports\DefaultSymbolResolverTest.cs | AsmResolver.PE.Tests.Imports
| DefaultSymbolResolverTest | [] | ['AsmResolver.PE.Imports', 'Xunit'] | xUnit | net8.0 | public class DefaultSymbolResolverTest
{
[Fact]
public void ResolveWinsockSymbol()
{
var module = new ImportedModule("ws2_32.dll");
var symbol = new ImportedSymbol(57);
module.Symbols.Add(symbol);
var resolvedSymbol = DefaultSymbolResolver.Instance.Resolve(symbol)!;
Assert.NotNull(resolvedSymbol);
Assert.Equal("gethostname", resolvedSymbol.Name);
}
[Fact]
public void ResolveOleaut32Symbol()
{
var module = new ImportedModule("oleaut32.dll");
var symbol = new ImportedSymbol(365);
module.Symbols.Add(symbol);
var resolvedSymbol = DefaultSymbolResolver.Instance.Resolve(symbol)!;
Assert.NotNull(resolvedSymbol);
Assert.Equal("VarDateFromUI8", resolvedSymbol.Name);
}
} | 94 | 1,007 | using System.Collections.Generic;
using AsmResolver.PE.Exports;
// ReSharper disable InconsistentNaming
namespace AsmResolver.PE.Imports
{
/// <summary>
/// Provides an implementation of the <see cref="ISymbolResolver"/> that includes some static ordinal-name mappings
/// from known Windows libraries.
/// </summary>
/// <remarks>
/// This class should only be used for quick static lookup of common ordinals to names (e.g. in conjuction with
/// the <see cref="ImportHash"/> class). The resulting symbol objects are mock objects and do not contain a valid
/// address to the actual symbol.
/// </remarks>
public sealed class DefaultSymbolResolver : ISymbolResolver
{
// Ordinal name mappings extracted using the AsmResolver.PE.Exports.OrdinalMapper utility.
private static readonly Dictionary<uint, string> _ws2_32OrdinalMapping = new()
{
[1] = "accept",
[2] = "bind",
[3] = "closesocket",
[4] = "connect",
[5] = "getpeername",
[6] = "getsockname",
[7] = "getsockopt",
[8] = "htonl",
[9] = "htons",
[10] = "ioctlsocket",
[11] = "inet_addr",
[12] = "inet_ntoa",
[13] = "listen",
[14] = "ntohl",
[15] = "ntohs",
[16] = "recv",
[17] = "recvfrom",
[18] = "select",
[19] = "send",
[20] = "sendto",
[21] = "setsockopt",
[22] = "shutdown",
[23] = "socket",
[24] = "WSApSetPostRoutine",
[25] = "FreeAddrInfoEx",
[26] = "FreeAddrInfoExW",
[27] = "FreeAddrInfoW",
[28] = "GetAddrInfoExA",
[29] = "GetAddrInfoExCancel",
[30] = "GetAddrInfoExOverlappedResult",
[31] = "GetAddrInfoExW",
[32] = "GetAddrInfoW",
[33] = "GetHostNameW",
[34] = "GetNameInfoW",
[35] = "InetNtopW",
[36] = "InetPtonW",
[37] = "SetAddrInfoExA",
[38] = "SetAddrInfoExW",
[39] = "WPUCompleteOverlappedRequest",
[40] = "WPUGetProviderPathEx",
[41] = "WSAAccept",
[42] = "WSAAddressToStringA",
[43] = "WSAAddressToStringW",
[44] = "WSAAdvertiseProvider",
[45] = "WSACloseEvent",
[46] = "WSAConnect",
[47] = "WSAConnectByList",
[48] = "WSAConnectByNameA",
[49] = "WSAConnectByNameW",
[50] = "WSACreateEvent",
[51] = "gethostbyaddr",
[52] = "gethostbyname",
[53] = "getprotobyname",
[54] = "getprotobynumber",
[55] = "getservbyname",
[56] = "getservbyport",
[57] = "gethostname",
[58] = "WSADuplicateSocketA",
[59] = "WSADuplicateSocketW",
[60] = "WSAEnumNameSpaceProvidersA",
[61] = "WSAEnumNameSpaceProvidersExA",
[62] = "WSAEnumNameSpaceProvidersExW",
[63] = "WSAEnumNameSpaceProvidersW",
[64] = "WSAEnumNetworkEvents",
[65] = "WSAEnumProtocolsA",
[66] = "WSAEnumProtocolsW",
[67] = "WSAEventSelect",
[68] = "WSAGetOverlappedResult",
[69] = "WSAGetQOSByName",
[70] = "WSAGetServiceClassInfoA",
[71] = "WSAGetServiceClassInfoW",
[72] = "WSAGetServiceClassNameByClassIdA",
[73] = "WSAGetServiceClassNameByClassIdW",
[74] = "WSAHtonl",
[75] = "WSAHtons",
[76] = "WSAInstallServiceClassA",
[77] = "WSAInstallServiceClassW",
[78] = "WSAIoctl",
[79] = "WSAJoinLeaf",
[80] = "WSALookupServiceBeginA",
[81] = "WSALookupServiceBeginW",
[82] = "WSALookupServiceEnd",
[83] = "WSALookupServiceNextA",
[84] = "WSALookupServiceNextW",
[85] = "WSANSPIoctl",
[86] = "WSANtohl",
[87] = "WSANtohs",
[88] = "WSAPoll",
[89] = "WSAProviderCompleteAsyncCall",
[90] = "WSAProviderConfigChange",
[91] = "WSARecv",
[92] = "WSARecvDisconnect",
[93] = "WSARecvFrom",
[94] = "WSARemoveServiceClass",
[95] = "WSAResetEvent",
[96] = "WSASend",
[97] = "WSASendDisconnect",
[98] = "WSASendMsg",
[99] = "WSASendTo",
[100] = "WSASetEvent",
[101] = "WSAAsyncSelect",
[102] = "WSAAsyncGetHostByAddr",
[103] = "WSAAsyncGetHostByName",
[104] = "WSAAsyncGetProtoByNumber",
[105] = "WSAAsyncGetProtoByName",
[106] = "WSAAsyncGetServByPort",
[107] = "WSAAsyncGetServByName",
[108] = "WSACancelAsyncRequest",
[109] = "WSASetBlockingHook",
[110] = "WSAUnhookBlockingHook",
[111] = "WSAGetLastError",
[112] = "WSASetLastError",
[113] = "WSACancelBlockingCall",
[114] = "WSAIsBlocking",
[115] = "WSAStartup",
[116] = "WSACleanup",
[117] = "WSASetServiceA",
[118] = "WSASetServiceW",
[119] = "WSASocketA",
[120] = "WSASocketW",
[121] = "WSAStringToAddressA",
[122] = "WSAStringToAddressW",
[123] = "WSAUnadvertiseProvider",
[124] = "WSAWaitForMultipleEvents",
[125] = "WSCDeinstallProvider",
[126] = "WSCDeinstallProvider32",
[127] = "WSCDeinstallProviderEx",
[128] = "WSCEnableNSProvider",
[129] = "WSCEnableNSProvider32",
[130] = "WSCEnumNameSpaceProviders32",
[131] = "WSCEnumNameSpaceProvidersEx32",
[132] = "WSCEnumProtocols",
[133] = "WSCEnumProtocols32",
[134] = "WSCEnumProtocolsEx",
[135] = "WSCGetApplicationCategory",
[136] = "WSCGetApplicationCategoryEx",
[137] = "WSCGetProviderInfo",
[138] = "WSCGetProviderInfo32",
[139] = "WSCGetProviderPath",
[140] = "WSCGetProviderPath32",
[141] = "WSCInstallNameSpace",
[142] = "WSCInstallNameSpace32",
[143] = "WSCInstallNameSpaceEx",
[144] = "WSCInstallNameSpaceEx2",
[145] = "WSCInstallNameSpaceEx32",
[146] = "WSCInstallProvider",
[147] = "WSCInstallProvider64_32",
[148] = "WSCInstallProviderAndChains64_32",
[149] = "WSCInstallProviderEx",
[150] = "WSCSetApplicationCategory",
[151] = "__WSAFDIsSet",
[152] = "WSCSetApplicationCategoryEx",
[153] = "WSCSetProviderInfo",
[154] = "WSCSetProviderInfo32",
[155] = "WSCUnInstallNameSpace",
[156] = "WSCUnInstallNameSpace32",
[157] = "WSCUnInstallNameSpaceEx2",
[158] = "WSCUpdateProvider",
[159] = "WSCUpdateProvider32",
[160] = "WSCUpdateProviderEx",
[161] = "WSCWriteNameSpaceOrder",
[162] = "WSCWriteNameSpaceOrder32",
[163] = "WSCWriteProviderOrder",
[164] = "WSCWriteProviderOrder32",
[165] = "WSCWriteProviderOrderEx",
[166] = "WahCloseApcHelper",
[167] = "WahCloseHandleHelper",
[168] = "WahCloseNotificationHandleHelper",
[169] = "WahCloseSocketHandle",
[170] = "WahCloseThread",
[171] = "WahCompleteRequest",
[172] = "WahCreateHandleContextTable",
[173] = "WahCreateNotificationHandle",
[174] = "WahCreateSocketHandle",
[175] = "WahDestroyHandleContextTable",
[176] = "WahDisableNonIFSHandleSupport",
[177] = "WahEnableNonIFSHandleSupport",
[178] = "WahEnumerateHandleContexts",
[179] = "WahInsertHandleContext",
[180] = "WahNotifyAllProcesses",
[181] = "WahOpenApcHelper",
[182] = "WahOpenCurrentThread",
[183] = "WahOpenHandleHelper",
[184] = "WahOpenNotificationHandleHelper",
[185] = "WahQueueUserApc",
[186] = "WahReferenceContextByHandle",
[187] = "WahRemoveHandleContext",
[188] = "WahWaitForNotification",
[189] = "WahWriteLSPEvent",
[190] = "freeaddrinfo",
[191] = "getaddrinfo",
[192] = "getnameinfo",
[193] = "inet_ntop",
[194] = "inet_pton",
[500] = "WEP",
};
private static readonly Dictionary<uint, string> _oleaut32OrdinalMapping = new()
{
[2] = "SysAllocString",
[3] = "SysReAllocString",
[4] = "SysAllocStringLen",
[5] = "SysReAllocStringLen",
[6] = "SysFreeString",
[7] = "SysStringLen",
[8] = "VariantInit",
[9] = "VariantClear",
[10] = "VariantCopy",
[11] = "VariantCopyInd",
[12] = "VariantChangeType",
[13] = "VariantTimeToDosDateTime",
[14] = "DosDateTimeToVariantTime",
[15] = "SafeArrayCreate",
[16] = "SafeArrayDestroy",
[17] = "SafeArrayGetDim",
[18] = "SafeArrayGetElemsize",
[19] = "SafeArrayGetUBound",
[20] = "SafeArrayGetLBound",
[21] = "SafeArrayLock",
[22] = "SafeArrayUnlock",
[23] = "SafeArrayAccessData",
[24] = "SafeArrayUnaccessData",
[25] = "SafeArrayGetElement",
[26] = "SafeArrayPutElement",
[27] = "SafeArrayCopy",
[28] = "DispGetParam",
[29] = "DispGetIDsOfNames",
[30] = "DispInvoke",
[31] = "CreateDispTypeInfo",
[32] = "CreateStdDispatch",
[33] = "RegisterActiveObject",
[34] = "RevokeActiveObject",
[35] = "GetActiveObject",
[36] = "SafeArrayAllocDescriptor",
[37] = "SafeArrayAllocData",
[38] = "SafeArrayDestroyDescriptor",
[39] = "SafeArrayDestroyData",
[40] = "SafeArrayRedim",
[41] = "SafeArrayAllocDescriptorEx",
[42] = "SafeArrayCreateEx",
[43] = "SafeArrayCreateVectorEx",
[44] = "SafeArraySetRecordInfo",
[45] = "SafeArrayGetRecordInfo",
[46] = "VarParseNumFromStr",
[47] = "VarNumFromParseNum",
[48] = "VarI2FromUI1",
[49] = "VarI2FromI4",
[50] = "VarI2FromR4",
[51] = "VarI2FromR8",
[52] = "VarI2FromCy",
[53] = "VarI2FromDate",
[54] = "VarI2FromStr",
[55] = "VarI2FromDisp",
[56] = "VarI2FromBool",
[57] = "SafeArraySetIID",
[58] = "VarI4FromUI1",
[59] = "VarI4FromI2",
[60] = "VarI4FromR4",
[61] = "VarI4FromR8",
[62] = "VarI4FromCy",
[63] = "VarI4FromDate",
[64] = "VarI4FromStr",
[65] = "VarI4FromDisp",
[66] = "VarI4FromBool",
[67] = "SafeArrayGetIID",
[68] = "VarR4FromUI1",
[69] = "VarR4FromI2",
[70] = "VarR4FromI4",
[71] = "VarR4FromR8",
[72] = "VarR4FromCy",
[73] = "VarR4FromDate",
[74] = "VarR4FromStr",
[75] = "VarR4FromDisp",
[76] = "VarR4FromBool",
[77] = "SafeArrayGetVartype",
[78] = "VarR8FromUI1",
[79] = "VarR8FromI2",
[80] = "VarR8FromI4",
[81] = "VarR8FromR4",
[82] = "VarR8FromCy",
[83] = "VarR8FromDate",
[84] = "VarR8FromStr",
[85] = "VarR8FromDisp",
[86] = "VarR8FromBool",
[87] = "VarFormat",
[88] = "VarDateFromUI1",
[89] = "VarDateFromI2",
[90] = "VarDateFromI4",
[91] = "VarDateFromR4",
[92] = "VarDateFromR8",
[93] = "VarDateFromCy",
[94] = "VarDateFromStr",
[95] = "VarDateFromDisp",
[96] = "VarDateFromBool",
[97] = "VarFormatDateTime",
[98] = "VarCyFromUI1",
[99] = "VarCyFromI2",
[100] = "VarCyFromI4",
[101] = "VarCyFromR4",
[102] = "VarCyFromR8",
[103] = "VarCyFromDate",
[104] = "VarCyFromStr",
[105] = "VarCyFromDisp",
[106] = "VarCyFromBool",
[107] = "VarFormatNumber",
[108] = "VarBstrFromUI1",
[109] = "VarBstrFromI2",
[110] = "VarBstrFromI4",
[111] = "VarBstrFromR4",
[112] = "VarBstrFromR8",
[113] = "VarBstrFromCy",
[114] = "VarBstrFromDate",
[115] = "VarBstrFromDisp",
[116] = "VarBstrFromBool",
[117] = "VarFormatPercent",
[118] = "VarBoolFromUI1",
[119] = "VarBoolFromI2",
[120] = "VarBoolFromI4",
[121] = "VarBoolFromR4",
[122] = "VarBoolFromR8",
[123] = "VarBoolFromDate",
[124] = "VarBoolFromCy",
[125] = "VarBoolFromStr",
[126] = "VarBoolFromDisp",
[127] = "VarFormatCurrency",
[128] = "VarWeekdayName",
[129] = "VarMonthName",
[130] = "VarUI1FromI2",
[131] = "VarUI1FromI4",
[132] = "VarUI1FromR4",
[133] = "VarUI1FromR8",
[134] = "VarUI1FromCy",
[135] = "VarUI1FromDate",
[136] = "VarUI1FromStr",
[137] = "VarUI1FromDisp",
[138] = "VarUI1FromBool",
[139] = "VarFormatFromTokens",
[140] = "VarTokenizeFormatString",
[141] = "VarAdd",
[142] = "VarAnd",
[143] = "VarDiv",
[144] = "BSTR_UserFree64",
[145] = "BSTR_UserMarshal64",
[146] = "DispCallFunc",
[147] = "VariantChangeTypeEx",
[148] = "SafeArrayPtrOfIndex",
[149] = "SysStringByteLen",
[150] = "SysAllocStringByteLen",
[151] = "BSTR_UserSize64",
[152] = "VarEqv",
[153] = "VarIdiv",
[154] = "VarImp",
[155] = "VarMod",
[156] = "VarMul",
[157] = "VarOr",
[158] = "VarPow",
[159] = "VarSub",
[160] = "CreateTypeLib",
[161] = "LoadTypeLib",
[162] = "LoadRegTypeLib",
[163] = "RegisterTypeLib",
[164] = "QueryPathOfRegTypeLib",
[165] = "LHashValOfNameSys",
[166] = "LHashValOfNameSysA",
[167] = "VarXor",
[168] = "VarAbs",
[169] = "VarFix",
[170] = "OaBuildVersion",
[171] = "ClearCustData",
[172] = "VarInt",
[173] = "VarNeg",
[174] = "VarNot",
[175] = "VarRound",
[176] = "VarCmp",
[177] = "VarDecAdd",
[178] = "VarDecDiv",
[179] = "VarDecMul",
[180] = "CreateTypeLib2",
[181] = "VarDecSub",
[182] = "VarDecAbs",
[183] = "LoadTypeLibEx",
[184] = "SystemTimeToVariantTime",
[185] = "VariantTimeToSystemTime",
[186] = "UnRegisterTypeLib",
[187] = "VarDecFix",
[188] = "VarDecInt",
[189] = "VarDecNeg",
[190] = "VarDecFromUI1",
[191] = "VarDecFromI2",
[192] = "VarDecFromI4",
[193] = "VarDecFromR4",
[194] = "VarDecFromR8",
[195] = "VarDecFromDate",
[196] = "VarDecFromCy",
[197] = "VarDecFromStr",
[198] = "VarDecFromDisp",
[199] = "VarDecFromBool",
[200] = "GetErrorInfo",
[201] = "SetErrorInfo",
[202] = "CreateErrorInfo",
[203] = "VarDecRound",
[204] = "VarDecCmp",
[205] = "VarI2FromI1",
[206] = "VarI2FromUI2",
[207] = "VarI2FromUI4",
[208] = "VarI2FromDec",
[209] = "VarI4FromI1",
[210] = "VarI4FromUI2",
[211] = "VarI4FromUI4",
[212] = "VarI4FromDec",
[213] = "VarR4FromI1",
[214] = "VarR4FromUI2",
[215] = "VarR4FromUI4",
[216] = "VarR4FromDec",
[217] = "VarR8FromI1",
[218] = "VarR8FromUI2",
[219] = "VarR8FromUI4",
[220] = "VarR8FromDec",
[221] = "VarDateFromI1",
[222] = "VarDateFromUI2",
[223] = "VarDateFromUI4",
[224] = "VarDateFromDec",
[225] = "VarCyFromI1",
[226] = "VarCyFromUI2",
[227] = "VarCyFromUI4",
[228] = "VarCyFromDec",
[229] = "VarBstrFromI1",
[230] = "VarBstrFromUI2",
[231] = "VarBstrFromUI4",
[232] = "VarBstrFromDec",
[233] = "VarBoolFromI1",
[234] = "VarBoolFromUI2",
[235] = "VarBoolFromUI4",
[236] = "VarBoolFromDec",
[237] = "VarUI1FromI1",
[238] = "VarUI1FromUI2",
[239] = "VarUI1FromUI4",
[240] = "VarUI1FromDec",
[241] = "VarDecFromI1",
[242] = "VarDecFromUI2",
[243] = "VarDecFromUI4",
[244] = "VarI1FromUI1",
[245] = "VarI1FromI2",
[246] = "VarI1FromI4",
[247] = "VarI1FromR4",
[248] = "VarI1FromR8",
[249] = "VarI1FromDate",
[250] = "VarI1FromCy",
[251] = "VarI1FromStr",
[252] = "VarI1FromDisp",
[253] = "VarI1FromBool",
[254] = "VarI1FromUI2",
[255] = "VarI1FromUI4",
[256] = "VarI1FromDec",
[257] = "VarUI2FromUI1",
[258] = "VarUI2FromI2",
[259] = "VarUI2FromI4",
[260] = "VarUI2FromR4",
[261] = "VarUI2FromR8",
[262] = "VarUI2FromDate",
[263] = "VarUI2FromCy",
[264] = "VarUI2FromStr",
[265] = "VarUI2FromDisp",
[266] = "VarUI2FromBool",
[267] = "VarUI2FromI1",
[268] = "VarUI2FromUI4",
[269] = "VarUI2FromDec",
[270] = "VarUI4FromUI1",
[271] = "VarUI4FromI2",
[272] = "VarUI4FromI4",
[273] = "VarUI4FromR4",
[274] = "VarUI4FromR8",
[275] = "VarUI4FromDate",
[276] = "VarUI4FromCy",
[277] = "VarUI4FromStr",
[278] = "VarUI4FromDisp",
[279] = "VarUI4FromBool",
[280] = "VarUI4FromI1",
[281] = "VarUI4FromUI2",
[282] = "VarUI4FromDec",
[283] = "BSTR_UserSize",
[284] = "BSTR_UserMarshal",
[285] = "BSTR_UserUnmarshal",
[286] = "BSTR_UserFree",
[287] = "VARIANT_UserSize",
[288] = "VARIANT_UserMarshal",
[289] = "VARIANT_UserUnmarshal",
[290] = "VARIANT_UserFree",
[291] = "LPSAFEARRAY_UserSize",
[292] = "LPSAFEARRAY_UserMarshal",
[293] = "LPSAFEARRAY_UserUnmarshal",
[294] = "LPSAFEARRAY_UserFree",
[295] = "LPSAFEARRAY_Size",
[296] = "LPSAFEARRAY_Marshal",
[297] = "LPSAFEARRAY_Unmarshal",
[298] = "VarDecCmpR8",
[299] = "VarCyAdd",
[300] = "BSTR_UserUnmarshal64",
[301] = "DllCanUnloadNow",
[302] = "DllGetClassObject",
[303] = "VarCyMul",
[304] = "VarCyMulI4",
[305] = "VarCySub",
[306] = "VarCyAbs",
[307] = "VarCyFix",
[308] = "VarCyInt",
[309] = "VarCyNeg",
[310] = "VarCyRound",
[311] = "VarCyCmp",
[312] = "VarCyCmpR8",
[313] = "VarBstrCat",
[314] = "VarBstrCmp",
[315] = "VarR8Pow",
[316] = "VarR4CmpR8",
[317] = "VarR8Round",
[318] = "VarCat",
[319] = "VarDateFromUdateEx",
[320] = "DllRegisterServer",
[321] = "DllUnregisterServer",
[322] = "GetRecordInfoFromGuids",
[323] = "GetRecordInfoFromTypeInfo",
[324] = "LPSAFEARRAY_UserFree64",
[325] = "SetVarConversionLocaleSetting",
[326] = "GetVarConversionLocaleSetting",
[327] = "SetOaNoCache",
[328] = "LPSAFEARRAY_UserMarshal64",
[329] = "VarCyMulI8",
[330] = "VarDateFromUdate",
[331] = "VarUdateFromDate",
[332] = "GetAltMonthNames",
[333] = "VarI8FromUI1",
[334] = "VarI8FromI2",
[335] = "VarI8FromR4",
[336] = "VarI8FromR8",
[337] = "VarI8FromCy",
[338] = "VarI8FromDate",
[339] = "VarI8FromStr",
[340] = "VarI8FromDisp",
[341] = "VarI8FromBool",
[342] = "VarI8FromI1",
[343] = "VarI8FromUI2",
[344] = "VarI8FromUI4",
[345] = "VarI8FromDec",
[346] = "VarI2FromI8",
[347] = "VarI2FromUI8",
[348] = "VarI4FromI8",
[349] = "VarI4FromUI8",
[350] = "LPSAFEARRAY_UserSize64",
[351] = "LPSAFEARRAY_UserUnmarshal64",
[352] = "OACreateTypeLib2",
[353] = "SafeArrayAddRef",
[354] = "SafeArrayReleaseData",
[355] = "SafeArrayReleaseDescriptor",
[356] = "SysAddRefString",
[357] = "SysReleaseString",
[358] = "VARIANT_UserFree64",
[359] = "VARIANT_UserMarshal64",
[360] = "VarR4FromI8",
[361] = "VarR4FromUI8",
[362] = "VarR8FromI8",
[363] = "VarR8FromUI8",
[364] = "VarDateFromI8",
[365] = "VarDateFromUI8",
[366] = "VarCyFromI8",
[367] = "VarCyFromUI8",
[368] = "VarBstrFromI8",
[369] = "VarBstrFromUI8",
[370] = "VarBoolFromI8",
[371] = "VarBoolFromUI8",
[372] = "VarUI1FromI8",
[373] = "VarUI1FromUI8",
[374] = "VarDecFromI8",
[375] = "VarDecFromUI8",
[376] = "VarI1FromI8",
[377] = "VarI1FromUI8",
[378] = "VarUI2FromI8",
[379] = "VarUI2FromUI8",
[380] = "VARIANT_UserSize64",
[381] = "VARIANT_UserUnmarshal64",
[401] = "OleLoadPictureEx",
[402] = "OleLoadPictureFileEx",
[411] = "SafeArrayCreateVector",
[412] = "SafeArrayCopyData",
[413] = "VectorFromBstr",
[414] = "BstrFromVector",
[415] = "OleIconToCursor",
[416] = "OleCreatePropertyFrameIndirect",
[417] = "OleCreatePropertyFrame",
[418] = "OleLoadPicture",
[419] = "OleCreatePictureIndirect",
[420] = "OleCreateFontIndirect",
[421] = "OleTranslateColor",
[422] = "OleLoadPictureFile",
[423] = "OleSavePictureFile",
[424] = "OleLoadPicturePath",
[425] = "VarUI4FromI8",
[426] = "VarUI4FromUI8",
[427] = "VarI8FromUI8",
[428] = "VarUI8FromI8",
[429] = "VarUI8FromUI1",
[430] = "VarUI8FromI2",
[431] = "VarUI8FromR4",
[432] = "VarUI8FromR8",
[433] = "VarUI8FromCy",
[434] = "VarUI8FromDate",
[435] = "VarUI8FromStr",
[436] = "VarUI8FromDisp",
[437] = "VarUI8FromBool",
[438] = "VarUI8FromI1",
[439] = "VarUI8FromUI2",
[440] = "VarUI8FromUI4",
[441] = "VarUI8FromDec",
[442] = "RegisterTypeLibForUser",
[443] = "UnRegisterTypeLibForUser",
[444] = "OaEnablePerUserTLibRegistration",
[445] = "HWND_UserFree",
[446] = "HWND_UserMarshal",
[447] = "HWND_UserSize",
[448] = "HWND_UserUnmarshal",
[449] = "HWND_UserFree64",
[450] = "HWND_UserMarshal64",
[451] = "HWND_UserSize64",
[452] = "HWND_UserUnmarshal64",
[500] = "OACleanup",
};
private static readonly Dictionary<string, Dictionary<uint, string>> _staticMappings = new()
{
["ws2_32"] = _ws2_32OrdinalMapping,
["oleaut32"] = _oleaut32OrdinalMapping,
};
/// <summary>
/// Gets the singleton instance for the <see cref="DefaultSymbolResolver"/> class.
/// </summary>
public static DefaultSymbolResolver Instance
{
get;
} = new();
private DefaultSymbolResolver()
{
}
/// <inheritdoc />
public ExportedSymbol? Resolve(ImportedSymbol symbol)
{
if (symbol.DeclaringModule?.Name is null)
return null;
string moduleName = symbol.DeclaringModule.Name;
if (moduleName.EndsWith(".dll"))
moduleName = moduleName.Remove(moduleName.Length - 4);
if (!_staticMappings.TryGetValue(moduleName, out var staticMapping))
return null;
return staticMapping.TryGetValue(symbol.Ordinal, out string? exportName)
? new ExportedSymbol(SegmentReference.Null, exportName)
: null;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Imports\ImportHashTest.cs | AsmResolver.PE.Tests.Imports
| ImportHashTest | [] | ['AsmResolver.PE.Imports', 'Xunit'] | xUnit | net8.0 | public class ImportHashTest
{
[Fact]
public void SimpleDllImportHash()
{
var image = PEImage.FromBytes(Properties.Resources.SimpleDll, TestReaderParameters);
byte[] hash = image.GetImportHash();
Assert.Equal(new byte[]
{
0xf4, 0x69, 0x90, 0x30, 0xd0, 0xf3, 0xc7, 0x7a, 0xdc, 0x12, 0x05, 0xa3, 0xd1, 0xee, 0xdb, 0x3b,
}, hash);
}
} | 94 | 554 | using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using AsmResolver.Shims;
namespace AsmResolver.PE.Imports
{
/// <summary>
/// Provides an implementation of the import hash (ImpHash) introduced by Mandiant.
///
/// Reference:
/// https://www.fireeye.com/blog/threat-research/2014/01/tracking-malware-import-hashing.html
/// </summary>
public static class ImportHash
{
private static readonly string[] Extensions = { ".dll", ".sys", ".ocx" };
/// <summary>
/// Computes the hash of all imported symbols.
/// </summary>
/// <param name="image">The image to get the import hash from.</param>
/// <returns>The hash.</returns>
/// <remarks>
/// This is the ImpHash as introduced by Mandiant.
/// Reference: https://www.fireeye.com/blog/threat-research/2014/01/tracking-malware-import-hashing.html
/// </remarks>
public static byte[] GetImportHash(this PEImage image) => image.GetImportHash(DefaultSymbolResolver.Instance);
/// <summary>
/// Computes the hash of all imported symbols.
/// </summary>
/// <param name="image">The image to get the import hash from.</param>
/// <param name="symbolResolver">The object responsible for resolving symbols imported by ordinal.</param>
/// <returns>The hash.</returns>
/// <remarks>
/// This is the ImpHash as introduced by Mandiant.
/// Reference: https://www.fireeye.com/blog/threat-research/2014/01/tracking-malware-import-hashing.html
/// </remarks>
public static byte[] GetImportHash(this PEImage image, ISymbolResolver symbolResolver)
{
var elements = new List<string>();
for (int j = 0; j < image.Imports.Count; j++)
{
var module = image.Imports[j];
string formattedModuleName = FormatModuleName(module);
for (int i = 0; i < module.Symbols.Count; i++)
elements.Add($"{formattedModuleName}.{FormatSymbolName(module.Symbols[i], symbolResolver)}");
}
using var md5 = MD5.Create();
return md5.ComputeHash(Encoding.ASCII.GetBytes(StringShim.Join(",", elements)));
}
private static string FormatModuleName(ImportedModule module)
{
string name = module.Name!;
if (string.IsNullOrEmpty(name))
return name;
foreach (string extension in Extensions)
{
if (name.EndsWith(extension))
{
name = name.Remove(name.Length - extension.Length);
break;
}
}
return name.ToLowerInvariant();
}
private static string FormatSymbolName(ImportedSymbol symbol, ISymbolResolver symbolResolver)
{
if (symbol.IsImportByName)
return symbol.Name.ToLowerInvariant();
var resolvedSymbol = symbolResolver.Resolve(symbol);
if (resolvedSymbol is null)
throw new ArgumentException($"Failed to resolve {symbol}.");
if (!resolvedSymbol.IsByName)
throw new ArgumentException($"Resolved export for {symbol} has no name.");
return resolvedSymbol.Name.ToLowerInvariant();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Relocations\BaseRelocationTest.cs | AsmResolver.PE.Tests.Relocations
| BaseRelocationTest | [] | ['AsmResolver.PE.Relocations', 'Xunit'] | xUnit | net8.0 | public class BaseRelocationTest
{
[Fact]
public void DotNetHelloWorld()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Equal(new[]
{
new BaseRelocation(RelocationType.HighLow, new VirtualAddress(0x2690)),
new BaseRelocation(RelocationType.Absolute, new VirtualAddress(0x2000)),
}, peImage.Relocations);
}
} | 102 | 592 | using System;
namespace AsmResolver.PE.Relocations
{
/// <summary>
/// Represents a single base relocation that is applied after the operating system has loaded the PE image into
/// memory.
/// </summary>
public readonly struct BaseRelocation
{
/// <summary>
/// Creates a new base relocation.
/// </summary>
/// <param name="type">The type of base relocation to apply.</param>
/// <param name="location">The location within the executable to apply the base relocation.</param>
public BaseRelocation(RelocationType type, ISegmentReference location)
{
Type = type;
Location = location ?? throw new ArgumentNullException(nameof(location));
}
/// <summary>
/// Gets the type of relocation to apply.
/// </summary>
public RelocationType Type
{
get;
}
/// <summary>
/// Gets the location within the executable to apply the relocation to.
/// </summary>
public ISegmentReference Location
{
get;
}
/// <inheritdoc />
public override string ToString()
{
return $"{Location.Rva:X8} ({Type})";
}
/// <summary>
/// Determines whether two base relocations are considered equal.
/// </summary>
/// <param name="other">The other base relocation.</param>
/// <returns><c>true</c> if the base relocations are equal, <c>false</c> otherwise.</returns>
/// <remarks>
/// This method only considers the virtual address (RVA) of the target location, and not the entire
/// <see cref="ISegmentReference"/> member.
/// </remarks>
public bool Equals(BaseRelocation other)
{
return Type == other.Type && Location.Rva == other.Location.Rva;
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is BaseRelocation other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
return ((int) Type * 397) ^ (int) Location.Rva;
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Tls\TlsDirectoryTest.cs | AsmResolver.PE.Tests.Tls
| TlsDirectoryTest | [] | ['System.IO', 'AsmResolver.PE.File', 'AsmResolver.PE.Tls', 'Xunit'] | xUnit | net8.0 | public class TlsDirectoryTest
{
[Fact]
public void ReadTemplateDataX86()
{
var image = PEImage.FromBytes(Properties.Resources.TlsTest_x86, TestReaderParameters);
Assert.Equal(new byte[]
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F,
0x72, 0x6C, 0x64, 0x21, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
}, image.TlsDirectory!.TemplateData!.ToArray());
}
[Fact]
public void ReadTemplateDataX64()
{
var image = PEImage.FromBytes(Properties.Resources.TlsTest_x64, TestReaderParameters);
Assert.Equal(new byte[]
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0x00, 0x00, 0x00, 0x00,
0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21, 0x0A, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00
}, image.TlsDirectory!.TemplateData!.ToArray());
}
[Fact]
public void ReadCallbacksTableX86()
{
var image = PEImage.FromBytes(Properties.Resources.TlsTest_x86, TestReaderParameters);
Assert.Single(image.TlsDirectory!.CallbackFunctions);
}
[Fact]
public void ReadCallbacksTableX64()
{
var image = PEImage.FromBytes(Properties.Resources.TlsTest_x64, TestReaderParameters);
Assert.Single(image.TlsDirectory!.CallbackFunctions);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Persistent(bool is32Bit)
{
// Build PE file skeleton.
var text = new PESection(".text",
SectionFlags.ContentCode | SectionFlags.MemoryExecute | SectionFlags.MemoryRead);
var textBuilder = new SegmentBuilder();
text.Contents = textBuilder;
var rdata = new PESection(".rdata",
SectionFlags.ContentInitializedData | SectionFlags.MemoryRead);
var rdataBuilder = new SegmentBuilder();
rdata.Contents = rdataBuilder;
var data = new PESection(".data",
SectionFlags.ContentInitializedData | SectionFlags.MemoryRead | SectionFlags.MemoryWrite);
var dataBuilder = new SegmentBuilder();
data.Contents = dataBuilder;
var tls = new PESection(".tls",
SectionFlags.ContentInitializedData | SectionFlags.MemoryRead | SectionFlags.MemoryWrite);
var tlsBuilder = new SegmentBuilder();
tls.Contents = tlsBuilder;
var file = new PEFile
{
FileHeader =
{
Machine = is32Bit ? MachineType.I386 : MachineType.Amd64,
},
OptionalHeader =
{
Magic = is32Bit ? OptionalHeaderMagic.PE32 : OptionalHeaderMagic.PE32Plus
},
Sections =
{
text,
rdata,
data,
tls
},
};
// Create dummy functions and TLS data.
var callbackFunction1 = new DataSegment(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 });
var callbackFunction2 = new DataSegment(new byte[] { 8, 9, 10, 11, 12, 13, 14, 15 });
var indexSegment = new DataSegment(new byte[] { 30, 31, 32, 33, 34, 35, 36, 37 });
var templateData = new DataSegment(new byte[] { 20, 21, 22, 23, 24, 25, 26, 27 });
var directory = new TlsDirectory
{
TemplateData = templateData,
Index = indexSegment.ToReference(),
Characteristics = TlsCharacteristics.Align4Bytes,
CallbackFunctions =
{
callbackFunction1.ToReference(),
callbackFunction2.ToReference(),
}
};
// Put dummy data into the sections.
textBuilder.Add(callbackFunction1, 4);
textBuilder.Add(callbackFunction2, 4);
rdataBuilder.Add(directory);
rdataBuilder.Add(directory.CallbackFunctions);
dataBuilder.Add(indexSegment);
tlsBuilder.Add(directory.TemplateData);
// Update TLS directory.
file.UpdateHeaders();
file.OptionalHeader.DataDirectories[(int) DataDirectoryIndex.TlsDirectory] =
new DataDirectory(directory.Rva, directory.GetPhysicalSize());
// Write.
using var s = new MemoryStream();
file.Write(s);
// Read.
var image = PEImage.FromBytes(s.ToArray(), TestReaderParameters);
var newDirectory = image.TlsDirectory!;
Assert.NotNull(newDirectory);
// Verify.
Assert.Equal(2, newDirectory.CallbackFunctions.Count);
byte[] buffer = new byte[8];
Assert.Equal(buffer.Length, newDirectory.Index.CreateReader().ReadBytes(buffer, 0, buffer.Length));
Assert.Equal(indexSegment.Data, buffer);
Assert.NotNull(newDirectory.TemplateData);
Assert.Equal(templateData.Data, newDirectory.TemplateData!.ToArray());
Assert.Equal(buffer.Length, newDirectory.CallbackFunctions[0].CreateReader().ReadBytes(buffer, 0, buffer.Length));
Assert.Equal(callbackFunction1.Data, buffer);
Assert.Equal(buffer.Length, newDirectory.CallbackFunctions[1].CreateReader().ReadBytes(buffer, 0, buffer.Length));
Assert.Equal(callbackFunction2.Data, buffer);
}
} | 132 | 13,236 | using AsmResolver.Collections;
using AsmResolver.IO;
using AsmResolver.PE.File;
namespace AsmResolver.PE.Tls
{
/// <summary>
/// Provides an implementation of a TLS directory that was read from an existing PE file.
/// </summary>
public class SerializedTlsDirectory : TlsDirectory
{
private readonly PEReaderContext _context;
private readonly ulong _templateStart;
private readonly ulong _templateEnd;
private readonly ulong _addressOfCallbacks;
/// <summary>
/// Reads a single TLS directory from an input stream.
/// </summary>
/// <param name="context">The reader context.</param>
/// <param name="reader">The input stream.</param>
public SerializedTlsDirectory(PEReaderContext context, ref BinaryStreamReader reader)
{
_context = context;
var relocation = context.GetRelocation(reader.Offset, reader.Rva);
_templateStart = reader.ReadNativeInt(relocation.Is32Bit);
_templateEnd = reader.ReadNativeInt(relocation.Is32Bit);
Index = context.File.GetReferenceToRva((uint)(reader.ReadNativeInt(relocation.Is32Bit) - relocation.ImageBase));
_addressOfCallbacks = reader.ReadNativeInt(relocation.Is32Bit);
SizeOfZeroFill = reader.ReadUInt32();
Characteristics = (TlsCharacteristics) reader.ReadUInt32();
UpdateOffsets(relocation);
}
/// <inheritdoc />
protected override IReadableSegment? GetTemplateData()
{
if (_templateEnd < _templateStart)
{
return _context.BadImageAndReturn<IReadableSegment>(
"End address of TLS template data is smaller than the start address.");
}
ulong imageBase = _context.File.OptionalHeader.ImageBase;
if (!_context.File.TryCreateReaderAtRva((uint) (_templateStart - imageBase), out var reader))
{
return _context.BadImageAndReturn<IReadableSegment>(
$"TLS template data start address 0x{_templateStart:X8} is invalid.");
}
uint length = (uint) (_templateEnd - _templateStart);
if (!reader.CanRead(length))
{
return _context.BadImageAndReturn<IReadableSegment>(
$"TLS template data end address 0x{_templateEnd:X8} is invalid.");
}
return reader.ReadSegment(length);
}
/// <inheritdoc />
protected override ReferenceTable GetCallbackFunctions()
{
var result = base.GetCallbackFunctions();
var file = _context.File;
var optionalHeader = file.OptionalHeader;
ulong imageBase = optionalHeader.ImageBase;
bool is32Bit = optionalHeader.Magic == OptionalHeaderMagic.PE32;
if (!file.TryCreateReaderAtRva((uint) (_addressOfCallbacks - imageBase), out var reader))
{
_context.BadImage($"TLS callback function table start address 0x{_addressOfCallbacks:X8} is invalid.");
return result;
}
while (true)
{
if (!reader.CanRead((uint) (is32Bit ? sizeof(uint) : sizeof(ulong))))
{
_context.BadImage($"TLS callback function table does not end with a zero entry.");
break;
}
ulong address = reader.ReadNativeInt(is32Bit);
if (address == 0)
break;
result.Add(file.GetReferenceToRva((uint) (address - imageBase)));
}
return result;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Win32Resources\ResourceDataTest.cs | AsmResolver.PE.Tests.Win32Resources
| ResourceDataTest | [] | ['AsmResolver.PE.Win32Resources', 'Xunit'] | xUnit | net8.0 | public class ResourceDataTest
{
[Fact]
public void ResourceDataConstructorShouldSetId()
{
var data = new ResourceData(1, new DataSegment(new byte[0]));
Assert.Equal(1u, data.Id);
}
[Fact]
public void ResourceDataConstructorShouldSetContents()
{
var rawData = new byte[]
{
1, 2, 3, 4
};
var data = new ResourceData(1, new DataSegment(rawData));
var readableContents = Assert.IsAssignableFrom<IReadableSegment>(data.Contents);
Assert.Equal(rawData, readableContents.CreateReader().ReadToEnd());
}
} | 108 | 811 | using System;
using System.Diagnostics.CodeAnalysis;
using AsmResolver.Collections;
using AsmResolver.IO;
namespace AsmResolver.PE.Win32Resources
{
/// <summary>
/// Represents a single data entry in a Win32 resource directory.
/// </summary>
public class ResourceData : IResourceEntry
{
private readonly LazyVariable<ResourceData, ISegment?> _contents;
/// <summary>
/// Initializes a new resource data entry.
/// </summary>
protected ResourceData()
{
_contents = new LazyVariable<ResourceData, ISegment?>(x => x.GetContents());
}
/// <summary>
/// Creates a new named data entry.
/// </summary>
/// <param name="name">The name of the entry.</param>
/// <param name="contents">The data to store in the entry.</param>
public ResourceData(string name, ISegment contents)
: this()
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Contents = contents ?? throw new ArgumentNullException(nameof(contents));
}
/// <summary>
/// Creates a new data entry defined by a numerical identifier..
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="contents">The data to store in the entry.</param>
public ResourceData(uint id, ISegment contents)
: this()
{
Id = id;
Contents = contents ?? throw new ArgumentNullException(nameof(contents));
}
/// <inheritdoc />
public ResourceDirectory? ParentDirectory
{
get;
private set;
}
ResourceDirectory? IOwnedCollectionElement<ResourceDirectory>.Owner
{
get => ParentDirectory;
set => ParentDirectory = value;
}
/// <inheritdoc />
public string? Name
{
get;
set;
}
/// <inheritdoc />
public uint Id
{
get;
set;
}
/// <inheritdoc />
bool IResourceEntry.IsDirectory => false;
/// <inheritdoc />
bool IResourceEntry.IsData => true;
/// <summary>
/// Gets or sets the raw contents of the data entry.
/// </summary>
public ISegment? Contents
{
get => _contents.GetValue(this);
set => _contents.SetValue(value);
}
/// <summary>
/// Gets or sets the code page that is used to decode code point values within the resource data.
/// </summary>
/// <remarks>
/// Typically, the code page would be the Unicode code page.
/// </remarks>
public uint CodePage
{
get;
set;
}
/// <summary>
/// Gets a value indicating whether the <see cref="Contents"/> is readable using a binary stream reader.
/// </summary>
[MemberNotNullWhen(true, nameof(Contents))]
public bool CanRead => Contents is IReadableSegment;
/// <summary>
/// Creates a new binary stream reader that reads the raw contents of the resource file.
/// </summary>
/// <returns>The reader.</returns>
public BinaryStreamReader CreateReader()
{
return Contents is IReadableSegment readableSegment
? readableSegment.CreateReader()
: throw new InvalidOperationException("Resource file is not readable.");
}
/// <summary>
/// Obtains the contents of the data entry.
/// </summary>
/// <returns>The contents.</returns>
/// <remarks>
/// This method is called upon initializing the value for the <see cref="Contents"/> property.
/// </remarks>
protected virtual ISegment? GetContents() => null;
/// <inheritdoc />
public override string ToString() => $"Data ({Name ?? Id.ToString()})";
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\AsmResolver.PE.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Tests\Win32Resources\ResourceDirectoryTest.cs | AsmResolver.PE.Tests.Win32Resources
| ResourceDirectoryTest | ['public uint Id { get; set; }', 'public string? Name { get; set; }', 'public bool IsData { get; set; }', 'public IList<ResourceEntryInfo> Entries { get; } = new List<ResourceEntryInfo>();'] | ['System.Collections.Generic', 'System.Linq', 'AsmResolver.PE.Win32Resources', 'Xunit'] | xUnit | net8.0 | public class ResourceDirectoryTest
{
private class ResourceEntryInfo
{
public ResourceEntryInfo(uint id)
{
Id = id;
}
public ResourceEntryInfo(string name)
{
Name = name;
}
public uint Id { get; set; }
public string? Name { get; set; }
public bool IsData { get; set; }
public IList<ResourceEntryInfo> Entries { get; } = new List<ResourceEntryInfo>();
}
private void AssertStructure(ResourceEntryInfo expectedStructure, IResourceEntry directory)
{
var expectedStack = new Stack<ResourceEntryInfo>();
var stack = new Stack<IResourceEntry>();
expectedStack.Push(expectedStructure);
stack.Push(directory);
while (stack.Count > 0)
{
var expected = expectedStack.Pop();
var current = stack.Pop();
Assert.Equal(expected.Name, current.Name);
Assert.Equal(expected.Id, current.Id);
if (expected.IsData)
{
Assert.IsAssignableFrom<ResourceData>(current);
}
else
{
Assert.IsAssignableFrom<ResourceDirectory>(current);
var subEntries = ((ResourceDirectory) current).Entries;
Assert.Equal(expected.Entries.Count, subEntries.Count);
for (int i = 0; i < subEntries.Count; i++)
{
expectedStack.Push(expected.Entries[i]);
stack.Push(subEntries[i]);
}
}
}
}
[Fact]
public void DotNetHelloWorld()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var expected = new ResourceEntryInfo(0)
{
Entries =
{
new ResourceEntryInfo(16)
{
Entries =
{
new ResourceEntryInfo(1)
{
Entries =
{
new ResourceEntryInfo(0) {IsData = true}
}
}
}
},
new ResourceEntryInfo(24)
{
Entries =
{
new ResourceEntryInfo(1)
{
Entries =
{
new ResourceEntryInfo(0) { IsData = true }
}
}
}
}
}
};
AssertStructure(expected, peImage.Resources!);
}
[Fact]
public void MaliciousSelfLoop()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld_MaliciousWin32ResLoop,
new PEReaderParameters(EmptyErrorListener.Instance));
const int maxDirCount = 20;
int dirCount = 0;
var stack = new Stack<IResourceEntry>();
stack.Push(peImage.Resources!);
while (stack.Count > 0)
{
var current = stack.Pop();
if (current.IsDirectory)
{
Assert.True(dirCount < maxDirCount, "Traversal reached limit of resource directories.");
dirCount++;
foreach (var entry in ((ResourceDirectory) current).Entries)
stack.Push(entry);
}
}
}
[Fact]
public void MaliciousDirectoryName()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld_MaliciousWin32ResDirName,
new PEReaderParameters(EmptyErrorListener.Instance));
Assert.Null(peImage.Resources!.Entries[0].Name);
}
[Fact]
public void MaliciousDirectoryOffset()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld_MaliciousWin32ResDirOffset,
new PEReaderParameters(EmptyErrorListener.Instance));
var entry = peImage.Resources!.Entries[0];
Assert.Equal(16u, entry.Id);
Assert.True(entry.IsDirectory);
var directory = (ResourceDirectory) entry;
Assert.Empty(directory.Entries);
}
[Fact]
public void MaliciousDataOffset()
{
var peImage = PEImage.FromBytes(Properties.Resources.HelloWorld_MaliciousWin32ResDataOffset,
new PEReaderParameters(EmptyErrorListener.Instance));
var directory = (ResourceDirectory) peImage.Resources!.Entries[0];
directory = (ResourceDirectory) directory.Entries[0];
var data = (ResourceData) directory.Entries[0];
Assert.Null(data.Contents);
}
[Fact]
public void GetNonExistingDirectory()
{
var root = new ResourceDirectory(0u);
Assert.Throws<KeyNotFoundException>(() => root.GetDirectory(1));
Assert.False(root.TryGetDirectory(1, out _));
}
[Fact]
public void GetNonExistingData()
{
var root = new ResourceDirectory(0u);
Assert.Throws<KeyNotFoundException>(() => root.GetData(1));
Assert.False(root.TryGetData(1, out _));
}
[Fact]
public void GetExistingDirectory()
{
var root = new ResourceDirectory(0u);
var stringDirectory = new ResourceDirectory(ResourceType.String);
root.Entries.Add(stringDirectory);
Assert.Same(stringDirectory, root.GetDirectory(ResourceType.String));
Assert.Same(stringDirectory, root.GetDirectory((uint) ResourceType.String));
Assert.True(root.TryGetDirectory(ResourceType.String, out var result));
Assert.Same(stringDirectory, result);
Assert.True(root.TryGetDirectory((uint) ResourceType.String, out result));
Assert.Same(stringDirectory, result);
Assert.Throws<KeyNotFoundException>(() => root.GetData((uint) ResourceType.String));
Assert.False(root.TryGetData((uint) ResourceType.String, out _));
}
[Fact]
public void GetExistingData()
{
var root = new ResourceDirectory(0u);
var dataEntry = new ResourceData(1234u, new DataSegment(new byte[] { 1, 2, 3, 4 }));
root.Entries.Add(dataEntry);
Assert.Throws<KeyNotFoundException>(() => root.GetDirectory(1234u));
Assert.False(root.TryGetDirectory(1234u, out _));
Assert.Same(dataEntry, root.GetData(1234u));
Assert.True(root.TryGetData(1234u, out var result));
Assert.Same(dataEntry, result);
}
[Fact]
public void AddNewDirectory()
{
var root = new ResourceDirectory(0u);
Assert.Empty(root.Entries);
var directory = new ResourceDirectory(ResourceType.String);
root.InsertOrReplaceEntry(directory);
Assert.Same(directory, Assert.Single(root.Entries));
}
[Fact]
public void AddSecondDirectory()
{
var root = new ResourceDirectory(0u)
{
Entries = { new ResourceDirectory(1234u) }
};
Assert.Single(root.Entries);
var directory = new ResourceDirectory(5678u);
root.InsertOrReplaceEntry(directory);
Assert.Equal(2, root.Entries.Count);
}
[Fact]
public void ReplaceDirectoryWithDirectory()
{
var root = new ResourceDirectory(0u)
{
Entries = { new ResourceDirectory(1234u) }
};
var oldDirectory = root.GetDirectory(1234u);
var newDirectory = new ResourceDirectory(1234u);
root.InsertOrReplaceEntry(newDirectory);
Assert.NotSame(oldDirectory, root.GetEntry(1234u));
Assert.Same(newDirectory, Assert.Single(root.Entries));
}
[Fact]
public void ReplaceDirectoryWithData()
{
var root = new ResourceDirectory(0u)
{
Entries = { new ResourceDirectory(1234u) }
};
var oldDirectory = root.GetDirectory(1234u);
var newEntry = new ResourceData(1234u, new DataSegment(new byte[] { 1, 2, 3, 4 }));
root.InsertOrReplaceEntry(newEntry);
Assert.NotSame(oldDirectory, root.GetEntry(1234u));
Assert.Same(newEntry, Assert.Single(root.Entries));
}
[Fact]
public void RemoveNonExistingEntry()
{
var root = new ResourceDirectory(0u)
{
Entries = { new ResourceDirectory(1234u) }
};
Assert.False(root.RemoveEntry(5678u));
Assert.Single(root.Entries);
}
[Fact]
public void RemoveExistingEntry()
{
var root = new ResourceDirectory(0u)
{
Entries =
{
new ResourceDirectory(1234u),
new ResourceDirectory(5678u)
}
};
Assert.True(root.RemoveEntry(1234u));
Assert.Single(root.Entries);
}
[Theory]
[InlineData(ResourceType.Icon, new[] {ResourceType.Icon, ResourceType.String, ResourceType.Version})]
[InlineData(ResourceType.RcData, new[] {ResourceType.String, ResourceType.RcData, ResourceType.Version})]
[InlineData(ResourceType.Manifest, new[] {ResourceType.String, ResourceType.Version, ResourceType.Manifest})]
[InlineData(ResourceType.String, new[] {ResourceType.String, ResourceType.Version})]
public void InsertShouldPreserveOrder(ResourceType insertedEntry, ResourceType[] expected)
{
var image = new PEImage();
image.Resources = new ResourceDirectory(0u);
image.Resources.Entries.Add(new ResourceDirectory(ResourceType.String));
image.Resources.Entries.Add(new ResourceDirectory(ResourceType.Version));
image.Resources.InsertOrReplaceEntry(new ResourceDirectory(insertedEntry));
Assert.Equal(expected, image.Resources.Entries.Select(x => (ResourceType) x.Id));
}
} | 163 | 11,337 | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using AsmResolver.Collections;
namespace AsmResolver.PE.Win32Resources
{
/// <summary>
/// Represents a single directory containing Win32 resources of a PE image.
/// </summary>
public class ResourceDirectory : IResourceEntry
{
private IList<IResourceEntry>? _entries;
/// <summary>
/// Initializes a new resource directory entry.
/// </summary>
protected ResourceDirectory()
{
}
/// <summary>
/// Creates a new named resource directory.
/// </summary>
/// <param name="name">The name of the directory.</param>
public ResourceDirectory(string name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
}
/// <summary>
/// Creates a new resource directory defined by a numeric identifier.
/// </summary>
/// <param name="id">The identifier.</param>
public ResourceDirectory(uint id)
{
Id = id;
}
/// <summary>
/// Creates a new resource directory defined by its resource type.
/// </summary>
/// <param name="type">The type.</param>
public ResourceDirectory(ResourceType type)
{
Type = type;
}
/// <inheritdoc />
public ResourceDirectory? ParentDirectory
{
get;
private set;
}
ResourceDirectory? IOwnedCollectionElement<ResourceDirectory>.Owner
{
get => ParentDirectory;
set => ParentDirectory = value;
}
/// <inheritdoc />
public string? Name
{
get;
set;
}
/// <inheritdoc />
public uint Id
{
get;
set;
}
/// <inheritdoc />
bool IResourceEntry.IsDirectory => true;
/// <inheritdoc />
bool IResourceEntry.IsData => false;
/// <summary>
/// Gets the type of resources stored in the directory.
/// </summary>
public ResourceType Type
{
get => (ResourceType) Id;
set => Id = (uint) value;
}
/// <summary>
/// Gets or sets the flags of the directory.
/// </summary>
/// <remarks>
/// This field is reserved and is usually set to zero.
/// </remarks>
public uint Characteristics
{
get;
set;
}
/// <summary>
/// Gets or sets the time that the resource data was created by the compiler.
/// </summary>
public uint TimeDateStamp
{
get;
set;
}
/// <summary>
/// Gets or sets the major version number of the directory.
/// </summary>
public ushort MajorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the minor version number of the directory.
/// </summary>
public ushort MinorVersion
{
get;
set;
}
/// <summary>
/// Gets a collection of entries that are stored in the directory.
/// </summary>
public IList<IResourceEntry> Entries
{
get
{
if (_entries is null)
Interlocked.CompareExchange(ref _entries, GetEntries(), null);
return _entries;
}
}
private bool TryGetEntryIndex(uint id, out int index)
{
for (int i = 0; i < Entries.Count; i++)
{
var candidate = Entries[i];
if (candidate.Id == id)
{
index = i;
return true;
}
if (candidate.Id > id)
{
index = i;
return false;
}
}
index = Entries.Count;
return false;
}
/// <summary>
/// Looks up an entry in the directory by its unique identifier.
/// </summary>
/// <param name="id">The identifier of the entry to lookup.</param>
/// <returns>The entry.</returns>
/// <exception cref="KeyNotFoundException">
/// Occurs when no entry with the provided identifier was found.
/// </exception>
public IResourceEntry GetEntry(uint id)
{
if (!TryGetEntry(id, out var entry))
throw new KeyNotFoundException($"Directory does not contain an entry with id {id}.");
return entry;
}
/// <summary>
/// Looks up an directory by its unique identifier.
/// </summary>
/// <param name="id">The identifier of the directory to lookup.</param>
/// <returns>The directory.</returns>
/// <exception cref="KeyNotFoundException">
/// Occurs when no directory with the provided identifier was found.
/// </exception>
public ResourceDirectory GetDirectory(uint id)
{
if (!TryGetDirectory(id, out var directory))
throw new KeyNotFoundException($"Directory does not contain a directory with id {id}.");
return directory;
}
/// <summary>
/// Looks up an directory by its resource type.
/// </summary>
/// <param name="type">The type of resources to lookup.</param>
/// <returns>The directory.</returns>
/// <exception cref="KeyNotFoundException">
/// Occurs when no directory with the provided identifier was found.
/// </exception>
public ResourceDirectory GetDirectory(ResourceType type)
{
if (!TryGetDirectory(type, out var directory))
throw new KeyNotFoundException($"Directory does not contain a directory of type {type}.");
return directory;
}
/// <summary>
/// Looks up a data entry in the directory by its unique identifier.
/// </summary>
/// <param name="id">The id of the data entry to lookup.</param>
/// <returns>The data entry.</returns>
/// <exception cref="KeyNotFoundException">
/// Occurs when no data entry with the provided identifier was found.
/// </exception>
public ResourceData GetData(uint id)
{
if (!TryGetData(id, out var data))
throw new KeyNotFoundException($"Directory does not contain a data entry with id {id}.");
return data;
}
/// <summary>
/// Attempts to looks up an entry in the directory by its unique identifier.
/// </summary>
/// <param name="id">The identifier of the entry to lookup.</param>
/// <param name="entry">The found entry, or <c>null</c> if none was found.</param>
/// <returns><c>true</c> if the entry was found, <c>false</c> otherwise.</returns>
public bool TryGetEntry(uint id, [NotNullWhen(true)] out IResourceEntry? entry)
{
if (!TryGetEntryIndex(id, out int index))
{
entry = null;
return false;
}
entry = Entries[index];
return true;
}
/// <summary>
/// Attempts to looks up a directory by its unique identifier.
/// </summary>
/// <param name="id">The identifier of the directory to lookup.</param>
/// <param name="directory">The found directory, or <c>null</c> if none was found.</param>
/// <returns><c>true</c> if the directory was found, <c>false</c> otherwise.</returns>
public bool TryGetDirectory(uint id, [NotNullWhen(true)] out ResourceDirectory? directory)
{
if (TryGetEntry(id, out var entry) && entry.IsDirectory)
{
directory = (ResourceDirectory) entry;
return true;
}
directory = null;
return false;
}
/// <summary>
/// Attempts to looks up a directory by its resource type.
/// </summary>
/// <param name="type">The type of resources to lookup.</param>
/// <param name="directory">The found directory, or <c>null</c> if none was found.</param>
/// <returns><c>true</c> if the directory was found, <c>false</c> otherwise.</returns>
public bool TryGetDirectory(ResourceType type, [NotNullWhen(true)] out ResourceDirectory? directory) =>
TryGetDirectory((uint) type, out directory);
/// <summary>
/// Attempts to looks up a data entry in the directory by its unique identifier.
/// </summary>
/// <param name="id">The identifier of the data entry to lookup.</param>
/// <param name="data">The found data entry, or <c>null</c> if none was found.</param>
/// <returns><c>true</c> if the data entry was found, <c>false</c> otherwise.</returns>
public bool TryGetData(uint id, [NotNullWhen(true)] out ResourceData? data)
{
if (TryGetEntry(id, out var entry) && entry.IsData)
{
data = (ResourceData) entry;
return true;
}
data = null;
return false;
}
/// <summary>
/// Replaces an existing entry with the same ID with the provided entry, or inserts the new entry into the directory.
/// </summary>
/// <param name="entry">The entry to store in the directory.</param>
public void InsertOrReplaceEntry(IResourceEntry entry)
{
if (TryGetEntryIndex(entry.Id, out int index))
Entries[index] = entry;
else
Entries.Insert(index, entry);
}
/// <summary>
/// Removes an entry in the directory by its unique identifier.
/// </summary>
/// <param name="id">The identifier of the entry to remove.</param>
/// <returns><c>true</c> if the data entry was found and removed, <c>false</c> otherwise.</returns>
public bool RemoveEntry(uint id)
{
if (!TryGetEntryIndex(id, out int index))
return false;
Entries.RemoveAt(index);
return true;
}
/// <summary>
/// Removes a directory in the directory by its resource type.
/// </summary>
/// <param name="type">The type of resources to remove.</param>
/// <returns><c>true</c> if the directory was found and removed, <c>false</c> otherwise.</returns>
public bool RemoveEntry(ResourceType type) => RemoveEntry((uint) type);
/// <summary>
/// Obtains the list of entries in the directory.
/// </summary>
/// <returns>The list of entries.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Entries"/> property.
/// </remarks>
protected virtual IList<IResourceEntry> GetEntries() =>
new OwnedCollection<ResourceDirectory, IResourceEntry>(this);
/// <inheritdoc />
public override string ToString() => $"Directory ({Name ?? Id.ToString()})";
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AssemblyDefinitionTest.cs | AsmResolver.DotNet.Tests
| AssemblyDefinitionTest | [] | ['System', 'System.IO', 'System.Security.Cryptography', 'AsmResolver.DotNet.Serialized', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.StrongName', 'Xunit'] | xUnit | net8.0 | public class AssemblyDefinitionTest
{
private static AssemblyDefinition Rebuild(AssemblyDefinition assembly)
{
using var stream = new MemoryStream();
assembly.ManifestModule!.Write(stream);
return AssemblyDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
}
[Fact]
public void ReadNameTest()
{
var assemblyDef = AssemblyDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Equal("HelloWorld", assemblyDef.Name);
}
[Fact]
public void NameIsPersistentAfterRebuild()
{
const string newName = "OtherAssembly";
var assemblyDef = AssemblyDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
assemblyDef.Name = newName;
var rebuilt = Rebuild(assemblyDef);
Assert.Equal(newName, rebuilt.Name);
}
[Fact]
public void ReadVersion()
{
var assemblyDef = AssemblyDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Equal(new Version(1,0,0,0), assemblyDef.Version);
}
[Fact]
public void VersionIsPersistentAfterRebuild()
{
var newVersion = new Version(1,2,3,4);
var assemblyDef = AssemblyDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
assemblyDef.Version = newVersion;
var rebuilt = Rebuild(assemblyDef);
Assert.Equal(newVersion, rebuilt.Version);
}
[Fact]
public void ReadSingleModuleAssembly()
{
var assemblyDef = AssemblyDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Single(assemblyDef.Modules);
Assert.NotNull(assemblyDef.ManifestModule);
Assert.Equal(new[] {assemblyDef.ManifestModule}, assemblyDef.Modules);
Assert.Same(assemblyDef, assemblyDef.ManifestModule.Assembly);
}
[Fact]
public void ReadMultiModuleAssembly()
{
var assemblyDef = AssemblyDefinition.FromFile(
Path.Combine("Resources", "Manifest.exe"),
new ModuleReaderParameters("Resources", ThrowErrorListener.Instance)
);
Assert.Equal(2, assemblyDef.Modules.Count);
Assert.Equal("Manifest.exe", assemblyDef.ManifestModule.Name);
Assert.Equal("MyModel.netmodule", assemblyDef.Modules[1].Name);
}
[Fact]
public void ReadSecondaryModuleAsAssemblyShouldThrow()
{
Assert.Throws<BadImageFormatException>(() =>
AssemblyDefinition.FromFile(Path.Combine("Resources", "MyModel.netmodule"), TestReaderParameters));
}
[Fact]
public void ReadPublicKeyToken()
{
var corlibAssembly = typeof(object).Assembly;
var corlibName = corlibAssembly.GetName();
var corlibAssemblyDef = AssemblyDefinition.FromFile(corlibAssembly.Location, TestReaderParameters);
Assert.Equal(corlibName.GetPublicKey(), corlibAssemblyDef.PublicKey);
Assert.Equal(corlibName.GetPublicKeyToken(), corlibAssemblyDef.GetPublicKeyToken());
}
[Fact]
public void PublicKeyIsPersistentAfterRebuild()
{
using var rsa = RSA.Create();
var rsaParameters = rsa.ExportParameters(true);
var snk = new StrongNamePrivateKey(rsaParameters);
var assemblyDef = AssemblyDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
assemblyDef.PublicKey = snk.CreatePublicKeyBlob(assemblyDef.HashAlgorithm);
var rebuilt = Rebuild(assemblyDef);
Assert.Equal(assemblyDef.PublicKey, rebuilt.PublicKey);
}
} | 231 | 4,268 | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.DotNet.Builder;
using AsmResolver.DotNet.Serialized;
using AsmResolver.IO;
using AsmResolver.PE;
using AsmResolver.PE.Builder;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.File;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents an assembly of self-describing modules of an executable file hosted by a common language runtime (CLR).
/// </summary>
public class AssemblyDefinition : AssemblyDescriptor, IModuleProvider, IHasSecurityDeclaration
{
private IList<ModuleDefinition>? _modules;
private IList<SecurityDeclaration>? _securityDeclarations;
private readonly LazyVariable<AssemblyDefinition, byte[]?> _publicKey;
private byte[]? _publicKeyToken;
/// <summary>
/// Reads a .NET assembly from the provided input buffer.
/// </summary>
/// <param name="buffer">The raw contents of the executable file to load.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static AssemblyDefinition FromBytes(byte[] buffer) => FromBytes(buffer, new ModuleReaderParameters());
/// <summary>
/// Reads a .NET assembly from the provided input buffer.
/// </summary>
/// <param name="buffer">The raw contents of the executable file to load.</param>
/// <param name="readerParameters">The parameters to use while reading the assembly.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static AssemblyDefinition FromBytes(byte[] buffer, ModuleReaderParameters readerParameters) =>
FromImage(PEImage.FromBytes(buffer, readerParameters.PEReaderParameters), readerParameters);
/// <summary>
/// Reads a .NET assembly from the provided input file.
/// </summary>
/// <param name="filePath">The file path to the input executable to load.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static AssemblyDefinition FromFile(string filePath)
=> FromFile(filePath, new ModuleReaderParameters(Path.GetDirectoryName(filePath)));
/// <summary>
/// Reads a .NET assembly from the provided input file.
/// </summary>
/// <param name="filePath">The file path to the input executable to load.</param>
/// <param name="readerParameters">The parameters to use while reading the assembly.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static AssemblyDefinition FromFile(string filePath, ModuleReaderParameters readerParameters) =>
FromImage(PEImage.FromFile(filePath, readerParameters.PEReaderParameters), readerParameters);
/// <summary>
/// Reads a .NET assembly from the provided input file.
/// </summary>
/// <param name="file">The portable executable file to load.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static AssemblyDefinition FromFile(PEFile file) => FromFile(file, new ModuleReaderParameters());
/// <summary>
/// Reads a .NET assembly from the provided input file.
/// </summary>
/// <param name="file">The portable executable file to load.</param>
/// <param name="readerParameters">The parameters to use while reading the assembly.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static AssemblyDefinition FromFile(PEFile file, ModuleReaderParameters readerParameters) =>
FromImage(PEImage.FromFile(file, readerParameters.PEReaderParameters), readerParameters);
/// <summary>
/// Reads a .NET assembly from the provided input file.
/// </summary>
/// <param name="file">The portable executable file to load.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static AssemblyDefinition FromFile(IInputFile file) =>
FromFile(file, new ModuleReaderParameters(Path.GetDirectoryName(file.FilePath)));
/// <summary>
/// Reads a .NET assembly from the provided input file.
/// </summary>
/// <param name="file">The portable executable file to load.</param>
/// <param name="readerParameters">The parameters to use while reading the assembly.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static AssemblyDefinition FromFile(IInputFile file, ModuleReaderParameters readerParameters) =>
FromImage(PEImage.FromFile(file, readerParameters.PEReaderParameters), readerParameters);
/// <summary>
/// Reads a .NET assembly from an input stream.
/// </summary>
/// <param name="reader">The input stream pointing at the beginning of the executable to load.</param>
/// <param name="mode">Indicates the input PE is mapped or unmapped.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static AssemblyDefinition FromReader(in BinaryStreamReader reader, PEMappingMode mode = PEMappingMode.Unmapped) =>
FromImage(PEImage.FromReader(reader, mode));
/// <summary>
/// Initializes a .NET assembly from a PE image.
/// </summary>
/// <param name="peImage">The image containing the .NET metadata.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static AssemblyDefinition FromImage(PEImage peImage) =>
FromImage(peImage, new ModuleReaderParameters(Path.GetDirectoryName(peImage.FilePath)));
/// <summary>
/// Initializes a .NET assembly from a PE image.
/// </summary>
/// <param name="peImage">The image containing the .NET metadata.</param>
/// <param name="readerParameters">The parameters to use while reading the assembly.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static AssemblyDefinition FromImage(PEImage peImage, ModuleReaderParameters readerParameters) =>
ModuleDefinition.FromImage(peImage, readerParameters).Assembly
?? throw new BadImageFormatException("The provided PE image does not contain an assembly manifest.");
/// <summary>
/// Initializes a new assembly definition.
/// </summary>
/// <param name="token">The token of the assembly definition.</param>
protected AssemblyDefinition(MetadataToken token)
: base(token)
{
_publicKey = new LazyVariable<AssemblyDefinition, byte[]?>(x => x.GetPublicKey());
}
/// <summary>
/// Creates a new assembly definition.
/// </summary>
/// <param name="name">The name of the assembly.</param>
/// <param name="version">The version of the assembly.</param>
public AssemblyDefinition(Utf8String? name, Version version)
: this(new MetadataToken(TableIndex.Assembly, 0))
{
Name = name;
Version = version;
}
/// <summary>
/// Gets or sets the hashing algorithm that is used to sign the assembly.
/// </summary>
public AssemblyHashAlgorithm HashAlgorithm
{
get;
set;
}
/// <summary>
/// Gets a value indicating whether the assembly contains a manifest module.
/// </summary>
[MemberNotNullWhen(true, nameof(ManifestModule))]
public bool HasManifestModule => ManifestModule is not null;
/// <summary>
/// Gets the main module of the .NET assembly containing the assembly's manifest.
/// </summary>
public ModuleDefinition? ManifestModule => Modules.Count > 0 ? Modules[0] : null;
ModuleDefinition? IModuleProvider.Module => ManifestModule;
/// <summary>
/// Gets a collection of modules that this .NET assembly defines.
/// </summary>
public IList<ModuleDefinition> Modules
{
get
{
if (_modules == null)
Interlocked.CompareExchange(ref _modules, GetModules(), null);
return _modules;
}
}
/// <inheritdoc />
public IList<SecurityDeclaration> SecurityDeclarations
{
get
{
if (_securityDeclarations is null)
Interlocked.CompareExchange(ref _securityDeclarations, GetSecurityDeclarations(), null);
return _securityDeclarations;
}
}
/// <summary>
/// Gets or sets the public key of the assembly to use for verification of a signature.
/// </summary>
/// <remarks>
/// <para>If this value is set to <c>null</c>, no public key will be assigned.</para>
/// <para>This property does not automatically update the <see cref="AssemblyDescriptor.HasPublicKey"/> property.</para>
/// <para>This property corresponds to the Culture column in the assembly definition table.</para>
/// </remarks>
public byte[]? PublicKey
{
get => _publicKey.GetValue(this);
set
{
_publicKey.SetValue(value);
_publicKeyToken = null;
}
}
/// <inheritdoc />
public override bool IsCorLib => Name is not null && KnownCorLibs.KnownCorLibNames.Contains(Name);
/// <summary>
/// Obtains the list of defined modules in the .NET assembly.
/// </summary>
/// <returns>The modules.</returns>
/// <remarks>
/// This method is called upon initializing the <see cref="Modules"/> and/or <see cref="ManifestModule"/> property.
/// </remarks>
protected virtual IList<ModuleDefinition> GetModules()
=> new OwnedCollection<AssemblyDefinition, ModuleDefinition>(this);
/// <summary>
/// Obtains the list of security declarations assigned to the member.
/// </summary>
/// <returns>The security declarations</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="SecurityDeclarations"/> property.
/// </remarks>
protected virtual IList<SecurityDeclaration> GetSecurityDeclarations() =>
new OwnedCollection<IHasSecurityDeclaration, SecurityDeclaration>(this);
/// <summary>
/// Obtains the public key of the assembly definition.
/// </summary>
/// <returns>The public key.</returns>
/// <remarks>
/// This method is called upon initializing the <see cref="PublicKey"/> property.
/// </remarks>
protected virtual byte[]? GetPublicKey() => null;
/// <inheritdoc />
public override byte[]? GetPublicKeyToken()
{
if (!HasPublicKey)
return PublicKey;
_publicKeyToken ??= PublicKey != null
? ComputePublicKeyToken(PublicKey, HashAlgorithm)
: null;
return _publicKeyToken;
}
/// <inheritdoc />
public override bool IsImportedInModule(ModuleDefinition module) => ManifestModule == module;
/// <inheritdoc />
public override AssemblyReference ImportWith(ReferenceImporter importer) =>
(AssemblyReference) importer.ImportScope(new AssemblyReference(this));
/// <inheritdoc />
public override AssemblyDefinition Resolve() => this;
/// <summary>
/// Attempts to extract the target runtime from the <see cref="TryGetTargetFramework"/> attribute.
/// </summary>
/// <param name="info">The runtime.</param>
/// <returns><c>true</c> if the attribute was found and the runtime was extracted, <c>false</c> otherwise.</returns>
public virtual bool TryGetTargetFramework(out DotNetRuntimeInfo info)
{
for (int i = 0; i < CustomAttributes.Count; i++)
{
var ctor = CustomAttributes[i].Constructor;
if (ctor?.DeclaringType is not null
&& ctor.DeclaringType.IsTypeOf("System.Runtime.Versioning", "TargetFrameworkAttribute")
&& CustomAttributes[i].Signature?.FixedArguments[0].Element?.ToString() is { } name
&& DotNetRuntimeInfo.TryParse(name, out info))
{
return true;
}
}
info = default;
return false;
}
/// <summary>
/// Rebuilds the .NET assembly to a portable executable file and writes it to the file system.
/// </summary>
/// <param name="filePath">The output path of the manifest module file.</param>
public void Write(string filePath)
{
Write(filePath, new ManagedPEImageBuilder(), new ManagedPEFileBuilder());
}
/// <summary>
/// Rebuilds the .NET assembly to a portable executable file and writes it to the file system.
/// </summary>
/// <param name="filePath">The output path of the manifest module file.</param>
/// <param name="imageBuilder">The engine to use for reconstructing a PE image.</param>
public void Write(string filePath, IPEImageBuilder imageBuilder)
{
Write(filePath, imageBuilder, new ManagedPEFileBuilder());
}
/// <summary>
/// Rebuilds the .NET assembly to a portable executable file and writes it to the file system.
/// </summary>
/// <param name="filePath">The output path of the manifest module file.</param>
/// <param name="imageBuilder">The engine to use for reconstructing a PE image.</param>
/// <param name="fileBuilder">The engine to use for reconstructing a PE file.</param>
public void Write(string filePath, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder)
{
string? directory = Path.GetDirectoryName(Path.GetFullPath(filePath));
if (directory is null || !Directory.Exists(directory))
throw new DirectoryNotFoundException();
for (int i = 0; i < Modules.Count; i++)
{
var module = Modules[i];
string modulePath = module == ManifestModule
? filePath
: Path.Combine(directory, module.Name?.Value ?? $"module{i}.bin");
module.Write(modulePath, imageBuilder, fileBuilder);
}
}
/// <summary>
/// Rebuilds the manifest module and writes it to the stream specified.
/// </summary>
/// <param name="stream">The output stream of the manifest module file.</param>
public void WriteManifest(Stream stream)
{
WriteManifest(stream, new ManagedPEImageBuilder(), new ManagedPEFileBuilder());
}
/// <summary>
/// Rebuilds the manifest module and writes it to the stream specified.
/// </summary>
/// <param name="stream">The output stream of the manifest module file.</param>
/// <param name="imageBuilder">The engine to use for reconstructing a PE image.</param>
public void WriteManifest(Stream stream, IPEImageBuilder imageBuilder)
{
WriteManifest(stream, imageBuilder, new ManagedPEFileBuilder());
}
/// <summary>
/// Rebuilds the manifest module and writes it to the stream specified.
/// </summary>
/// <param name="stream">The output stream of the manifest module file.</param>
/// <param name="imageBuilder">The engine to use for reconstructing a PE image.</param>
/// <param name="fileBuilder">The engine to use for reconstructing a PE file.</param>
public void WriteManifest(Stream stream, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder)
{
ManifestModule?.Write(stream, imageBuilder, fileBuilder);
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AssemblyReferenceTest.cs | AsmResolver.DotNet.Tests
| AssemblyReferenceTest | [] | ['System', 'System.Reflection', 'System.Runtime.InteropServices', 'Xunit'] | xUnit | net8.0 | public class AssemblyReferenceTest
{
[Fact]
public void ReadName()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var assemblyRef = module.AssemblyReferences[0];
Assert.Equal("mscorlib", assemblyRef.Name);
}
[Fact]
public void ReadVersion()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var assemblyRef = module.AssemblyReferences[0];
Assert.Equal(new Version(4,0,0,0), assemblyRef.Version);
}
[Fact]
public void ReadPublicKeyOrToken()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var assemblyRef = module.AssemblyReferences[0];
Assert.False(assemblyRef.HasPublicKey);
var expectedToken = new byte[] {0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89};
Assert.Equal(expectedToken, assemblyRef.PublicKeyOrToken);
Assert.Equal(expectedToken, assemblyRef.GetPublicKeyToken());
}
[Fact]
public void GetFullNameCultureNeutralAssembly()
{
var name = new AssemblyName(KnownCorLibs.MsCorLib_v4_0_0_0.FullName);
Assert.Equal("mscorlib", name.Name);
Assert.Equal(new Version(4,0,0,0), name.Version);
Assert.Equal(string.Empty, name.CultureName);
Assert.Equal(new byte[] {0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89}, name.GetPublicKeyToken());
}
[Fact]
public void GetFullNameCultureNonNeutralAssembly()
{
var assembly = new AssemblyReference("SomeAssembly", new Version(1, 2, 3, 4));
assembly.Culture = "en-US";
var name = new AssemblyName(assembly.FullName);
Assert.Equal("SomeAssembly", name.Name);
Assert.Equal(new Version(1,2,3,4), name.Version);
Assert.Equal("en-US", name.CultureName);
Assert.Equal(Array.Empty<byte>(), name.GetPublicKeyToken());
}
[Fact]
public void CorLibResolution()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var assemblyRef = module.AssemblyReferences[0];
var assemblyDef = assemblyRef.Resolve();
Assert.NotNull(assemblyDef);
Assert.Equal(assemblyDef.Name, assemblyDef.Name);
Assert.Equal(assemblyDef.Version, assemblyDef.Version);
}
} | 139 | 2,832 | using System;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a reference to an external .NET assembly, hosted by a common language runtime (CLR).
/// </summary>
public class AssemblyReference :
AssemblyDescriptor,
IResolutionScope,
IOwnedCollectionElement<ModuleDefinition>,
IImplementation
{
private readonly LazyVariable<AssemblyReference, byte[]?> _publicKeyOrToken;
private readonly LazyVariable<AssemblyReference, byte[]?> _hashValue;
private byte[]? _publicKeyToken;
/// <summary>
/// Initializes a new assembly reference.
/// </summary>
/// <param name="token">The token of the assembly reference.</param>
protected AssemblyReference(MetadataToken token)
: base(token)
{
_publicKeyOrToken = new LazyVariable<AssemblyReference, byte[]?>(x => x.GetPublicKeyOrToken());
_hashValue = new LazyVariable<AssemblyReference, byte[]?>(x => x.GetHashValue());
}
/// <summary>
/// Creates a new assembly reference.
/// </summary>
/// <param name="name">The name of the assembly.</param>
/// <param name="version">The version of the assembly.</param>
public AssemblyReference(Utf8String? name, Version version)
: this(new MetadataToken(TableIndex.AssemblyRef, 0))
{
Name = name;
Version = version;
}
/// <summary>
/// Creates a new assembly reference.
/// </summary>
/// <param name="name">The name of the assembly.</param>
/// <param name="version">The version of the assembly.</param>
/// <param name="publicKey">Indicates the key provided by <paramref name="publicKeyOrToken"/> is the full,
/// unhashed public key used to verify the authenticity of the assembly.</param>
/// <param name="publicKeyOrToken">Indicates the public key or token (depending on <paramref name="publicKey"/>),
/// used to verify the authenticity of the assembly.</param>
public AssemblyReference(Utf8String? name, Version version, bool publicKey, byte[]? publicKeyOrToken)
: this(new MetadataToken(TableIndex.AssemblyRef, 0))
{
Name = name;
Version = version;
HasPublicKey = publicKey;
PublicKeyOrToken = publicKeyOrToken;
}
/// <summary>
/// Creates a new assembly reference, and copies over all properties of another assembly descriptor.
/// </summary>
/// <param name="descriptor">The assembly to base the reference on.</param>
public AssemblyReference(AssemblyDescriptor descriptor)
: this(new MetadataToken(TableIndex.AssemblyRef, 0))
{
Name = descriptor.Name;
Version = descriptor.Version;
Attributes = descriptor.Attributes;
HasPublicKey = false;
PublicKeyOrToken = descriptor.GetPublicKeyToken();
if (PublicKeyOrToken?.Length == 0)
PublicKeyOrToken = null;
Culture = descriptor.Culture;
if (Utf8String.IsNullOrEmpty(Culture))
Culture = null;
}
/// <inheritdoc />
public ModuleDefinition? Module
{
get;
private set;
}
/// <inheritdoc />
ModuleDefinition? IOwnedCollectionElement<ModuleDefinition>.Owner
{
get => Module;
set => Module = value;
}
/// <summary>
/// Gets or sets the (token of the) public key of the assembly to use for verification of a signature.
/// </summary>
/// <remarks>
/// <para>If this value is set to <c>null</c>, no public key will be assigned.</para>
/// <para>When <see cref="AssemblyDescriptor.HasPublicKey"/> is set to <c>true</c>, this value contains the full
/// unhashed public key that was used to sign the assembly. This property does not automatically update the
/// <see cref="AssemblyDescriptor.HasPublicKey"/> property.</para>
/// <para>This property corresponds to the Culture column in the assembly definition table.</para>
/// </remarks>
public byte[]? PublicKeyOrToken
{
get => _publicKeyOrToken.GetValue(this);
set => _publicKeyOrToken.SetValue(value);
}
/// <summary>
/// Gets or sets the hash value of the assembly reference.
/// </summary>
public byte[]? HashValue
{
get => _hashValue.GetValue(this);
set => _hashValue.SetValue(value);
}
/// <inheritdoc />
public override bool IsCorLib => KnownCorLibs.KnownCorLibReferences.Contains(this);
/// <inheritdoc />
public override byte[]? GetPublicKeyToken()
{
if (!HasPublicKey)
return PublicKeyOrToken;
if (_publicKeyToken is null && PublicKeyOrToken is not null)
{
lock (_publicKeyOrToken)
{
if (_publicKeyToken is null && PublicKeyOrToken is not null)
_publicKeyToken = ComputePublicKeyToken(PublicKeyOrToken, AssemblyHashAlgorithm.Sha1);
}
}
return _publicKeyToken;
}
/// <summary>
/// Obtains the public key or token of the assembly reference.
/// </summary>
/// <returns>The public key or token.</returns>
/// <remarks>
/// This method is called upon initializing the <see cref="PublicKeyOrToken"/> property.
/// </remarks>
protected virtual byte[]? GetPublicKeyOrToken() => null;
/// <summary>
/// Obtains the hash value of the assembly reference.
/// </summary>
/// <returns>The hash value.</returns>
/// <remarks>
/// This method is called upon initializing the <see cref="HashValue"/> property.
/// </remarks>
protected virtual byte[]? GetHashValue() => null;
/// <inheritdoc />
public override bool IsImportedInModule(ModuleDefinition module) => Module == module;
/// <inheritdoc />
public override AssemblyReference ImportWith(ReferenceImporter importer) =>
(AssemblyReference) importer.ImportScope(this);
/// <inheritdoc />
public override AssemblyDefinition? Resolve() => Module?.MetadataResolver.AssemblyResolver.Resolve(this);
AssemblyDescriptor IResolutionScope.GetAssembly() => this;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AssemblyResolverTest.cs | AsmResolver.DotNet.Tests
| AssemblyResolverTest | ['private const string NonWindowsPlatform = "Test checks for the presence of Windows specific runtime libraries.";', 'private readonly SignatureComparer _comparer = new();'] | ['System', 'System.IO', 'System.Runtime.InteropServices', 'AsmResolver.DotNet.Config.Json', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.NestedClasses', 'AsmResolver.IO', 'AsmResolver.PE.File', 'Xunit'] | xUnit | net8.0 | public class AssemblyResolverTest
{
private const string NonWindowsPlatform = "Test checks for the presence of Windows specific runtime libraries.";
private readonly SignatureComparer _comparer = new();
[Fact]
public void ResolveCorLib()
{
var assemblyName = typeof(object).Assembly.GetName();
var assemblyRef = new AssemblyReference(
assemblyName.Name,
assemblyName.Version!,
false,
assemblyName.GetPublicKeyToken());
var resolver = new DotNetCoreAssemblyResolver(new Version(3, 1, 0));
var assemblyDef = resolver.Resolve(assemblyRef);
Assert.NotNull(assemblyDef);
Assert.Equal(assemblyName.Name, assemblyDef.Name);
Assert.NotNull(assemblyDef.ManifestModule!.FilePath);
}
[Fact]
public void ResolveCorLibUsingFileService()
{
using var service = new ByteArrayFileService();
var assemblyName = typeof(object).Assembly.GetName();
var assemblyRef = new AssemblyReference(
assemblyName.Name,
assemblyName.Version!,
false,
assemblyName.GetPublicKeyToken());
var resolver = new DotNetCoreAssemblyResolver(service, new Version(3, 1, 0));
Assert.Empty(service.GetOpenedFiles());
Assert.NotNull(resolver.Resolve(assemblyRef));
Assert.NotEmpty(service.GetOpenedFiles());
}
[Fact]
public void ResolveLocalLibrary()
{
var resolver = new DotNetCoreAssemblyResolver(new Version(3, 1, 0));
resolver.SearchDirectories.Add(Path.GetDirectoryName(typeof(AssemblyResolverTest).Assembly.Location));
var assemblyDef = AssemblyDefinition.FromFile(typeof(TopLevelClass1).Assembly.Location, TestReaderParameters);
var assemblyRef = new AssemblyReference(assemblyDef);
Assert.Equal(assemblyDef, resolver.Resolve(assemblyRef), _comparer);
Assert.NotNull(assemblyDef.ManifestModule!.FilePath);
resolver.ClearCache();
Assert.False(resolver.HasCached(assemblyRef));
resolver.AddToCache(assemblyRef, assemblyDef);
Assert.True(resolver.HasCached(assemblyRef));
Assert.Equal(assemblyDef, resolver.Resolve(assemblyRef));
resolver.RemoveFromCache(assemblyRef);
Assert.NotEqual(assemblyDef, resolver.Resolve(assemblyRef));
}
[Fact]
public void ResolveWithConfiguredRuntime()
{
var assemblyName = typeof(object).Assembly.GetName();
var assemblyRef = new AssemblyReference(
assemblyName.Name,
assemblyName.Version!,
false,
assemblyName.GetPublicKeyToken());
var config = RuntimeConfiguration.FromJson(@"{
""runtimeOptions"": {
""tfm"": ""netcoreapp3.1"",
""framework"": {
""name"": ""Microsoft.NETCore.App"",
""version"": ""3.1.0""
}
}
}");
var resolver = new DotNetCoreAssemblyResolver(config, new Version(3, 1, 0));
var assemblyDef = resolver.Resolve(assemblyRef);
Assert.NotNull(assemblyDef);
Assert.Equal(assemblyName.Name, assemblyDef.Name);
Assert.NotNull(assemblyDef.ManifestModule!.FilePath);
Assert.Contains("Microsoft.NETCore.App", assemblyDef.ManifestModule.FilePath);
}
[SkippableFact]
public void ResolveWithConfiguredRuntimeWindowsCanStillResolveCorLib()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
var assemblyName = typeof(object).Assembly.GetName();
var assemblyRef = new AssemblyReference(
assemblyName.Name,
assemblyName.Version,
false,
assemblyName.GetPublicKeyToken());
var config = RuntimeConfiguration.FromJson(@"{
""runtimeOptions"": {
""tfm"": ""netcoreapp3.1"",
""framework"": {
""name"": ""Microsoft.WindowsDesktop.App"",
""version"": ""3.1.0""
}
}
}");
var resolver = new DotNetCoreAssemblyResolver(config, new Version(3, 1, 0));
var assemblyDef = resolver.Resolve(assemblyRef);
Assert.NotNull(assemblyDef);
Assert.Equal(assemblyName.Name, assemblyDef.Name);
Assert.NotNull(assemblyDef.ManifestModule!.FilePath);
}
[SkippableFact]
public void ResolveWithConfiguredRuntimeWindowsResolvesRightWindowsBase()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
var assemblyRef = new AssemblyReference(
"WindowsBase",
new Version(4,0,0,0),
false,
new byte[] {0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35});
var config = RuntimeConfiguration.FromJson(@"{
""runtimeOptions"": {
""tfm"": ""netcoreapp3.1"",
""framework"": {
""name"": ""Microsoft.WindowsDesktop.App"",
""version"": ""3.1.0""
}
}
}");
var resolver = new DotNetCoreAssemblyResolver(config, new Version(3, 1, 0));
var assemblyDef = resolver.Resolve(assemblyRef);
Assert.NotNull(assemblyDef);
Assert.Equal("WindowsBase", assemblyDef.Name);
Assert.NotNull(assemblyDef.ManifestModule!.FilePath);
Assert.Contains("Microsoft.WindowsDesktop.App", assemblyDef.ManifestModule.FilePath);
}
[SkippableTheory]
[InlineData(false)]
[InlineData(true)]
public void PreferResolveFromGac32If32BitAssembly(bool legacy)
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
var module = new ModuleDefinition("SomeAssembly", legacy
? KnownCorLibs.MsCorLib_v2_0_0_0
: KnownCorLibs.MsCorLib_v4_0_0_0);
module.IsBit32Preferred = true;
module.IsBit32Required = true;
module.MachineType = MachineType.I386;
module.PEKind = OptionalHeaderMagic.PE32;
var resolved = module.CorLibTypeFactory.CorLibScope.GetAssembly()!.Resolve();
Assert.NotNull(resolved);
Assert.Contains("GAC_32", resolved.ManifestModule!.FilePath!);
}
[SkippableTheory]
[InlineData(false)]
[InlineData(true)]
public void PreferResolveFromGac64If64BitAssembly(bool legacy)
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
var module = new ModuleDefinition("SomeAssembly", legacy
? KnownCorLibs.MsCorLib_v2_0_0_0
: KnownCorLibs.MsCorLib_v4_0_0_0);
module.IsBit32Preferred = false;
module.IsBit32Required = false;
module.MachineType = MachineType.Amd64;
module.PEKind = OptionalHeaderMagic.PE32Plus;
var resolved = module.CorLibTypeFactory.CorLibScope.GetAssembly()!.Resolve();
Assert.NotNull(resolved);
Assert.Contains("GAC_64", resolved.ManifestModule!.FilePath!);
}
[Fact]
public void ResolveReferenceWithExplicitPublicKey()
{
// https://github.com/Washi1337/AsmResolver/issues/381
var reference = new AssemblyReference(
"System.Collections",
new Version(6, 0, 0, 0),
true,
new byte[]
{
0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00,
0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x07, 0xD1,
0xFA, 0x57, 0xC4, 0xAE, 0xD9, 0xF0, 0xA3, 0x2E, 0x84, 0xAA, 0x0F, 0xAE, 0xFD, 0x0D, 0xE9, 0xE8, 0xFD,
0x6A, 0xEC, 0x8F, 0x87, 0xFB, 0x03, 0x76, 0x6C, 0x83, 0x4C, 0x99, 0x92, 0x1E, 0xB2, 0x3B, 0xE7, 0x9A,
0xD9, 0xD5, 0xDC, 0xC1, 0xDD, 0x9A, 0xD2, 0x36, 0x13, 0x21, 0x02, 0x90, 0x0B, 0x72, 0x3C, 0xF9, 0x80,
0x95, 0x7F, 0xC4, 0xE1, 0x77, 0x10, 0x8F, 0xC6, 0x07, 0x77, 0x4F, 0x29, 0xE8, 0x32, 0x0E, 0x92, 0xEA,
0x05, 0xEC, 0xE4, 0xE8, 0x21, 0xC0, 0xA5, 0xEF, 0xE8, 0xF1, 0x64, 0x5C, 0x4C, 0x0C, 0x93, 0xC1, 0xAB,
0x99, 0x28, 0x5D, 0x62, 0x2C, 0xAA, 0x65, 0x2C, 0x1D, 0xFA, 0xD6, 0x3D, 0x74, 0x5D, 0x6F, 0x2D, 0xE5,
0xF1, 0x7E, 0x5E, 0xAF, 0x0F, 0xC4, 0x96, 0x3D, 0x26, 0x1C, 0x8A, 0x12, 0x43, 0x65, 0x18, 0x20, 0x6D,
0xC0, 0x93, 0x34, 0x4D, 0x5A, 0xD2, 0x93
});
var module = new ModuleDefinition("Dummy", KnownCorLibs.SystemRuntime_v6_0_0_0);
module.AssemblyReferences.Add(reference);
var definition = reference.Resolve();
Assert.NotNull(definition);
Assert.Equal(reference.Name, definition.Name);
Assert.NotNull(definition.ManifestModule!.FilePath);
}
} | 310 | 9,855 | using System.Collections.Concurrent;
using System.IO;
using AsmResolver.DotNet.Serialized;
using AsmResolver.DotNet.Signatures;
namespace AsmResolver.DotNet.Bundles;
/// <summary>
/// Provides an implementation of an assembly resolver that prefers assemblies embedded in single-file-host executable.
/// </summary>
public class BundleAssemblyResolver : IAssemblyResolver
{
private readonly BundleManifest _manifest;
private readonly DotNetCoreAssemblyResolver _baseResolver;
private readonly ConcurrentDictionary<AssemblyDescriptor, AssemblyDefinition> _embeddedFilesCache = new(SignatureComparer.Default);
internal BundleAssemblyResolver(BundleManifest manifest, ModuleReaderParameters readerParameters)
{
_manifest = manifest;
// Bundles are .NET core 3.1+ only -> we can always default to .NET Core assembly resolution.
_baseResolver = new DotNetCoreAssemblyResolver(readerParameters, manifest.GetTargetRuntime().Version);
}
/// <inheritdoc />
public AssemblyDefinition? Resolve(AssemblyDescriptor assembly)
{
// Prefer embedded files before we forward to the default assembly resolution algorithm.
if (TryResolveFromEmbeddedFiles(assembly, out var resolved))
return resolved;
return _baseResolver.Resolve(assembly);
}
private bool TryResolveFromEmbeddedFiles(AssemblyDescriptor assembly, out AssemblyDefinition? resolved)
{
if (_embeddedFilesCache.TryGetValue(assembly, out resolved))
return true;
try
{
for (int i = 0; i < _manifest.Files.Count; i++)
{
var file = _manifest.Files[i];
if (file.Type != BundleFileType.Assembly)
continue;
if (Path.GetFileNameWithoutExtension(file.RelativePath) == assembly.Name)
{
resolved = AssemblyDefinition.FromBytes(file.GetData(), _baseResolver.ReaderParameters);
_embeddedFilesCache.TryAdd(assembly, resolved);
return true;
}
}
}
catch
{
// Ignore any reader errors.
}
resolved = null;
return false;
}
/// <inheritdoc />
public void AddToCache(AssemblyDescriptor descriptor, AssemblyDefinition definition)
{
_baseResolver.AddToCache(descriptor, definition);
}
/// <inheritdoc />
public bool RemoveFromCache(AssemblyDescriptor descriptor)
{
// Note: This is intentionally not an or-else (||) construction.
return _embeddedFilesCache.TryRemove(descriptor, out _) | _baseResolver.RemoveFromCache(descriptor);
}
/// <inheritdoc />
public bool HasCached(AssemblyDescriptor descriptor)
{
return _embeddedFilesCache.ContainsKey(descriptor) || _baseResolver.HasCached(descriptor);
}
/// <inheritdoc />
public void ClearCache()
{
_embeddedFilesCache.Clear();
_baseResolver.ClearCache();
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Builder\BlobStreamBufferTest.cs | AsmResolver.DotNet.Tests.Builder
| BlobStreamBufferTest | [] | ['AsmResolver.DotNet.Builder', 'AsmResolver.DotNet.Builder.Metadata', 'AsmResolver.PE.DotNet.Metadata', 'Xunit'] | xUnit | net8.0 | public class BlobStreamBufferTest
{
[Fact]
public void AddDistinct()
{
var buffer = new BlobStreamBuffer();
var blob1 = new byte[]
{
1, 2, 3
};
uint index1 = buffer.GetBlobIndex(blob1);
var blob2 = new byte[]
{
4, 5, 6
};
uint index2 = buffer.GetBlobIndex(blob2);
Assert.NotEqual(index1, index2);
var blobStream = buffer.CreateStream();
Assert.Equal(blob1, blobStream.GetBlobByIndex(index1));
Assert.Equal(blob2, blobStream.GetBlobByIndex(index2));
}
[Fact]
public void AddDuplicate()
{
var buffer = new BlobStreamBuffer();
var blob1 = new byte[]
{
1, 2, 3
};
uint index1 = buffer.GetBlobIndex(blob1);
var blob2 = new byte[]
{
1, 2, 3
};
uint index2 = buffer.GetBlobIndex(blob2);
Assert.Equal(index1, index2);
var blobStream = buffer.CreateStream();
Assert.Equal(blob1, blobStream.GetBlobByIndex(index1));
}
[Fact]
public void AddRaw()
{
var buffer = new BlobStreamBuffer();
var blob1 = new byte[]
{
3, 1, 2, 3
};
uint index1 = buffer.AppendRawData(blob1);
var blob2 = new byte[]
{
1, 2, 3
};
uint index2 = buffer.GetBlobIndex(blob2);
Assert.NotEqual(index1, index2);
var blobStream = buffer.CreateStream();
Assert.Equal(blob2, blobStream.GetBlobByIndex(index2));
}
[Fact]
public void ImportBlobStreamShouldIndexExistingBlobs()
{
var existingBlobStream = new SerializedBlobStream(BlobStream.DefaultName, new byte[]
{
0,
3, 0, 1, 2,
5, 0, 1, 2, 3, 4,
2, 0, 1
});
var buffer = new BlobStreamBuffer();
buffer.ImportStream(existingBlobStream);
var newStream = buffer.CreateStream();
Assert.Equal(new byte[]
{
0, 1, 2
}, newStream.GetBlobByIndex(1));
Assert.Equal(new byte[]
{
0, 1, 2, 3, 4
}, newStream.GetBlobByIndex(5));
Assert.Equal(new byte[]
{
0, 1
}, newStream.GetBlobByIndex(11));
}
[Fact]
public void ImportBlobStreamWithDuplicateBlobs()
{
var existingBlobStream = new SerializedBlobStream(BlobStream.DefaultName, new byte[]
{
0,
3, 0, 1, 2,
3, 0, 1, 2,
3, 0, 1, 2,
});
var buffer = new BlobStreamBuffer();
buffer.ImportStream(existingBlobStream);
var newStream = buffer.CreateStream();
Assert.Equal(new byte[]
{
0, 1, 2
}, newStream.GetBlobByIndex(1));
Assert.Equal(new byte[]
{
0, 1, 2
}, newStream.GetBlobByIndex(5));
Assert.Equal(new byte[]
{
0, 1, 2
}, newStream.GetBlobByIndex(9));
}
[Fact]
public void ImportBlobStreamWithGarbageData()
{
var existingBlobStream = new SerializedBlobStream(BlobStream.DefaultName, new byte[]
{
0,
3, 0, 1, 2,
123,
3, 0, 1, 2,
});
var buffer = new BlobStreamBuffer();
buffer.ImportStream(existingBlobStream);
var newStream = buffer.CreateStream();
Assert.Equal(new byte[]
{
0, 1, 2
}, newStream.GetBlobByIndex(1));
Assert.Equal(new byte[]
{
0, 1, 2
}, newStream.GetBlobByIndex(6));
}
[Fact]
public void ImportBlobStreamWithUnoptimalSizedBlobHeaders()
{
var existingBlobStream = new SerializedBlobStream(BlobStream.DefaultName, new byte[]
{
0,
3, 0, 1, 2,
0x80,
3, 0, 1, 2,
});
var buffer = new BlobStreamBuffer();
buffer.ImportStream(existingBlobStream);
var newStream = buffer.CreateStream();
Assert.Equal(new byte[]
{
0, 1, 2
}, newStream.GetBlobByIndex(1));
Assert.Equal(new byte[]
{
0, 1, 2
}, newStream.GetBlobByIndex(5));
}
} | 185 | 5,389 | using System;
using System.Collections.Generic;
using System.IO;
using AsmResolver.DotNet.Signatures;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata;
namespace AsmResolver.DotNet.Builder.Metadata
{
/// <summary>
/// Provides a mutable buffer for building up a blob stream in a .NET portable executable.
/// </summary>
public class BlobStreamBuffer : IMetadataStreamBuffer
{
private readonly MemoryStream _rawStream = new();
private readonly BinaryStreamWriter _writer;
private readonly Dictionary<byte[], uint> _blobs = new(ByteArrayEqualityComparer.Instance);
private readonly MemoryStreamWriterPool _blobWriterPool = new();
/// <summary>
/// Creates a new blob stream buffer with the default blob stream name.
/// </summary>
public BlobStreamBuffer()
: this(BlobStream.DefaultName)
{
}
/// <summary>
/// Creates a new blob stream buffer.
/// </summary>
/// <param name="name">The name of the stream.</param>
public BlobStreamBuffer(string name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
_writer = new BinaryStreamWriter(_rawStream);
_writer.WriteByte(0);
}
/// <inheritdoc />
public string Name
{
get;
}
/// <inheritdoc />
public bool IsEmpty => _rawStream.Length <= 1;
/// <summary>
/// Imports the contents of a user strings stream and indexes all present strings.
/// </summary>
/// <param name="stream">The stream to import.</param>
public void ImportStream(BlobStream stream)
{
MetadataStreamBufferHelper.CloneBlobHeap(stream, _writer, (index, newIndex) =>
{
if (stream.GetBlobByIndex(index) is { } blob)
_blobs[blob] = newIndex;
});
}
/// <summary>
/// Appends raw data to the stream.
/// </summary>
/// <param name="data">The data to append.</param>
/// <returns>The index to the start of the data.</returns>
/// <remarks>
/// This method does not index the blob data. Calling <see cref="AppendRawData"/> or <see cref="GetBlobIndex(byte[])"/>
/// on the same data will append the data a second time.
/// </remarks>
public uint AppendRawData(byte[] data)
{
uint offset = (uint) _rawStream.Length;
_writer.WriteBytes(data, 0, data.Length);
return offset;
}
private uint AppendBlob(byte[] blob)
{
uint offset = (uint) _rawStream.Length;
_writer.WriteCompressedUInt32((uint) blob.Length);
AppendRawData(blob);
return offset;
}
/// <summary>
/// Gets the index to the provided blob. If the blob is not present in the buffer, it will be appended to the end
/// of the stream.
/// </summary>
/// <param name="blob">The blob to lookup or add.</param>
/// <returns>The index of the blob.</returns>
public uint GetBlobIndex(byte[]? blob)
{
if (blob is null || blob.Length == 0)
return 0;
if (!_blobs.TryGetValue(blob, out uint offset))
{
offset = AppendBlob(blob);
_blobs.Add(blob, offset);
}
return offset;
}
/// <summary>
/// Gets the index to the provided blob signature. If the signature is not present in the buffer, it will be
/// appended to the end of the stream.
/// </summary>
/// <param name="provider">The object to use for obtaining metadata tokens for members in the tables stream.</param>
/// <param name="signature">The signature to lookup or add.</param>
/// <param name="errorListener">The object responsible for collecting diagnostic information.</param>
/// <returns>The index of the signature.</returns>
public uint GetBlobIndex(ITypeCodedIndexProvider provider, BlobSignature? signature, IErrorListener errorListener)
{
if (signature is null)
return 0u;
// Serialize blob.
using var rentedWriter = _blobWriterPool.Rent();
signature.Write(new BlobSerializationContext(rentedWriter.Writer, provider, errorListener));
return GetBlobIndex(rentedWriter.GetData());
}
/// <summary>
/// Serialises the blob stream buffer to a metadata stream.
/// </summary>
/// <returns>The metadata stream.</returns>
public BlobStream CreateStream()
{
_writer.Align(4);
return new SerializedBlobStream(Name, _rawStream.ToArray());
}
/// <inheritdoc />
IMetadataStream IMetadataStreamBuffer.CreateStream() => CreateStream();
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Builder\CilMethodBodySerializerTest.cs | AsmResolver.DotNet.Tests.Builder
| CilMethodBodySerializerTest | [] | ['AsmResolver.DotNet.Builder', 'AsmResolver.DotNet.Code.Cil', 'AsmResolver.DotNet.Signatures', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class CilMethodBodySerializerTest
{
[Theory]
[InlineData(false, true, 0)]
[InlineData(false, false, 100)]
[InlineData(false, null, 100)]
[InlineData(true, true, 0)]
[InlineData(true, false, 100)]
[InlineData(true, null, 0)]
public void ComputeMaxStackOnBuildOverride(bool computeMaxStack, bool? computeMaxStackOverride, int expectedMaxStack)
{
const int maxStack = 100;
var module = new ModuleDefinition("SomeModule", KnownCorLibs.SystemPrivateCoreLib_v4_0_0_0);
var main = new MethodDefinition(
"Main",
MethodAttributes.Public | MethodAttributes.Static,
MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));
main.CilMethodBody = new CilMethodBody(main)
{
ComputeMaxStackOnBuild = computeMaxStack,
MaxStack = maxStack,
Instructions = {new CilInstruction(CilOpCodes.Ret)},
LocalVariables = {new CilLocalVariable(module.CorLibTypeFactory.Int32)} // Force fat method body.
};
module.GetOrCreateModuleType().Methods.Add(main);
module.ManagedEntryPoint = main;
var builder = new ManagedPEImageBuilder(new DotNetDirectoryFactory
{
MethodBodySerializer = new CilMethodBodySerializer
{
ComputeMaxStackOnBuildOverride = computeMaxStackOverride
}
});
var newImage = builder.CreateImage(module).ConstructedImage;
var newModule = ModuleDefinition.FromImage(newImage, TestReaderParameters);
Assert.Equal(expectedMaxStack, newModule.ManagedEntryPointMethod.CilMethodBody.MaxStack);
}
} | 256 | 2,127 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AsmResolver.DotNet.Signatures;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet.Code.Cil
{
/// <summary>
/// Provides a default implementation of the <see cref="IMethodBodySerializer"/> interface, that serializes all
/// managed CIL method bodies of type <see cref="CilMethodBody"/> to raw method bodies of type <see cref="CilRawMethodBody"/>.
/// </summary>
public class CilMethodBodySerializer : IMethodBodySerializer
{
private readonly MemoryStreamWriterPool _writerPool = new();
/// <summary>
/// Gets or sets the value of an override switch indicating whether the max stack should always be recalculated
/// or should always be preserved.
/// </summary>
/// <remarks>
/// <para>
/// When this property is set to <c>true</c>, the maximum stack depth of all method bodies will be recalculated.
/// </para>
/// <para>
/// When this property is set to <c>false</c>, the maximum stack depth of all method bodies will be preserved.
/// </para>
/// <para>
/// When this property is set to <c>null</c>, the maximum stack depth will only be recalculated if
/// <see cref="CilMethodBody.ComputeMaxStackOnBuild"/> is set to <c>true</c>.
/// </para>
/// </remarks>
public bool? ComputeMaxStackOnBuildOverride
{
get;
set;
} = null;
/// <summary>
/// Gets or sets the value of an override switch indicating whether labels should always be verified for
/// validity or not.
/// </summary>
/// <remarks>
/// <para>
/// When this property is set to <c>true</c>, all method bodies will be verified for branch validity.
/// </para>
/// <para>
/// When this property is set to <c>false</c>, no method body will be verified for branch validity.
/// </para>
/// <para>
/// When this property is set to <c>null</c>, a method body will only be verified if
/// <see cref="CilMethodBody.VerifyLabelsOnBuild"/> is set to <c>true</c>.
/// </para>
/// </remarks>
public bool? VerifyLabelsOnBuildOverride
{
get;
set;
} = null;
/// <inheritdoc />
public ISegmentReference SerializeMethodBody(MethodBodySerializationContext context, MethodDefinition method)
{
if (method.CilMethodBody is null)
return SegmentReference.Null;
var body = method.CilMethodBody;
body.Instructions.CalculateOffsets();
try
{
if (ComputeMaxStackOnBuildOverride ?? body.ComputeMaxStackOnBuild)
{
// Max stack computation requires branches to be correct.
body.VerifyLabels(false);
body.MaxStack = body.ComputeMaxStack(false);
}
else if (VerifyLabelsOnBuildOverride ?? body.VerifyLabelsOnBuild)
{
body.VerifyLabels(false);
}
}
catch (Exception ex)
{
context.ErrorListener.RegisterException(ex);
}
// Serialize CIL stream.
byte[] code = BuildRawCodeStream(context, body);
// Build method body.
var rawBody = body.IsFat
? BuildFatMethodBody(context, body, code)
: BuildTinyMethodBody(code);
return rawBody.ToReference();
}
private static CilRawMethodBody BuildTinyMethodBody(byte[] code) => new CilRawTinyMethodBody(code);
private CilRawMethodBody BuildFatMethodBody(MethodBodySerializationContext context, CilMethodBody body, byte[] code)
{
// Serialize local variables.
MetadataToken token;
if (body.LocalVariables.Count == 0)
{
token = MetadataToken.Zero;
}
else
{
var localVarSig = new LocalVariablesSignature();
for (int i = 0; i < body.LocalVariables.Count; i++)
localVarSig.VariableTypes.Add(body.LocalVariables[i].VariableType);
var standAloneSig = new StandAloneSignature(localVarSig);
token = context.TokenProvider.GetStandAloneSignatureToken(standAloneSig);
}
var fatBody = new CilRawFatMethodBody(CilMethodBodyAttributes.Fat, (ushort) body.MaxStack, token, new DataSegment(code));
fatBody.InitLocals = body.InitializeLocals;
// Build up EH table section.
if (body.ExceptionHandlers.Count > 0)
{
fatBody.HasSections = true;
bool needsFatFormat = body.ExceptionHandlers.Any(e => e.IsFat);
var attributes = CilExtraSectionAttributes.EHTable;
if (needsFatFormat)
attributes |= CilExtraSectionAttributes.FatFormat;
var rawSectionData = SerializeExceptionHandlers(context, body.ExceptionHandlers, needsFatFormat);
var section = new CilExtraSection(attributes, rawSectionData);
fatBody.ExtraSections.Add(section);
}
return fatBody;
}
private byte[] BuildRawCodeStream(MethodBodySerializationContext context, CilMethodBody body)
{
var bag = context.ErrorListener;
using var rentedWriter = _writerPool.Rent();
var assembler = new CilAssembler(
rentedWriter.Writer,
new CilOperandBuilder(context.TokenProvider, bag),
body.Owner.SafeToString,
bag);
assembler.WriteInstructions(body.Instructions);
return rentedWriter.GetData();
}
private byte[] SerializeExceptionHandlers(MethodBodySerializationContext context, IList<CilExceptionHandler> exceptionHandlers, bool needsFatFormat)
{
using var rentedWriter = _writerPool.Rent();
for (int i = 0; i < exceptionHandlers.Count; i++)
{
var handler = exceptionHandlers[i];
WriteExceptionHandler(context, rentedWriter.Writer, handler, needsFatFormat);
}
return rentedWriter.GetData();
}
private void WriteExceptionHandler(MethodBodySerializationContext context, BinaryStreamWriter writer, CilExceptionHandler handler, bool useFatFormat)
{
if (handler.IsFat && !useFatFormat)
throw new InvalidOperationException("Can only serialize fat exception handlers in fat format.");
uint tryStart = (uint) (handler.TryStart?.Offset ?? 0);
uint tryEnd= (uint) (handler.TryEnd?.Offset ?? 0);
uint handlerStart = (uint) (handler.HandlerStart?.Offset ?? 0);
uint handlerEnd = (uint) (handler.HandlerEnd?.Offset ?? 0);
// Write handler type and boundaries.
if (useFatFormat)
{
writer.WriteUInt32((uint) handler.HandlerType);
writer.WriteUInt32(tryStart);
writer.WriteUInt32(tryEnd - tryStart);
writer.WriteUInt32(handlerStart);
writer.WriteUInt32(handlerEnd - handlerStart);
}
else
{
writer.WriteUInt16((ushort)handler. HandlerType);
writer.WriteUInt16((ushort) tryStart);
writer.WriteByte((byte) (tryEnd - tryStart));
writer.WriteUInt16((ushort) handlerStart);
writer.WriteByte((byte) (handlerEnd - handlerStart));
}
// Write handler type or filter start.
switch (handler.HandlerType)
{
case CilExceptionHandlerType.Exception:
{
var provider = context.TokenProvider;
var token = handler.ExceptionType switch
{
TypeReference typeReference => provider.GetTypeReferenceToken(typeReference),
TypeDefinition typeDefinition => provider.GetTypeDefinitionToken(typeDefinition),
TypeSpecification typeSpecification => provider.GetTypeSpecificationToken(typeSpecification),
_ => context.ErrorListener.RegisterExceptionAndReturnDefault<MetadataToken>(
new ArgumentOutOfRangeException(
$"Invalid or unsupported exception type ({handler.ExceptionType.SafeToString()})"))
};
writer.WriteUInt32(token.ToUInt32());
break;
}
case CilExceptionHandlerType.Filter:
writer.WriteUInt32((uint) (handler.FilterStart?.Offset ?? 0));
break;
case CilExceptionHandlerType.Finally:
case CilExceptionHandlerType.Fault:
writer.WriteUInt32(0);
break;
default:
context.ErrorListener.RegisterException(new ArgumentOutOfRangeException(
$"Invalid or unsupported handler type ({handler.HandlerType.SafeToString()}"));
break;
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Builder\GuidStreamBufferTest.cs | AsmResolver.DotNet.Tests.Builder
| GuidStreamBufferTest | [] | ['System', 'AsmResolver.DotNet.Builder', 'AsmResolver.DotNet.Builder.Metadata', 'AsmResolver.PE.DotNet.Metadata', 'Xunit'] | xUnit | net8.0 | public class GuidStreamBufferTest
{
[Fact]
public void AddDistinct()
{
var buffer = new GuidStreamBuffer();
var guid1 = new Guid(new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
});
uint index1 = buffer.GetGuidIndex(guid1);
var guid2 = new Guid(new byte[]
{
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
});
uint index2 = buffer.GetGuidIndex(guid2);
Assert.NotEqual(index1, index2);
var blobStream = buffer.CreateStream();
Assert.Equal(guid1, blobStream.GetGuidByIndex(index1));
Assert.Equal(guid2, blobStream.GetGuidByIndex(index2));
}
[Fact]
public void AddDuplicate()
{
var buffer = new GuidStreamBuffer();
var guid1 = new Guid(new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
});
uint index1 = buffer.GetGuidIndex(guid1);
var guid2 = new Guid(new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
});
uint index2 = buffer.GetGuidIndex(guid2);
Assert.Equal(index1, index2);
var blobStream = buffer.CreateStream();
Assert.Equal(guid1, blobStream.GetGuidByIndex(index1));
}
[Fact]
public void ImportGuidStreamShouldIndexExistingGuids()
{
var existingGuidStream = new SerializedGuidStream(GuidStream.DefaultName, new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
});
var buffer = new GuidStreamBuffer();
buffer.ImportStream(existingGuidStream);
var newStream = buffer.CreateStream();
Assert.Equal(new Guid(new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
}), newStream.GetGuidByIndex(1));
Assert.Equal(new Guid(new byte[]
{
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
}), newStream.GetGuidByIndex(2));
}
[Fact]
public void ImportGuidStreamWithDuplicateGuid()
{
var existingGuidStream = new SerializedGuidStream(GuidStream.DefaultName, new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
});
var buffer = new GuidStreamBuffer();
buffer.ImportStream(existingGuidStream);
var newStream = buffer.CreateStream();
Assert.Equal(new Guid(new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
}), newStream.GetGuidByIndex(1));
Assert.Equal(new Guid(new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
}), newStream.GetGuidByIndex(2));
Assert.Equal(new Guid(new byte[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
}), newStream.GetGuidByIndex(3));
}
} | 200 | 4,387 | using System;
using System.Collections.Generic;
using System.IO;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata;
namespace AsmResolver.DotNet.Builder.Metadata
{
/// <summary>
/// Provides a mutable buffer for building up a GUID stream in a .NET portable executable.
/// </summary>
public class GuidStreamBuffer : IMetadataStreamBuffer
{
private readonly MemoryStream _rawStream = new();
private readonly BinaryStreamWriter _writer;
private readonly Dictionary<System.Guid, uint> _guids = new();
/// <summary>
/// Creates a new GUID stream buffer with the default GUID stream name.
/// </summary>
public GuidStreamBuffer()
: this(GuidStream.DefaultName)
{
}
/// <summary>
/// Creates a new GUID stream buffer.
/// </summary>
/// <param name="name">The name of the stream.</param>
public GuidStreamBuffer(string name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
_writer = new BinaryStreamWriter(_rawStream);
}
/// <inheritdoc />
public string Name
{
get;
}
/// <inheritdoc />
public bool IsEmpty => _rawStream.Length <= 0;
/// <summary>
/// Imports the contents of a GUID stream and indexes all present GUIDs.
/// </summary>
/// <param name="stream">The stream to import.</param>
public void ImportStream(GuidStream stream)
{
uint index = 1;
while (index < stream.GetPhysicalSize() / GuidStream.GuidSize + 1)
{
var guid = stream.GetGuidByIndex(index);
uint newIndex = AppendGuid(guid);
_guids[guid] = newIndex;
index++;
}
}
private uint AppendRawData(byte[] data)
{
uint offset = (uint) _rawStream.Length;
_writer.WriteBytes(data, 0, data.Length);
return offset;
}
private uint AppendGuid(System.Guid guid)
{
uint index = (uint) _rawStream.Length / GuidStream.GuidSize + 1;
AppendRawData(guid.ToByteArray());
return index;
}
/// <summary>
/// Gets the index to the provided GUID. If the GUID. is not present in the buffer, it will be appended to the
/// end of the stream.
/// </summary>
/// <param name="guid">The GUID. to lookup or add.</param>
/// <returns>The index of the GUID.</returns>
public uint GetGuidIndex(System.Guid guid)
{
if (guid == System.Guid.Empty)
return 0;
if (!_guids.TryGetValue(guid, out uint index))
{
index = AppendGuid(guid);
_guids.Add(guid, index);
}
return index;
}
/// <summary>
/// Serializes the GUID stream buffer to a metadata stream.
/// </summary>
/// <returns>The metadata stream.</returns>
public GuidStream CreateStream() =>
new SerializedGuidStream(Name, _rawStream.ToArray());
/// <inheritdoc />
IMetadataStream IMetadataStreamBuffer.CreateStream() => CreateStream();
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Builder\ManagedPEImageBuilderTest.cs | AsmResolver.DotNet.Tests.Builder
| ManagedPEImageBuilderTest | [] | ['System', 'System.IO', 'System.Linq', 'AsmResolver.DotNet.Builder', 'AsmResolver.DotNet.Builder.Metadata', 'AsmResolver.PE', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class ManagedPEImageBuilderTest
{
[Fact]
public void ExecutableImportDirectoryShouldContainMsCoreeCorExeMain()
{
using var stream = new MemoryStream();
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
module.Write(stream);
var image = PEImage.FromBytes(stream.ToArray());
var symbol = image
.Imports.FirstOrDefault(m => m.Name == "mscoree.dll")
?.Symbols.FirstOrDefault(m => m.Name == "_CorExeMain");
Assert.NotNull(symbol);
Assert.Contains(image.Relocations, relocation =>
relocation.Location.CanRead
&& relocation.Location.CreateReader().ReadUInt32() == image.ImageBase + symbol.AddressTableEntry!.Rva);
}
[Fact]
public void ExecutableImportDirectoryShouldContainMsCoreeCorDllMain()
{
using var stream = new MemoryStream();
var module = ModuleDefinition.FromBytes(Properties.Resources.ForwarderLibrary, TestReaderParameters);
module.Write(stream);
var image = PEImage.FromBytes(stream.ToArray());
var symbol = image
.Imports.FirstOrDefault(m => m.Name == "mscoree.dll")
?.Symbols.FirstOrDefault(m => m.Name == "_CorDllMain");
Assert.NotNull(symbol);
Assert.Contains(image.Relocations, relocation =>
relocation.Location.CanRead
&& relocation.Location.CreateReader().ReadUInt32() == image.ImageBase + symbol.AddressTableEntry!.Rva);
}
[Fact]
public void ConstructPEImageFromNewModuleWithNoPreservation()
{
var module = new ModuleDefinition("Module");
var result = module.ToPEImage();
var newModule = ModuleDefinition.FromImage(result, TestReaderParameters);
Assert.Equal(module.Name, newModule.Name);
}
[Fact]
public void ConstructPEImageFromNewModuleWithPreservation()
{
var module = new ModuleDefinition("Module");
var result = module.ToPEImage(new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveAll));
var newModule = ModuleDefinition.FromImage(result, TestReaderParameters);
Assert.Equal(module.Name, newModule.Name);
}
[Fact]
public void ConstructPEImageFromExistingModuleWithNoPreservation()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var result = module.ToPEImage();
var newModule = ModuleDefinition.FromImage(result, TestReaderParameters);
Assert.Equal(module.Name, newModule.Name);
}
[Fact]
public void ConstructPEImageFromExistingModuleWithPreservation()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var result = module.ToPEImage(new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveAll));
var newModule = ModuleDefinition.FromImage(result, TestReaderParameters);
Assert.Equal(module.Name, newModule.Name);
}
[Fact]
public void PreserveUnknownStreams()
{
// Prepare a PE image with an extra unconventional stream.
var image = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters.PEReaderParameters);
byte[] data = { 1, 2, 3, 4 };
image.DotNetDirectory!.Metadata!.Streams.Add(new CustomMetadataStream("#Custom", data));
// Load and rebuild.
var module = ModuleDefinition.FromImage(image, TestReaderParameters);
var newImage = module.ToPEImage(new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveUnknownStreams));
// Verify unconventional stream is still present.
var newStream = Assert.IsAssignableFrom<CustomMetadataStream>(
newImage.DotNetDirectory!.Metadata!.GetStream("#Custom"));
Assert.Equal(data, Assert.IsAssignableFrom<IReadableSegment>(newStream.Contents).ToArray());
}
[Fact]
public void PreserveStreamOrder()
{
// Prepare a PE image with an unconventional stream order.
var image = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters.PEReaderParameters);
var streams = image.DotNetDirectory!.Metadata!.Streams;
for (int i = 0; i < streams.Count / 2; i++)
(streams[i], streams[streams.Count - i - 1]) = (streams[streams.Count - i - 1], streams[i]);
// Load and rebuild.
var module = ModuleDefinition.FromImage(image, TestReaderParameters);
var newImage = module.ToPEImage(new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveStreamOrder));
// Verify order is still the same.
Assert.Equal(
streams.Select(x => x.Name),
newImage.DotNetDirectory!.Metadata!.Streams.Select(x => x.Name));
}
[Fact]
public void PreserveUnknownStreamsAndStreamOrder()
{
// Prepare a PE image with an unconventional stream order and custom stream.
var image = PEImage.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters.PEReaderParameters);
var streams = image.DotNetDirectory!.Metadata!.Streams;
for (int i = 0; i < streams.Count / 2; i++)
(streams[i], streams[streams.Count - i - 1]) = (streams[streams.Count - i - 1], streams[i]);
byte[] data = { 1, 2, 3, 4 };
image.DotNetDirectory!.Metadata!.Streams.Insert(streams.Count / 2,
new CustomMetadataStream("#Custom", data));
// Load and rebuild.
var module = ModuleDefinition.FromImage(image, TestReaderParameters);
var newImage = module.ToPEImage(new ManagedPEImageBuilder(
MetadataBuilderFlags.PreserveStreamOrder | MetadataBuilderFlags.PreserveUnknownStreams));
// Verify order is still the same.
Assert.Equal(
streams.Select(x => x.Name),
newImage.DotNetDirectory!.Metadata!.Streams.Select(x => x.Name));
// Verify unconventional stream is still present.
var newStream = Assert.IsAssignableFrom<CustomMetadataStream>(
newImage.DotNetDirectory!.Metadata!.GetStream("#Custom"));
Assert.Equal(data, Assert.IsAssignableFrom<IReadableSegment>(newStream.Contents).ToArray());
}
[Fact]
public void BuildInvalidImageShouldRegisterDiagnostics()
{
// Prepare temp assembly.
var assembly = new AssemblyDefinition("Assembly", new Version(1, 0, 0, 0));
var module = new ModuleDefinition("Module");
assembly.Modules.Add(module);
// Add some field with an non-imported field type.
module.GetOrCreateModuleType().Fields.Add(new FieldDefinition(
"Field",
FieldAttributes.Static,
new TypeReference(null, "NonImportedNamespace", "NonImportedType").ToTypeSignature()));
// Build.
var bag = new DiagnosticBag();
var image = module.ToPEImage(new ManagedPEImageBuilder(bag), false);
// Verify diagnostics.
Assert.NotNull(image);
Assert.Contains(bag.Exceptions, x => x is MemberNotImportedException);
}
[Fact]
public void BuildingImageShouldConsiderJTDStreamAndUseLargeColumns()
{
var moduleDefinition = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_JTDStream, TestReaderParameters);
var metadata = moduleDefinition.DotNetDirectory!.Metadata!;
Assert.True(metadata.IsEncMetadata);
Assert.True(metadata.GetStream<TablesStream>().ForceLargeColumns);
var builder = new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveAll | MetadataBuilderFlags.ForceEncMetadata);
var rebuiltImage = moduleDefinition.ToPEImage(builder);
var rebuiltMetadata = rebuiltImage.DotNetDirectory!.Metadata!;
Assert.True(rebuiltMetadata.IsEncMetadata);
Assert.True(rebuiltMetadata.GetStream<TablesStream>().ForceLargeColumns);
}
} | 307 | 8,985 | using System;
using System.Linq;
using AsmResolver.DotNet.Code.Native;
using AsmResolver.PE;
using AsmResolver.PE.Exports;
namespace AsmResolver.DotNet.Builder
{
/// <summary>
/// Provides a default implementation of <see cref="IPEImageBuilder"/>.
/// </summary>
public class ManagedPEImageBuilder : IPEImageBuilder
{
/// <summary>
/// Creates a new instance of the <see cref="ManagedPEImageBuilder"/> class, using the default implementation
/// of the <see cref="IDotNetDirectoryFactory"/>.
/// </summary>
public ManagedPEImageBuilder()
: this(new DotNetDirectoryFactory())
{
}
/// <summary>
/// Creates a new instance of the <see cref="ManagedPEImageBuilder"/> class, and initializes a new
/// .NET data directory factory using the provided metadata builder flags.
/// </summary>
public ManagedPEImageBuilder(MetadataBuilderFlags metadataBuilderFlags)
: this(new DotNetDirectoryFactory(metadataBuilderFlags))
{
}
/// <summary>
/// Creates a new instance of the <see cref="ManagedPEImageBuilder"/> class, using the provided
/// .NET data directory factory.
/// </summary>
public ManagedPEImageBuilder(IDotNetDirectoryFactory factory)
: this(factory, new DiagnosticBag())
{
}
/// <summary>
/// Creates a new instance of the <see cref="ManagedPEImageBuilder"/> class, using the provided
/// .NET data directory factory.
/// </summary>
public ManagedPEImageBuilder(IErrorListener errorListener)
: this(new DotNetDirectoryFactory(), errorListener)
{
}
/// <summary>
/// Creates a new instance of the <see cref="ManagedPEImageBuilder"/> class, using the provided
/// .NET data directory factory and error listener.
/// </summary>
public ManagedPEImageBuilder(IDotNetDirectoryFactory factory, IErrorListener errorListener)
{
DotNetDirectoryFactory = factory;
ErrorListener = errorListener;
}
/// <summary>
/// Gets or sets the factory responsible for constructing the .NET data directory.
/// </summary>
public IDotNetDirectoryFactory DotNetDirectoryFactory
{
get;
set;
}
/// <summary>
/// Gets or sets the object responsible for keeping track of diagnostics during the building process.
/// </summary>
public IErrorListener ErrorListener
{
get;
set;
}
/// <inheritdoc />
public PEImageBuildResult CreateImage(ModuleDefinition module)
{
var context = new PEImageBuildContext(ErrorListener);
PEImage? image = null;
ITokenMapping? tokenMapping = null;
try
{
// Create basic PE image skeleton.
image = new PEImage
{
MachineType = module.MachineType,
PEKind = module.PEKind,
Characteristics = module.FileCharacteristics,
SubSystem = module.SubSystem,
DllCharacteristics = module.DllCharacteristics,
Resources = module.NativeResourceDirectory,
TimeDateStamp = module.TimeDateStamp
};
// Construct new .NET directory.
var symbolProvider = new NativeSymbolsProvider();
var result = DotNetDirectoryFactory.CreateDotNetDirectory(
module,
symbolProvider,
context.ErrorListener);
image.DotNetDirectory = result.Directory;
tokenMapping = result.TokenMapping;
// Copy any collected imported native symbol over to the image.
foreach (var import in symbolProvider.GetImportedModules())
image.Imports.Add(import);
// Copy any collected exported native symbols over to the image.
var exportedSymbols = symbolProvider.GetExportedSymbols(out uint baseOrdinal).ToArray();
if (exportedSymbols.Length > 0)
{
image.Exports = new ExportDirectory(!Utf8String.IsNullOrEmpty(module.Name)
? module.Name
: string.Empty)
{
BaseOrdinal = baseOrdinal
};
foreach (var export in exportedSymbols)
image.Exports.Entries.Add(export);
}
// Copy any collected base relocations over to the image.
foreach (var relocation in symbolProvider.GetBaseRelocations())
image.Relocations.Add(relocation);
// Copy over debug data.
for (int i = 0; i < module.DebugData.Count; i++)
image.DebugData.Add(module.DebugData[i]);
}
catch (Exception ex)
{
context.ErrorListener.RegisterException(ex);
context.ErrorListener.MarkAsFatal();
}
tokenMapping ??= new TokenMapping();
return new PEImageBuildResult(image, context.ErrorListener, tokenMapping);
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Builder\StringsStreamBufferTest.cs | AsmResolver.DotNet.Tests.Builder
| StringsStreamBufferTest | ['private static readonly Random Random = new();'] | ['System', 'System.Collections.Generic', 'System.IO', 'System.Text', 'AsmResolver.DotNet.Builder.Metadata', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.Metadata', 'Xunit'] | xUnit | net8.0 | public class StringsStreamBufferTest
{
private static readonly Random Random = new();
private static void Shuffle<T>(IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = Random.Next(n + 1);
(list[k], list[n]) = (list[n], list[k]);
}
}
[Fact]
public void AddDistinct()
{
var buffer = new StringsStreamBuffer();
const string string1 = "String 1";
uint index1 = buffer.GetStringIndex(string1);
const string string2 = "String 2";
uint index2 = buffer.GetStringIndex(string2);
Assert.NotEqual(index1, index2);
var stringsStream = buffer.CreateStream();
Assert.Equal(string1, stringsStream.GetStringByIndex(index1));
Assert.Equal(string2, stringsStream.GetStringByIndex(index2));
}
[Fact]
public void AddDuplicate()
{
var buffer = new StringsStreamBuffer();
const string string1 = "String 1";
uint index1 = buffer.GetStringIndex(string1);
const string string2 = "String 1";
uint index2 = buffer.GetStringIndex(string2);
Assert.Equal(index1, index2);
var stringsStream = buffer.CreateStream();
Assert.Equal(string1, stringsStream.GetStringByIndex(index1));
}
[Fact]
public void AddStringWithZeroByte()
{
var buffer = new StringsStreamBuffer();
Assert.Throws<ArgumentException>(() => buffer.GetStringIndex("Test\0Test"));
}
[Fact]
public void ImportStringStreamShouldIndexExistingStrings()
{
var existingStringsStream = new SerializedStringsStream(StringsStream.DefaultName, Encoding.UTF8.GetBytes(
"\0"
+ "String\0"
+ "LongerString\0"
+ "AnEvenLongerString\0"));
var buffer = new StringsStreamBuffer();
buffer.ImportStream(existingStringsStream);
var newStream = buffer.CreateStream();
Assert.Equal("String", newStream.GetStringByIndex(1));
Assert.Equal("LongerString", newStream.GetStringByIndex(8));
Assert.Equal("AnEvenLongerString", newStream.GetStringByIndex(21));
}
[Fact]
public void ImportStringsStreamWithDuplicateStrings()
{
var existingStringsStream = new SerializedStringsStream(StringsStream.DefaultName, Encoding.UTF8.GetBytes(
"\0"
+ "String\0"
+ "String\0"
+ "String\0"));
var buffer = new StringsStreamBuffer();
buffer.ImportStream(existingStringsStream);
var newStream = buffer.CreateStream();
Assert.Equal("String", newStream.GetStringByIndex(1));
Assert.Equal("String", newStream.GetStringByIndex(8));
Assert.Equal("String", newStream.GetStringByIndex(15));
}
[Fact]
public void StringsStreamBufferShouldPreserveInvalidCharacters()
{
var str = new Utf8String(new byte[] {0x80, 0x79, 0x78 });
var buffer = new StringsStreamBuffer();
uint index = buffer.GetStringIndex(str);
var stringsStream = buffer.CreateStream();
Assert.Equal(str, stringsStream.GetStringByIndex(index));
}
[Fact]
public void StringsStreamBufferShouldDistinguishDifferentInvalidCharacters()
{
var string1 = new Utf8String(new byte[] {0x80, 0x79, 0x78 });
var string2 = new Utf8String(new byte[] {0x80, 0x79, 0x78 });
var string3 = new Utf8String(new byte[] {0x81, 0x79, 0x78 });
var buffer = new StringsStreamBuffer();
uint index1 = buffer.GetStringIndex(string1);
uint index2 = buffer.GetStringIndex(string2);
uint index3 = buffer.GetStringIndex(string3);
Assert.Equal(index1, index2);
Assert.NotEqual(index1, index3);
}
[Fact]
public void OptimizeEmpty()
{
var buffer = new StringsStreamBuffer();
buffer.Optimize();
Assert.True(buffer.IsEmpty);
}
private static void OptimizeAndVerifyIndices(StringsStreamBuffer buffer, params Utf8String[] values)
{
uint[] indices = new uint[values.Length];
for (int i = 0; i < values.Length; i++)
indices[i] = buffer.GetStringIndex(values[i]);
var translationTable = buffer.Optimize();
for (int i = 0; i < values.Length; i++)
Assert.Equal(translationTable[indices[i]], buffer.GetStringIndex(values[i]));
var stream = buffer.CreateStream();
for (int i = 0; i < values.Length; i++)
Assert.Equal(values[i], stream.GetStringByIndex(translationTable[indices[i]]));
}
[Fact]
public void AddStringsWithSameSuffixShouldResultInStringReuseAfterOptimize()
{
var buffer = new StringsStreamBuffer();
OptimizeAndVerifyIndices(buffer,
"AAAABBBB",
"BBBB",
"BB");
uint index1 = buffer.GetStringIndex("AAAABBBB");
uint index2 = buffer.GetStringIndex("BBBB");
uint index3 = buffer.GetStringIndex("BB");
Assert.Equal(index1 + 4u, index2);
Assert.Equal(index1 + 6u, index3);
var stream = buffer.CreateStream();
Assert.Equal((1u + 8u + 1u).Align(4), stream.GetPhysicalSize());
}
[Fact]
public void AddStringsWithSameSuffixReversedShouldResultInStringReuseAfterOptimize()
{
var buffer = new StringsStreamBuffer();
OptimizeAndVerifyIndices(buffer,
"BB",
"BBBB",
"AAAABBBB");
uint index1 = buffer.GetStringIndex("AAAABBBB");
uint index2 = buffer.GetStringIndex("BBBB");
uint index3 = buffer.GetStringIndex("BB");
Assert.Equal(index1 + 4u, index2);
Assert.Equal(index1 + 6u, index3);
var stream = buffer.CreateStream();
Assert.Equal((1u + 8u + 1u).Align(4), stream.GetPhysicalSize());
}
[Fact]
public void OptimizeAfterImportedStreamShouldPreserveImportedData()
{
var existingStringsStream = new SerializedStringsStream(StringsStream.DefaultName, Encoding.UTF8.GetBytes(
"\0"
+ "AAAABBBB\0"
+ "abc\0"));
var buffer = new StringsStreamBuffer();
buffer.ImportStream(existingStringsStream);
OptimizeAndVerifyIndices(buffer, "AAAABBBB", "BBBB");
Assert.Equal(1u, buffer.GetStringIndex("AAAABBBB"));
Assert.Equal(1u + 4u, buffer.GetStringIndex("BBBB"));
var stream = buffer.CreateStream();
Assert.Equal((1u + 9u + 4u).Align(4), stream.GetPhysicalSize());
}
[Fact]
public void OptimizeAfterImportedStreamShouldPreserveImportedData2()
{
var existingStringsStream = new SerializedStringsStream(StringsStream.DefaultName, Encoding.UTF8.GetBytes(
"\0"
+ "AAAABBBB\0"
+ "abc\0"));
var buffer = new StringsStreamBuffer();
buffer.ImportStream(existingStringsStream);
OptimizeAndVerifyIndices(buffer, "AAAABBBBCCCC");
var stream = buffer.CreateStream();
Assert.Equal("AAAABBBB", stream.GetStringByIndex(1u));
Assert.Equal("AAAABBBBCCCC", stream.GetStringByIndex(1u + 9u + 4u));
}
[Fact]
public void OptimizeLongChainOfSuffixStrings()
{
const string templateString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var oldIndices = new List<uint>();
var buffer = new StringsStreamBuffer();
for (int i = 0; i < templateString.Length; i++)
oldIndices.Add(buffer.GetStringIndex(templateString[i..]));
var table = buffer.Optimize();
for (uint i = 0; i < templateString.Length; i++)
{
Assert.Equal(i + 1, buffer.GetStringIndex(templateString[(int) i..]));
Assert.Equal(i + 1, table[oldIndices[(int) i]]);
}
var stream = buffer.CreateStream();
Assert.Equal((1u + (uint)templateString.Length + 1u).Align(4), stream.GetPhysicalSize());
}
[Fact]
public void OptimizeMultipleLongChainsOfSuffixStrings()
{
const string templateString1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const string templateString2 = "zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA";
var strings = new List<string>();
for (int i = 0; i < templateString1.Length; i++)
strings.Add(templateString1[i..]);
for (int i = 0; i < templateString2.Length; i++)
strings.Add(templateString2[i..]);
Shuffle(strings);
var buffer = new StringsStreamBuffer();
foreach (string s in strings)
buffer.GetStringIndex(s);
buffer.Optimize();
var stream = buffer.CreateStream();
Assert.Equal(
(1u + (uint)templateString1.Length + 1u + (uint)templateString2.Length + 1u).Align(4),
stream.GetPhysicalSize());
}
[Fact]
public void OptimizeWithInvalidUtf8Characters()
{
var string1 = new Utf8String(new byte[] { 0x80, 0x79, 0x78 });
var string2 = new Utf8String(new byte[] { 0x79, 0x78 });
var buffer = new StringsStreamBuffer();
OptimizeAndVerifyIndices(buffer, string1, string2);
uint index = buffer.GetStringIndex(string1);
Assert.Equal(index + 1, buffer.GetStringIndex(string2));
}
[Fact]
public void OptimizeWithCyrillicCharacters()
{
var originalStream = new SerializedStringsStream("#Strings", new byte[]
{
0x00,
0x67, 0x65, 0x74, 0x5F, 0xD0, 0xA1, 0x00,
0x41, 0x42, 0x43, 0x44, 0x00,
0x00, 0x00, 0x00
});
var string1 = new Utf8String(new byte[] { 0x67, 0x65, 0x74, 0x5F, 0xD0, 0xA1 });
var string2 = new Utf8String(new byte[] { 0xD0, 0xA1 });
var string3 = new Utf8String("ABCD");
var buffer = new StringsStreamBuffer();
buffer.ImportStream(originalStream);
OptimizeAndVerifyIndices(buffer, string1, string2, string3);
// Assert.Equal(1u, buffer.GetStringIndex(string1));
// Assert.Equal(5u, buffer.GetStringIndex(string2));
// Assert.Equal(8u, buffer.GetStringIndex(string3));
}
} | 261 | 11,730 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata;
namespace AsmResolver.DotNet.Builder.Metadata
{
/// <summary>
/// Provides a mutable buffer for building up a strings stream in a .NET portable executable.
/// </summary>
public class StringsStreamBuffer : IMetadataStreamBuffer
{
private Dictionary<Utf8String, StringIndex> _index = new();
private List<StringsStreamBlob> _blobs = new();
private uint _currentOffset = 1;
private int _fixedBlobCount = 0;
/// <summary>
/// Creates a new strings stream buffer with the default strings stream name.
/// </summary>
public StringsStreamBuffer()
: this(StringsStream.DefaultName)
{
}
/// <summary>
/// Creates a new strings stream buffer.
/// </summary>
/// <param name="name">The name of the stream.</param>
public StringsStreamBuffer(string name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
}
/// <inheritdoc />
public string Name
{
get;
}
/// <inheritdoc />
public bool IsEmpty => _blobs.Count == 0;
/// <summary>
/// Imports the contents of a strings stream and indexes all present strings.
/// </summary>
/// <param name="stream">The stream to import.</param>
/// <exception cref="InvalidOperationException">Occurs when the stream buffer is not empty.</exception>
public void ImportStream(StringsStream stream)
{
if (!IsEmpty)
throw new InvalidOperationException("Cannot import a stream if the buffer is not empty.");
uint offset = 1;
uint size = stream.GetPhysicalSize();
while (offset < size)
{
var value = stream.GetStringByIndex(offset)!;
uint newOffset = AppendString(value, true);
_index[value] = new StringIndex(_blobs.Count - 1, newOffset);
offset += (uint) value.ByteCount + 1;
_fixedBlobCount++;
}
}
private uint AppendString(Utf8String value, bool isFixed)
{
uint offset = _currentOffset;
_blobs.Add(new StringsStreamBlob(value, isFixed));
_currentOffset += (uint)value.ByteCount + 1;
return offset;
}
/// <summary>
/// Gets the index to the provided string. If the string is not present in the buffer, it will be appended to
/// the end of the stream.
/// </summary>
/// <param name="value">The string to lookup or add.</param>
/// <returns>The index of the string.</returns>
public uint GetStringIndex(Utf8String? value)
{
if (Utf8String.IsNullOrEmpty(value))
return 0;
if (Array.IndexOf(value.GetBytesUnsafe(), (byte) 0x00) >= 0)
throw new ArgumentException("String contains a zero byte.");
if (!_index.TryGetValue(value, out var offsetId))
{
uint offset = AppendString(value, false);
offsetId = new StringIndex(_blobs.Count - 1, offset);
_index.Add(value, offsetId);
}
return offsetId.Offset;
}
/// <summary>
/// Optimizes the buffer by removing string entries that have a common suffix with another.
/// </summary>
/// <returns>A translation table that maps old offsets to the new ones after optimizing.</returns>
/// <remarks>
/// This method might invalidate all offsets obtained by <see cref="GetStringIndex"/>.
/// </remarks>
public IDictionary<uint, uint> Optimize()
{
uint finalOffset = 1;
var newIndex = new Dictionary<Utf8String, StringIndex>();
var newBlobs = new List<StringsStreamBlob>(_fixedBlobCount);
var translationTable = new Dictionary<uint, uint>
{
[0] = 0
};
// Import fixed blobs.
for (int i = 0; i < _fixedBlobCount; i++)
AppendBlob(_blobs[i]);
// Sort all blobs based on common suffix.
var sortedEntries = _index.ToList();
sortedEntries.Sort(StringsStreamBlobSuffixComparer.Instance);
for (int i = 0; i < sortedEntries.Count; i++)
{
var currentEntry = sortedEntries[i];
var currentBlob = _blobs[currentEntry.Value.BlobIndex];
// Ignore blobs that are already added.
if (currentBlob.IsFixed)
continue;
if (i == 0)
{
// First blob should always be added, since it has no common prefix with anything else.
AppendBlob(currentBlob);
}
else
{
// Check if any blobs have a common suffix.
int reusedIndex = i;
while (reusedIndex > 0 && BytesEndsWith(sortedEntries[reusedIndex - 1].Key.GetBytesUnsafe(), currentEntry.Key.GetBytesUnsafe()))
reusedIndex--;
// Reuse blob if blob had a common suffix.
if (reusedIndex != i)
ReuseBlob(currentEntry, reusedIndex);
else
AppendBlob(currentBlob);
}
}
// Replace contents of current buffer with the newly constructed buffer.
_blobs = newBlobs;
_index = newIndex;
_currentOffset = finalOffset;
return translationTable;
void AppendBlob(in StringsStreamBlob blob)
{
newBlobs.Add(blob);
var oldIndex = _index[blob.Blob];
translationTable[oldIndex.Offset] = finalOffset;
newIndex[blob.Blob] = new StringIndex(newBlobs.Count - 1, finalOffset);
finalOffset += blob.GetPhysicalSize();
}
void ReuseBlob(in KeyValuePair<Utf8String, StringIndex> currentEntry, int reusedIndex)
{
var reusedEntry = sortedEntries[reusedIndex];
uint reusedEntryNewOffset = translationTable[reusedEntry.Value.Offset];
int relativeOffset = reusedEntry.Key.ByteCount - currentEntry.Key.ByteCount;
uint newOffset = (uint)(reusedEntryNewOffset + relativeOffset);
translationTable[currentEntry.Value.Offset] = newOffset;
newIndex[currentEntry.Key] = new StringIndex(reusedEntry.Value.BlobIndex, newOffset);
}
}
private static bool BytesEndsWith(byte[] x, byte[] y)
{
if (x.Length < y.Length)
return false;
for (int i = x.Length - 1, j = y.Length - 1; i >= 0 && j >= 0; i--, j--)
{
if (x[i] != y[j])
return false;
}
return true;
}
/// <summary>
/// Serializes the strings stream buffer to a metadata stream.
/// </summary>
/// <returns>The metadata stream.</returns>
public StringsStream CreateStream()
{
using var outputStream = new MemoryStream();
var writer = new BinaryStreamWriter(outputStream);
writer.WriteByte(0);
foreach (var blob in _blobs)
blob.Write(writer);
writer.Align(4);
return new SerializedStringsStream(Name, outputStream.ToArray());
}
/// <inheritdoc />
IMetadataStream IMetadataStreamBuffer.CreateStream() => CreateStream();
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Builder\TokenMappingTest.cs | AsmResolver.DotNet.Tests.Builder
| TokenMappingTest | [] | ['System', 'System.Collections.Generic', 'System.IO', 'AsmResolver.DotNet.Builder', 'AsmResolver.DotNet.Signatures', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class TokenMappingTest
{
[Fact]
public void NewTypeDefinition()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Create new type.
var type = new TypeDefinition("Namespace", "Name", TypeAttributes.Interface); ;
module.TopLevelTypes.Add(type);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[type];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the new type.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage, TestReaderParameters);
var newType = (TypeDefinition) newModule.LookupMember(newToken);
Assert.Equal(type.Namespace, newType.Namespace);
Assert.Equal(type.Name, newType.Name);
}
[Fact]
public void NewFieldDefinition()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Create new field.
var field = new FieldDefinition(
"MyField",
FieldAttributes.Public | FieldAttributes.Static,
module.CorLibTypeFactory.Object);
module.GetOrCreateModuleType().Fields.Add(field);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[field];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the new field.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage, TestReaderParameters);
var newField = (FieldDefinition) newModule.LookupMember(newToken);
Assert.Equal(field.Name, newField.Name);
}
[Fact]
public void NewMethodDefinition()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Create new method.
var method = new MethodDefinition(
"MyMethod",
MethodAttributes.Public | MethodAttributes.Static,
MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));
module.GetOrCreateModuleType().Methods.Add(method);
// Get existing main method.
var main = module.ManagedEntryPointMethod;
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid tokens for both methods.
var methodToken = result.TokenMapping[method];
var mainMethodToken = result.TokenMapping[main];
Assert.NotEqual(0u, methodToken.Rid);
Assert.NotEqual(0u, mainMethodToken.Rid);
// Assert tokens resolve to the same methods.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage, TestReaderParameters);
var newMethod = (MethodDefinition) newModule.LookupMember(methodToken);
Assert.Equal(method.Name, newMethod.Name);
var newMain = (MethodDefinition) newModule.LookupMember(mainMethodToken);
Assert.Equal(main.Name, newMain.Name);
}
[Fact]
public void NewTypeReference()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Import arbitrary type as reference.
var importer = new ReferenceImporter(module);
var reference = importer.ImportType(typeof(MemoryStream));
// Ensure type ref is added to the module by adding a dummy field referencing it.
module.GetOrCreateModuleType().Fields.Add(new FieldDefinition(
"MyField",
FieldAttributes.Public | FieldAttributes.Static,
reference.ToTypeSignature()));
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[reference];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the same type reference.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage, TestReaderParameters);
var newReference = (TypeReference) newModule.LookupMember(newToken);
Assert.Equal(reference.Namespace, newReference.Namespace);
Assert.Equal(reference.Name, newReference.Name);
}
[Fact]
public void NewMemberReference()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Import arbitrary method.
var importer = new ReferenceImporter(module);
var reference = importer.ImportMethod(typeof(MemoryStream).GetConstructor(Type.EmptyTypes));
// Ensure method reference is added to the module by referencing it in main.
var instructions = module.ManagedEntryPointMethod.CilMethodBody.Instructions;
instructions.Insert(0, CilOpCodes.Newobj, reference);
instructions.Insert(1, CilOpCodes.Pop);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[reference];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the same method reference.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage, TestReaderParameters);
var newReference = (MemberReference) newModule.LookupMember(newToken);
Assert.Equal(reference.Name, newReference.Name);
}
[Fact]
public void NewTypeSpecification()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Import arbitrary generic method.
var importer = new ReferenceImporter(module);
var specification = importer.ImportType(typeof(List<object>));
// Ensure method reference is added to the module by referencing it in main.
var instructions = module.ManagedEntryPointMethod.CilMethodBody.Instructions;
instructions.Insert(0, CilOpCodes.Ldtoken, specification);
instructions.Insert(1, CilOpCodes.Pop);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[specification];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the same method reference.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage, TestReaderParameters);
var newReference = (TypeSpecification) newModule.LookupMember(newToken);
Assert.Equal(specification.Name, newReference.Name);
}
[Fact]
public void NewMethodSpecification()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Import arbitrary generic method.
var importer = new ReferenceImporter(module);
var reference = importer.ImportMethod(typeof(Array).GetMethod("Empty").MakeGenericMethod(typeof(object)));
// Ensure method reference is added to the module by referencing it in main.
var instructions = module.ManagedEntryPointMethod.CilMethodBody.Instructions;
instructions.Insert(0, CilOpCodes.Call, reference);
instructions.Insert(1, CilOpCodes.Pop);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[reference];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the same method reference.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage, TestReaderParameters);
var newReference = (MethodSpecification) newModule.LookupMember(newToken);
Assert.Equal(reference.Name, newReference.Name);
}
[Fact]
public void NewStandaloneSignature()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Import arbitrary method signature.
var importer = new ReferenceImporter(module);
var signature = new StandAloneSignature(
importer.ImportMethodSignature(MethodSignature.CreateStatic(module.CorLibTypeFactory.Void)));
// Ensure reference is added to the module by referencing it in main.
var instructions = module.ManagedEntryPointMethod.CilMethodBody.Instructions;
instructions.Insert(0, CilOpCodes.Ldnull);
instructions.Insert(0, CilOpCodes.Calli, signature);
// Rebuild.
var builder = new ManagedPEImageBuilder();
var result = builder.CreateImage(module);
// Assert valid token.
var newToken = result.TokenMapping[signature];
Assert.NotEqual(0u, newToken.Rid);
// Assert token resolves to the same method reference.
var newModule = ModuleDefinition.FromImage(result.ConstructedImage, TestReaderParameters);
var newSignature = (StandAloneSignature) newModule.LookupMember(newToken);
Assert.Equal((CallingConventionSignature) signature.Signature,
newSignature.Signature as CallingConventionSignature, new SignatureComparer());
}
} | 288 | 10,657 | using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet.Builder
{
/// <summary>
/// Maps new metadata tokens to members added to a .NET tables stream.
/// </summary>
public interface ITokenMapping
{
/// <summary>
/// Gets the new metadata token assigned to the provided member.
/// </summary>
/// <param name="member">The member.</param>
MetadataToken this[IMetadataMember member]
{
get;
}
/// <summary>
/// Gets the new metadata token assigned to the provided member, if it was registered in this mapping.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="token">The new metadata token.</param>
/// <returns><c>true</c> if the provided member was assigned a new token, <c>false</c> otherwise.</returns>
bool TryGetNewToken(IMetadataMember member, out MetadataToken token);
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Builder\UserStringsStreamBufferTest.cs | AsmResolver.DotNet.Tests.Builder
| UserStringsStreamBufferTest | [] | ['System.Text', 'AsmResolver.DotNet.Builder', 'AsmResolver.DotNet.Builder.Metadata', 'AsmResolver.PE.DotNet.Metadata', 'Xunit'] | xUnit | net8.0 | public class UserStringsStreamBufferTest
{
[Fact]
public void AddDistinct()
{
var buffer = new UserStringsStreamBuffer();
const string string1 = "String 1";
uint index1 = buffer.GetStringIndex(string1);
const string string2 = "String 2";
uint index2 = buffer.GetStringIndex(string2);
Assert.NotEqual(index1, index2);
var usStream = buffer.CreateStream();
Assert.Equal(string1, usStream.GetStringByIndex(index1));
Assert.Equal(string2, usStream.GetStringByIndex(index2));
}
[Fact]
public void AddDuplicate()
{
var buffer = new UserStringsStreamBuffer();
const string string1 = "String 1";
uint index1 = buffer.GetStringIndex(string1);
const string string2 = "String 1";
uint index2 = buffer.GetStringIndex(string2);
Assert.Equal(index1, index2);
var usStream = buffer.CreateStream();
Assert.Equal(string1, usStream.GetStringByIndex(index1));
}
[Fact]
public void AddRaw()
{
var buffer = new UserStringsStreamBuffer();
const string string1 = "String 1";
var rawData = Encoding.UTF8.GetBytes(string1);
uint index1 = buffer.AppendRawData(rawData);
uint index2 = buffer.GetStringIndex(string1);
Assert.NotEqual(index1, index2);
var usStream = buffer.CreateStream();
Assert.Equal(string1, usStream.GetStringByIndex(index2));
}
[Theory]
[InlineData('\x00', 0)]
[InlineData('\x01', 1)]
[InlineData('\x08', 1)]
[InlineData('\x09', 0)]
[InlineData('\x0E', 1)]
[InlineData('\x1F', 1)]
[InlineData('\x26', 0)]
[InlineData('\x27', 1)]
[InlineData('\x2D', 1)]
[InlineData('A', 0)]
[InlineData('\x7F', 1)]
[InlineData('\u3910', 1)]
public void SpecialCharactersTerminatorByte(char specialChar, byte terminatorByte)
{
string value = "My String" + specialChar;
var buffer = new UserStringsStreamBuffer();
uint index = buffer.GetStringIndex(value);
var usStream = buffer.CreateStream();
Assert.Equal(value, usStream.GetStringByIndex(index));
var reader = usStream.CreateReader();
reader.Offset = (uint) (index + Encoding.Unicode.GetByteCount(value) + 1);
byte b = reader.ReadByte();
Assert.Equal(terminatorByte, b);
}
[Fact]
public void ImportStreamShouldIndexExistingUserStrings()
{
var existingUserStringsStream = new SerializedUserStringsStream(UserStringsStream.DefaultName, new byte[]
{
0x00,
// "User string"
0x17,
0x55, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x20, 0x00, 0x73, 0x00, 0x74, 0x00,
0x72, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x00,
// "A longer user string"
0x29,
0x41, 0x00, 0x20, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x65, 0x00,
0x72, 0x00, 0x20, 0x00, 0x75, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x20, 0x00,
0x73, 0x00, 0x74, 0x00, 0x72, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x00,
// "An even longer user string"
0x35,
0x41, 0x00, 0x6E, 0x00, 0x20, 0x00, 0x65, 0x00, 0x76, 0x00, 0x65, 0x00, 0x6E, 0x00,
0x20, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x65, 0x00, 0x72, 0x00,
0x20, 0x00, 0x75, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x20, 0x00, 0x73, 0x00,
0x74, 0x00, 0x72, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00
});
var buffer = new UserStringsStreamBuffer();
buffer.ImportStream(existingUserStringsStream);
var newStream = buffer.CreateStream();
Assert.Equal("User string", newStream.GetStringByIndex(1));
Assert.Equal("A longer user string", newStream.GetStringByIndex(25));
Assert.Equal("An even longer user string", newStream.GetStringByIndex(67));
}
[Fact]
public void ImportStreamWithDuplicateUserStrings()
{
var existingUserStringsStream = new SerializedUserStringsStream(UserStringsStream.DefaultName, new byte[]
{
0x00,
// "User string"
0x17,
0x55, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x20, 0x00, 0x73, 0x00, 0x74, 0x00,
0x72, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x00,
// "User string"
0x17,
0x55, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x20, 0x00, 0x73, 0x00, 0x74, 0x00,
0x72, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x00,
// "User string"
0x17,
0x55, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x20, 0x00, 0x73, 0x00, 0x74, 0x00,
0x72, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x00,
});
var buffer = new UserStringsStreamBuffer();
buffer.ImportStream(existingUserStringsStream);
var newStream = buffer.CreateStream();
Assert.Equal("User string", newStream.GetStringByIndex(1));
Assert.Equal("User string", newStream.GetStringByIndex(25));
Assert.Equal("User string", newStream.GetStringByIndex(49));
}
[Fact]
public void ImportStreamWithGarbageData()
{
var existingUserStringsStream = new SerializedUserStringsStream(UserStringsStream.DefaultName, new byte[]
{
0x00,
// "User string"
0x17,
0x55, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x20, 0x00, 0x73, 0x00, 0x74, 0x00,
0x72, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x00,
0xAA,
// "User string"
0x17,
0x55, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x20, 0x00, 0x73, 0x00, 0x74, 0x00,
0x72, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x00,
});
var buffer = new UserStringsStreamBuffer();
buffer.ImportStream(existingUserStringsStream);
var newStream = buffer.CreateStream();
Assert.Equal("User string", newStream.GetStringByIndex(1));
Assert.Equal("User string", newStream.GetStringByIndex(26));
}
[Fact]
public void RebuildWithPreserveAbsentUSStream()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_NoUSStream, TestReaderParameters);
var image = module.ToPEImage(new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveUserStringIndices));
Assert.False(image.DotNetDirectory!.Metadata!.TryGetStream<UserStringsStream>(out _));
}
} | 205 | 7,590 | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata;
namespace AsmResolver.DotNet.Builder.Metadata
{
/// <summary>
/// Provides a mutable buffer for building up a user-strings stream in a .NET portable executable.
/// </summary>
public class UserStringsStreamBuffer : IMetadataStreamBuffer
{
private readonly MemoryStream _rawStream = new();
private readonly BinaryStreamWriter _writer;
private readonly Dictionary<string, uint> _strings = new();
/// <summary>
/// Creates a new user-strings stream buffer with the default user-strings stream name.
/// </summary>
public UserStringsStreamBuffer()
: this(UserStringsStream.DefaultName)
{
}
/// <summary>
/// Creates a new user-strings stream buffer.
/// </summary>
/// <param name="name">The name of the stream.</param>
public UserStringsStreamBuffer(string name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
_writer = new BinaryStreamWriter(_rawStream);
_writer.WriteByte(0);
}
/// <inheritdoc />
public string Name
{
get;
}
/// <inheritdoc />
public bool IsEmpty => _rawStream.Length <= 1;
/// <summary>
/// Imports the contents of a user strings stream and indexes all present strings.
/// </summary>
/// <param name="stream">The stream to import.</param>
public void ImportStream(UserStringsStream stream)
{
MetadataStreamBufferHelper.CloneBlobHeap(stream, _writer, (index, newIndex) =>
{
if (stream.GetStringByIndex(index) is { } str)
_strings[str] = newIndex;
});
}
/// <summary>
/// Appends raw data to the stream.
/// </summary>
/// <param name="data">The data to append.</param>
/// <returns>The index to the start of the data.</returns>
/// <remarks>
/// This method does not index the string. Calling <see cref="AppendRawData"/> or <see cref="GetStringIndex" />
/// on the same data will append the data a second time.
/// </remarks>
public uint AppendRawData(byte[] data)
{
uint offset = (uint) _rawStream.Length;
_writer.WriteBytes(data, 0, data.Length);
return offset;
}
private uint AppendString(string? value)
{
uint offset = (uint) _rawStream.Length;
if (value is null)
{
_writer.WriteByte(0);
return offset;
}
int byteCount = Encoding.Unicode.GetByteCount(value) + 1;
_writer.WriteCompressedUInt32((uint) byteCount);
byte[] rawData = new byte[byteCount];
Encoding.Unicode.GetBytes(value, 0, value.Length, rawData, 0);
rawData[byteCount - 1] = GetTerminatorByte(value);
AppendRawData(rawData);
return offset;
}
/// <summary>
/// Gets the index to the provided user-string. If the string is not present in the buffer, it will be appended to
/// the end of the stream.
/// </summary>
/// <param name="value">The user-string to lookup or add.</param>
/// <returns>The index of the user-string.</returns>
public uint GetStringIndex(string? value)
{
if (value is null)
return 0;
if (!_strings.TryGetValue(value, out uint offset))
{
offset = AppendString(value);
_strings.Add(value, offset);
}
return offset;
}
private static byte GetTerminatorByte(string data)
{
for (int i = 0; i < data.Length; i++)
{
char c = data[i];
if (c >= 0x01 && c <= 0x08
|| c >= 0x0E && c <= 0x1F
|| c == 0x27
|| c == 0x2D
|| c == 0x7F
|| c >= 0x100)
{
return 1;
}
}
return 0;
}
/// <summary>
/// Serializes
/// </summary>
/// <returns></returns>
public UserStringsStream CreateStream()
{
_writer.Align(4);
return new SerializedUserStringsStream(Name, _rawStream.ToArray());
}
/// <inheritdoc />
IMetadataStream IMetadataStreamBuffer.CreateStream() => CreateStream();
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Bundles\BundleFileTest.cs | AsmResolver.DotNet.Tests.Bundles
| BundleFileTest | [] | ['System.Linq', 'System.Text', 'AsmResolver.DotNet.Bundles', 'Xunit'] | xUnit | net8.0 | public class BundleFileTest
{
[Fact]
public void ReadUncompressedStringContents()
{
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6);
var file = manifest.Files.First(f => f.Type == BundleFileType.RuntimeConfigJson);
string contents = Encoding.UTF8.GetString(file.GetData()).Replace("\r", "");
Assert.Equal(@"{
""runtimeOptions"": {
""tfm"": ""net6.0"",
""framework"": {
""name"": ""Microsoft.NETCore.App"",
""version"": ""6.0.0""
},
""configProperties"": {
""System.Reflection.Metadata.MetadataUpdater.IsSupported"": false
}
}
}".Replace("\r", ""), contents);
}
[Fact]
public void ReadUncompressedAssemblyContents()
{
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6);
var bundleFile = manifest.Files.First(f => f.RelativePath == "HelloWorld.dll");
var embeddedImage = ModuleDefinition.FromBytes(bundleFile.GetData(), TestReaderParameters);
Assert.Equal("HelloWorld.dll", embeddedImage.Name);
}
} | 142 | 1,358 | using System;
using System.IO;
using System.IO.Compression;
using AsmResolver.Collections;
using AsmResolver.IO;
namespace AsmResolver.DotNet.Bundles
{
/// <summary>
/// Represents a single file in a .NET bundle manifest.
/// </summary>
public class BundleFile : IOwnedCollectionElement<BundleManifest>
{
private readonly LazyVariable<BundleFile, ISegment> _contents;
/// <summary>
/// Creates a new empty bundle file.
/// </summary>
/// <param name="relativePath">The path of the file, relative to the root of the bundle.</param>
public BundleFile(string relativePath)
{
RelativePath = relativePath;
_contents = new LazyVariable<BundleFile, ISegment>(x => x.GetContents());
}
/// <summary>
/// Creates a new bundle file.
/// </summary>
/// <param name="relativePath">The path of the file, relative to the root of the bundle.</param>
/// <param name="type">The type of the file.</param>
/// <param name="contents">The contents of the file.</param>
public BundleFile(string relativePath, BundleFileType type, byte[] contents)
: this(relativePath, type, new DataSegment(contents))
{
}
/// <summary>
/// Creates a new empty bundle file.
/// </summary>
/// <param name="relativePath">The path of the file, relative to the root of the bundle.</param>
/// <param name="type">The type of the file.</param>
/// <param name="contents">The contents of the file.</param>
public BundleFile(string relativePath, BundleFileType type, ISegment contents)
{
RelativePath = relativePath;
Type = type;
_contents = new LazyVariable<BundleFile, ISegment>(contents);
}
/// <summary>
/// Gets the parent manifest this file was added to.
/// </summary>
public BundleManifest? ParentManifest
{
get;
private set;
}
/// <inheritdoc />
BundleManifest? IOwnedCollectionElement<BundleManifest>.Owner
{
get => ParentManifest;
set => ParentManifest = value;
}
/// <summary>
/// Gets or sets the path to the file, relative to the root directory of the bundle.
/// </summary>
public string RelativePath
{
get;
set;
}
/// <summary>
/// Gets or sets the type of the file.
/// </summary>
public BundleFileType Type
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the data stored in <see cref="Contents"/> is compressed or not.
/// </summary>
/// <remarks>
/// The default implementation of the application host by Microsoft only supports compressing files if it is
/// a fully self-contained binary and the file is not the <c>.deps.json</c> nor the <c>.runtmeconfig.json</c>
/// file. This property does not do validation on any of these conditions. As such, if the file is supposed to be
/// compressed with any of these conditions not met, a custom application host template needs to be provided
/// upon serializing the bundle for it to be runnable.
/// </remarks>
public bool IsCompressed
{
get;
set;
}
/// <summary>
/// Gets or sets the raw contents of the file.
/// </summary>
public ISegment Contents
{
get => _contents.GetValue(this);
set => _contents.SetValue(value);
}
/// <summary>
/// Gets a value whether the contents of the file can be read using a <see cref="BinaryStreamReader"/>.
/// </summary>
public bool CanRead => Contents is IReadableSegment;
/// <summary>
/// Obtains the raw contents of the file.
/// </summary>
/// <returns>The contents.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Contents"/> property.
/// </remarks>
protected virtual ISegment? GetContents() => null;
/// <summary>
/// Attempts to create a <see cref="BinaryStreamReader"/> that points to the start of the raw contents of the file.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns><c>true</c> if the reader was constructed successfully, <c>false</c> otherwise.</returns>
public bool TryGetReader(out BinaryStreamReader reader)
{
if (Contents is IReadableSegment segment)
{
reader = segment.CreateReader();
return true;
}
reader = default;
return false;
}
/// <summary>
/// Reads (and decompresses if necessary) the contents of the file.
/// </summary>
/// <returns>The contents.</returns>
public byte[] GetData() => GetData(true);
/// <summary>
/// Reads the contents of the file.
/// </summary>
/// <param name="decompressIfRequired"><c>true</c> if the contents should be decompressed or not when necessary.</param>
/// <returns>The contents.</returns>
public byte[] GetData(bool decompressIfRequired)
{
if (TryGetReader(out var reader))
{
byte[] contents = reader.ReadToEnd();
if (decompressIfRequired && IsCompressed)
{
using var outputStream = new MemoryStream();
using var inputStream = new MemoryStream(contents);
using (var deflate = new DeflateStream(inputStream, CompressionMode.Decompress))
{
deflate.CopyTo(outputStream);
}
contents = outputStream.ToArray();
}
return contents;
}
throw new InvalidOperationException("Contents of file is not readable.");
}
/// <summary>
/// Marks the file as compressed, compresses the file contents, and replaces the value of <see cref="Contents"/>
/// with the result.
/// </summary>
/// <exception cref="InvalidOperationException">Occurs when the file was already compressed.</exception>
/// <remarks>
/// The default implementation of the application host by Microsoft only supports compressing files if it is
/// a fully self-contained binary and the file is not the <c>.deps.json</c> nor the <c>.runtmeconfig.json</c>
/// file. This method does not do validation on any of these conditions. As such, if the file is supposed to be
/// compressed with any of these conditions not met, a custom application host template needs to be provided
/// upon serializing the bundle for it to be runnable.
/// </remarks>
public void Compress()
{
if (IsCompressed)
throw new InvalidOperationException("File is already compressed.");
using var inputStream = new MemoryStream(GetData());
using var outputStream = new MemoryStream();
using (var deflate = new DeflateStream(outputStream, CompressionMode.Compress))
{
inputStream.CopyTo(deflate);
}
Contents = new DataSegment(outputStream.ToArray());
IsCompressed = true;
}
/// <summary>
/// Marks the file as uncompressed, decompresses the file contents, and replaces the value of
/// <see cref="Contents"/> with the result.
/// </summary>
/// <exception cref="InvalidOperationException">Occurs when the file was not compressed.</exception>
public void Decompress()
{
if (!IsCompressed)
throw new InvalidOperationException("File is not compressed.");
Contents = new DataSegment(GetData(true));
IsCompressed = false;
}
/// <inheritdoc />
public override string ToString() => RelativePath;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Bundles\BundleManifestTest.cs | AsmResolver.DotNet.Tests.Bundles
| BundleManifestTest | ['private readonly TemporaryDirectoryFixture _fixture;'] | ['System', 'System.IO', 'System.Linq', 'System.Runtime.CompilerServices', 'System.Runtime.InteropServices', 'System.Text', 'AsmResolver.DotNet.Bundles', 'AsmResolver.DotNet.Serialized', 'AsmResolver.IO', 'AsmResolver.PE', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.File', 'AsmResolver.PE.Win32Resources.Version', 'AsmResolver.Tests.Runners', 'Xunit'] | xUnit | net8.0 | public class BundleManifestTest : IClassFixture<TemporaryDirectoryFixture>
{
private readonly TemporaryDirectoryFixture _fixture;
public BundleManifestTest(TemporaryDirectoryFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void ReadBundleManifestHeaderV1()
{
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V1);
Assert.Equal(1u, manifest.MajorVersion);
Assert.Equal("j7LK4is5ipe1CCtiafaTb8uhSOR7JhI=", manifest.BundleID);
Assert.Equal(new[]
{
"HelloWorld.dll", "HelloWorld.deps.json", "HelloWorld.runtimeconfig.json"
}, manifest.Files.Select(f => f.RelativePath));
}
[Fact]
public void ReadBundleManifestHeaderV2()
{
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V2);
Assert.Equal(2u, manifest.MajorVersion);
Assert.Equal("poUQ+RBCefcEL4xrSAXdE2I5M+5D_Pk=", manifest.BundleID);
Assert.Equal(new[]
{
"HelloWorld.dll", "HelloWorld.deps.json", "HelloWorld.runtimeconfig.json"
}, manifest.Files.Select(f => f.RelativePath));
}
[Fact]
public void ReadBundleManifestHeaderV6()
{
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6);
Assert.Equal(6u, manifest.MajorVersion);
Assert.Equal("lc43r48XAQNxN7Cx8QQvO9JgZI5lqPA=", manifest.BundleID);
Assert.Equal(new[]
{
"HelloWorld.dll", "HelloWorld.deps.json", "HelloWorld.runtimeconfig.json"
}, manifest.Files.Select(f => f.RelativePath));
}
[SkippableFact]
public void WriteBundleManifestV1Windows()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
AssertWriteManifestWindowsPreservesOutput(
BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V1),
"3.1",
"HelloWorld.dll",
"Hello, World!\n");
}
[SkippableFact]
public void WriteBundleManifestV2Windows()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
AssertWriteManifestWindowsPreservesOutput(
BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V2),
"5.0",
"HelloWorld.dll",
"Hello, World!\n");
}
[SkippableFact]
public void WriteBundleManifestV6Windows()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
AssertWriteManifestWindowsPreservesOutput(
BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6),
"6.0",
"HelloWorld.dll",
"Hello, World!\n");
}
[Fact]
public void DetectNetCoreApp31Bundle()
{
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V1);
Assert.Equal(
new DotNetRuntimeInfo(DotNetRuntimeInfo.NetCoreApp, new Version(3, 1)),
manifest.GetTargetRuntime()
);
}
[Fact]
public void DetectNet50Bundle()
{
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V2);
Assert.Equal(
new DotNetRuntimeInfo(DotNetRuntimeInfo.NetCoreApp, new Version(5, 0)),
manifest.GetTargetRuntime()
);
}
[Fact]
public void DetectNet60Bundle()
{
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6);
Assert.Equal(
new DotNetRuntimeInfo(DotNetRuntimeInfo.NetCoreApp, new Version(6, 0)),
manifest.GetTargetRuntime()
);
}
[Fact]
public void DetectNet80Bundle()
{
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6_WithDependency);
Assert.Equal(
new DotNetRuntimeInfo(DotNetRuntimeInfo.NetCoreApp, new Version(8, 0)),
manifest.GetTargetRuntime()
);
}
[SkippableFact]
public void MarkFilesAsCompressed()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6);
manifest.Files.First(f => f.RelativePath == "HelloWorld.dll").Compress();
using var stream = new MemoryStream();
ulong address = manifest.WriteManifest(new BinaryStreamWriter(stream), false);
var reader = new BinaryStreamReader(stream.ToArray());
reader.Offset = address;
var newManifest = BundleManifest.FromReader(reader);
AssertBundlesAreEqual(manifest, newManifest);
}
[SkippableTheory()]
[InlineData(SubSystem.WindowsCui)]
[InlineData(SubSystem.WindowsGui)]
public void WriteWithSubSystem(SubSystem subSystem)
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6);
string appHostTemplatePath = FindAppHostTemplate("6.0");
using var stream = new MemoryStream();
var parameters = BundlerParameters.FromTemplate(appHostTemplatePath, "HelloWorld.dll");
parameters.SubSystem = subSystem;
manifest.WriteUsingTemplate(stream, parameters);
var newFile = PEFile.FromBytes(stream.ToArray());
Assert.Equal(subSystem, newFile.OptionalHeader.SubSystem);
}
[SkippableFact]
public void WriteWithWin32Resources()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6_WithResources);
string appHostTemplatePath = FindAppHostTemplate("6.0");
// Obtain expected version info.
var oldImage = PEImage.FromBytes(
Properties.Resources.HelloWorld_SingleFile_V6_WithResources,
TestReaderParameters.PEReaderParameters
);
var versionInfo = VersionInfoResource.FromDirectory(oldImage.Resources!)!;
// Bundle with PE image as template for PE headers and resources.
using var stream = new MemoryStream();
manifest.WriteUsingTemplate(stream, BundlerParameters.FromTemplate(
File.ReadAllBytes(appHostTemplatePath),
"HelloWorld.dll",
oldImage));
// Verify new file still runs as expected.
string output = _fixture
.GetRunner<NativePERunner>()
.RunAndCaptureOutput("HelloWorld.exe", stream.ToArray());
Assert.Equal("Hello, World!\n", output);
// Verify that resources were added properly.
var newImage = PEImage.FromBytes(stream.ToArray());
Assert.NotNull(newImage.Resources);
var newVersionInfo = VersionInfoResource.FromDirectory(newImage.Resources);
Assert.NotNull(newVersionInfo);
Assert.Equal(versionInfo.FixedVersionInfo.FileVersion, newVersionInfo.FixedVersionInfo.FileVersion);
}
[Fact]
public void NewManifestShouldGenerateBundleIdIfUnset()
{
var manifest = new BundleManifest(6);
manifest.Files.Add(new BundleFile("HelloWorld.dll", BundleFileType.Assembly,
Properties.Resources.HelloWorld_NetCore));
manifest.Files.Add(new BundleFile("HelloWorld.runtimeconfig.json", BundleFileType.RuntimeConfigJson,
Encoding.UTF8.GetBytes(@"{
""runtimeOptions"": {
""tfm"": ""net6.0"",
""includedFrameworks"": [
{
""name"": ""Microsoft.NETCore.App"",
""version"": ""6.0.0""
}
]
}
}")));
Assert.Null(manifest.BundleID);
using var stream = new MemoryStream();
manifest.WriteUsingTemplate(stream, BundlerParameters.FromTemplate(
FindAppHostTemplate("6.0"),
"HelloWorld.dll"));
Assert.NotNull(manifest.BundleID);
}
[Fact]
public void SameManifestContentsShouldResultInSameBundleID()
{
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6);
var newManifest = new BundleManifest(manifest.MajorVersion);
foreach (var file in manifest.Files)
newManifest.Files.Add(new BundleFile(file.RelativePath, file.Type, file.GetData()));
Assert.Equal(manifest.BundleID, newManifest.GenerateDeterministicBundleID());
}
[SkippableFact]
public void PatchAndRepackageExistingBundleV1()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
AssertPatchAndRepackageChangesOutput(Properties.Resources.HelloWorld_SingleFile_V1);
}
[SkippableFact]
public void PatchAndRepackageExistingBundleV2()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
AssertPatchAndRepackageChangesOutput(Properties.Resources.HelloWorld_SingleFile_V2);
}
[SkippableFact]
public void PatchAndRepackageExistingBundleV6()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
AssertPatchAndRepackageChangesOutput(Properties.Resources.HelloWorld_SingleFile_V6);
}
private void AssertPatchAndRepackageChangesOutput(
byte[] original,
[CallerFilePath] string className = "File",
[CallerMemberName] string methodName = "Method")
{
// Read manifest and locate main entry point file.
var manifest = BundleManifest.FromBytes(original);
var mainFile = manifest.Files.First(f => f.RelativePath.Contains("HelloWorld.dll"));
// Patch entry point file.
var module = ModuleDefinition.FromBytes(mainFile.GetData(), TestReaderParameters);
module.ManagedEntryPointMethod!.CilMethodBody!
.Instructions.First(i => i.OpCode.Code == CilCode.Ldstr)
.Operand = "Hello, Mars!";
using var moduleStream = new MemoryStream();
module.Write(moduleStream);
mainFile.Contents = new DataSegment(moduleStream.ToArray());
mainFile.IsCompressed = false;
manifest.BundleID = manifest.GenerateDeterministicBundleID();
// Repackage bundle using existing bundle as template.
using var bundleStream = new MemoryStream();
manifest.WriteUsingTemplate(bundleStream, BundlerParameters.FromExistingBundle(
original,
mainFile.RelativePath));
// Verify application runs as expected.
DeleteTempExtractionDirectory(manifest, "HelloWorld.dll");
string output = _fixture
.GetRunner<NativePERunner>()
.RunAndCaptureOutput(
"HelloWorld.exe",
bundleStream.ToArray(),
null,
5000,
className,
methodName);
Assert.Equal("Hello, Mars!\n", output);
}
private void AssertWriteManifestWindowsPreservesOutput(
BundleManifest manifest,
string sdkVersion,
string fileName,
string expectedOutput,
[CallerFilePath] string className = "File",
[CallerMemberName] string methodName = "Method")
{
string appHostTemplatePath = FindAppHostTemplate(sdkVersion);
DeleteTempExtractionDirectory(manifest, fileName);
using var stream = new MemoryStream();
manifest.WriteUsingTemplate(stream, BundlerParameters.FromTemplate(appHostTemplatePath, fileName));
var newManifest = BundleManifest.FromBytes(stream.ToArray());
AssertBundlesAreEqual(manifest, newManifest);
string output = _fixture
.GetRunner<NativePERunner>()
.RunAndCaptureOutput(
Path.ChangeExtension(fileName, ".exe"),
stream.ToArray(),
null,
5000,
className,
methodName);
Assert.Equal(expectedOutput.Replace("\r\n", "\n"), output);
}
private static void DeleteTempExtractionDirectory(BundleManifest manifest, string fileName)
{
if (manifest.MajorVersion != 1 || manifest.BundleID is null || !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return;
string tempPath = Path.Combine(Path.GetTempPath(), ".net", Path.GetFileNameWithoutExtension(fileName), manifest.BundleID);
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
private static string FindAppHostTemplate(string sdkVersion)
{
string sdkPath = Path.Combine(DotNetCorePathProvider.DefaultInstallationPath!, "sdk");
string sdkVersionPath = null;
foreach (string dir in Directory.GetDirectories(sdkPath))
{
if (Path.GetFileName(dir).StartsWith(sdkVersion))
{
sdkVersionPath = Path.Combine(dir);
break;
}
}
if (string.IsNullOrEmpty(sdkVersionPath))
{
throw new InvalidOperationException(
$"Could not find the apphost template for .NET SDK version {sdkVersion}. This is an indication that the test environment does not have this SDK installed.");
}
string fileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "apphost.exe"
: "apphost";
string finalPath = Path.Combine(sdkVersionPath, "AppHostTemplate", fileName);
if (!File.Exists(finalPath))
{
throw new InvalidOperationException(
$"Could not find the apphost template for .NET SDK version {sdkVersion}. This is an indication that the test environment does not have this SDK installed.");
}
return finalPath;
}
private static void AssertBundlesAreEqual(BundleManifest manifest, BundleManifest newManifest)
{
Assert.Equal(manifest.MajorVersion, newManifest.MajorVersion);
Assert.Equal(manifest.MinorVersion, newManifest.MinorVersion);
Assert.Equal(manifest.BundleID, newManifest.BundleID);
Assert.Equal(manifest.Files.Count, newManifest.Files.Count);
for (int i = 0; i < manifest.Files.Count; i++)
{
var file = manifest.Files[i];
var newFile = newManifest.Files[i];
Assert.Equal(file.Type, newFile.Type);
Assert.Equal(file.RelativePath, newFile.RelativePath);
Assert.Equal(file.IsCompressed, newFile.IsCompressed);
Assert.Equal(file.GetData(), newFile.GetData());
}
}
[Fact]
public void BundleRuntimeContext()
{
var manifest = BundleManifest.FromBytes(Properties.Resources.HelloWorld_SingleFile_V6_WithDependency);
var context = new RuntimeContext(manifest);
var module = ModuleDefinition.FromBytes(
manifest.Files.First(x => x.RelativePath == "MainApp.dll").GetData(),
new ModuleReaderParameters(context));
var resolved = module.AssemblyReferences.First(x => x.Name == "Library").Resolve();
Assert.NotNull(resolved);
}
} | 480 | 17,267 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.DotNet.Config.Json;
using AsmResolver.IO;
using AsmResolver.PE.File;
using AsmResolver.PE.Win32Resources.Builder;
using AsmResolver.Shims;
namespace AsmResolver.DotNet.Bundles
{
/// <summary>
/// Represents a set of bundled files embedded in a .NET application host or single-file host.
/// </summary>
public class BundleManifest
{
private const int DefaultBundleIDLength = 12;
private static readonly byte[] BundleSignature =
{
0x8b, 0x12, 0x02, 0xb9, 0x6a, 0x61, 0x20, 0x38,
0x72, 0x7b, 0x93, 0x02, 0x14, 0xd7, 0xa0, 0x32,
0x13, 0xf5, 0xb9, 0xe6, 0xef, 0xae, 0x33, 0x18,
0xee, 0x3b, 0x2d, 0xce, 0x24, 0xb3, 0x6a, 0xae
};
private IList<BundleFile>? _files;
/// <summary>
/// Initializes an empty bundle manifest.
/// </summary>
protected BundleManifest()
{
}
/// <summary>
/// Creates a new bundle manifest.
/// </summary>
/// <param name="majorVersionNumber">The file format version.</param>
public BundleManifest(uint majorVersionNumber)
{
MajorVersion = majorVersionNumber;
MinorVersion = 0;
}
/// <summary>
/// Creates a new bundle manifest with a specific bundle identifier.
/// </summary>
/// <param name="majorVersionNumber">The file format version.</param>
/// <param name="bundleId">The unique bundle manifest identifier.</param>
public BundleManifest(uint majorVersionNumber, string bundleId)
{
MajorVersion = majorVersionNumber;
MinorVersion = 0;
BundleID = bundleId;
}
/// <summary>
/// Gets or sets the major file format version of the bundle.
/// </summary>
/// <remarks>
/// Version numbers recognized by the CLR are:
/// <list type="bullet">
/// <item>1 for .NET Core 3.1</item>
/// <item>2 for .NET 5.0</item>
/// <item>6 for .NET 6.0</item>
/// </list>
/// </remarks>
public uint MajorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the minor file format version of the bundle.
/// </summary>
/// <remarks>
/// This value is ignored by the CLR and should be set to 0.
/// </remarks>
public uint MinorVersion
{
get;
set;
}
/// <summary>
/// Gets or sets the unique identifier for the bundle manifest.
/// </summary>
/// <remarks>
/// When this property is set to <c>null</c>, the bundle identifier will be generated upon writing the manifest
/// based on the contents of the manifest.
/// </remarks>
public string? BundleID
{
get;
set;
}
/// <summary>
/// Gets or sets flags associated to the bundle.
/// </summary>
public BundleManifestFlags Flags
{
get;
set;
}
/// <summary>
/// Gets a collection of files stored in the bundle.
/// </summary>
public IList<BundleFile> Files
{
get
{
if (_files is null)
Interlocked.CompareExchange(ref _files, GetFiles(), null);
return _files;
}
}
/// <summary>
/// Attempts to automatically locate and parse the bundle header in the provided file.
/// </summary>
/// <param name="filePath">The path to the file to read.</param>
/// <returns>The read manifest.</returns>
public static BundleManifest FromFile(string filePath)
{
return FromBytes(File.ReadAllBytes(filePath));
}
/// <summary>
/// Attempts to automatically locate and parse the bundle header in the provided file.
/// </summary>
/// <param name="data">The raw contents of the file to read.</param>
/// <returns>The read manifest.</returns>
public static BundleManifest FromBytes(byte[] data)
{
return FromDataSource(new ByteArrayDataSource(data));
}
/// <summary>
/// Parses the bundle header in the provided file at the provided address.
/// </summary>
/// <param name="data">The raw contents of the file to read.</param>
/// <param name="offset">The address within the file to start reading the bundle at.</param>
/// <returns>The read manifest.</returns>
public static BundleManifest FromBytes(byte[] data, ulong offset)
{
return FromDataSource(new ByteArrayDataSource(data), offset);
}
/// <summary>
/// Attempts to automatically locate and parse the bundle header in the provided file.
/// </summary>
/// <param name="source">The raw contents of the file to read.</param>
/// <returns>The read manifest.</returns>
public static BundleManifest FromDataSource(IDataSource source)
{
long address = FindBundleManifestAddress(source);
if (address == -1)
throw new BadImageFormatException("File does not contain an AppHost bundle signature.");
return FromDataSource(source, (ulong) address);
}
/// <summary>
/// Parses the bundle header in the provided file at the provided address.
/// </summary>
/// <param name="source">The raw contents of the file to read.</param>
/// <param name="offset">The address within the file to start reading the bundle at.</param>
/// <returns>The read manifest.</returns>
public static BundleManifest FromDataSource(IDataSource source, ulong offset)
{
var reader = new BinaryStreamReader(source, 0, 0, (uint) source.Length)
{
Offset = offset
};
return FromReader(reader);
}
/// <summary>
/// Parses the bundle header from the provided input stream.
/// </summary>
/// <param name="reader">The input stream pointing to the start of the bundle to read.</param>
/// <returns>The read manifest.</returns>
public static BundleManifest FromReader(BinaryStreamReader reader) => new SerializedBundleManifest(reader);
internal static long FindInFile(IDataSource source, byte[] needle)
{
// Note: For performance reasons, we read data from the data source in blocks, such that we avoid
// virtual-dispatch calls and do the searching directly on a byte array instead.
byte[] buffer = new byte[0x1000];
ulong start = 0;
while (start < source.Length)
{
int read = source.ReadBytes(start, buffer, 0, buffer.Length);
for (int i = sizeof(ulong); i < read - needle.Length; i++)
{
bool fullMatch = true;
for (int j = 0; fullMatch && j < needle.Length; j++)
{
if (buffer[i + j] != needle[j])
fullMatch = false;
}
if (fullMatch)
return (long) start + i;
}
start += (ulong) read;
}
return -1;
}
private static long ReadBundleManifestAddress(IDataSource source, long signatureAddress)
{
var reader = new BinaryStreamReader(source, (ulong) signatureAddress - sizeof(ulong), 0, 8);
ulong manifestAddress = reader.ReadUInt64();
return source.IsValidAddress(manifestAddress)
? (long) manifestAddress
: -1;
}
/// <summary>
/// Attempts to find the start of the bundle header in the provided file.
/// </summary>
/// <param name="source">The file to locate the bundle header in.</param>
/// <returns>The offset, or -1 if none was found.</returns>
public static long FindBundleManifestAddress(IDataSource source)
{
long signatureAddress = FindInFile(source, BundleSignature);
if (signatureAddress == -1)
return -1;
return ReadBundleManifestAddress(source, signatureAddress);
}
/// <summary>
/// Gets a value indicating whether the provided data source contains a conventional bundled assembly signature.
/// </summary>
/// <param name="source">The file to locate the bundle header in.</param>
/// <returns><c>true</c> if a bundle signature was found, <c>false</c> otherwise.</returns>
public static bool IsBundledAssembly(IDataSource source) => FindBundleManifestAddress(source) != -1;
/// <summary>
/// Obtains the list of files stored in the bundle.
/// </summary>
/// <returns>The files</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Files"/> property.
/// </remarks>
protected virtual IList<BundleFile> GetFiles() => new OwnedCollection<BundleManifest, BundleFile>(this);
/// <summary>
/// Generates a bundle identifier based on the SHA-256 hashes of all files in the manifest.
/// </summary>
/// <returns>The generated bundle identifier.</returns>
public string GenerateDeterministicBundleID()
{
using var manifestHasher = SHA256.Create();
for (int i = 0; i < Files.Count; i++)
{
var file = Files[i];
using var fileHasher = SHA256.Create();
byte[] fileHash = fileHasher.ComputeHash(file.GetData());
manifestHasher.TransformBlock(fileHash, 0, fileHash.Length, fileHash, 0);
}
manifestHasher.TransformFinalBlock(ArrayShim.Empty<byte>(), 0, 0);
byte[] manifestHash = manifestHasher.Hash!;
return Convert.ToBase64String(manifestHash)
.Substring(DefaultBundleIDLength)
.Replace('/', '_');
}
/// <summary>
/// Determines the runtime that the assemblies in the bundle are targeting.
/// </summary>
/// <returns>The runtime.</returns>
/// <exception cref="ArgumentException">Occurs when the runtime could not be determined.</exception>
public DotNetRuntimeInfo GetTargetRuntime()
{
return TryGetTargetRuntime(out var runtime)
? runtime
: throw new ArgumentException("Could not determine the target runtime for the bundle");
}
/// <summary>
/// Attempts to determine the runtime that the assemblies in the bundle are targeting.
/// </summary>
/// <param name="targetRuntime">When the method returns <c>true</c>, contains the target runtime.</param>
/// <returns><c>true</c> if the runtime could be determined, <c>false</c> otherwise.</returns>
public bool TryGetTargetRuntime(out DotNetRuntimeInfo targetRuntime)
{
// Try find the runtimeconfig.json file.
for (int i = 0; i < Files.Count; i++)
{
var file = Files[i];
if (file.Type == BundleFileType.RuntimeConfigJson)
{
var config = RuntimeConfiguration.FromJson(Encoding.UTF8.GetString(file.GetData()));
if (config is not {RuntimeOptions.TargetFrameworkMoniker: { } tfm})
continue;
if (DotNetRuntimeInfo.TryParseMoniker(tfm, out targetRuntime))
return true;
}
}
// If it is not present, make a best effort guess based on the bundle file format version.
switch (MajorVersion)
{
case 1:
targetRuntime = new DotNetRuntimeInfo(DotNetRuntimeInfo.NetCoreApp, new Version(3, 1));
return true;
case 2:
targetRuntime = new DotNetRuntimeInfo(DotNetRuntimeInfo.NetCoreApp, new Version(5, 0));
return true;
case 6:
targetRuntime = new DotNetRuntimeInfo(DotNetRuntimeInfo.NetCoreApp, new Version(6, 0));
return true;
}
targetRuntime = default;
return false;
}
/// <summary>
/// Constructs a new application host file based on the bundle manifest.
/// </summary>
/// <param name="outputPath">The path of the file to write to.</param>
/// <param name="parameters">The parameters to use for bundling all files into a single executable.</param>
public void WriteUsingTemplate(string outputPath, in BundlerParameters parameters)
{
using var fs = File.Create(outputPath);
WriteUsingTemplate(fs, parameters);
}
/// <summary>
/// Constructs a new application host file based on the bundle manifest.
/// </summary>
/// <param name="outputStream">The output stream to write to.</param>
/// <param name="parameters">The parameters to use for bundling all files into a single executable.</param>
public void WriteUsingTemplate(Stream outputStream, in BundlerParameters parameters)
{
WriteUsingTemplate(new BinaryStreamWriter(outputStream), parameters);
}
/// <summary>
/// Constructs a new application host file based on the bundle manifest.
/// </summary>
/// <param name="writer">The output stream to write to.</param>
/// <param name="parameters">The parameters to use for bundling all files into a single executable.</param>
public void WriteUsingTemplate(BinaryStreamWriter writer, BundlerParameters parameters)
{
// Verify entry point assembly exists within the bundle and is a correct length.
var appBinaryEntry = Files.FirstOrDefault(f => f.RelativePath == parameters.ApplicationBinaryPath);
if (appBinaryEntry is null)
throw new ArgumentException($"Application {parameters.ApplicationBinaryPath} does not exist within the bundle.");
byte[] appBinaryPathBytes = Encoding.UTF8.GetBytes(parameters.ApplicationBinaryPath);
if (appBinaryPathBytes.Length > 1024)
throw new ArgumentException("Application binary path cannot exceed 1024 bytes.");
// Patch headers when necessary.
if (!parameters.IsArm64Linux)
EnsureAppHostPEHeadersAreUpToDate(ref parameters);
var appHostTemplateSource = new ByteArrayDataSource(parameters.ApplicationHostTemplate);
long signatureAddress = FindInFile(appHostTemplateSource, BundleSignature);
if (signatureAddress == -1)
throw new ArgumentException("AppHost template does not contain the bundle signature.");
long appBinaryPathAddress = FindInFile(appHostTemplateSource, parameters.PathPlaceholder);
if (appBinaryPathAddress == -1)
throw new ArgumentException("AppHost template does not contain the application binary path placeholder.");
// Write template.
writer.WriteBytes(parameters.ApplicationHostTemplate);
// Append manifest.
writer.Offset = writer.Length;
ulong headerAddress = WriteManifest(writer, parameters.IsArm64Linux);
// Update header address in apphost template.
writer.Offset = (ulong) signatureAddress - sizeof(ulong);
writer.WriteUInt64(headerAddress);
// Replace binary path placeholder with actual path.
writer.Offset = (ulong) appBinaryPathAddress;
writer.WriteBytes(appBinaryPathBytes);
if (parameters.PathPlaceholder.Length > appBinaryPathBytes.Length)
writer.WriteZeroes(parameters.PathPlaceholder.Length - appBinaryPathBytes.Length);
}
private static void EnsureAppHostPEHeadersAreUpToDate(ref BundlerParameters parameters)
{
PEFile file;
try
{
file = PEFile.FromBytes(parameters.ApplicationHostTemplate);
}
catch (BadImageFormatException)
{
// Template is not a PE file.
return;
}
bool changed = false;
// Ensure same Windows subsystem is used (typically required for GUI applications).
if (file.OptionalHeader.SubSystem != parameters.SubSystem)
{
file.OptionalHeader.SubSystem = parameters.SubSystem;
changed = true;
}
// If the app binary has resources (such as an icon or version info), we need to copy it into the
// AppHost template so that they are also visible from the final packed executable.
if (parameters.Resources is { } directory)
{
// Put original resource directory in a new .rsrc section.
var buffer = new ResourceDirectoryBuffer();
buffer.AddDirectory(directory);
var rsrc = new PESection(".rsrc", SectionFlags.MemoryRead | SectionFlags.ContentInitializedData);
rsrc.Contents = buffer;
// Find .reloc section, and insert .rsrc before it if it is present. Otherwise just append to the end.
int sectionIndex = file.Sections.Count - 1;
for (int i = file.Sections.Count - 1; i >= 0; i--)
{
if (file.Sections[i].Name == ".reloc")
{
sectionIndex = i;
break;
}
}
file.Sections.Insert(sectionIndex, rsrc);
// Update resource data directory va + size.
file.AlignSections();
file.OptionalHeader.DataDirectories[(int) DataDirectoryIndex.ResourceDirectory] = new DataDirectory(
buffer.Rva,
buffer.GetPhysicalSize());
changed = true;
}
// Rebuild AppHost PE file if necessary.
if (changed)
{
using var stream = new MemoryStream();
file.Write(stream);
parameters.ApplicationHostTemplate = stream.ToArray();
}
}
/// <summary>
/// Writes the manifest to an output stream.
/// </summary>
/// <param name="writer">The output stream to write to.</param>
/// <param name="isArm64Linux"><c>true</c> if the application host is a Linux ELF binary targeting ARM64.</param>
/// <returns>The address of the bundle header.</returns>
/// <remarks>
/// This does not necessarily produce a working executable file, it only writes the contents of the entire manifest,
/// without a host application that invokes the manifest. If you want to produce a runnable executable, use one
/// of the <c>WriteUsingTemplate</c> methods instead.
/// </remarks>
public ulong WriteManifest(BinaryStreamWriter writer, bool isArm64Linux)
{
WriteFileContents(writer, isArm64Linux
? 4096u
: 16u);
ulong headerAddress = writer.Offset;
WriteManifestHeader(writer);
return headerAddress;
}
private void WriteFileContents(BinaryStreamWriter writer, uint alignment)
{
for (int i = 0; i < Files.Count; i++)
{
var file = Files[i];
if (file.Type == BundleFileType.Assembly)
writer.Align(alignment);
file.Contents.UpdateOffsets(new RelocationParameters(writer.Offset, (uint) writer.Offset));
file.Contents.Write(writer);
}
}
private void WriteManifestHeader(BinaryStreamWriter writer)
{
writer.WriteUInt32(MajorVersion);
writer.WriteUInt32(MinorVersion);
writer.WriteInt32(Files.Count);
BundleID ??= GenerateDeterministicBundleID();
writer.WriteBinaryFormatterString(BundleID);
if (MajorVersion >= 2)
{
WriteFileOffsetSizePair(writer, Files.FirstOrDefault(f => f.Type == BundleFileType.DepsJson));
WriteFileOffsetSizePair(writer, Files.FirstOrDefault(f => f.Type == BundleFileType.RuntimeConfigJson));
writer.WriteUInt64((ulong) Flags);
}
WriteFileHeaders(writer);
}
private void WriteFileHeaders(BinaryStreamWriter writer)
{
for (int i = 0; i < Files.Count; i++)
{
var file = Files[i];
WriteFileOffsetSizePair(writer, file);
if (MajorVersion >= 6)
writer.WriteUInt64(file.IsCompressed ? file.Contents.GetPhysicalSize() : 0);
writer.WriteByte((byte) file.Type);
writer.WriteBinaryFormatterString(file.RelativePath);
}
}
private static void WriteFileOffsetSizePair(BinaryStreamWriter writer, BundleFile? file)
{
if (file is not null)
{
writer.WriteUInt64(file.Contents.Offset);
writer.WriteUInt64((ulong) file.GetData().Length);
}
else
{
writer.WriteUInt64(0);
writer.WriteUInt64(0);
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Code\Cil\CilInstructionCollectionTest.cs | AsmResolver.DotNet.Tests.Code.Cil
| CilInstructionCollectionTest | ['private readonly ModuleDefinition _module;'] | ['System', 'System.Linq', 'AsmResolver.DotNet.Code.Cil', 'AsmResolver.DotNet.Signatures', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class CilInstructionCollectionTest
{
private readonly ModuleDefinition _module;
public CilInstructionCollectionTest()
{
_module = new ModuleDefinition("DummyModule");
}
private CilInstructionCollection CreateDummyMethod(bool hasThis, int paramCount, int localCount)
{
var flags = hasThis
? MethodAttributes.Public
: MethodAttributes.Public | MethodAttributes.Static;
var parameterTypes = Enumerable.Repeat<TypeSignature>(_module.CorLibTypeFactory.Object, paramCount);
var signature = hasThis
? MethodSignature.CreateInstance(_module.CorLibTypeFactory.Void, parameterTypes)
: MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void, parameterTypes);
var method = new MethodDefinition("Dummy", flags, signature);
var body = new CilMethodBody(method);
for (int i = 0; i < localCount; i++)
body.LocalVariables.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
method.MethodBody = body;
return body.Instructions;
}
[Theory]
[InlineData(0, CilCode.Ldarg_0)]
[InlineData(1, CilCode.Ldarg_1)]
[InlineData(2, CilCode.Ldarg_2)]
[InlineData(3, CilCode.Ldarg_3)]
public void OptimizeFirst4ArgumentsToMacros(int index, CilCode expectedMacro)
{
var instructions = CreateDummyMethod(false, 4, 0);
instructions.Add(CilOpCodes.Ldarg, instructions.Owner.Owner.Parameters[index]);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(expectedMacro.ToOpCode(), instructions[0].OpCode);
Assert.Null(instructions[0].Operand);
}
[Fact]
public void OptimizeHiddenThisToLdarg0()
{
var instructions = CreateDummyMethod(true, 0, 0);
instructions.Add(CilOpCodes.Ldarg, instructions.Owner.Owner.Parameters.ThisParameter!);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(CilOpCodes.Ldarg_0, instructions[0].OpCode);
Assert.Null(instructions[0].Operand);
}
[Fact]
public void BranchWithSmallPositiveDeltaShouldOptimizeToShortBranch()
{
var instructions = CreateDummyMethod(false, 0, 0);
var target = new CilInstructionLabel();
instructions.Add(CilOpCodes.Br, target);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
target.Instruction = instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(CilOpCodes.Br_S, instructions[0].OpCode);
}
[Fact]
public void BranchWithSmallNegativeDeltaShouldOptimizeToShortBranch()
{
var instructions = CreateDummyMethod(false, 0, 0);
var target = new CilInstructionLabel();
target.Instruction = instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Br, target);
instructions.OptimizeMacros();
Assert.Equal(CilOpCodes.Br_S, instructions[3].OpCode);
}
[Fact]
public void BranchWithLargePositiveDeltaShouldNotOptimize()
{
var instructions = CreateDummyMethod(false, 0, 0);
var target = new CilInstructionLabel();
instructions.Add(CilOpCodes.Br, target);
for (int i = 0; i < 255; i++)
instructions.Add(CilOpCodes.Nop);
target.Instruction = instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(CilOpCodes.Br, instructions[0].OpCode);
}
[Fact]
public void BranchWithLargeNegativeDeltaShouldNotOptimize()
{
var instructions = CreateDummyMethod(false, 0, 0);
var target = new CilInstructionLabel();
target.Instruction = instructions.Add(CilOpCodes.Nop);
for (int i = 0; i < 255; i++)
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Br, target);
instructions.OptimizeMacros();
Assert.Equal(CilOpCodes.Br, instructions[^1].OpCode);
}
[Fact]
public void BranchWithInitialLargeDeltaButSmallDeltaAfterFirstPassShouldOptimize()
{
var instructions = CreateDummyMethod(false, 0, 0);
var target = new CilInstructionLabel();
instructions.Add(CilOpCodes.Br, target);
for (int i = 0; i < 60; i++)
{
instructions.Add(CilOpCodes.Ldc_I4, 1);
instructions.Add(CilOpCodes.Pop);
}
target.Instruction = instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(CilOpCodes.Br_S, instructions[0].OpCode);
}
[Theory]
[InlineData(0, CilCode.Ldloc_0)]
[InlineData(1, CilCode.Ldloc_1)]
[InlineData(2, CilCode.Ldloc_2)]
[InlineData(3, CilCode.Ldloc_3)]
[InlineData(4, CilCode.Ldloc_S)]
[InlineData(255, CilCode.Ldloc_S)]
[InlineData(256, CilCode.Ldloc)]
public void OptimizeLoadLocalInstructions(int index, CilCode expected)
{
var instructions = CreateDummyMethod(false, 0, index + 1);
instructions.Add(CilOpCodes.Ldloc, instructions.Owner.LocalVariables[index]);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(expected, instructions[0].OpCode.Code);
}
[Theory]
[InlineData(0, CilCode.Ldloca_S)]
[InlineData(1, CilCode.Ldloca_S)]
[InlineData(255, CilCode.Ldloca_S)]
[InlineData(256, CilCode.Ldloca)]
public void OptimizeLoadLocalAddressInstructions(int index, CilCode expected)
{
var instructions = CreateDummyMethod(false, 0, index + 1);
instructions.Add(CilOpCodes.Ldloca, instructions.Owner.LocalVariables[index]);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(expected, instructions[0].OpCode.Code);
}
[Theory]
[InlineData(0, CilCode.Stloc_0)]
[InlineData(1, CilCode.Stloc_1)]
[InlineData(2, CilCode.Stloc_2)]
[InlineData(3, CilCode.Stloc_3)]
[InlineData(4, CilCode.Stloc_S)]
[InlineData(255, CilCode.Stloc_S)]
[InlineData(256, CilCode.Stloc)]
public void OptimizeStoreLocalInstructions(int index, CilCode expected)
{
var instructions = CreateDummyMethod(false, 0, index + 1);
instructions.Add(CilOpCodes.Ldnull);
instructions.Add(CilOpCodes.Stloc, instructions.Owner.LocalVariables[index]);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(expected, instructions[1].OpCode.Code);
}
[Theory]
[InlineData(0, CilCode.Ldarg_0)]
[InlineData(1, CilCode.Ldarg_1)]
[InlineData(2, CilCode.Ldarg_2)]
[InlineData(3, CilCode.Ldarg_3)]
[InlineData(4, CilCode.Ldarg_S)]
[InlineData(255, CilCode.Ldarg_S)]
[InlineData(256, CilCode.Ldarg)]
public void OptimizeLoadArgInstructions(int index, CilCode expected)
{
var instructions = CreateDummyMethod(false, index + 1, 0);
var method = instructions.Owner.Owner;
instructions.Add(CilOpCodes.Ldarg, method.Parameters[index]);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(expected, instructions[0].OpCode.Code);
}
[Theory]
[InlineData(0, CilCode.Ldarga_S)]
[InlineData(1, CilCode.Ldarga_S)]
[InlineData(255, CilCode.Ldarga_S)]
[InlineData(256, CilCode.Ldarga)]
public void OptimizeLoadArgAddressInstructions(int index, CilCode expected)
{
var instructions = CreateDummyMethod(false, index + 1, 0);
var method = instructions.Owner.Owner;
instructions.Add(CilOpCodes.Ldarga, method.Parameters[index]);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(expected, instructions[0].OpCode.Code);
}
[Theory]
[InlineData(0, CilCode.Starg_S)]
[InlineData(255, CilCode.Starg_S)]
[InlineData(256, CilCode.Starg)]
public void OptimizeStoreArgInstructions(int index, CilCode expected)
{
var instructions = CreateDummyMethod(false, index + 1, 0);
var method = instructions.Owner.Owner;
instructions.Add(CilOpCodes.Ldnull);
instructions.Add(CilOpCodes.Starg, method.Parameters[index]);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(expected, instructions[1].OpCode.Code);
}
[Theory]
[InlineData(0, CilCode.Ldc_I4_0)]
[InlineData(1, CilCode.Ldc_I4_1)]
[InlineData(2, CilCode.Ldc_I4_2)]
[InlineData(3, CilCode.Ldc_I4_3)]
[InlineData(4, CilCode.Ldc_I4_4)]
[InlineData(5, CilCode.Ldc_I4_5)]
[InlineData(6, CilCode.Ldc_I4_6)]
[InlineData(7, CilCode.Ldc_I4_7)]
[InlineData(8, CilCode.Ldc_I4_8)]
[InlineData(-1, CilCode.Ldc_I4_M1)]
[InlineData(sbyte.MaxValue, CilCode.Ldc_I4_S)]
[InlineData(sbyte.MinValue, CilCode.Ldc_I4_S)]
[InlineData(sbyte.MaxValue + 1, CilCode.Ldc_I4)]
[InlineData(sbyte.MinValue - 1, CilCode.Ldc_I4)]
public void OptimizeLdcI4(int operand, CilCode expected)
{
var instructions = CreateDummyMethod(false, 0, 0);
instructions.Add(CilOpCodes.Ldc_I4, operand);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(expected, instructions[0].OpCode.Code);
}
[Fact]
public void UnalignedShouldNotOptimize()
{
var instructions = CreateDummyMethod(false, 0, 0);
instructions.Add(CilOpCodes.Ldnull);
instructions.Add(CilOpCodes.Unaligned, 4);
instructions.Add(CilOpCodes.Ldind_I);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
Assert.Equal(CilCode.Unaligned, instructions[1].OpCode.Code);
Assert.Equal((sbyte) 4, instructions[1].Operand);
}
[Fact]
public void RemoveIndices()
{
var instructions = CreateDummyMethod(false, 0, 0);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Ret);
var expected = new[]
{
instructions[0],
instructions[2],
instructions[4],
instructions[5],
instructions[6],
};
instructions.RemoveAt(2, -1, 1);
Assert.Equal(expected, instructions);
}
[Fact]
public void RemoveIndicesWithInvalidRelativeIndicesShouldThrowAndNotChangeAnything()
{
var instructions = CreateDummyMethod(false, 0, 0);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Ret);
var expected = instructions.ToArray();
Assert.Throws<ArgumentOutOfRangeException>(() =>
instructions.RemoveAt(2, -1, 100));
Assert.Equal(expected, instructions);
}
[Fact]
public void RemoveRangeOnSetOfInstructions()
{
var instructions = CreateDummyMethod(false, 0, 0);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Ret);
var expected = new[]
{
instructions[0],
instructions[2],
instructions[4],
instructions[6],
};
instructions.RemoveRange(new []
{
instructions[1],
instructions[3],
instructions[5],
});
Assert.Equal(expected, instructions);
}
[Fact]
public void OptimizeShouldUpdateOffsets()
{
var instructions = CreateDummyMethod(false, 0, 0);
instructions.Add(CilOpCodes.Ldc_I4, 0);
instructions.Add(CilOpCodes.Ldc_I4, 1);
instructions.Add(CilOpCodes.Ldc_I4, 2);
instructions.Add(CilOpCodes.Add);
instructions.Add(CilOpCodes.Add);
instructions.Add(CilOpCodes.Ret);
instructions.OptimizeMacros();
int[] offsets = instructions.Select(i => i.Offset).ToArray();
Assert.All(offsets.Skip(1), offset => Assert.NotEqual(0, offset));
instructions.CalculateOffsets();
Assert.Equal(offsets, instructions.Select(i => i.Offset));
}
[Fact]
public void ExpandShouldUpdateOffsets()
{
var instructions = CreateDummyMethod(false, 0, 0);
instructions.Add(CilOpCodes.Ldc_I4_0);
instructions.Add(CilOpCodes.Ldc_I4_1);
instructions.Add(CilOpCodes.Ldc_I4_2);
instructions.Add(CilOpCodes.Add);
instructions.Add(CilOpCodes.Add);
instructions.Add(CilOpCodes.Ret);
instructions.ExpandMacros();
int[] offsets = instructions.Select(i => i.Offset).ToArray();
Assert.All(offsets.Skip(1), offset => Assert.NotEqual(0, offset));
instructions.CalculateOffsets();
Assert.Equal(offsets, instructions.Select(i => i.Offset));
}
} | 257 | 15,604 | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using AsmResolver.PE.DotNet.Cil;
namespace AsmResolver.DotNet.Code.Cil
{
/// <summary>
/// Represents a collection of CIL instructions found in a method body.
/// </summary>
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
public partial class CilInstructionCollection : IList<CilInstruction>
{
private readonly List<CilInstruction> _items = new();
private ICilLabel? _endLabel;
/// <summary>
/// Creates a new collection of CIL instructions stored in a method body.
/// </summary>
/// <param name="body">The method body that owns the collection.</param>
public CilInstructionCollection(CilMethodBody body)
{
Owner = body ?? throw new ArgumentNullException(nameof(body));
}
/// <summary>
/// Gets the method body that owns the collection of CIL instructions.
/// </summary>
public CilMethodBody Owner
{
get;
}
/// <inheritdoc />
public int Count => _items.Count;
/// <inheritdoc />
public bool IsReadOnly => false;
/// <summary>
/// Gets the size in bytes of the collection.
/// </summary>
public int Size => _items.Sum(x => x.Size);
/// <inheritdoc />
public CilInstruction this[int index]
{
get => _items[index];
set => _items[index] = value;
}
/// <summary>
/// Gets the label indicating the end of the CIL code stream.
/// </summary>
/// <remarks>
/// This label does not point to the beginning of an instruction. The offset of this label is equal
/// to the last instruction's offset + its size.
/// </remarks>
public ICilLabel EndLabel
{
get
{
// Most method bodies won't be using the end label. Delay allocation if it can be avoided.
if (_endLabel is null)
Interlocked.CompareExchange(ref _endLabel, new CilEndLabel(this), null);
return _endLabel;
}
}
/// <inheritdoc />
public void Add(CilInstruction item) => _items.Add(item);
/// <summary>
/// Adds a collection of CIL instructions to the end of the list.
/// </summary>
/// <param name="items">The instructions to add.</param>
public void AddRange(IEnumerable<CilInstruction> items) => _items.AddRange(items);
/// <summary>
/// Inserts a collection of CIL instructions at the provided index.
/// </summary>
/// <param name="index">The index to insert the instructions into.</param>
/// <param name="items">The instructions to insert.</param>
public void InsertRange(int index, IEnumerable<CilInstruction> items) => _items.InsertRange(index, items);
/// <inheritdoc />
public void Clear() => _items.Clear();
/// <inheritdoc />
public bool Contains(CilInstruction item) => _items.Contains(item);
/// <inheritdoc />
public void CopyTo(CilInstruction[] array, int arrayIndex) => _items.CopyTo(array, arrayIndex);
/// <inheritdoc />
public bool Remove(CilInstruction item) => _items.Remove(item);
/// <summary>
/// Removes a range of CIL instructions from the collection.
/// </summary>
/// <param name="index">The starting index.</param>
/// <param name="count">The number of instructions to remove.</param>
public void RemoveRange(int index, int count) => _items.RemoveRange(index, count);
/// <summary>
/// Removes a set of CIL instructions from the collection.
/// </summary>
/// <param name="items">The instructions to remove.</param>
public void RemoveRange(IEnumerable<CilInstruction> items)
{
foreach (var item in items)
_items.Remove(item);
}
/// <inheritdoc />
public int IndexOf(CilInstruction item) => _items.IndexOf(item);
/// <inheritdoc />
public void Insert(int index, CilInstruction item) => _items.Insert(index, item);
/// <inheritdoc />
public void RemoveAt(int index) => _items.RemoveAt(index);
/// <summary>
/// Removes a set of CIL instructions based on a list of indices that are relative to a starting index.
/// </summary>
/// <param name="baseIndex">The base index.</param>
/// <param name="relativeIndices">The indices relative to <paramref name="baseIndex"/> to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Occurs when any relative index in <paramref name="relativeIndices"/> results in an index that is
/// out of bounds of the instruction collection.
/// </exception>
public void RemoveAt(int baseIndex, params int[] relativeIndices) =>
RemoveAt(baseIndex, relativeIndices.AsEnumerable());
/// <summary>
/// Removes a set of CIL instructions based on a list of indices that are relative to a starting index.
/// </summary>
/// <param name="baseIndex">The base index.</param>
/// <param name="relativeIndices">The indices relative to <paramref name="baseIndex"/> to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Occurs when any relative index in <paramref name="relativeIndices"/> results in an index that is
/// out of bounds of the instruction collection.
/// </exception>
public void RemoveAt(int baseIndex, IEnumerable<int> relativeIndices)
{
// Verify and translate relative indices into absolute indices.
var absoluteIndices = new List<int>();
foreach (int relativeIndex in relativeIndices.Distinct())
{
int absoluteIndex = baseIndex + relativeIndex;
if (absoluteIndex < 0 || absoluteIndex >= _items.Count)
throw new ArgumentOutOfRangeException(nameof(relativeIndices));
absoluteIndices.Add(absoluteIndex);
}
absoluteIndices.Sort();
// Remove indices.
for (int i = 0; i < absoluteIndices.Count; i++)
{
int index = absoluteIndices[i];
_items.RemoveAt(index);
// Removal of instruction offsets all remaining indices by one. Update remaining indices.
for (int j = i+1; j < absoluteIndices.Count; j++)
absoluteIndices[j]--;
}
}
/// <summary>
/// Returns an enumerator that enumerates through the instructions sequentially.
/// </summary>
/// <returns>The enumerator.</returns>
public Enumerator GetEnumerator() => new Enumerator(this);
/// <inheritdoc />
IEnumerator<CilInstruction> IEnumerable<CilInstruction>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Gets a label at the provided offset.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns>The label.</returns>
/// <remarks>
/// If the provided offset falls outside of the CIL code stream, <see cref="EndLabel"/> is returned instead.
/// </remarks>
public ICilLabel GetLabel(int offset)
{
if (offset >= EndLabel.Offset)
return EndLabel;
var instruction = this.GetByOffset(offset);
return instruction is null
? new CilOffsetLabel(offset)
: instruction.CreateLabel();
}
/// <summary>
/// Calculates the offsets of each instruction in the list.
/// </summary>
public void CalculateOffsets()
{
int currentOffset = 0;
foreach (var instruction in _items)
{
instruction.Offset = currentOffset;
currentOffset += instruction.Size;
}
}
/// <summary>
/// Simplifies the CIL instructions by transforming macro instructions to their expanded form.
/// </summary>
/// <remarks>
/// This method reverses any optimizations done by <see cref="OptimizeMacros"/>.
/// </remarks>
public void ExpandMacros()
{
int currentOffset = 0;
foreach (var instruction in _items)
{
instruction.Offset = currentOffset;
ExpandMacro(instruction);
currentOffset += instruction.Size;
}
}
private void ExpandMacro(CilInstruction instruction)
{
switch (instruction.OpCode.Code)
{
case CilCode.Ldc_I4_0:
case CilCode.Ldc_I4_1:
case CilCode.Ldc_I4_2:
case CilCode.Ldc_I4_3:
case CilCode.Ldc_I4_4:
case CilCode.Ldc_I4_5:
case CilCode.Ldc_I4_6:
case CilCode.Ldc_I4_7:
case CilCode.Ldc_I4_8:
case CilCode.Ldc_I4_M1:
case CilCode.Ldc_I4_S:
instruction.Operand = instruction.GetLdcI4Constant();
instruction.OpCode = CilOpCodes.Ldc_I4;
break;
case CilCode.Ldarg_0:
case CilCode.Ldarg_1:
case CilCode.Ldarg_2:
case CilCode.Ldarg_3:
case CilCode.Ldarg_S:
instruction.Operand = instruction.GetParameter(Owner.Owner.Parameters);
instruction.OpCode = CilOpCodes.Ldarg;
break;
case CilCode.Ldarga_S:
instruction.OpCode = CilOpCodes.Ldarga;
break;
case CilCode.Starg_S:
instruction.OpCode = CilOpCodes.Starg;
break;
case CilCode.Ldloc_0:
case CilCode.Ldloc_1:
case CilCode.Ldloc_2:
case CilCode.Ldloc_3:
case CilCode.Ldloc_S:
instruction.Operand = instruction.GetLocalVariable(Owner.LocalVariables);
instruction.OpCode = CilOpCodes.Ldloc;
break;
case CilCode.Ldloca_S:
instruction.OpCode = CilOpCodes.Ldloca;
break;
case CilCode.Stloc_0:
case CilCode.Stloc_1:
case CilCode.Stloc_2:
case CilCode.Stloc_3:
case CilCode.Stloc_S:
instruction.Operand = instruction.GetLocalVariable(Owner.LocalVariables);
instruction.OpCode = CilOpCodes.Stloc;
break;
case CilCode.Beq_S:
instruction.OpCode = CilOpCodes.Beq;
break;
case CilCode.Bge_S:
instruction.OpCode = CilOpCodes.Bge;
break;
case CilCode.Bgt_S:
instruction.OpCode = CilOpCodes.Bgt;
break;
case CilCode.Ble_S:
instruction.OpCode = CilOpCodes.Ble;
break;
case CilCode.Blt_S:
instruction.OpCode = CilOpCodes.Blt;
break;
case CilCode.Br_S:
instruction.OpCode = CilOpCodes.Br;
break;
case CilCode.Brfalse_S:
instruction.OpCode = CilOpCodes.Brfalse;
break;
case CilCode.Brtrue_S:
instruction.OpCode = CilOpCodes.Brtrue;
break;
case CilCode.Bge_Un_S:
instruction.OpCode = CilOpCodes.Bge_Un;
break;
case CilCode.Bgt_Un_S:
instruction.OpCode = CilOpCodes.Bgt_Un;
break;
case CilCode.Ble_Un_S:
instruction.OpCode = CilOpCodes.Ble_Un;
break;
case CilCode.Blt_Un_S:
instruction.OpCode = CilOpCodes.Blt_Un;
break;
case CilCode.Bne_Un_S:
instruction.OpCode = CilOpCodes.Bne_Un;
break;
case CilCode.Leave_S:
instruction.OpCode = CilOpCodes.Leave;
break;
}
}
/// <summary>
/// Optimizes all instructions to use the least amount of bytes required to encode all operations.
/// </summary>
/// <remarks>
/// This method reverses any effects introduced by <see cref="ExpandMacros"/>.
/// </remarks>
public void OptimizeMacros()
{
while (OptimizeMacrosPass())
{
// Repeat until no more optimizations can be done.
}
CalculateOffsets();
}
private bool OptimizeMacrosPass()
{
CalculateOffsets();
bool changed = false;
foreach (var instruction in _items)
changed |= TryOptimizeMacro(instruction);
return changed;
}
private bool TryOptimizeMacro(CilInstruction instruction)
{
return instruction.OpCode.OperandType switch
{
CilOperandType.InlineBrTarget => TryOptimizeBranch(instruction),
CilOperandType.ShortInlineBrTarget => TryOptimizeBranch(instruction),
CilOperandType.InlineI => TryOptimizeLdc(instruction),
CilOperandType.ShortInlineI when instruction.IsLdcI4() => TryOptimizeLdc(instruction),
CilOperandType.InlineVar => TryOptimizeVariable(instruction),
CilOperandType.ShortInlineVar => TryOptimizeVariable(instruction),
CilOperandType.InlineArgument => TryOptimizeArgument(instruction),
CilOperandType.ShortInlineArgument => TryOptimizeArgument(instruction),
_ => false
};
}
private bool TryOptimizeBranch(CilInstruction instruction)
{
if (instruction.Operand is not ICilLabel targetLabel)
throw new ArgumentException("Branch target is null.");
int nextOffset = instruction.Offset + instruction.Size;
int targetOffset = targetLabel.Offset;
int delta = targetOffset - nextOffset;
bool isShortJump = delta >= sbyte.MinValue && delta <= sbyte.MaxValue;
CilOpCode code;
if (isShortJump)
{
code = instruction.OpCode.Code switch
{
CilCode.Beq => CilOpCodes.Beq_S,
CilCode.Bge => CilOpCodes.Bge_S,
CilCode.Bgt => CilOpCodes.Bgt_S,
CilCode.Ble => CilOpCodes.Ble_S,
CilCode.Blt => CilOpCodes.Blt_S,
CilCode.Br => CilOpCodes.Br_S,
CilCode.Brfalse => CilOpCodes.Brfalse_S,
CilCode.Brtrue => CilOpCodes.Brtrue_S,
CilCode.Bge_Un => CilOpCodes.Bge_Un_S,
CilCode.Bgt_Un => CilOpCodes.Bgt_Un_S,
CilCode.Ble_Un => CilOpCodes.Ble_Un_S,
CilCode.Blt_Un => CilOpCodes.Blt_Un_S,
CilCode.Bne_Un => CilOpCodes.Bne_Un_S,
CilCode.Leave => CilOpCodes.Leave_S,
_ => instruction.OpCode
};
}
else
{
code = instruction.OpCode.Code switch
{
CilCode.Beq_S => CilOpCodes.Beq,
CilCode.Bge_S => CilOpCodes.Bge,
CilCode.Bgt_S => CilOpCodes.Bgt,
CilCode.Ble_S => CilOpCodes.Ble,
CilCode.Blt_S => CilOpCodes.Blt,
CilCode.Br_S => CilOpCodes.Br,
CilCode.Brfalse_S => CilOpCodes.Brfalse,
CilCode.Brtrue_S => CilOpCodes.Brtrue,
CilCode.Bge_Un_S => CilOpCodes.Bge_Un,
CilCode.Bgt_Un_S => CilOpCodes.Bgt_Un,
CilCode.Ble_Un_S => CilOpCodes.Ble_Un,
CilCode.Blt_Un_S => CilOpCodes.Blt_Un,
CilCode.Bne_Un_S => CilOpCodes.Bne_Un,
CilCode.Leave_S => CilOpCodes.Leave,
_ => instruction.OpCode
};
}
if (instruction.OpCode != code)
{
instruction.OpCode = code;
return true;
}
return false;
}
private static bool TryOptimizeLdc(CilInstruction instruction)
{
int value = instruction.GetLdcI4Constant();
var (code, operand) = CilInstruction.GetLdcI4OpCodeOperand(value);
if (code != instruction.OpCode)
{
instruction.OpCode = code;
instruction.Operand = operand;
return true;
}
return false;
}
private bool TryOptimizeVariable(CilInstruction instruction)
{
var variable = instruction.GetLocalVariable(Owner.LocalVariables);
var code = instruction.OpCode;
object? operand = instruction.Operand;
if (instruction.IsLdloc())
{
(code, operand) = variable.Index switch
{
0 => (CilOpCodes.Ldloc_0, null),
1 => (CilOpCodes.Ldloc_1, null),
2 => (CilOpCodes.Ldloc_2, null),
3 => (CilOpCodes.Ldloc_3, null),
<= byte.MaxValue and >= byte.MinValue => (CilOpCodes.Ldloc_S, variable),
_ => (CilOpCodes.Ldloc, variable),
};
}
else if (instruction.IsStloc())
{
(code, operand) = variable.Index switch
{
0 => (CilOpCodes.Stloc_0, null),
1 => (CilOpCodes.Stloc_1, null),
2 => (CilOpCodes.Stloc_2, null),
3 => (CilOpCodes.Stloc_3, null),
<= byte.MaxValue and >= byte.MinValue => (CilOpCodes.Stloc_S, variable),
_ => (CilOpCodes.Stloc, variable),
};
}
else if (instruction.OpCode.Code == CilCode.Ldloca)
{
if (variable.Index is >= byte.MinValue and <= byte.MaxValue)
code = CilOpCodes.Ldloca_S;
}
if (code != instruction.OpCode)
{
instruction.OpCode = code;
instruction.Operand = operand;
return true;
}
return false;
}
private bool TryOptimizeArgument(CilInstruction instruction)
{
var parameter = instruction.GetParameter(Owner.Owner.Parameters);
var code = instruction.OpCode;
object? operand = instruction.Operand;
if (instruction.IsLdarg())
{
(code, operand) = parameter.MethodSignatureIndex switch
{
0 => (CilOpCodes.Ldarg_0, null),
1 => (CilOpCodes.Ldarg_1, null),
2 => (CilOpCodes.Ldarg_2, null),
3 => (CilOpCodes.Ldarg_3, null),
>= byte.MinValue and <= byte.MaxValue => (CilOpCodes.Ldarg_S, parameter),
_ => (CilOpCodes.Ldarg, parameter),
};
}
else if (instruction.IsStarg())
{
if (parameter.MethodSignatureIndex <= byte.MaxValue)
code = CilOpCodes.Starg_S;
}
else if (instruction.OpCode.Code == CilCode.Ldarga)
{
if (parameter.Index is >= byte.MinValue and <= byte.MaxValue)
code = CilOpCodes.Ldarga_S;
}
if (code != instruction.OpCode)
{
instruction.OpCode = code;
instruction.Operand = operand;
return true;
}
return false;
}
/// <summary>
/// Represents an enumerator that enumerates through a collection of CIL instructions.
/// </summary>
public struct Enumerator : IEnumerator<CilInstruction>
{
private List<CilInstruction>.Enumerator _enumerator;
/// <summary>
/// Creates a new instance of the <see cref="Enumerator"/> structure.
/// </summary>
/// <param name="collection">The collection to enumerate.</param>
public Enumerator(CilInstructionCollection collection)
{
_enumerator = collection._items.GetEnumerator();
}
/// <inheritdoc />
public bool MoveNext() => _enumerator.MoveNext();
/// <inheritdoc />
public void Reset() => ((IEnumerator) _enumerator).Reset();
/// <inheritdoc />
public CilInstruction Current => _enumerator.Current!;
/// <inheritdoc />
object IEnumerator.Current => Current;
/// <inheritdoc />
public void Dispose() => _enumerator.Dispose();
}
private sealed class CilEndLabel : ICilLabel
{
private readonly CilInstructionCollection _collection;
public CilEndLabel(CilInstructionCollection collection)
{
_collection = collection ?? throw new ArgumentNullException(nameof(collection));
}
/// <inheritdoc />
public int Offset
{
get
{
if (_collection.Count == 0)
return 0;
var last = _collection[_collection.Count - 1];
return last.Offset + last.Size;
}
}
/// <inheritdoc />
public bool Equals(ICilLabel? other) => other != null && Offset == other.Offset;
public override string ToString() => $"IL_{Offset:X4}";
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Code\Cil\CilInstructionExtensionsTest.cs | AsmResolver.DotNet.Tests.Code.Cil
| CilInstructionExtensionsTest | ['private readonly ModuleDefinition _module = new ModuleDefinition("SomeModule");'] | ['System.Linq', 'AsmResolver.DotNet.Code.Cil', 'AsmResolver.DotNet.Signatures', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class CilInstructionExtensionsTest
{
private readonly ModuleDefinition _module = new ModuleDefinition("SomeModule");
[Fact]
public void NopShouldPopZeroElements()
{
var method = new MethodDefinition("Method", MethodAttributes.Static,
MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void));
method.CilMethodBody = new CilMethodBody(method);
var instruction = new CilInstruction(CilOpCodes.Nop);
Assert.Equal(0, instruction.GetStackPopCount(method.CilMethodBody));
}
[Fact]
public void RetInVoidMethodShouldPopZeroElements()
{
var method = new MethodDefinition("Method", MethodAttributes.Static,
MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void));
method.CilMethodBody = new CilMethodBody(method);
var instruction = new CilInstruction(CilOpCodes.Ret);
Assert.Equal(0, instruction.GetStackPopCount(method.CilMethodBody));
}
[Fact]
public void RetInNonVoidMethodShouldPopOneElement()
{
var method = new MethodDefinition("Method", MethodAttributes.Static,
MethodSignature.CreateStatic(_module.CorLibTypeFactory.Int32));
method.CilMethodBody = new CilMethodBody(method);
var instruction = new CilInstruction(CilOpCodes.Ret);
Assert.Equal(1, instruction.GetStackPopCount(method.CilMethodBody));
}
[Fact]
public void CallStaticWithZeroParametersShouldPopZeroElements()
{
var method = new MethodDefinition("Method", MethodAttributes.Static,
MethodSignature.CreateStatic(_module.CorLibTypeFactory.Int32));
method.CilMethodBody = new CilMethodBody(method);
var type = new TypeReference(_module, null, "SomeType");
var member = new MemberReference(type, "SomeMethod",
MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void));
var instruction = new CilInstruction(CilOpCodes.Call, member);
Assert.Equal(0, instruction.GetStackPopCount(method.CilMethodBody));
}
[Fact]
public void CallStaticWithTwoParametersShouldPopTwoElements()
{
var method = new MethodDefinition("Method", MethodAttributes.Static,
MethodSignature.CreateStatic(_module.CorLibTypeFactory.Int32));
method.CilMethodBody = new CilMethodBody(method);
var type = new TypeReference(_module, null, "SomeType");
var member = new MemberReference(type, "SomeMethod",
MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void,
_module.CorLibTypeFactory.Int32, _module.CorLibTypeFactory.Int32));
var instruction = new CilInstruction(CilOpCodes.Call, member);
Assert.Equal(2, instruction.GetStackPopCount(method.CilMethodBody));
}
[Fact]
public void CallInstanceWithZeroParametersShouldPopOneElement()
{
var method = new MethodDefinition("Method", MethodAttributes.Static,
MethodSignature.CreateStatic(_module.CorLibTypeFactory.Int32));
method.CilMethodBody = new CilMethodBody(method);
var type = new TypeReference(_module, null, "SomeType");
var member = new MemberReference(type, "SomeMethod",
MethodSignature.CreateInstance(_module.CorLibTypeFactory.Void));
var instruction = new CilInstruction(CilOpCodes.Call, member);
Assert.Equal(1, instruction.GetStackPopCount(method.CilMethodBody));
}
[Fact]
public void CallInstanceWithTwoParametersShouldPopThreeElements()
{
var method = new MethodDefinition("Method", MethodAttributes.Static,
MethodSignature.CreateStatic(_module.CorLibTypeFactory.Int32));
method.CilMethodBody = new CilMethodBody(method);
var type = new TypeReference(_module, null, "SomeType");
var member = new MemberReference(type, "SomeMethod",
MethodSignature.CreateInstance(_module.CorLibTypeFactory.Void,
_module.CorLibTypeFactory.Int32, _module.CorLibTypeFactory.Int32));
var instruction = new CilInstruction(CilOpCodes.Call, member);
Assert.Equal(3, instruction.GetStackPopCount(method.CilMethodBody));
}
[Fact]
public void CallVoidMethodShouldPushZeroElements()
{
var type = new TypeReference(_module, null, "SomeType");
var member = new MemberReference(type, "SomeMethod",
MethodSignature.CreateInstance(_module.CorLibTypeFactory.Void));
var instruction = new CilInstruction(CilOpCodes.Call, member);
Assert.Equal(0, instruction.GetStackPushCount());
}
[Fact]
public void CallNonVoidMethodShouldPushSingleElement()
{
var type = new TypeReference(_module, null, "SomeType");
var member = new MemberReference(type, "SomeMethod",
MethodSignature.CreateInstance(_module.CorLibTypeFactory.Int32));
var instruction = new CilInstruction(CilOpCodes.Call, member);
Assert.Equal(1, instruction.GetStackPushCount());
}
[Fact]
public void NewObjVoidMethodShouldPushSingleElement()
{
var type = new TypeReference(_module, null, "SomeType");
var member = new MemberReference(type, "SomeMethod",
MethodSignature.CreateInstance(_module.CorLibTypeFactory.Int32));
var instruction = new CilInstruction(CilOpCodes.Newobj, member);
Assert.Equal(1, instruction.GetStackPushCount());
}
[Fact]
public void ModreqReturnTypeShouldNotAffectPopCount()
{
var module = ModuleDefinition.FromFile(typeof(TestClass).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.Single(t => t.MetadataToken == typeof(TestClass).MetadataToken);
var property = type.Properties[0];
var setter = property.SetMethod;
var body = setter.CilMethodBody;
var ret = body.Instructions[^1];
Assert.Equal(0, ret.GetStackPopCount(body));
property = type.Properties[1];
setter = property.SetMethod;
body = setter.CilMethodBody;
ret = body.Instructions[^1];
Assert.Equal(0, ret.GetStackPopCount(body));
}
} | 242 | 7,041 | using System;
using System.Collections.Generic;
using AsmResolver.DotNet.Collections;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Cil;
namespace AsmResolver.DotNet.Code.Cil
{
/// <summary>
/// Provides extensions to the <see cref="CilInstruction"/> class.
/// </summary>
public static class CilInstructionExtensions
{
/// <summary>
/// Determines the number of values that are popped from the stack by this instruction.
/// </summary>
/// <param name="instruction">The instruction.</param>
/// <param name="parent">The method body that this instruction resides in. When passed on <c>null</c>,
/// a method body of a System.Void method is assumed.</param>
/// <returns>The number of values popped from the stack.</returns>
/// <exception cref="ArgumentOutOfRangeException">Occurs when the instruction's operation code provides an
/// invalid stack behaviour.</exception>
public static int GetStackPopCount(this CilInstruction instruction, CilMethodBody? parent)
{
return GetStackPopCount(instruction,
parent == null
|| !(parent.Owner.Signature?.ReturnsValue ?? true));
}
/// <summary>
/// Determines the number of values that are popped from the stack by this instruction.
/// </summary>
/// <param name="instruction">The instruction.</param>
/// <param name="isVoid">A value indicating whether the enclosing method is returning System.Void or not.</param>
/// <returns>The number of values popped from the stack.</returns>
/// <exception cref="ArgumentOutOfRangeException">Occurs when the instruction's operation code provides an
/// invalid stack behaviour.</exception>
public static int GetStackPopCount(this CilInstruction instruction, bool isVoid)
{
switch (instruction.OpCode.StackBehaviourPop)
{
case CilStackBehaviour.Pop0:
return 0;
case CilStackBehaviour.Pop1:
case CilStackBehaviour.PopI:
case CilStackBehaviour.PopRef:
return 1;
case CilStackBehaviour.Pop1_Pop1:
case CilStackBehaviour.PopI_Pop1:
case CilStackBehaviour.PopI_PopI:
case CilStackBehaviour.PopI_PopI8:
case CilStackBehaviour.PopI_PopR4:
case CilStackBehaviour.PopI_PopR8:
case CilStackBehaviour.PopRef_Pop1:
case CilStackBehaviour.PopRef_PopI:
return 2;
case CilStackBehaviour.PopI_PopI_PopI:
case CilStackBehaviour.PopRef_PopI_PopI:
case CilStackBehaviour.PopRef_PopI_PopI8:
case CilStackBehaviour.PopRef_PopI_PopR4:
case CilStackBehaviour.PopRef_PopI_PopR8:
case CilStackBehaviour.PopRef_PopI_PopRef:
case CilStackBehaviour.PopRef_PopI_Pop1:
return 3;
case CilStackBehaviour.VarPop:
return DetermineVarPopCount(instruction, isVoid);
case CilStackBehaviour.PopAll:
return -1;
default:
throw new ArgumentOutOfRangeException();
}
}
private static int DetermineVarPopCount(CilInstruction instruction, bool isVoid)
{
var opCode = instruction.OpCode;
var signature = instruction.Operand switch
{
IMethodDescriptor method => method.Signature,
StandAloneSignature standAloneSig => standAloneSig.Signature as MethodSignature,
_ => null
};
if (signature == null)
{
if (opCode.Code == CilCode.Ret)
return isVoid ? 0 : 1;
}
else
{
int count = signature.GetTotalParameterCount();
switch (opCode.Code)
{
case CilCode.Newobj:
// NewObj produces instead of consumes the this parameter.
count--;
break;
case CilCode.Calli:
// Calli consumes an extra parameter (the address to call).
count++;
break;
}
return count;
}
return 0;
}
/// <summary>
/// Determines the number of values that are pushed onto the stack by this instruction.
/// </summary>
/// <param name="instruction">The instruction.</param>
/// <returns>The number of values pushed onto the stack.</returns>
/// <exception cref="ArgumentOutOfRangeException">Occurs when the instruction's operation code provides an
/// invalid stack behaviour.</exception>
public static int GetStackPushCount(this CilInstruction instruction)
{
switch (instruction.OpCode.StackBehaviourPush)
{
case CilStackBehaviour.Push0:
return 0;
case CilStackBehaviour.Push1:
case CilStackBehaviour.PushI:
case CilStackBehaviour.PushI8:
case CilStackBehaviour.PushR4:
case CilStackBehaviour.PushR8:
case CilStackBehaviour.PushRef:
return 1;
case CilStackBehaviour.Push1_Push1:
return 2;
case CilStackBehaviour.VarPush:
return DetermineVarPushCount(instruction);
default:
throw new ArgumentOutOfRangeException();
}
}
private static int DetermineVarPushCount(CilInstruction instruction)
{
var signature = instruction.Operand switch
{
IMethodDescriptor method => method.Signature,
StandAloneSignature standAloneSig => standAloneSig.Signature as MethodSignature,
_ => null
};
if (signature == null)
return 0;
if (signature.ReturnsValue || instruction.OpCode.Code == CilCode.Newobj)
return 1;
return 0;
}
/// <summary>
/// When this instruction is using a variant of the ldloc or stloc opcodes, gets the local variable that is
/// referenced by the instruction.
/// </summary>
/// <param name="instruction">The instruction.</param>
/// <param name="variables">The local variables defined in the enclosing method body.</param>
/// <returns>The variable.</returns>
/// <exception cref="ArgumentException">Occurs when the instruction is not using a variant of the ldloc or stloc opcodes.</exception>
public static CilLocalVariable GetLocalVariable(this CilInstruction instruction, IList<CilLocalVariable> variables)
{
switch (instruction.OpCode.Code)
{
case CilCode.Ldloc:
case CilCode.Ldloc_S:
case CilCode.Stloc:
case CilCode.Stloc_S:
case CilCode.Ldloca:
case CilCode.Ldloca_S:
return (CilLocalVariable) instruction.Operand!;
case CilCode.Ldloc_0:
case CilCode.Stloc_0:
return variables[0];
case CilCode.Ldloc_1:
case CilCode.Stloc_1:
return variables[1];
case CilCode.Ldloc_2:
case CilCode.Stloc_2:
return variables[2];
case CilCode.Ldloc_3:
case CilCode.Stloc_3:
return variables[3];
default:
throw new ArgumentException("Instruction is not a ldloc or stloc instruction.");
}
}
/// <summary>
/// When this instruction is using a variant of the ldarg or starg opcodes, gets the parameter that is
/// referenced by the instruction.
/// </summary>
/// <param name="instruction">The instruction.</param>
/// <param name="parameters">The parameters defined in the enclosing method body.</param>
/// <returns>The parameter.</returns>
/// <exception cref="ArgumentException">Occurs when the instruction is not using a variant of the ldarg or starg opcodes.</exception>
public static Parameter GetParameter(this CilInstruction instruction, ParameterCollection parameters)
{
switch (instruction.OpCode.Code)
{
case CilCode.Ldarg:
case CilCode.Ldarg_S:
case CilCode.Ldarga:
case CilCode.Ldarga_S:
case CilCode.Starg:
case CilCode.Starg_S:
return (Parameter) instruction.Operand!;
case CilCode.Ldarg_0:
return parameters.GetBySignatureIndex(0);
case CilCode.Ldarg_1:
return parameters.GetBySignatureIndex(1);
case CilCode.Ldarg_2:
return parameters.GetBySignatureIndex(2);
case CilCode.Ldarg_3:
return parameters.GetBySignatureIndex(3);
default:
throw new ArgumentException("Instruction is not a ldarg or starg instruction.");
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Code\Cil\CilLocalVariableCollectionTest.cs | AsmResolver.DotNet.Tests.Code.Cil
| CilLocalVariableCollectionTest | ['private readonly CilLocalVariableCollection _collection = new CilLocalVariableCollection();', 'private readonly ModuleDefinition _module = new ModuleDefinition("Test.dll");'] | ['AsmResolver.DotNet.Code.Cil', 'Xunit'] | xUnit | net8.0 | public class CilLocalVariableCollectionTest
{
private readonly CilLocalVariableCollection _collection = new CilLocalVariableCollection();
private readonly ModuleDefinition _module = new ModuleDefinition("Test.dll");
private void AssertCollectionIndicesAreConsistent(CilLocalVariableCollection collection)
{
for (int i = 0; i < collection.Count; i++)
Assert.Equal(i, collection[i].Index);
}
[Fact]
public void NoIndex()
{
var variable = new CilLocalVariable(_module.CorLibTypeFactory.Object);
Assert.Equal(-1, variable.Index);
}
[Fact]
public void AddToEmptyListShouldSetIndexToZero()
{
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
AssertCollectionIndicesAreConsistent(_collection);
}
[Fact]
public void AddToEndOfListShouldSetIndexToCount()
{
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
AssertCollectionIndicesAreConsistent(_collection);
}
[Fact]
public void InsertShouldUpdateIndices()
{
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
_collection.Insert(1, new CilLocalVariable(_module.CorLibTypeFactory.String));
AssertCollectionIndicesAreConsistent(_collection);
}
[Fact]
public void RemoveShouldUpdateIndices()
{
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
_collection.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
var variable = _collection[1];
_collection.RemoveAt(1);
AssertCollectionIndicesAreConsistent(_collection);
Assert.Equal(-1, variable.Index);
}
[Fact]
public void ClearingVariablesShouldUpdateAllIndices()
{
var variables = new[]
{
new CilLocalVariable(_module.CorLibTypeFactory.Object),
new CilLocalVariable(_module.CorLibTypeFactory.Object),
new CilLocalVariable(_module.CorLibTypeFactory.Object),
new CilLocalVariable(_module.CorLibTypeFactory.Object)
};
foreach (var variable in variables)
_collection.Add(variable);
_collection.Clear();
foreach (var variable in variables)
Assert.Equal(-1, variable.Index);
}
} | 104 | 3,417 | using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace AsmResolver.DotNet.Code.Cil
{
/// <summary>
/// Represents a collection of local variables stored in a CIL method body.
/// </summary>
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
public class CilLocalVariableCollection : Collection<CilLocalVariable>
{
private static void AssertHasNoOwner(CilLocalVariable item)
{
if (item.Index != -1)
throw new ArgumentException("Variable is already added to another list of variables.");
}
/// <inheritdoc />
protected override void ClearItems()
{
lock (Items)
{
foreach (var item in Items)
item.Index = -1;
base.ClearItems();
}
}
/// <inheritdoc />
protected override void InsertItem(int index, CilLocalVariable item)
{
lock (Items)
{
AssertHasNoOwner(item);
for (int i = index; i < Count; i++)
Items[i].Index++;
item.Index = index;
base.InsertItem(index, item);
}
}
/// <inheritdoc />
protected override void RemoveItem(int index)
{
lock (Items)
{
for (int i = index; i < Count; i++)
Items[i].Index--;
Items[index].Index = -1;
base.RemoveItem(index);
}
}
/// <inheritdoc />
protected override void SetItem(int index, CilLocalVariable item)
{
lock (Items)
{
AssertHasNoOwner(item);
Items[index].Index = -1;
base.SetItem(index, item);
item.Index = index;
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Code\Cil\CilMethodBodyTest.cs | AsmResolver.DotNet.Tests.Code.Cil
| CilMethodBodyTest | [] | ['System', 'System.IO', 'System.Linq', 'System.Reflection.Emit', 'AsmResolver.DotNet.Builder', 'AsmResolver.DotNet.Code.Cil', 'AsmResolver.DotNet.Serialized', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Methods', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class CilMethodBodyTest
{
private CilMethodBody ReadMethodBody(string name)
{
var module = ModuleDefinition.FromFile(typeof(MethodBodyTypes).Assembly.Location, TestReaderParameters);
return GetMethodBodyInModule(module, name);
}
private static CilMethodBody GetMethodBodyInModule(ModuleDefinition module, string name)
{
var type = module.TopLevelTypes.First(t => t.Name == nameof(MethodBodyTypes));
return type.Methods.First(m => m.Name == name).CilMethodBody;
}
private CilMethodBody RebuildAndLookup(CilMethodBody methodBody)
{
var module = methodBody.Owner.Module!;
var stream = new MemoryStream();
module.Write(stream);
var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
return GetMethodBodyInModule(newModule, methodBody.Owner.Name);
}
[Fact]
public void ReadTinyMethod()
{
var body = ReadMethodBody(nameof(MethodBodyTypes.TinyMethod));
Assert.False(body.IsFat);
}
[Fact]
public void PersistentTinyMethod()
{
var body = ReadMethodBody(nameof(MethodBodyTypes.TinyMethod));
var newBody = RebuildAndLookup(body);
Assert.False(newBody.IsFat);
Assert.Equal(body.Instructions.Count, newBody.Instructions.Count);
}
[Fact]
public void ReadFatLongMethod()
{
var body = ReadMethodBody(nameof(MethodBodyTypes.FatLongMethod));
Assert.True(body.IsFat);
}
[Fact]
public void PersistentFatLongMethod()
{
var body = ReadMethodBody(nameof(MethodBodyTypes.FatLongMethod));
var newBody = RebuildAndLookup(body);
Assert.True(newBody.IsFat);
Assert.Equal(body.Instructions.Count, newBody.Instructions.Count);
}
[Fact]
public void ReadFatMethodWithLocals()
{
var body = ReadMethodBody(nameof(MethodBodyTypes.FatMethodWithLocals));
Assert.True(body.IsFat);
Assert.Contains(body.LocalVariables, x => x.VariableType.ElementType == ElementType.I4);
}
[Fact]
public void ReadFatMethodWithManyLocals()
{
// https://github.com/Washi1337/AsmResolver/issues/55
var body = ReadMethodBody(nameof(MethodBodyTypes.FatMethodWithManyLocals));
int expectedIndex = 0;
foreach (var instruction in body.Instructions)
{
if (instruction.IsLdloc())
{
var variable = instruction.GetLocalVariable(body.LocalVariables);
Assert.Equal(expectedIndex, variable.Index);
expectedIndex++;
}
}
}
[Fact]
public void PersistentFatMethodWithLocals()
{
var body = ReadMethodBody(nameof(MethodBodyTypes.FatLongMethod));
var newBody = RebuildAndLookup(body);
Assert.True(newBody.IsFat);
Assert.Equal(
body.LocalVariables.Select(v => v.VariableType.FullName),
newBody.LocalVariables.Select(v => v.VariableType.FullName));
}
[Fact]
public void ReadFatMethodWithExceptionHandler()
{
var body = ReadMethodBody(nameof(MethodBodyTypes.FatMethodWithExceptionHandler));
Assert.True(body.IsFat);
Assert.Single(body.ExceptionHandlers);
}
private static CilMethodBody CreateDummyBody(bool isVoid)
{
var module = new ModuleDefinition("DummyModule");
var method = new MethodDefinition("Main",
MethodAttributes.Static,
MethodSignature.CreateStatic(isVoid ? module.CorLibTypeFactory.Void : module.CorLibTypeFactory.Int32));
module.GetOrCreateModuleType().Methods.Add(method);
return method.CilMethodBody = new CilMethodBody(method);
}
[Fact]
public void MaxStackComputationOnNonVoidShouldFailIfNoValueOnStack()
{
var body = CreateDummyBody(false);
body.Instructions.Add(CilOpCodes.Ret);
Assert.ThrowsAny<StackImbalanceException>(() => body.ComputeMaxStack());
}
[Fact]
public void MaxStackComputationOnNonVoid()
{
var body = CreateDummyBody(false);
body.Instructions.Add(CilOpCodes.Ldnull);
body.Instructions.Add(CilOpCodes.Ret);
Assert.Equal(1, body.ComputeMaxStack());
}
[Fact]
public void MaxStackComputationOnVoidShouldFailIfValueOnStack()
{
var body = CreateDummyBody(true);
body.Instructions.Add(CilOpCodes.Ldnull);
body.Instructions.Add(CilOpCodes.Ret);
Assert.ThrowsAny<StackImbalanceException>(() => body.ComputeMaxStack());
}
[Fact]
public void JoiningPathsWithSameStackSizeShouldSucceed()
{
var body = CreateDummyBody(false);
var instructions = body.Instructions;
var branchTarget1 = new CilInstructionLabel();
var branchTarget2 = new CilInstructionLabel();
instructions.Add(CilOpCodes.Ldarg_0);
instructions.Add(CilOpCodes.Brtrue, branchTarget1);
instructions.Add(CilOpCodes.Ldc_I4_1);
instructions.Add(CilOpCodes.Br, branchTarget2);
branchTarget1.Instruction = instructions.Add(CilOpCodes.Ldc_I4_0);
branchTarget2.Instruction = instructions.Add(CilOpCodes.Nop);
instructions.Add(CilOpCodes.Ret);
Assert.Equal(1, body.ComputeMaxStack());
}
[Fact]
public void JoiningPathsWithDifferentStackSizesShouldFail()
{
var body = CreateDummyBody(false);
var instructions = body.Instructions;
var branchTarget1 = new CilInstructionLabel();
var branchTarget2 = new CilInstructionLabel();
var end = new CilInstructionLabel();
instructions.Add(CilOpCodes.Ldarg_0);
instructions.Add(CilOpCodes.Brtrue, branchTarget1);
instructions.Add(CilOpCodes.Ldc_I4_1);
instructions.Add(CilOpCodes.Ldc_I4_2);
instructions.Add(CilOpCodes.Br, branchTarget2);
branchTarget1.Instruction = instructions.Add(CilOpCodes.Ldc_I4_0);
branchTarget2.Instruction = instructions.Add(CilOpCodes.Nop);
end.Instruction = instructions.Add(CilOpCodes.Ret);
var exception = Assert.ThrowsAny<StackImbalanceException>(() => body.ComputeMaxStack());
Assert.Equal(end.Offset, exception.Offset);
}
[Fact]
public void ThrowsInstructionShouldTerminateTraversal()
{
var body = CreateDummyBody(false);
var instructions = body.Instructions;
instructions.Add(CilOpCodes.Ldnull);
instructions.Add(CilOpCodes.Throw);
// Junk opcodes..
instructions.Add(CilOpCodes.Ldc_I4_0);
Assert.Equal(1, body.ComputeMaxStack());
}
[Fact]
public void ExceptionHandlerExpectsOneValueOnStack()
{
var body = CreateDummyBody(true);
var end = new CilInstructionLabel();
var tryStart = new CilInstructionLabel();
var tryEnd = new CilInstructionLabel();
var handlerStart = new CilInstructionLabel();
var handlerEnd = new CilInstructionLabel();
body.ExceptionHandlers.Add(new CilExceptionHandler
{
HandlerType = CilExceptionHandlerType.Exception,
ExceptionType = body.Owner.Module.CorLibTypeFactory.Object.ToTypeDefOrRef(),
TryStart = tryStart,
TryEnd = tryEnd,
HandlerStart = handlerStart,
HandlerEnd = handlerEnd,
});
tryStart.Instruction = body.Instructions.Add(CilOpCodes.Nop);
tryEnd.Instruction = body.Instructions.Add(CilOpCodes.Leave, end);
handlerStart.Instruction = body.Instructions.Add(CilOpCodes.Pop);
handlerEnd.Instruction = body.Instructions.Add(CilOpCodes.Leave, end);
end.Instruction = body.Instructions.Add(CilOpCodes.Ret);
Assert.Equal(1, body.ComputeMaxStack());
}
[Fact]
public void FinallyHandlerExpectsNoValueOnStack()
{
var body = CreateDummyBody(true);
var end = new CilInstructionLabel();
var tryStart = new CilInstructionLabel();
var tryEnd = new CilInstructionLabel();
var handlerStart = new CilInstructionLabel();
var handlerEnd = new CilInstructionLabel();
body.ExceptionHandlers.Add(new CilExceptionHandler
{
HandlerType = CilExceptionHandlerType.Finally,
ExceptionType = body.Owner.Module.CorLibTypeFactory.Object.ToTypeDefOrRef(),
TryStart = tryStart,
TryEnd = tryEnd,
HandlerStart = handlerStart,
HandlerEnd = handlerEnd,
});
tryStart.Instruction = body.Instructions.Add(CilOpCodes.Nop);
tryEnd.Instruction = body.Instructions.Add(CilOpCodes.Leave, end);
handlerStart.Instruction = body.Instructions.Add(CilOpCodes.Nop);
handlerEnd.Instruction = body.Instructions.Add(CilOpCodes.Leave, end);
end.Instruction = body.Instructions.Add(CilOpCodes.Ret);
Assert.Equal(0, body.ComputeMaxStack());
}
[Fact]
public void LeaveInstructionShouldClearStackAndNotFail()
{
var body = CreateDummyBody(true);
var end = new CilInstructionLabel();
var tryStart = new CilInstructionLabel();
var tryEnd = new CilInstructionLabel();
var handlerStart = new CilInstructionLabel();
var handlerEnd = new CilInstructionLabel();
body.ExceptionHandlers.Add(new CilExceptionHandler
{
HandlerType = CilExceptionHandlerType.Exception,
ExceptionType = body.Owner.Module.CorLibTypeFactory.Object.ToTypeDefOrRef(),
TryStart = tryStart,
TryEnd = tryEnd,
HandlerStart = handlerStart,
HandlerEnd = handlerEnd,
});
tryStart.Instruction = body.Instructions.Add(CilOpCodes.Nop);
tryEnd.Instruction = body.Instructions.Add(CilOpCodes.Leave, end);
handlerStart.Instruction = body.Instructions.Add(CilOpCodes.Nop);
// Push junk values on the stack.
body.Instructions.Add(CilOpCodes.Ldc_I4_0);
body.Instructions.Add(CilOpCodes.Ldc_I4_1);
body.Instructions.Add(CilOpCodes.Ldc_I4_2);
// Leave should clear.
handlerEnd.Instruction = body.Instructions.Add(CilOpCodes.Leave, end);
end.Instruction = body.Instructions.Add(CilOpCodes.Ret);
Assert.Equal(4, body.ComputeMaxStack());
}
[Fact]
public void LazyInitializationTest()
{
// https://github.com/Washi1337/AsmResolver/issues/97
var module = ModuleDefinition.FromFile(typeof(MethodBodyTypes).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(new MetadataToken(TableIndex.Method, 1));
var body = method.CilMethodBody;
method.DeclaringType.Methods.Remove(method);
Assert.NotNull(body);
var module2 = ModuleDefinition.FromFile(typeof(MethodBodyTypes).Assembly.Location, TestReaderParameters);
var method2 = (MethodDefinition) module2.LookupMember(new MetadataToken(TableIndex.Method, 1));
method2.DeclaringType.Methods.Remove(method2);
var body2 = method2.CilMethodBody;
Assert.NotNull(body2);
}
[Fact]
public void PathWithThrowDoesNotHaveToEndWithAnEmptyStack()
{
var body = CreateDummyBody(true);
body.Instructions.Add(CilOpCodes.Ldc_I4_0);
body.Instructions.Add(CilOpCodes.Ldnull);
body.Instructions.Add(CilOpCodes.Throw);
Assert.Equal(2, body.ComputeMaxStack());
}
[Fact]
public void JmpShouldNotContinueAnalysisAfter()
{
var body = CreateDummyBody(true);
body.Instructions.Add(CilOpCodes.Jmp, body.Owner);
body.Instructions.Add(CilOpCodes.Ldnull);
Assert.Equal(0, body.ComputeMaxStack());
}
[Fact]
public void NonEmptyStackAtJmpShouldThrow()
{
var body = CreateDummyBody(true);
body.Instructions.Add(CilOpCodes.Ldnull);
body.Instructions.Add(CilOpCodes.Jmp, body.Owner);
Assert.Throws<StackImbalanceException>(() => body.ComputeMaxStack());
}
[Fact]
public void ReadInvalidMethodBodyErrorShouldAppearInDiagnostics()
{
var bag = new DiagnosticBag();
// Read module with diagnostic bag as error listener.
var module = ModuleDefinition.FromBytes(
Properties.Resources.HelloWorld_InvalidMethodBody,
new ModuleReaderParameters(bag));
// Ensure invalid method body is loaded.
foreach (var method in module.GetOrCreateModuleType().Methods)
Assert.Null(method.CilMethodBody);
// Verify error was reported.
Assert.NotEmpty(bag.Exceptions);
}
[Fact]
public void ExceptionHandlerWithHandlerEndOutsideOfMethodShouldResultInEndLabel()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HandlerEndAtEndOfMethodBody, TestReaderParameters);
var body = module.ManagedEntryPointMethod.CilMethodBody;
Assert.Same(body.Instructions.EndLabel, body.ExceptionHandlers[0].HandlerEnd);
body.VerifyLabels();
}
[Fact]
public void NullBranchTargetShouldThrow()
{
var body = CreateDummyBody(true);
body.Instructions.Add(new CilInstruction(CilOpCodes.Br, null));
Assert.Throws<InvalidCilInstructionException>(() => body.VerifyLabels());
}
[Fact]
public void NonExistingBranchTargetShouldThrow()
{
var body = CreateDummyBody(true);
body.Instructions.Add(CilOpCodes.Br, new CilOffsetLabel(1337));
Assert.Throws<InvalidCilInstructionException>(() => body.VerifyLabels());
}
[Fact]
public void ExistingOffsetBranchTargetShouldNotThrow()
{
var body = CreateDummyBody(true);
body.Instructions.Add(CilOpCodes.Br_S, new CilOffsetLabel(2));
body.Instructions.Add(CilOpCodes.Ret);
body.VerifyLabels();
}
[Fact]
public void ExistingInstructionBranchTargetShouldNotThrow()
{
var body = CreateDummyBody(true);
var label = new CilInstructionLabel();
body.Instructions.Add(CilOpCodes.Br_S, label);
label.Instruction = body.Instructions.Add(CilOpCodes.Ret);
body.VerifyLabels();
}
[Fact]
public void NullHandlerShouldThrow()
{
var body = CreateDummyBody(true);
var handler = new CilExceptionHandler();
body.ExceptionHandlers.Add(handler);
Assert.Throws<AggregateException>(() => body.VerifyLabels());
}
[Fact]
public void ValidHandlerShouldNotThrow()
{
var body = CreateDummyBody(true);
var tryStart = new CilInstructionLabel();
var tryEnd = new CilInstructionLabel();
var handlerStart = new CilInstructionLabel();
var handlerEnd = new CilInstructionLabel();
var handler = new CilExceptionHandler
{
TryStart = tryStart,
TryEnd = tryEnd,
HandlerStart = handlerStart,
HandlerEnd = handlerEnd,
HandlerType = CilExceptionHandlerType.Exception
};
body.Instructions.Add(CilOpCodes.Nop);
tryStart.Instruction = body.Instructions.Add(CilOpCodes.Leave, handlerEnd);
handlerStart.Instruction = tryEnd.Instruction = body.Instructions.Add(CilOpCodes.Leave, handlerEnd);
handlerEnd.Instruction = body.Instructions.Add(CilOpCodes.Ret);
body.ExceptionHandlers.Add(handler);
body.VerifyLabels();
}
[Fact]
public void NullFilterOnFilterHandlerShouldThrow()
{
var body = CreateDummyBody(true);
var tryStart = new CilInstructionLabel();
var tryEnd = new CilInstructionLabel();
var handlerStart = new CilInstructionLabel();
var handlerEnd = new CilInstructionLabel();
var handler = new CilExceptionHandler
{
TryStart = tryStart,
TryEnd = tryEnd,
HandlerStart = handlerStart,
HandlerEnd = handlerEnd,
HandlerType = CilExceptionHandlerType.Filter
};
body.Instructions.Add(CilOpCodes.Nop);
tryStart.Instruction = body.Instructions.Add(CilOpCodes.Leave, handlerEnd);
tryEnd.Instruction = body.Instructions.Add(CilOpCodes.Endfilter);
handlerStart.Instruction = body.Instructions.Add(CilOpCodes.Leave, handlerEnd);
handlerEnd.Instruction = body.Instructions.Add(CilOpCodes.Ret);
body.ExceptionHandlers.Add(handler);
Assert.Throws<InvalidCilInstructionException>(() => body.VerifyLabels());
}
[Fact]
public void SmallTryAndHandlerBlockShouldResultInTinyFormat()
{
var body = CreateDummyBody(true);
for (int i = 0; i < 10; i++)
body.Instructions.Add(CilOpCodes.Nop);
body.Instructions.Add(CilOpCodes.Ret);
body.Instructions.CalculateOffsets();
var handler = new CilExceptionHandler
{
TryStart = body.Instructions[0].CreateLabel(),
TryEnd = body.Instructions[1].CreateLabel(),
HandlerStart = body.Instructions[1].CreateLabel(),
HandlerEnd = body.Instructions[2].CreateLabel(),
HandlerType = CilExceptionHandlerType.Finally
};
body.ExceptionHandlers.Add(handler);
Assert.False(handler.IsFat);
}
[Fact]
public void LargeTryBlockShouldResultInFatFormat()
{
var body = CreateDummyBody(true);
for (int i = 0; i < 300; i++)
body.Instructions.Add(CilOpCodes.Nop);
body.Instructions.Add(CilOpCodes.Ret);
body.Instructions.CalculateOffsets();
var handler = new CilExceptionHandler
{
TryStart = body.Instructions[0].CreateLabel(),
TryEnd = body.Instructions[256].CreateLabel(),
HandlerStart = body.Instructions[256].CreateLabel(),
HandlerEnd = body.Instructions[257].CreateLabel(),
HandlerType = CilExceptionHandlerType.Finally
};
body.ExceptionHandlers.Add(handler);
Assert.True(handler.IsFat);
}
[Fact]
public void LargeHandlerBlockShouldResultInFatFormat()
{
var body = CreateDummyBody(true);
for (int i = 0; i < 300; i++)
body.Instructions.Add(CilOpCodes.Nop);
body.Instructions.Add(CilOpCodes.Ret);
body.Instructions.CalculateOffsets();
var handler = new CilExceptionHandler
{
TryStart = body.Instructions[0].CreateLabel(),
TryEnd = body.Instructions[1].CreateLabel(),
HandlerStart = body.Instructions[1].CreateLabel(),
HandlerEnd = body.Instructions[257].CreateLabel(),
HandlerType = CilExceptionHandlerType.Finally
};
body.ExceptionHandlers.Add(handler);
Assert.True(handler.IsFat);
}
[Fact]
public void SmallTryBlockStartingOnLargeOffsetShouldResultInFatFormat()
{
var body = CreateDummyBody(true);
for (int i = 0; i < 0x20000; i++)
body.Instructions.Add(CilOpCodes.Nop);
body.Instructions.Add(CilOpCodes.Ret);
body.Instructions.CalculateOffsets();
var handler = new CilExceptionHandler
{
TryStart = body.Instructions[0x10000].CreateLabel(),
TryEnd = body.Instructions[0x10001].CreateLabel(),
HandlerStart = body.Instructions[0x10001].CreateLabel(),
HandlerEnd = body.Instructions[0x10002].CreateLabel(),
HandlerType = CilExceptionHandlerType.Finally
};
body.ExceptionHandlers.Add(handler);
Assert.True(handler.IsFat);
}
[Fact]
public void ReadUserStringFromNormalMetadata()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_DoubleUserStringsStream, TestReaderParameters);
var instruction = module.ManagedEntryPointMethod!.CilMethodBody!.Instructions
.First(i => i.OpCode.Code == CilCode.Ldstr);
Assert.Equal("Hello Mars!!", instruction.Operand);
}
[Fact]
public void ReadUserStringFromEnCMetadata()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_DoubleUserStringsStream_EnC, TestReaderParameters);
var instruction = module.ManagedEntryPointMethod!.CilMethodBody!.Instructions
.First(i => i.OpCode.Code == CilCode.Ldstr);
Assert.Equal("Hello World!", instruction.Operand);
}
private CilMethodBody CreateAndReadPatchedBody(IErrorListener listener, Action<CilRawFatMethodBody> patch)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Add new dummy method to type.
var method = new MethodDefinition("Dummy", MethodAttributes.Static,
MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));
module.GetOrCreateModuleType().Methods.Add(method);
// Give it a method body.
var body = new CilMethodBody(method);
method.MethodBody = body;
// Add some random local variables.
for (int i = 0; i < 10; i++)
body.LocalVariables.Add(new CilLocalVariable(module.CorLibTypeFactory.Object));
// Add some random instructions.
for (int i = 0; i < 100; i++)
body.Instructions.Add(CilOpCodes.Nop);
body.Instructions.Add(CilOpCodes.Ret);
// Construct PE image.
var result = new ManagedPEImageBuilder().CreateImage(module);
// Look up raw method body.
var token = result.TokenMapping[method];
var metadata = result.ConstructedImage!.DotNetDirectory!.Metadata!;
var rawBody = (CilRawFatMethodBody) metadata
.GetStream<TablesStream>()
.GetTable<MethodDefinitionRow>()
.GetByRid(token.Rid)
.Body.GetSegment();
Assert.NotNull(rawBody);
// Patch it.
patch(rawBody);
// Read back module definition and look up interpreted method body.
module = ModuleDefinition.FromImage(result.ConstructedImage, new ModuleReaderParameters(listener));
return ((MethodDefinition) module.LookupMember(token)).CilMethodBody;
}
[Fact]
public void ReadLocalsFromBodyWithInvalidCodeStream()
{
var body = CreateAndReadPatchedBody(EmptyErrorListener.Instance, raw =>
{
raw.Code = new DataSegment(new byte[]
{
0xFE // 2-byte prefix opcode
});
});
Assert.NotEmpty(body.LocalVariables);
}
[Fact]
public void ReadCodeStreamFromBodyWithInvalidLocalVariablesSignature()
{
var body = CreateAndReadPatchedBody(EmptyErrorListener.Instance, raw =>
{
raw.LocalVarSigToken = new MetadataToken(TableIndex.StandAloneSig, 0x123456);
});
Assert.NotEmpty(body.Instructions);
}
[Fact]
public void ReadInvalidBody()
{
var body = CreateAndReadPatchedBody(EmptyErrorListener.Instance, raw =>
{
raw.Code = new DataSegment(new byte[] { 0xFE });
raw.LocalVarSigToken = new MetadataToken(TableIndex.StandAloneSig, 0x123456);
});
Assert.NotNull(body);
}
} | 463 | 26,618 | using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using AsmResolver.DotNet.Serialized;
using AsmResolver.DotNet.Signatures;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet.Code.Cil
{
/// <summary>
/// Represents a method body of a method defined in a .NET assembly, implemented using the Common Intermediate Language (CIL).
/// </summary>
public class CilMethodBody : MethodBody
{
/// <summary>
/// Creates a new method body.
/// </summary>
/// <param name="owner">The method that owns the method body.</param>
public CilMethodBody(MethodDefinition owner)
: base(owner)
{
Instructions = new CilInstructionCollection(this);
}
/// <summary>
/// Gets a collection of instructions to be executed in the method.
/// </summary>
public CilInstructionCollection Instructions
{
get;
}
/// <summary>
/// Gets or sets a value indicating the maximum amount of values stored onto the stack.
/// </summary>
public int MaxStack
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether all local variables should be initialized to zero by the runtime
/// upon execution of the method body.
/// </summary>
public bool InitializeLocals
{
get;
set;
}
/// <summary>
/// Gets a value indicating whether the method body is considered fat. That is, it has at least one of the
/// following properties
/// <list type="bullet">
/// <item><description>The method is larger than 64 bytes.</description></item>
/// <item><description>The method defines exception handlers.</description></item>
/// <item><description>The method defines local variables.</description></item>
/// <item><description>The method needs more than 8 values on the stack.</description></item>
/// </list>
/// </summary>
public bool IsFat
{
get
{
if (ExceptionHandlers.Count > 0
|| LocalVariables.Count > 0
|| MaxStack > 8)
{
return true;
}
if (Instructions.Count == 0)
return false;
var last = Instructions[Instructions.Count - 1];
return last.Offset + last.Size >= 64;
}
}
/// <summary>
/// Gets a collection of local variables defined in the method body.
/// </summary>
public CilLocalVariableCollection LocalVariables
{
get;
} = new();
/// <summary>
/// Gets a collection of regions protected by exception handlers, finally or faulting clauses defined in the method body.
/// </summary>
public IList<CilExceptionHandler> ExceptionHandlers
{
get;
} = new List<CilExceptionHandler>();
/// <summary>
/// Gets or sets flags that alter the behaviour of the method body serializer for this specific method body.
/// </summary>
public CilMethodBodyBuildFlags BuildFlags
{
get;
set;
} = CilMethodBodyBuildFlags.FullValidation;
/// <summary>
/// Gets or sets a value indicating whether a .NET assembly builder should automatically compute and update the
/// <see cref="MaxStack"/> property according to the contents of the method body.
/// </summary>
public bool ComputeMaxStackOnBuild
{
get => (BuildFlags & CilMethodBodyBuildFlags.ComputeMaxStack) == CilMethodBodyBuildFlags.ComputeMaxStack;
set => BuildFlags = (BuildFlags & ~CilMethodBodyBuildFlags.ComputeMaxStack)
| (value ? CilMethodBodyBuildFlags.ComputeMaxStack : 0);
}
/// <summary>
/// Gets or sets a value indicating whether a .NET assembly builder should verify branch instructions and
/// exception handler labels in this method body for validity.
/// </summary>
/// <remarks>
/// The value of this property will be ignored if <see cref="ComputeMaxStackOnBuild"/> is set to <c>true</c>.
/// </remarks>
public bool VerifyLabelsOnBuild
{
get => (BuildFlags & CilMethodBodyBuildFlags.VerifyLabels) == CilMethodBodyBuildFlags.VerifyLabels;
set => BuildFlags = (BuildFlags & ~CilMethodBodyBuildFlags.VerifyLabels)
| (value ? CilMethodBodyBuildFlags.VerifyLabels : 0);
}
/// <summary>
/// Creates a CIL method body from a raw CIL method body.
/// </summary>
/// <param name="context">The reader context.</param>
/// <param name="method">The method that owns the method body.</param>
/// <param name="rawBody">The raw method body.</param>
/// <param name="operandResolver">The object instance to use for resolving operands of an instruction in the
/// method body.</param>
/// <returns>The method body.</returns>
public static CilMethodBody FromRawMethodBody(
ModuleReaderContext context,
MethodDefinition method,
CilRawMethodBody rawBody,
ICilOperandResolver? operandResolver = null)
{
var result = new CilMethodBody(method);
// Interpret body header.
var fatBody = rawBody as CilRawFatMethodBody;
if (fatBody is not null)
{
result.MaxStack = fatBody.MaxStack;
result.InitializeLocals = fatBody.InitLocals;
ReadLocalVariables(context, result, fatBody);
}
else
{
result.MaxStack = 8;
result.InitializeLocals = false;
}
// Parse instructions.
operandResolver ??= new PhysicalCilOperandResolver(context.ParentModule, result);
ReadInstructions(context, result, operandResolver, rawBody);
// Read exception handlers.
if (fatBody is not null)
ReadExceptionHandlers(context, fatBody, result);
return result;
}
private static void ReadLocalVariables(
ModuleReaderContext context,
CilMethodBody result,
CilRawFatMethodBody fatBody)
{
// Method bodies can have 0 tokens if there are no locals defined.
if (fatBody.LocalVarSigToken == MetadataToken.Zero)
return;
// If there is a non-zero token however, it needs to point to a stand-alone signature with a
// local variable signature stored in it.
if (!context.ParentModule.TryLookupMember(fatBody.LocalVarSigToken, out var member)
|| member is not StandAloneSignature { Signature: LocalVariablesSignature localVariablesSignature })
{
context.BadImage($"Method body of {result.Owner.SafeToString()} contains an invalid local variable signature token.");
return;
}
// Copy over the local variable types from the signature into the method body.
var variableTypes = localVariablesSignature.VariableTypes;
for (int i = 0; i < variableTypes.Count; i++)
result.LocalVariables.Add(new CilLocalVariable(variableTypes[i]));
}
private static void ReadInstructions(
ModuleReaderContext context,
CilMethodBody result,
ICilOperandResolver operandResolver,
CilRawMethodBody rawBody)
{
try
{
var reader = rawBody.Code.CreateReader();
var disassembler = new CilDisassembler(reader, operandResolver);
result.Instructions.AddRange(disassembler.ReadInstructions());
}
catch (Exception ex)
{
context.RegisterException(new BadImageFormatException(
$"Method body of {result.Owner.SafeToString()} contains an invalid CIL code stream.", ex));
}
}
private static void ReadExceptionHandlers(
ModuleReaderContext context,
CilRawFatMethodBody fatBody,
CilMethodBody result)
{
try
{
for (int i = 0; i < fatBody.ExtraSections.Count; i++)
{
var section = fatBody.ExtraSections[i];
if (section.IsEHTable)
{
var reader = new BinaryStreamReader(section.Data);
uint size = section.IsFat
? CilExceptionHandler.FatExceptionHandlerSize
: CilExceptionHandler.TinyExceptionHandlerSize;
while (reader.CanRead(size))
{
var handler = CilExceptionHandler.FromReader(result, ref reader, section.IsFat);
result.ExceptionHandlers.Add(handler);
}
}
}
}
catch (Exception ex)
{
context.RegisterException(new BadImageFormatException(
$"Method body of {result.Owner.SafeToString()} contains invalid extra sections.", ex));
}
}
/// <summary>
/// Verifies all branch targets and exception handler labels in the method body for validity.
/// </summary>
/// <exception cref="InvalidCilInstructionException">Occurs when one branch instruction in the method body is invalid.</exception>
/// <exception cref="AggregateException">Occurs when multiple branch instructions in the method body are invalid.</exception>
/// <remarks>This method will force the offsets of each instruction to be calculated.</remarks>
public void VerifyLabels() => VerifyLabels(true);
/// <summary>
/// Verifies all branch targets and exception handler labels in the method body for validity.
/// </summary>
/// <param name="calculateOffsets">Determines whether offsets should be calculated beforehand.</param>
/// <exception cref="InvalidCilInstructionException">Occurs when one branch instruction in the method body is invalid.</exception>
/// <exception cref="AggregateException">Occurs when multiple branch instructions in the method body are invalid.</exception>
public void VerifyLabels(bool calculateOffsets)
{
if (calculateOffsets)
Instructions.CalculateOffsets();
new CilLabelVerifier(this).Verify();
}
/// <summary>
/// Computes the maximum values pushed onto the stack by this method body.
/// </summary>
/// <exception cref="StackImbalanceException">Occurs when the method body will result in an unbalanced stack.</exception>
/// <remarks>This method will force the offsets of each instruction to be calculated.</remarks>
public int ComputeMaxStack() => ComputeMaxStack(true);
/// <summary>
/// Computes the maximum values pushed onto the stack by this method body.
/// </summary>
/// <param name="calculateOffsets">Determines whether offsets should be calculated beforehand.</param>
/// <exception cref="StackImbalanceException">Occurs when the method body will result in an unbalanced stack.</exception>
public int ComputeMaxStack(bool calculateOffsets)
{
if (calculateOffsets)
Instructions.CalculateOffsets();
return new CilMaxStackCalculator(this).Compute();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Code\Native\NativeMethodBodyTest.cs | AsmResolver.DotNet.Tests.Code.Native
| NativeMethodBodyTest | ['private const string NonWindowsPlatform = "Test produces a mixed mode assembly which is not supported on non-Windows platforms.";', 'private TemporaryDirectoryFixture _fixture;'] | ['System.Collections.Generic', 'System.IO', 'System.Linq', 'System.Runtime.InteropServices', 'System.Text', 'AsmResolver.DotNet.Code.Native', 'AsmResolver.DotNet.Signatures', 'AsmResolver.PE', 'AsmResolver.PE.Builder', 'AsmResolver.PE.Code', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'AsmResolver.PE.File', 'AsmResolver.PE.Imports', 'AsmResolver.Tests.Runners', 'Xunit'] | xUnit | net8.0 | public class NativeMethodBodyTest : IClassFixture<TemporaryDirectoryFixture>
{
private const string NonWindowsPlatform = "Test produces a mixed mode assembly which is not supported on non-Windows platforms.";
private TemporaryDirectoryFixture _fixture;
public NativeMethodBodyTest(TemporaryDirectoryFixture fixture)
{
_fixture = fixture;
}
private static NativeMethodBody CreateDummyBody(bool isVoid, bool is32Bit)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.TheAnswer_NetFx, TestReaderParameters);
module.IsILOnly = false;
if (is32Bit)
{
module.PEKind = OptionalHeaderMagic.PE32;
module.MachineType = MachineType.I386;
module.IsBit32Required = true;
}
else
{
module.PEKind = OptionalHeaderMagic.PE32Plus;
module.MachineType = MachineType.Amd64;
module.IsBit32Required = false;
}
var method = module
.TopLevelTypes.First(t => t.Name == "Program")
.Methods.First(m => m.Name == "GetTheAnswer");
method.Attributes |= MethodAttributes.PInvokeImpl;
method.ImplAttributes |= MethodImplAttributes.Unmanaged
| MethodImplAttributes.Native
| MethodImplAttributes.PreserveSig;
method.DeclaringType!.Methods.Remove(method);
module.GetOrCreateModuleType().Methods.Add(method);
return method.NativeMethodBody = new NativeMethodBody(method);
}
private static IReadableSegment GetNewCodeSegment(PEImage image)
{
var methodTable = image.DotNetDirectory!.Metadata!
.GetStream<TablesStream>()
.GetTable<MethodDefinitionRow>(TableIndex.Method);
var row = methodTable.First(r => (r.ImplAttributes & MethodImplAttributes.Native) != 0);
Assert.True(row.Body.IsBounded);
return Assert.IsAssignableFrom<IReadableSegment>(row.Body.GetSegment());
}
[Fact]
public void NativeMethodBodyShouldResultInRawCodeSegment()
{
// Create native body.
var body = CreateDummyBody(false, false);
body.Code = new byte[]
{
0xb8, 0x39, 0x05, 0x00, 0x00, // mov rax, 1337
0xc3 // ret
};
// Serialize module to PE image.
var module = body.Owner.Module!;
var image = module.ToPEImage();
// Lookup method row.
var segment = GetNewCodeSegment(image);
// Verify code segment was created.
Assert.Equal(segment.ToArray(), body.Code);
}
[Fact]
public void NativeMethodBodyImportedSymbolShouldEndUpInImportsDirectory()
{
// Create native body.
var body = CreateDummyBody(false, false);
body.Code = new byte[]
{
/* 00: */ 0x48, 0x83, 0xEC, 0x28, // sub rsp, 0x28
/* 04: */ 0x48, 0x8D, 0x0D, 0x10, 0x00, 0x00, 0x00, // lea rcx, [rel str]
/* 0B: */ 0xFF, 0x15, 0x00, 0x00, 0x00, 0x00, // call [rel puts]
/* 11: */ 0xB8, 0x37, 0x13, 0x00, 0x00, // mov eax, 0x1337
/* 16: */ 0x48, 0x83, 0xC4, 0x28, // add rsp, 0x28
/* 1A: */ 0xC3, // ret
// str:
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x66, // "Hello f"
0x72, 0x6f, 0x6d, 0x20, 0x74, 0x68, 0x65, // "rom the"
0x20, 0x75, 0x6e, 0x6d, 0x61, 0x6e, 0x61, // "unmanag"
0x67, 0x65, 0x64, 0x20, 0x77, 0x6f, 0x72, // "ed worl"
0x6c, 0x64, 0x21, 0x00 // "d!"
};
// Fix up reference to ucrtbased.dll!puts
var ucrtbased = new ImportedModule("ucrtbased.dll");
var puts = new ImportedSymbol(0x4fc, "puts");
ucrtbased.Symbols.Add(puts);
body.AddressFixups.Add(new AddressFixup(
0xD, AddressFixupType.Relative32BitAddress, puts
));
// Serialize module to PE image.
var module = body.Owner.Module!;
var image = module.ToPEImage();
// Verify import is added to PE image.
Assert.Contains(image.Imports, m =>
m.Name == ucrtbased.Name && m.Symbols.Any(s => s.Name == puts.Name));
}
[Fact]
public void Native32BitMethodShouldResultInBaseRelocation()
{
// Create native body.
var body = CreateDummyBody(false, true);
body.Code = new byte[]
{
/* 00: */ 0x55, // push ebp
/* 01: */ 0x89, 0xE5, // mov ebp,esp
/* 03: */ 0x6A, 0x6F, // push byte +0x6f ; H
/* 05: */ 0x68, 0x48, 0x65, 0x6C, 0x6C, // push dword 0x6c6c6548 ; ello
/* 0A: */ 0x54, // push esp
/* 0B: */ 0xFF, 0x15, 0x00, 0x00, 0x00, 0x00, // call [dword puts]
/* 11: */ 0x83, 0xC4, 0x0C, // add esp,byte +0xc
/* 14: */ 0xB8, 0x37, 0x13, 0x00, 0x00, // mov eax,0x1337
/* 19: */ 0x5D, // pop ebp
/* 1A: */ 0xC3, // ret
};
// Fix up reference to ucrtbased.dll!puts
var ucrtbased = new ImportedModule("ucrtbased.dll");
var puts = new ImportedSymbol(0x4fc, "puts");
ucrtbased.Symbols.Add(puts);
body.AddressFixups.Add(new AddressFixup(
0xD, AddressFixupType.Absolute32BitAddress, puts
));
// Serialize module to PE image.
var module = body.Owner.Module!;
var image = module.ToPEImage();
// Verify import is added to PE image.
Assert.Contains(image.Imports, m =>
m.Name == ucrtbased.Name && m.Symbols.Any(s => s.Name == puts.Name));
// Verify relocation is added.
var segment = GetNewCodeSegment(image);
Assert.Contains(image.Relocations, r =>
r.Location is RelativeReference relativeRef
&& relativeRef.Base == segment
&& relativeRef.Offset == 0xD);
}
[Fact]
public void DuplicateImportedSymbolsShouldResultInSameImportInImage()
{
// Create native body.
var body = CreateDummyBody(true, false);
body.Code = new byte[]
{
/* 00: */ 0x48, 0x83, 0xEC, 0x28, // sub rsp, 0x28
/* 04: */ 0x48, 0x8D, 0x0D, 0x18, 0x00, 0x00, 0x00, // lea rcx, [rel str]
/* 0B: */ 0xFF, 0x15, 0x00, 0x00, 0x00, 0x00, // call [rel puts]
/* 11: */ 0x48, 0x8D, 0x0D, 0x0B, 0x00, 0x00, 0x00, // lea rcx, [rel str]
/* 18: */ 0xFF, 0x15, 0x00, 0x00, 0x00, 0x00, // call [rel puts]
/* 24: */ 0xC3, // ret
// str:
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x66, // "Hello f"
0x72, 0x6f, 0x6d, 0x20, 0x74, 0x68, 0x65, // "rom the"
0x20, 0x75, 0x6e, 0x6d, 0x61, 0x6e, 0x61, // "unmanag"
0x67, 0x65, 0x64, 0x20, 0x77, 0x6f, 0x72, // "ed worl"
0x6c, 0x64, 0x21, 0x00 // "d!"
};
// Add reference to ucrtbased.dll!puts at offset 0xD.
var ucrtbased1 = new ImportedModule("ucrtbased.dll");
var puts1 = new ImportedSymbol(0x4fc, "puts");
ucrtbased1.Symbols.Add(puts1);
body.AddressFixups.Add(new AddressFixup(
0xD, AddressFixupType.Relative32BitAddress, puts1
));
// Add second (duplicated) reference to ucrtbased.dll!puts at offset 0x20.
var ucrtbased2 = new ImportedModule("ucrtbased.dll");
var puts2 = new ImportedSymbol(0x4fc, "puts");
ucrtbased2.Symbols.Add(puts2);
body.AddressFixups.Add(new AddressFixup(
0x20, AddressFixupType.Relative32BitAddress, puts2
));
// Serialize module to PE image.
var module = body.Owner.Module!;
var image = module.ToPEImage();
// Verify import is added to PE image.
var importedModule = Assert.Single(image.Imports);
Assert.NotNull(importedModule);
Assert.Equal(ucrtbased1.Name, importedModule.Name);
var importedSymbol = Assert.Single(importedModule.Symbols);
Assert.NotNull(importedSymbol);
Assert.Equal(puts1.Name, importedSymbol.Name);
}
[Fact]
public void ReadNativeMethodShouldResultInReferenceWithRightContents()
{
// Create native body.
var body = CreateDummyBody(false, false);
body.Code = new byte[]
{
0xb8, 0x39, 0x05, 0x00, 0x00, // mov rax, 1337
0xc3 // ret
};
// Serialize module.
var module = body.Owner.Module!;
using var stream = new MemoryStream();
module.Write(stream);
// Reload and look up native method.
var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
var method = newModule.GetAllTypes().SelectMany(t => t.Methods).First(m => m.IsNative);
// Verify if code behind the entry address is consistent.
var reference = method.MethodBody?.Address;
Assert.NotNull(reference);
Assert.True(reference.CanRead);
byte[] newBuffer = new byte[body.Code.Length];
reference.CreateReader().ReadBytes(newBuffer, 0, newBuffer.Length);
Assert.Equal(body.Code, newBuffer);
}
[SkippableTheory]
[InlineData(
true,
new byte[] {0xB8, 0x00, 0x00, 0x00, 0x00}, // mov eax, message
1u, AddressFixupType.Absolute32BitAddress,
6u)]
[InlineData(
false,
new byte[] {0x48, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // mov rax, message
2u, AddressFixupType.Absolute64BitAddress,
11u)]
public void NativeBodyWithLocalSymbols(bool is32Bit, byte[] movInstruction, uint fixupOffset, AddressFixupType fixupType, uint symbolOffset)
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
// Create native body.
var code = new List<byte>(movInstruction);
code.AddRange(new byte[]
{
0xc3, // ret
// message:
0x48, 0x00, 0x65, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6f, 0x00, 0x2c, 0x00, 0x20, 0x00, // "Hello, "
0x77, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x6c, 0x00, 0x64, 0x00, 0x21, 0x00, 0x00, 0x00 // "world!."
});
var body = CreateDummyBody(false, is32Bit);
body.Code = code.ToArray();
// Define local symbol.
var messageSymbol = new NativeLocalSymbol(body, symbolOffset);
InjectCallToNativeBody(body, messageSymbol, fixupOffset, fixupType);
// Verify.
_fixture
.GetRunner<FrameworkPERunner>()
.RebuildAndRun(body.Owner.Module!, "StringPointer.exe", "Hello, world!\n");
}
[SkippableTheory]
[InlineData(
true,
new byte[] {0xB8, 0x00, 0x00, 0x00, 0x00}, // mov eax, message
1u, AddressFixupType.Absolute32BitAddress)]
[InlineData(
false,
new byte[] {0x48, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // mov rax, message
2u, AddressFixupType.Absolute64BitAddress)]
public void NativeBodyWithGlobalSymbol(bool is32Bit, byte[] movInstruction, uint fixupOffset, AddressFixupType fixupType)
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
// Create native body.
var code = new List<byte>(movInstruction)
{
0xc3 // ret
};
var body = CreateDummyBody(false, is32Bit);
body.Code = code.ToArray();
// Define new symbol.
var messageSegment = new DataSegment(Encoding.Unicode.GetBytes("Hello, world!\0"));
var messageSymbol = new Symbol(messageSegment.ToReference());
InjectCallToNativeBody(body, messageSymbol, fixupOffset, fixupType);
// Add symbol to new section.
var image = body.Owner.Module!.ToPEImage();
var file = new ManagedPEFileBuilder().CreateFile(image);
file.Sections.Add(new PESection(
".asmres",
SectionFlags.MemoryRead | SectionFlags.ContentInitializedData,
messageSegment));
// Verify.
_fixture
.GetRunner<FrameworkPERunner>()
.RebuildAndRun(file, "StringPointer.exe", "Hello, world!\n");
}
private static void InjectCallToNativeBody(NativeMethodBody body, ISymbol messageSymbol, uint fixupOffset, AddressFixupType fixupType)
{
// Fixup address in mov instruction.
body.AddressFixups.Add(new AddressFixup(fixupOffset, fixupType, messageSymbol));
// Update main to call native method, convert the returned pointer to a String, and write to stdout.
var module = body.Owner.Module!;
body.Owner.Signature!.ReturnType = module.CorLibTypeFactory.IntPtr;
var stringConstructor = module.CorLibTypeFactory.String.Type
.CreateMemberReference(".ctor", MethodSignature.CreateInstance(
module.CorLibTypeFactory.Void,
module.CorLibTypeFactory.Char.MakePointerType()
))
.ImportWith(module.DefaultImporter);
var writeLine = module.CorLibTypeFactory.CorLibScope
.CreateTypeReference("System", "Console")
.CreateMemberReference("WriteLine", MethodSignature.CreateStatic(
module.CorLibTypeFactory.Void,
module.CorLibTypeFactory.String
))
.ImportWith(module.DefaultImporter);
var instructions = module.ManagedEntryPointMethod!.CilMethodBody!.Instructions;
instructions.Clear();
instructions.Add(CilOpCodes.Call, body.Owner);
instructions.Add(CilOpCodes.Newobj, stringConstructor);
instructions.Add(CilOpCodes.Call, writeLine);
instructions.Add(CilOpCodes.Ret);
}
} | 574 | 16,382 | using System;
using System.Collections.Generic;
using AsmResolver.Collections;
using AsmResolver.PE.Code;
using AsmResolver.Shims;
namespace AsmResolver.DotNet.Code.Native
{
/// <summary>
/// Represents a method body of a method defined in a .NET assembly, implemented using machine code that runs
/// natively on the processor.
/// </summary>
public class NativeMethodBody : MethodBody
{
/// <summary>
/// Creates a new empty native method body.
/// </summary>
/// <param name="owner">The method that owns the body.</param>
public NativeMethodBody(MethodDefinition owner)
: base(owner)
{
Code = ArrayShim.Empty<byte>();
}
/// <summary>
/// Creates a new native method body with the provided raw code stream.
/// </summary>
/// <param name="owner">The method that owns the body.</param>
/// <param name="code">The raw code stream.</param>
public NativeMethodBody(MethodDefinition owner, byte[] code)
: base(owner)
{
Code = code;
}
/// <summary>
/// Gets or sets the raw native code stream.
/// </summary>
public byte[] Code
{
get;
set;
}
/// <summary>
/// Gets a collection of fixups that need to be applied upon writing the code to the output stream.
/// This includes addresses to imported symbols and global fields stored in data sections.
/// </summary>
public IList<AddressFixup> AddressFixups
{
get;
} = new List<AddressFixup>();
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Collections\MethodSemanticsCollectionTest.cs | AsmResolver.DotNet.Tests.Collections
| MethodSemanticsCollectionTest | ['private readonly PropertyDefinition _property;', 'private readonly PropertyDefinition _property2;', 'private readonly MethodDefinition _getMethod;', 'private readonly MethodDefinition _setMethod;'] | ['System', 'AsmResolver.DotNet.Signatures', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class MethodSemanticsCollectionTest
{
private readonly PropertyDefinition _property;
private readonly PropertyDefinition _property2;
private readonly MethodDefinition _getMethod;
private readonly MethodDefinition _setMethod;
public MethodSemanticsCollectionTest()
{
var module = new ModuleDefinition("Module");
_property = new PropertyDefinition("Property", 0,
PropertySignature.CreateStatic(module.CorLibTypeFactory.Int32));
_property2 = new PropertyDefinition("Property2", 0,
PropertySignature.CreateStatic(module.CorLibTypeFactory.Int32));
_getMethod = new MethodDefinition("get_Property",
MethodAttributes.Public | MethodAttributes.Static,
MethodSignature.CreateStatic(module.CorLibTypeFactory.Int32));
_setMethod = new MethodDefinition("set_Property",
MethodAttributes.Public | MethodAttributes.Static,
MethodSignature.CreateStatic(module.CorLibTypeFactory.Void, module.CorLibTypeFactory.Int32));
}
[Fact]
public void AddSemanticsShouldSetSemanticsPropertyOfMethod()
{
var semantics = new MethodSemantics(_getMethod, MethodSemanticsAttributes.Getter);
_property.Semantics.Add(semantics);
Assert.Same(semantics, _getMethod.Semantics);
}
[Fact]
public void RemoveSemanticsShouldUnsetSemanticsPropertyOfMethod()
{
var semantics = new MethodSemantics(_getMethod, MethodSemanticsAttributes.Getter);
_property.Semantics.Add(semantics);
_property.Semantics.Remove(semantics);
Assert.Null(_getMethod.Semantics);
}
[Fact]
public void ClearMultipleSemanticsShouldUnsetAllSemanticsProperties()
{
var semantics1 = new MethodSemantics(_getMethod, MethodSemanticsAttributes.Getter);
var semantics2 = new MethodSemantics(_setMethod, MethodSemanticsAttributes.Getter);
_property.Semantics.Add(semantics1);
_property.Semantics.Add(semantics2);
_property.Semantics.Clear();
Assert.Null(_getMethod.Semantics);
Assert.Null(_setMethod.Semantics);
}
[Fact]
public void AddSemanticsAgainShouldThrow()
{
var semantics = new MethodSemantics(_getMethod, MethodSemanticsAttributes.Getter);
_property.Semantics.Add(semantics);
Assert.Throws<ArgumentException>(() => _property.Semantics.Add(semantics));
}
[Fact]
public void AddEquivalentSemanticsAgainShouldThrow()
{
var semantics1 = new MethodSemantics(_getMethod, MethodSemanticsAttributes.Getter);
var semantics2 = new MethodSemantics(_getMethod, MethodSemanticsAttributes.Getter);
_property.Semantics.Add(semantics1);
Assert.Throws<ArgumentException>(() => _property.Semantics.Add(semantics2));
}
[Fact]
public void AddExistingSemanticsToAnotherOwnerShouldThrow()
{
var semantics = new MethodSemantics(_getMethod, MethodSemanticsAttributes.Getter);
_property.Semantics.Add(semantics);
Assert.Throws<ArgumentException>(() => _property2.Semantics.Add(semantics));
}
} | 170 | 3,677 | using System;
using System.Collections.Generic;
using System.Linq;
namespace AsmResolver.DotNet.Collections
{
/// <summary>
/// Provides an implementation of a list of method semantics that are associated to a property or event.
/// </summary>
public class MethodSemanticsCollection : MemberCollection<IHasSemantics, MethodSemantics>
{
/// <summary>
/// Creates a new instance of the <see cref="MethodSemanticsCollection"/> class.
/// </summary>
/// <param name="owner">The owner of the collection.</param>
public MethodSemanticsCollection(IHasSemantics owner)
: base(owner)
{
}
/// <summary>
/// Creates a new instance of the <see cref="MethodSemanticsCollection"/> class.
/// </summary>
/// <param name="owner">The owner of the collection.</param>
/// <param name="capacity">The initial number of elements the collection can store.</param>
public MethodSemanticsCollection(IHasSemantics owner, int capacity)
: base(owner, capacity)
{
}
internal bool ValidateMembership
{
get;
set;
} = true;
private void AssertSemanticsValidity(MethodSemantics item)
{
if (!ValidateMembership)
return;
if (item.Method is null)
throw new ArgumentException("Method semantics is not assigned to a method.");
if (item.Method.Semantics is { })
throw new ArgumentException($"Method {item.Method} is already assigned semantics.");
}
/// <inheritdoc />
protected override void OnInsertItem(int index, MethodSemantics item)
{
AssertSemanticsValidity(item);
base.OnInsertItem(index, item);
item.Method!.Semantics = item;
}
/// <inheritdoc />
protected override void OnSetItem(int index, MethodSemantics item)
{
AssertSemanticsValidity(item);
Items[index].Method!.Semantics = null;
base.OnSetItem(index, item);
item.Method!.Semantics = item;
}
/// <inheritdoc />
protected override void OnInsertRange(int index, IEnumerable<MethodSemantics> items)
{
var list = items as MethodSemantics[] ?? items.ToArray();
foreach (var item in list)
AssertSemanticsValidity(item);
base.OnInsertRange(index, list);
foreach (var item in list)
item.Method!.Semantics = item;
}
/// <inheritdoc />
protected override void OnRemoveItem(int index)
{
Items[index].Method!.Semantics = null;
base.OnRemoveItem(index);
}
/// <inheritdoc />
protected override void OnClearItems()
{
foreach (var item in Items)
item.Method!.Semantics = null;
base.OnClearItems();
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Collections\ParameterCollectionTest.cs | AsmResolver.DotNet.Tests.Collections
| ParameterCollectionTest | [] | ['System', 'System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Methods', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class ParameterCollectionTest
{
private static MethodDefinition ObtainStaticTestMethod(string name)
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleMethods));
return type.Methods.First(m => m.Name == name);
}
private static MethodDefinition ObtainInstanceTestMethod(string name)
{
var module = ModuleDefinition.FromFile(typeof(InstanceMethods).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(InstanceMethods));
return type.Methods.First(m => m.Name == name);
}
private static MethodDefinition ObtainGenericInstanceTestMethod(string name)
{
var module = ModuleDefinition.FromFile(typeof(GenericInstanceMethods<,>).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == "GenericInstanceMethods`2");
return type.Methods.First(m => m.Name == name);
}
[Fact]
public void ReadEmptyParametersFromStaticMethod()
{
var method = ObtainStaticTestMethod(nameof(MultipleMethods.VoidParameterlessMethod));
Assert.Empty(method.Parameters);
Assert.Null(method.Parameters.ThisParameter);
}
[Fact]
public void ReadSingleParameterFromStaticMethod()
{
var method = ObtainStaticTestMethod(nameof(MultipleMethods.SingleParameterMethod));
Assert.Single(method.Parameters);
Assert.Equal("intParameter", method.Parameters[0].Name);
Assert.True(method.Parameters[0].ParameterType.IsTypeOf("System", "Int32"));
Assert.Null(method.Parameters.ThisParameter);
}
[Fact]
public void ReadMultipleParametersFromStaticMethod()
{
var method = ObtainStaticTestMethod(nameof(MultipleMethods.MultipleParameterMethod));
Assert.Equal(new[]
{
"intParameter",
"stringParameter",
"typeDefOrRefParameter"
}, method.Parameters.Select(p => p.Name));
Assert.Equal(new[]
{
"System.Int32",
"System.String",
typeof(MultipleMethods).FullName
}, method.Parameters.Select(p => p.ParameterType.FullName));
Assert.Null(method.Parameters.ThisParameter);
}
[Fact]
public void ReadEmptyParametersFromInstanceMethod()
{
var method = ObtainInstanceTestMethod(nameof(InstanceMethods.InstanceParameterlessMethod));
Assert.Empty(method.Parameters);
Assert.NotNull(method.Parameters.ThisParameter);
Assert.Equal(nameof(InstanceMethods), method.Parameters.ThisParameter.ParameterType.Name);
}
[Fact]
public void ReadSingleParameterFromInstanceMethod()
{
var method = ObtainInstanceTestMethod(nameof(InstanceMethods.InstanceSingleParameterMethod));
Assert.Single(method.Parameters);
Assert.Equal(new[]
{
"intParameter"
}, method.Parameters.Select(p => p.Name));
Assert.NotNull(method.Parameters.ThisParameter);
Assert.Equal(nameof(InstanceMethods), method.Parameters.ThisParameter.ParameterType.Name);
}
[Fact]
public void ReadMultipleParametersFromInstanceMethod()
{
var method = ObtainInstanceTestMethod(nameof(InstanceMethods.InstanceMultipleParametersMethod));
Assert.Equal(new[]
{
"intParameter",
"stringParameter",
"boolParameter"
}, method.Parameters.Select(p => p.Name));
Assert.Equal(new[]
{
"System.Int32",
"System.String",
"System.Boolean",
}, method.Parameters.Select(p => p.ParameterType.FullName));
Assert.NotNull(method.Parameters.ThisParameter);
Assert.Equal(nameof(InstanceMethods), method.Parameters.ThisParameter.ParameterType.Name);
}
[Fact]
public void ReadEmptyParametersFromGenericInstanceMethod()
{
var method = ObtainGenericInstanceTestMethod(nameof(GenericInstanceMethods<int, int>.InstanceParameterlessMethod));
Assert.Empty(method.Parameters);
Assert.NotNull(method.Parameters.ThisParameter);
var genericInstanceType = Assert.IsAssignableFrom<GenericInstanceTypeSignature>(method.Parameters.ThisParameter.ParameterType);
Assert.Equal("GenericInstanceMethods`2", genericInstanceType.GenericType.Name);
Assert.Equal(2, genericInstanceType.TypeArguments.Count);
Assert.All(genericInstanceType.TypeArguments, (typeArgument, i) =>
{
var genericParameterSignature = Assert.IsAssignableFrom<GenericParameterSignature>(typeArgument);
Assert.Equal(GenericParameterType.Type, genericParameterSignature.ParameterType);
Assert.Equal(i, genericParameterSignature.Index);
});
}
[Fact]
public void ReadReturnTypeFromStaticParameterlessMethod()
{
var method = ObtainStaticTestMethod(nameof(MultipleMethods.VoidParameterlessMethod));
Assert.True(method.Parameters.ReturnParameter.ParameterType.IsTypeOf("System", "Void"));
}
[Fact]
public void UpdateReturnTypeFromStaticParameterlessMethodShouldThrow()
{
var method = ObtainStaticTestMethod(nameof(MultipleMethods.VoidParameterlessMethod));
Assert.Throws<InvalidOperationException>(() => method.Parameters.ReturnParameter.ParameterType = method.Module.CorLibTypeFactory.Int32);
}
[Fact]
public void UpdateThisParameterParameterTypeShouldThrow()
{
var method = ObtainInstanceTestMethod(nameof(InstanceMethods.InstanceParameterlessMethod));
Assert.Throws<InvalidOperationException>(() => method.Parameters.ThisParameter.ParameterType = method.Module.CorLibTypeFactory.Int32);
}
[Fact]
public void MoveMethodToOtherTypeShouldUpdateThisParameter()
{
var method = ObtainInstanceTestMethod(nameof(InstanceMethods.InstanceParameterlessMethod));
var newType = method.Module.TopLevelTypes.First(t => t.Name == nameof(MultipleMethods));
method.DeclaringType.Methods.Remove(method);
newType.Methods.Add(method);
method.Parameters.PullUpdatesFromMethodSignature();
Assert.Equal(nameof(MultipleMethods), method.Parameters.ThisParameter.ParameterType.Name);
}
[Fact]
public void TurnInstanceMethodIntoStaticMethodShouldRemoveThisParameter()
{
var method = ObtainInstanceTestMethod(nameof(InstanceMethods.InstanceParameterlessMethod));
method.IsStatic = true;
method.Signature.HasThis = false;
method.Parameters.PullUpdatesFromMethodSignature();
Assert.Null(method.Parameters.ThisParameter);
}
[Fact]
public void TurnStaticMethodIntoInstanceMethodShouldAddThisParameter()
{
var method = ObtainStaticTestMethod(nameof(MultipleMethods.VoidParameterlessMethod));
method.IsStatic = false;
method.Signature.HasThis = true;
method.Parameters.PullUpdatesFromMethodSignature();
Assert.NotNull(method.Parameters.ThisParameter);
Assert.Equal(nameof(MultipleMethods), method.Parameters.ThisParameter.ParameterType.Name);
}
[Fact]
public void ThisParameterOfCorLibShouldResultInCorLibTypeSignature()
{
var module = ModuleDefinition.FromFile(typeof(object).Assembly.Location, TestReaderParameters);
var type = module.CorLibTypeFactory.Object.Type.Resolve();
var instanceMethod = type.Methods.First(t => !t.IsStatic);
var signature = Assert.IsAssignableFrom<CorLibTypeSignature>(instanceMethod.Parameters.ThisParameter.ParameterType);
Assert.Same(module.CorLibTypeFactory.Object, signature);
}
[Fact]
public void UnnamedParameterShouldResultInDummyName()
{
var method = ObtainInstanceTestMethod(nameof(InstanceMethods.InstanceMultipleParametersMethod));
foreach (var param in method.ParameterDefinitions)
param.Name = null;
Assert.All(method.Parameters, p => Assert.Equal(p.Name, $"A_{p.MethodSignatureIndex}"));
}
[Fact]
public void GetOrCreateDefinitionShouldCreateNewDefinition()
{
var dummyModule = new ModuleDefinition("TestModule");
var corLibTypesFactory = dummyModule.CorLibTypeFactory;
var method = new MethodDefinition("TestMethodNoParameterDefinitions",
MethodAttributes.Public | MethodAttributes.Static,
MethodSignature.CreateStatic(corLibTypesFactory.Void, corLibTypesFactory.Int32));
var param = Assert.Single(method.Parameters);
Assert.Null(param.Definition);
var definition = param.GetOrCreateDefinition();
Assert.Equal(param.Sequence, definition.Sequence);
Assert.Equal(Utf8String.Empty, definition.Name);
Assert.Equal((ParameterAttributes)0, definition.Attributes);
Assert.Contains(definition, method.ParameterDefinitions);
Assert.Same(definition, param.Definition);
}
[Fact]
public void GetOrCreateDefinitionShouldReturnExistingDefinition()
{
var method = ObtainStaticTestMethod(nameof(MultipleMethods.SingleParameterMethod));
var param = Assert.Single(method.Parameters);
var existingDefinition = param.Definition;
Assert.NotNull(existingDefinition);
var definition = param.GetOrCreateDefinition();
Assert.Same(existingDefinition, definition);
}
[Fact]
public void GetOrCreateDefinitionThrowsOnVirtualThisParameter()
{
var method = ObtainInstanceTestMethod(nameof(InstanceMethods.InstanceParameterlessMethod));
Assert.NotNull(method.Parameters.ThisParameter);
Assert.Throws<InvalidOperationException>(() => method.Parameters.ThisParameter.GetOrCreateDefinition());
}
} | 274 | 11,266 | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using AsmResolver.DotNet.Signatures;
namespace AsmResolver.DotNet.Collections
{
/// <summary>
/// Represents an ordered collection of parameters that a method defines and/or uses. This includes the hidden
/// "this" parameter, as well as the virtual return parameter.
/// </summary>
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
public class ParameterCollection : IReadOnlyList<Parameter>
{
private readonly List<Parameter> _parameters = new List<Parameter>();
private readonly MethodDefinition _owner;
private bool _hasThis;
/// <summary>
/// Creates a new parameter collection for the specified method.
/// </summary>
/// <param name="owner">The method that owns the parameters.</param>
internal ParameterCollection(MethodDefinition owner)
{
_owner = owner ?? throw new ArgumentNullException(nameof(owner));
ReturnParameter = new Parameter(this, -1, -1);
PullUpdatesFromMethodSignature();
}
/// <inheritdoc />
public int Count => _parameters.Count;
/// <summary>
/// Gets the displacement of the parameters in the method signature, depending on the value of
/// <see cref="CallingConventionSignature.HasThis"/>.
/// </summary>
public int MethodSignatureIndexBase => _hasThis ? 1 : 0;
/// <inheritdoc />
public Parameter this[int index] => _parameters[index];
/// <summary>
/// Gets the virtual parameter representing the return value of the method.
/// </summary>
public Parameter ReturnParameter
{
get;
}
/// <summary>
/// Gets the virtual parameter containing the current instance of the class that the method is defined in.
/// </summary>
public Parameter? ThisParameter
{
get;
private set;
}
/// <summary>
/// Updates the list of parameters according to the parameters specified in the method's signature.
/// </summary>
/// <remarks>
/// This method should be called once the signature of the owner method is updated.
/// </remarks>
public void PullUpdatesFromMethodSignature()
{
bool newHasThis = _owner.Signature?.HasThis ?? false;
if (newHasThis != _hasThis)
{
_parameters.Clear();
_hasThis = newHasThis;
}
EnsureAllParametersCreated();
UpdateParameterTypes();
}
private void EnsureAllParametersCreated()
{
// Update this parameter if necessary.
if (!_hasThis)
{
ThisParameter = null;
}
else
{
ThisParameter ??= new Parameter(this, -1, 0);
}
int signatureCount = _owner.Signature?.ParameterTypes.Count ?? 0;
// Add missing parameters.
while (_parameters.Count < signatureCount)
{
int index = _parameters.Count;
var parameter = new Parameter(this, index, index + MethodSignatureIndexBase);
_parameters.Add(parameter);
}
// Remove excess parameters.
while (_parameters.Count > signatureCount)
{
_parameters[_parameters.Count - 1].Remove();
_parameters.RemoveAt(_parameters.Count - 1);
}
}
private void UpdateParameterTypes()
{
// Update implicit parameters.
if (_owner.Signature is null)
return;
ReturnParameter.SetParameterTypeInternal(_owner.Signature.ReturnType);
if (GetThisParameterType() is { } thisType)
ThisParameter?.SetParameterTypeInternal(thisType);
// Update remaining parameter types.
for (int i = 0; i < _parameters.Count; i++)
_parameters[i].SetParameterTypeInternal(_owner.Signature.ParameterTypes[i]);
}
private TypeSignature? GetThisParameterType()
{
var declaringType = _owner.DeclaringType;
if (declaringType is null)
return null;
TypeSignature result;
if (declaringType.GenericParameters.Count > 0)
{
var genArgs = new TypeSignature[declaringType.GenericParameters.Count];
for (int i = 0; i < genArgs.Length; i++)
genArgs[i] = new GenericParameterSignature(_owner.Module, GenericParameterType.Type, i);
result = declaringType.MakeGenericInstanceType(genArgs);
}
else
{
result = declaringType.ToTypeSignature();
}
if (declaringType.IsValueType)
result = result.MakeByReferenceType();
return result;
}
internal ParameterDefinition? GetParameterDefinition(int sequence)
{
return _owner.ParameterDefinitions.FirstOrDefault(p => p.Sequence == sequence);
}
internal ParameterDefinition GetOrCreateParameterDefinition(Parameter parameter)
{
if (parameter == ThisParameter)
throw new InvalidOperationException("Cannot retrieve a parameter definition for the virtual this parameter.");
if (parameter.Definition is not null)
return parameter.Definition;
var parameterDefinition = new ParameterDefinition(parameter.Sequence, Utf8String.Empty, 0);
_owner.ParameterDefinitions.Add(parameterDefinition);
return parameterDefinition;
}
internal void PushParameterUpdateToSignature(Parameter parameter)
{
if (_owner.Signature is null)
return;
if (parameter.Index == -2)
_owner.Signature.ReturnType = parameter.ParameterType;
else if (parameter.Index == -1)
throw new InvalidOperationException("Cannot update the parameter type of the this parameter.");
else
_owner.Signature.ParameterTypes[parameter.Index] = parameter.ParameterType;
}
/// <summary>
/// Determines whether a parameter with the provided signature index exists within this parameter collection.
/// </summary>
/// <param name="index">The method signature index of the parameter.</param>
/// <returns><c>true</c> if the parameter exists, <c>false</c> otherwise.</returns>
public bool ContainsSignatureIndex(int index)
{
int actualIndex = index - MethodSignatureIndexBase;
int lowerIndex = _hasThis ? -1 : 0;
return actualIndex >= lowerIndex && actualIndex < Count;
}
/// <summary>
/// Gets a parameter by its method signature index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns>The parameter.</returns>
/// <remarks>
/// This method can be used to resolve parameter indices in a method body to parameter objects.
/// </remarks>
public Parameter GetBySignatureIndex(int index)
{
int actualIndex = index - MethodSignatureIndexBase;
return actualIndex == -1 && _hasThis
? ThisParameter ?? throw new IndexOutOfRangeException()
: this[actualIndex];
}
/// <inheritdoc />
public IEnumerator<Parameter> GetEnumerator() => _parameters.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Config\Json\RuntimeConfigurationTest.cs | AsmResolver.DotNet.Tests.Config.Json
| RuntimeConfigurationTest | [] | ['System.Collections.Generic', 'System.Text.Json', 'AsmResolver.DotNet.Config.Json', 'Xunit'] | xUnit | net8.0 | public class RuntimeConfigurationTest
{
[Fact]
public void ReadSingleFramework()
{
var config = RuntimeConfiguration.FromJson(@"{
""runtimeOptions"": {
""tfm"": ""netcoreapp3.1"",
""framework"": {
""name"": ""Microsoft.NETCore.App"",
""version"": ""3.1.0""
}
}
}");
Assert.NotNull(config);
Assert.NotNull(config.RuntimeOptions);
Assert.Equal("netcoreapp3.1", config.RuntimeOptions.TargetFrameworkMoniker);
var framework = config.RuntimeOptions.Framework;
Assert.NotNull(framework);
Assert.Equal("Microsoft.NETCore.App", framework.Name);
Assert.Equal("3.1.0", framework.Version);
}
[Fact]
public void ReadMultipleFrameworks()
{
var config = RuntimeConfiguration.FromJson(@"{
""runtimeOptions"": {
""tfm"": ""net5.0"",
""includedFrameworks"": [
{
""name"": ""Microsoft.NETCore.App"",
""version"": ""5.0.0""
},
{
""name"": ""Microsoft.WindowsDesktop.App"",
""version"": ""5.0.0""
}
]
}
}");
Assert.NotNull(config);
Assert.NotNull(config.RuntimeOptions);
Assert.Equal("net5.0", config.RuntimeOptions.TargetFrameworkMoniker);
var frameworks = config.RuntimeOptions.IncludedFrameworks;
Assert.NotNull(frameworks);
Assert.Contains(frameworks, framework => framework is { Name: "Microsoft.NETCore.App", Version: "5.0.0" });
Assert.Contains(frameworks, framework => framework is { Name: "Microsoft.WindowsDesktop.App", Version: "5.0.0" });
}
[Fact]
public void ReadConfigurationProperties()
{
var config = RuntimeConfiguration.FromJson(@"{
""runtimeOptions"": {
""tfm"": ""netcoreapp3.1"",
""framework"": {
""name"": ""Microsoft.NETCore.App"",
""version"": ""3.1.0""
},
""configProperties"": {
""System.GC.Concurrent"": false,
""System.Threading.ThreadPool.MinThreads"": 4
}
}
}");
Assert.NotNull(config);
Assert.NotNull(config.RuntimeOptions.ConfigProperties);
#if NET5_0_OR_GREATER
var value = Assert.Contains("System.GC.Concurrent", config.RuntimeOptions.ConfigProperties);
Assert.Equal(JsonValueKind.False, value.ValueKind);
value = Assert.Contains("System.Threading.ThreadPool.MinThreads", config.RuntimeOptions.ConfigProperties);
Assert.Equal(JsonValueKind.Number, value.ValueKind);
Assert.Equal(4, value.GetInt32());
#else
object value = Assert.Contains("System.GC.Concurrent", config.RuntimeOptions.ConfigProperties);
Assert.Equal(false, value);
value = Assert.Contains("System.Threading.ThreadPool.MinThreads", config.RuntimeOptions.ConfigProperties);
Assert.Equal(4, value);
#endif
}
} | 170 | 3,391 | using System;
using System.IO;
#if NET5_0_OR_GREATER
using System.Text.Json;
#endif
namespace AsmResolver.DotNet.Config.Json
{
/// <summary>
/// Represents the root object of a runtime configuration, stored in a *.runtimeconfig.json file.
/// </summary>
public class RuntimeConfiguration
{
/// <summary>
/// Parses runtime configuration from a JSON file.
/// </summary>
/// <param name="path">The path to the runtime configuration file.</param>
/// <returns>The parsed runtime configuration.</returns>
public static RuntimeConfiguration? FromFile(string path)
{
return FromJson(File.ReadAllText(path));
}
/// <summary>
/// Parses runtime configuration from a JSON string.
/// </summary>
/// <param name="json">The raw json string configuration file.</param>
/// <returns>The parsed runtime configuration.</returns>
public static RuntimeConfiguration? FromJson(string json)
{
#if NET5_0_OR_GREATER
return JsonSerializer.Deserialize(json, RuntimeConfigurationSerializerContext.Default.RuntimeConfiguration);
#else
var result = new RuntimeConfiguration();
var root = JSON.Parse(json);
if (!root.HasKey("runtimeOptions"))
return result;
result.RuntimeOptions = RuntimeOptions.FromJsonNode(root["runtimeOptions"]);
return result;
#endif
}
/// <summary>
/// Creates a new empty runtime configuration.
/// </summary>
public RuntimeConfiguration()
{
RuntimeOptions = new();
}
/// <summary>
/// Creates a new runtime configuration with the provided options.
/// </summary>
public RuntimeConfiguration(RuntimeOptions options)
{
RuntimeOptions = options;
}
/// <summary>
/// Gets or sets the runtime options.
/// </summary>
public RuntimeOptions RuntimeOptions
{
get;
set;
}
/// <summary>
/// Serializes the configuration to a JSON string.
/// </summary>
/// <returns>The JSON string.</returns>
public string ToJson()
{
#if NET5_0_OR_GREATER
return JsonSerializer.Serialize(this, RuntimeConfigurationSerializerContext.Default.RuntimeConfiguration);
#else
throw new NotSupportedException();
#endif
}
/// <summary>
/// Writes the configuration to a file.
/// </summary>
/// <param name="path">The path to the JSON output file.</param>
public void Write(string path)
{
File.WriteAllText(path, ToJson());
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\ConstantTest.cs | AsmResolver.DotNet.Tests
| ConstantTest | [] | ['System.IO', 'System.Linq', 'AsmResolver.DotNet.TestCases.Fields', 'Xunit'] | xUnit | net8.0 | public partial class ConstantTest
{
private Constant GetFieldConstant(string name)
{
var module = ModuleDefinition.FromFile(typeof(Constants).Assembly.Location, TestReaderParameters);
return GetFieldConstantInModule(module, name);
}
private static Constant GetFieldConstantInModule(ModuleDefinition module, string name)
{
var t = module.TopLevelTypes.First(t => t.Name == nameof(Constants));
return t.Fields.First(f => f.Name == name).Constant;
}
private Constant RebuildAndLookup(ModuleDefinition module, string name)
{
var stream = new MemoryStream();
module.Write(stream);
var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
return GetFieldConstantInModule(newModule, name);
}
[Theory]
[InlineData(nameof(Constants.Boolean), Constants.Boolean)]
[InlineData(nameof(Constants.Byte), Constants.Byte)]
[InlineData(nameof(Constants.UInt16), Constants.UInt16)]
[InlineData(nameof(Constants.UInt32), Constants.UInt32)]
[InlineData(nameof(Constants.UInt64), Constants.UInt64)]
[InlineData(nameof(Constants.SByte), Constants.SByte)]
[InlineData(nameof(Constants.Int16), Constants.Int16)]
[InlineData(nameof(Constants.Int32), Constants.Int32)]
[InlineData(nameof(Constants.Int64), Constants.Int64)]
[InlineData(nameof(Constants.Single), Constants.Single)]
[InlineData(nameof(Constants.Double), Constants.Double)]
[InlineData(nameof(Constants.Char), Constants.Char)]
[InlineData(nameof(Constants.String), Constants.String)]
public void ReadAndInterpretData(string name, object expected)
{
var constant = GetFieldConstant(name);
Assert.Equal(expected, constant.Value.InterpretData(constant.Type));
}
[Theory]
[InlineData(nameof(Constants.Boolean))]
[InlineData(nameof(Constants.Byte))]
[InlineData(nameof(Constants.UInt16))]
[InlineData(nameof(Constants.UInt32))]
[InlineData(nameof(Constants.UInt64))]
[InlineData(nameof(Constants.SByte))]
[InlineData(nameof(Constants.Int16))]
[InlineData(nameof(Constants.Int32))]
[InlineData(nameof(Constants.Int64))]
[InlineData(nameof(Constants.Single))]
[InlineData(nameof(Constants.Double))]
[InlineData(nameof(Constants.Char))]
[InlineData(nameof(Constants.String))]
public void PersistentConstants(string name)
{
var constant = GetFieldConstant(name);
var newConstant = RebuildAndLookup(constant.Parent.Module, name);
Assert.NotNull(newConstant);
Assert.Equal(constant.Value.Data, newConstant.Value.Data);
}
[Fact]
public void ReadInvalidConstantValueShouldNotThrow()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.ConstantZeroValueColumn, TestReaderParameters);
var constantValue = module
.TopLevelTypes.First(t => t.Name == "MyClass")
.Fields.First(f => f.Name == "MyIntegerConstant")
.Constant.Value;
Assert.Null(constantValue);
}
[Fact]
public void WriteNullConstantValueShouldNotThrow()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.ConstantZeroValueColumn, TestReaderParameters);
var stream = new MemoryStream();
module.Write(stream);
var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
var constantValue = newModule
.TopLevelTypes.First(t => t.Name == "MyClass")
.Fields.First(f => f.Name == "MyIntegerConstant")
.Constant.Value;
Assert.Null(constantValue);
}
} | 141 | 4,232 | using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a literal value that is assigned to a field, parameter or property.
/// </summary>
public class Constant : MetadataMember
{
private readonly LazyVariable<Constant, IHasConstant?> _parent;
private readonly LazyVariable<Constant, DataBlobSignature?> _value;
/// <summary>
/// Initializes the constant with a metadata token.
/// </summary>
/// <param name="token">The metadata token.</param>
protected Constant(MetadataToken token)
: base(token)
{
_parent = new LazyVariable<Constant, IHasConstant?>(x => x.GetParent());
_value = new LazyVariable<Constant, DataBlobSignature?>(x => x.GetValue());
}
/// <summary>
/// Creates a new constant for a member, with the provided constant type and raw literal value.
/// </summary>
/// <param name="type">The type of the constant.</param>
/// <param name="value">The raw literal value of the constant.</param>
public Constant(ElementType type, DataBlobSignature? value)
: this(new MetadataToken(TableIndex.Constant, 0))
{
Type = type;
Value = value;
}
/// <summary>
/// Gets the type of constant that is stored in the blob stream.
/// </summary>
/// <remarks>This field must always be a value-type.</remarks>
public ElementType Type
{
get;
set;
}
/// <summary>
/// Gets the member that is assigned a constant.
/// </summary>
public IHasConstant? Parent
{
get => _parent.GetValue(this);
internal set => _parent.SetValue(value);
}
/// <summary>
/// Gets or sets the serialized literal value.
/// </summary>
public DataBlobSignature? Value
{
get => _value.GetValue(this);
set => _value.SetValue(value);
}
/// <summary>
/// Obtains the owner of the constant.
/// </summary>
/// <returns>The parent.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Parent"/> property.
/// </remarks>
protected virtual IHasConstant? GetParent() => null;
/// <summary>
/// Obtains the literal value of the constant.
/// </summary>
/// <returns>The value.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Value"/> property.
/// </remarks>
protected virtual DataBlobSignature? GetValue() => null;
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(bool value)
{
return new Constant(ElementType.Boolean, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(char value)
{
return new Constant(ElementType.Char, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(byte value)
{
return new Constant(ElementType.U1, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(sbyte value)
{
return new Constant(ElementType.I1, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(ushort value)
{
return new Constant(ElementType.U2, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(short value)
{
return new Constant(ElementType.I2, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(uint value)
{
return new Constant(ElementType.U4, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(int value)
{
return new Constant(ElementType.I4, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(ulong value)
{
return new Constant(ElementType.U8, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(long value)
{
return new Constant(ElementType.I8, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(float value)
{
return new Constant(ElementType.R4, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(double value)
{
return new Constant(ElementType.R8, DataBlobSignature.FromValue(value));
}
/// <summary>
/// Create a <see cref="Constant"/> from a value
/// </summary>
/// <param name="value">The value to be assigned to the constant</param>
/// <returns>
/// A new <see cref="Constant"/> with the correct <see cref="Type"/> and <see cref="Value"/>
/// </returns>
public static Constant FromValue(string value)
{
return new Constant(ElementType.String, DataBlobSignature.FromValue(value));
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\CustomAttributeTest.cs | AsmResolver.DotNet.Tests
| CustomAttributeTest | ['private readonly SignatureComparer _comparer = new();'] | ['System', 'System.IO', 'System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.CustomAttributes', 'AsmResolver.DotNet.TestCases.Properties', 'AsmResolver.IO', 'AsmResolver.PE', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class CustomAttributeTest
{
private readonly SignatureComparer _comparer = new();
[Fact]
public void ReadConstructor()
{
var module = ModuleDefinition.FromFile(typeof(CustomAttributesTestClass).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(CustomAttributesTestClass));
Assert.All(type.CustomAttributes, a =>
Assert.Equal(nameof(TestCaseAttribute), a.Constructor!.DeclaringType!.Name));
}
[Fact]
public void PersistentConstructor()
{
var module = ModuleDefinition.FromFile(typeof(CustomAttributesTestClass).Assembly.Location, TestReaderParameters);
using var stream = new MemoryStream();
module.Write(stream);
module = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(CustomAttributesTestClass));
Assert.All(type.CustomAttributes, a =>
Assert.Equal(nameof(TestCaseAttribute), a.Constructor!.DeclaringType!.Name));
}
[Fact]
public void ReadParent()
{
int parentToken = typeof(CustomAttributesTestClass).MetadataToken;
string filePath = typeof(CustomAttributesTestClass).Assembly.Location;
var image = PEImage.FromFile(filePath);
var tablesStream = image.DotNetDirectory!.Metadata!.GetStream<TablesStream>();
var encoder = tablesStream.GetIndexEncoder(CodedIndex.HasCustomAttribute);
var attributeTable = tablesStream.GetTable<CustomAttributeRow>(TableIndex.CustomAttribute);
// Find token of custom attribute
var attributeToken = MetadataToken.Zero;
for (int i = 0; i < attributeTable.Count && attributeToken == 0; i++)
{
var row = attributeTable[i];
var token = encoder.DecodeIndex(row.Parent);
if (token == parentToken)
attributeToken = new MetadataToken(TableIndex.CustomAttribute, (uint) (i + 1));
}
// Resolve by token and verify parent (forcing parent to execute the lazy initialization ).
var module = ModuleDefinition.FromFile(filePath, TestReaderParameters);
var attribute = (CustomAttribute) module.LookupMember(attributeToken);
Assert.NotNull(attribute.Parent);
Assert.IsAssignableFrom<TypeDefinition>(attribute.Parent);
Assert.Equal(parentToken, attribute.Parent.MetadataToken);
}
private static CustomAttribute GetCustomAttributeTestCase(
string methodName,
bool rebuild = false,
bool access = false,
bool generic = false)
{
var module = ModuleDefinition.FromFile(typeof(CustomAttributesTestClass).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(CustomAttributesTestClass));
var method = type.Methods.First(m => m.Name == methodName);
string attributeName = nameof(TestCaseAttribute);
if (generic)
attributeName += "`1";
var attribute = method.CustomAttributes
.First(c => c.Constructor!.DeclaringType!.Name!.Value.StartsWith(attributeName));
if (access)
{
_ = attribute.Signature!.FixedArguments;
_ = attribute.Signature.NamedArguments;
}
if (rebuild)
attribute = RebuildAndLookup(attribute);
return attribute;
}
private static CustomAttribute RebuildAndLookup(CustomAttribute attribute)
{
var stream = new MemoryStream();
var method = (MethodDefinition) attribute.Parent!;
method.Module!.Write(stream);
var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
return newModule
.TopLevelTypes.First(t => t.FullName == method.DeclaringType!.FullName)
.Methods.First(f => f.Name == method.Name)
.CustomAttributes[0];
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedInt32Argument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(
nameof(CustomAttributesTestClass.FixedInt32Argument),
rebuild,
access);
Assert.Single(attribute.Signature!.FixedArguments);
Assert.Empty(attribute.Signature.NamedArguments);
var argument = attribute.Signature.FixedArguments[0];
Assert.Equal(1, argument.Element);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedStringArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedStringArgument),rebuild, access);
Assert.Single(attribute.Signature!.FixedArguments);
Assert.Empty(attribute.Signature.NamedArguments);
var argument = attribute.Signature.FixedArguments[0];
Assert.Equal("String fixed arg", Assert.IsAssignableFrom<Utf8String>(argument.Element));
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedEnumArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedEnumArgument),rebuild, access);
Assert.Single(attribute.Signature!.FixedArguments);
Assert.Empty(attribute.Signature.NamedArguments);
var argument = attribute.Signature.FixedArguments[0];
Assert.Equal((int) TestEnum.Value3, argument.Element);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedNullTypeArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedNullTypeArgument),rebuild, access);
var fixedArg = Assert.Single(attribute.Signature!.FixedArguments);
Assert.Null(fixedArg.Element);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedTypeArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedTypeArgument),rebuild, access);
Assert.Single(attribute.Signature!.FixedArguments);
Assert.Empty(attribute.Signature.NamedArguments);
var argument = attribute.Signature.FixedArguments[0];
Assert.Equal(
attribute.Constructor!.Module!.CorLibTypeFactory.String,
argument.Element as TypeSignature, _comparer);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedComplexTypeArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedComplexTypeArgument),rebuild, access);
Assert.Single(attribute.Signature!.FixedArguments);
Assert.Empty(attribute.Signature.NamedArguments);
var argument = attribute.Signature.FixedArguments[0];
var factory = attribute.Constructor!.Module!.CorLibTypeFactory;
var instance = factory.CorLibScope
.CreateTypeReference("System.Collections.Generic", "KeyValuePair`2")
.MakeGenericInstanceType(
false,
factory.String.MakeSzArrayType(),
factory.Int32.MakeSzArrayType()
);
Assert.Equal(instance, argument.Element as TypeSignature, _comparer);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void NamedInt32Argument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedInt32Argument),rebuild, access);
Assert.Empty(attribute.Signature!.FixedArguments);
Assert.Single(attribute.Signature.NamedArguments);
var argument = attribute.Signature.NamedArguments[0];
Assert.Equal(nameof(TestCaseAttribute.IntValue), argument.MemberName);
Assert.Equal(2, argument.Argument.Element);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void NamedStringArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedStringArgument),rebuild, access);
Assert.Empty(attribute.Signature!.FixedArguments);
Assert.Single(attribute.Signature.NamedArguments);
var argument = attribute.Signature.NamedArguments[0];
Assert.Equal(nameof(TestCaseAttribute.StringValue), argument.MemberName);
Assert.Equal("String named arg", Assert.IsAssignableFrom<Utf8String>(argument.Argument.Element));
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void NamedEnumArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedEnumArgument),rebuild, access);
Assert.Empty(attribute.Signature!.FixedArguments);
Assert.Single(attribute.Signature.NamedArguments);
var argument = attribute.Signature.NamedArguments[0];
Assert.Equal(nameof(TestCaseAttribute.EnumValue), argument.MemberName);
Assert.Equal((int) TestEnum.Value2, argument.Argument.Element);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void NamedTypeArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedTypeArgument),rebuild, access);
Assert.Empty(attribute.Signature!.FixedArguments);
Assert.Single(attribute.Signature.NamedArguments);
var expected = new TypeReference(
attribute.Constructor!.Module!.CorLibTypeFactory.CorLibScope,
"System", "Int32");
var argument = attribute.Signature.NamedArguments[0];
Assert.Equal(nameof(TestCaseAttribute.TypeValue), argument.MemberName);
Assert.Equal(expected, (ITypeDescriptor) argument.Argument.Element, _comparer);
}
[Fact]
public void IsCompilerGeneratedMember()
{
var module = ModuleDefinition.FromFile(typeof(SingleProperty).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleProperty));
var property = type.Properties.First();
var setMethod = property.SetMethod!;
Assert.True(setMethod.IsCompilerGenerated());
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void GenericTypeArgument(bool rebuild, bool access)
{
// https://github.com/Washi1337/AsmResolver/issues/92
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.GenericType),rebuild, access);
var argument = attribute.Signature!.FixedArguments[0];
var module = attribute.Constructor!.Module!;
var nestedClass = (TypeDefinition) module.LookupMember(typeof(TestGenericType<>).MetadataToken);
var expected = nestedClass.MakeGenericInstanceType(false, module.CorLibTypeFactory.Object);
var element = Assert.IsAssignableFrom<TypeSignature>(argument.Element);
Assert.Equal(expected, element, _comparer);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void ArrayGenericTypeArgument(bool rebuild, bool access)
{
// https://github.com/Washi1337/AsmResolver/issues/92
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.GenericTypeArray),rebuild, access);
var argument = attribute.Signature!.FixedArguments[0];
var module = attribute.Constructor!.Module!;
var nestedClass = (TypeDefinition) module.LookupMember(typeof(TestGenericType<>).MetadataToken);
var expected = nestedClass
.MakeGenericInstanceType(false, module.CorLibTypeFactory.Object)
.MakeSzArrayType();
var element = Assert.IsAssignableFrom<TypeSignature>(argument.Element);
Assert.Equal(expected, element, _comparer);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void IntPassedOnAsObject(bool rebuild, bool access)
{
// https://github.com/Washi1337/AsmResolver/issues/92
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.Int32PassedAsObject),rebuild, access);
var argument = attribute.Signature!.FixedArguments[0];
var element = Assert.IsAssignableFrom<BoxedArgument>(argument.Element);
Assert.Equal(123, element.Value);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void TypePassedOnAsObject(bool rebuild, bool access)
{
// https://github.com/Washi1337/AsmResolver/issues/92
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.TypePassedAsObject),rebuild, access);
var argument = attribute.Signature!.FixedArguments[0];
var module = attribute.Constructor!.Module!;
var element = Assert.IsAssignableFrom<BoxedArgument>(argument.Element);
Assert.Equal(module.CorLibTypeFactory.Int32, (ITypeDescriptor) element.Value, _comparer);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedInt32NullArray(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayNullArgument),rebuild, access);
var argument = attribute.Signature!.FixedArguments[0];
Assert.True(argument.IsNullArray);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedInt32EmptyArray(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayEmptyArgument),rebuild, access);
var argument = attribute.Signature!.FixedArguments[0];
Assert.False(argument.IsNullArray);
Assert.Empty(argument.Elements);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedInt32Array(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayArgument),rebuild, access);
var argument = attribute.Signature!.FixedArguments[0];
Assert.Equal(new[]
{
1, 2, 3, 4
}, argument.Elements.Cast<int>());
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedInt32ArrayNullAsObject(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayAsObjectNullArgument),rebuild, access);
var argument = attribute.Signature!.FixedArguments[0];
var boxedArgument = Assert.IsAssignableFrom<BoxedArgument>(argument.Element);
Assert.Null(boxedArgument.Value);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedInt32EmptyArrayAsObject(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayAsObjectEmptyArgument),rebuild, access);
var argument = attribute.Signature!.FixedArguments[0];
var boxedArgument = Assert.IsAssignableFrom<BoxedArgument>(argument.Element);
Assert.Equal(Array.Empty<object>(), boxedArgument.Value);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedInt32ArrayAsObject(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedInt32ArrayAsObjectArgument),rebuild, access);
var argument = attribute.Signature!.FixedArguments[0];
var boxedArgument = Assert.IsAssignableFrom<BoxedArgument>(argument.Element);
Assert.Equal(new[]
{
1, 2, 3, 4
}, boxedArgument.Value);
}
[Fact]
public void CreateNewWithFixedArgumentsViaConstructor()
{
var module = new ModuleDefinition("Module.exe");
var attribute = new CustomAttribute(module.CorLibTypeFactory.CorLibScope
.CreateTypeReference("System", "ObsoleteAttribute")
.CreateMemberReference(".ctor", MethodSignature.CreateInstance(
module.CorLibTypeFactory.Void,
module.CorLibTypeFactory.String)),
new CustomAttributeSignature(new CustomAttributeArgument(
module.CorLibTypeFactory.String,
"My Message")));
Assert.NotNull(attribute.Signature);
var argument = Assert.Single(attribute.Signature.FixedArguments);
Assert.Equal("My Message", argument.Element);
}
[Fact]
public void CreateNewWithFixedArgumentsViaProperty()
{
var module = new ModuleDefinition("Module.exe");
var attribute = new CustomAttribute(module.CorLibTypeFactory.CorLibScope
.CreateTypeReference("System", "ObsoleteAttribute")
.CreateMemberReference(".ctor", MethodSignature.CreateInstance(
module.CorLibTypeFactory.Void,
module.CorLibTypeFactory.String)));
attribute.Signature!.FixedArguments.Add(new CustomAttributeArgument(
module.CorLibTypeFactory.String,
"My Message"));
Assert.NotNull(attribute.Signature);
var argument = Assert.Single(attribute.Signature.FixedArguments);
Assert.Equal("My Message", argument.Element);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedGenericInt32Argument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedGenericInt32Argument),
rebuild, access, true);
var argument = attribute.Signature!.FixedArguments[0];
int value = Assert.IsAssignableFrom<int>(argument.Element);
Assert.Equal(1, value);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedGenericStringArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedGenericStringArgument),
rebuild, access, true);
var argument = attribute.Signature!.FixedArguments[0];
string value = Assert.IsAssignableFrom<Utf8String>(argument.Element);
Assert.Equal("Fixed string generic argument", value);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedGenericInt32ArrayArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedGenericInt32ArrayArgument),
rebuild, access, true);
var argument = attribute.Signature!.FixedArguments[0];
Assert.Equal(new int[] {1, 2, 3, 4}, argument.Elements.Cast<int>());
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedGenericInt32ArrayAsObjectArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedGenericInt32ArrayAsObjectArgument),
rebuild, access, true);
var argument = attribute.Signature!.FixedArguments[0];
var boxedArgument = Assert.IsAssignableFrom<BoxedArgument>(argument.Element);
Assert.Equal(new[]
{
1, 2, 3, 4
}, boxedArgument.Value);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedGenericTypeArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedGenericTypeArgument),
rebuild, access, true);
var argument = attribute.Signature!.FixedArguments[0];
var expected = attribute.Constructor!.Module!.CorLibTypeFactory.Int32;
var element = Assert.IsAssignableFrom<TypeSignature>(argument.Element);
Assert.Equal(expected, element, _comparer);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void FixedGenericTypeNullArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.FixedGenericTypeNullArgument),
rebuild, access, true);
var argument = attribute.Signature!.FixedArguments[0];
Assert.Null(argument.Element);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void NamedGenericInt32Argument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedGenericInt32Argument),
rebuild, access, true);
var argument = attribute.Signature!.NamedArguments[0];
Assert.Equal("Value", argument.MemberName);
int value = Assert.IsAssignableFrom<int>(argument.Argument.Element);
Assert.Equal(1, value);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void NamedGenericStringArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedGenericStringArgument),
rebuild, access, true);
var argument = attribute.Signature!.NamedArguments[0];
Assert.Equal("Value", argument.MemberName);
string value = Assert.IsAssignableFrom<Utf8String>(argument.Argument.Element);
Assert.Equal("Named string generic argument", value);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void NamedGenericInt32ArrayArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedGenericInt32ArrayArgument),
rebuild, access, true);
var argument = attribute.Signature!.NamedArguments[0];
Assert.Equal("Value", argument.MemberName);
Assert.Equal(new int[] {1,2,3,4}, argument.Argument.Elements.Cast<int>());
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void NamedGenericInt32ArrayAsObjectArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedGenericInt32ArrayAsObjectArgument),
rebuild, access, true);
var argument = attribute.Signature!.NamedArguments[0];
Assert.Equal("Value", argument.MemberName);
var boxedArgument = Assert.IsAssignableFrom<BoxedArgument>(argument.Argument.Element);
Assert.Equal(new[]
{
1, 2, 3, 4
}, boxedArgument.Value);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void NamedGenericTypeArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedGenericTypeArgument),
rebuild, access, true);
var argument = attribute.Signature!.NamedArguments[0];
var expected = attribute.Constructor!.Module!.CorLibTypeFactory.Int32;
var element = Assert.IsAssignableFrom<TypeSignature>(argument.Argument.Element);
Assert.Equal(expected, element, _comparer);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public void NamedGenericTypeNullArgument(bool rebuild, bool access)
{
var attribute = GetCustomAttributeTestCase(nameof(CustomAttributesTestClass.NamedGenericTypeNullArgument),
rebuild, access, true);
var argument = attribute.Signature!.NamedArguments[0];
Assert.Null(argument.Argument.Element);
}
[Fact]
public void TestSignatureCompatibility()
{
var module = new ModuleDefinition("Dummy");
var factory = module.CorLibTypeFactory;
var ctor = factory.CorLibScope
.CreateTypeReference("System", "CLSCompliantAttribute")
.CreateMemberReference(".ctor", MethodSignature.CreateInstance(factory.Void, factory.Boolean))
.ImportWith(module.DefaultImporter);
var attribute = new CustomAttribute(ctor);
// Empty signature is not compatible with a ctor that takes a boolean.
Assert.False(attribute.Signature!.IsCompatibleWith(attribute.Constructor!));
// If we add it, it should be compatible again.
attribute.Signature.FixedArguments.Add(new CustomAttributeArgument(factory.Boolean, true));
Assert.True(attribute.Signature!.IsCompatibleWith(attribute.Constructor!));
}
} | 383 | 28,981 | using AsmResolver.Collections;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a custom attribute that is associated to a member in a .NET module.
/// </summary>
public class CustomAttribute : MetadataMember, IOwnedCollectionElement<IHasCustomAttribute>
{
private readonly LazyVariable<CustomAttribute, IHasCustomAttribute?> _parent;
private readonly LazyVariable<CustomAttribute, ICustomAttributeType?> _constructor;
private readonly LazyVariable<CustomAttribute, CustomAttributeSignature?> _signature;
/// <summary>
/// Initializes an empty custom attribute.
/// </summary>
/// <param name="token">The token of the custom attribute.</param>
protected CustomAttribute(MetadataToken token)
: base(token)
{
_parent = new LazyVariable<CustomAttribute, IHasCustomAttribute?>(x => x.GetParent());
_constructor = new LazyVariable<CustomAttribute, ICustomAttributeType?>(x => x.GetConstructor());
_signature = new LazyVariable<CustomAttribute, CustomAttributeSignature?>(x => x.GetSignature());
}
/// <summary>
/// Creates a new custom attribute.
/// </summary>
/// <param name="constructor">The constructor of the attribute to call.</param>
public CustomAttribute(ICustomAttributeType? constructor)
: this(new MetadataToken(TableIndex.CustomAttribute, 0))
{
Constructor = constructor;
Signature = new CustomAttributeSignature();
}
/// <summary>
/// Creates a new custom attribute.
/// </summary>
/// <param name="constructor">The constructor of the attribute to call.</param>
/// <param name="signature">The signature containing the arguments to the constructor.</param>
public CustomAttribute(ICustomAttributeType? constructor, CustomAttributeSignature? signature)
: this(new MetadataToken(TableIndex.CustomAttribute, 0))
{
Constructor = constructor;
Signature = signature;
}
/// <summary>
/// Gets the member that this custom attribute is assigned to.
/// </summary>
public IHasCustomAttribute? Parent
{
get => _parent.GetValue(this);
private set => _parent.SetValue(value);
}
IHasCustomAttribute? IOwnedCollectionElement<IHasCustomAttribute>.Owner
{
get => Parent;
set => Parent = value;
}
/// <summary>
/// Gets or sets the constructor that is invoked upon initializing the attribute.
/// </summary>
public ICustomAttributeType? Constructor
{
get => _constructor.GetValue(this);
set => _constructor.SetValue(value);
}
/// <summary>
/// Gets or sets the signature containing the arguments passed onto the attribute's constructor.
/// </summary>
public CustomAttributeSignature? Signature
{
get => _signature.GetValue(this);
set => _signature.SetValue(value);
}
/// <summary>
/// Obtains the parent member of the attribute.
/// </summary>
/// <returns>The member</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Parent"/> property.
/// </remarks>
protected virtual IHasCustomAttribute? GetParent() => null;
/// <summary>
/// Obtains the constructor of the attribute.
/// </summary>
/// <returns>The constructor</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Constructor"/> property.
/// </remarks>
protected virtual ICustomAttributeType? GetConstructor() => null;
/// <summary>
/// Obtains the signature of the attribute.
/// </summary>
/// <returns>The signature</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Signature"/> property.
/// </remarks>
protected virtual CustomAttributeSignature? GetSignature() => null;
/// <inheritdoc />
public override string ToString() => Constructor?.FullName ?? "<<<NULL CONSTRUCTOR>>>";
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\DotNetRuntimeInfoTest.cs | AsmResolver.DotNet.Tests
| DotNetRuntimeInfoTest | [] | ['System', 'System.Reflection', 'AsmResolver.DotNet.Signatures', 'Xunit'] | xUnit | net8.0 | public class DotNetRuntimeInfoTest
{
[Theory]
[InlineData(".NETFramework,Version=v2.0", DotNetRuntimeInfo.NetFramework, 2, 0)]
[InlineData(".NETFramework,Version=v3.5", DotNetRuntimeInfo.NetFramework, 3, 5)]
[InlineData(".NETFramework,Version=v4.0", DotNetRuntimeInfo.NetFramework, 4, 0)]
[InlineData(".NETStandard,Version=v1.0", DotNetRuntimeInfo.NetStandard, 1, 0)]
[InlineData(".NETStandard,Version=v2.0", DotNetRuntimeInfo.NetStandard, 2, 0)]
[InlineData(".NETCoreApp,Version=v2.0", DotNetRuntimeInfo.NetCoreApp, 2, 0)]
[InlineData(".NETCoreApp,Version=v5.0", DotNetRuntimeInfo.NetCoreApp, 5, 0)]
public void Parse(string name, string expectedFramework, int major, int minor)
{
Assert.Equal(
new DotNetRuntimeInfo(expectedFramework, new Version(major, minor)),
DotNetRuntimeInfo.Parse(name)
);
}
[Theory]
[InlineData(".NETFramework,Version=v2.0", "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
[InlineData(".NETFramework,Version=v3.5", "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
[InlineData(".NETFramework,Version=v4.0", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
[InlineData(".NETStandard,Version=v1.0", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[InlineData(".NETStandard,Version=v2.0", "netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")]
[InlineData(".NETCoreApp,Version=v2.0", "System.Runtime, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[InlineData(".NETCoreApp,Version=v5.0", "System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public void DefaultCorLib(string name, string expectedCorLib)
{
Assert.Equal(
new ReflectionAssemblyDescriptor(new AssemblyName(expectedCorLib)),
(AssemblyDescriptor) DotNetRuntimeInfo.Parse(name).GetDefaultCorLib(),
SignatureComparer.Default
);
}
[Theory]
[InlineData("net20", DotNetRuntimeInfo.NetFramework, 2, 0)]
[InlineData("net35", DotNetRuntimeInfo.NetFramework, 3, 5)]
[InlineData("net40", DotNetRuntimeInfo.NetFramework, 4, 0)]
[InlineData("net47", DotNetRuntimeInfo.NetFramework, 4, 7)]
[InlineData("net472", DotNetRuntimeInfo.NetFramework, 4, 7)]
[InlineData("netstandard2.0", DotNetRuntimeInfo.NetStandard, 2, 0)]
[InlineData("netcoreapp2.1", DotNetRuntimeInfo.NetCoreApp, 2,1)]
[InlineData("net5.0", DotNetRuntimeInfo.NetCoreApp, 5, 0)]
[InlineData("net8.0", DotNetRuntimeInfo.NetCoreApp, 8, 0)]
public void ParseMoniker(string tfm, string expectedFramework, int major, int minor)
{
Assert.Equal(
new DotNetRuntimeInfo(expectedFramework, new Version(major, minor)),
DotNetRuntimeInfo.ParseMoniker(tfm)
);
}
} | 138 | 3,363 | using System;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
namespace AsmResolver.DotNet
{
/// <summary>
/// Provides information about a target runtime.
/// </summary>
public readonly struct DotNetRuntimeInfo : IEquatable<DotNetRuntimeInfo>
{
/// <summary>
/// The target framework name used by applications targeting .NET and .NET Core.
/// </summary>
public const string NetCoreApp = ".NETCoreApp";
/// <summary>
/// The target framework name used by libraries targeting .NET Standard.
/// </summary>
public const string NetStandard = ".NETStandard";
/// <summary>
/// The target framework name used by applications targeting legacy .NET Framework.
/// </summary>
public const string NetFramework = ".NETFramework";
private static readonly Regex FormatRegex = new(@"([a-zA-Z.]+)\s*,\s*Version=v(\d+\.\d+)");
private static readonly Regex NetFxMonikerRegex = new(@"net(\d)(\d)(\d?)");
private static readonly Regex NetCoreAppMonikerRegex = new(@"netcoreapp(\d)\.(\d)");
private static readonly Regex NetStandardMonikerRegex = new(@"netstandard(\d)\.(\d)");
private static readonly Regex NetMonikerRegex = new(@"net(\d+)\.(\d+)");
/// <summary>
/// Creates a new instance of the <see cref="DotNetRuntimeInfo"/> structure.
/// </summary>
/// <param name="name">The name of the runtime.</param>
/// <param name="version">The version of the runtime.</param>
public DotNetRuntimeInfo(string name, Version version)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Version = version ?? throw new ArgumentNullException(nameof(version));
}
/// <summary>
/// Gets the name of the runtime.
/// </summary>
public string Name
{
get;
}
/// <summary>
/// Gets the version of the runtime.
/// </summary>
public Version Version
{
get;
}
/// <summary>
/// Gets a value indicating whether the application targets the .NET or .NET Core runtime or not.
/// </summary>
public bool IsNetCoreApp => Name == NetCoreApp;
/// <summary>
/// Gets a value indicating whether the application targets the .NET Framework runtime or not.
/// </summary>
public bool IsNetFramework => Name == NetFramework;
/// <summary>
/// Gets a value indicating whether the application targets the .NET standard specification or not.
/// </summary>
public bool IsNetStandard => Name == NetStandard;
/// <summary>
/// Parses the framework name as provided in a <c>System.Runtime.Versioning.TargetFrameworkAttribute</c> attribute.
/// </summary>
/// <param name="frameworkName">The full runtime name.</param>
/// <returns>The parsed version info.</returns>
public static DotNetRuntimeInfo Parse(string frameworkName)
{
return TryParse(frameworkName, out var info) ? info : throw new FormatException();
}
/// <summary>
/// Attempts to parse the framework name as provided in a <c>System.Runtime.Versioning.TargetFrameworkAttribute</c> attribute.
/// </summary>
/// <param name="frameworkName">The full runtime name.</param>
/// <param name="info">The parsed version info.</param>
/// <returns><c>true</c> if the provided name was in the correct format, <c>false</c> otherwise.</returns>
public static bool TryParse(string frameworkName, out DotNetRuntimeInfo info)
{
var match = FormatRegex.Match(frameworkName);
if (!match.Success)
{
info = default;
return false;
}
string name = match.Groups[1].Value;
var version = new Version(match.Groups[2].Value);
info = new DotNetRuntimeInfo(name, version);
return true;
}
/// <summary>
/// Parses the target framework moniker as provided in a <c>.runtimeconfig.json</c> file.
/// </summary>
/// <param name="moniker">The moniker</param>
/// <returns>The parsed version info.</returns>
public static DotNetRuntimeInfo ParseMoniker(string moniker)
{
return TryParseMoniker(moniker, out var info) ? info : throw new FormatException();
}
/// <summary>
/// Attempts to parse the target framework moniker as provided in a <c>.runtimeconfig.json</c> file.
/// </summary>
/// <param name="moniker">The moniker</param>
/// <param name="info">The parsed version info.</param>
/// <returns><c>true</c> if the provided name was in the correct format, <c>false</c> otherwise.</returns>
public static bool TryParseMoniker(string moniker, out DotNetRuntimeInfo info)
{
info = default;
string runtime;
Match match;
if ((match = NetMonikerRegex.Match(moniker)).Success)
runtime = NetCoreApp;
else if ((match = NetCoreAppMonikerRegex.Match(moniker)).Success)
runtime = NetCoreApp;
else if ((match = NetStandardMonikerRegex.Match(moniker)).Success)
runtime = NetStandard;
else if ((match = NetFxMonikerRegex.Match(moniker)).Success)
runtime = NetFramework;
else
return false;
var version = new Version(int.Parse(match.Groups[1].Value), int.Parse(match.Groups[2].Value));
info = new DotNetRuntimeInfo(runtime, version);
return true;
}
/// <summary>
/// Obtains a reference to the default core lib reference of this runtime.
/// </summary>
/// <returns>The reference to the default core lib.</returns>
/// <exception cref="ArgumentException">The runtime information is invalid or unsupported.</exception>
public AssemblyReference GetDefaultCorLib() => KnownCorLibs.FromRuntimeInfo(this);
/// <inheritdoc />
public override string ToString() => $"{Name},Version=v{Version}";
/// <inheritdoc />
public bool Equals(DotNetRuntimeInfo other)
{
return Name == other.Name && Version.Equals(other.Version);
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is DotNetRuntimeInfo other && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
return (Name.GetHashCode() * 397) ^ Version.GetHashCode();
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\EventDefinitionTest.cs | AsmResolver.DotNet.Tests
| EventDefinitionTest | [] | ['System.Linq', 'AsmResolver.DotNet.TestCases.Events', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class EventDefinitionTest
{
[Fact]
public void ReadName()
{
var module = ModuleDefinition.FromFile(typeof(SingleEvent).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleEvent));
var @event = type.Events.FirstOrDefault(m => m.Name == nameof(SingleEvent.SimpleEvent));
Assert.NotNull(@event);
}
[Theory]
[InlineData(nameof(MultipleEvents.Event1), "System.EventHandler")]
[InlineData(nameof(MultipleEvents.Event2), "System.AssemblyLoadEventHandler")]
[InlineData(nameof(MultipleEvents.Event3), "System.ResolveEventHandler")]
public void ReadReturnType(string eventName, string expectedReturnType)
{
var module = ModuleDefinition.FromFile(typeof(MultipleEvents).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleEvents));
var @event = type.Events.First(m => m.Name == eventName);
Assert.Equal(expectedReturnType, @event.EventType.FullName);
}
[Fact]
public void ReadDeclaringType()
{
var module = ModuleDefinition.FromFile(typeof(SingleEvent).Assembly.Location, TestReaderParameters);
var @event = (EventDefinition) module.LookupMember(
typeof(SingleEvent).GetEvent(nameof(SingleEvent.SimpleEvent)).MetadataToken);
Assert.NotNull(@event.DeclaringType);
Assert.Equal(nameof(SingleEvent), @event.DeclaringType.Name);
}
[Fact]
public void ReadEventSemantics()
{
var module = ModuleDefinition.FromFile(typeof(SingleEvent).Assembly.Location, TestReaderParameters);
var @event = (EventDefinition) module.LookupMember(
typeof(SingleEvent).GetEvent(nameof(SingleEvent.SimpleEvent)).MetadataToken);
Assert.Equal(2, @event.Semantics.Count);
Assert.NotNull(@event.AddMethod);
Assert.NotNull(@event.RemoveMethod);
}
[Fact]
public void ReadFullName()
{
var module = ModuleDefinition.FromFile(typeof(SingleEvent).Assembly.Location, TestReaderParameters);
var @event = (EventDefinition) module.LookupMember(
typeof(SingleEvent).GetEvent(nameof(SingleEvent.SimpleEvent)).MetadataToken);
Assert.Equal("System.EventHandler AsmResolver.DotNet.TestCases.Events.SingleEvent::SimpleEvent", @event.FullName);
}
} | 169 | 2,819 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.DotNet.Collections;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a single event in a type definition of a .NET module.
/// </summary>
public class EventDefinition :
MetadataMember,
IHasSemantics,
IHasCustomAttribute,
IOwnedCollectionElement<TypeDefinition>
{
private readonly LazyVariable<EventDefinition, Utf8String?> _name;
private readonly LazyVariable<EventDefinition, TypeDefinition?> _declaringType;
private readonly LazyVariable<EventDefinition, ITypeDefOrRef?> _eventType;
private IList<MethodSemantics>? _semantics;
private IList<CustomAttribute>? _customAttributes;
/// <summary>
/// Initializes a new property definition.
/// </summary>
/// <param name="token">The token of the property.</param>
protected EventDefinition(MetadataToken token)
: base(token)
{
_name = new LazyVariable<EventDefinition, Utf8String?>(x => x.GetName());
_eventType = new LazyVariable<EventDefinition, ITypeDefOrRef?>(x => x.GetEventType());
_declaringType = new LazyVariable<EventDefinition, TypeDefinition?>(x => x.GetDeclaringType());
}
/// <summary>
/// Creates a new property definition.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="attributes">The attributes.</param>
/// <param name="eventType">The delegate type of the event.</param>
public EventDefinition(Utf8String? name, EventAttributes attributes, ITypeDefOrRef? eventType)
: this(new MetadataToken(TableIndex.Event,0))
{
Name = name;
Attributes = attributes;
EventType = eventType;
}
/// <summary>
/// Gets or sets the attributes associated to the field.
/// </summary>
public EventAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating the event uses a special name.
/// </summary>
public bool IsSpecialName
{
get => (Attributes & EventAttributes.SpecialName) != 0;
set => Attributes = (Attributes & ~EventAttributes.SpecialName)
| (value ? EventAttributes.SpecialName : 0);
}
/// <summary>
/// Gets or sets a value indicating the event uses a special name used by the runtime.
/// </summary>
public bool IsRuntimeSpecialName
{
get => (Attributes & EventAttributes.RtSpecialName) != 0;
set => Attributes = (Attributes & ~EventAttributes.RtSpecialName)
| (value ? EventAttributes.RtSpecialName : 0);
}
/// <summary>
/// Gets or sets the name of the event.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the event table.
/// </remarks>
public Utf8String? Name
{
get => _name.GetValue(this);
set => _name.SetValue(value);
}
string? INameProvider.Name => Name;
/// <inheritdoc />
public string FullName => MemberNameGenerator.GetEventFullName(this);
/// <summary>
/// Gets or sets the delegate type of the event.
/// </summary>
public ITypeDefOrRef? EventType
{
get => _eventType.GetValue(this);
set => _eventType.SetValue(value);
}
/// <inheritdoc />
public ModuleDefinition? Module => DeclaringType?.Module;
/// <summary>
/// Gets the type that defines the property.
/// </summary>
public TypeDefinition? DeclaringType
{
get => _declaringType.GetValue(this);
private set => _declaringType.SetValue(value);
}
ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType;
TypeDefinition? IOwnedCollectionElement<TypeDefinition>.Owner
{
get => DeclaringType;
set => DeclaringType = value;
}
/// <inheritdoc />
public IList<MethodSemantics> Semantics
{
get
{
if (_semantics is null)
Interlocked.CompareExchange(ref _semantics, GetSemantics(), null);
return _semantics;
}
}
/// <summary>
/// Gets the method definition representing the first add accessor of this event definition.
/// </summary>
public MethodDefinition? AddMethod
{
get => Semantics.FirstOrDefault(s => s.Attributes == MethodSemanticsAttributes.AddOn)?.Method;
set => SetSemanticMethods(value, RemoveMethod, FireMethod);
}
/// <summary>
/// Gets the method definition representing the first remove accessor of this event definition.
/// </summary>
public MethodDefinition? RemoveMethod
{
get => Semantics.FirstOrDefault(s => s.Attributes == MethodSemanticsAttributes.RemoveOn)?.Method;
set => SetSemanticMethods(AddMethod, value, FireMethod);
}
/// <summary>
/// Gets the method definition representing the first fire accessor of this event definition.
/// </summary>
public MethodDefinition? FireMethod
{
get => Semantics.FirstOrDefault(s => s.Attributes == MethodSemanticsAttributes.Fire)?.Method;
set => SetSemanticMethods(AddMethod, RemoveMethod, value);
}
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <summary>
/// Clear <see cref="Semantics"/> and apply these methods to the event definition.
/// </summary>
/// <param name="addMethod">The method definition representing the add accessor of this event definition.</param>
/// <param name="removeMethod">The method definition representing the remove accessor of this event definition.</param>
/// <param name="fireMethod">The method definition representing the fire accessor of this event definition.</param>
public void SetSemanticMethods(MethodDefinition? addMethod, MethodDefinition? removeMethod, MethodDefinition? fireMethod)
{
Semantics.Clear();
if (addMethod is not null)
Semantics.Add(new MethodSemantics(addMethod, MethodSemanticsAttributes.AddOn));
if (removeMethod is not null)
Semantics.Add(new MethodSemantics(removeMethod, MethodSemanticsAttributes.RemoveOn));
if (fireMethod is not null)
Semantics.Add(new MethodSemantics(fireMethod, MethodSemanticsAttributes.Fire));
}
/// <inheritdoc />
public bool IsAccessibleFromType(TypeDefinition type) =>
Semantics.Any(s => s.Method?.IsAccessibleFromType(type) ?? false);
IMemberDefinition IMemberDescriptor.Resolve() => this;
/// <inheritdoc />
public bool IsImportedInModule(ModuleDefinition module)
{
return Module == module
&& (EventType?.IsImportedInModule(module) ?? false);
}
/// <inheritdoc />
IImportable IImportable.ImportWith(ReferenceImporter importer) => throw new NotSupportedException();
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
/// <summary>
/// Obtains the name of the event definition.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual Utf8String? GetName() => null;
/// <summary>
/// Obtains the event type of the event definition.
/// </summary>
/// <returns>The event type.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="EventType"/> property.
/// </remarks>
protected virtual ITypeDefOrRef? GetEventType() => null;
/// <summary>
/// Obtains the declaring type of the event definition.
/// </summary>
/// <returns>The declaring type.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="DeclaringType"/> property.
/// </remarks>
protected virtual TypeDefinition? GetDeclaringType() => null;
/// <summary>
/// Obtains the methods associated to this event definition.
/// </summary>
/// <returns>The method semantic objects.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Semantics"/> property.
/// </remarks>
protected virtual IList<MethodSemantics> GetSemantics() => new MethodSemanticsCollection(this);
/// <inheritdoc />
public override string ToString() => FullName;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\FieldDefinitionTest.cs | AsmResolver.DotNet.Tests
| FieldDefinitionTest | [] | ['System', 'System.IO', 'System.Linq', 'AsmResolver.DotNet.Serialized', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Fields', 'AsmResolver.DotNet.TestCases.Types.Structs', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class FieldDefinitionTest
{
private FieldDefinition RebuildAndLookup(FieldDefinition field)
{
var stream = new MemoryStream();
field.Module.Write(stream);
var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
return newModule
.TopLevelTypes.First(t => t.FullName == field.DeclaringType.FullName)
.Fields.First(f => f.Name == field.Name);
}
[Fact]
public void ReadName()
{
var module = ModuleDefinition.FromFile(typeof(SingleField).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleField));
Assert.Equal(nameof(SingleField.IntField), type.Fields[0].Name);
}
[Fact]
public void PersistentName()
{
const string newName = "NewName";
var module = ModuleDefinition.FromFile(typeof(SingleField).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleField));
var field = type.Fields[0];
type.Fields[0].Name = newName;
var newField = RebuildAndLookup(field);
Assert.Equal(newName, newField.Name);
}
[Fact]
public void ReadDeclaringType()
{
var module = ModuleDefinition.FromFile(typeof(SingleField).Assembly.Location, TestReaderParameters);
var field = (FieldDefinition) module.LookupMember(
typeof(SingleField).GetField(nameof(SingleField.IntField)).MetadataToken);
Assert.NotNull(field.DeclaringType);
Assert.Equal(nameof(SingleField), field.DeclaringType.Name);
}
[Fact]
public void ReadFieldSignature()
{
var module = ModuleDefinition.FromFile(typeof(SingleField).Assembly.Location, TestReaderParameters);
var field = (FieldDefinition) module.LookupMember(
typeof(SingleField).GetField(nameof(SingleField.IntField)).MetadataToken);
Assert.NotNull(field.Signature);
Assert.True(field.Signature.FieldType.IsTypeOf("System", "Int32"), "Field type should be System.Int32");
}
[Fact]
public void PersistentFieldSignature()
{
var module = ModuleDefinition.FromFile(typeof(SingleField).Assembly.Location, TestReaderParameters);
var field = (FieldDefinition) module.LookupMember(
typeof(SingleField).GetField(nameof(SingleField.IntField)).MetadataToken);
field.Signature = new FieldSignature(module.CorLibTypeFactory.Byte);
var newField = RebuildAndLookup(field);
Assert.True(newField.Signature.FieldType.IsTypeOf("System", "Byte"), "Field type should be System.Byte");
}
[Fact]
public void ReadFullName()
{
var module = ModuleDefinition.FromFile(typeof(SingleField).Assembly.Location, TestReaderParameters);
var field = (FieldDefinition) module.LookupMember(
typeof(SingleField).GetField(nameof(SingleField.IntField)).MetadataToken);
Assert.Equal("System.Int32 AsmResolver.DotNet.TestCases.Fields.SingleField::IntField", field.FullName);
}
[Fact]
public void ReadFieldRva()
{
var module = ModuleDefinition.FromFile(typeof(InitialValues).Assembly.Location, TestReaderParameters);
var field = module
.TopLevelTypes.First(t => t.Name == nameof(InitialValues))
.Fields.First(f => f.Name == nameof(InitialValues.ByteArray));
var initializer = field.FindInitializerField();
Assert.NotNull(initializer.FieldRva);
Assert.IsAssignableFrom<IReadableSegment>(initializer.FieldRva);
Assert.Equal(InitialValues.ByteArray, ((IReadableSegment) initializer.FieldRva).ToArray());
}
[Fact]
public void PersistentFieldRva()
{
var module = ModuleDefinition.FromFile(typeof(InitialValues).Assembly.Location, TestReaderParameters);
var field = module
.TopLevelTypes.First(t => t.Name == nameof(InitialValues))
.Fields.First(f => f.Name == nameof(InitialValues.ByteArray));
var initializer = field.FindInitializerField();
var data = new byte[]
{
1, 2, 3, 4
};
initializer.FieldRva = new DataSegment(data);
initializer.Signature.FieldType.Resolve().ClassLayout.ClassSize = (uint) data.Length;
var newInitializer = RebuildAndLookup(initializer);
Assert.NotNull(newInitializer.FieldRva);
Assert.IsAssignableFrom<IReadableSegment>(newInitializer.FieldRva);
Assert.Equal(data, ((IReadableSegment) newInitializer.FieldRva).ToArray());
}
[Fact]
public void ReadInvalidFieldRva()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.FieldRvaTest, TestReaderParameters);
Assert.Throws<NotSupportedException>(() =>
module.GetModuleType()!.Fields.First(f => f.Name == "InvalidFieldRva").FieldRva);
module = ModuleDefinition.FromBytes(Properties.Resources.FieldRvaTest,
new ModuleReaderParameters(EmptyErrorListener.Instance));
Assert.Null(module.GetModuleType()!.Fields.First(f => f.Name == "InvalidFieldRva").FieldRva);
}
[Fact]
public void ReadVirtualFieldRva()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_VirtualSegment, TestReaderParameters);
var data = module.GetModuleType()!.Fields.First(f => f.Name == "__dummy__").FieldRva;
var readableData = Assert.IsAssignableFrom<IReadableSegment>(data);
Assert.Equal(new byte[4], readableData.ToArray());
Assert.Equal(new byte[4], data.WriteIntoArray());
}
[Fact]
public void ReadNativeIntFieldRvaX86()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_IntPtrFieldRva_X86, TestReaderParameters);
var data = module.GetModuleType()!.Fields.First(f => f.Name == "__dummy__").FieldRva;
var readableData = Assert.IsAssignableFrom<IReadableSegment>(data);
Assert.Equal(new byte[] {0xEF, 0xCD, 0xAB, 0x89}, readableData.ToArray());
}
[Fact]
public void ReadNativeIntFieldRvaX64()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_IntPtrFieldRva_X64, TestReaderParameters);
var data = module.GetModuleType()!.Fields.First(f => f.Name == "__dummy__").FieldRva;
var readableData = Assert.IsAssignableFrom<IReadableSegment>(data);
Assert.Equal(new byte[] {0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01}, readableData.ToArray());
}
[Theory]
[InlineData(nameof(ExplicitOffsetsStruct.IntField), 0)]
[InlineData(nameof(ExplicitOffsetsStruct.ByteField), 10)]
[InlineData(nameof(ExplicitOffsetsStruct.BoolField), 100)]
public void ReadFieldOffset(string name, int offset)
{
var module = ModuleDefinition.FromFile(typeof(ExplicitOffsetsStruct).Assembly.Location, TestReaderParameters);
var field = module
.TopLevelTypes.First(t => t.Name == nameof(ExplicitOffsetsStruct))
.Fields.First(f => f.Name == name);
Assert.Equal(offset, field.FieldOffset);
}
[Theory]
[InlineData(nameof(ExplicitOffsetsStruct.IntField), 0)]
[InlineData(nameof(ExplicitOffsetsStruct.ByteField), 10)]
[InlineData(nameof(ExplicitOffsetsStruct.BoolField), 100)]
public void PersistentFieldOffset(string name, int offset)
{
var module = ModuleDefinition.FromFile(typeof(ExplicitOffsetsStruct).Assembly.Location, TestReaderParameters);
var field = module
.TopLevelTypes.First(t => t.Name == nameof(ExplicitOffsetsStruct))
.Fields.First(f => f.Name == name);
var newField = RebuildAndLookup(field);
Assert.Equal(offset, newField.FieldOffset);
}
[Fact]
public void AddSameFieldTwiceToTypeShouldThrow()
{
var module = new ModuleDefinition("SomeModule");
var field = new FieldDefinition("SomeField", FieldAttributes.Public, module.CorLibTypeFactory.Int32);
var type = new TypeDefinition("SomeNamespace", "SomeType", TypeAttributes.Public);
type.Fields.Add(field);
Assert.Throws<ArgumentException>(() => type.Fields.Add(field));
}
[Fact]
public void AddSameFieldToDifferentTypesShouldThrow()
{
var module = new ModuleDefinition("SomeModule");
var field = new FieldDefinition("SomeField", FieldAttributes.Public, module.CorLibTypeFactory.Int32);
var type1 = new TypeDefinition("SomeNamespace", "SomeType1", TypeAttributes.Public);
var type2 = new TypeDefinition("SomeNamespace", "SomeType2", TypeAttributes.Public);
type1.Fields.Add(field);
Assert.Throws<ArgumentException>(() => type2.Fields.Add(field));
}
} | 363 | 10,057 | using System;
using System.Collections.Generic;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a single field in a type definition of a .NET module.
/// </summary>
public class FieldDefinition :
MetadataMember,
IMemberDefinition,
IFieldDescriptor,
IHasCustomAttribute,
IHasConstant,
IMemberForwarded,
IHasFieldMarshal,
IOwnedCollectionElement<TypeDefinition>
{
private readonly LazyVariable<FieldDefinition, Utf8String?> _name;
private readonly LazyVariable<FieldDefinition, FieldSignature?> _signature;
private readonly LazyVariable<FieldDefinition, TypeDefinition?> _declaringType;
private readonly LazyVariable<FieldDefinition, Constant?> _constant;
private readonly LazyVariable<FieldDefinition, MarshalDescriptor?> _marshalDescriptor;
private readonly LazyVariable<FieldDefinition, ImplementationMap?> _implementationMap;
private readonly LazyVariable<FieldDefinition, ISegment?> _fieldRva;
private readonly LazyVariable<FieldDefinition, int?> _fieldOffset;
private IList<CustomAttribute>? _customAttributes;
/// <summary>
/// Initializes a new field definition.
/// </summary>
/// <param name="token">The token of the field.</param>
protected FieldDefinition(MetadataToken token)
: base(token)
{
_name = new LazyVariable<FieldDefinition, Utf8String?>(x => x.GetName());
_signature = new LazyVariable<FieldDefinition, FieldSignature?>(x => x.GetSignature());
_declaringType = new LazyVariable<FieldDefinition, TypeDefinition?>(x => x.GetDeclaringType());
_constant = new LazyVariable<FieldDefinition, Constant?>(x => x.GetConstant());
_marshalDescriptor = new LazyVariable<FieldDefinition, MarshalDescriptor?>(x => x.GetMarshalDescriptor());
_implementationMap = new LazyVariable<FieldDefinition, ImplementationMap?>(x => x.GetImplementationMap());
_fieldRva = new LazyVariable<FieldDefinition, ISegment?>(x => x.GetFieldRva());
_fieldOffset = new LazyVariable<FieldDefinition, int?>(x => x.GetFieldOffset());
}
/// <summary>
/// Creates a new field definition.
/// </summary>
/// <param name="name">The name of the field.</param>
/// <param name="attributes">The attributes.</param>
/// <param name="signature">The signature of the field.</param>
public FieldDefinition(Utf8String? name, FieldAttributes attributes, FieldSignature? signature)
: this(new MetadataToken(TableIndex.Field, 0))
{
Name = name;
Attributes = attributes;
Signature = signature;
}
/// <summary>
/// Creates a new field definition.
/// </summary>
/// <param name="name">The name of the field.</param>
/// <param name="attributes">The attributes.</param>
/// <param name="fieldType">The type of values the field contains.</param>
public FieldDefinition(Utf8String name, FieldAttributes attributes, TypeSignature? fieldType)
: this(new MetadataToken(TableIndex.Field, 0))
{
Name = name;
Attributes = attributes;
Signature = fieldType is not null
? new FieldSignature(fieldType)
: null;
}
/// <summary>
/// Gets or sets the name of the field.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the field table.
/// </remarks>
public Utf8String? Name
{
get => _name.GetValue(this);
set => _name.SetValue(value);
}
string? INameProvider.Name => Name;
/// <summary>
/// Gets or sets the signature of the field. This includes the field type.
/// </summary>
public FieldSignature? Signature
{
get => _signature.GetValue(this);
set => _signature.SetValue(value);
}
/// <inheritdoc />
public string FullName => MemberNameGenerator.GetFieldFullName(this);
/// <summary>
/// Gets or sets the attributes associated to the field.
/// </summary>
public FieldAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the field is in a private scope.
/// </summary>
public bool IsPrivateScope
{
get => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.PrivateScope;
set => Attributes = value ? Attributes & ~FieldAttributes.FieldAccessMask : Attributes;
}
/// <summary>
/// Gets or sets a value indicating whether the field is marked private and can only be accessed by
/// members within the same enclosing type.
/// </summary>
public bool IsPrivate
{
get => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private;
set => Attributes = (Attributes & ~FieldAttributes.FieldAccessMask)
| (value ? FieldAttributes.Private : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field is marked family and assembly, and can only be accessed by
/// members within the same enclosing type and any derived type, within the same assembly.
/// </summary>
public bool IsFamilyAndAssembly
{
get => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamilyAndAssembly;
set => Attributes = (Attributes & ~FieldAttributes.FieldAccessMask)
| (value ? FieldAttributes.FamilyAndAssembly : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field is marked private and can only be accessed by
/// members within the same assembly.
/// </summary>
public bool IsAssembly
{
get => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly;
set => Attributes = (Attributes & ~FieldAttributes.FieldAccessMask)
| (value ? FieldAttributes.Assembly : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field is marked private and can only be accessed by
/// members within the same enclosing type, as well as any derived type.
/// </summary>
public bool IsFamily
{
get => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family;
set => Attributes = (Attributes & ~FieldAttributes.FieldAccessMask)
| (value ? FieldAttributes.Family : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field is marked family or assembly, and can only be accessed by
/// members within the same enclosing type and any derived type, or within the same assembly.
/// </summary>
public bool IsFamilyOrAssembly
{
get => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamilyOrAssembly;
set => Attributes = (Attributes & ~FieldAttributes.FieldAccessMask)
| (value ? FieldAttributes.FamilyOrAssembly : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field is marked public, and can be accessed by
/// any member having access to the enclosing type.
/// </summary>
public bool IsPublic
{
get => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public;
set => Attributes = (Attributes & ~FieldAttributes.FieldAccessMask)
| (value ? FieldAttributes.Public : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field requires an object instance to access it.
/// </summary>
/// <remarks>
/// This property does not reflect the value of <see cref="CallingConventionSignature.HasThis"/>, nor will it
/// change the value of <see cref="CallingConventionSignature.HasThis"/> if this property is changed. For a
/// valid .NET image, these values should match, however.
/// </remarks>
public bool IsStatic
{
get => (Attributes & FieldAttributes.Static) != 0;
set => Attributes = (Attributes & ~FieldAttributes.Static)
| (value ? FieldAttributes.Static : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field is marked init-only, and can only be assigned a value by
/// a constructor of the enclosing type.
/// </summary>
public bool IsInitOnly
{
get => (Attributes & FieldAttributes.InitOnly) != 0;
set => Attributes = (Attributes & ~FieldAttributes.InitOnly)
| (value ? FieldAttributes.InitOnly : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field is marked as a literal, and its value is decided upon
/// compile time.
/// </summary>
public bool IsLiteral
{
get => (Attributes & FieldAttributes.Literal) != 0;
set => Attributes = (Attributes & ~FieldAttributes.Literal)
| (value ? FieldAttributes.Literal : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field is marked as not serialized, indicating the field does
/// not have to be serialized when the enclosing type is remoted.
/// </summary>
public bool IsNotSerialized
{
get => (Attributes & FieldAttributes.NotSerialized) != 0;
set => Attributes = (Attributes & ~FieldAttributes.NotSerialized)
| (value ? FieldAttributes.NotSerialized : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field uses a special name.
/// </summary>
public bool IsSpecialName
{
get => (Attributes & FieldAttributes.SpecialName) != 0;
set => Attributes = (Attributes & ~FieldAttributes.SpecialName)
| (value ? FieldAttributes.SpecialName : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field's implementation is forwarded through Platform Invoke.
/// </summary>
public bool IsPInvokeImpl
{
get => (Attributes & FieldAttributes.PInvokeImpl) != 0;
set => Attributes = (Attributes & ~FieldAttributes.PInvokeImpl)
| (value ? FieldAttributes.PInvokeImpl : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field uses a name that is used by the runtime.
/// </summary>
public bool IsRuntimeSpecialName
{
get => (Attributes & FieldAttributes.RuntimeSpecialName) != 0;
set => Attributes = (Attributes & ~FieldAttributes.RuntimeSpecialName)
| (value ? FieldAttributes.RuntimeSpecialName : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field has marshalling information associated to it.
/// </summary>
public bool HasFieldMarshal
{
get => (Attributes & FieldAttributes.HasFieldMarshal) != 0;
set => Attributes = (Attributes & ~FieldAttributes.HasFieldMarshal)
| (value ? FieldAttributes.HasFieldMarshal : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field has a default value associated to it.
/// </summary>
public bool HasDefault
{
get => (Attributes & FieldAttributes.HasDefault) != 0;
set => Attributes = (Attributes & ~FieldAttributes.HasDefault)
| (value ? FieldAttributes.HasDefault : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the field has an initial value associated to it that is referenced
/// by a relative virtual address.
/// </summary>
public bool HasFieldRva
{
get => (Attributes & FieldAttributes.HasFieldRva) != 0;
set => Attributes = (Attributes & ~FieldAttributes.HasFieldRva)
| (value ? FieldAttributes.HasFieldRva : 0);
}
/// <inheritdoc />
public ModuleDefinition? Module => DeclaringType?.Module;
/// <summary>
/// Gets the type that defines the field.
/// </summary>
public TypeDefinition? DeclaringType
{
get => _declaringType.GetValue(this);
private set => _declaringType.SetValue(value);
}
TypeDefinition? IOwnedCollectionElement<TypeDefinition>.Owner
{
get => DeclaringType;
set => DeclaringType = value;
}
ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType;
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <inheritdoc />
public Constant? Constant
{
get => _constant.GetValue(this);
set => _constant.SetValue(value);
}
/// <inheritdoc />
public MarshalDescriptor? MarshalDescriptor
{
get => _marshalDescriptor.GetValue(this);
set => _marshalDescriptor.SetValue(value);
}
/// <inheritdoc />
public ImplementationMap? ImplementationMap
{
get => _implementationMap.GetValue(this);
set
{
if (value?.MemberForwarded is not null)
throw new ArgumentException("Cannot add an implementation map that was already added to another member.");
if (_implementationMap.GetValue(this) is { } map)
map.MemberForwarded = null;
_implementationMap.SetValue(value);
if (value is not null)
value.MemberForwarded = this;
}
}
/// <summary>
/// Gets or sets a segment containing the initial value of the field.
/// </summary>
/// <remarks>
/// Updating this property does not automatically update the <see cref="HasFieldRva"/> property, nor does the
/// value of <see cref="HasFieldRva"/> reflect whether the field has initialization data or not. Well-formed
/// .NET binaries should always set the <see cref="HasFieldRva"/> flag to <c>true</c> if this property is non-null.
/// </remarks>
public ISegment? FieldRva
{
get => _fieldRva.GetValue(this);
set => _fieldRva.SetValue(value);
}
/// <summary>
/// Gets or sets the explicit offset of the field, relative to the starting address of the object (if available).
/// </summary>
public int? FieldOffset
{
get => _fieldOffset.GetValue(this);
set => _fieldOffset.SetValue(value);
}
FieldDefinition IFieldDescriptor.Resolve() => this;
/// <inheritdoc />
public bool IsImportedInModule(ModuleDefinition module)
{
return Module == module
&& (Signature?.IsImportedInModule(module) ?? false);
}
/// <summary>
/// Imports the field using the provided reference importer object.
/// </summary>
/// <param name="importer">The reference importer to use.</param>
/// <returns>The imported field.</returns>
public IFieldDescriptor ImportWith(ReferenceImporter importer) => importer.ImportField(this);
/// <inheritdoc />
IImportable IImportable.ImportWith(ReferenceImporter importer) => ImportWith(importer);
IMemberDefinition IMemberDescriptor.Resolve() => this;
/// <inheritdoc />
public bool IsAccessibleFromType(TypeDefinition type)
{
if (DeclaringType is not { } declaringType || !declaringType.IsAccessibleFromType(type))
return false;
var comparer = new SignatureComparer();
bool isInSameAssembly = comparer.Equals(declaringType.Module, type.Module);
return IsPublic
|| isInSameAssembly && IsAssembly
|| comparer.Equals(DeclaringType, type);
// TODO: check if in the same family of declaring types.
}
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
/// <summary>
/// Obtains the name of the field definition.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual Utf8String? GetName() => null;
/// <summary>
/// Obtains the signature of the field definition.
/// </summary>
/// <returns>The signature.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Signature"/> property.
/// </remarks>
protected virtual FieldSignature? GetSignature() => null;
/// <summary>
/// Obtains the declaring type of the field definition.
/// </summary>
/// <returns>The declaring type.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="DeclaringType"/> property.
/// </remarks>
protected virtual TypeDefinition? GetDeclaringType() => null;
/// <summary>
/// Obtains the constant value assigned to the field definition.
/// </summary>
/// <returns>The constant.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Constant"/> property.
/// </remarks>
protected virtual Constant? GetConstant() => null;
/// <summary>
/// Obtains the marshal descriptor value assigned to the field definition.
/// </summary>
/// <returns>The marshal descriptor.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="MarshalDescriptor"/> property.
/// </remarks>
protected virtual MarshalDescriptor? GetMarshalDescriptor() => null;
/// <summary>
/// Obtains the platform invoke information assigned to the field.
/// </summary>
/// <returns>The mapping.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="ImplementationMap"/> property.
/// </remarks>
protected virtual ImplementationMap? GetImplementationMap() => null;
/// <summary>
/// Obtains the initial value of the field.
/// </summary>
/// <returns>The initial value.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="FieldRva"/> property.
/// </remarks>
protected virtual ISegment? GetFieldRva() => null;
/// <summary>
/// Obtains the offset of the field as defined in the field layout.
/// </summary>
/// <returns>The field offset.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="FieldOffset"/> property.
/// </remarks>
protected virtual int? GetFieldOffset() => null;
/// <inheritdoc />
public override string ToString() => FullName;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\GenericParameterTest.cs | AsmResolver.DotNet.Tests
| GenericParameterTest | [] | ['System.Linq', 'AsmResolver.DotNet.TestCases.Generics', 'AsmResolver.PE.DotNet.Metadata', 'Xunit'] | xUnit | net8.0 | public class GenericParameterTest
{
[Fact]
public void ReadName()
{
var module = ModuleDefinition.FromFile(typeof(GenericType<,,>).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == typeof(GenericType<,,>).Name);
Assert.Equal(new Utf8String[]
{
"T1", "T2", "T3"
}, type.GenericParameters.Select(p => p.Name));
}
[Fact]
public void ReadTypeOwner()
{
var module = ModuleDefinition.FromFile(typeof(GenericType<,,>).Assembly.Location, TestReaderParameters);
var token = typeof(GenericType<,,>).GetGenericArguments()[0].MetadataToken;
var genericParameter = (GenericParameter) module.LookupMember(token);
Assert.NotNull(genericParameter.Owner);
Assert.Equal(typeof(GenericType<,,>).MetadataToken, genericParameter.Owner.MetadataToken);
}
[Fact]
public void ReadMethodOwner()
{
var module = ModuleDefinition.FromFile(typeof(GenericType<,,>).Assembly.Location, TestReaderParameters);
var method = typeof(GenericType<,,>).GetMethod("GenericMethodInGenericType");
var token = method.GetGenericArguments()[0].MetadataToken;
var genericParameter = (GenericParameter) module.LookupMember(token);
Assert.NotNull(genericParameter.Owner);
Assert.Equal(method.MetadataToken, genericParameter.Owner.MetadataToken);
}
[Fact]
public void ReadSingleGenericParameterConstraint()
{
var module = ModuleDefinition.FromFile(typeof(NonGenericType).Assembly.Location, TestReaderParameters);
var token = typeof(NonGenericType)
.GetMethod(nameof(NonGenericType.GenericMethodWithConstraints))
.GetGenericArguments()[0]
.MetadataToken;
var genericParameter = (GenericParameter) module.LookupMember(token);
Assert.Single(genericParameter.Constraints);
Assert.Equal(nameof(IFoo), genericParameter.Constraints[0].Constraint.Name);
}
[Fact]
public void ReadMultipleGenericParameterConstraints()
{
var module = ModuleDefinition.FromFile(typeof(NonGenericType).Assembly.Location, TestReaderParameters);
var token = typeof(NonGenericType)
.GetMethod(nameof(NonGenericType.GenericMethodWithConstraints))
.GetGenericArguments()[1]
.MetadataToken;
var genericParameter = (GenericParameter) module.LookupMember(token);
Assert.Equal(new Utf8String[]
{
nameof(IFoo),
nameof(IBar)
}, genericParameter.Constraints.Select(c => c.Constraint.Name));
}
} | 164 | 3,124 | using System.Collections.Generic;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a type parameter that a generic method or type in a .NET module defines.
/// </summary>
public class GenericParameter :
MetadataMember,
INameProvider,
IHasCustomAttribute,
IModuleProvider,
IOwnedCollectionElement<IHasGenericParameters>
{
private readonly LazyVariable<GenericParameter, Utf8String?> _name;
private readonly LazyVariable<GenericParameter, IHasGenericParameters?> _owner;
private IList<GenericParameterConstraint>? _constraints;
private IList<CustomAttribute>? _customAttributes;
/// <summary>
/// Initializes a new empty generic parameter.
/// </summary>
/// <param name="token">The token of the generic parameter.</param>
protected GenericParameter(MetadataToken token)
: base(token)
{
_name = new LazyVariable<GenericParameter, Utf8String?>(x => x.GetName());
_owner = new LazyVariable<GenericParameter, IHasGenericParameters?>(x => x.GetOwner());
}
/// <summary>
/// Creates a new generic parameter.
/// </summary>
/// <param name="name">The name of the parameter.</param>
public GenericParameter(Utf8String? name)
: this(new MetadataToken(TableIndex.GenericParam, 0))
{
Name = name;
}
/// <summary>
/// Creates a new generic parameter.
/// </summary>
/// <param name="name">The name of the parameter.</param>
/// <param name="attributes">Additional attributes to assign to the parameter.</param>
public GenericParameter(Utf8String? name, GenericParameterAttributes attributes)
: this(new MetadataToken(TableIndex.GenericParam, 0))
{
Name = name;
Attributes = attributes;
}
/// <summary>
/// Gets the member that defines this generic parameter.
/// </summary>
public IHasGenericParameters? Owner
{
get => _owner.GetValue(this);
private set => _owner.SetValue(value);
}
IHasGenericParameters? IOwnedCollectionElement<IHasGenericParameters>.Owner
{
get => Owner;
set => Owner = value;
}
/// <summary>
/// Gets or sets the name of the generic parameter.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the generic parameter table.
/// </remarks>
public Utf8String? Name
{
get => _name.GetValue(this);
set => _name.SetValue(value);
}
string? INameProvider.Name => Name;
/// <summary>
/// Gets or sets additional attributes assigned to this generic parameter.
/// </summary>
public GenericParameterAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets the index of this parameter within the list of generic parameters that the owner defines.
/// </summary>
public ushort Number => Owner is null ? (ushort) 0 : (ushort) Owner.GenericParameters.IndexOf(this);
/// <inheritdoc />
public ModuleDefinition? Module => Owner?.Module;
/// <summary>
/// Gets a collection of constraints put on the generic parameter.
/// </summary>
public IList<GenericParameterConstraint> Constraints
{
get
{
if (_constraints is null)
Interlocked.CompareExchange(ref _constraints, GetConstraints(), null);
return _constraints;
}
}
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <summary>
/// Obtains the name of the generic parameter.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual Utf8String? GetName() => null;
/// <summary>
/// Obtains the owner of the generic parameter.
/// </summary>
/// <returns>The owner</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Owner"/> property.
/// </remarks>
protected virtual IHasGenericParameters? GetOwner() => null;
/// <summary>
/// Obtains a collection of constraints put on the generic parameter.
/// </summary>
/// <returns>The constraints</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Constraints"/> property.
/// </remarks>
protected virtual IList<GenericParameterConstraint> GetConstraints() =>
new OwnedCollection<GenericParameter, GenericParameterConstraint>(this);
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
/// <inheritdoc />
public override string ToString() => Name ?? NullName;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\ImplementationMapTest.cs | AsmResolver.DotNet.Tests
| ImplementationMapTest | [] | ['System', 'System.IO', 'System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Methods', 'AsmResolver.PE', 'Xunit'] | xUnit | net8.0 | public class ImplementationMapTest
{
private ImplementationMap Lookup(string methodName)
{
var method = LookupMethod(methodName);
return method.ImplementationMap;
}
private static MethodDefinition LookupMethod(string methodName)
{
var module = ModuleDefinition.FromFile(typeof(PlatformInvoke).Assembly.Location, TestReaderParameters);
var t = module.TopLevelTypes.First(t => t.Name == nameof(PlatformInvoke));
var method = t.Methods.First(m => m.Name == methodName);
return method;
}
private ImplementationMap RebuildAndLookup(ImplementationMap implementationMap)
{
using var stream = new MemoryStream();
implementationMap.MemberForwarded.Module.Write(stream);
var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
var t = newModule.TopLevelTypes.First(t => t.Name == nameof(PlatformInvoke));
return t.Methods.First(m => m.Name == implementationMap.MemberForwarded.Name).ImplementationMap;
}
[Fact]
public void ReadName()
{
var map = Lookup(nameof(PlatformInvoke.ExternalMethod));
Assert.Equal("SomeEntryPoint", map.Name);
}
[Fact]
public void PersistentName()
{
var map = Lookup(nameof(PlatformInvoke.ExternalMethod));
map.Name = "NewName";
var newMap = RebuildAndLookup(map);
Assert.Equal(map.Name, newMap.Name);
}
[Fact]
public void ReadScope()
{
var map = Lookup(nameof(PlatformInvoke.ExternalMethod));
Assert.Equal("SomeDll.dll", map.Scope.Name);
}
[Fact]
public void PersistentScope()
{
var map = Lookup(nameof(PlatformInvoke.ExternalMethod));
var newModule = new ModuleReference("SomeOtherDll.dll");
map.MemberForwarded.Module.ModuleReferences.Add(newModule);
map.Scope = newModule;
var newMap = RebuildAndLookup(map);
Assert.Equal(newModule.Name, newMap.Scope.Name);
}
[Fact]
public void ReadMemberForwarded()
{
var map = Lookup(nameof(PlatformInvoke.ExternalMethod));
Assert.Equal(nameof(PlatformInvoke.ExternalMethod), map.MemberForwarded.Name);
}
[Fact]
public void RemoveMapShouldUnsetMemberForwarded()
{
var map = Lookup(nameof(PlatformInvoke.ExternalMethod));
map.MemberForwarded.ImplementationMap = null;
Assert.Null(map.MemberForwarded);
}
[Fact]
public void AddingAlreadyAddedMapToAnotherMemberShouldThrow()
{
var map = Lookup(nameof(PlatformInvoke.ExternalMethod));
var declaringType = (TypeDefinition) map.MemberForwarded.DeclaringType;
var otherMethod = declaringType.Methods.First(m =>
m.Name == nameof(PlatformInvoke.NonImplementationMapMethod));
Assert.Throws<ArgumentException>(() => otherMethod.ImplementationMap = map);
}
[Fact]
public void PersistentMemberForwarded()
{
var map = Lookup(nameof(PlatformInvoke.ExternalMethod));
var declaringType = (TypeDefinition) map.MemberForwarded.DeclaringType;
var otherMethod = declaringType.Methods.First(m =>
m.Name == nameof(PlatformInvoke.NonImplementationMapMethod));
map.MemberForwarded.ImplementationMap = null;
otherMethod.ImplementationMap = map;
var newMap = RebuildAndLookup(map);
Assert.Equal(otherMethod.Name, newMap.MemberForwarded.Name);
}
} | 218 | 4,152 | using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a mapping that maps a method or field defined in a .NET module to an unmanaged function or
/// global field defined in an external module through Platform Invoke (P/Invoke).
/// </summary>
public class ImplementationMap : MetadataMember, IFullNameProvider
{
private readonly LazyVariable<ImplementationMap, Utf8String?> _name;
private readonly LazyVariable<ImplementationMap, ModuleReference?> _scope;
private readonly LazyVariable<ImplementationMap, IMemberForwarded?> _memberForwarded;
/// <summary>
/// Initializes the <see cref="ImplementationMap"/> with a metadata token.
/// </summary>
/// <param name="token">The token of the member.</param>
protected ImplementationMap(MetadataToken token)
: base(token)
{
_name = new LazyVariable<ImplementationMap, Utf8String?>(x => x.GetName());
_scope = new LazyVariable<ImplementationMap, ModuleReference?>(x => x.GetScope());
_memberForwarded = new LazyVariable<ImplementationMap, IMemberForwarded?>(x => x.GetMemberForwarded());
}
/// <summary>
/// Creates a new instance of the <see cref="ImplementationMap"/> class.
/// </summary>
/// <param name="scope">The scope that declares the imported member.</param>
/// <param name="name">The name of the imported member.</param>
/// <param name="attributes">The attributes associated to the implementation mapping.</param>
public ImplementationMap(ModuleReference? scope, Utf8String? name, ImplementationMapAttributes attributes)
: this(new MetadataToken(TableIndex.ImplMap, 0))
{
Scope = scope;
Name = name;
Attributes = attributes;
}
/// <summary>
/// Gets the attributes associated to the implementation mapping.
/// </summary>
public ImplementationMapAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets the member that this P/Invoke implementation mapping is assigned to.
/// </summary>
public IMemberForwarded? MemberForwarded
{
get => _memberForwarded.GetValue(this);
internal set => _memberForwarded.SetValue(value);
}
/// <summary>
/// Gets or sets the name of the map.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the implementation map table.
/// </remarks>
public Utf8String? Name
{
get => _name.GetValue(this);
set => _name.SetValue(value);
}
string? INameProvider.Name => Name;
/// <inheritdoc />
public string FullName => Scope is null
? Name ?? NullName
: $"{Scope.Name}!{Name}";
/// <summary>
/// Gets or sets the module that contains the external member.
/// </summary>
public ModuleReference? Scope
{
get => _scope.GetValue(this);
set => _scope.SetValue(value);
}
/// <summary>
/// Obtains the name of the imported member.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual Utf8String? GetName() => null;
/// <summary>
/// Obtains the scope that declares the imported member.
/// </summary>
/// <returns>The scope.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Scope"/> property.
/// </remarks>
protected virtual ModuleReference? GetScope() => null;
/// <summary>
/// Obtains the owner of the P/Invoke implementation mapping.
/// </summary>
/// <returns>The owner.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="MemberForwarded"/> property.
/// </remarks>
protected virtual IMemberForwarded? GetMemberForwarded() => null;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\ManifestResourceTest.cs | AsmResolver.DotNet.Tests
| ManifestResourceTest | ['private readonly TemporaryDirectoryFixture _fixture;'] | ['System.IO', 'System.Linq', 'System.Text', 'AsmResolver.DotNet.Builder', 'AsmResolver.PE.Builder', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'AsmResolver.Tests.Runners', 'Xunit', 'AsmResolver.DotNet.TestCases.Resources.Resources'] | xUnit | net8.0 | public class ManifestResourceTest : IClassFixture<TemporaryDirectoryFixture>
{
private readonly TemporaryDirectoryFixture _fixture;
public ManifestResourceTest(TemporaryDirectoryFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void ReadEmbeddedResource1Data()
{
var module = ModuleDefinition.FromFile(typeof(TestCaseResources).Assembly.Location, TestReaderParameters);
var resource = module.Resources.First(r =>
r.Name == "AsmResolver.DotNet.TestCases.Resources.Resources.EmbeddedResource1");
Assert.Equal(TestCaseResources.GetEmbeddedResource1Data(), Encoding.ASCII.GetString(resource.GetData()));
}
[Fact]
public void ReadEmbeddedResource2Data()
{
var module = ModuleDefinition.FromFile(typeof(TestCaseResources).Assembly.Location, TestReaderParameters);
var resource = module.Resources.First(r =>
r.Name == "AsmResolver.DotNet.TestCases.Resources.Resources.EmbeddedResource2");
Assert.Equal(TestCaseResources.GetEmbeddedResource2Data(), Encoding.ASCII.GetString(resource.GetData()));
}
[Fact]
public void PersistentData()
{
const string resourceName = "SomeResource";
var contents = new byte[]
{
0,1,2,3,4
};
var module = ModuleDefinition.FromFile(typeof(TestCaseResources).Assembly.Location, TestReaderParameters);
module.Resources.Add(new ManifestResource(resourceName, ManifestResourceAttributes.Public, new DataSegment(contents)));
using var stream = new MemoryStream();
module.Write(stream);
var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
Assert.Equal(contents, newModule.Resources.First(r => r.Name == resourceName).GetData());
}
[Fact]
public void PersistentDataReader()
{
const string resourceName = "SomeResource";
var contents = new byte[]
{
0,1,2,3,4
};
var module = ModuleDefinition.FromFile(typeof(TestCaseResources).Assembly.Location, TestReaderParameters);
module.Resources.Add(new ManifestResource(resourceName, ManifestResourceAttributes.Public, new DataSegment(contents)));
using var stream = new MemoryStream();
module.Write(stream);
var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
var resource = newModule.Resources.First(r => r.Name == resourceName);
Assert.True(resource.TryGetReader(out var reader));
Assert.Equal(contents, reader.ReadToEnd());
}
[Fact]
public void PersistentUniqueResourceData()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.DupResource, TestReaderParameters);
// Create three unique resources.
module.Resources.Add(new ManifestResource(
"resource1",
ManifestResourceAttributes.Public,
new DataSegment(new byte[] {1, 2, 3, 4}))
);
module.Resources.Add(new ManifestResource(
"resource2",
ManifestResourceAttributes.Public,
new DataSegment(new byte[] {5, 6, 7, 8}))
);
module.Resources.Add(new ManifestResource(
"resource3",
ManifestResourceAttributes.Public,
new DataSegment(new byte[] {9, 10, 11, 12}))
);
// Verify program returns correct data.
_fixture
.GetRunner<CorePERunner>()
.RebuildAndRun(module, "DupResource.dll",
"""
resource1: 01020304
resource2: 05060708
resource3: 090A0B0C
""");
}
[Theory]
[InlineData(MetadataBuilderFlags.None)]
[InlineData(MetadataBuilderFlags.NoResourceDataDeduplication)]
public void PersistentIdenticalResourceData(MetadataBuilderFlags flags)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.DupResource, TestReaderParameters);
// Create two identical resources and one unique resource.
module.Resources.Add(new ManifestResource(
"resource1",
ManifestResourceAttributes.Public,
new DataSegment(new byte[] {1, 2, 3, 4}))
);
module.Resources.Add(new ManifestResource(
"resource2",
ManifestResourceAttributes.Public,
new DataSegment(new byte[] {1, 2, 3, 4}))
);
module.Resources.Add(new ManifestResource(
"resource3",
ManifestResourceAttributes.Public,
new DataSegment(new byte[] {9, 10, 11, 12}))
);
// Build image.
var image = module.ToPEImage(new ManagedPEImageBuilder(flags));
var table = image.DotNetDirectory!.Metadata!
.GetStream<TablesStream>()
.GetTable<ManifestResourceRow>();
if ((flags & MetadataBuilderFlags.NoResourceDataDeduplication) != 0)
{
// Without deduplication, all offsets should be different.
Assert.NotEqual(table[0].Offset, table[1].Offset);
Assert.NotEqual(table[0].Offset, table[2].Offset);
}
else
{
// With deduplication, resources with same data should share data offset.
Assert.Equal(table[0].Offset, table[1].Offset);
Assert.NotEqual(table[0].Offset, table[2].Offset);
}
// Verify program returns correct data.
var file = new ManagedPEFileBuilder().CreateFile(image);
_fixture
.GetRunner<CorePERunner>()
.RebuildAndRun(file, $"DupResource_{flags}.dll",
"""
resource1: 01020304
resource2: 01020304
resource3: 090A0B0C
""");
}
} | 379 | 6,910 | using System;
using System.Collections.Generic;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.IO;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a single manifest resource file either embedded into the .NET assembly, or put into a separate file.
/// In this case, it contains also a reference to the file the resource is located in.
/// </summary>
public class ManifestResource :
MetadataMember,
INameProvider,
IHasCustomAttribute,
IOwnedCollectionElement<ModuleDefinition>
{
private readonly LazyVariable<ManifestResource, Utf8String?> _name;
private readonly LazyVariable<ManifestResource, IImplementation?> _implementation;
private readonly LazyVariable<ManifestResource, ISegment?> _embeddedData;
private IList<CustomAttribute>? _customAttributes;
/// <summary>
/// Initializes the <see cref="ManifestResource"/> with a metadata token.
/// </summary>
/// <param name="token">The metadata token.</param>
protected ManifestResource(MetadataToken token)
: base(token)
{
_name = new LazyVariable<ManifestResource, Utf8String?>(x => x.GetName());
_implementation = new LazyVariable<ManifestResource, IImplementation?>(x => x.GetImplementation());
_embeddedData = new LazyVariable<ManifestResource, ISegment?>(x => x.GetEmbeddedDataSegment());
}
/// <summary>
/// Creates a new external manifest resource.
/// </summary>
/// <param name="name">The name of the resource</param>
/// <param name="attributes">The attributes of the resource.</param>
/// <param name="implementation">The location of the resource data.</param>
/// <param name="offset">The offset within the file referenced by <paramref name="implementation"/> where the data starts.</param>
public ManifestResource(Utf8String? name, ManifestResourceAttributes attributes, IImplementation? implementation, uint offset)
: this(new MetadataToken(TableIndex.ManifestResource, 0))
{
Name = name;
Attributes = attributes;
Implementation = implementation;
Offset = offset;
}
/// <summary>
/// Creates a new embedded manifest resource.
/// </summary>
/// <param name="name">The name of the repository.</param>
/// <param name="attributes">The attributes of the resource.</param>
/// <param name="data">The embedded resource data.</param>
public ManifestResource(Utf8String? name, ManifestResourceAttributes attributes, ISegment? data)
: this(new MetadataToken(TableIndex.ManifestResource, 0))
{
Name = name;
Attributes = attributes;
EmbeddedDataSegment = data;
}
/// <summary>
/// Depending on the value of <see cref="Implementation"/>, gets or sets the (relative) offset the resource data
/// starts at.
/// </summary>
public uint Offset
{
get;
set;
}
/// <summary>
/// Gets or sets the attributes associated with this resource.
/// </summary>
public ManifestResourceAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the resource is public and exported by the .NET module.
/// </summary>
public bool IsPublic
{
get => Attributes == ManifestResourceAttributes.Public;
set => Attributes = value ? ManifestResourceAttributes.Public : ManifestResourceAttributes.Private;
}
/// <summary>
/// Gets or sets a value indicating whether the resource is private to the .NET module.
/// </summary>
public bool IsPrivate
{
get => Attributes == ManifestResourceAttributes.Private;
set => Attributes = value ? ManifestResourceAttributes.Private : ManifestResourceAttributes.Public;
}
/// <summary>
/// Gets or sets the name of the manifest resource.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the manifest resource table.
/// </remarks>
public Utf8String? Name
{
get => _name.GetValue(this);
set => _name.SetValue(value);
}
string? INameProvider.Name => Name;
/// <summary>
/// Gets or sets the implementation indicating the file containing the resource data.
/// </summary>
public IImplementation? Implementation
{
get => _implementation.GetValue(this);
set => _implementation.SetValue(value);
}
/// <summary>
/// Gets a value indicating whether the resource is embedded into the current module.
/// </summary>
public bool IsEmbedded => Implementation is null;
/// <summary>
/// When this resource is embedded into the current module, gets or sets the embedded resource data.
/// </summary>
public ISegment? EmbeddedDataSegment
{
get => _embeddedData.GetValue(this);
set => _embeddedData.SetValue(value);
}
/// <summary>
/// Gets the module that this manifest resource reference is stored in.
/// </summary>
public ModuleDefinition? Module
{
get;
private set;
}
/// <inheritdoc />
ModuleDefinition? IOwnedCollectionElement<ModuleDefinition>.Owner
{
get => Module;
set => Module = value;
}
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <summary>
/// Gets the data stored in the manifest resource.
/// </summary>
/// <returns>The data, or <c>null</c> if no data was stored or if the external resource was not found.</returns>
public byte[]? GetData()
{
// TODO: resolve external resources.
return EmbeddedDataSegment is IReadableSegment readableSegment
? readableSegment.ToArray()
: null;
}
/// <summary>
/// Gets the reader of stored data in the manifest resource.
/// </summary>
/// <returns>The reader, or <c>null</c> if no data was stored or if the external resource was not found.</returns>
[Obsolete("Use TryGetReader instead.")]
public BinaryStreamReader? GetReader()
{
// TODO: resolve external resources.
return EmbeddedDataSegment is IReadableSegment readableSegment
? readableSegment.CreateReader()
: null;
}
/// <summary>
/// Gets the reader of stored data in the manifest resource.
/// </summary>
public bool TryGetReader(out BinaryStreamReader reader)
{
// TODO: resolve external resources.
if (EmbeddedDataSegment is IReadableSegment readableSegment)
{
reader = readableSegment.CreateReader();
return true;
}
reader = default;
return false;
}
/// <summary>
/// Obtains the name of the manifest resource.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual Utf8String? GetName() => null;
/// <summary>
/// Obtains the implementation of this resource.
/// </summary>
/// <returns>The implementation.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Implementation"/> property.
/// </remarks>
protected virtual IImplementation? GetImplementation() => null;
/// <summary>
/// When the resource is embedded, obtains the contents of the manifest resource.
/// </summary>
/// <returns>The data, or <c>null</c> if the resource is not embedded.</returns>
protected virtual ISegment? GetEmbeddedDataSegment() => null;
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
/// <inheritdoc />
public override string ToString() => Name ?? NullName;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\MemberReferenceTest.cs | AsmResolver.DotNet.Tests
| MemberReferenceTest | [] | ['System.Linq', 'Xunit'] | xUnit | net8.0 | public class MemberReferenceTest
{
[Fact]
public void ResolveForwardedMethod()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.ForwarderRefTest, TestReaderParameters);
var forwarder = ModuleDefinition.FromBytes(Properties.Resources.ForwarderLibrary, TestReaderParameters).Assembly!;
var library = ModuleDefinition.FromBytes(Properties.Resources.ActualLibrary, TestReaderParameters).Assembly!;
module.MetadataResolver.AssemblyResolver.AddToCache(forwarder, forwarder);
module.MetadataResolver.AssemblyResolver.AddToCache(library, library);
forwarder.ManifestModule!.MetadataResolver.AssemblyResolver.AddToCache(library, library);
var reference = module
.GetImportedMemberReferences()
.First(m => m.IsMethod && m.Name == "StaticMethod");
var definition = reference.Resolve();
Assert.NotNull(definition);
}
} | 79 | 1,102 | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a reference to a method or a field in an (external) .NET assembly.
/// </summary>
public class MemberReference : MetadataMember, ICustomAttributeType, IFieldDescriptor
{
private readonly LazyVariable<MemberReference, IMemberRefParent?> _parent;
private readonly LazyVariable<MemberReference, Utf8String?> _name;
private readonly LazyVariable<MemberReference, CallingConventionSignature?> _signature;
private IList<CustomAttribute>? _customAttributes;
/// <summary>
/// Initializes a new member reference.
/// </summary>
/// <param name="token">The metadata token of the reference.</param>
protected MemberReference(MetadataToken token)
: base(token)
{
_parent = new LazyVariable<MemberReference, IMemberRefParent?>(x => x.GetParent());
_name = new LazyVariable<MemberReference, Utf8String?>(x => x.GetName());
_signature = new LazyVariable<MemberReference, CallingConventionSignature?>(x => x.GetSignature());
}
/// <summary>
/// Creates a new reference to a member in an (external) .NET assembly.
/// </summary>
/// <param name="parent">The declaring member that defines the referenced member.</param>
/// <param name="name">The name of the referenced member.</param>
/// <param name="signature">The signature of the referenced member. This dictates whether the
/// referenced member is a field or a method.</param>
public MemberReference(IMemberRefParent? parent, Utf8String? name, MemberSignature? signature)
: this(new MetadataToken(TableIndex.MemberRef, 0))
{
Parent = parent;
Name = name;
Signature = signature;
}
/// <summary>
/// Gets or sets the member that declares the referenced member.
/// </summary>
public IMemberRefParent? Parent
{
get => _parent.GetValue(this);
set => _parent.SetValue(value);
}
/// <summary>
/// Gets or sets the name of the referenced member.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the member reference table.
/// </remarks>
public Utf8String? Name
{
get => _name.GetValue(this);
set => _name.SetValue(value);
}
/// <inheritdoc />
string? INameProvider.Name => Name;
/// <summary>
/// Gets or sets the signature of the referenced member.
/// </summary>
/// <remarks>
/// This property dictates whether the referenced member is a field or a method.
/// </remarks>
public CallingConventionSignature? Signature
{
get => _signature.GetValue(this);
set => _signature.SetValue(value);
}
MethodSignature? IMethodDescriptor.Signature => Signature as MethodSignature;
FieldSignature? IFieldDescriptor.Signature => Signature as FieldSignature;
/// <summary>
/// Gets a value indicating whether the referenced member is a field.
/// </summary>
[MemberNotNullWhen(true, nameof(Signature))]
public bool IsField => Signature is FieldSignature;
/// <summary>
/// Gets a value indicating whether the referenced member is a method
/// </summary>
[MemberNotNullWhen(true, nameof(Signature))]
public bool IsMethod => Signature is MethodSignature;
/// <inheritdoc />
public string FullName
{
get
{
if (IsField)
return MemberNameGenerator.GetFieldFullName(this);
if (IsMethod)
return MemberNameGenerator.GetMethodFullName(this);
return Name ?? NullName;
}
}
/// <inheritdoc />
public ModuleDefinition? Module => Parent?.Module;
/// <summary>
/// Gets the type that declares the referenced member, if available.
/// </summary>
public ITypeDefOrRef? DeclaringType => Parent switch
{
ITypeDefOrRef typeDefOrRef => typeDefOrRef,
MethodDefinition method => method.DeclaringType,
_ => null
};
ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType;
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <summary>
/// Resolves the reference to a member definition.
/// </summary>
/// <returns>The resolved member definition, or <c>null</c> if the member could not be resolved.</returns>
/// <exception cref="ArgumentOutOfRangeException">Occurs when the member reference has an invalid signature.</exception>
/// <remarks>
/// This method can only be invoked if the reference was added to a module.
/// </remarks>
public IMemberDefinition? Resolve()
{
if (IsMethod)
return ((IMethodDescriptor) this).Resolve();
if (IsField)
return ((IFieldDescriptor) this).Resolve();
throw new ArgumentOutOfRangeException();
}
/// <inheritdoc />
public bool IsImportedInModule(ModuleDefinition module)
{
return Module == module
&& (Signature?.IsImportedInModule(module) ?? false);
}
/// <summary>
/// Imports the member using the provided reference importer object.
/// </summary>
/// <param name="importer">The reference importer to use for importing the object.</param>
/// <returns>The imported member.</returns>
public MemberReference ImportWith(ReferenceImporter importer) => IsMethod
? (MemberReference) importer.ImportMethod(this)
: (MemberReference) importer.ImportField(this);
/// <inheritdoc />
IImportable IImportable.ImportWith(ReferenceImporter importer) => ImportWith(importer);
FieldDefinition? IFieldDescriptor.Resolve()
{
if (!IsField)
throw new InvalidOperationException("Member reference must reference a field.");
return Module?.MetadataResolver.ResolveField(this);
}
MethodDefinition? IMethodDescriptor.Resolve()
{
if (!IsMethod)
throw new InvalidOperationException("Member reference must reference a method.");
return Module?.MetadataResolver.ResolveMethod(this);
}
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
/// <summary>
/// Obtains the parent of the member reference.
/// </summary>
/// <returns>The parent</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Parent"/> property.
/// </remarks>
protected virtual IMemberRefParent? GetParent() => null;
/// <summary>
/// Obtains the name of the member reference.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual Utf8String? GetName() => null;
/// <summary>
/// Obtains the signature of the member reference.
/// </summary>
/// <returns>The signature</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Signature"/> property.
/// </remarks>
protected virtual CallingConventionSignature? GetSignature() => null;
/// <inheritdoc />
public override string ToString() => FullName;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\MetadataResolverTest.cs | AsmResolver.DotNet.Tests
| MetadataResolverTest | ['private readonly DefaultMetadataResolver _fwResolver;', 'private readonly DefaultMetadataResolver _coreResolver;', 'private readonly SignatureComparer _comparer;'] | ['System', 'System.IO', 'System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.NestedClasses', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class MetadataResolverTest
{
private readonly DefaultMetadataResolver _fwResolver;
private readonly DefaultMetadataResolver _coreResolver;
private readonly SignatureComparer _comparer;
public MetadataResolverTest()
{
_fwResolver = new DefaultMetadataResolver(new DotNetFrameworkAssemblyResolver()
{
SearchDirectories =
{
Path.GetDirectoryName(typeof(MetadataResolverTest).Assembly.Location)
}
});
_coreResolver = new DefaultMetadataResolver(new DotNetCoreAssemblyResolver(new Version(3, 1, 0))
{
SearchDirectories =
{
Path.GetDirectoryName(typeof(MetadataResolverTest).Assembly.Location)
}
});
_comparer = new SignatureComparer();
}
[Fact]
public void ResolveSystemObjectFramework()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var reference = new TypeReference(module.CorLibTypeFactory.CorLibScope, "System", "Object");
var definition = _fwResolver.ResolveType(reference);
Assert.Equal((ITypeDefOrRef) reference, definition, _comparer);
}
[Fact]
public void ResolveSystemObjectNetCore()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_NetCore, TestReaderParameters);
var reference = new TypeReference(module.CorLibTypeFactory.CorLibScope, "System", "Object");
var definition = _coreResolver.ResolveType(reference);
Assert.NotNull(definition);
Assert.True(definition.IsTypeOf(reference.Namespace, reference.Name));
}
[Fact]
public void ResolveCorLibTypeSignature()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var definition = _fwResolver.ResolveType(module.CorLibTypeFactory.Object);
Assert.Equal(module.CorLibTypeFactory.Object.Type, definition, _comparer);
}
[Fact]
public void ResolveType()
{
var module = ModuleDefinition.FromFile(typeof(TopLevelClass1).Assembly.Location, TestReaderParameters);
var topLevelClass1 = new TypeReference(new AssemblyReference(module.Assembly!),
typeof(TopLevelClass1).Namespace, nameof(TopLevelClass1));
var definition = _coreResolver.ResolveType(topLevelClass1);
Assert.Equal((ITypeDefOrRef) topLevelClass1, definition, _comparer);
}
[Fact]
public void ResolveTypeReferenceTwice()
{
var module = new ModuleDefinition("SomeModule.dll");
var consoleType = new TypeReference(module.CorLibTypeFactory.CorLibScope, "System", "Console");
Assert.Same(_fwResolver.ResolveType(consoleType), _fwResolver.ResolveType(consoleType));
}
[Fact]
public void ResolveTypeReferenceThenChangeRefAndResolveAgain()
{
var module = new ModuleDefinition("SomeModule.dll");
ITypeDefOrRef expected = new TypeReference(module.CorLibTypeFactory.CorLibScope, "System", "Object");
var reference = new TypeReference(module.CorLibTypeFactory.CorLibScope, "System", "Object");
Assert.Equal(expected, _fwResolver.ResolveType(reference), _comparer);
reference.Name = "String";
Assert.NotEqual(expected, _fwResolver.ResolveType(reference), _comparer);
}
[Fact]
public void ResolveTypeReferenceThenChangeDefAndResolveAgain()
{
var module = new ModuleDefinition("SomeModule.dll");
ITypeDefOrRef expected = new TypeReference(module.CorLibTypeFactory.CorLibScope, "System", "Object");
var reference = new TypeReference(module.CorLibTypeFactory.CorLibScope, "System", "Object");
var definition = _fwResolver.ResolveType(reference)!;
Assert.Equal(expected, definition, _comparer);
definition.Name = "String";
Assert.NotEqual(expected, _fwResolver.ResolveType(reference), _comparer);
}
[Fact]
public void ResolveNestedType()
{
var module = ModuleDefinition.FromFile(typeof(TopLevelClass1).Assembly.Location, TestReaderParameters);
var topLevelClass1 = new TypeReference(new AssemblyReference(module.Assembly!),
typeof(TopLevelClass1).Namespace, nameof(TopLevelClass1));
var nested1 = new TypeReference(topLevelClass1,null, nameof(TopLevelClass1.Nested1));
var definition = _coreResolver.ResolveType(nested1);
Assert.Equal((ITypeDefOrRef) nested1, definition, _comparer);
}
[Fact]
public void ResolveNestedNestedType()
{
var module = ModuleDefinition.FromFile(typeof(TopLevelClass1).Assembly.Location, TestReaderParameters);
var topLevelClass1 = new TypeReference(new AssemblyReference(module.Assembly!),
typeof(TopLevelClass1).Namespace, nameof(TopLevelClass1));
var nested1 = new TypeReference(topLevelClass1,null, nameof(TopLevelClass1.Nested1));
var nested1nested1 = new TypeReference(nested1,null, nameof(TopLevelClass1.Nested1.Nested1Nested1));
var definition = _fwResolver.ResolveType(nested1nested1);
Assert.Equal((ITypeDefOrRef) nested1nested1, definition, _comparer);
}
[Fact]
public void ResolveTypeWithModuleScope()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.TypeRefModuleScope, TestReaderParameters);
var reference = module.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 2));
var definition = reference.Resolve();
Assert.NotNull(definition);
Assert.Same(module, definition.Module);
}
[Fact]
public void ResolveTypeWithNullScopeCurrentModule()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.TypeRefNullScope_CurrentModule, TestReaderParameters);
var reference = module.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 2));
var definition = reference.Resolve();
Assert.NotNull(definition);
Assert.Same(module, definition.Module);
}
[Fact]
public void ResolveTypeWithNullScopeExportedType()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.TypeRefNullScope_ExportedType, TestReaderParameters);
var reference = module.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 1));
var definition = reference.Resolve();
Assert.NotNull(definition);
Assert.Equal("mscorlib", definition.Module!.Assembly!.Name);
}
[Fact]
public void ResolveConsoleWriteLineMethod()
{
var module = new ModuleDefinition("SomeModule.dll");
var consoleType = new TypeReference(module.CorLibTypeFactory.CorLibScope, "System", "Console");
var writeLineMethod = new MemberReference(consoleType, "WriteLine",
MethodSignature.CreateStatic(module.CorLibTypeFactory.Void, module.CorLibTypeFactory.String));
var definition = _fwResolver.ResolveMethod(writeLineMethod);
Assert.NotNull(definition);
Assert.Equal(writeLineMethod.Name, definition.Name);
Assert.Equal(writeLineMethod.Signature, definition.Signature, _comparer);
}
[Fact]
public void ResolveStringEmptyField()
{
var module = new ModuleDefinition("SomeModule.dll");
var stringType = new TypeReference(module.CorLibTypeFactory.CorLibScope, "System", "String");
var emptyField = new MemberReference(
stringType,
"Empty",
new FieldSignature(module.CorLibTypeFactory.String));
var definition = _fwResolver.ResolveField(emptyField);
Assert.NotNull(definition);
Assert.Equal(emptyField.Name, definition.Name);
Assert.Equal(emptyField.Signature, definition.Signature, _comparer);
}
[Fact]
public void ResolveExportedMemberReference()
{
// Issue: https://github.com/Washi1337/AsmResolver/issues/124
// Load assemblies.
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_Forwarder, TestReaderParameters);
var assembly1 = AssemblyDefinition.FromBytes(Properties.Resources.Assembly1_Forwarder, TestReaderParameters);
var assembly2 = AssemblyDefinition.FromBytes(Properties.Resources.Assembly2_Actual, TestReaderParameters);
// Manually wire assemblies together for in-memory resolution.
var resolver = (AssemblyResolverBase) module.MetadataResolver.AssemblyResolver;
resolver.AddToCache(assembly1, assembly1);
resolver.AddToCache(assembly2, assembly2);
resolver = (AssemblyResolverBase) assembly1.ManifestModule!.MetadataResolver.AssemblyResolver;
resolver.AddToCache(assembly1, assembly1);
resolver.AddToCache(assembly2, assembly2);
// Resolve
var instructions = module.ManagedEntryPointMethod!.CilMethodBody!.Instructions;
Assert.NotNull(((IMethodDescriptor) instructions[0].Operand!).Resolve());
}
[Fact]
public void MaliciousExportedTypeLoop()
{
// Load assemblies.
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_MaliciousExportedTypeLoop, TestReaderParameters);
var assembly1 = AssemblyDefinition.FromBytes(Properties.Resources.Assembly1_MaliciousExportedTypeLoop, TestReaderParameters);
var assembly2 = AssemblyDefinition.FromBytes(Properties.Resources.Assembly2_MaliciousExportedTypeLoop, TestReaderParameters);
// Manually wire assemblies together for in-memory resolution.
var resolver = (AssemblyResolverBase) module.MetadataResolver.AssemblyResolver;
resolver.AddToCache(assembly1, assembly1);
resolver.AddToCache(assembly2, assembly2);
resolver = (AssemblyResolverBase) assembly1.ManifestModule!.MetadataResolver.AssemblyResolver;
resolver.AddToCache(assembly1, assembly1);
resolver.AddToCache(assembly2, assembly2);
resolver = (AssemblyResolverBase) assembly2.ManifestModule!.MetadataResolver.AssemblyResolver;
resolver.AddToCache(assembly1, assembly1);
resolver.AddToCache(assembly2, assembly2);
// Find reference to exported type loop.
var reference = module
.GetImportedTypeReferences()
.First(t => t.Name == "SomeName");
// Attempt to resolve. The test here is that it should not result in an infinite loop / stack overflow.
Assert.Null(reference.Resolve());
}
[Fact]
public void ResolveToOlderNetVersion()
{
// https://github.com/Washi1337/AsmResolver/issues/321
var mainApp = ModuleDefinition.FromBytes(Properties.Resources.DifferentNetVersion_MainApp, TestReaderParameters);
var library = ModuleDefinition.FromBytes(Properties.Resources.DifferentNetVersion_Library, TestReaderParameters);
mainApp.MetadataResolver.AssemblyResolver.AddToCache(library.Assembly!, library.Assembly!);
var definition = library
.TopLevelTypes.First(t => t.Name == "MyClass")
.Methods.First(m => m.Name == "ThrowMe");
var reference = (IMethodDescriptor) mainApp.ManagedEntryPointMethod!.CilMethodBody!.Instructions.First(
i => i.OpCode == CilOpCodes.Callvirt && ((IMethodDescriptor) i.Operand)?.Name == "ThrowMe")
.Operand!;
var resolved = reference.Resolve();
Assert.NotNull(resolved);
Assert.Equal(definition, resolved);
}
[Fact]
public void ResolveMethodWithoutHideBySig()
{
// https://github.com/Washi1337/AsmResolver/issues/241
var classLibrary = ModuleDefinition.FromFile(typeof(ClassLibraryVB.Class1).Assembly.Location, TestReaderParameters);
var definitions = classLibrary
.TopLevelTypes.First(t => t.Name == nameof(ClassLibraryVB.Class1))
.Methods.Where(m => m.Name == nameof(ClassLibraryVB.Class1.Test))
.OrderBy(x => x.Parameters.Count)
.ToArray();
var helloWorld = ModuleDefinition.FromFile(typeof(HelloWorldVB.Program).Assembly.Location, TestReaderParameters);
var resolved = helloWorld.ManagedEntryPointMethod!.CilMethodBody!.Instructions
.Where(x => x.OpCode == CilOpCodes.Call)
.Select(x => ((IMethodDescriptor) x.Operand!).Resolve())
.ToArray();
Assert.Equal(definitions, resolved, new SignatureComparer());
}
} | 281 | 13,975 | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Provides a default implementation for the <see cref="IMetadataResolver"/> interface.
/// </summary>
public class DefaultMetadataResolver : IMetadataResolver
{
private readonly ConcurrentDictionary<ITypeDescriptor, TypeDefinition> _typeCache;
private readonly SignatureComparer _comparer = new(SignatureComparisonFlags.VersionAgnostic);
/// <summary>
/// Creates a new metadata resolver.
/// </summary>
/// <param name="assemblyResolver">The resolver to use for resolving external assemblies.</param>
public DefaultMetadataResolver(IAssemblyResolver assemblyResolver)
{
AssemblyResolver = assemblyResolver ?? throw new ArgumentNullException(nameof(assemblyResolver));
_typeCache = new ConcurrentDictionary<ITypeDescriptor, TypeDefinition>();
}
/// <inheritdoc />
public IAssemblyResolver AssemblyResolver
{
get;
}
/// <inheritdoc />
public TypeDefinition? ResolveType(ITypeDescriptor? type)
{
return type switch
{
TypeDefinition definition => definition,
TypeReference reference => ResolveTypeReference(reference),
TypeSpecification specification => ResolveType(specification.Signature),
TypeSignature signature => ResolveTypeSignature(signature),
ExportedType exportedType => ResolveExportedType(exportedType),
_ => null
};
}
private TypeDefinition? LookupInCache(ITypeDescriptor type)
{
if (_typeCache.TryGetValue(type, out var typeDef))
{
// Check if type definition has changed since last lookup.
if (typeDef.IsTypeOf(type.Namespace, type.Name))
return typeDef;
_typeCache.TryRemove(type, out _);
}
return null;
}
private TypeDefinition? ResolveTypeReference(TypeReference? reference)
{
if (reference is null)
return null;
var resolvedType = LookupInCache(reference);
if (resolvedType is not null)
return resolvedType;
var resolution = new TypeResolution(AssemblyResolver);
resolvedType = resolution.ResolveTypeReference(reference);
if (resolvedType is not null)
_typeCache[reference] = resolvedType;
return resolvedType;
}
private TypeDefinition? ResolveExportedType(ExportedType? exportedType)
{
if (exportedType is null)
return null;
var resolvedType = LookupInCache(exportedType);
if (resolvedType is not null)
return resolvedType;
var resolution = new TypeResolution(AssemblyResolver);
resolvedType = resolution.ResolveExportedType(exportedType);
if (resolvedType is not null)
_typeCache[exportedType] = resolvedType;
return resolvedType;
}
private TypeDefinition? ResolveTypeSignature(TypeSignature? signature)
{
var type = signature?.GetUnderlyingTypeDefOrRef();
if (type is null)
return null;
return type.MetadataToken.Table switch
{
TableIndex.TypeDef => (TypeDefinition) type,
TableIndex.TypeRef => ResolveTypeReference((TypeReference) type),
TableIndex.TypeSpec => ResolveTypeSignature(((TypeSpecification) type).Signature),
_ => null
};
}
/// <inheritdoc />
public MethodDefinition? ResolveMethod(IMethodDescriptor? method)
{
if (method is null)
return null;
var declaringType = ResolveType(method.DeclaringType);
if (declaringType is null)
return null;
for (int i = 0; i < declaringType.Methods.Count; i++)
{
var candidate = declaringType.Methods[i];
if (candidate.Name == method.Name && _comparer.Equals(method.Signature, candidate.Signature))
return candidate;
}
return null;
}
/// <inheritdoc />
public FieldDefinition? ResolveField(IFieldDescriptor? field)
{
if (field is null)
return null;
var declaringType = ResolveType(field.DeclaringType);
if (declaringType is null)
return null;
var name = field is MemberReference member
? member.Name
: (Utf8String?) field.Name;
for (int i = 0; i < declaringType.Fields.Count; i++)
{
var candidate = declaringType.Fields[i];
if (candidate.Name == field.Name && _comparer.Equals(field.Signature, candidate.Signature))
return candidate;
}
return null;
}
private readonly struct TypeResolution
{
private readonly IAssemblyResolver _assemblyResolver;
private readonly Stack<IResolutionScope> _scopeStack;
private readonly Stack<IImplementation> _implementationStack;
public TypeResolution(IAssemblyResolver resolver)
{
_assemblyResolver = resolver ?? throw new ArgumentNullException(nameof(resolver));
_scopeStack = new Stack<IResolutionScope>();
_implementationStack = new Stack<IImplementation>();
}
public TypeDefinition? ResolveTypeReference(TypeReference? reference)
{
if (reference is null)
return null;
var scope = reference.Scope ?? reference.Module;
if (reference.Name is null || scope is null || _scopeStack.Contains(scope))
return null;
_scopeStack.Push(scope);
switch (scope.MetadataToken.Table)
{
case TableIndex.AssemblyRef:
if (reference.Module?.Assembly is { } assembly)
{
// Are we referencing the current assembly the reference was declared in?
if (SignatureComparer.Default.Equals(scope.GetAssembly(), assembly))
return FindTypeInModule(reference.Module, reference.Namespace, reference.Name);
}
var assemblyDefScope = _assemblyResolver.Resolve((AssemblyReference) scope);
return assemblyDefScope is not null
? FindTypeInAssembly(assemblyDefScope, reference.Namespace, reference.Name)
: null;
case TableIndex.Module:
return FindTypeInModule((ModuleDefinition) scope, reference.Namespace, reference.Name);
case TableIndex.TypeRef:
var typeDefScope = ResolveTypeReference((TypeReference) scope);
return typeDefScope is not null
? FindTypeInType(typeDefScope, reference.Name)
: null;
default:
return null;
}
}
public TypeDefinition? ResolveExportedType(ExportedType? exportedType)
{
var implementation = exportedType?.Implementation;
if (exportedType?.Name is null || implementation is null || _implementationStack.Contains(implementation))
return null;
_implementationStack.Push(implementation);
switch (implementation.MetadataToken.Table)
{
case TableIndex.AssemblyRef:
var assembly = _assemblyResolver.Resolve((AssemblyReference) implementation);
return assembly is not null
? FindTypeInAssembly(assembly, exportedType.Namespace, exportedType.Name)
: null;
case TableIndex.File when !string.IsNullOrEmpty(implementation.Name):
var module = FindModuleInAssembly(exportedType.Module!.Assembly!, implementation.Name!);
return module is not null
? FindTypeInModule(module, exportedType.Namespace, exportedType.Name)
: null;
case TableIndex.ExportedType:
var exportedDeclaringType = (ExportedType) implementation;
var declaringType = ResolveExportedType(exportedDeclaringType);
return declaringType is not null
? FindTypeInType(declaringType, exportedType.Name)
: null;
default:
throw new ArgumentOutOfRangeException();
}
}
private TypeDefinition? FindTypeInAssembly(AssemblyDefinition assembly, Utf8String? ns, Utf8String name)
{
for (int i = 0; i < assembly.Modules.Count; i++)
{
var module = assembly.Modules[i];
var type = FindTypeInModule(module, ns, name);
if (type is not null)
return type;
}
return null;
}
private TypeDefinition? FindTypeInModule(ModuleDefinition module, Utf8String? ns, Utf8String name)
{
for (int i = 0; i < module.TopLevelTypes.Count; i++)
{
var type = module.TopLevelTypes[i];
if (type.IsTypeOfUtf8(ns, name))
return type;
}
for (int i = 0; i < module.ExportedTypes.Count; i++)
{
var exportedType = module.ExportedTypes[i];
if (exportedType.IsTypeOfUtf8(ns, name))
return ResolveExportedType(exportedType);
}
return null;
}
private static TypeDefinition? FindTypeInType(TypeDefinition enclosingType, Utf8String name)
{
for (int i = 0; i < enclosingType.NestedTypes.Count; i++)
{
var type = enclosingType.NestedTypes[i];
if (type.Name == name)
return type;
}
return null;
}
private static ModuleDefinition? FindModuleInAssembly(AssemblyDefinition assembly, Utf8String name)
{
for (int i = 0; i < assembly.Modules.Count; i++)
{
var module = assembly.Modules[i];
if (module.Name == name)
return module;
}
return null;
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\MethodDefinitionTest.cs | AsmResolver.DotNet.Tests
| MethodDefinitionTest | ['private const string NonWindowsPlatform = "Test operates on native Windows binaries.";', 'private readonly TemporaryDirectoryFixture _fixture;'] | ['System', 'System.Collections.Generic', 'System.IO', 'System.Linq', 'System.Runtime.InteropServices', 'AsmResolver.DotNet.Code.Cil', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Events', 'AsmResolver.DotNet.TestCases.Generics', 'AsmResolver.DotNet.TestCases.Methods', 'AsmResolver.DotNet.TestCases.Properties', 'AsmResolver.PE.DotNet', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata.Tables', 'AsmResolver.PE.DotNet.VTableFixups', 'AsmResolver.PE.Exports', 'AsmResolver.PE.File', 'AsmResolver.Tests.Runners', 'Xunit'] | xUnit | net8.0 | public class MethodDefinitionTest: IClassFixture<TemporaryDirectoryFixture>
{
private const string NonWindowsPlatform = "Test operates on native Windows binaries.";
private readonly TemporaryDirectoryFixture _fixture;
public MethodDefinitionTest(TemporaryDirectoryFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void ReadName()
{
var module = ModuleDefinition.FromFile(typeof(SingleMethod).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleMethod));
var method = type.Methods.FirstOrDefault(m => m.Name == nameof(SingleMethod.VoidParameterlessMethod));
Assert.NotNull(method);
}
[Theory]
[InlineData(".ctor", "System.Void")]
[InlineData(nameof(MultipleMethods.VoidParameterlessMethod), "System.Void")]
[InlineData(nameof(MultipleMethods.IntParameterlessMethod), "System.Int32")]
[InlineData(nameof(MultipleMethods.TypeDefOrRefParameterlessMethod), "AsmResolver.DotNet.TestCases.Methods.MultipleMethods")]
public void ReadReturnType(string methodName, string expectedReturnType)
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleMethods));
var method = type.Methods.First(m => m.Name == methodName);
Assert.Equal(expectedReturnType, method.Signature.ReturnType.FullName);
}
[Fact]
public void ReadDeclaringType()
{
var module = ModuleDefinition.FromFile(typeof(SingleMethod).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(SingleMethod).GetMethod(nameof(SingleMethod.VoidParameterlessMethod)).MetadataToken);
Assert.NotNull(method.DeclaringType);
Assert.Equal(nameof(SingleMethod), method.DeclaringType.Name);
}
[Fact]
public void ReadEmptyParameterDefinitions()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(MultipleMethods).GetMethod(nameof(MultipleMethods.VoidParameterlessMethod)).MetadataToken);
Assert.Empty(method.ParameterDefinitions);
}
[Fact]
public void ReadSingleParameterDefinition()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(MultipleMethods).GetMethod(nameof(MultipleMethods.SingleParameterMethod)).MetadataToken);
Assert.Single(method.ParameterDefinitions);
}
[Fact]
public void ReadMultipleParameterDefinitions()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(MultipleMethods).GetMethod(nameof(MultipleMethods.MultipleParameterMethod)).MetadataToken);
Assert.Equal(3, method.ParameterDefinitions.Count);
}
[Fact]
public void ReadEmptyParametersStatic()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(MultipleMethods).GetMethod(nameof(MultipleMethods.VoidParameterlessMethod)).MetadataToken);
Assert.Empty(method.Parameters);
}
[Fact]
public void ReadSingleParameterStatic()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(MultipleMethods).GetMethod(nameof(MultipleMethods.SingleParameterMethod)).MetadataToken);
Assert.Single(method.Parameters);
Assert.Equal("intParameter", method.Parameters[0].Name);
Assert.True(method.Parameters[0].ParameterType.IsTypeOf("System", "Int32"));
}
[Fact]
public void ReadMultipleParameterStatic()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(MultipleMethods).GetMethod(nameof(MultipleMethods.MultipleParameterMethod)).MetadataToken);
Assert.Equal(3, method.Parameters.Count);
Assert.Equal("intParameter", method.Parameters[0].Name);
Assert.True(method.Parameters[0].ParameterType.IsTypeOf("System", "Int32"),
"Expected first parameter to be of type System.Int32.");
Assert.Equal("stringParameter", method.Parameters[1].Name);
Assert.True(method.Parameters[1].ParameterType.IsTypeOf("System", "String"),
"Expected second parameter to be of type System.String.");
Assert.Equal("typeDefOrRefParameter", method.Parameters[2].Name);
Assert.True(method.Parameters[2].ParameterType.IsTypeOf("AsmResolver.DotNet.TestCases.Methods", "MultipleMethods"),
"Expected third parameter to be of type AsmResolver.TestCases.DotNet.MultipleMethods.");
}
[Fact]
public void ReadParameterlessInt32MethodFullName()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(MultipleMethods).GetMethod(nameof(MultipleMethods.IntParameterlessMethod)).MetadataToken);
Assert.Equal(
"System.Int32 AsmResolver.DotNet.TestCases.Methods.MultipleMethods::IntParameterlessMethod()",
method.FullName);
}
[Fact]
public void ReadParameterlessMethodFullName()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(MultipleMethods).GetMethod(nameof(MultipleMethods.VoidParameterlessMethod)).MetadataToken);
Assert.Equal(
"System.Void AsmResolver.DotNet.TestCases.Methods.MultipleMethods::VoidParameterlessMethod()",
method.FullName);
}
[Fact]
public void ReadSingleParameterMethodFullName()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(MultipleMethods).GetMethod(nameof(MultipleMethods.SingleParameterMethod)).MetadataToken);
Assert.Equal(
"System.Void AsmResolver.DotNet.TestCases.Methods.MultipleMethods::SingleParameterMethod(System.Int32)",
method.FullName);
}
[Fact]
public void ReadMultipleParametersMethodFullName()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(MultipleMethods).GetMethod(nameof(MultipleMethods.MultipleParameterMethod)).MetadataToken);
Assert.Equal(
"System.Void AsmResolver.DotNet.TestCases.Methods.MultipleMethods::MultipleParameterMethod(System.Int32, System.String, AsmResolver.DotNet.TestCases.Methods.MultipleMethods)",
method.FullName);
}
[Fact]
public void ReadNormalMethod()
{
var module = ModuleDefinition.FromFile(typeof(SingleMethod).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(SingleMethod).GetMethod(nameof(SingleMethod.VoidParameterlessMethod)).MetadataToken);
Assert.False(method.IsGetMethod);
Assert.False(method.IsSetMethod);
Assert.False(method.IsAddMethod);
Assert.False(method.IsRemoveMethod);
Assert.False(method.IsFireMethod);
}
[Fact]
public void ReadIsGetMethod()
{
var module = ModuleDefinition.FromFile(typeof(SingleProperty).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(SingleProperty).GetMethod("get_" + nameof(SingleProperty.IntProperty)).MetadataToken);
Assert.True(method.IsGetMethod);
}
[Fact]
public void ReadIsSetMethod()
{
var module = ModuleDefinition.FromFile(typeof(SingleProperty).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(SingleProperty).GetMethod("set_" + nameof(SingleProperty.IntProperty)).MetadataToken);
Assert.True(method.IsSetMethod);
}
[Fact]
public void ReadIsAddMethod()
{
var module = ModuleDefinition.FromFile(typeof(SingleEvent).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(SingleEvent).GetMethod("add_" + nameof(SingleEvent.SimpleEvent)).MetadataToken);
Assert.True(method.IsAddMethod);
}
[Fact]
public void ReadIsRemoveMethod()
{
var module = ModuleDefinition.FromFile(typeof(SingleEvent).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(
typeof(SingleEvent).GetMethod("remove_" + nameof(SingleEvent.SimpleEvent)).MetadataToken);
Assert.True(method.IsRemoveMethod);
}
[Fact]
public void ReadSignatureIsReturnsValue()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = module.TopLevelTypes
.First(t => t.Name == nameof(MultipleMethods)).Methods
.First(m => m.Name == nameof(MultipleMethods.IntParameterlessMethod));
Assert.True(method.Signature.ReturnsValue);
}
[Fact]
public void ReadSignatureNotReturnsValue()
{
var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters);
var method = module.TopLevelTypes
.First(t => t.Name == nameof(MultipleMethods)).Methods
.First(m => m.Name == nameof(MultipleMethods.VoidParameterlessMethod));
Assert.False(method.Signature.ReturnsValue);
}
private static AssemblyDefinition CreateDummyLibraryWithExport(int methodCount, bool is32Bit)
{
// Build new dummy lib.
var assembly = new AssemblyDefinition("MyLibrary", new Version(1, 0, 0, 0));
var module = new ModuleDefinition("MyLibrary.dll");
module.Attributes &= ~DotNetDirectoryFlags.ILOnly;
if (is32Bit)
{
module.Attributes |= DotNetDirectoryFlags.Bit32Required;
module.FileCharacteristics |= Characteristics.Dll | Characteristics.Machine32Bit;
module.PEKind = OptionalHeaderMagic.PE32;
module.MachineType = MachineType.I386;
}
else
{
module.FileCharacteristics |= Characteristics.Dll;
module.PEKind = OptionalHeaderMagic.PE32Plus;
module.MachineType = MachineType.Amd64;
}
assembly.Modules.Add(module);
// Import Console.WriteLine.
var importer = new ReferenceImporter(module);
var writeLine = importer.ImportMethod(new MemberReference(
new TypeReference(module.CorLibTypeFactory.CorLibScope, "System", "Console"),
"WriteLine",
MethodSignature.CreateStatic(module.CorLibTypeFactory.Void, module.CorLibTypeFactory.String)));
// Add a couple unmanaged exports.
for (int i = 0; i < methodCount; i++)
AddExportedMethod($"MyMethod{i.ToString()}");
return assembly;
void AddExportedMethod(string methodName)
{
// New static method.
var method = new MethodDefinition(
methodName,
MethodAttributes.Public | MethodAttributes.Static,
MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));
// Add a Console.WriteLine call
var body = new CilMethodBody(method);
method.MethodBody = body;
body.Instructions.Add(CilOpCodes.Ldstr, $"Hello from {methodName}.");
body.Instructions.Add(CilOpCodes.Call, writeLine);
body.Instructions.Add(CilOpCodes.Ret);
// Add to <Module>
module.GetOrCreateModuleType().Methods.Add(method);
// Register as unmanaged export.
method.ExportInfo = new UnmanagedExportInfo(methodName,
is32Bit ? VTableType.VTable32Bit : VTableType.VTable64Bit);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ReadExportMethodByName(bool is32Bit)
{
byte[] binary = is32Bit
? Properties.Resources.MyLibrary_X86
: Properties.Resources.MyLibrary_X64;
var module = ModuleDefinition.FromBytes(binary, TestReaderParameters);
const int methodCount = 3;
int matchedMethods = 0;
foreach (var method in module.GetOrCreateModuleType().Methods)
{
if (method.Name!.Value.StartsWith("MyMethod"))
{
Assert.True(method.ExportInfo.HasValue);
Assert.Equal(method.Name, method.ExportInfo.Value.Name);
matchedMethods++;
}
}
Assert.Equal(methodCount, matchedMethods);
}
[SkippableTheory]
[InlineData(false)]
[InlineData(true)]
public void PersistExportMethodByName(bool is32Bit)
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
const int methodCount = 3;
var assembly = CreateDummyLibraryWithExport(methodCount, is32Bit);
var runner = _fixture.GetRunner<NativePERunner>();
string suffix = is32Bit ? "x86" : "x64";
// Write library to temp dir.
string libraryPath = Path.ChangeExtension(runner.GetTestExecutablePath(
nameof(MethodDefinitionTest),
nameof(PersistExportMethodByName),
$"MyLibrary.{suffix}.dll"), ".dll");
assembly.Write(libraryPath);
// Write caller to temp dir.
string callerPath = runner.GetTestExecutablePath(
nameof(MethodDefinitionTest),
nameof(PersistExportMethodByName),
$"CallManagedExport.{suffix}.exe");
File.WriteAllBytes(callerPath, is32Bit
? Properties.Resources.CallManagedExport_X86
: Properties.Resources.CallManagedExport_X64);
// Verify all exported methods.
for (int i = 0; i < methodCount; i++)
{
string methodName = $"MyMethod{i.ToString()}";
string output = runner.RunAndCaptureOutput(callerPath, new[]
{
libraryPath,
methodName
});
Assert.Contains($"Hello from {methodName}.", output);
}
}
[Fact]
public void SingleExportWithOrdinalShouldUpdateBaseOrdinal()
{
const uint ordinal = 100u;
var module = CreateDummyLibraryWithExport(1, false).ManifestModule!;
var method = module.GetModuleType()!.Methods.First(m => m.Name == "MyMethod0");
method.ExportInfo = new UnmanagedExportInfo(ordinal, "MyMethod0", VTableType.VTable32Bit);
var image = module.ToPEImage();
Assert.NotNull(image.Exports);
var entry = Assert.Single(image.Exports.Entries);
Assert.Equal(ordinal, entry.Ordinal);
Assert.Equal(ordinal, image.Exports.BaseOrdinal);
}
[Theory]
[InlineData(new[] {0, 1, 2})]
[InlineData(new[] {2, 1, 0})]
[InlineData(new[] {1, 0, 2})]
public void MultipleExportsWithFixedOrdinalInSequenceShouldUpdateBaseOrdinal(int[] order)
{
string[] names =
{
"MyMethod0",
"MyMethod1",
"MyMethod2",
};
const uint baseOrdinal = 100u;
var module = CreateDummyLibraryWithExport(3, false).ManifestModule!;
var methods = module.GetModuleType()!.Methods;
var method1 = methods.First(m => m.Name == names[order[0]]);
var method2 = methods.First(m => m.Name == names[order[1]]);
var method3 = methods.First(m => m.Name == names[order[2]]);
method1.ExportInfo = new UnmanagedExportInfo(baseOrdinal, names[order[0]], VTableType.VTable32Bit);
method2.ExportInfo = new UnmanagedExportInfo(baseOrdinal + 1, names[order[1]], VTableType.VTable32Bit);
method3.ExportInfo = new UnmanagedExportInfo(baseOrdinal + 2, names[order[2]], VTableType.VTable32Bit);
var image = module.ToPEImage();
Assert.NotNull(image.Exports);
Assert.Equal(3, image.Exports.Entries.Count);
Assert.Equal(baseOrdinal, image.Exports.Entries[0].Ordinal);
Assert.Equal(names[order[0]], image.Exports.Entries[0].Name);
Assert.Equal(baseOrdinal + 1, image.Exports.Entries[1].Ordinal);
Assert.Equal(names[order[1]], image.Exports.Entries[1].Name);
Assert.Equal(baseOrdinal + 2, image.Exports.Entries[2].Ordinal);
Assert.Equal(names[order[2]], image.Exports.Entries[2].Name);
Assert.Equal(baseOrdinal, image.Exports.BaseOrdinal);
}
[Fact]
public void PreferInsertingFloatingExportsBeforeFixedExports()
{
const uint ordinal = 100u;
var module = CreateDummyLibraryWithExport(2, false).ManifestModule!;
var methods = module.GetModuleType()!.Methods;
var method1 = methods.First(m => m.Name == "MyMethod0");
var method2 = methods.First(m => m.Name == "MyMethod1");
method1.ExportInfo = new UnmanagedExportInfo(ordinal, "MyMethod0", VTableType.VTable32Bit);
method2.ExportInfo = new UnmanagedExportInfo("MyMethod1", VTableType.VTable32Bit);
var image = module.ToPEImage();
Assert.NotNull(image.Exports);
Assert.Equal(2, image.Exports.Entries.Count);
Assert.Equal("MyMethod1", image.Exports.Entries[0].Name);
Assert.Equal("MyMethod0", image.Exports.Entries[1].Name);
Assert.Equal(ordinal - 1, image.Exports.BaseOrdinal);
}
[Fact]
public void AppendFloatingExportsToEndIfNoSpaceBeforeFixedExports()
{
const uint ordinal = 2u;
var module = CreateDummyLibraryWithExport(4, false).ManifestModule!;
var methods = module.GetModuleType()!.Methods;
var method1 = methods.First(m => m.Name == "MyMethod0");
var method2 = methods.First(m => m.Name == "MyMethod1");
var method3 = methods.First(m => m.Name == "MyMethod2");
var method4 = methods.First(m => m.Name == "MyMethod3");
method1.ExportInfo = new UnmanagedExportInfo(ordinal, "MyMethod0", VTableType.VTable32Bit);
method2.ExportInfo = new UnmanagedExportInfo("MyMethod1", VTableType.VTable32Bit);
method3.ExportInfo = new UnmanagedExportInfo("MyMethod2", VTableType.VTable32Bit);
method4.ExportInfo = new UnmanagedExportInfo("MyMethod3", VTableType.VTable32Bit);
var image = module.ToPEImage();
Assert.NotNull(image.Exports);
Assert.Equal(4, image.Exports.Entries.Count);
Assert.Equal("MyMethod0", image.Exports.Entries[1].Name);
Assert.Equal(1u, image.Exports.BaseOrdinal);
}
[Fact]
public void PreferInsertingFloatingExportsInGapsBetweenFixedExports()
{
const uint ordinal1 = 1u;
const uint ordinal2 = 3u;
var module = CreateDummyLibraryWithExport(3, false).ManifestModule!;
var methods = module.GetModuleType()!.Methods;
var method1 = methods.First(m => m.Name == "MyMethod0");
var method2 = methods.First(m => m.Name == "MyMethod1");
var method3 = methods.First(m => m.Name == "MyMethod2");
method1.ExportInfo = new UnmanagedExportInfo(ordinal1, "MyMethod0", VTableType.VTable32Bit);
method2.ExportInfo = new UnmanagedExportInfo(ordinal2, "MyMethod1", VTableType.VTable32Bit);
method3.ExportInfo = new UnmanagedExportInfo( "MyMethod2", VTableType.VTable32Bit);
var image = module.ToPEImage();
Assert.NotNull(image.Exports);
Assert.Equal("MyMethod0", image.Exports.Entries[0].Name);
Assert.Equal("MyMethod2", image.Exports.Entries[1].Name);
Assert.Equal("MyMethod1", image.Exports.Entries[2].Name);
Assert.Equal(ordinal1, image.Exports.BaseOrdinal);
}
[Fact]
public void FillUpExportGapsWithDummyExports()
{
const uint ordinal1 = 25u;
const uint ordinal2 = 50u;
const uint ordinal3 = 75u;
var module = CreateDummyLibraryWithExport(3, false).ManifestModule!;
var methods = module.GetModuleType()!.Methods;
var method1 = methods.First(m => m.Name == "MyMethod0");
var method2 = methods.First(m => m.Name == "MyMethod1");
var method3 = methods.First(m => m.Name == "MyMethod2");
method1.ExportInfo = new UnmanagedExportInfo(ordinal1, "MyMethod0", VTableType.VTable32Bit);
method2.ExportInfo = new UnmanagedExportInfo(ordinal2, "MyMethod1", VTableType.VTable32Bit);
method3.ExportInfo = new UnmanagedExportInfo(ordinal3, "MyMethod2", VTableType.VTable32Bit);
var image = module.ToPEImage();
Assert.NotNull(image.Exports);
Assert.Equal(51, image.Exports.Entries.Count);
foreach (var entry in image.Exports.Entries)
{
switch (entry.Ordinal)
{
case ordinal1:
Assert.Equal("MyMethod0", entry.Name);
Assert.NotNull(entry.Address.GetSegment());
break;
case ordinal2:
Assert.Equal("MyMethod1", entry.Name);
Assert.NotNull(entry.Address.GetSegment());
break;
case ordinal3:
Assert.Equal("MyMethod2", entry.Name);
Assert.NotNull(entry.Address.GetSegment());
break;
default:
Assert.False(entry.IsByName);
Assert.Null(entry.Address.GetSegment());
break;
}
}
Assert.Equal(ordinal1, image.Exports.BaseOrdinal);
}
[Theory]
[InlineData("NonGenericMethodInNonGenericType",
"System.Void AsmResolver.DotNet.TestCases.Generics.NonGenericType::NonGenericMethodInNonGenericType()")]
[InlineData("GenericMethodInNonGenericType",
"System.Void AsmResolver.DotNet.TestCases.Generics.NonGenericType::GenericMethodInNonGenericType<U1, U2, U3>()")]
[InlineData("GenericMethodWithConstraints",
"System.Void AsmResolver.DotNet.TestCases.Generics.NonGenericType::GenericMethodWithConstraints<T1, T2>()")]
public void MethodFullNameTests(string methodName, string expectedFullName)
{
var module = ModuleDefinition.FromFile(typeof(NonGenericType).Assembly.Location, TestReaderParameters);
var method = module
.TopLevelTypes.First(t => t.Name == nameof(NonGenericType))
.Methods.First(m => m.Name == methodName);
Assert.Equal(expectedFullName, method.FullName);
}
[Fact]
public void CreateParameterlessConstructor()
{
var module = ModuleDefinition.FromFile(typeof(Constructors).Assembly.Location, TestReaderParameters);
var ctor = MethodDefinition.CreateConstructor(module);
Assert.True(ctor.IsConstructor);
Assert.Empty(ctor.Parameters);
Assert.NotNull(ctor.CilMethodBody);
Assert.Equal(CilOpCodes.Ret, Assert.Single(ctor.CilMethodBody.Instructions).OpCode);
}
[Fact]
public void CreateConstructor()
{
var module = ModuleDefinition.FromFile(typeof(Constructors).Assembly.Location, TestReaderParameters);
var factory = module.CorLibTypeFactory;
var ctor = MethodDefinition.CreateConstructor(module, factory.Int32, factory.Double);
Assert.True(ctor.IsConstructor);
Assert.Equal(new[] {factory.Int32, factory.Double}, ctor.Parameters.Select(x => x.ParameterType));
}
} | 689 | 27,494 | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.DotNet.Code;
using AsmResolver.DotNet.Code.Cil;
using AsmResolver.DotNet.Code.Native;
using AsmResolver.DotNet.Collections;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a single method in a type definition of a .NET module.
/// </summary>
public class MethodDefinition :
MetadataMember,
IMemberDefinition,
IOwnedCollectionElement<TypeDefinition>,
IMemberRefParent,
ICustomAttributeType,
IHasGenericParameters,
IMemberForwarded,
IHasSecurityDeclaration,
IManagedEntryPoint
{
private readonly LazyVariable<MethodDefinition, Utf8String?> _name;
private readonly LazyVariable<MethodDefinition, TypeDefinition?> _declaringType;
private readonly LazyVariable<MethodDefinition, MethodSignature?> _signature;
private readonly LazyVariable<MethodDefinition, MethodBody?> _methodBody;
private readonly LazyVariable<MethodDefinition, ImplementationMap?> _implementationMap;
private readonly LazyVariable<MethodDefinition, MethodSemantics?> _semantics;
private readonly LazyVariable<MethodDefinition, UnmanagedExportInfo?> _exportInfo;
private IList<ParameterDefinition>? _parameterDefinitions;
private ParameterCollection? _parameters;
private IList<CustomAttribute>? _customAttributes;
private IList<SecurityDeclaration>? _securityDeclarations;
private IList<GenericParameter>? _genericParameters;
/// <summary>
/// Initializes a new method definition.
/// </summary>
/// <param name="token">The token of the method</param>
protected MethodDefinition(MetadataToken token)
: base(token)
{
_name = new LazyVariable<MethodDefinition, Utf8String?>(x => GetName());
_declaringType = new LazyVariable<MethodDefinition, TypeDefinition?>(x => GetDeclaringType());
_signature = new LazyVariable<MethodDefinition, MethodSignature?>(x => x.GetSignature());
_methodBody = new LazyVariable<MethodDefinition, MethodBody?>(x => x.GetBody());
_implementationMap = new LazyVariable<MethodDefinition, ImplementationMap?>(x => x.GetImplementationMap());
_semantics = new LazyVariable<MethodDefinition, MethodSemantics?>(x => x.GetSemantics());
_exportInfo = new LazyVariable<MethodDefinition, UnmanagedExportInfo?>(x => x.GetExportInfo());
}
/// <summary>
/// Creates a new method definition.
/// </summary>
/// <param name="name">The name of the method.</param>
/// <param name="attributes">The attributes.</param>
/// <param name="signature">The signature of the method</param>
/// <remarks>
/// For a valid .NET image, if <see cref="CallingConventionSignature.HasThis"/> of the signature referenced by
/// <paramref name="signature"/> is set, the <see cref="MethodAttributes.Static"/> bit should be unset in
/// <paramref name="attributes"/> and vice versa.
/// </remarks>
public MethodDefinition(Utf8String? name, MethodAttributes attributes, MethodSignature? signature)
: this(new MetadataToken(TableIndex.Method, 0))
{
Name = name;
Attributes = attributes;
Signature = signature;
}
/// <summary>
/// Gets or sets the name of the method definition.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the method definition table.
/// </remarks>
public Utf8String? Name
{
get => _name.GetValue(this);
set => _name.SetValue(value);
}
string? INameProvider.Name => Name;
/// <summary>
/// Gets or sets the signature of the method This includes the return type, as well as the types of the
/// parameters that this method defines.
/// </summary>
public MethodSignature? Signature
{
get => _signature.GetValue(this);
set => _signature.SetValue(value);
}
/// <inheritdoc />
public string FullName => MemberNameGenerator.GetMethodFullName(this);
/// <summary>
/// Gets or sets the attributes associated to the method.
/// </summary>
public MethodAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the method is compiler controlled and cannot be referenced directly.
/// </summary>
public bool IsCompilerControlled
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.CompilerControlled;
set => Attributes = value ? Attributes & ~MethodAttributes.MemberAccessMask : Attributes;
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked private and can only be accessed by
/// members within the same enclosing type.
/// </summary>
public bool IsPrivate
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.Private : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked family and assembly, and can only be accessed by
/// members within the same enclosing type and any derived type, within the same assembly.
/// </summary>
public bool IsFamilyAndAssembly
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamilyAndAssembly;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.FamilyAndAssembly : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked private and can only be accessed by
/// members within the same assembly.
/// </summary>
public bool IsAssembly
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.Assembly : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked private and can only be accessed by
/// members within the same enclosing type, as well as any derived type.
/// </summary>
public bool IsFamily
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.Family : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked family or assembly, and can only be accessed by
/// members within the same enclosing type and any derived type, or within the same assembly.
/// </summary>
public bool IsFamilyOrAssembly
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamilyOrAssembly;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.FamilyOrAssembly : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked public, and can be accessed by
/// any member having access to the enclosing type.
/// </summary>
public bool IsPublic
{
get => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public;
set => Attributes = (Attributes & ~MethodAttributes.MemberAccessMask)
| (value ? MethodAttributes.Public : 0);
}
/// <summary>
/// Gets or sets a value indicating the managed method is exported by a thunk to unmanaged code.
/// </summary>
public bool IsUnmanagedExport
{
get => (Attributes & MethodAttributes.UnmanagedExport) != 0;
set => Attributes = (Attributes & ~MethodAttributes.UnmanagedExport)
| (value ? MethodAttributes.UnmanagedExport : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method requires an object instance to access it.
/// </summary>
/// <remarks>
/// This property does not reflect the value of <see cref="CallingConventionSignature.HasThis"/>, nor will it
/// change the value of <see cref="CallingConventionSignature.HasThis"/> if this property is changed. For a
/// valid .NET image, these values should match, however.
/// </remarks>
public bool IsStatic
{
get => (Attributes & MethodAttributes.Static) != 0;
set => Attributes = (Attributes & ~MethodAttributes.Static)
| (value ? MethodAttributes.Static : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is marked final and cannot be overridden by a derived
/// class.
/// </summary>
public bool IsFinal
{
get => (Attributes & MethodAttributes.Final) != 0;
set => Attributes = (Attributes & ~MethodAttributes.Final)
| (value ? MethodAttributes.Final : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is virtual.
/// </summary>
public bool IsVirtual
{
get => (Attributes & MethodAttributes.Virtual) != 0;
set => Attributes = (Attributes & ~MethodAttributes.Virtual)
| (value ? MethodAttributes.Virtual : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is distinguished by both its name and signature.
/// </summary>
public bool IsHideBySig
{
get => (Attributes & MethodAttributes.HideBySig) != 0;
set => Attributes = (Attributes & ~MethodAttributes.HideBySig)
| (value ? MethodAttributes.HideBySig : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the runtime should reuse an existing slot in the VTable of the
/// enclosing class for this method.
/// </summary>
public bool IsReuseSlot
{
get => (Attributes & MethodAttributes.VtableLayoutMask) == MethodAttributes.ReuseSlot;
set => Attributes = value ? Attributes & ~MethodAttributes.VtableLayoutMask : Attributes;
}
/// <summary>
/// Gets or sets a value indicating whether the runtime allocate a new slot in the VTable of the
/// enclosing class for this method.
/// </summary>
public bool IsNewSlot
{
get => (Attributes & MethodAttributes.VtableLayoutMask) == MethodAttributes.NewSlot;
set => Attributes = (Attributes & ~MethodAttributes.VtableLayoutMask)
| (value ? MethodAttributes.NewSlot : 0);
}
/// <summary>
/// Gets or sets a value indicating the method can only be overridden if it is also accessible.
/// </summary>
public bool CheckAccessOnOverride
{
get => (Attributes & MethodAttributes.CheckAccessOnOverride) != 0;
set => Attributes = (Attributes & ~MethodAttributes.CheckAccessOnOverride)
| (value ? MethodAttributes.CheckAccessOnOverride : 0);
}
/// <summary>
/// Gets or sets a value indicating the method is marked abstract, and should be overridden by a derived class.
/// </summary>
/// <remarks>
/// Methods with this flag set should not have a method body assigned for a valid .NET executable. However,
/// updating this flag will not remove the body of this method, nor does the existence of the method body reflect
/// the value of this property.
/// </remarks>
public bool IsAbstract
{
get => (Attributes & MethodAttributes.Abstract) != 0;
set => Attributes = (Attributes & ~MethodAttributes.Abstract)
| (value ? MethodAttributes.Abstract : 0);
}
/// <summary>
/// Gets or sets a value indicating the method is given a special name.
/// </summary>
public bool IsSpecialName
{
get => (Attributes & MethodAttributes.SpecialName) != 0;
set => Attributes = (Attributes & ~MethodAttributes.SpecialName)
| (value ? MethodAttributes.SpecialName : 0);
}
/// <summary>
/// Gets or sets a value indicating the method is given a special name that is used by the runtime.
/// </summary>
public bool IsRuntimeSpecialName
{
get => (Attributes & MethodAttributes.RuntimeSpecialName) != 0;
set => Attributes = (Attributes & ~MethodAttributes.RuntimeSpecialName)
| (value ? MethodAttributes.RuntimeSpecialName : 0);
}
/// <summary>
/// Gets or sets a value indicating the method contains Platform Invoke information.
/// </summary>
/// <remarks>
/// Methods containing Platform Invoke information should have this flag set. This property does not
/// update automatically however when P/Invoke information is assigned to this method, nor does it reflect
/// the existence of P/Invoke information.
/// </remarks>
public bool IsPInvokeImpl
{
get => (Attributes & MethodAttributes.PInvokeImpl) != 0;
set => Attributes = (Attributes & ~MethodAttributes.PInvokeImpl)
| (value ? MethodAttributes.PInvokeImpl : 0);
}
/// <summary>
/// Gets or sets a value indicating the method has security attributes assigned to it.
/// </summary>
/// <remarks>
/// Methods containing security attributes should have this flag set. This property does not automatically
/// however when attributes are added or removed from this method, nor does it reflect the existence of
/// attributes.
/// </remarks>
public bool HasSecurity
{
get => (Attributes & MethodAttributes.HasSecurity) != 0;
set => Attributes = (Attributes & ~MethodAttributes.HasSecurity)
| (value ? MethodAttributes.HasSecurity : 0);
}
/// <summary>
/// Gets or sets a value indicating themethod calls another method containing security code.
/// </summary>
public bool RequireSecObject
{
get => (Attributes & MethodAttributes.RequireSecObject) != 0;
set => Attributes = (Attributes & ~MethodAttributes.RequireSecObject)
| (value ? MethodAttributes.RequireSecObject : 0);
}
/// <summary>
/// Gets or sets the attributes that describe the implementation of the method body.
/// </summary>
public MethodImplAttributes ImplAttributes
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating the method body is implemented using the Common Intermediate Language (CIL).
/// </summary>
public bool IsIL
{
get => (ImplAttributes & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.IL;
set => ImplAttributes = value ? ImplAttributes & ~MethodImplAttributes.CodeTypeMask : ImplAttributes;
}
/// <summary>
/// Gets or sets a value indicating the method body is implemented using the Common Intermediate Language (CIL).
/// </summary>
public bool IsNative
{
get => (ImplAttributes & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.Native;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.CodeTypeMask)
| (value ? MethodImplAttributes.Native : 0);
}
/// <summary>
/// Gets or sets a value indicating the method body is implemented using OPTIL.
/// </summary>
public bool IsOPTIL
{
get => (ImplAttributes & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.OPTIL;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.CodeTypeMask)
| (value ? MethodImplAttributes.OPTIL : 0);
}
/// <summary>
/// Gets or sets a value indicating the method body is implemented by the runtime.
/// </summary>
public bool IsRuntime
{
get => (ImplAttributes & MethodImplAttributes.CodeTypeMask) == MethodImplAttributes.Runtime;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.CodeTypeMask)
| (value ? MethodImplAttributes.Runtime : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method body is managed by the runtime.
/// </summary>
public bool Managed
{
get => (ImplAttributes & MethodImplAttributes.ManagedMask) == MethodImplAttributes.Managed;
set => ImplAttributes = value ? ImplAttributes & ~MethodImplAttributes.ManagedMask : ImplAttributes;
}
/// <summary>
/// Gets or sets a value indicating whether the method body is not managed by the runtime.
/// </summary>
public bool Unmanaged
{
get => (ImplAttributes & MethodImplAttributes.ManagedMask) == MethodImplAttributes.Unmanaged;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.ManagedMask)
| (value ? MethodImplAttributes.Unmanaged : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method body is forwarded.
/// </summary>
public bool IsForwardReference
{
get => (ImplAttributes & MethodImplAttributes.ForwardRef) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.ForwardRef)
| (value ? MethodImplAttributes.ForwardRef : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the runtime should not optimize the code upon generating native code.
/// </summary>
public bool IsNoOptimization
{
get => (ImplAttributes & MethodImplAttributes.NoOptimization) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.NoOptimization)
| (value ? MethodImplAttributes.NoOptimization : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method's signature is not to be mangled to do HRESULT conversion.
/// </summary>
public bool PreserveSignature
{
get => (ImplAttributes & MethodImplAttributes.PreserveSig) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.PreserveSig)
| (value ? MethodImplAttributes.PreserveSig : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method is an internal call into the runtime.
/// </summary>
public bool IsInternalCall
{
get => (ImplAttributes & MethodImplAttributes.InternalCall) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.InternalCall)
| (value ? MethodImplAttributes.InternalCall : 0);
}
/// <summary>
/// Gets or sets a value indicating only one thread can run the method at once.
/// </summary>
public bool IsSynchronized
{
get => (ImplAttributes & MethodImplAttributes.Synchronized) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.Synchronized)
| (value ? MethodImplAttributes.Synchronized : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method can be inlined by the runtime or not.
/// </summary>
public bool NoInlining
{
get => (ImplAttributes & MethodImplAttributes.NoInlining) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.NoInlining)
| (value ? MethodImplAttributes.NoInlining : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method should be inlined if possible.
/// </summary>
public bool IsAggressiveInlining
{
get => (ImplAttributes & MethodImplAttributes.AggressiveInlining) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.AggressiveInlining)
| (value ? MethodImplAttributes.AggressiveInlining : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the method contains hot code and should be aggressively optimized.
/// </summary>
public bool IsAggressiveOptimization
{
get => (ImplAttributes & MethodImplAttributes.AggressiveOptimization) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.AggressiveOptimization)
| (value ? MethodImplAttributes.AggressiveOptimization : 0);
}
/// <summary>
/// Gets or sets a value indicating that the JIT compiler should look for security mitigation attributes,
/// such as the user-defined <c>System.Runtime.CompilerServices.SecurityMitigationsAttribute</c>. If found,
/// the JIT compiler applies any related security mitigations. Available starting with .NET Framework 4.8.
/// </summary>
/// <remarks>
/// This is an undocumented flag and is currently not used:
/// Original addition: https://github.com/dotnet/dotnet-api-docs/pull/2253
/// Documentation removal: https://github.com/dotnet/dotnet-api-docs/pull/4652
/// </remarks>
public bool HasSecurityMitigations
{
get => (ImplAttributes & MethodImplAttributes.SecurityMitigations) != 0;
set => ImplAttributes = (ImplAttributes & ~MethodImplAttributes.SecurityMitigations)
| (value ? MethodImplAttributes.SecurityMitigations : 0);
}
/// <inheritdoc />
public virtual ModuleDefinition? Module => DeclaringType?.Module;
/// <summary>
/// Gets the type that defines the method.
/// </summary>
public TypeDefinition? DeclaringType
{
get => _declaringType.GetValue(this);
set => _declaringType.SetValue(value);
}
ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType;
ITypeDefOrRef? IMethodDefOrRef.DeclaringType => DeclaringType;
TypeDefinition? IOwnedCollectionElement<TypeDefinition>.Owner
{
get => DeclaringType;
set => DeclaringType = value;
}
/// <summary>
/// Gets a collection of parameter definitions that this method defines.
/// </summary>
/// <remarks>
/// This property might not reflect the list of actual parameters that the method defines and uses according
/// to the method signature. This property only reflects the list that is inferred from the ParamList column
/// in the metadata row. For the actual list of parameters, use the <see cref="Parameters"/> property instead.
/// </remarks>
public IList<ParameterDefinition> ParameterDefinitions
{
get
{
if (_parameterDefinitions is null)
Interlocked.CompareExchange(ref _parameterDefinitions, GetParameterDefinitions(), null);
return _parameterDefinitions;
}
}
/// <summary>
/// Gets a collection of parameters that the method signature defines.
/// </summary>
public ParameterCollection Parameters
{
get
{
if (_parameters is null)
Interlocked.CompareExchange(ref _parameters, new ParameterCollection(this), null);
return _parameters;
}
}
/// <summary>
/// Gets a value indicating whether the method is implemented using a method body. That is, whether the
/// <see cref="MethodBody"/> property is not <c>null</c>.
/// </summary>
[MemberNotNullWhen(true, nameof(MethodBody))]
public bool HasMethodBody => MethodBody is not null;
/// <summary>
/// Gets or sets the body of the method.
/// </summary>
/// <remarks>
/// <para>
/// Updating this property does not automatically set the appropriate implementation attributes in the
/// <see cref="ImplAttributes"/>.
/// </para>
/// </remarks>
public MethodBody? MethodBody
{
get => _methodBody.GetValue(this);
set => _methodBody.SetValue(value);
}
/// <summary>
/// Gets or sets the managed CIL body of the method if available.
/// </summary>
/// <remarks>
/// <para>
/// If this property is set to <c>null</c>, it does not necessarily mean the method does not have a method body.
/// There could be an unmanaged method body assigned instead. See the <see cref="MethodBody"/> or
/// <see cref="HasMethodBody"/> properties instead.
/// </para>
/// <para>
/// Updating this property does not automatically set the appropriate implementation attributes in the
/// <see cref="ImplAttributes"/>.
/// </para>
/// </remarks>
public CilMethodBody? CilMethodBody
{
get => MethodBody as CilMethodBody;
set => MethodBody = value;
}
/// <summary>
/// Gets or sets the unmanaged native body of the method if available.
/// </summary>
/// <remarks>
/// <para>
/// If this property is set to <c>null</c>, it does not necessarily mean the method does not have a method body.
/// There could be a managed body assigned instead, or the current method body reader that the declaring module
/// uses does not support reading a certain type of native method body. See the <see cref="MethodBody"/> or
/// <see cref="HasMethodBody"/> properties instead.
/// </para>
/// <para>
/// Updating this property does not automatically set the appropriate implementation attributes in the
/// <see cref="ImplAttributes"/>.
/// </para>
/// </remarks>
public NativeMethodBody? NativeMethodBody
{
get => MethodBody as NativeMethodBody;
set => MethodBody = value;
}
/// <inheritdoc />
public ImplementationMap? ImplementationMap
{
get => _implementationMap.GetValue(this);
set
{
if (value?.MemberForwarded is not null)
throw new ArgumentException("Cannot add an implementation map that was already added to another member.");
if (_implementationMap.GetValue(this) is { } map)
map.MemberForwarded = null;
_implementationMap.SetValue(value);
if (value is not null)
value.MemberForwarded = this;
}
}
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <inheritdoc />
public IList<SecurityDeclaration> SecurityDeclarations
{
get
{
if (_securityDeclarations is null)
Interlocked.CompareExchange(ref _securityDeclarations, GetSecurityDeclarations(), null);
return _securityDeclarations;
}
}
/// <inheritdoc />
public IList<GenericParameter> GenericParameters
{
get
{
if (_genericParameters is null)
Interlocked.CompareExchange(ref _genericParameters, GetGenericParameters(), null);
return _genericParameters;
}
}
/// <summary>
/// Gets the semantics associated to this method (if available).
/// </summary>
public MethodSemantics? Semantics
{
get => _semantics.GetValue(this);
set => _semantics.SetValue(value);
}
/// <summary>
/// Gets a value indicating whether the method is a get method for a property.
/// </summary>
public bool IsGetMethod => Semantics is not null && (Semantics.Attributes & MethodSemanticsAttributes.Getter) != 0;
/// <summary>
/// Gets a value indicating whether the method is a set method for a property.
/// </summary>
public bool IsSetMethod => Semantics is not null && (Semantics.Attributes & MethodSemanticsAttributes.Setter) != 0;
/// <summary>
/// Gets a value indicating whether the method is an add method for an event.
/// </summary>
public bool IsAddMethod => Semantics is not null && (Semantics.Attributes & MethodSemanticsAttributes.AddOn) != 0;
/// <summary>
/// Gets a value indicating whether the method is a remove method for an event.
/// </summary>
public bool IsRemoveMethod => Semantics is not null && (Semantics.Attributes & MethodSemanticsAttributes.RemoveOn) != 0;
/// <summary>
/// Gets a value indicating whether the method is a fire method for an event.
/// </summary>
public bool IsFireMethod => Semantics is not null && (Semantics.Attributes & MethodSemanticsAttributes.Fire) != 0;
/// <summary>
/// Gets a value indicating whether the method is a (class) constructor.
/// </summary>
public bool IsConstructor => IsSpecialName && IsRuntimeSpecialName && Name?.Value is ".cctor" or ".ctor";
/// <summary>
/// Gets or sets the unmanaged export info assigned to this method (if available). This can be used to indicate
/// that a method needs to be exported in the final PE file as an unmanaged symbol.
/// </summary>
public UnmanagedExportInfo? ExportInfo
{
get => _exportInfo.GetValue(this);
set => _exportInfo.SetValue(value);
}
/// <summary>
/// Creates a new private static constructor for a type that is executed when its declaring type is loaded by the CLR.
/// </summary>
/// <param name="module">The target module the method will be added to.</param>
/// <returns>The constructor.</returns>
/// <remarks>
/// The resulting method's body will consist of a single <c>ret</c> instruction.
/// </remarks>
public static MethodDefinition CreateStaticConstructor(ModuleDefinition module)
{
var cctor = new MethodDefinition(".cctor",
MethodAttributes.Private
| MethodAttributes.Static
| MethodAttributes.SpecialName
| MethodAttributes.RuntimeSpecialName,
MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));
cctor.CilMethodBody = new CilMethodBody(cctor);
cctor.CilMethodBody.Instructions.Add(CilOpCodes.Ret);
return cctor;
}
/// <summary>
/// Creates a new public constructor for a type that is executed when its declaring type is loaded by the CLR.
/// </summary>
/// <param name="module">The target module the method will be added to.</param>
/// <param name="parameterTypes">An ordered list of types the parameters of the constructor should have.</param>
/// <returns>The constructor.</returns>
/// <remarks>
/// The resulting method's body will consist of a single <c>ret</c> instruction, and does not contain a call to
/// any of the declaring type's base classes. For an idiomatic .NET binary, this should be added.
/// </remarks>
public static MethodDefinition CreateConstructor(ModuleDefinition module, params TypeSignature[] parameterTypes)
{
var ctor = new MethodDefinition(".ctor",
MethodAttributes.Public
| MethodAttributes.SpecialName
| MethodAttributes.RuntimeSpecialName,
MethodSignature.CreateInstance(module.CorLibTypeFactory.Void, parameterTypes));
for (int i = 0; i < parameterTypes.Length; i++)
ctor.ParameterDefinitions.Add(new ParameterDefinition(null));
ctor.CilMethodBody = new CilMethodBody(ctor);
ctor.CilMethodBody.Instructions.Add(CilOpCodes.Ret);
return ctor;
}
MethodDefinition IMethodDescriptor.Resolve() => this;
/// <inheritdoc />
public bool IsImportedInModule(ModuleDefinition module)
{
return Module == module
&& (Signature?.IsImportedInModule(module) ?? false);
}
/// <summary>
/// Imports the method using the provided reference importer object.
/// </summary>
/// <param name="importer">The reference importer to use.</param>
/// <returns>The imported method.</returns>
public IMethodDefOrRef ImportWith(ReferenceImporter importer) => importer.ImportMethod(this);
/// <inheritdoc />
IImportable IImportable.ImportWith(ReferenceImporter importer) => ImportWith(importer);
IMemberDefinition IMemberDescriptor.Resolve() => this;
/// <inheritdoc />
public bool IsAccessibleFromType(TypeDefinition type)
{
if (DeclaringType is not { } declaringType || !declaringType.IsAccessibleFromType(type))
return false;
var comparer = new SignatureComparer();
bool isInSameAssembly = comparer.Equals(declaringType.Module, type.Module);
return IsPublic
|| isInSameAssembly && IsAssembly
|| comparer.Equals(DeclaringType, type);
// TODO: check if in the same family of declaring types.
}
/// <summary>
/// Obtains the name of the method definition.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual Utf8String? GetName() => null;
/// <summary>
/// Obtains the declaring type of the method definition.
/// </summary>
/// <returns>The declaring type.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="DeclaringType"/> property.
/// </remarks>
protected virtual TypeDefinition? GetDeclaringType() => null;
/// <summary>
/// Obtains the signature of the method definition.
/// </summary>
/// <returns>The signature.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Signature"/> property.
/// </remarks>
protected virtual MethodSignature? GetSignature() => null;
/// <summary>
/// Obtains the parameter definitions of the method definition.
/// </summary>
/// <returns>The signature.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="ParameterDefinitions"/> property.
/// </remarks>
protected virtual IList<ParameterDefinition> GetParameterDefinitions() =>
new OwnedCollection<MethodDefinition, ParameterDefinition>(this);
/// <summary>
/// Obtains the body of the method definition.
/// </summary>
/// <returns>The signature.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="MethodBody"/> property.
/// </remarks>
protected virtual MethodBody? GetBody() => null;
/// <summary>
/// Obtains the platform invoke information assigned to the method.
/// </summary>
/// <returns>The mapping.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="ImplementationMap"/> property.
/// </remarks>
protected virtual ImplementationMap? GetImplementationMap() => null;
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
/// <summary>
/// Obtains the list of security declarations assigned to the member.
/// </summary>
/// <returns>The security declarations</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="SecurityDeclarations"/> property.
/// </remarks>
protected virtual IList<SecurityDeclaration> GetSecurityDeclarations() =>
new OwnedCollection<IHasSecurityDeclaration, SecurityDeclaration>(this);
/// <summary>
/// Obtains the list of generic parameters this member declares.
/// </summary>
/// <returns>The generic parameters</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="GenericParameters"/> property.
/// </remarks>
protected virtual IList<GenericParameter> GetGenericParameters() =>
new OwnedCollection<IHasGenericParameters, GenericParameter>(this);
/// <summary>
/// Obtains the semantics associated to the method (if available).
/// </summary>
/// <returns>The semantics, or <c>null</c> if the method was not assigned semantics.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Semantics"/> property.
/// </remarks>
protected virtual MethodSemantics? GetSemantics() => null;
/// <summary>
/// Obtains the unmanaged export information associated to the method (if available).
/// </summary>
/// <returns>The export information or <c>null</c> if the method was not exported as a native symbol.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="ExportInfo"/> property.
/// </remarks>
protected virtual UnmanagedExportInfo? GetExportInfo() => null;
/// <inheritdoc />
public override string ToString() => FullName;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\MethodSpecificationTest.cs | AsmResolver.DotNet.Tests
| MethodSpecificationTest | ['private readonly SignatureComparer _comparer = new();'] | ['System', 'System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Generics', 'AsmResolver.PE.DotNet.Cil', 'Xunit'] | xUnit | net8.0 | public class MethodSpecificationTest
{
private readonly SignatureComparer _comparer = new();
[Fact]
public void ReadMethod()
{
var module = ModuleDefinition.FromFile(typeof(GenericsTestClass).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(typeof(GenericsTestClass)
.GetMethod(nameof(GenericsTestClass.MethodInstantiationFromGenericType))!.MetadataToken);
var call = method.CilMethodBody!.Instructions.First(i => i.OpCode.Code == CilCode.Call);
Assert.IsAssignableFrom<MethodSpecification>(call.Operand);
var specification = (MethodSpecification) call.Operand;
Assert.Equal("GenericMethodInGenericType", specification.Method!.Name);
}
[Fact]
public void ReadFullName()
{
var module = ModuleDefinition.FromFile(typeof(GenericsTestClass).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(typeof(GenericsTestClass)
.GetMethod(nameof(GenericsTestClass.MethodInstantiationFromGenericType))!.MetadataToken);
var call = method.CilMethodBody!.Instructions.First(i => i.OpCode.Code == CilCode.Call);
Assert.IsAssignableFrom<MethodSpecification>(call.Operand);
var specification = (MethodSpecification) call.Operand;
Assert.Equal(
"System.Void AsmResolver.DotNet.TestCases.Generics.GenericType`3<System.Byte, System.UInt16, System.UInt32>::GenericMethodInGenericType<System.SByte, System.Int16, System.Int32>()",
specification.FullName);
Assert.Equal(
"System.Void AsmResolver.DotNet.TestCases.Generics.GenericType`3<System.Byte, System.UInt16, System.UInt32>::GenericMethodInGenericType<?, ?, ?>()",
specification.Method!.FullName);
}
[Fact]
public void ReadSignature()
{
var module = ModuleDefinition.FromFile(typeof(GenericsTestClass).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(typeof(GenericsTestClass)
.GetMethod(nameof(GenericsTestClass.MethodInstantiationFromGenericType))!.MetadataToken);
var call = method.CilMethodBody!.Instructions.First(i => i.OpCode.Code == CilCode.Call);
Assert.IsAssignableFrom<MethodSpecification>(call.Operand);
var specification = (MethodSpecification) call.Operand;
Assert.Equal(
new GenericInstanceMethodSignature(
module.CorLibTypeFactory.SByte,
module.CorLibTypeFactory.Int16,
module.CorLibTypeFactory.Int32),
specification.Signature,
_comparer);
}
[Fact]
public void InstantiateGenericMethod()
{
var module = ModuleDefinition.FromFile(typeof(GenericsTestClass).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(typeof(NonGenericType)
.GetMethod(nameof(NonGenericType.GenericMethodInNonGenericType))!.MetadataToken);
var specification = method.MakeGenericInstanceMethod(
module.CorLibTypeFactory.SByte,
module.CorLibTypeFactory.Int16,
module.CorLibTypeFactory.Int32);
Assert.Equal(
new GenericInstanceMethodSignature(
module.CorLibTypeFactory.SByte,
module.CorLibTypeFactory.Int16,
module.CorLibTypeFactory.Int32),
specification.Signature,
_comparer);
}
[Fact]
public void InstantiateGenericMethodWithWrongNumberOfArgumentsShouldThrow()
{
var module = ModuleDefinition.FromFile(typeof(GenericsTestClass).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(typeof(NonGenericType)
.GetMethod(nameof(NonGenericType.GenericMethodInNonGenericType))!.MetadataToken);
Assert.Throws<ArgumentException>(() => method.MakeGenericInstanceMethod(
module.CorLibTypeFactory.SByte,
module.CorLibTypeFactory.Int16));
}
[Fact]
public void InstantiateNonGenericMethodShouldThrow()
{
var module = ModuleDefinition.FromFile(typeof(GenericsTestClass).Assembly.Location, TestReaderParameters);
var method = (MethodDefinition) module.LookupMember(typeof(NonGenericType)
.GetMethod(nameof(NonGenericType.NonGenericMethodInNonGenericType))!.MetadataToken);
Assert.Throws<ArgumentException>(() => method.MakeGenericInstanceMethod(
module.CorLibTypeFactory.SByte,
module.CorLibTypeFactory.Int16,
module.CorLibTypeFactory.Int32));
}
} | 212 | 5,351 | using System.Collections.Generic;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a reference to a generic method that is instantiated with type arguments.
/// </summary>
public class MethodSpecification : MetadataMember, IMethodDescriptor, IHasCustomAttribute
{
private readonly LazyVariable<MethodSpecification, IMethodDefOrRef?> _method;
private readonly LazyVariable<MethodSpecification, GenericInstanceMethodSignature?> _signature;
private IList<CustomAttribute>? _customAttributes;
/// <summary>
/// Creates a new empty method specification.
/// </summary>
/// <param name="token">The token of the specification.</param>
protected MethodSpecification(MetadataToken token)
: base(token)
{
_method = new LazyVariable<MethodSpecification, IMethodDefOrRef?>(x => x.GetMethod());
_signature = new LazyVariable<MethodSpecification, GenericInstanceMethodSignature?>(x => x.GetSignature());
}
/// <summary>
/// Creates a new reference to a generic instantiation of a method.
/// </summary>
/// <param name="method">The method to instantiate.</param>
/// <param name="signature">The instantiation signature.</param>
public MethodSpecification(IMethodDefOrRef? method, GenericInstanceMethodSignature? signature)
: this(new MetadataToken(TableIndex.MethodSpec,0))
{
Method = method;
Signature = signature;
}
/// <summary>
/// Gets or sets the method that was instantiated.
/// </summary>
public IMethodDefOrRef? Method
{
get => _method.GetValue(this);
set => _method.SetValue(value);
}
MethodSignature? IMethodDescriptor.Signature => Method?.Signature;
/// <summary>
/// Gets or sets the generic instantiation of the method.
/// </summary>
public GenericInstanceMethodSignature? Signature
{
get => _signature.GetValue(this);
set => _signature.SetValue(value);
}
/// <summary>
/// Gets or sets the name of the method specification.
/// </summary>
public Utf8String Name => Method?.Name ?? NullName;
string? INameProvider.Name => Name;
/// <inheritdoc />
public string FullName => MemberNameGenerator.GetMethodFullName(this);
/// <inheritdoc />
public ModuleDefinition? Module => Method?.Module;
/// <summary>
/// Gets the declaring type of the method.
/// </summary>
public ITypeDefOrRef? DeclaringType => Method?.DeclaringType;
ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType;
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <inheritdoc />
public MethodDefinition? Resolve() => Method?.Resolve();
/// <inheritdoc />
public bool IsImportedInModule(ModuleDefinition module)
{
return (Method?.IsImportedInModule(module) ?? false)
&& (Signature?.IsImportedInModule(module) ?? false);
}
/// <summary>
/// Imports the method specification using the provided reference importer.
/// </summary>
/// <param name="importer">The reference importer to use.</param>
/// <returns>The imported method specification.</returns>
public MethodSpecification ImportWith(ReferenceImporter importer) => importer.ImportMethod(this);
/// <inheritdoc />
IImportable IImportable.ImportWith(ReferenceImporter importer) => ImportWith(importer);
IMemberDefinition? IMemberDescriptor.Resolve() => Resolve();
/// <summary>
/// Obtains the instantiated method.
/// </summary>
/// <returns>The method.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Method"/> property.
/// </remarks>
protected virtual IMethodDefOrRef? GetMethod() => null;
/// <summary>
/// Obtains the method instantiation signature.
/// </summary>
/// <returns>The signature.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Signature"/> property.
/// </remarks>
protected virtual GenericInstanceMethodSignature? GetSignature() => null;
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
/// <inheritdoc />
public override string ToString() => FullName;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\ModuleDefinitionTest.cs | AsmResolver.DotNet.Tests
| ModuleDefinitionTest | ['private static readonly SignatureComparer Comparer = new();', 'private const string NonWindowsPlatform = "Test loads a module from a base address, which is only supported on Windows.";'] | ['System', 'System.Collections.Generic', 'System.IO', 'System.Linq', 'System.Reflection', 'System.Runtime.InteropServices', 'AsmResolver.DotNet.Serialized', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.NestedClasses', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.Metadata.Tables', 'AsmResolver.PE.File', 'AsmResolver.PE.Win32Resources', 'Xunit', 'AsmResolver.PE.DotNet.Metadata.Tables.FileAttributes', 'AsmResolver.PE.DotNet.Metadata.Tables.TypeAttributes'] | xUnit | net8.0 | public class ModuleDefinitionTest
{
private static readonly SignatureComparer Comparer = new();
private const string NonWindowsPlatform = "Test loads a module from a base address, which is only supported on Windows.";
private static ModuleDefinition Rebuild(ModuleDefinition module)
{
using var stream = new MemoryStream();
module.Write(stream);
return ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
}
[SkippableFact]
public void LoadFromModule()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
var reflectionModule = typeof(ModuleDefinition).Assembly.ManifestModule;
var module = ModuleDefinition.FromModule(reflectionModule, TestReaderParameters);
Assert.Equal(reflectionModule.Name, module.Name);
}
[SkippableFact]
public void LoadFromDynamicModule()
{
Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
var reflectionModule = Assembly.Load(Properties.Resources.ActualLibrary).ManifestModule;
var module = ModuleDefinition.FromModule(reflectionModule, TestReaderParameters);
Assert.Equal("ActualLibrary.dll", module.Name);
}
[Fact]
public void LoadFromFileShouldPopulateResolverSearchDirectories()
{
string path = typeof(ModuleDefinitionTest).Assembly.Location;
var module = ModuleDefinition.FromFile(path, TestReaderParameters);
Assert.Contains(
Path.GetDirectoryName(path),
((AssemblyResolverBase) module.MetadataResolver.AssemblyResolver).SearchDirectories);
}
[Fact]
public void LoadFromBytesShouldLeaveSearchDirectoriesEmpty()
{
string path = typeof(ModuleDefinitionTest).Assembly.Location;
var module = ModuleDefinition.FromBytes(File.ReadAllBytes(path), TestReaderParameters);
Assert.DoesNotContain(
Path.GetDirectoryName(path),
((AssemblyResolverBase) module.MetadataResolver.AssemblyResolver).SearchDirectories);
}
[Fact]
public void LoadFromBytesWithWorkingDirectoryShouldPopulateSearchDirectories()
{
string path = typeof(ModuleDefinitionTest).Assembly.Location;
var module = ModuleDefinition.FromBytes(
File.ReadAllBytes(path),
new ModuleReaderParameters(Path.GetDirectoryName(path)));
Assert.Contains(
Path.GetDirectoryName(path),
((AssemblyResolverBase) module.MetadataResolver.AssemblyResolver).SearchDirectories);
}
[Fact]
public void LoadFromFileWithSameWorkingDirectoryShouldNotPopulateSearchDirectoriesTwice()
{
string path = typeof(ModuleDefinitionTest).Assembly.Location;
var module = ModuleDefinition.FromFile(path,
new ModuleReaderParameters(Path.GetDirectoryName(path)));
Assert.Equal(1, ((AssemblyResolverBase) module.MetadataResolver.AssemblyResolver)
.SearchDirectories.Count(x => x == Path.GetDirectoryName(path)));
}
[Fact]
public void LoadFromFileWithDifferentWorkingDirectoryShouldPopulateSearchDirectoriesTwice()
{
string path = typeof(ModuleDefinitionTest).Assembly.Location;
string otherPath = @"C:\other\path";
var module = ModuleDefinition.FromFile(path, new ModuleReaderParameters(otherPath));
var searchDirectories = ((AssemblyResolverBase) module.MetadataResolver.AssemblyResolver).SearchDirectories;
Assert.Contains(Path.GetDirectoryName(path), searchDirectories);
Assert.Contains(otherPath, searchDirectories);
}
[Fact]
public void ReadNameTest()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Equal("HelloWorld.exe", module.Name);
}
[Fact]
public void ReadMvidFromNormalMetadata()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_DoubleGuidStream, TestReaderParameters);
Assert.Equal(
new Guid(new byte[]
{
0x94, 0xe3, 0x75, 0xe2, 0x82, 0x8b, 0xac, 0x4c, 0xa3, 0x8c, 0xb3, 0x72, 0x4b, 0x81, 0xea, 0x05
}), module.Mvid);
}
[Fact]
public void ReadMvidFromEnCMetadata()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_DoubleGuidStream_EnC, TestReaderParameters);
Assert.Equal(
new Guid(new byte[]
{
0x8F, 0x6C, 0x77, 0x06, 0xEE, 0x44, 0x65, 0x41, 0xB0, 0xF7, 0x2D, 0xBD, 0x12, 0x7F, 0xE2, 0x1B
}), module.Mvid);
}
[Fact]
public void NameIsPersistentAfterRebuild()
{
const string newName = "HelloMars.exe";
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
module.Name = newName;
var newModule = Rebuild(module);
Assert.Equal(newName, newModule.Name);
}
[Fact]
public void ReadManifestModule()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.NotNull(module.Assembly);
Assert.Same(module, module.Assembly.ManifestModule);
}
[Fact]
public void ReadTypesNoNested()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Equal(new Utf8String[] { "<Module>", "Program" }, module.TopLevelTypes.Select(t => t.Name));
}
[Fact]
public void ReadTypesNested()
{
var module = ModuleDefinition.FromFile(typeof(TopLevelClass1).Assembly.Location, TestReaderParameters);
Assert.Equal(new Utf8String[]
{
"<Module>",
nameof(TopLevelClass1),
nameof(TopLevelClass2)
}, module.TopLevelTypes.Select(t => t.Name));
}
[Fact]
public void ReadMaliciousNestedClassLoop()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_MaliciousNestedClassLoop, TestReaderParameters);
Assert.Equal(new Utf8String[] { "<Module>", "Program" }, module.TopLevelTypes.Select(t => t.Name));
}
[Fact]
public void ReadMaliciousNestedClassLoop2()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_MaliciousNestedClassLoop2, TestReaderParameters);
Assert.Equal(
new HashSet<Utf8String> { "<Module>", "Program", "MaliciousEnclosingClass" },
new HashSet<Utf8String>(module.TopLevelTypes.Select(t => t.Name)));
var enclosingClass = module.TopLevelTypes.First(x => x.Name == "MaliciousEnclosingClass");
Assert.Single(enclosingClass.NestedTypes);
Assert.Single(enclosingClass.NestedTypes[0].NestedTypes);
Assert.Empty(enclosingClass.NestedTypes[0].NestedTypes[0].NestedTypes);
}
[Fact]
public void HelloWorldReadAssemblyReferences()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Single(module.AssemblyReferences);
Assert.Equal("mscorlib", module.AssemblyReferences[0].Name);
}
[Fact]
public void LookupTypeReference()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var member = module.LookupMember(new MetadataToken(TableIndex.TypeRef, 12));
var reference = Assert.IsAssignableFrom<TypeReference>(member);
Assert.Equal("System", reference.Namespace);
Assert.Equal("Object", reference.Name);
}
[Fact]
public void LookupTypeReferenceStronglyTyped()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var reference = module.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 12));
Assert.Equal("System", reference.Namespace);
Assert.Equal("Object", reference.Name);
}
[Fact]
public void TryLookupTypeReferenceStronglyTyped()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.True(module.TryLookupMember(new MetadataToken(TableIndex.TypeRef, 12), out TypeReference reference));
Assert.Equal("System", reference.Namespace);
Assert.Equal("Object", reference.Name);
}
[Fact]
public void LookupTypeDefinition()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var member = module.LookupMember(new MetadataToken(TableIndex.TypeDef, 2));
var definition = Assert.IsAssignableFrom<TypeDefinition>(member);
Assert.Equal("HelloWorld", definition.Namespace);
Assert.Equal("Program", definition.Name);
}
[Fact]
public void LookupTypeDefinitionStronglyTyped()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var definition = module.LookupMember<TypeDefinition>(new MetadataToken(TableIndex.TypeDef, 2));
Assert.Equal("HelloWorld", definition.Namespace);
Assert.Equal("Program", definition.Name);
}
[Fact]
public void LookupAssemblyReference()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var member = module.LookupMember(new MetadataToken(TableIndex.AssemblyRef, 1));
var reference = Assert.IsAssignableFrom<AssemblyReference>(member);
Assert.Equal("mscorlib", reference.Name);
Assert.Same(module.AssemblyReferences[0], reference);
}
[Fact]
public void LookupAssemblyReferenceStronglyTyped()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var reference = module.LookupMember<AssemblyReference>(new MetadataToken(TableIndex.AssemblyRef, 1));
Assert.Equal("mscorlib", reference.Name);
Assert.Same(module.AssemblyReferences[0], reference);
}
[Fact]
public void LookupModuleReference()
{
var module = ModuleDefinition.FromFile(Path.Combine("Resources", "Manifest.exe"), TestReaderParameters);
var member = module.LookupMember(new MetadataToken(TableIndex.ModuleRef, 1));
var reference =Assert.IsAssignableFrom<ModuleReference>(member);
Assert.Equal("MyModel.netmodule", reference.Name);
Assert.Same(module.ModuleReferences[0], reference);
}
[Fact]
public void LookupModuleReferenceStronglyTyped()
{
var module = ModuleDefinition.FromFile(Path.Combine("Resources", "Manifest.exe"), TestReaderParameters);
var reference = module.LookupMember<ModuleReference>(new MetadataToken(TableIndex.ModuleRef, 1));
Assert.Equal("MyModel.netmodule", reference.Name);
Assert.Same(module.ModuleReferences[0], reference);
}
[Fact]
public void EmptyModuleShouldAlwaysContainCorLibReference()
{
// Issue #39 (https://github.com/Washi1337/AsmResolver/issues/39)
var module = new ModuleDefinition("TestModule");
var corLib = module.CorLibTypeFactory.CorLibScope;
using var stream = new MemoryStream();
module.Write(stream);
var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
var comparer = new SignatureComparer();
Assert.Contains(newModule.AssemblyReferences, reference => comparer.Equals(corLib, reference));
}
[Fact]
public void CreateNewCorLibFactory()
{
var module = new ModuleDefinition("MySampleModule");
Assert.NotNull(module.CorLibTypeFactory);
Assert.NotNull(module.CorLibTypeFactory.CorLibScope);
Assert.NotNull(module.CorLibTypeFactory.Void);
}
[Fact]
public void AddingTypeIsPersistentAfterRebuild()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var newType = new TypeDefinition("SomeNamespace", "SomeType",
TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Sealed);
module.TopLevelTypes.Add(newType);
var newModule = Rebuild(module);
var comparer = new SignatureComparer();
Assert.Contains(newModule.TopLevelTypes, t => comparer.Equals(newType, t));
}
[Fact]
public void NewFW40ModuleShouldAlwaysContainModuleType()
{
var module = new ModuleDefinition("TestModule");
Assert.NotNull(module.GetModuleType());
}
[Fact]
public void NewModuleShouldAlwaysContainModuleType()
{
var module = new ModuleDefinition("TestModule", KnownCorLibs.NetStandard_v2_1_0_0);
Assert.NotNull(module.GetModuleType());
}
[Fact]
public void GetOrCreateModuleConstructorShouldAddNewConstructorIfNotPresent()
{
var module = new ModuleDefinition("TestModule", KnownCorLibs.NetStandard_v2_1_0_0);
var cctor = module.GetOrCreateModuleConstructor();
Assert.Contains(cctor, module.GetModuleType().Methods);
}
[Fact]
public void GetOrCreateModuleConstructorShouldGetExistingConstructorIfPresent()
{
var module = new ModuleDefinition("TestModule", KnownCorLibs.NetStandard_v2_1_0_0);
var cctor = module.GetOrCreateModuleConstructor();
var cctor2 = module.GetOrCreateModuleConstructor();
Assert.Same(cctor, cctor2);
}
[Fact]
public void PersistentResources()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
// Add new directory.
const string directoryName = "Test";
var entryData = new byte[] { 0, 1, 2, 3, 4 };
var directory = new ResourceDirectory(directoryName)
{
Entries =
{
new ResourceDirectory(1)
{
Entries = { new ResourceData(1234, new DataSegment(entryData)) }
}
}
};
module.NativeResourceDirectory!.Entries.Add(directory);
// Write and rebuild.
using var stream = new MemoryStream();
module.Write(stream);
var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
// Assert contents.
var newDirectory = (ResourceDirectory) newModule.NativeResourceDirectory!.Entries
.First(entry => entry.Name == directoryName);
newDirectory = (ResourceDirectory)newDirectory.Entries[0];
var newData = (ResourceData)newDirectory.Entries[0];
var newContents = (IReadableSegment)newData.Contents!;
Assert.Equal(entryData, newContents.ToArray());
}
[Fact]
public void PersistentTimeStamp()
{
var time = new DateTime(2020, 1, 2, 18, 30, 34);
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
module.TimeDateStamp = time;
var image = module.ToPEImage();
Assert.Equal(time, image.TimeDateStamp);
}
[Fact]
public void PersistentExportedType()
{
var module = new ModuleDefinition("SomeModule.exe");
var assembly = new AssemblyReference("SomeAssembly", new Version(1, 0, 0, 0));
var type = new ExportedType(assembly, "SomeNamespace", "SomeType");
module.AssemblyReferences.Add(assembly);
module.ExportedTypes.Add(type);
var newModule = Rebuild(module);
var newType = Assert.Single(newModule.ExportedTypes);
Assert.Equal(type, newType, new SignatureComparer());
}
[Fact]
public void PersistentFileReferences()
{
var module = new ModuleDefinition("SomeModule.exe");
var file = new FileReference("SubModule.netmodule", FileAttributes.ContainsMetadata);
module.FileReferences.Add(file);
var newModule = Rebuild(module);
var newFile = Assert.Single(newModule.FileReferences);
Assert.NotNull(newFile);
Assert.Equal(file.Name, newFile.Name);
}
[Fact]
public void DetectTargetNetFramework40()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.True(module.OriginalTargetRuntime.IsNetFramework);
Assert.Contains(DotNetRuntimeInfo.NetFramework, module.OriginalTargetRuntime.Name);
Assert.Equal(4, module.OriginalTargetRuntime.Version.Major);
Assert.Equal(0, module.OriginalTargetRuntime.Version.Minor);
}
[Fact]
public void DetectTargetNetCore()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_NetCore, TestReaderParameters);
Assert.True(module.OriginalTargetRuntime.IsNetCoreApp);
Assert.Contains(DotNetRuntimeInfo.NetCoreApp, module.OriginalTargetRuntime.Name);
Assert.Equal(2, module.OriginalTargetRuntime.Version.Major);
Assert.Equal(2, module.OriginalTargetRuntime.Version.Minor);
}
[Fact]
public void DetectTargetStandard()
{
var module = ModuleDefinition.FromFile(typeof(TestCases.Types.Class).Assembly.Location, TestReaderParameters);
Assert.True(module.OriginalTargetRuntime.IsNetStandard);
Assert.Contains(DotNetRuntimeInfo.NetStandard, module.OriginalTargetRuntime.Name);
Assert.Equal(2, module.OriginalTargetRuntime.Version.Major);
}
[Fact]
public void NewModuleShouldContainSingleReferenceToCorLib()
{
var module = new ModuleDefinition("SomeModule", KnownCorLibs.NetStandard_v2_0_0_0);
var reference = Assert.Single(module.AssemblyReferences);
Assert.Equal(KnownCorLibs.NetStandard_v2_0_0_0, reference, Comparer);
}
[Fact]
public void RewriteSystemPrivateCoreLib()
{
string runtimePath = DotNetCorePathProvider.Default
.GetRuntimePathCandidates("Microsoft.NETCore.App", new Version(3, 1, 0))
.FirstOrDefault() ?? throw new InvalidOperationException(".NET Core 3.1 is not installed.");
var module = ModuleDefinition.FromFile(Path.Combine(runtimePath, "System.Private.CoreLib.dll"), TestReaderParameters);
using var stream = new MemoryStream();
module.Write(stream);
}
[Fact]
public void RewriteSystemRuntime()
{
string runtimePath = DotNetCorePathProvider.Default
.GetRuntimePathCandidates("Microsoft.NETCore.App", new Version(3, 1, 0))
.FirstOrDefault() ?? throw new InvalidOperationException(".NET Core 3.1 is not installed.");
var module = ModuleDefinition.FromFile(Path.Combine(runtimePath, "System.Runtime.dll"), TestReaderParameters);
using var stream = new MemoryStream();
module.Write(stream);
}
[Fact]
public void RewriteSystemPrivateXml()
{
string runtimePath = DotNetCorePathProvider.Default
.GetRuntimePathCandidates("Microsoft.NETCore.App", new Version(3, 1, 0))
.FirstOrDefault() ?? throw new InvalidOperationException(".NET Core 3.1 is not installed.");
var module = ModuleDefinition.FromFile(Path.Combine(runtimePath, "System.Private.Xml.dll"), TestReaderParameters);
using var stream = new MemoryStream();
module.Write(stream);
}
[Fact]
public void GetModuleTypeNetFramework()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.ModuleCctorNetFramework, TestReaderParameters);
// Module type should exist.
var type = module.GetModuleType();
Assert.NotNull(type);
Assert.Equal("CustomModuleType", type.Name);
// Creating module type should give us the existing type.
Assert.Same(type, module.GetOrCreateModuleType());
}
[Fact]
public void GetModuleTypeNet6()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.ModuleCctorNet6, TestReaderParameters);
// Module type should exist.
var type = module.GetModuleType();
Assert.NotNull(type);
Assert.Equal("<Module>", type.Name);
// Creating module type should give us the existing type.
Assert.Same(type, module.GetOrCreateModuleType());
}
[Fact]
public void GetModuleTypeAbsentNet6()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.ModuleCctorAbsentNet6, TestReaderParameters);
// Module type should not exist.
var type = module.GetModuleType();
Assert.Null(type);
// Creating should add it to the module.
type = module.GetOrCreateModuleType();
Assert.NotNull(type);
Assert.Same(type, module.GetModuleType());
}
[Fact]
public void GetModuleTypeLookalikeNet6()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.ModuleCctorLookalikeNet6, TestReaderParameters);
// Module type should not exist.
var type = module.GetModuleType();
Assert.Null(type);
// Creating should add it to the module.
type = module.GetOrCreateModuleType();
Assert.NotNull(type);
Assert.Same(type, module.GetModuleType());
}
[Theory]
[InlineData(false, false, false)]
[InlineData(false, true, false)]
[InlineData(true, false, true)]
[InlineData(true, true, true)]
public void IsLoadedAs32BitAnyCPUModule(bool assume32Bit, bool canLoadAs32Bit, bool expected)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Equal(expected, module.IsLoadedAs32Bit(assume32Bit, canLoadAs32Bit));
}
[Theory]
[InlineData(false, false, false)]
[InlineData(false, true, true)]
[InlineData(true, false, true)]
[InlineData(true, true, true)]
public void IsLoadedAs32BitAnyCPUModulePrefer32Bit(bool assume32Bit, bool canLoadAs32Bit, bool expected)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
module.IsBit32Preferred = true;
Assert.Equal(expected, module.IsLoadedAs32Bit(assume32Bit, canLoadAs32Bit));
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void IsLoadedAs32Bit64BitModule(bool assume32Bit, bool canLoadAs32Bit)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
module.MachineType = MachineType.Amd64;
Assert.False(module.IsLoadedAs32Bit(assume32Bit, canLoadAs32Bit));
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void IsLoadedAs32Bit32BitModule(bool assume32Bit, bool canLoadAs32Bit)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
module.MachineType = MachineType.I386;
module.IsBit32Required = true;
Assert.True(module.IsLoadedAs32Bit(assume32Bit, canLoadAs32Bit));
}
} | 630 | 26,405 | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.DotNet.Builder;
using AsmResolver.DotNet.Serialized;
using AsmResolver.DotNet.Signatures;
using AsmResolver.IO;
using AsmResolver.PE;
using AsmResolver.PE.Builder;
using AsmResolver.PE.Debug;
using AsmResolver.PE.DotNet;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.File;
using AsmResolver.PE.Platforms;
using AsmResolver.PE.Win32Resources;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a single module in a .NET assembly. A module definition is the root object of any .NET module and
/// defines types, as well as any resources and referenced assemblies.
/// </summary>
public class ModuleDefinition :
MetadataMember,
IResolutionScope,
IHasCustomAttribute,
IOwnedCollectionElement<AssemblyDefinition>
{
private readonly LazyVariable<ModuleDefinition, Utf8String?> _name;
private readonly LazyVariable<ModuleDefinition, Guid> _mvid;
private readonly LazyVariable<ModuleDefinition, Guid> _encId;
private readonly LazyVariable<ModuleDefinition, Guid> _encBaseId;
private IList<TypeDefinition>? _topLevelTypes;
private IList<AssemblyReference>? _assemblyReferences;
private IList<CustomAttribute>? _customAttributes;
private readonly LazyVariable<ModuleDefinition, IManagedEntryPoint?> _managedEntryPoint;
private IList<ModuleReference>? _moduleReferences;
private IList<FileReference>? _fileReferences;
private IList<ManifestResource>? _resources;
private IList<ExportedType>? _exportedTypes;
private TokenAllocator? _tokenAllocator;
private readonly LazyVariable<ModuleDefinition, string> _runtimeVersion;
private readonly LazyVariable<ModuleDefinition, ResourceDirectory?> _nativeResources;
private IList<DebugDataEntry>? _debugData;
private ReferenceImporter? _defaultImporter;
/// <summary>
/// Reads a .NET module from the provided input buffer.
/// </summary>
/// <param name="buffer">The raw contents of the executable file to load.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromBytes(byte[] buffer) =>
FromBytes(buffer, new ModuleReaderParameters());
/// <summary>
/// Reads a .NET module from the provided input buffer.
/// </summary>
/// <param name="buffer">The raw contents of the executable file to load.</param>
/// <param name="readerParameters">The parameters to use while reading the module.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromBytes(byte[] buffer, ModuleReaderParameters readerParameters) =>
FromImage(PEImage.FromBytes(buffer, readerParameters.PEReaderParameters), readerParameters);
/// <summary>
/// Reads a .NET module from the provided input file.
/// </summary>
/// <param name="filePath">The file path to the input executable to load.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromFile(string filePath) =>
FromFile(filePath, new ModuleReaderParameters(Path.GetDirectoryName(filePath)));
/// <summary>
/// Reads a .NET module from the provided input file.
/// </summary>
/// <param name="filePath">The file path to the input executable to load.</param>
/// <param name="readerParameters">The parameters to use while reading the module.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromFile(string filePath, ModuleReaderParameters readerParameters) =>
FromImage(PEImage.FromFile(filePath, readerParameters.PEReaderParameters), readerParameters);
/// <summary>
/// Reads a .NET module from the provided input file.
/// </summary>
/// <param name="file">The portable executable file to load.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromFile(IInputFile file) => FromFile(file, new ModuleReaderParameters());
/// <summary>
/// Reads a .NET module from the provided input file.
/// </summary>
/// <param name="file">The portable executable file to load.</param>
/// <param name="readerParameters">The parameters to use while reading the module.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromFile(IInputFile file, ModuleReaderParameters readerParameters) =>
FromImage(PEImage.FromFile(file, readerParameters.PEReaderParameters), readerParameters);
/// <summary>
/// Reads a .NET module from the provided input file.
/// </summary>
/// <param name="file">The portable executable file to load.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromFile(PEFile file) => FromFile(file, new ModuleReaderParameters());
/// <summary>
/// Reads a .NET module from the provided input file.
/// </summary>
/// <param name="file">The portable executable file to load.</param>
/// <param name="readerParameters">The parameters to use while reading the module.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromFile(PEFile file, ModuleReaderParameters readerParameters) =>
FromImage(PEImage.FromFile(file, readerParameters.PEReaderParameters), readerParameters);
/// <summary>
/// Reads a mapped .NET module starting at the provided module base address (HINSTANCE).
/// </summary>
/// <param name="hInstance">The HINSTANCE or base address of the module.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromModuleBaseAddress(IntPtr hInstance) =>
FromModuleBaseAddress(hInstance, new ModuleReaderParameters());
/// <summary>
/// Reads a mapped .NET module starting at the provided module base address (HINSTANCE).
/// </summary>
/// <param name="hInstance">The HINSTANCE or base address of the module.</param>
/// <param name="readerParameters">The parameters to use while reading the module.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromModuleBaseAddress(IntPtr hInstance, ModuleReaderParameters readerParameters) =>
FromImage(PEImage.FromModuleBaseAddress(hInstance, readerParameters.PEReaderParameters), readerParameters);
/// <summary>
/// Reads a .NET module starting at the provided module base address (HINSTANCE).
/// </summary>
/// <param name="hInstance">The HINSTANCE or base address of the module.</param>
/// <param name="mode">Indicates how the input PE file is mapped.</param>
/// <param name="readerParameters">The parameters to use while reading the module.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromModuleBaseAddress(IntPtr hInstance, PEMappingMode mode, ModuleReaderParameters readerParameters) =>
FromImage(PEImage.FromModuleBaseAddress(hInstance, mode, readerParameters.PEReaderParameters), readerParameters);
/// <summary>
/// Opens a module from an instance of a <see cref="System.Reflection.Module"/>.
/// </summary>
/// <param name="module">The reflection module to load.</param>
/// <returns>The module.</returns>
public static ModuleDefinition FromModule(Module module) => FromModule(module, new ModuleReaderParameters());
/// <summary>
/// Opens a module from an instance of a <see cref="System.Reflection.Module"/>.
/// </summary>
/// <param name="module">The reflection module to load.</param>
/// <param name="readerParameters">The parameters to use while reading the module.</param>
/// <returns>The module.</returns>
public static ModuleDefinition FromModule(Module module, ModuleReaderParameters readerParameters)
{
if (!ReflectionHacks.TryGetHINSTANCE(module, out var handle))
throw new NotSupportedException("The current platform does not support getting the base address of an instance of System.Reflection.Module.");
if (handle == -1)
throw new NotSupportedException("Provided module does not have a module base address.");
// Dynamically loaded modules are in their unmapped form, as opposed to modules loaded normally by the
// Windows PE loader. They also have a fully qualified name "<Unknown>" or similar.
string name = module.FullyQualifiedName;
var mappingMode = name[0] == '<' && name[name.Length - 1] == '>'
? PEMappingMode.Unmapped
: PEMappingMode.Mapped;
// Load from base address.
return FromModuleBaseAddress(handle, mappingMode, readerParameters);
}
/// <summary>
/// Reads a .NET module from the provided data source.
/// </summary>
/// <param name="dataSource">The data source to read from.</param>
/// <param name="mode">Indicates how the input PE file is mapped.</param>
/// <returns>The module that was read.</returns>
/// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception>
public static ModuleDefinition FromDataSource(IDataSource dataSource, PEMappingMode mode = PEMappingMode.Unmapped) =>
FromReader(new BinaryStreamReader(dataSource, dataSource.BaseAddress, 0, (uint) dataSource.Length), mode);
/// <summary>
/// Reads a .NET module from the provided data source.
/// </summary>
/// <param name="dataSource">The data source to read from.</param>
/// <param name="mode">Indicates how the input PE file is mapped.</param>
/// <param name="readerParameters">The parameters to use while reading the module.</param>
/// <returns>The module that was read.</returns>
/// <exception cref="BadImageFormatException">Occurs when the file does not follow the PE file format.</exception>
public static ModuleDefinition FromDataSource(IDataSource dataSource, PEMappingMode mode, ModuleReaderParameters readerParameters) =>
FromReader(new BinaryStreamReader(dataSource, dataSource.BaseAddress, 0, (uint) dataSource.Length), mode, readerParameters);
/// <summary>
/// Reads a .NET module from an input stream.
/// </summary>
/// <param name="reader">The input stream pointing at the beginning of the executable to load.</param>
/// <param name="mode">Indicates the input PE is mapped or unmapped.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromReader(in BinaryStreamReader reader, PEMappingMode mode = PEMappingMode.Unmapped) =>
FromFile(PEFile.FromReader(reader, mode));
/// <summary>
/// Reads a .NET module from an input stream.
/// </summary>
/// <param name="reader">The input stream pointing at the beginning of the executable to load.</param>
/// <param name="mode">Indicates the input PE is mapped or unmapped.</param>
/// <param name="readerParameters">The parameters to use while reading the module.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromReader(in BinaryStreamReader reader, PEMappingMode mode, ModuleReaderParameters readerParameters) =>
FromImage(PEImage.FromReader(reader, mode, readerParameters.PEReaderParameters), readerParameters);
/// <summary>
/// Initializes a .NET module from a PE image.
/// </summary>
/// <param name="peImage">The image containing the .NET metadata.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET metadata directory.</exception>
public static ModuleDefinition FromImage(PEImage peImage)
{
var moduleParameters = new ModuleReaderParameters(Path.GetDirectoryName(peImage.FilePath))
{
PEReaderParameters = peImage is SerializedPEImage serializedImage
? serializedImage.ReaderContext.Parameters
: new PEReaderParameters()
};
return FromImage(peImage, moduleParameters);
}
/// <summary>
/// Initializes a .NET module from a PE image.
/// </summary>
/// <param name="peImage">The image containing the .NET metadata.</param>
/// <param name="readerParameters">The parameters to use while reading the module.</param>
/// <returns>The module.</returns>
/// <exception cref="BadImageFormatException">Occurs when the image does not contain a valid .NET data directory.</exception>
public static ModuleDefinition FromImage(PEImage peImage, ModuleReaderParameters readerParameters) =>
new SerializedModuleDefinition(peImage, readerParameters);
// Disable non-nullable property initialization warnings for the CorLibTypeFactory, RuntimeContext and
// MetadataResolver properties. These are expected to be initialized by constructors that use this base
// constructor.
#pragma warning disable 8618
/// <summary>
/// Initializes a new empty module with the provided metadata token.
/// </summary>
/// <param name="token">The metadata token.</param>
protected ModuleDefinition(MetadataToken token)
: base(token)
{
_name = new LazyVariable<ModuleDefinition, Utf8String?>(x => x.GetName());
_mvid = new LazyVariable<ModuleDefinition, Guid>(x => x.GetMvid());
_encId = new LazyVariable<ModuleDefinition, Guid>(x => x.GetEncId());
_encBaseId = new LazyVariable<ModuleDefinition, Guid>(x => x.GetEncBaseId());
_managedEntryPoint = new LazyVariable<ModuleDefinition, IManagedEntryPoint?>(x => x.GetManagedEntryPoint());
_runtimeVersion = new LazyVariable<ModuleDefinition, string>(x => x.GetRuntimeVersion());
_nativeResources = new LazyVariable<ModuleDefinition, ResourceDirectory?>(x => x.GetNativeResources());
Attributes = DotNetDirectoryFlags.ILOnly;
}
#pragma warning restore 8618
/// <summary>
/// Defines a new .NET module that references mscorlib version 4.0.0.0.
/// </summary>
/// <param name="name">The name of the module.</param>
/// <remarks>
/// This constructor co-exists with the Utf8String overload for backwards compatibility.
/// </remarks>
public ModuleDefinition(string? name)
: this((Utf8String?) name)
{
}
/// <summary>
/// Defines a new .NET module that references mscorlib version 4.0.0.0.
/// </summary>
/// <param name="name">The name of the module.</param>
public ModuleDefinition(Utf8String? name)
: this(new MetadataToken(TableIndex.Module, 0))
{
Name = name;
CorLibTypeFactory = CorLibTypeFactory.CreateMscorlib40TypeFactory(this);
OriginalTargetRuntime = DetectTargetRuntime();
RuntimeContext = new RuntimeContext(OriginalTargetRuntime);
MetadataResolver = new DefaultMetadataResolver(RuntimeContext.AssemblyResolver);
TopLevelTypes.Add(new TypeDefinition(null, TypeDefinition.ModuleTypeName, 0));
}
/// <summary>
/// Defines a new .NET module.
/// </summary>
/// <param name="name">The name of the module.</param>
/// <param name="corLib">The reference to the common object runtime (COR) library that this module will use.</param>
public ModuleDefinition(string? name, AssemblyReference corLib)
: this(new MetadataToken(TableIndex.Module, 0))
{
Name = name;
CorLibTypeFactory = new CorLibTypeFactory(corLib.ImportWith(DefaultImporter));
OriginalTargetRuntime = DetectTargetRuntime();
RuntimeContext = new RuntimeContext(OriginalTargetRuntime);
MetadataResolver = new DefaultMetadataResolver(RuntimeContext.AssemblyResolver);
TopLevelTypes.Add(new TypeDefinition(null, TypeDefinition.ModuleTypeName, 0));
}
/// <summary>
/// When this module was read from the disk, gets the file path to the module.
/// </summary>
public string? FilePath
{
get;
internal set;
}
/// <summary>
/// Gets the underlying object providing access to the data directory containing .NET metadata (if available).
/// </summary>
/// <remarks>
/// When this property is <c>null</c>, the module is a new module that is not yet assembled.
/// </remarks>
public virtual DotNetDirectory? DotNetDirectory
{
get;
} = null;
/// <summary>
/// Gets the object describing the current active runtime context the module is loaded in.
/// </summary>
public RuntimeContext RuntimeContext
{
get;
protected set;
}
/// <summary>
/// Gets the runtime that this module was targeted for at compile-time.
/// </summary>
public DotNetRuntimeInfo OriginalTargetRuntime
{
get;
protected set;
}
/// <summary>
/// Gets the parent assembly that defines this module.
/// </summary>
public AssemblyDefinition? Assembly
{
get;
internal set;
}
/// <inheritdoc />
AssemblyDefinition? IOwnedCollectionElement<AssemblyDefinition>.Owner
{
get => Assembly;
set => Assembly = value;
}
/// <inheritdoc />
ModuleDefinition IModuleProvider.Module => this;
/// <summary>
/// Gets or sets the name of the module.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the module definition table.
/// </remarks>
public Utf8String? Name
{
get => _name.GetValue(this);
set => _name.SetValue(value);
}
string? INameProvider.Name => Name;
/// <summary>
/// Gets or sets the generation number of the module.
/// </summary>
/// <remarks>
/// <para>
/// This value is reserved and should be set to zero.
/// </para>
/// <para>
/// This property corresponds to the Generation column in the module definition table.
/// </para>
/// </remarks>
public ushort Generation
{
get;
set;
}
/// <summary>
/// Gets or sets the unique identifier to distinguish between two versions
/// of the same module.
/// </summary>
/// <remarks>
/// This property corresponds to the MVID column in the module definition table.
/// </remarks>
public Guid Mvid
{
get => _mvid.GetValue(this);
set => _mvid.SetValue(value);
}
/// <summary>
/// Gets or sets the unique identifier to distinguish between two edit-and-continue generations.
/// </summary>
/// <remarks>
/// This property corresponds to the EncId column in the module definition table.
/// </remarks>
public Guid EncId
{
get => _encId.GetValue(this);
set => _encId.SetValue(value);
}
/// <summary>
/// Gets or sets the base identifier of an edit-and-continue generation.
/// </summary>
/// <remarks>
/// This property corresponds to the EncBaseId column in the module definition table.
/// </remarks>
public Guid EncBaseId
{
get => _encBaseId.GetValue(this);
set => _encBaseId.SetValue(value);
}
/// <summary>
/// Gets or sets the attributes associated to the underlying .NET directory of this module.
/// </summary>
public DotNetDirectoryFlags Attributes
{
get;
set;
}
/// <summary>
/// Gets an object responsible for assigning new <see cref="MetadataToken"/> to members
/// </summary>
public TokenAllocator TokenAllocator
{
get
{
if (_tokenAllocator is null)
Interlocked.CompareExchange(ref _tokenAllocator, new TokenAllocator(this), null);
return _tokenAllocator;
}
}
/// <summary>
/// Gets or sets a value indicating whether the .NET module only contains CIL code or also contains
/// code targeting other architectures.
/// </summary>
public bool IsILOnly
{
get => (Attributes & DotNetDirectoryFlags.ILOnly) != 0;
set => Attributes = (Attributes & ~DotNetDirectoryFlags.ILOnly)
| (value ? DotNetDirectoryFlags.ILOnly : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the .NET module requires a 32-bit environment to run.
/// </summary>
public bool IsBit32Required
{
get => (Attributes & DotNetDirectoryFlags.Bit32Required) != 0;
set => Attributes = (Attributes & ~DotNetDirectoryFlags.Bit32Required)
| (value ? DotNetDirectoryFlags.Bit32Required : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the .NET module is a library.
/// </summary>
public bool IsILLibrary
{
get => (Attributes & DotNetDirectoryFlags.ILLibrary) != 0;
set => Attributes = (Attributes & ~DotNetDirectoryFlags.ILLibrary)
| (value ? DotNetDirectoryFlags.ILLibrary : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the .NET module is signed with a strong name.
/// </summary>
public bool IsStrongNameSigned
{
get => (Attributes & DotNetDirectoryFlags.StrongNameSigned) != 0;
set => Attributes = (Attributes & ~DotNetDirectoryFlags.StrongNameSigned)
| (value ? DotNetDirectoryFlags.StrongNameSigned : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the .NET module has a native entry point or not.
/// </summary>
public bool HasNativeEntryPoint
{
get => (Attributes & DotNetDirectoryFlags.NativeEntryPoint) != 0;
set => Attributes = (Attributes & ~DotNetDirectoryFlags.NativeEntryPoint)
| (value ? DotNetDirectoryFlags.NativeEntryPoint : 0);
}
/// <summary>
/// Gets or sets a value indicating whether debug data is tracked in this .NET module.
/// </summary>
public bool TrackDebugData
{
get => (Attributes & DotNetDirectoryFlags.TrackDebugData) != 0;
set => Attributes = (Attributes & ~DotNetDirectoryFlags.TrackDebugData)
| (value ? DotNetDirectoryFlags.TrackDebugData : 0);
}
/// <summary>
/// Gets or sets a value indicating whether the .NET module prefers a 32-bit environment to run in.
/// </summary>
public bool IsBit32Preferred
{
get => (Attributes & DotNetDirectoryFlags.Bit32Preferred) != 0;
set => Attributes = (Attributes & ~DotNetDirectoryFlags.Bit32Preferred)
| (value ? DotNetDirectoryFlags.Bit32Preferred : 0);
}
/// <summary>
/// Gets or sets the machine type that the underlying PE image of the .NET module image is targeting.
/// </summary>
/// <remarks>
/// This property is in direct relation with the machine type field in the file header of a portable
/// executable file.
/// </remarks>
public MachineType MachineType
{
get;
set;
} = MachineType.I386;
/// <summary>
/// Gets or sets the date and time the module was created.
/// </summary>
/// <remarks>
/// This property is in direct relation with the TimeDateStamp field in the file header of a portable
/// executable file.
/// </remarks>
public DateTime TimeDateStamp
{
get;
set;
}
/// <summary>
/// Gets or sets the attributes assigned to the underlying executable file.
/// </summary>
/// <remarks>
/// This property is in direct relation with the characteristics field in the file header of a portable
/// executable file.
/// </remarks>
public Characteristics FileCharacteristics
{
get;
set;
} = Characteristics.Image | Characteristics.LargeAddressAware;
/// <summary>
/// Gets or sets the magic optional header signature, determining whether the underlying PE image is a
/// PE32 (32-bit) or a PE32+ (64-bit) image.
/// </summary>
/// <remarks>
/// This property is in direct relation with the magic field in the optional header of a portable
/// executable file.
/// </remarks>
public OptionalHeaderMagic PEKind
{
get;
set;
} = OptionalHeaderMagic.PE32;
/// <summary>
/// Gets or sets the subsystem to use when running the underlying portable executable (PE) file.
/// </summary>
/// <remarks>
/// This property is in direct relation with the subsystem field in the optional header of a portable
/// executable file.
/// </remarks>
public SubSystem SubSystem
{
get;
set;
} = SubSystem.WindowsCui;
/// <summary>
/// Gets or sets the dynamic linked library characteristics of the underlying portable executable (PE) file.
/// </summary>
/// <remarks>
/// This property is in direct relation with the DLL characteristics field in the optional header of a portable
/// executable file.
/// </remarks>
public DllCharacteristics DllCharacteristics
{
get;
set;
} = DllCharacteristics.DynamicBase | DllCharacteristics.NoSeh | DllCharacteristics.NxCompat
| DllCharacteristics.TerminalServerAware;
/// <summary>
/// Gets a collection of data entries stored in the debug data directory of the PE image (if available).
/// </summary>
public IList<DebugDataEntry> DebugData
{
get
{
if (_debugData is null)
Interlocked.CompareExchange(ref _debugData, GetDebugData(), null);
return _debugData;
}
}
/// <summary>
/// Gets or sets the runtime version string
/// </summary>
public string RuntimeVersion
{
get => _runtimeVersion.GetValue(this);
set => _runtimeVersion.SetValue(value);
}
/// <summary>
/// Gets or sets the contents of the native Win32 resources data directory of the underlying
/// portable executable (PE) file.
/// </summary>
public ResourceDirectory? NativeResourceDirectory
{
get => _nativeResources.GetValue(this);
set => _nativeResources.SetValue(value);
}
/// <summary>
/// Gets a collection of top-level (not nested) types defined in the module.
/// </summary>
public IList<TypeDefinition> TopLevelTypes
{
get
{
if (_topLevelTypes is null)
Interlocked.CompareExchange(ref _topLevelTypes, GetTopLevelTypes(), null);
return _topLevelTypes;
}
}
/// <summary>
/// Gets a collection of references to .NET assemblies that the module uses.
/// </summary>
public IList<AssemblyReference> AssemblyReferences
{
get
{
if (_assemblyReferences is null)
Interlocked.CompareExchange(ref _assemblyReferences, GetAssemblyReferences(), null);
return _assemblyReferences;
}
}
/// <summary>
/// Gets a collection of references to external modules that the module uses.
/// </summary>
public IList<ModuleReference> ModuleReferences
{
get
{
if (_moduleReferences is null)
Interlocked.CompareExchange(ref _moduleReferences, GetModuleReferences(), null);
return _moduleReferences;
}
}
/// <summary>
/// Gets a collection of references to external files that the module uses.
/// </summary>
public IList<FileReference> FileReferences
{
get
{
if (_fileReferences is null)
Interlocked.CompareExchange(ref _fileReferences, GetFileReferences(), null);
return _fileReferences;
}
}
/// <summary>
/// Gets a collection of resources stored in the module.
/// </summary>
public IList<ManifestResource> Resources
{
get
{
if (_resources is null)
Interlocked.CompareExchange(ref _resources, GetResources(), null);
return _resources;
}
}
/// <summary>
/// Gets a collection of types that are forwarded to another .NET module.
/// </summary>
public IList<ExportedType> ExportedTypes
{
get
{
if (_exportedTypes is null)
Interlocked.CompareExchange(ref _exportedTypes, GetExportedTypes(), null);
return _exportedTypes;
}
}
/// <summary>
/// Gets the common object runtime library type factory for this module, containing element type signatures used
/// in blob signatures.
/// </summary>
public CorLibTypeFactory CorLibTypeFactory
{
get;
protected set;
}
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <summary>
/// Gets or sets the object responsible for resolving references to external .NET assemblies.
/// </summary>
public IMetadataResolver MetadataResolver
{
get;
set;
}
/// <summary>
/// Gets or sets the managed method that is invoked after the .NET module is loaded and initialized.
/// </summary>
public MethodDefinition? ManagedEntryPointMethod
{
get => ManagedEntryPoint as MethodDefinition;
set => ManagedEntryPoint = value;
}
/// <summary>
/// Gets or sets the managed entry point that is invoked when the .NET module is initialized. This is either a
/// method, or a reference to a secondary module containing the entry point method.
/// </summary>
public IManagedEntryPoint? ManagedEntryPoint
{
get => _managedEntryPoint.GetValue(this);
set => _managedEntryPoint.SetValue(value);
}
/// <summary>
/// Gets the default importer instance for this module.
/// </summary>
public ReferenceImporter DefaultImporter
{
get
{
if (_defaultImporter is null)
Interlocked.CompareExchange(ref _defaultImporter, GetDefaultImporter(), null);
return _defaultImporter;
}
}
/// <summary>
/// Determines whether the module is loaded as a 32-bit process.
/// </summary>
/// <returns>
/// <c>true</c> if the module is loaded as a 32-bit process, <c>false</c> if it is loaded as a 64-bit process.
/// </returns>
public bool IsLoadedAs32Bit() => IsLoadedAs32Bit(false, true);
/// <summary>
/// Determines whether the module is loaded as a 32-bit process.
/// </summary>
/// <param name="assume32BitSystem"><c>true</c> if a 32-bit system should be assumed.</param>
/// <param name="canLoadAs32Bit"><c>true</c> if the application can be loaded as a 32-bit process.</param>
/// <returns>
/// <c>true</c> if the module is loaded as a 32-bit process, <c>false</c> if it is loaded as a 64-bit process.
/// </returns>
public bool IsLoadedAs32Bit(bool assume32BitSystem, bool canLoadAs32Bit)
{
// Assume 32-bit if platform is unknown.
return Platform.TryGet(MachineType, out var platform)
&& Attributes.IsLoadedAs32Bit(platform, assume32BitSystem, canLoadAs32Bit);
}
/// <summary>
/// Looks up a member by its metadata token.
/// </summary>
/// <param name="token">The token of the member to look up.</param>
/// <returns>The member.</returns>
/// <exception cref="InvalidOperationException">
/// Occurs when the module does not support looking up members by its token.
/// </exception>
/// <exception cref="NotSupportedException">
/// Occurs when a metadata token indexes a table that cannot be converted to a metadata member.
/// </exception>
public virtual IMetadataMember LookupMember(MetadataToken token) =>
throw new InvalidOperationException("Cannot lookup members by tokens from a non-serialized module.");
/// <summary>
/// Looks up a member by its metadata token, and casts it to the provided metadata member type.
/// </summary>
/// <param name="token">The token of the member to look up.</param>
/// <typeparam name="T">The type of member to look up.</typeparam>
/// <returns>The casted member.</returns>
/// <exception cref="InvalidOperationException">
/// Occurs when the module does not support looking up members by its token.
/// </exception>
/// <exception cref="NotSupportedException">
/// Occurs when a metadata token indexes a table that cannot be converted to a metadata member.
/// </exception>
public T LookupMember<T>(MetadataToken token)
where T : class, IMetadataMember
{
return (T) LookupMember(token);
}
/// <summary>
/// Attempts to look up a member by its metadata token.
/// </summary>
/// <param name="token">The token of the member to look up.</param>
/// <param name="member">The member, or <c>null</c> if the lookup failed.</param>
/// <returns><c>true</c> if the member was successfully looked up, false otherwise.</returns>
public virtual bool TryLookupMember(MetadataToken token, [NotNullWhen(true)] out IMetadataMember? member)
{
member = null;
return false;
}
/// <summary>
/// Attempts to look up a member by its metadata token, and cast it to the specified metadata member type.
/// </summary>
/// <param name="token">The token of the member to look up.</param>
/// <param name="member">The member, or <c>null</c> if the lookup failed.</param>
/// <typeparam name="T">The type of member to look up.</typeparam>
/// <returns><c>true</c> if the member was successfully looked up and of the correct type, false otherwise.</returns>
public bool TryLookupMember<T>(MetadataToken token, [NotNullWhen((true))] out T? member)
where T : class, IMetadataMember
{
if (TryLookupMember(token, out var resolved) && resolved is T casted)
{
member = casted;
return true;
}
member = null;
return false;
}
/// <summary>
/// Looks up a user string by its string token.
/// </summary>
/// <param name="token">The token of the string to look up.</param>
/// <returns>The member.</returns>
/// <exception cref="InvalidOperationException">
/// Occurs when the module does not support looking up string by its token.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Occurs when a metadata token indexes an invalid string.
/// </exception>
public virtual string LookupString(MetadataToken token) =>
throw new InvalidOperationException("Cannot lookup strings by tokens from a non-serialized module.");
/// <summary>
/// Attempts to look up a user string by its metadata token.
/// </summary>
/// <param name="token">The token of the member to lookup.</param>
/// <param name="value">The string, or <c>null</c> if the lookup failed.</param>
/// <returns><c>true</c> if the string was successfully looked up, false otherwise.</returns>
public virtual bool TryLookupString(MetadataToken token, [NotNullWhen(true)] out string? value)
{
value = null;
return false;
}
/// <summary>
/// Obtains an object that can be used to decode coded indices to metadata tokens.
/// </summary>
/// <param name="codedIndex">The type of indices to get the encoder for.</param>
/// <returns>The index encoder.</returns>
/// <exception cref="InvalidOperationException">
/// Occurs when the module does not support index encoders.
/// </exception>
public virtual IndexEncoder GetIndexEncoder(CodedIndex codedIndex) =>
throw new InvalidOperationException("Cannot get an index encoder from a non-serialized module.");
/// <summary>
/// Obtains a list of type references that were imported into the module.
/// </summary>
/// <returns>The type references.</returns>
/// <remarks>
/// The return value of this method does not update when the <see cref="ReferenceImporter"/> class is used to
/// import new type references into the module. This method only serves as a way to easily get all the type
/// references that were imported during the last compilation or assembly process.
/// </remarks>
public virtual IEnumerable<TypeReference> GetImportedTypeReferences() => EnumerateTableMembers<TypeReference>(TableIndex.TypeRef);
/// <summary>
/// Obtains a list of member references that were imported into the module.
/// </summary>
/// <returns>The type references.</returns>
/// <remarks>
/// The return value of this method does not update when the <see cref="ReferenceImporter"/> class is used to
/// import new member references into the module. This method only serves as a way to easily get all the member
/// references that were imported during the last compilation or assembly process.
/// </remarks>
public virtual IEnumerable<MemberReference> GetImportedMemberReferences() => EnumerateTableMembers<MemberReference>(TableIndex.MemberRef);
/// <summary>
/// Enumerates all metadata members stored in the module.
/// </summary>
/// <param name="tableIndex">The table to enumerate the members for.</param>
/// <returns>The members.</returns>
/// <remarks>
/// The return value of this method does not update when new members are added or imported into the module.
/// This method only serves as a way to easily get all the member references that were imported during the last
/// compilation or assembly process. This method can also only enumerate members in a table for which there is
/// an explicit <see cref="IMetadataMember" /> implementation available, and will return an empty collection
/// for tables that do not have one.
/// </remarks>
public virtual IEnumerable<IMetadataMember> EnumerateTableMembers(TableIndex tableIndex)
{
return Enumerable.Empty<IMetadataMember>();
}
/// <summary>
/// Enumerates all metadata members stored in the module.
/// </summary>
/// <param name="tableIndex">The table to enumerate the members for.</param>
/// <typeparam name="TMember">The type of members to return.</typeparam>
/// <returns>The members.</returns>
/// <remarks>
/// The return value of this method does not update when new members are added or imported into the module.
/// This method only serves as a way to easily get all the member references that were imported during the last
/// compilation or assembly process. This method can also only enumerate members in a table for which there is
/// an explicit <see cref="IMetadataMember" /> implementation available, and will return an empty collection
/// for tables that do not have one.
/// </remarks>
public virtual IEnumerable<TMember> EnumerateTableMembers<TMember>(TableIndex tableIndex)
where TMember : IMetadataMember
{
return EnumerateTableMembers(tableIndex).Cast<TMember>();
}
/// <summary>
/// Enumerates all types (including nested types) defined in the module.
/// </summary>
/// <returns>The types.</returns>
public IEnumerable<TypeDefinition> GetAllTypes()
{
var agenda = new Queue<TypeDefinition>();
foreach (var type in TopLevelTypes)
agenda.Enqueue(type);
while (agenda.Count > 0)
{
var currentType = agenda.Dequeue();
yield return currentType;
foreach (var nestedType in currentType.NestedTypes)
agenda.Enqueue(nestedType);
}
}
/// <summary>
/// Gets the module static constructor of this metadata image. That is, the first method that is executed
/// upon loading the .NET module.
/// </summary>
/// <returns>The module constructor, or <c>null</c> if none is present.</returns>
public MethodDefinition? GetModuleConstructor() => GetModuleType()?.GetStaticConstructor();
/// <summary>
/// Gets or creates the module static constructor of this metadata image. That is, the first method that is
/// executed upon loading the .NET module.
/// </summary>
/// <returns>The module constructor.</returns>
/// <remarks>
/// If the static constructor was not present in the image, the new one is automatically added.
/// </remarks>
public MethodDefinition GetOrCreateModuleConstructor() => GetOrCreateModuleType().GetOrCreateStaticConstructor();
/// <summary>
/// Obtains the global scope type of the .NET module.
/// </summary>
/// <returns>The module type.</returns>
public TypeDefinition? GetModuleType()
{
if (TopLevelTypes.Count == 0)
return null;
var firstType = TopLevelTypes[0];
// Only .NET Framework allows the module type to be renamed to something else.
if (!OriginalTargetRuntime.IsNetFramework && !firstType.IsTypeOfUtf8(null, TypeDefinition.ModuleTypeName))
return null;
return firstType;
}
/// <summary>
/// Obtains or creates the global scope type of the .NET module.
/// </summary>
/// <returns>The module type.</returns>
public TypeDefinition GetOrCreateModuleType()
{
var moduleType = GetModuleType();
if (moduleType is null)
{
moduleType = new TypeDefinition(null, TypeDefinition.ModuleTypeName, 0);
TopLevelTypes.Insert(0, moduleType);
}
return moduleType;
}
/// <summary>
/// Obtains the name of the module definition.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual Utf8String? GetName() => null;
/// <summary>
/// Obtains the MVID of the module definition.
/// </summary>
/// <returns>The MVID.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Mvid"/> property.
/// </remarks>
protected virtual Guid GetMvid() => Guid.NewGuid();
/// <summary>
/// Obtains the edit-and-continue identifier of the module definition.
/// </summary>
/// <returns>The identifier.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="EncId"/> property.
/// </remarks>
protected virtual Guid GetEncId() => Guid.Empty;
/// <summary>
/// Obtains the edit-and-continue base identifier of the module definition.
/// </summary>
/// <returns>The identifier.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="EncBaseId"/> property.
/// </remarks>
protected virtual Guid GetEncBaseId() => Guid.Empty;
/// <summary>
/// Obtains the list of top-level types the module defines.
/// </summary>
/// <returns>The types.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="TopLevelTypes"/> property.
/// </remarks>
protected virtual IList<TypeDefinition> GetTopLevelTypes() =>
new OwnedCollection<ModuleDefinition, TypeDefinition>(this);
/// <summary>
/// Obtains the list of references to .NET assemblies that the module uses.
/// </summary>
/// <returns>The references to the assemblies..</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="AssemblyReferences"/> property.
/// </remarks>
protected virtual IList<AssemblyReference> GetAssemblyReferences() =>
new OwnedCollection<ModuleDefinition, AssemblyReference>(this);
/// <summary>
/// Obtains the list of references to external modules that the module uses.
/// </summary>
/// <returns>The references to the modules.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="ModuleReferences"/> property.
/// </remarks>
protected virtual IList<ModuleReference> GetModuleReferences() =>
new OwnedCollection<ModuleDefinition, ModuleReference>(this);
/// <summary>
/// Obtains the list of references to external files that the module uses.
/// </summary>
/// <returns>The references to the files.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="FileReferences"/> property.
/// </remarks>
protected virtual IList<FileReference> GetFileReferences() =>
new OwnedCollection<ModuleDefinition, FileReference>(this);
/// <summary>
/// Obtains the list of resources stored in the module.
/// </summary>
/// <returns>The resources.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Resources"/> property.
/// </remarks>
protected virtual IList<ManifestResource> GetResources() =>
new OwnedCollection<ModuleDefinition, ManifestResource>(this);
/// <summary>
/// Obtains the list of types that are redirected to another external module.
/// </summary>
/// <returns>The exported types.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="ExportedTypes"/> property.
/// </remarks>
protected virtual IList<ExportedType> GetExportedTypes() =>
new OwnedCollection<ModuleDefinition, ExportedType>(this);
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
AssemblyDescriptor? IResolutionScope.GetAssembly() => Assembly;
/// <summary>
/// Obtains the version string of the runtime.
/// </summary>
/// <returns>The runtime version.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="RuntimeVersion"/> property.
/// </remarks>
protected virtual string GetRuntimeVersion() => KnownRuntimeVersions.Clr40;
/// <summary>
/// Obtains the managed entry point of this module.
/// </summary>
/// <returns>The entry point.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="ManagedEntryPoint"/> property.
/// </remarks>
protected virtual IManagedEntryPoint? GetManagedEntryPoint() => null;
/// <summary>
/// Obtains the native win32 resources directory of the underlying PE image (if available).
/// </summary>
/// <returns>The resources directory.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="NativeResourceDirectory"/> property.
/// </remarks>
protected virtual ResourceDirectory? GetNativeResources() => null;
/// <summary>
/// Obtains the native debug data directory of the underlying PE image (if available).
/// </summary>
/// <returns>The debug directory.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="DebugData"/> property.
/// </remarks>
protected virtual IList<DebugDataEntry> GetDebugData() => new List<DebugDataEntry>();
/// <summary>
/// Obtains the default reference importer assigned to this module.
/// </summary>
/// <returns>The importer.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="DefaultImporter"/> property.
/// </remarks>
protected virtual ReferenceImporter GetDefaultImporter() => new(this);
/// <summary>
/// Detects the runtime that this module targets.
/// </summary>
/// <remarks>
/// This method is called to initialize the <see cref="OriginalTargetRuntime"/> property.
/// It should be called before the assembly resolver is initialized.
/// </remarks>
protected DotNetRuntimeInfo DetectTargetRuntime()
{
return Assembly is not null && Assembly.TryGetTargetFramework(out var targetRuntime)
? targetRuntime
: CorLibTypeFactory.ExtractDotNetRuntimeInfo();
}
/// <inheritdoc />
public override string ToString() => Name ?? string.Empty;
/// <inheritdoc />
bool IImportable.IsImportedInModule(ModuleDefinition module) => this == module;
/// <summary>
/// Imports the module using the provided reference importer object.
/// </summary>
/// <param name="importer">The reference importer to use.</param>
/// <returns>The imported module.</returns>
public ModuleReference ImportWith(ReferenceImporter importer) => importer.ImportModule(new ModuleReference(Name));
/// <inheritdoc />
IImportable IImportable.ImportWith(ReferenceImporter importer) => ImportWith(importer);
/// <summary>
/// Rebuilds the .NET module to a portable executable file and writes it to the file system.
/// </summary>
/// <param name="filePath">The output path of the manifest module file.</param>
/// <exception cref="AggregateException">Occurs when the construction of the image threw exceptions.</exception>
public void Write(string filePath) =>
Write(filePath, new ManagedPEImageBuilder(), new ManagedPEFileBuilder());
/// <summary>
/// Rebuilds the .NET module to a portable executable file and writes it to an output stream.
/// </summary>
/// <param name="outputStream">The output stream of the manifest module file.</param>
/// <exception cref="AggregateException">Occurs when the construction of the image threw exceptions.</exception>
public void Write(Stream outputStream) =>
Write(outputStream, new ManagedPEImageBuilder(), new ManagedPEFileBuilder());
/// <summary>
/// Rebuilds the .NET module to a portable executable file and writes it to the file system.
/// </summary>
/// <param name="filePath">The output path of the manifest module file.</param>
/// <param name="imageBuilder">The engine to use for reconstructing a PE image.</param>
/// <exception cref="AggregateException">Occurs when the construction of the image threw exceptions.</exception>
public void Write(string filePath, IPEImageBuilder imageBuilder) =>
Write(filePath, imageBuilder, new ManagedPEFileBuilder());
/// <summary>
/// Rebuilds the .NET module to a portable executable file and writes it to an output stream.
/// </summary>
/// <param name="outputStream">The output stream of the manifest module file.</param>
/// <param name="imageBuilder">The engine to use for reconstructing a PE image.</param>
/// <exception cref="AggregateException">Occurs when the construction of the image threw exceptions.</exception>
public void Write(Stream outputStream, IPEImageBuilder imageBuilder) =>
Write(outputStream, imageBuilder, new ManagedPEFileBuilder());
/// <summary>
/// Rebuilds the .NET module to a portable executable file and writes it to the file system.
/// </summary>
/// <param name="filePath">The output path of the manifest module file.</param>
/// <param name="imageBuilder">The engine to use for reconstructing a PE image.</param>
/// <param name="fileBuilder">The engine to use for reconstructing a PE file.</param>
/// <exception cref="AggregateException">Occurs when the construction of the image threw exceptions.</exception>
public void Write(string filePath, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder)
{
using var fs = File.Create(filePath);
Write(fs, imageBuilder, fileBuilder);
}
/// <summary>
/// Rebuilds the .NET module to a portable executable file and writes it to an output stream.
/// </summary>
/// <param name="outputStream">The output stream of the manifest module file.</param>
/// <param name="imageBuilder">The engine to use for reconstructing a PE image.</param>
/// <param name="fileBuilder">The engine to use for reconstructing a PE file.</param>
/// <exception cref="AggregateException">Occurs when the construction of the image threw exceptions.</exception>
public void Write(Stream outputStream, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder)
{
Write(new BinaryStreamWriter(outputStream), imageBuilder, fileBuilder);
}
/// <summary>
/// Rebuilds the .NET module to a portable executable file and writes it to the file system.
/// </summary>
/// <param name="writer">The output stream of the manifest module file.</param>
/// <param name="imageBuilder">The engine to use for reconstructing a PE image.</param>
/// <param name="fileBuilder">The engine to use for reconstructing a PE file.</param>
/// <exception cref="AggregateException">Occurs when the construction of the image threw exceptions.</exception>
public void Write(BinaryStreamWriter writer, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder)
{
ToPEImage(imageBuilder).ToPEFile(fileBuilder).Write(writer);
}
/// <summary>
/// Rebuilds the .NET module to a portable executable file and returns the IPEImage.
/// </summary>
/// <returns>IPEImage built using <see cref="ManagedPEImageBuilder"/> by default</returns>
/// <exception cref="AggregateException">Occurs when the construction of the image threw exceptions.</exception>
public PEImage ToPEImage() => ToPEImage(new ManagedPEImageBuilder(), true);
/// <summary>
/// Rebuilds the .NET module to a portable executable file and returns the IPEImage.
/// </summary>
/// <param name="imageBuilder">The engine to use for reconstructing a PE image.</param>
/// <returns>IPEImage built by the specified IPEImageBuilder</returns>
/// <exception cref="AggregateException">
/// Occurs when the construction of the image threw exceptions, and the used error listener is an instance of
/// a <see cref="DiagnosticBag"/>.
/// </exception>
/// <exception cref="MetadataBuilderException">
/// Occurs when the construction of the PE image failed completely.
/// </exception>
public PEImage ToPEImage(IPEImageBuilder imageBuilder) => ToPEImage(imageBuilder, true);
/// <summary>
/// Rebuilds the .NET module to a portable executable file and returns the IPEImage.
/// </summary>
/// <param name="imageBuilder">The engine to use for reconstructing a PE image.</param>
/// <param name="throwOnNonFatalError">
/// <c>true</c> if non-fatal errors should be thrown as an exception, <c>false</c> otherwise.
/// </param>
/// <returns>IPEImage built by the specified IPEImageBuilder</returns>
/// <exception cref="AggregateException">
/// Occurs when the construction of the image threw exceptions, and the used error listener is an instance of
/// a <see cref="DiagnosticBag"/>.
/// </exception>
/// <exception cref="MetadataBuilderException">
/// Occurs when the construction of the PE image failed completely.
/// </exception>
public PEImage ToPEImage(IPEImageBuilder imageBuilder, bool throwOnNonFatalError)
{
var result = imageBuilder.CreateImage(this);
// If the error listener is a diagnostic bag, we can pull out the exceptions that were thrown.
if (result.ErrorListener is DiagnosticBag {HasErrors: true} diagnosticBag && throwOnNonFatalError)
{
throw new AggregateException(
"Construction of the PE image failed with one or more errors.",
diagnosticBag.Exceptions);
}
// If we still failed but we don't have special handling for the provided error listener, just throw a
// simple exception instead.
if (result.HasFailed)
throw new MetadataBuilderException("Construction of the PE image failed.");
return result.ConstructedImage;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\ModuleReferenceTest.cs | AsmResolver.DotNet.Tests
| ModuleReferenceTest | [] | ['System.IO', 'Xunit'] | xUnit | net8.0 | public class ModuleReferenceTest
{
[Fact]
public void ReadName()
{
var module = ModuleDefinition.FromFile(Path.Combine("Resources", "Manifest.exe"), TestReaderParameters);
var moduleRef = module.ModuleReferences[0];
Assert.Equal("MyModel.netmodule", moduleRef.Name);
}
} | 77 | 432 | using System.Collections.Generic;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a reference to an external module. This module can be managed or unmanaged.
/// </summary>
public class ModuleReference :
MetadataMember,
IResolutionScope,
IMemberRefParent,
IHasCustomAttribute,
IOwnedCollectionElement<ModuleDefinition>
{
private readonly LazyVariable<ModuleReference, Utf8String?> _name;
private IList<CustomAttribute>? _customAttributes;
/// <summary>
/// Initializes the module reference with a metadata token.
/// </summary>
/// <param name="token">The metadata token.</param>
protected ModuleReference(MetadataToken token)
: base(token)
{
_name = new LazyVariable<ModuleReference, Utf8String?>(x => x.GetName());
}
/// <summary>
/// Creates a new reference to an external module.
/// </summary>
/// <param name="name">The file name of the module.</param>
public ModuleReference(Utf8String? name)
: this(new MetadataToken(TableIndex.ModuleRef, 0))
{
Name = name;
}
/// <summary>
/// Gets or sets the name of the module.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the module definition table.
/// </remarks>
public Utf8String? Name
{
get => _name.GetValue(this);
set => _name.SetValue(value);
}
string? INameProvider.Name => Name;
/// <inheritdoc />
public ModuleDefinition? Module
{
get;
private set;
}
ModuleDefinition? IOwnedCollectionElement<ModuleDefinition>.Owner
{
get => Module;
set => Module = value;
}
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <inheritdoc />
public bool IsImportedInModule(ModuleDefinition module) => Module == module;
/// <summary>
/// Imports the module reference using the provided reference importer object.
/// </summary>
/// <param name="importer">The reference importer to use.</param>
/// <returns>The imported module.</returns>
public ModuleReference ImportWith(ReferenceImporter importer) => importer.ImportModule(this);
/// <inheritdoc />
IImportable IImportable.ImportWith(ReferenceImporter importer) => ImportWith(importer);
/// <summary>
/// Obtains the name of the module.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual Utf8String? GetName() => null;
AssemblyDescriptor? IResolutionScope.GetAssembly() => Module?.Assembly;
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
/// <inheritdoc />
public override string ToString() => Name ?? NullName;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\PropertyDefinitionTest.cs | AsmResolver.DotNet.Tests
| PropertyDefinitionTest | [] | ['System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Properties', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class PropertyDefinitionTest
{
[Fact]
public void ReadName()
{
var module = ModuleDefinition.FromFile(typeof(SingleProperty).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleProperty));
var property = type.Properties.FirstOrDefault(m => m.Name == nameof(SingleProperty.IntProperty));
Assert.NotNull(property);
}
[Theory]
[InlineData(nameof(MultipleProperties.ReadOnlyProperty), "System.Int32")]
[InlineData(nameof(MultipleProperties.WriteOnlyProperty), "System.String")]
[InlineData(nameof(MultipleProperties.ReadWriteProperty), "AsmResolver.DotNet.TestCases.Properties.MultipleProperties")]
[InlineData("Item", "System.Int32")]
public void ReadReturnType(string propertyName, string expectedReturnType)
{
var module = ModuleDefinition.FromFile(typeof(MultipleProperties).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleProperties));
var property = type.Properties.First(m => m.Name == propertyName);
Assert.Equal(expectedReturnType, property.Signature.ReturnType.FullName);
}
[Fact]
public void ReadDeclaringType()
{
var module = ModuleDefinition.FromFile(typeof(SingleProperty).Assembly.Location, TestReaderParameters);
var property = (PropertyDefinition) module.LookupMember(
typeof(SingleProperty).GetProperty(nameof(SingleProperty.IntProperty)).MetadataToken);
Assert.NotNull(property.DeclaringType);
Assert.Equal(nameof(SingleProperty), property.DeclaringType.Name);
}
[Fact]
public void ReadReadOnlyPropertySemantics()
{
var module = ModuleDefinition.FromFile(typeof(MultipleProperties).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleProperties));
var property = type.Properties.First(m => m.Name == nameof(MultipleProperties.ReadOnlyProperty));
Assert.Single(property.Semantics);
Assert.Equal(MethodSemanticsAttributes.Getter, property.Semantics[0].Attributes);
Assert.Same(property, property.Semantics[0].Association);
Assert.Equal("get_ReadOnlyProperty", property.Semantics[0].Method.Name);
Assert.NotNull(property.GetMethod);
Assert.Null(property.SetMethod);
}
[Fact]
public void ReadWriteOnlyPropertySemantics()
{
var module = ModuleDefinition.FromFile(typeof(MultipleProperties).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleProperties));
var property = type.Properties.First(m => m.Name == nameof(MultipleProperties.WriteOnlyProperty));
Assert.Single(property.Semantics);
Assert.Equal(MethodSemanticsAttributes.Setter, property.Semantics[0].Attributes);
Assert.Same(property, property.Semantics[0].Association);
Assert.Equal("set_WriteOnlyProperty", property.Semantics[0].Method.Name);
Assert.NotNull(property.SetMethod);
Assert.Null(property.GetMethod);
}
[Fact]
public void ReadReadWritePropertySemantics()
{
var module = ModuleDefinition.FromFile(typeof(MultipleProperties).Assembly.Location, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleProperties));
var property = type.Properties.First(m => m.Name == nameof(MultipleProperties.ReadWriteProperty));
Assert.Equal(2, property.Semantics.Count);
}
[Fact]
public void ReadParameterlessPropertyFullName()
{
var module = ModuleDefinition.FromFile(typeof(MultipleProperties).Assembly.Location, TestReaderParameters);
var property = (PropertyDefinition) module.LookupMember(
typeof(MultipleProperties).GetProperty(nameof(MultipleProperties.ReadOnlyProperty)).MetadataToken);
Assert.Equal("System.Int32 AsmResolver.DotNet.TestCases.Properties.MultipleProperties::ReadOnlyProperty", property.FullName);
}
[Fact]
public void ReadParameterPropertyFullName()
{
var module = ModuleDefinition.FromFile(typeof(MultipleProperties).Assembly.Location, TestReaderParameters);
var property = (PropertyDefinition) module.LookupMember(
typeof(MultipleProperties).GetProperty("Item").MetadataToken);
Assert.Equal("System.Int32 AsmResolver.DotNet.TestCases.Properties.MultipleProperties::Item[System.Int32]", property.FullName);
}
[Fact]
public void GetMethodSetMethodProperties()
{
var module = new ModuleDefinition("TestModule");
var type = new TypeDefinition("Namespace", "Name", TypeAttributes.Public);
module.TopLevelTypes.Add(type);
var get1 = new MethodDefinition("get_Property1", default, MethodSignature.CreateInstance(module.CorLibTypeFactory.Int32));
var get2 = new MethodDefinition("get_Property2", default, MethodSignature.CreateInstance(module.CorLibTypeFactory.Int32));
var set = new MethodDefinition("set_Property", default, MethodSignature.CreateInstance(module.CorLibTypeFactory.Void, module.CorLibTypeFactory.Int32));
type.Methods.Add(get1);
type.Methods.Add(get2);
type.Methods.Add(set);
Assert.False(get1.IsGetMethod || get1.IsSetMethod);
Assert.False(get2.IsGetMethod || get2.IsSetMethod);
Assert.False(set.IsGetMethod || set.IsSetMethod);
var property = new PropertyDefinition("Property", PropertyAttributes.None, PropertySignature.CreateInstance(module.CorLibTypeFactory.Int32));
type.Properties.Add(property);
property.SetSemanticMethods(get1, set);
Assert.True(get1.IsGetMethod);
Assert.False(get2.IsGetMethod);
Assert.True(set.IsSetMethod);
property.GetMethod = get2;
Assert.False(get1.IsGetMethod);
Assert.True(get2.IsGetMethod);
Assert.True(set.IsSetMethod);
}
} | 211 | 6,805 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.DotNet.Collections;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Metadata.Tables;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a single property in a type definition of a .NET module.
/// </summary>
public class PropertyDefinition :
MetadataMember,
IHasSemantics,
IHasCustomAttribute,
IHasConstant,
IOwnedCollectionElement<TypeDefinition>
{
private readonly LazyVariable<PropertyDefinition, Utf8String?> _name;
private readonly LazyVariable<PropertyDefinition, TypeDefinition?> _declaringType;
private readonly LazyVariable<PropertyDefinition, PropertySignature?> _signature;
private readonly LazyVariable<PropertyDefinition, Constant?> _constant;
private IList<MethodSemantics>? _semantics;
private IList<CustomAttribute>? _customAttributes;
/// <summary>
/// Initializes a new property definition.
/// </summary>
/// <param name="token">The token of the property.</param>
protected PropertyDefinition(MetadataToken token)
: base(token)
{
_name = new LazyVariable<PropertyDefinition, Utf8String?>(x => x.GetName());
_signature = new LazyVariable<PropertyDefinition, PropertySignature?>(x => x.GetSignature());
_declaringType = new LazyVariable<PropertyDefinition, TypeDefinition?>(x => x.GetDeclaringType());
_constant = new LazyVariable<PropertyDefinition, Constant?>(x => x.GetConstant());
}
/// <summary>
/// Creates a new property definition.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="attributes">The attributes.</param>
/// <param name="signature">The signature of the property.</param>
public PropertyDefinition(Utf8String? name, PropertyAttributes attributes, PropertySignature? signature)
: this(new MetadataToken(TableIndex.Property,0))
{
Name = name;
Attributes = attributes;
Signature = signature;
}
/// <summary>
/// Gets or sets the attributes associated to the field.
/// </summary>
public PropertyAttributes Attributes
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating the property uses a special name.
/// </summary>
public bool IsSpecialName
{
get => (Attributes & PropertyAttributes.SpecialName) != 0;
set => Attributes = (Attributes & ~PropertyAttributes.SpecialName)
| (value ? PropertyAttributes.SpecialName : 0);
}
/// <summary>
/// Gets or sets a value indicating the property uses a special name used by the runtime.
/// </summary>
public bool IsRuntimeSpecialName
{
get => (Attributes & PropertyAttributes.RuntimeSpecialName) != 0;
set => Attributes = (Attributes & ~PropertyAttributes.RuntimeSpecialName)
| (value ? PropertyAttributes.RuntimeSpecialName : 0);
}
/// <summary>
/// Gets or sets a value indicating the property has a default value.
/// </summary>
public bool HasDefault
{
get => (Attributes & PropertyAttributes.HasDefault) != 0;
set => Attributes = (Attributes & ~PropertyAttributes.HasDefault)
| (value ? PropertyAttributes.HasDefault : 0);
}
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
/// <remarks>
/// This property corresponds to the Name column in the property definition table.
/// </remarks>
public Utf8String? Name
{
get => _name.GetValue(this);
set => _name.SetValue(value);
}
string? INameProvider.Name => Name;
/// <inheritdoc />
public string FullName => MemberNameGenerator.GetPropertyFullName(this);
/// <summary>
/// Gets or sets the signature of the property. This includes the property type, as well as any parameters the
/// property might define.
/// </summary>
public PropertySignature? Signature
{
get => _signature.GetValue(this);
set => _signature.SetValue(value);
}
/// <inheritdoc />
public ModuleDefinition? Module => DeclaringType?.Module;
/// <summary>
/// Gets the type that defines the property.
/// </summary>
public TypeDefinition? DeclaringType
{
get => _declaringType.GetValue(this);
private set => _declaringType.SetValue(value);
}
ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType;
TypeDefinition? IOwnedCollectionElement<TypeDefinition>.Owner
{
get => DeclaringType;
set => DeclaringType = value;
}
/// <inheritdoc />
public IList<MethodSemantics> Semantics
{
get
{
if (_semantics is null)
Interlocked.CompareExchange(ref _semantics, GetSemantics(), null);
return _semantics;
}
}
/// <inheritdoc />
public IList<CustomAttribute> CustomAttributes
{
get
{
if (_customAttributes is null)
Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
return _customAttributes;
}
}
/// <inheritdoc />
public Constant? Constant
{
get => _constant.GetValue(this);
set => _constant.SetValue(value);
}
/// <summary>
/// Gets the method definition representing the first get accessor of this property definition.
/// </summary>
public MethodDefinition? GetMethod
{
get => Semantics.FirstOrDefault(s => s.Attributes == MethodSemanticsAttributes.Getter)?.Method;
set => SetSemanticMethods(value, SetMethod);
}
/// <summary>
/// Gets the method definition representing the first set accessor of this property definition.
/// </summary>
public MethodDefinition? SetMethod
{
get => Semantics.FirstOrDefault(s => s.Attributes == MethodSemanticsAttributes.Setter)?.Method;
set => SetSemanticMethods(GetMethod, value);
}
/// <summary>
/// Clear <see cref="Semantics"/> and apply these methods to the property definition.
/// </summary>
/// <param name="getMethod">The method definition representing the get accessor of this property definition.</param>
/// <param name="setMethod">The method definition representing the set accessor of this property definition.</param>
public void SetSemanticMethods(MethodDefinition? getMethod, MethodDefinition? setMethod)
{
Semantics.Clear();
if (getMethod is not null)
Semantics.Add(new MethodSemantics(getMethod, MethodSemanticsAttributes.Getter));
if (setMethod is not null)
Semantics.Add(new MethodSemantics(setMethod, MethodSemanticsAttributes.Setter));
}
/// <inheritdoc />
public bool IsAccessibleFromType(TypeDefinition type) =>
Semantics.Any(s => s.Method?.IsAccessibleFromType(type) ?? false);
IMemberDefinition IMemberDescriptor.Resolve() => this;
/// <inheritdoc />
public bool IsImportedInModule(ModuleDefinition module)
{
return Module == module
&& (Signature?.IsImportedInModule(module) ?? false);
}
/// <inheritdoc />
IImportable IImportable.ImportWith(ReferenceImporter importer) => throw new NotSupportedException();
/// <summary>
/// Obtains the name of the property definition.
/// </summary>
/// <returns>The name.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Name"/> property.
/// </remarks>
protected virtual Utf8String? GetName() => null;
/// <summary>
/// Obtains the signature of the property definition.
/// </summary>
/// <returns>The signature.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Signature"/> property.
/// </remarks>
protected virtual PropertySignature? GetSignature() => null;
/// <summary>
/// Obtains the declaring type of the property definition.
/// </summary>
/// <returns>The declaring type.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="DeclaringType"/> property.
/// </remarks>
protected virtual TypeDefinition? GetDeclaringType() => null;
/// <summary>
/// Obtains the methods associated to this property definition.
/// </summary>
/// <returns>The method semantic objects.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Semantics"/> property.
/// </remarks>
protected virtual IList<MethodSemantics> GetSemantics() =>
new MethodSemanticsCollection(this);
/// <summary>
/// Obtains the list of custom attributes assigned to the member.
/// </summary>
/// <returns>The attributes</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="CustomAttributes"/> property.
/// </remarks>
protected virtual IList<CustomAttribute> GetCustomAttributes() =>
new OwnedCollection<IHasCustomAttribute, CustomAttribute>(this);
/// <summary>
/// Obtains the constant value assigned to the property definition.
/// </summary>
/// <returns>The constant.</returns>
/// <remarks>
/// This method is called upon initialization of the <see cref="Constant"/> property.
/// </remarks>
protected virtual Constant? GetConstant() => null;
/// <inheritdoc />
public override string ToString() => FullName;
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\ReferenceImporterTest.cs | AsmResolver.DotNet.Tests
| ReferenceImporterTest | ['private static readonly SignatureComparer Comparer = new();', 'private readonly AssemblyReference _dummyAssembly = new("SomeAssembly", new Version(1, 2, 3, 4));', 'private readonly ModuleDefinition _module;', 'private readonly ReferenceImporter _importer;', 'public static delegate*unmanaged[Cdecl, SuppressGCTransition]<int, uint> Complex = null;', 'public static delegate*unmanaged[Stdcall]<int, uint> StdcallOnly = null;', 'public static delegate*unmanaged[SuppressGCTransition]<int, uint> GcOnly = null;'] | ['System', 'System.Collections.Generic', 'System.IO', 'System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Fields', 'AsmResolver.DotNet.TestCases.Generics', 'AsmResolver.DotNet.TestCases.NestedClasses', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class ReferenceImporterTest
{
private static readonly SignatureComparer Comparer = new();
private readonly AssemblyReference _dummyAssembly = new("SomeAssembly", new Version(1, 2, 3, 4));
private readonly ModuleDefinition _module;
private readonly ReferenceImporter _importer;
public ReferenceImporterTest()
{
_module = new ModuleDefinition("SomeModule.dll");
_importer = new ReferenceImporter(_module);
}
[Fact]
public void ImportNewAssemblyShouldAddToModule()
{
var result = _importer.ImportScope(_dummyAssembly);
Assert.Equal(_dummyAssembly, result, Comparer);
Assert.Contains(result, _module.AssemblyReferences);
}
[Fact]
public void ImportExistingAssemblyShouldUseExistingAssembly()
{
_module.AssemblyReferences.Add(_dummyAssembly);
int count = _module.AssemblyReferences.Count;
var copy = new AssemblyReference(_dummyAssembly);
var result = _importer.ImportScope(copy);
Assert.Same(_dummyAssembly, result);
Assert.Equal(count, _module.AssemblyReferences.Count);
}
[Fact]
public void ImportNewTypeShouldCreateNewReference()
{
var type = new TypeReference(_dummyAssembly, "SomeNamespace", "SomeName");
var result = _importer.ImportType(type);
Assert.Equal(type, result, Comparer);
Assert.Equal(_module, result.Module);
}
[Fact]
public void ImportAlreadyImportedTypeShouldUseSameInstance()
{
var type = new TypeReference(_dummyAssembly, "SomeNamespace", "SomeName");
var importedType = _importer.ImportType(type);
var result = _importer.ImportType(importedType);
Assert.Same(importedType, result);
}
[Fact]
public void ImportTypeDefFromDifferentModuleShouldReturnTypeRef()
{
var assembly = new AssemblyDefinition("ExternalAssembly", new Version(1, 2, 3, 4));
assembly.Modules.Add(new ModuleDefinition("ExternalAssembly.dll"));
var definition = new TypeDefinition("SomeNamespace", "SomeName", TypeAttributes.Public);
assembly.ManifestModule!.TopLevelTypes.Add(definition);
var result = _importer.ImportType(definition);
Assert.IsAssignableFrom<TypeReference>(result);
Assert.Equal(definition, result, Comparer);
}
[Fact]
public void ImportTypeDefInSameModuleShouldReturnSameInstance()
{
var definition = new TypeDefinition("SomeNamespace", "SomeName", TypeAttributes.Public);
_module.TopLevelTypes.Add(definition);
var importedType = _importer.ImportType(definition);
Assert.Same(definition, importedType);
}
[Fact]
public void ImportNestedTypeShouldImportParentType()
{
var declaringType = new TypeReference(_dummyAssembly, "SomeNamespace", "SomeName");
var nested = new TypeReference(declaringType, null, "Nested");
var result = _importer.ImportType(nested);
Assert.Equal(nested, result, Comparer);
Assert.Equal(_module, result.Module);
Assert.Equal(_module, result.DeclaringType?.Module);
}
[Fact]
public void ImportNestedTypeDefinitionShouldImportParentType()
{
var otherAssembly = new AssemblyDefinition(_dummyAssembly.Name, _dummyAssembly.Version);
var otherModule = new ModuleDefinition("OtherModule");
otherAssembly.Modules.Add(otherModule);
var objectType = otherModule.CorLibTypeFactory.Object.ToTypeDefOrRef();
var declaringType = new TypeDefinition(
"SomeNamespace",
"SomeName",
TypeAttributes.Class | TypeAttributes.Public,
objectType);
var nestedType = new TypeDefinition(
null,
"NestedType",
TypeAttributes.Class | TypeAttributes.NestedPublic,
objectType);
declaringType.NestedTypes.Add(nestedType);
otherModule.TopLevelTypes.Add(declaringType);
var reference = _importer.ImportType(nestedType);
Assert.NotNull(reference.DeclaringType);
Assert.Equal(declaringType, reference.DeclaringType, Comparer);
Assert.Equal(_module, reference.Module);
Assert.Equal(_module, reference.DeclaringType.Module);
}
[Fact]
public void ImportNestedTypeViaReflectionShouldImportParentType()
{
var module = ModuleDefinition.FromFile(typeof(TopLevelClass1).Assembly.Location, TestReaderParameters);
var declaringType = module.TopLevelTypes.First(t => t.Name == nameof(TopLevelClass1));
var nested = declaringType.NestedTypes.First(t => t.Name == nameof(TopLevelClass1.Nested1));
var result = _importer.ImportType(typeof(TopLevelClass1.Nested1));
Assert.Equal(nested, result, Comparer);
Assert.Equal(_module, result.Module);
Assert.Equal(_module, result.DeclaringType?.Module);
}
[Fact]
public void ImportSimpleTypeFromReflectionShouldResultInTypeRef()
{
var type = typeof(Console);
var result = _importer.ImportType(type);
Assert.IsAssignableFrom<TypeReference>(result);
Assert.Equal(type.FullName, result.FullName);
Assert.Equal(type.Assembly.GetName().Name, result.Scope?.Name);
}
[Fact]
public void ImportArrayTypeShouldResultInTypeSpecWithSzArray()
{
var type = typeof(Stream[]);
var result = _importer.ImportType(type);
Assert.IsAssignableFrom<TypeSpecification>(result);
Assert.IsAssignableFrom<SzArrayTypeSignature>(((TypeSpecification) result).Signature);
}
[Fact]
public void ImportCorLibTypeAsSignatureShouldResultInCorLibTypeSignature()
{
var type = typeof(string[]);
var result = _importer.ImportType(type);
Assert.IsAssignableFrom<TypeSpecification>(result);
var specification = (TypeSpecification) result;
Assert.IsAssignableFrom<SzArrayTypeSignature>(specification.Signature);
var arrayType = (SzArrayTypeSignature) specification.Signature;
Assert.IsAssignableFrom<CorLibTypeSignature>(arrayType.BaseType);
Assert.Equal(ElementType.String, arrayType.BaseType.ElementType);
}
[Fact]
public void ImportGenericTypeShouldResultInTypeSpecWithGenericInstance()
{
var type = typeof(List<string>);
var result = _importer.ImportType(type);
Assert.IsAssignableFrom<TypeSpecification>(result);
var specification = (TypeSpecification) result;
Assert.IsAssignableFrom<GenericInstanceTypeSignature>(specification.Signature);
var genericInstance = (GenericInstanceTypeSignature) specification.Signature;
Assert.Equal(typeof(List<>).FullName, genericInstance.GenericType.FullName);
Assert.Equal(new TypeSignature[]
{
_module.CorLibTypeFactory.String
}, genericInstance.TypeArguments);
}
[Fact]
public void ImportMethodFromExternalModuleShouldResultInMemberRef()
{
var type = new TypeReference(_dummyAssembly, null, "Type");
var method = new MemberReference(type, "Method",
MethodSignature.CreateStatic(_module.CorLibTypeFactory.String));
var result = _importer.ImportMethod(method);
Assert.Equal(method, result, Comparer);
Assert.Same(_module, result.Module);
}
[Fact]
public void ImportMethodFromSameModuleShouldResultInSameInstance()
{
var type = new TypeDefinition(null, "Type", TypeAttributes.Public);
_module.TopLevelTypes.Add(type);
var method = new MethodDefinition("Method", MethodAttributes.Public | MethodAttributes.Static,
MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void));
type.Methods.Add(method);
var result = _importer.ImportMethod(method);
Assert.Same(method, result);
}
[Fact]
public void ImportMethodFromGenericTypeThroughReflectionShouldIncludeGenericParamSig()
{
var method = typeof(List<string>).GetMethod("Add")!;
var result = _importer.ImportMethod(method);
Assert.IsAssignableFrom<GenericParameterSignature>(result.Signature?.ParameterTypes[0]);
var genericParameter = (GenericParameterSignature) result.Signature.ParameterTypes[0];
Assert.Equal(0, genericParameter.Index);
Assert.Equal(GenericParameterType.Type, genericParameter.ParameterType);
}
[Fact]
public void ImportGenericMethodFromReflectionShouldResultInMethodSpec()
{
var method = typeof(Enumerable)
.GetMethod("Empty")!
.MakeGenericMethod(typeof(string));
var result = _importer.ImportMethod(method);
Assert.IsAssignableFrom<MethodSpecification>(result);
var specification = (MethodSpecification) result;
Assert.Equal("Empty", result.Name);
Assert.Equal(new TypeSignature[]
{
_module.CorLibTypeFactory.String
}, specification.Signature?.TypeArguments, Comparer);
}
[Fact]
public void ImportFieldFromExternalModuleShouldResultInMemberRef()
{
var type = new TypeReference(_dummyAssembly, null, "Type");
var field = new MemberReference(
type,
"Field",
new FieldSignature(_module.CorLibTypeFactory.String));
var result = _importer.ImportField(field);
Assert.Equal(field, result, Comparer);
Assert.Same(_module, result.Module);
}
[Fact]
public void ImportFieldFromSameModuleShouldResultInSameInstance()
{
var type = new TypeDefinition(null, "Type", TypeAttributes.Public);
_module.TopLevelTypes.Add(type);
var field = new FieldDefinition(
"Field",
FieldAttributes.Public | FieldAttributes.Static,
_module.CorLibTypeFactory.Int32);
type.Fields.Add(field);
var result = _importer.ImportField(field);
Assert.Same(field, result);
}
[Fact]
public void ImportFieldFromReflectionShouldResultInMemberRef()
{
var field = typeof(string).GetField("Empty")!;
var result = _importer.ImportField(field);
Assert.Equal(field.Name, result.Name);
Assert.Equal(field.DeclaringType!.FullName, result.DeclaringType?.FullName);
Assert.Equal(field.FieldType.FullName, ((FieldSignature) result.Signature)?.FieldType.FullName);
}
[Fact]
public void ImportNonImportedTypeDefOrRefShouldResultInNewInstance()
{
var signature = new TypeReference(_module.CorLibTypeFactory.CorLibScope, "System.IO", "Stream")
.ToTypeSignature();
var imported = _importer.ImportTypeSignature(signature);
Assert.NotSame(signature, imported);
Assert.Equal(signature, imported, Comparer);
Assert.Equal(_module, imported.Module);
}
[Fact]
public void ImportTypeSpecWithNonImportedBaseTypeShouldResultInNewInstance()
{
var signature = new TypeReference(_module.CorLibTypeFactory.CorLibScope, "System.IO", "Stream")
.ToTypeSignature()
.MakeSzArrayType();
var imported = _importer.ImportTypeSignature(signature);
var newInstance = Assert.IsAssignableFrom<SzArrayTypeSignature>(imported);
Assert.NotSame(signature, newInstance);
Assert.Equal(signature, newInstance, Comparer);
Assert.Equal(_module, newInstance.BaseType.Module);
}
[Fact]
public void ImportFullyImportedTypeDefOrRefShouldResultInSameInstance()
{
var signature = new TypeReference(_module, _module.CorLibTypeFactory.CorLibScope, "System.IO", "Stream")
.ToTypeSignature();
var imported = _importer.ImportTypeSignature(signature);
Assert.Same(signature, imported);
}
[Fact]
public void ImportFullyImportedTypeSpecShouldResultInSameInstance()
{
var signature = new TypeReference(_module, _module.CorLibTypeFactory.CorLibScope, "System.IO", "Stream")
.ToTypeSignature()
.MakeSzArrayType();
var imported = _importer.ImportTypeSignature(signature);
Assert.Same(signature, imported);
}
[Fact]
public void ImportGenericTypeSigWithNonImportedTypeArgumentShouldResultInNewInstance()
{
// https://github.com/Washi1337/AsmResolver/issues/268
var genericType = new TypeDefinition("SomeNamespace", "SomeName", TypeAttributes.Class);
genericType.GenericParameters.Add(new GenericParameter("T"));
_module.TopLevelTypes.Add(genericType);
var instance = genericType.MakeGenericInstanceType(
new TypeDefOrRefSignature(
new TypeReference(_module.CorLibTypeFactory.CorLibScope, "System.IO", "Stream"), false)
);
var imported = _importer.ImportTypeSignature(instance);
var newInstance = Assert.IsAssignableFrom<GenericInstanceTypeSignature>(imported);
Assert.NotSame(instance, newInstance);
Assert.Equal(_module, newInstance.Module);
Assert.Equal(_module, newInstance.TypeArguments[0].Module);
}
[Fact]
public void ImportFullyImportedGenericTypeSigShouldResultInSameInstance()
{
// https://github.com/Washi1337/AsmResolver/issues/268
var genericType = new TypeDefinition("SomeNamespace", "SomeName", TypeAttributes.Class);
genericType.GenericParameters.Add(new GenericParameter("T"));
_module.TopLevelTypes.Add(genericType);
var instance = genericType.MakeGenericInstanceType(
new TypeDefOrRefSignature(
new TypeReference(_module, _module.CorLibTypeFactory.CorLibScope, "System.IO", "Stream"), false)
);
var imported = _importer.ImportTypeSignature(instance);
var newInstance = Assert.IsAssignableFrom<GenericInstanceTypeSignature>(imported);
Assert.Same(instance, newInstance);
}
[Fact]
public void ImportCustomModifierTypeWithNonImportedModifierTypeShouldResultInNewInstance()
{
var signature = new TypeReference(_module, _dummyAssembly, "SomeNamespace", "SomeType")
.ToTypeSignature()
.MakeModifierType(new TypeReference(_dummyAssembly, "SomeNamespace", "SomeModifierType"), true);
var imported = _importer.ImportTypeSignature(signature);
var newInstance = Assert.IsAssignableFrom<CustomModifierTypeSignature>(imported);
Assert.NotSame(signature, newInstance);
Assert.Equal(_module, newInstance.Module);
Assert.Equal(_module, newInstance.ModifierType.Module);
}
[Fact]
public void ImportFullyImportedCustomModifierTypeShouldResultInSameInstance()
{
var assembly = _importer.ImportScope(_dummyAssembly);
var signature = new TypeReference(_module, assembly, "SomeNamespace", "SomeType")
.ToTypeSignature()
.MakeModifierType(new TypeReference(_module, assembly, "SomeNamespace", "SomeModifierType"), true);
var imported = _importer.ImportTypeSignature(signature);
var newInstance = Assert.IsAssignableFrom<CustomModifierTypeSignature>(imported);
Assert.Same(signature, newInstance);
}
[Fact]
public void ImportFunctionPointerTypeWithNonImportedParameterShouldResultInNewInstance()
{
var signature = MethodSignature
.CreateStatic(
_module.CorLibTypeFactory.Void,
new TypeReference(_dummyAssembly, "SomeNamespace", "SomeType").ToTypeSignature())
.MakeFunctionPointerType();
var imported = _importer.ImportTypeSignature(signature);
var newInstance = Assert.IsAssignableFrom<FunctionPointerTypeSignature>(imported);
Assert.NotSame(signature, newInstance);
Assert.Equal(signature, newInstance, Comparer);
Assert.Equal(_module, newInstance.Module);
Assert.Equal(_module, newInstance.Signature.ParameterTypes[0].Module);
}
[Fact]
public void ImportFunctionPointerTypeWithNonImportedReturnTypeShouldResultInNewInstance()
{
var signature = MethodSignature
.CreateStatic(
new TypeReference(_dummyAssembly, "SomeNamespace", "SomeType").ToTypeSignature(),
_module.CorLibTypeFactory.Int32)
.MakeFunctionPointerType();
var imported = _importer.ImportTypeSignature(signature);
var newInstance = Assert.IsAssignableFrom<FunctionPointerTypeSignature>(imported);
Assert.NotSame(signature, newInstance);
Assert.Equal(signature, newInstance, Comparer);
Assert.Equal(_module, newInstance.Module);
Assert.Equal(_module, newInstance.Signature.ReturnType.Module);
}
[Fact]
public void ImportFullyImportedFunctionPointerTypeShouldResultInSameInstance()
{
var assembly = _importer.ImportScope(_dummyAssembly);
var signature = MethodSignature
.CreateStatic(
_module.CorLibTypeFactory.Void,
new TypeReference(_module, assembly, "SomeNamespace", "SomeType").ToTypeSignature())
.MakeFunctionPointerType();
var imported = _importer.ImportTypeSignature(signature);
var newInstance = Assert.IsAssignableFrom<FunctionPointerTypeSignature>(imported);
Assert.Same(signature, newInstance);
}
[Fact]
public void ImportInstanceFieldByReflectionShouldConstructValidFieldSignature()
{
// https://github.com/Washi1337/AsmResolver/issues/307
var module = ModuleDefinition.FromFile(typeof(SingleField).Assembly.Location, TestReaderParameters);
var field = module.GetAllTypes()
.First(t => t.Name == nameof(SingleField))
.Fields
.First(f => f.Name == nameof(SingleField.IntField));
var fieldInfo = typeof(SingleField).GetField(nameof(SingleField.IntField))!;
var importer = new ReferenceImporter(module);
var imported = importer.ImportField(fieldInfo);
var resolved = imported.Resolve();
Assert.NotNull(resolved);
Assert.Equal(field, Assert.IsAssignableFrom<IFieldDescriptor>(resolved), Comparer);
}
[Fact]
public void ImportGenericTypeInstantiationViaReflection()
{
var type = typeof(GenericType<int, string, Stream>);
var imported = Assert.IsAssignableFrom<TypeSpecification>(_importer.ImportType(type));
var signature = Assert.IsAssignableFrom<GenericInstanceTypeSignature>(imported.Signature);
Assert.Equal("Int32", signature.TypeArguments[0].Name);
Assert.Equal("String", signature.TypeArguments[1].Name);
Assert.Equal("Stream", signature.TypeArguments[2].Name);
}
[Fact]
public void ImportGenericMethodInstantiationViaReflection()
{
var method = typeof(NonGenericType)
.GetMethod(nameof(NonGenericType.GenericMethodInNonGenericType))!
.MakeGenericMethod(typeof(int), typeof(string), typeof(Stream));
var imported = Assert.IsAssignableFrom<MethodSpecification>(_importer.ImportMethod(method));
Assert.Equal(nameof(NonGenericType.GenericMethodInNonGenericType), imported.Name);
Assert.NotNull(imported.Signature);
Assert.True(imported.Method!.Signature!.IsGeneric);
Assert.Equal(3, imported.Method!.Signature!.GenericParameterCount);
Assert.Equal("Int32", imported.Signature.TypeArguments[0].Name);
Assert.Equal("String", imported.Signature.TypeArguments[1].Name);
Assert.Equal("Stream", imported.Signature.TypeArguments[2].Name);
}
[Fact]
public void ImportGenericMethodInstantiationWithReturnTypeViaReflection()
{
var method = typeof(GenericType<int, bool, Stream>)
.GetMethod(nameof(GenericType<int, bool, Stream>.NonGenericMethodWithReturnType))!;
var imported = Assert.IsAssignableFrom<IMethodDescriptor>(_importer.ImportMethod(method));
Assert.Equal(nameof(GenericType<int, bool, Stream>.NonGenericMethodWithReturnType), imported.Name);
Assert.NotNull(imported.Signature);
var signature = Assert.IsAssignableFrom<GenericParameterSignature>(imported.Signature.ReturnType);
Assert.Equal(2, signature.Index);
}
#if NET8_0_OR_GREATER
private static unsafe class DelegatePointerHolder
{
public static delegate*unmanaged[Cdecl, SuppressGCTransition]<int, uint> Complex = null;
public static delegate*unmanaged[Stdcall]<int, uint> StdcallOnly = null;
public static delegate*unmanaged[SuppressGCTransition]<int, uint> GcOnly = null;
}
[Fact]
public void ImportComplexFunctionPointerFromReflectedFieldType()
{
var fieldType = typeof(DelegatePointerHolder).GetField("Complex")!.GetModifiedFieldType();
var imported = Assert.IsAssignableFrom<FunctionPointerTypeSignature>(_importer.ImportType(fieldType).ToTypeSignature());
Assert.Equal(CallingConventionAttributes.Unmanaged, imported.Signature.CallingConvention);
var firstModifier = Assert.IsAssignableFrom<CustomModifierTypeSignature>(imported.Signature.ReturnType);
Assert.True(firstModifier.ModifierType is
{
Namespace.Value: "System.Runtime.CompilerServices",
Name.Value: "CallConvCdecl" or "CallConvSuppressGCTransition"
});
var secondModifier = Assert.IsAssignableFrom<CustomModifierTypeSignature>(firstModifier.BaseType);
Assert.True(secondModifier.ModifierType is
{
Namespace.Value: "System.Runtime.CompilerServices",
Name.Value: "CallConvCdecl" or "CallConvSuppressGCTransition"
});
}
[Fact]
public void ImportSimpleFunctionPointerFromReflectedFieldType()
{
var fieldType = typeof(DelegatePointerHolder).GetField("StdcallOnly")!.GetModifiedFieldType();
var imported = Assert.IsAssignableFrom<FunctionPointerTypeSignature>(_importer.ImportType(fieldType).ToTypeSignature());
Assert.Equal(CallingConventionAttributes.StdCall, imported.Signature.CallingConvention);
}
[Fact]
public void ImportModoptOnlyFunctionPointerFromReflectedFieldType()
{
var fieldType = typeof(DelegatePointerHolder).GetField("GcOnly")!.GetModifiedFieldType();
var imported = Assert.IsAssignableFrom<FunctionPointerTypeSignature>(_importer.ImportType(fieldType).ToTypeSignature());
Assert.Equal(CallingConventionAttributes.Unmanaged, imported.Signature.CallingConvention);
var firstModifier = Assert.IsAssignableFrom<CustomModifierTypeSignature>(imported.Signature.ReturnType);
Assert.Equal("System.Runtime.CompilerServices.CallConvSuppressGCTransition", firstModifier.ModifierType.FullName);
}
[Fact]
public void ImportFunctionPointerFromTypeof()
{
var imported = Assert.IsAssignableFrom<FunctionPointerTypeSignature>(_importer.ImportType(typeof(delegate*<int, uint>)).ToTypeSignature());
Assert.Collection(imported.Signature.ParameterTypes, t => Assert.Same(_module.CorLibTypeFactory.Int32, t));
Assert.Same(imported.Signature.ReturnType, _module.CorLibTypeFactory.UInt32);
}
#endif
} | 372 | 26,050 | using System;
namespace AsmResolver.DotNet.Cloning
{
/// <summary>
/// Provides an extension to the normal <see cref="ReferenceImporter"/> class, that takes cloned members into account.
/// </summary>
public class CloneContextAwareReferenceImporter : ReferenceImporter
{
private readonly MemberCloneContext _context;
/// <summary>
/// Creates a new instance of the <see cref="CloneContextAwareReferenceImporter"/> class.
/// </summary>
/// <param name="context">The metadata cloning workspace.</param>
public CloneContextAwareReferenceImporter(MemberCloneContext context)
: base(context.Module)
{
_context = context;
}
/// <summary>
/// The working space for this member cloning procedure.
/// </summary>
protected MemberCloneContext Context => _context;
/// <inheritdoc />
protected override ITypeDefOrRef ImportType(TypeDefinition type)
{
return _context.ClonedMembers.TryGetValue(type, out var clonedType)
? (ITypeDefOrRef) clonedType
: base.ImportType(type);
}
/// <inheritdoc />
public override IFieldDescriptor ImportField(IFieldDescriptor field)
{
return _context.ClonedMembers.TryGetValue(field, out var clonedField)
? (IFieldDescriptor) clonedField
: base.ImportField(field);
}
/// <inheritdoc />
public override IMethodDefOrRef ImportMethod(IMethodDefOrRef method)
{
return _context.ClonedMembers.TryGetValue(method, out var clonedMethod)
? (IMethodDefOrRef) clonedMethod
: base.ImportMethod(method);
}
/// <inheritdoc />
protected override ITypeDefOrRef ImportType(TypeReference type)
{
// Special case for System.Object.
if (type.IsTypeOf(nameof(System), nameof(Object)) && (type.Scope?.GetAssembly()?.IsCorLib ?? false))
return _context.Module.CorLibTypeFactory.Object.Type;
// Rare case where a type reference could point to one of the included type definitions
// (e.g., in custom attributes type arguments, see https://github.com/Washi1337/AsmResolver/issues/482).
if (_context.ClonedTypes.TryGetValue(type, out var clonedType))
return (ITypeDefOrRef) clonedType;
return base.ImportType(type);
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Resources\ResourceSetTest.cs | AsmResolver.DotNet.Tests.Resources
| ResourceSetTest | ['private static readonly ManifestResource Resource;'] | ['System.IO', 'System.Linq', 'System.Resources', 'AsmResolver.DotNet.Resources', 'AsmResolver.IO', 'Xunit', 'AsmResolver.DotNet.Resources.ResourceSet'] | xUnit | net8.0 | public class ResourceSetTest
{
private static readonly ManifestResource Resource;
static ResourceSetTest()
{
var module = ModuleDefinition.FromFile(typeof(TestCases.Resources.Resources).Assembly.Location, TestReaderParameters);
Resource = module.Resources.First(r =>
r.Name == "AsmResolver.DotNet.TestCases.Resources.Properties.Resources.resources");
}
public static ResourceSet ReadResourceSet()
{
Assert.True(Resource.TryGetReader(out var reader));
return ResourceSet.FromReader(reader);
}
[Theory]
[InlineData("Null", ResourceTypeCode.Null, null)]
[InlineData("String", ResourceTypeCode.String, "Hello, world!")]
[InlineData("BoolFalse", ResourceTypeCode.Boolean, false)]
[InlineData("BoolTrue", ResourceTypeCode.Boolean, true)]
[InlineData("Char", ResourceTypeCode.Char, 'a')]
[InlineData("Byte", ResourceTypeCode.Byte, (byte) 0x12)]
[InlineData("SByte", ResourceTypeCode.SByte, (sbyte) 0x12)]
[InlineData("UInt16", ResourceTypeCode.UInt16, (ushort) 0x1234)]
[InlineData("Int16", ResourceTypeCode.Int16, (short) 0x1234)]
[InlineData("UInt32", ResourceTypeCode.UInt32, (uint) 0x12345678)]
[InlineData("Int32", ResourceTypeCode.Int32, (int) 0x12345678)]
[InlineData("UInt64", ResourceTypeCode.UInt64, (ulong) 0x123456789abcdef)]
[InlineData("Int64", ResourceTypeCode.Int64, (long) 0x123456789abcdef)]
[InlineData("Single", ResourceTypeCode.Single, 1.234f)]
[InlineData("Double", ResourceTypeCode.Double, 1.234D)]
public void ReadIntrinsicElement(string key, ResourceTypeCode expectedType, object expectedValue)
{
var entry = ReadResourceSet().First(e => e.Name == key);
Assert.Equal(IntrinsicResourceType.Get(expectedType), entry.Type);
Assert.Equal(expectedValue, entry.Data);
}
[Fact]
public void ReadUserDefinedTypeElement()
{
var entry = ReadResourceSet().First(e => e.Name == "Point");
Assert.Equal(
"System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
entry.Type.FullName);
Assert.Equal(
new byte[]
{
0x03, 0x06, 0x31, 0x32, 0x2C, 0x20, 0x33, 0x34
}, entry.Data);
}
[Theory]
[InlineData("Null", ResourceTypeCode.Null, null)]
[InlineData("String", ResourceTypeCode.String, "Hello, world!")]
[InlineData("BoolFalse", ResourceTypeCode.Boolean, false)]
[InlineData("BoolTrue", ResourceTypeCode.Boolean, true)]
[InlineData("Char", ResourceTypeCode.Char, 'a')]
[InlineData("Byte", ResourceTypeCode.Byte, (byte) 0x12)]
[InlineData("SByte", ResourceTypeCode.SByte, (sbyte) 0x12)]
[InlineData("UInt16", ResourceTypeCode.UInt16, (ushort) 0x1234)]
[InlineData("Int16", ResourceTypeCode.Int16, (short) 0x1234)]
[InlineData("UInt32", ResourceTypeCode.UInt32, (uint) 0x12345678)]
[InlineData("Int32", ResourceTypeCode.Int32, (int) 0x12345678)]
[InlineData("UInt64", ResourceTypeCode.UInt64, (ulong) 0x123456789abcdef)]
[InlineData("Int64", ResourceTypeCode.Int64, (long) 0x123456789abcdef)]
[InlineData("Single", ResourceTypeCode.Single, 1.234f)]
[InlineData("Double", ResourceTypeCode.Double, 1.234D)]
public void PersistentIntrinsicElement(string key, ResourceTypeCode type, object value)
{
var set = new ResourceSet();
var entry = new ResourceSetEntry(key, type, value);
set.Add(entry);
using var stream = new MemoryStream();
set.Write(new BinaryStreamWriter(stream));
var actualSet = ResourceSet.FromReader(new BinaryStreamReader(stream.ToArray()));
var actualEntry = actualSet.First(e => e.Name == key);
Assert.Equal(entry.Type, actualEntry.Type);
Assert.Equal(entry.Data, actualEntry.Data);
}
[Fact]
public void PersistentUserDefinedTypeElement()
{
var type = new UserDefinedResourceType(
"System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
var set = new ResourceSet(ResourceManagerHeader.Deserializing_v4_0_0_0);
var entry = new ResourceSetEntry("Point", type,
new byte[]
{
0x03, 0x06, 0x31, 0x32, 0x2C, 0x20, 0x33, 0x34
});
set.Add(entry);
using var stream = new MemoryStream();
set.Write(new BinaryStreamWriter(stream));
var actualSet = ResourceSet.FromReader(new BinaryStreamReader(stream.ToArray()));
var actualEntry = actualSet.First(e => e.Name == "Point");
Assert.Equal(entry.Type.FullName, actualEntry.Type.FullName);
Assert.Equal(entry.Data, actualEntry.Data);
}
[Fact]
public void PersistentSetMultipleEntries()
{
var set = new ResourceSet
{
new("Lorem", ResourceTypeCode.ByteArray, new byte[] {1, 2, 3, 4, 5, 6}),
new("Ipsum", ResourceTypeCode.ByteArray, new byte[] {7, 8, 9, 10}),
new("Dolor", ResourceTypeCode.ByteArray, new byte[] {11, 12, 13, 14, 15, 16, 17}),
new("Sit", ResourceTypeCode.ByteArray, new byte[] {18}),
new("Amet", ResourceTypeCode.ByteArray, new byte[] {19, 20, 21, 22, 23}),
};
using var stream = new MemoryStream();
set.Write(new BinaryStreamWriter(stream));
stream.Position = 0;
var resourceReader = new ResourceReader(stream);
var actualSet = ResourceSet.FromReader(new BinaryStreamReader(stream.ToArray()));
Assert.Equal(set.Count, actualSet.Count);
for (int i = 0; i < set.Count; i++)
{
var entry = set[i];
var actualEntry = actualSet.First(x => x.Name == entry.Name);
// Verify type and contents.
Assert.Equal(entry.Type, actualEntry.Type);
Assert.Equal(entry.Data, actualEntry.Data);
// Verify default resource reader can still get to the data (== hash table verification).
resourceReader.GetResourceData(entry.Name, out string type, out byte[] data);
}
}
} | 255 | 7,068 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using AsmResolver.Collections;
using AsmResolver.IO;
namespace AsmResolver.DotNet.Resources
{
/// <summary>
/// Represents a set of resources embedded into a ".resources" file.
/// </summary>
public class ResourceSet : LazyList<ResourceSetEntry>
{
/// <summary>
/// Creates a new empty resource set, targeting the default <c>System.Resources.ResourceReader</c> and
/// <c>System.Resources.RuntimeResourceSet</c> back-end classes, and using file format 2.
/// </summary>
public ResourceSet()
: this(ResourceManagerHeader.Default_v4_0_0_0, 2)
{
}
/// <summary>
/// Creates a new empty resource set using file format 2.
/// </summary>
/// <param name="managerHeader">The header to target.</param>
public ResourceSet(ResourceManagerHeader managerHeader)
: this(managerHeader, 2)
{
}
/// <summary>
/// Creates a new empty resource set.
/// </summary>
/// <param name="managerHeader">The header to target.</param>
/// <param name="formatVersion">The version of the file format.</param>
public ResourceSet(ResourceManagerHeader managerHeader, int formatVersion)
{
ManagerHeader = managerHeader;
FormatVersion = formatVersion;
}
/// <summary>
/// Gets or sets the resource manager header of the set.
/// </summary>
public ResourceManagerHeader ManagerHeader
{
get;
set;
}
/// <summary>
/// Gets the version of the file format that is used for this resource set.
/// </summary>
public int FormatVersion
{
get;
set;
}
/// <summary>
/// Reads a resource set from the provided input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <returns>The resource set.</returns>
public static ResourceSet FromReader(in BinaryStreamReader reader) =>
FromReader(reader, DefaultResourceDataSerializer.Instance);
/// <summary>
/// Reads a resource set from the provided input stream.
/// </summary>
/// <param name="reader">The input stream.</param>
/// <param name="serializer">The object responsible for deserializing user-defined types.</param>
/// <returns>The resource set.</returns>
public static ResourceSet FromReader(in BinaryStreamReader reader, IResourceDataSerializer serializer) =>
new SerializedResourceSet(reader, serializer);
/// <inheritdoc />
protected override void Initialize()
{
}
/// <summary>
/// Serializes the resource set and writes it to the provided output stream.
/// </summary>
/// <param name="writer">The output stream.</param>
/// <exception cref="NotSupportedException">Occurs when an invalid or unsupported version is specified in <see cref="FormatVersion"/>.</exception>
public void Write(BinaryStreamWriter writer) => Write(writer, DefaultResourceDataSerializer.Instance);
/// <summary>
/// Serializes the resource set and writes it to the provided output stream.
/// </summary>
/// <param name="writer">The output stream.</param>
/// <param name="serializer">The object responsible for serializing user-defined types.</param>
/// <exception cref="NotSupportedException">Occurs when an invalid or unsupported version is specified in <see cref="FormatVersion"/>.</exception>
public void Write(BinaryStreamWriter writer, IResourceDataSerializer serializer)
{
if (FormatVersion is not 1 and not 2)
throw new NotSupportedException($"Invalid or unsupported format version {FormatVersion}.");
using var dataSection = new MemoryStream();
var dataWriter = new BinaryStreamWriter(dataSection);
// Entry headers.
var sortedEntries = Items.OrderBy(item => item.Name).ToArray();
var entryHeaders = new ResourceSetEntryHeader[Count];
uint entryOffset = 0;
// Hash table.
uint[] nameHashes = new uint[Count];
uint[] nameOffsets = new uint[Count];
// Type codes.
var userTypeNames = new List<string>();
var typeNameToTypeCode = new Dictionary<string, int>();
// Add all items in the resource set.
for (int i = 0; i < sortedEntries.Length; i++)
{
var item = sortedEntries[i];
// Determine type code.
if ((FormatVersion == 1 || item.Type is not IntrinsicResourceType)
&& !typeNameToTypeCode.TryGetValue(item.Type.FullName, out int typeCode))
{
// New user-defined type. Add it to the list.
typeCode = userTypeNames.Count;
if (FormatVersion == 2)
typeCode += (int) ResourceTypeCode.StartOfUserTypes;
typeNameToTypeCode[item.Type.FullName] = typeCode;
userTypeNames.Add(item.Type.FullName);
}
else if (item.Type is IntrinsicResourceType intrinsicType)
{
// Format allows for intrinsic types to be used.
typeCode = (int)intrinsicType.TypeCode;
}
else
{
throw new NotSupportedException($"Invalid or unsupported resource type {item.Type.FullName}.");
}
// Create and add entry header to hash table.
var entryHeader = new ResourceSetEntryHeader(item.Name, (uint) dataWriter.Offset);
entryHeaders[i] = entryHeader;
nameHashes[i] = HashString(item.Name);
nameOffsets[i] = entryOffset;
entryOffset += entryHeader.GetPhysicalSize();
// Write data to data section.
item.Write(dataWriter, FormatVersion, typeCode, serializer);
}
// Write header.
ManagerHeader.Write(writer);
writer.WriteInt32(FormatVersion);
writer.WriteInt32(Count);
// Write user types.
writer.WriteInt32(userTypeNames.Count);
foreach (string typeName in userTypeNames)
writer.WriteBinaryFormatterString(typeName);
// Write padding.
int x = 0;
while ((writer.Offset & 0b111) != 0)
writer.WriteByte((byte) "PAD"[x++ % 3]);
// Write hash table.
Array.Sort(nameHashes, nameOffsets);
foreach (uint hash in nameHashes)
writer.WriteUInt32(hash);
foreach (uint offset in nameOffsets)
writer.WriteUInt32(offset);
// Write location of data section.
writer.WriteUInt32((uint) (writer.Offset + sizeof(uint) + entryOffset));
// Write names in name table
foreach (var header in entryHeaders)
header.Write(writer);
// Write data section.
writer.WriteBytes(dataSection.ToArray());
}
private static uint HashString(string key)
{
// Reference:
// https://github.com/dotnet/runtime/blob/97ef512a7cbc21d982ce68de805fec2c42e3561c/src/libraries/System.Private.CoreLib/src/System/Resources/FastResourceComparer.cs#L42
uint hash = 5381;
foreach (char c in key)
hash = ((hash << 5) + hash) ^ c;
return hash;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\RuntimeContextTest.cs | AsmResolver.DotNet.Tests
| RuntimeContextTest | [] | ['System', 'AsmResolver.DotNet.Serialized', 'AsmResolver.DotNet.TestCases.Methods', 'AsmResolver.DotNet.TestCases.Types', 'AsmResolver.IO', 'Xunit'] | xUnit | net8.0 | public class RuntimeContextTest
{
[Fact]
public void ResolveDependencyShouldUseSameRuntimeContext()
{
var main = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var dependency = main.CorLibTypeFactory.CorLibScope.GetAssembly()!.Resolve()!.ManifestModule!;
Assert.Same(main.RuntimeContext, dependency.RuntimeContext);
}
[Fact]
public void ResolveDependencyShouldUseSameFileService()
{
var service = new ByteArrayFileService();
service.OpenBytesAsFile("HelloWorld.dll", Properties.Resources.HelloWorld);
var main = ModuleDefinition.FromFile("HelloWorld.dll", new ModuleReaderParameters(service));
var dependency = main.CorLibTypeFactory.CorLibScope.GetAssembly()!.Resolve()!.ManifestModule!;
Assert.Contains(main.FilePath, service.GetOpenedFiles());
Assert.Contains(dependency.FilePath, service.GetOpenedFiles());
}
[Fact]
public void DetectNetFrameworkContext()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Equal(
new DotNetRuntimeInfo(DotNetRuntimeInfo.NetFramework, new Version(4, 0)),
module.RuntimeContext.TargetRuntime
);
}
[Fact]
public void DetectNetCoreAppContext()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_NetCore, TestReaderParameters);
Assert.Equal(
new DotNetRuntimeInfo(DotNetRuntimeInfo.NetCoreApp, new Version(2, 2)),
module.RuntimeContext.TargetRuntime
);
}
[Fact]
public void ForceNetFXLoadAsNetCore()
{
var context = new RuntimeContext(new DotNetRuntimeInfo(DotNetRuntimeInfo.NetCoreApp, new Version(3, 1)));
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, new ModuleReaderParameters(context));
Assert.Equal(context.TargetRuntime, module.RuntimeContext.TargetRuntime);
Assert.IsAssignableFrom<DotNetCoreAssemblyResolver>(module.MetadataResolver.AssemblyResolver);
}
[Fact]
public void ForceNetStandardLoadAsNetFx()
{
var context = new RuntimeContext(new DotNetRuntimeInfo(DotNetRuntimeInfo.NetFramework, new Version(4, 8)));
var module = ModuleDefinition.FromFile(typeof(Class).Assembly.Location, new ModuleReaderParameters(context));
Assert.Equal(context.TargetRuntime, module.RuntimeContext.TargetRuntime);
Assert.Equal("mscorlib", module.CorLibTypeFactory.Object.Resolve()?.Module?.Assembly?.Name);
}
[Fact]
public void ForceNetStandardLoadAsNetCore()
{
var context = new RuntimeContext(new DotNetRuntimeInfo(DotNetRuntimeInfo.NetCoreApp, new Version(3, 1)));
var module = ModuleDefinition.FromFile(typeof(Class).Assembly.Location, new ModuleReaderParameters(context));
Assert.Equal(context.TargetRuntime, module.RuntimeContext.TargetRuntime);
Assert.Equal("System.Private.CoreLib", module.CorLibTypeFactory.Object.Resolve()?.Module?.Assembly?.Name);
}
[Fact]
public void ResolveSameDependencyInSameContextShouldResultInSameAssembly()
{
var module1 = ModuleDefinition.FromFile(typeof(Class).Assembly.Location, TestReaderParameters);
var module2 = ModuleDefinition.FromFile(typeof(SingleMethod).Assembly.Location, new ModuleReaderParameters
{
RuntimeContext = module1.RuntimeContext
});
var object1 = module1.CorLibTypeFactory.Object.Resolve();
var object2 = module2.CorLibTypeFactory.Object.Resolve();
Assert.NotNull(object1);
Assert.Same(object1, object2);
}
} | 223 | 4,325 | using System;
using System.Reflection;
using AsmResolver.DotNet.Bundles;
using AsmResolver.DotNet.Serialized;
using AsmResolver.IO;
namespace AsmResolver.DotNet
{
/// <summary>
/// Describes a context in which a .NET runtime is active.
/// </summary>
public class RuntimeContext
{
/// <summary>
/// Creates a new runtime context.
/// </summary>
/// <param name="targetRuntime">The target runtime version.</param>
public RuntimeContext(DotNetRuntimeInfo targetRuntime)
: this(targetRuntime, new ModuleReaderParameters(new ByteArrayFileService()))
{
}
/// <summary>
/// Creates a new runtime context.
/// </summary>
/// <param name="targetRuntime">The target runtime version.</param>
/// <param name="readerParameters">The parameters to use when reading modules in this context.</param>
public RuntimeContext(DotNetRuntimeInfo targetRuntime, ModuleReaderParameters readerParameters)
{
TargetRuntime = targetRuntime;
DefaultReaderParameters = new ModuleReaderParameters(readerParameters) {RuntimeContext = this};
AssemblyResolver = CreateAssemblyResolver(targetRuntime, DefaultReaderParameters);
}
/// <summary>
/// Creates a new runtime context.
/// </summary>
/// <param name="targetRuntime">The target runtime version.</param>
/// <param name="assemblyResolver">The assembly resolver to use when resolving assemblies into this context.</param>
public RuntimeContext(DotNetRuntimeInfo targetRuntime, IAssemblyResolver assemblyResolver)
{
TargetRuntime = targetRuntime;
DefaultReaderParameters = new ModuleReaderParameters(new ByteArrayFileService()) {RuntimeContext = this};
AssemblyResolver = assemblyResolver;
}
/// <summary>
/// Creates a new runtime context for the provided bundled application.
/// </summary>
/// <param name="manifest">The bundle to create the runtime context for.</param>
public RuntimeContext(BundleManifest manifest)
: this(manifest, new ModuleReaderParameters(new ByteArrayFileService()))
{
}
/// <summary>
/// Creates a new runtime context.
/// </summary>
/// <param name="manifest">The bundle to create the runtime context for.</param>
/// <param name="readerParameters">The parameters to use when reading modules in this context.</param>
public RuntimeContext(BundleManifest manifest, ModuleReaderParameters readerParameters)
{
TargetRuntime = manifest.GetTargetRuntime();
DefaultReaderParameters = new ModuleReaderParameters(readerParameters) {RuntimeContext = this};
AssemblyResolver = new BundleAssemblyResolver(manifest, readerParameters);
}
/// <summary>
/// Gets the runtime version this context is targeting.
/// </summary>
public DotNetRuntimeInfo TargetRuntime
{
get;
}
/// <summary>
/// Gets the default parameters that are used for reading .NET modules in the context.
/// </summary>
public ModuleReaderParameters DefaultReaderParameters
{
get;
}
/// <summary>
/// Gets the assembly resolver that the context uses to resolve assemblies.
/// </summary>
public IAssemblyResolver AssemblyResolver
{
get;
}
private static IAssemblyResolver CreateAssemblyResolver(
DotNetRuntimeInfo runtime,
ModuleReaderParameters readerParameters)
{
switch (runtime.Name)
{
case DotNetRuntimeInfo.NetFramework:
case DotNetRuntimeInfo.NetStandard when string.IsNullOrEmpty(DotNetCorePathProvider.DefaultInstallationPath):
return new DotNetFrameworkAssemblyResolver(readerParameters);
case DotNetRuntimeInfo.NetStandard when DotNetCorePathProvider.Default.TryGetLatestStandardCompatibleVersion(runtime.Version, out var coreVersion):
return new DotNetCoreAssemblyResolver(readerParameters, coreVersion);
case DotNetRuntimeInfo.NetCoreApp:
return new DotNetCoreAssemblyResolver(readerParameters, runtime.Version);
default:
return new DotNetFrameworkAssemblyResolver(readerParameters);
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\SecurityDeclarationTest.cs | AsmResolver.DotNet.Tests
| SecurityDeclarationTest | [] | ['System.IO', 'System.Linq', 'AsmResolver.DotNet.TestCases.CustomAttributes', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class SecurityDeclarationTest
{
private static MethodDefinition LookupMethod(string methodName, bool rebuild)
{
var module = ModuleDefinition.FromFile(typeof(SecurityAttributes).Assembly.Location, TestReaderParameters);
if (rebuild)
{
var stream = new MemoryStream();
module.Write(stream);
module = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
}
var type = module.TopLevelTypes.First(t => t.Name == nameof(SecurityAttributes));
return type.Methods.First(m => m.Name == methodName);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void RowSecurityAction(bool rebuild)
{
var method = LookupMethod(nameof(SecurityAttributes.NoParameters), rebuild);
Assert.Contains(method.SecurityDeclarations, declaration => declaration.Action == SecurityAction.Assert);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void RowAttributeType(bool rebuild)
{
var method = LookupMethod(nameof(SecurityAttributes.NoParameters), rebuild);
var declaration = method.SecurityDeclarations[0];
Assert.Single(declaration.PermissionSet.Attributes);
var attribute = declaration.PermissionSet.Attributes[0];
Assert.Equal(nameof(CustomCodeAccessSecurityAttribute), attribute.AttributeType.Name);
Assert.Empty(attribute.NamedArguments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void NoParameters(bool rebuild)
{
var method = LookupMethod(nameof(SecurityAttributes.NoParameters), rebuild);
var declaration = method.SecurityDeclarations[0];
var attribute = declaration.PermissionSet.Attributes[0];
Assert.Empty(attribute.NamedArguments);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SingleParameter(bool rebuild)
{
var method = LookupMethod(nameof(SecurityAttributes.SingleParameter), rebuild);
var declaration = method.SecurityDeclarations[0];
var attribute = declaration.PermissionSet.Attributes[0];
Assert.Contains(attribute.NamedArguments, argument =>
argument.MemberName == nameof(CustomCodeAccessSecurityAttribute.PropertyA)
&& argument.Argument.Element.Equals(1));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void MultipleParameters(bool rebuild)
{
var method = LookupMethod(nameof(SecurityAttributes.MultipleParameters), rebuild);
var declaration = method.SecurityDeclarations[0];
var attribute = declaration.PermissionSet.Attributes[0];
Assert.Contains(attribute.NamedArguments, argument =>
argument.MemberName == nameof(CustomCodeAccessSecurityAttribute.PropertyA)
&& argument.Argument.Element.Equals(1));
Assert.Contains(attribute.NamedArguments, argument =>
argument.MemberName == nameof(CustomCodeAccessSecurityAttribute.PropertyB)
&& argument.Argument.Element.Equals(2));
Assert.Contains(attribute.NamedArguments, argument =>
argument.MemberName == nameof(CustomCodeAccessSecurityAttribute.PropertyC)
&& argument.Argument.Element.Equals(3));
}
} | 220 | 3,916 | using System.Collections.Generic;
namespace AsmResolver.DotNet
{
/// <summary>
/// Represents a member that can be assigned security declarations, and can be referenced by a HasDeclSecurity
/// coded index.
/// </summary>
public interface IHasSecurityDeclaration : IMetadataMember
{
/// <summary>
/// Gets a collection of security declarations assigned to the member.
/// </summary>
IList<SecurityDeclaration> SecurityDeclarations
{
get;
}
}
} |
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Signatures\GenericContextTest.cs | AsmResolver.DotNet.Tests.Signatures
| GenericContextTest | ['private readonly ReferenceImporter _importer;'] | ['System.Collections.Generic', 'AsmResolver.DotNet.Signatures', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class GenericContextTest
{
private readonly ReferenceImporter _importer;
public GenericContextTest()
{
var module = new ModuleDefinition("TempModule");
_importer = new ReferenceImporter(module);
}
[Theory]
[InlineData(GenericParameterType.Type)]
[InlineData(GenericParameterType.Method)]
public void ResolveGenericParameterWithEmptyType(GenericParameterType parameterType)
{
var context = new GenericContext();
var parameter = new GenericParameterSignature(parameterType, 0);
Assert.Equal(parameter, context.GetTypeArgument(parameter));
}
[Fact]
public void ResolveMethodGenericParameterWithMethod()
{
var genericInstance = new GenericInstanceMethodSignature();
genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var context = new GenericContext(null, genericInstance);
var parameter = new GenericParameterSignature(GenericParameterType.Method, 0);
Assert.Equal("System.String", context.GetTypeArgument(parameter).FullName);
}
[Fact]
public void ResolveTypeGenericParameterWithType()
{
var genericInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false);
genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var context = new GenericContext(genericInstance, null);
var parameter = new GenericParameterSignature(GenericParameterType.Type, 0);
Assert.Equal("System.String", context.GetTypeArgument(parameter).FullName);
}
[Fact]
public void ResolveTypeGenericParameterWithTypeAndMethod()
{
var genericType = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false);
genericType.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var genericMethod = new GenericInstanceMethodSignature();
genericMethod.TypeArguments.Add(_importer.ImportTypeSignature(typeof(int)));
var context = new GenericContext(genericType, genericMethod);
var parameter = new GenericParameterSignature(GenericParameterType.Type, 0);
Assert.Equal("System.String", context.GetTypeArgument(parameter).FullName);
}
[Fact]
public void ResolveMethodGenericParameterWithTypeAndMethod()
{
var genericType = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false);
genericType.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var genericMethod = new GenericInstanceMethodSignature();
genericMethod.TypeArguments.Add(_importer.ImportTypeSignature(typeof(int)));
var context = new GenericContext(genericType, genericMethod);
var parameter = new GenericParameterSignature(GenericParameterType.Method, 0);
Assert.Equal("System.Int32", context.GetTypeArgument(parameter).FullName);
}
[Fact]
public void ResolveTypeGenericParameterWithOnlyMethod()
{
var genericInstance = new GenericInstanceMethodSignature();
genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var context = new GenericContext(null, genericInstance);
var parameter = new GenericParameterSignature(GenericParameterType.Type, 0);
Assert.Equal(parameter, context.GetTypeArgument(parameter));
}
[Fact]
public void ResolveMethodGenericParameterWithOnlyType()
{
var genericInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false);
genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var context = new GenericContext(genericInstance, null);
var parameter = new GenericParameterSignature(GenericParameterType.Method, 0);
Assert.Equal(parameter, context.GetTypeArgument(parameter));
}
[Fact]
public void ParseGenericFromTypeSignature()
{
var genericInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false);
genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var context = GenericContext.FromType(genericInstance);
var context2 = GenericContext.FromMember(genericInstance);
var context3 = GenericContext.FromType((ITypeDescriptor) genericInstance);
Assert.Equal(context, context3);
Assert.Equal(context, context2);
Assert.False(context.IsEmpty);
Assert.Equal(genericInstance, context.Type);
Assert.Null(context.Method);
}
[Fact]
public void ParseGenericFromNonGenericTypeSignature()
{
var type = new TypeDefinition("", "Test type", TypeAttributes.Public);
var notGenericSignature = new TypeDefOrRefSignature(type);
var context = GenericContext.FromType(notGenericSignature);
var context2 = GenericContext.FromMember(notGenericSignature);
Assert.Equal(context, context2);
Assert.True(context.IsEmpty);
}
[Fact]
public void ParseGenericFromTypeSpecification()
{
var genericInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false);
genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var typeSpecification = new TypeSpecification(genericInstance);
var context = GenericContext.FromType(typeSpecification);
var context2 = GenericContext.FromMember(typeSpecification);
var context3 = GenericContext.FromType((ITypeDescriptor) typeSpecification);
Assert.Equal(context, context3);
Assert.Equal(context, context2);
Assert.False(context.IsEmpty);
Assert.Equal(genericInstance, context.Type);
Assert.Null(context.Method);
}
[Fact]
public void ParseGenericFromMethodSpecification()
{
var genericParameter = new GenericParameterSignature(GenericParameterType.Method, 0);
var method = new MethodDefinition("TestMethod", MethodAttributes.Private,
MethodSignature.CreateStatic(genericParameter));
var genericInstance = new GenericInstanceMethodSignature();
genericInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(int)));
var methodSpecification = new MethodSpecification(method, genericInstance);
var context = GenericContext.FromMethod(methodSpecification);
var context2 = GenericContext.FromMember(methodSpecification);
var context3 = GenericContext.FromMethod((IMethodDescriptor) methodSpecification);
Assert.Equal(context, context3);
Assert.Equal(context, context2);
Assert.False(context.IsEmpty);
Assert.Null(context.Type);
Assert.Equal(genericInstance, context.Method);
}
[Fact]
public void ParseGenericFromMethodSpecificationWithTypeSpecification()
{
var genericTypeInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false);
genericTypeInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var typeSpecification = new TypeSpecification(genericTypeInstance);
var genericParameter = new GenericParameterSignature(GenericParameterType.Method, 0);
var method = new MemberReference(typeSpecification, "TestMethod",
MethodSignature.CreateStatic(genericParameter));
var genericMethodInstance = new GenericInstanceMethodSignature();
genericMethodInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(int)));
var methodSpecification = new MethodSpecification(method, genericMethodInstance);
var context = GenericContext.FromMethod(methodSpecification);
var context2 = GenericContext.FromMember(methodSpecification);
var context3 = GenericContext.FromMethod((IMethodDescriptor) methodSpecification);
Assert.Equal(context, context3);
Assert.Equal(context, context2);
Assert.False(context.IsEmpty);
Assert.Equal(genericTypeInstance, context.Type);
Assert.Equal(genericMethodInstance, context.Method);
}
[Fact]
public void ParseGenericFromNotGenericTypeSpecification()
{
var type = new TypeDefinition("", "Test type", TypeAttributes.Public);
var notGenericSignature = new TypeDefOrRefSignature(type);
var typeSpecification = new TypeSpecification(notGenericSignature);
var context = GenericContext.FromType(typeSpecification);
var context2 = GenericContext.FromMember(typeSpecification);
var context3 = GenericContext.FromType((ITypeDescriptor) typeSpecification);
Assert.Equal(context, context3);
Assert.Equal(context, context2);
Assert.True(context.IsEmpty);
}
[Fact]
public void ParseGenericFromNotGenericMethodSpecification()
{
var type = new TypeDefinition("", "Test type", TypeAttributes.Public);
var notGenericSignature = new TypeDefOrRefSignature(type);
var method = new MethodDefinition("TestMethod", MethodAttributes.Private,
MethodSignature.CreateStatic(notGenericSignature));
var methodSpecification = new MethodSpecification(method, null);
var context = GenericContext.FromMethod(methodSpecification);
var context2 = GenericContext.FromMember(methodSpecification);
var context3 = GenericContext.FromMethod((IMethodDescriptor) methodSpecification);
Assert.Equal(context, context3);
Assert.Equal(context, context2);
Assert.True(context.IsEmpty);
}
[Fact]
public void ParseGenericFromNotGenericMethodSpecificationWithTypeSpecification()
{
var genericTypeInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false);
genericTypeInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var typeSpecification = new TypeSpecification(genericTypeInstance);
var type = new TypeDefinition("", "Test type", TypeAttributes.Public);
var notGenericSignature = new TypeDefOrRefSignature(type);
var method = new MemberReference(typeSpecification, "TestMethod",
MethodSignature.CreateStatic(notGenericSignature));
var methodSpecification = new MethodSpecification(method, null);
var context = GenericContext.FromMethod(methodSpecification);
var context2 = GenericContext.FromMember(methodSpecification);
var context3 = GenericContext.FromMethod((IMethodDescriptor) methodSpecification);
Assert.Equal(context, context3);
Assert.Equal(context, context2);
Assert.False(context.IsEmpty);
Assert.Equal(genericTypeInstance, context.Type);
Assert.Null(context.Method);
}
[Fact]
public void ParseGenericFromField()
{
var genericTypeInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false);
genericTypeInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var typeSpecification = new TypeSpecification(genericTypeInstance);
var genericParameter = new GenericParameterSignature(GenericParameterType.Type, 0);
var field = new FieldDefinition("Field", FieldAttributes.Private, genericParameter);
var member = new MemberReference(typeSpecification, field.Name, field.Signature);
var context = GenericContext.FromField(member);
var context2 = GenericContext.FromMember(member);
Assert.Equal(context, context2);
Assert.False(context.IsEmpty);
Assert.Equal(genericTypeInstance, context.Type);
Assert.Null(context.Method);
}
[Fact]
public void ParseGenericFromNotGenericField()
{
var type = new TypeDefinition("", "Test type", TypeAttributes.Public);
var notGenericSignature = new TypeDefOrRefSignature(type);
var field = new FieldDefinition("Field", FieldAttributes.Private, notGenericSignature);
var member = new MemberReference(type, field.Name, field.Signature);
var context = GenericContext.FromField(member);
var context2 = GenericContext.FromMember(member);
Assert.Equal(context, context2);
Assert.True(context.IsEmpty);
}
[Fact]
public void ParseGenericFromMethod()
{
var genericTypeInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false);
genericTypeInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var typeSpecification = new TypeSpecification(genericTypeInstance);
var genericParameter = new GenericParameterSignature(GenericParameterType.Type, 0);
var method = new MethodDefinition("Method", MethodAttributes.Private,
MethodSignature.CreateStatic(genericParameter));
var member = new MemberReference(typeSpecification, method.Name, method.Signature);
var context = GenericContext.FromMethod(member);
var context2 = GenericContext.FromMember(member);
Assert.Equal(context, context2);
Assert.False(context.IsEmpty);
Assert.Equal(genericTypeInstance, context.Type);
Assert.Null(context.Method);
}
[Fact]
public void ParseGenericFromNotGenericMethod()
{
var type = new TypeDefinition("", "Test type", TypeAttributes.Public);
var notGenericSignature = new TypeDefOrRefSignature(type);
var method = new MethodDefinition("Method", MethodAttributes.Private,
MethodSignature.CreateStatic(notGenericSignature));
var member = new MemberReference(type, method.Name, method.Signature);
var context = GenericContext.FromMethod(member);
var context2 = GenericContext.FromMember(member);
Assert.Equal(context, context2);
Assert.True(context.IsEmpty);
}
[Fact]
public void ParseGenericFromProperty()
{
var genericTypeInstance = new GenericInstanceTypeSignature(_importer.ImportType(typeof(List<>)), false);
genericTypeInstance.TypeArguments.Add(_importer.ImportTypeSignature(typeof(string)));
var typeSpecification = new TypeSpecification(genericTypeInstance);
var genericParameter = new GenericParameterSignature(GenericParameterType.Type, 0);
var property = new PropertyDefinition("Property", PropertyAttributes.None,
PropertySignature.CreateStatic(genericParameter));
var member = new MemberReference(typeSpecification, property.Name, property.Signature);
var context = GenericContext.FromMethod(member);
var context2 = GenericContext.FromMember(member);
Assert.Equal(context, context2);
Assert.False(context.IsEmpty);
Assert.Equal(genericTypeInstance, context.Type);
Assert.Null(context.Method);
}
[Fact]
public void ParseGenericFromNotGenericProperty()
{
var type = new TypeDefinition("", "Test type", TypeAttributes.Public);
var notGenericSignature = new TypeDefOrRefSignature(type);
var property = new PropertyDefinition("Property", PropertyAttributes.None,
PropertySignature.CreateStatic(notGenericSignature));
var member = new MemberReference(type, property.Name, property.Signature);
var context = GenericContext.FromMethod(member);
var context2 = GenericContext.FromMember(member);
Assert.Equal(context, context2);
Assert.True(context.IsEmpty);
}
} | 189 | 17,327 | using System;
namespace AsmResolver.DotNet.Signatures
{
/// <summary>
/// Provides a context within a generic instantiation, including the type arguments of the enclosing type and method.
/// </summary>
public readonly struct GenericContext : IEquatable<GenericContext>
{
/// <summary>
/// Creates a new instance of the <see cref="GenericContext"/> class.
/// </summary>
/// <param name="type">The type providing type arguments.</param>
/// <param name="method">The method providing type arguments.</param>
public GenericContext(IGenericArgumentsProvider? type, IGenericArgumentsProvider? method)
{
Type = type;
Method = method;
}
/// <summary>
/// Gets the object responsible for providing type arguments defined by the current generic type instantiation.
/// </summary>
public IGenericArgumentsProvider? Type
{
get;
}
/// <summary>
/// Gets the object responsible for providing type arguments defined by the current generic method instantiation.
/// </summary>
public IGenericArgumentsProvider? Method
{
get;
}
/// <summary>
/// Returns true if both Type and Method providers are null
/// </summary>
public bool IsEmpty => Type is null && Method is null;
/// <summary>
/// Enters a new generic context with a new type providing type arguments.
/// </summary>
/// <param name="type">The new type providing the type arguments.</param>
/// <returns>The new generic context.</returns>
public GenericContext WithType(IGenericArgumentsProvider type) => new GenericContext(type, Method);
/// <summary>
/// Enters a new generic context with a new method providing type arguments.
/// </summary>
/// <param name="method">The new method providing the type arguments.</param>
/// <returns>The new generic context.</returns>
public GenericContext WithMethod(IGenericArgumentsProvider method) => new GenericContext(Type, method);
/// <summary>
/// Resolves a type parameter to a type argument, based on the current generic context.
/// </summary>
/// <remarks>
/// If a type parameter within the signature references a parameter that is not captured by the context
/// (i.e. the corresponding generic argument provider is set to null),
/// then this type parameter will not be substituted.
/// </remarks>
/// <param name="parameter">The parameter to get the argument value for.</param>
/// <returns>The argument type.</returns>
public TypeSignature GetTypeArgument(GenericParameterSignature parameter)
{
var argumentProvider = parameter.ParameterType switch
{
GenericParameterType.Type => Type,
GenericParameterType.Method => Method,
_ => throw new ArgumentOutOfRangeException()
};
if (argumentProvider is null)
return parameter;
if (parameter.Index >= 0 && parameter.Index < argumentProvider.TypeArguments.Count)
return argumentProvider.TypeArguments[parameter.Index];
throw new ArgumentOutOfRangeException();
}
/// <summary>
/// Gets a type generic context from <see cref="TypeSpecification"/>.
/// </summary>
/// <param name="type">Type specification to get the generic context from.</param>
/// <returns>Generic context.</returns>
public static GenericContext FromType(TypeSpecification type) => type.Signature switch
{
GenericInstanceTypeSignature typeSig => new GenericContext(typeSig, null),
_ => default
};
/// <summary>
/// Gets a type generic context from <see cref="GenericInstanceTypeSignature"/>.
/// </summary>
/// <param name="type">Generic type signature to get the generic context from.</param>
/// <returns>Generic context.</returns>
public static GenericContext FromType(GenericInstanceTypeSignature type) => new(type, null);
/// <summary>
/// Gets a type generic context from <see cref="ITypeDescriptor"/>.
/// </summary>
/// <param name="type">Type to get the generic context from.</param>
/// <returns>Generic context.</returns>
public static GenericContext FromType(ITypeDescriptor type) => type switch
{
TypeSpecification typeSpecification => FromType(typeSpecification),
GenericInstanceTypeSignature typeSig => FromType(typeSig),
_ => default
};
/// <summary>
/// Gets a method and/or type generic context from <see cref="MethodSpecification"/>.
/// </summary>
/// <param name="method">Method specification to get the generic context from.</param>
/// <returns>Generic context.</returns>
public static GenericContext FromMethod(MethodSpecification method)
{
return method.DeclaringType is TypeSpecification {Signature: GenericInstanceTypeSignature typeSig}
? new GenericContext(typeSig, method.Signature)
: new GenericContext(null, method.Signature);
}
/// <summary>
/// Gets a method and/or type generic context from <see cref="IMethodDescriptor"/>.
/// </summary>
/// <param name="method">Method to get the generic context from.</param>
/// <returns>Generic context.</returns>
public static GenericContext FromMethod(IMethodDescriptor method) =>
method switch
{
MethodSpecification methodSpecification => FromMethod(methodSpecification),
MemberReference member => FromMember(member),
_ => default
};
/// <summary>
/// Gets a type generic context from <see cref="IFieldDescriptor"/>.
/// </summary>
/// <param name="field">Field to get the generic context from.</param>
/// <returns>Generic context.</returns>
public static GenericContext FromField(IFieldDescriptor field) =>
field switch
{
MemberReference member => FromMember(member),
_ => default
};
/// <summary>
/// Gets a type generic context from <see cref="MemberReference"/>.
/// </summary>
/// <param name="member">Member reference to get the generic context from.</param>
/// <returns>Generic context.</returns>
public static GenericContext FromMember(MemberReference member) =>
member.DeclaringType switch
{
TypeSpecification type => FromType(type),
_ => default
};
/// <summary>
/// Gets a type generic context from <see cref="IMemberDescriptor"/>.
/// </summary>
/// <param name="member">Member to get the generic context from.</param>
/// <returns>Generic context.</returns>
public static GenericContext FromMember(IMemberDescriptor member) =>
member switch
{
IMethodDescriptor method => FromMethod(method),
IFieldDescriptor field => FromField(field),
ITypeDescriptor type => FromType(type),
_ => default
};
/// <summary>
/// Determines whether two generic contexts have the same generic argument providers.
/// </summary>
/// <param name="other">The other context.</param>
/// <returns><c>true</c> if the contexts are considered equal, <c>false</c> otherwise.</returns>
public bool Equals(GenericContext other) => Equals(Type, other.Type) && Equals(Method, other.Method);
/// <inheritdoc />
public override bool Equals(object? obj) => obj is GenericContext other && Equals(other);
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
return ((Type is { } type ? type.GetHashCode() : 0) * 397)
^ (Method is { } method ? method.GetHashCode() : 0);
}
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Signatures\GenericTypeActivatorTest.cs | AsmResolver.DotNet.Tests.Signatures
| GenericTypeActivatorTest | ['public IList<TypeSignature> TypeArguments\n {\n get;\n }', 'private readonly SignatureComparer Comparer = new SignatureComparer();', 'private readonly ModuleDefinition _module = new ModuleDefinition("DummyModule");', 'private TypeReference _dummyGenericType;'] | ['System', 'System.Collections.Generic', 'AsmResolver.DotNet.Signatures', 'Xunit'] | xUnit | net8.0 | public class GenericTypeActivatorTest
{
private readonly SignatureComparer Comparer = new SignatureComparer();
private readonly ModuleDefinition _module = new ModuleDefinition("DummyModule");
private TypeReference _dummyGenericType;
public GenericTypeActivatorTest()
{
_dummyGenericType = new TypeReference(
new AssemblyReference("SomeAssembly", new Version()),
"SomeNamespace", "SomeType");
}
public static IGenericArgumentsProvider GetProvider(params TypeSignature[] signatures)
{
return new MockGenericArgumentProvider(signatures);
}
[Fact]
public void InstantiateCorLibShouldNotChange()
{
var signature = _module.CorLibTypeFactory.Boolean;
var context = new GenericContext();
var newSignature = signature.InstantiateGenericTypes(context);
Assert.Equal(_module.CorLibTypeFactory.Boolean, newSignature, Comparer);
}
[Fact]
public void InstantiateTypeGenericParameter()
{
var signature = new GenericParameterSignature(GenericParameterType.Type, 0);
var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null);
var newSignature = signature.InstantiateGenericTypes(context);
Assert.Equal(_module.CorLibTypeFactory.String, newSignature, Comparer);
}
[Fact]
public void InstantiateMethodGenericParameter()
{
var signature = new GenericParameterSignature(GenericParameterType.Method, 0);
var context = new GenericContext(null, GetProvider(_module.CorLibTypeFactory.String));
var newSignature = signature.InstantiateGenericTypes(context);
Assert.Equal(_module.CorLibTypeFactory.String, newSignature, Comparer);
}
[Fact]
public void InstantiateSimpleGenericInstanceType()
{
var signature = new GenericInstanceTypeSignature(_dummyGenericType, false,
new GenericParameterSignature(GenericParameterType.Type, 0));
var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null);
var newSignature = signature.InstantiateGenericTypes(context);
Assert.Equal(new GenericInstanceTypeSignature(_dummyGenericType, false,
_module.CorLibTypeFactory.String), newSignature, Comparer);
}
[Fact]
public void InstantiateNestedGenericInstanceType()
{
var signature = new GenericInstanceTypeSignature(_dummyGenericType, false,
new GenericInstanceTypeSignature(_dummyGenericType, false,
new GenericParameterSignature(GenericParameterType.Type, 0)));
var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null);
var newSignature = signature.InstantiateGenericTypes(context);
Assert.Equal(new GenericInstanceTypeSignature(_dummyGenericType, false,
new GenericInstanceTypeSignature(_dummyGenericType, false,
_module.CorLibTypeFactory.String)), newSignature, Comparer);
}
[Fact]
public void InstantiateGenericInstanceTypeWithTypeAndMethodArgument()
{
var signature = new GenericInstanceTypeSignature(_dummyGenericType, false,
new GenericParameterSignature(GenericParameterType.Type, 0),
new GenericParameterSignature(GenericParameterType.Method, 0));
var context = new GenericContext(
GetProvider(_module.CorLibTypeFactory.String),
GetProvider(_module.CorLibTypeFactory.Int32));
var newSignature = signature.InstantiateGenericTypes(context);
Assert.Equal(new GenericInstanceTypeSignature(_dummyGenericType, false,
_module.CorLibTypeFactory.String,
_module.CorLibTypeFactory.Int32), newSignature, Comparer);
}
[Fact]
public void InstantiateMethodSignatureWithGenericReturnType()
{
var signature = MethodSignature.CreateStatic(
new GenericParameterSignature(GenericParameterType.Type, 0));
var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null);
var newSignature = signature.InstantiateGenericTypes(context);
Assert.Equal(MethodSignature.CreateStatic(
_module.CorLibTypeFactory.String
), newSignature, Comparer);
}
[Fact]
public void InstantiateMethodSignatureWithGenericParameterType()
{
var signature = MethodSignature.CreateStatic(
_module.CorLibTypeFactory.Void,
new GenericParameterSignature(GenericParameterType.Type, 0));
var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null);
var newSignature = signature.InstantiateGenericTypes(context);
Assert.Equal(MethodSignature.CreateStatic(
_module.CorLibTypeFactory.Void,
_module.CorLibTypeFactory.String
), newSignature, Comparer);
}
[Fact]
public void InstantiateMethodSignatureWithGenericSentinelParameterType()
{
var signature = MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void);
signature.IncludeSentinel = true;
signature.SentinelParameterTypes.Add(new GenericParameterSignature(GenericParameterType.Type, 0));
var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null);
var newSignature = signature.InstantiateGenericTypes(context);
var expected = MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void);
expected.IncludeSentinel = true;
expected.SentinelParameterTypes.Add(_module.CorLibTypeFactory.String);
Assert.Equal(expected, newSignature, Comparer);
}
[Fact]
public void InstantiateFieldSignature()
{
var signature = new FieldSignature(new GenericParameterSignature(GenericParameterType.Type, 0));
var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null);
var newSignature = signature.InstantiateGenericTypes(context);
Assert.Equal(new FieldSignature(_module.CorLibTypeFactory.String), newSignature, Comparer);
}
[Fact]
public void InstantiatePropertySignatureWithGenericPropertyType()
{
var signature = PropertySignature.CreateStatic(new GenericParameterSignature(GenericParameterType.Type, 0));
var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null);
var newSignature = signature.InstantiateGenericTypes(context);
var expected = PropertySignature.CreateStatic(_module.CorLibTypeFactory.String);
Assert.Equal(expected, newSignature, Comparer);
}
[Fact]
public void InstantiatePropertySignatureWithGenericParameterType()
{
var signature = PropertySignature.CreateStatic(
_module.CorLibTypeFactory.String,
new GenericParameterSignature(GenericParameterType.Type, 0));
var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null);
var newSignature = signature.InstantiateGenericTypes(context);
var expected = PropertySignature.CreateStatic(
_module.CorLibTypeFactory.String,
_module.CorLibTypeFactory.String);
Assert.Equal(expected, newSignature, Comparer);
}
private sealed class MockGenericArgumentProvider : IGenericArgumentsProvider
{
public MockGenericArgumentProvider(IList<TypeSignature> typeArguments)
{
TypeArguments = typeArguments ?? throw new ArgumentNullException(nameof(typeArguments));
}
public IList<TypeSignature> TypeArguments
{
get;
}
}
} | 158 | 8,839 | using System.Linq;
namespace AsmResolver.DotNet.Signatures
{
/// <summary>
/// Provides a mechanism for substituting generic type parameters in a type signature with arguments.
/// </summary>
/// <remarks>
/// When the type signature does not contain any generic parameter, this activator might return the current
/// instance of the type signature, to preserve heap allocations.
/// </remarks>
public class GenericTypeActivator : ITypeSignatureVisitor<GenericContext, TypeSignature>
{
/// <summary>
/// Gets the default instance of the <see cref="GenericTypeActivator"/> class
/// </summary>
public static GenericTypeActivator Instance
{
get;
} = new();
/// <summary>
/// Instantiates a new field signature, substituting any generic type parameter in the signature with
/// the activation context.
/// </summary>
/// <param name="signature">The signature to activate.</param>
/// <param name="context">The generic context to put the type signature in.</param>
/// <returns>The activated signature.</returns>
public FieldSignature InstantiateFieldSignature(FieldSignature signature, GenericContext context)
{
return new FieldSignature(
signature.Attributes,
signature.FieldType.AcceptVisitor(this, context));
}
/// <summary>
/// Instantiates a new method signature, substituting any generic type parameter in the signature with
/// the activation context.
/// </summary>
/// <param name="signature">The signature to activate.</param>
/// <param name="context">The generic context to put the type signature in.</param>
/// <returns>The activated signature.</returns>
public PropertySignature InstantiatePropertySignature(PropertySignature signature, GenericContext context)
{
var result = new PropertySignature(signature.Attributes, signature.ReturnType, Enumerable.Empty<TypeSignature>());
InstantiateMethodSignatureBase(signature, result, context);
return result;
}
/// <summary>
/// Instantiates a new method signature, substituting any generic type parameter in the signature with
/// the activation context.
/// </summary>
/// <param name="signature">The signature to activate.</param>
/// <param name="context">The generic context to put the type signature in.</param>
/// <returns>The activated signature.</returns>
public MethodSignature InstantiateMethodSignature(MethodSignature signature, GenericContext context)
{
var result = new MethodSignature(signature.Attributes, signature.ReturnType, Enumerable.Empty<TypeSignature>());
InstantiateMethodSignatureBase(signature, result, context);
result.GenericParameterCount = signature.GenericParameterCount;
if (signature.IncludeSentinel)
{
result.IncludeSentinel = signature.IncludeSentinel;
foreach (var sentinelType in signature.SentinelParameterTypes)
result.SentinelParameterTypes.Add(sentinelType.AcceptVisitor(this, context));
}
return result;
}
private void InstantiateMethodSignatureBase(MethodSignatureBase signature, MethodSignatureBase result,
GenericContext context)
{
result.ReturnType = signature.ReturnType.AcceptVisitor(this, context);
foreach (var parameterType in signature.ParameterTypes)
result.ParameterTypes.Add(parameterType.AcceptVisitor(this, context));
}
/// <inheritdoc />
public TypeSignature VisitArrayType(ArrayTypeSignature signature, GenericContext context)
{
var result = new ArrayTypeSignature(signature.BaseType.AcceptVisitor(this, context));
for (int i = 0; i < signature.Dimensions.Count; i++)
result.Dimensions.Add(signature.Dimensions[i]);
return result;
}
/// <inheritdoc />
public TypeSignature VisitBoxedType(BoxedTypeSignature signature, GenericContext context)
{
var instantiatedBaseType = signature.BaseType.AcceptVisitor(this, context);
return !ReferenceEquals(instantiatedBaseType, signature.BaseType)
? new BoxedTypeSignature(instantiatedBaseType)
: signature;
}
/// <inheritdoc />
public TypeSignature VisitByReferenceType(ByReferenceTypeSignature signature, GenericContext context)
{
var instantiatedBaseType = signature.BaseType.AcceptVisitor(this, context);
return !ReferenceEquals(instantiatedBaseType, signature.BaseType)
? new ByReferenceTypeSignature(instantiatedBaseType)
: signature;
}
/// <inheritdoc />
public TypeSignature VisitCorLibType(CorLibTypeSignature signature, GenericContext context)
{
return signature;
}
/// <inheritdoc />
public TypeSignature VisitCustomModifierType(CustomModifierTypeSignature signature, GenericContext context)
{
return new CustomModifierTypeSignature(
signature.ModifierType,
signature.IsRequired,
signature.BaseType.AcceptVisitor(this, context));
}
/// <inheritdoc />
public TypeSignature VisitGenericInstanceType(GenericInstanceTypeSignature signature, GenericContext context)
{
var result = new GenericInstanceTypeSignature(signature.GenericType, signature.IsValueType);
for (int i = 0; i < signature.TypeArguments.Count; i++)
result.TypeArguments.Add(signature.TypeArguments[i].AcceptVisitor(this, context));
return result;
}
/// <inheritdoc />
public TypeSignature VisitGenericParameter(GenericParameterSignature signature, GenericContext context)
{
return context.GetTypeArgument(signature);
}
/// <inheritdoc />
public TypeSignature VisitPinnedType(PinnedTypeSignature signature, GenericContext context)
{
var instantiatedBaseType = signature.BaseType.AcceptVisitor(this, context);
return !ReferenceEquals(instantiatedBaseType, signature.BaseType)
? new PinnedTypeSignature(instantiatedBaseType)
: signature;
}
/// <inheritdoc />
public TypeSignature VisitPointerType(PointerTypeSignature signature, GenericContext context)
{
var instantiatedBaseType = signature.BaseType.AcceptVisitor(this, context);
return !ReferenceEquals(instantiatedBaseType, signature.BaseType)
? new PointerTypeSignature(instantiatedBaseType)
: signature;
}
/// <inheritdoc />
public TypeSignature VisitSentinelType(SentinelTypeSignature signature, GenericContext context)
{
return signature;
}
/// <inheritdoc />
public TypeSignature VisitSzArrayType(SzArrayTypeSignature signature, GenericContext context)
{
var instantiatedBaseType = signature.BaseType.AcceptVisitor(this, context);
return !ReferenceEquals(instantiatedBaseType, signature.BaseType)
? new SzArrayTypeSignature(instantiatedBaseType)
: signature;
}
/// <inheritdoc />
public TypeSignature VisitTypeDefOrRef(TypeDefOrRefSignature signature, GenericContext context)
{
return signature;
}
/// <inheritdoc />
public TypeSignature VisitFunctionPointerType(FunctionPointerTypeSignature signature, GenericContext context)
{
var instantiatedSignature = InstantiateMethodSignature(signature.Signature, context);
return !ReferenceEquals(instantiatedSignature, signature.Signature)
? new FunctionPointerTypeSignature(instantiatedSignature)
: signature;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Signatures\MarshalDescriptorTest.cs | AsmResolver.DotNet.Tests.Signatures
| MarshalDescriptorTest | [] | ['System.Linq', 'AsmResolver.DotNet.Builder', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Fields', 'AsmResolver.DotNet.TestCases.Methods', 'Xunit'] | xUnit | net8.0 | public class MarshalDescriptorTest
{
private static MethodDefinition LookupMethod(string methodName)
{
var module = ModuleDefinition.FromFile(typeof(PlatformInvoke).Assembly.Location, TestReaderParameters);
return LookupMethodInModule(module, methodName);
}
private static MethodDefinition LookupMethodInModule(ModuleDefinition module, string methodName)
{
var t = module.TopLevelTypes.First(t => t.Name == nameof(PlatformInvoke));
var method = t.Methods.First(m => m.Name == methodName);
return method;
}
private static FieldDefinition LookupField(string fieldName)
{
var module = ModuleDefinition.FromFile(typeof(Marshalling).Assembly.Location, TestReaderParameters);
return LookupFieldInModule(module, fieldName);
}
private static FieldDefinition LookupFieldInModule(ModuleDefinition module, string fieldName)
{
var t = module.TopLevelTypes.First(t => t.Name == nameof(Marshalling));
var field = t.Fields.First(m => m.Name == fieldName);
return field;
}
private static MethodDefinition RebuildAndLookup(MethodDefinition method)
{
var builder = new ManagedPEImageBuilder();
var newImage = builder.CreateImage(method.Module).ConstructedImage;
var newModule = ModuleDefinition.FromImage(newImage, TestReaderParameters);
return LookupMethodInModule(newModule, method.Name);
}
private static FieldDefinition RebuildAndLookup(FieldDefinition field)
{
var builder = new ManagedPEImageBuilder();
var newImage = builder.CreateImage(field.Module).ConstructedImage;
var newModule = ModuleDefinition.FromImage(newImage, TestReaderParameters);
return LookupFieldInModule(newModule, field.Name);
}
[Fact]
public void ReadSimpleMarshaller()
{
var method = LookupMethod(nameof(PlatformInvoke.SimpleMarshaller));
var marshaller = method.Parameters[0].Definition.MarshalDescriptor;
Assert.NotNull(marshaller);
Assert.Equal(NativeType.Boolean, marshaller.NativeType);
}
[Fact]
public void PersistentSimpleMarshaller()
{
var method = LookupMethod(nameof(PlatformInvoke.SimpleMarshaller));
var newMethod = RebuildAndLookup(method);
Assert.Equal(method.Parameters[0].Definition.MarshalDescriptor.NativeType,
newMethod.Parameters[0].Definition.MarshalDescriptor.NativeType);
}
[Fact]
public void PersistentLPArrayWithoutElementType()
{
var method = LookupMethod(nameof(PlatformInvoke.LPArrayFixedSizeMarshaller));
var originalMarshaller = (LPArrayMarshalDescriptor) method.Parameters[0].Definition!.MarshalDescriptor!;
originalMarshaller.ArrayElementType = null;
var newMethod = RebuildAndLookup(method);
var newArrayMarshaller = Assert.IsAssignableFrom<LPArrayMarshalDescriptor>(
newMethod.Parameters[0].Definition!.MarshalDescriptor);
Assert.Null(newArrayMarshaller.ArrayElementType);
}
[Fact]
public void ReadLPArrayMarshallerWithFixedSize()
{
var method = LookupMethod(nameof(PlatformInvoke.LPArrayFixedSizeMarshaller));
var marshaller = method.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<LPArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (LPArrayMarshalDescriptor) marshaller;
Assert.Equal(10, arrayMarshaller.NumberOfElements);
}
[Fact]
public void PersistentLPArrayMarshallerWithFixedSize()
{
var method = LookupMethod(nameof(PlatformInvoke.LPArrayFixedSizeMarshaller));
var originalMarshaller = (LPArrayMarshalDescriptor) method.Parameters[0].Definition.MarshalDescriptor;
var newMethod = RebuildAndLookup(method);
var newMarshaller = newMethod.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<LPArrayMarshalDescriptor>(newMarshaller);
var newArrayMarshaller = (LPArrayMarshalDescriptor) newMarshaller;
Assert.Equal(originalMarshaller.NumberOfElements, newArrayMarshaller.NumberOfElements);
}
[Fact]
public void ReadLPArrayMarshallerWithVariableSize()
{
var method = LookupMethod(nameof(PlatformInvoke.LPArrayVariableSizeMarshaller));
var marshaller = method.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<LPArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (LPArrayMarshalDescriptor) marshaller;
Assert.Equal(1, arrayMarshaller.ParameterIndex);
}
[Fact]
public void PersistentLPArrayMarshallerWithVariableSize()
{
var method = LookupMethod(nameof(PlatformInvoke.LPArrayVariableSizeMarshaller));
var originalMarshaller = (LPArrayMarshalDescriptor) method.Parameters[0].Definition.MarshalDescriptor;
var newMethod = RebuildAndLookup(method);
var marshaller = newMethod.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<LPArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (LPArrayMarshalDescriptor) marshaller;
Assert.Equal(originalMarshaller.ParameterIndex, arrayMarshaller.ParameterIndex);
}
[Fact]
public void ReadSafeArrayMarshaller()
{
var method = LookupMethod(nameof(PlatformInvoke.SafeArrayMarshaller));
var marshaller = method.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<SafeArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (SafeArrayMarshalDescriptor) marshaller;
Assert.Equal(SafeArrayVariantType.NotSet, arrayMarshaller.VariantType);
}
[Fact]
public void PersistentSafeArrayMarshaller()
{
var method = LookupMethod(nameof(PlatformInvoke.SafeArrayMarshaller));
var originalMarshaller = (SafeArrayMarshalDescriptor) method.Parameters[0].Definition.MarshalDescriptor;
var newMethod = RebuildAndLookup(method);
var marshaller = newMethod.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<SafeArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (SafeArrayMarshalDescriptor) marshaller;
Assert.Equal(originalMarshaller.VariantType, arrayMarshaller.VariantType);
}
[Fact]
public void ReadSafeArrayMarshallerWithSubType()
{
var method = LookupMethod(nameof(PlatformInvoke.SafeArrayMarshallerWithSubType));
var marshaller = method.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<SafeArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (SafeArrayMarshalDescriptor) marshaller;
Assert.Equal(SafeArrayVariantType.UI1, arrayMarshaller.VariantType);
}
[Fact]
public void PersistentSafeArrayMarshallerWithSubType()
{
var method = LookupMethod(nameof(PlatformInvoke.SafeArrayMarshallerWithSubType));
var originalMarshaller = (SafeArrayMarshalDescriptor) method.Parameters[0].Definition.MarshalDescriptor;
var newMethod = RebuildAndLookup(method);
var marshaller = newMethod.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<SafeArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (SafeArrayMarshalDescriptor) marshaller;
Assert.Equal(originalMarshaller.VariantType, arrayMarshaller.VariantType);
}
[Fact]
public void ReadSafeArrayMarshallerWithUserDefinedSubType()
{
var method = LookupMethod(nameof(PlatformInvoke.SafeArrayMarshallerWithUserSubType));
var marshaller = method.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<SafeArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (SafeArrayMarshalDescriptor) marshaller;
Assert.NotNull(arrayMarshaller.UserDefinedSubType);
Assert.Equal(nameof(PlatformInvoke), arrayMarshaller.UserDefinedSubType.Name);
}
[Fact]
public void PersistentSafeArrayMarshallerWithUserDefinedSubType()
{
var method = LookupMethod(nameof(PlatformInvoke.SafeArrayMarshallerWithUserSubType));
var originalMarshaller = (SafeArrayMarshalDescriptor) method.Parameters[0].Definition.MarshalDescriptor;
var newMethod = RebuildAndLookup(method);
var marshaller = newMethod.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<SafeArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (SafeArrayMarshalDescriptor) marshaller;
Assert.NotNull(arrayMarshaller.UserDefinedSubType);
Assert.Equal(originalMarshaller.UserDefinedSubType.Name, arrayMarshaller.UserDefinedSubType.Name);
}
[Fact]
public void ReadFixedArrayMarshaller()
{
var field = LookupField(nameof(Marshalling.FixedArrayMarshaller));
var marshaller = field.MarshalDescriptor;
Assert.IsAssignableFrom<FixedArrayMarshalDescriptor>(marshaller);
}
[Fact]
public void PersistentFixedArrayMarshaller()
{
var field = LookupField(nameof(Marshalling.FixedArrayMarshaller));
var newField = RebuildAndLookup(field);
var marshaller = newField.MarshalDescriptor;
Assert.IsAssignableFrom<FixedArrayMarshalDescriptor>(marshaller);
}
[Fact]
public void ReadFixedArrayMarshallerWithFixedSizeSpecifier()
{
var field = LookupField(nameof(Marshalling.FixedArrayMarshallerWithFixedSize));
var marshaller = field.MarshalDescriptor;
Assert.IsAssignableFrom<FixedArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (FixedArrayMarshalDescriptor) marshaller;
Assert.Equal(10, arrayMarshaller.Size);
}
[Fact]
public void PersistentFixedArrayMarshallerWithFixedSizeSpecifier()
{
var field = LookupField(nameof(Marshalling.FixedArrayMarshallerWithFixedSize));
var originalMarshaller = (FixedArrayMarshalDescriptor) field.MarshalDescriptor;
var newField = RebuildAndLookup(field);
var marshaller = newField.MarshalDescriptor;
Assert.IsAssignableFrom<FixedArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (FixedArrayMarshalDescriptor) marshaller;
Assert.Equal(originalMarshaller.Size, arrayMarshaller.Size);
}
[Fact]
public void ReadFixedArrayMarshallerWithFixedSizeSpecifierAndArrayType()
{
var field = LookupField(nameof(Marshalling.FixedArrayMarshallerWithFixedSizeAndArrayType));
var marshaller = field.MarshalDescriptor;
Assert.IsAssignableFrom<FixedArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (FixedArrayMarshalDescriptor) marshaller;
Assert.Equal(10, arrayMarshaller.Size);
Assert.Equal(NativeType.U1, arrayMarshaller.ArrayElementType);
}
[Fact]
public void PersistentFixedArrayMarshallerWithFixedSizeSpecifierAndArrayType()
{
var field = LookupField(nameof(Marshalling.FixedArrayMarshallerWithFixedSizeAndArrayType));
var originalMarshaller = (FixedArrayMarshalDescriptor) field.MarshalDescriptor;
var newField = RebuildAndLookup(field);
var marshaller = newField.MarshalDescriptor;
Assert.IsAssignableFrom<FixedArrayMarshalDescriptor>(marshaller);
var arrayMarshaller = (FixedArrayMarshalDescriptor) marshaller;
Assert.Equal(originalMarshaller.Size, arrayMarshaller.Size);
Assert.Equal(originalMarshaller.ArrayElementType, arrayMarshaller.ArrayElementType);
}
[Fact]
public void ReadCustomMarshallerType()
{
var field = LookupField(nameof(Marshalling.CustomMarshallerWithCustomType));
var marshaller = field.MarshalDescriptor;
Assert.IsAssignableFrom<CustomMarshalDescriptor>(marshaller);
var customMarshaller = (CustomMarshalDescriptor) marshaller;
Assert.Equal(nameof(Marshalling), customMarshaller.MarshalType.Name);
}
[Fact]
public void PersistentCustomMarshallerType()
{
var field = LookupField(nameof(Marshalling.CustomMarshallerWithCustomType));
var originalMarshaller = (CustomMarshalDescriptor) field.MarshalDescriptor;
var newField = RebuildAndLookup(field);
var marshaller = newField.MarshalDescriptor;
Assert.IsAssignableFrom<CustomMarshalDescriptor>(marshaller);
var customMarshaller = (CustomMarshalDescriptor) marshaller;
Assert.Equal(originalMarshaller.MarshalType.Name, customMarshaller.MarshalType.Name);
}
[Fact]
public void ReadCustomMarshallerTypeWithCookie()
{
var field = LookupField(nameof(Marshalling.CustomMarshallerWithCustomTypeAndCookie));
var marshaller = field.MarshalDescriptor;
Assert.IsAssignableFrom<CustomMarshalDescriptor>(marshaller);
var customMarshaller = (CustomMarshalDescriptor) marshaller;
Assert.Equal(nameof(Marshalling), customMarshaller.MarshalType.Name);
Assert.Equal("abc", customMarshaller.Cookie);
}
[Fact]
public void PersistentCustomMarshallerTypeWithCookie()
{
var field = LookupField(nameof(Marshalling.CustomMarshallerWithCustomTypeAndCookie));
var originalMarshaller = (CustomMarshalDescriptor) field.MarshalDescriptor;
var newField = RebuildAndLookup(field);
var marshaller = newField.MarshalDescriptor;
Assert.IsAssignableFrom<CustomMarshalDescriptor>(marshaller);
var customMarshaller = (CustomMarshalDescriptor) marshaller;
Assert.Equal(originalMarshaller.MarshalType.Name, customMarshaller.MarshalType.Name);
Assert.Equal(originalMarshaller.Cookie, customMarshaller.Cookie);
}
[Fact]
public void ReadFixedSysString()
{
var field = LookupField(nameof(Marshalling.FixedSysString));
var marshaller = field.MarshalDescriptor;
Assert.IsAssignableFrom<FixedSysStringMarshalDescriptor>(marshaller);
var stringMarshaller = (FixedSysStringMarshalDescriptor) marshaller;
Assert.Equal(123, stringMarshaller.Size);
}
[Fact]
public void PersistentFixedSysString()
{
var field = LookupField(nameof(Marshalling.FixedSysString));
var originalMarshaller = (FixedSysStringMarshalDescriptor) field.MarshalDescriptor;
var newField = RebuildAndLookup(field);
var marshaller = newField.MarshalDescriptor;
Assert.IsAssignableFrom<FixedSysStringMarshalDescriptor>(marshaller);
var stringMarshaller = (FixedSysStringMarshalDescriptor) marshaller;
Assert.Equal(originalMarshaller.Size, stringMarshaller.Size);
}
[Fact]
public void ReadComInterface()
{
var method = LookupMethod(nameof(PlatformInvoke.ComInterface));
var marshaller = method.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<ComInterfaceMarshalDescriptor>(marshaller);
var comMarshaller = (ComInterfaceMarshalDescriptor) marshaller;
Assert.Null(comMarshaller.IidParameterIndex);
}
[Fact]
public void PersistentComInterface()
{
var method = LookupMethod(nameof(PlatformInvoke.ComInterface));
var newMethod = RebuildAndLookup(method);
var marshaller = newMethod.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<ComInterfaceMarshalDescriptor>(marshaller);
var comMarshaller = (ComInterfaceMarshalDescriptor) marshaller;
Assert.Null(comMarshaller.IidParameterIndex);
}
[Fact]
public void ReadComInterfaceWithParameterIndex()
{
var method = LookupMethod(nameof(PlatformInvoke.ComInterfaceWithIidParameter));
var marshaller = method.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<ComInterfaceMarshalDescriptor>(marshaller);
var comMarshaller = (ComInterfaceMarshalDescriptor) marshaller;
Assert.Equal(1, comMarshaller.IidParameterIndex);
}
[Fact]
public void PersistentComInterfaceWithParameterIndex()
{
var method = LookupMethod(nameof(PlatformInvoke.ComInterfaceWithIidParameter));
var originalMarshaller = (ComInterfaceMarshalDescriptor) method.Parameters[0].Definition.MarshalDescriptor;
var newMethod = RebuildAndLookup(method);
var marshaller = newMethod.Parameters[0].Definition.MarshalDescriptor;
Assert.IsAssignableFrom<ComInterfaceMarshalDescriptor>(marshaller);
var comMarshaller = (ComInterfaceMarshalDescriptor) marshaller;
Assert.Equal(originalMarshaller.IidParameterIndex, comMarshaller.IidParameterIndex);
}
} | 252 | 18,593 | using System;
using AsmResolver.IO;
namespace AsmResolver.DotNet.Signatures
{
/// <summary>
/// Represents a description of a marshaller that marshals a value to a COM interface object.
/// </summary>
public class ComInterfaceMarshalDescriptor : MarshalDescriptor
{
/// <summary>
/// Reads a single COM interface marshal descriptor from the provided input stream.
/// </summary>
/// <param name="type">The type of COM interface marshaller to read.</param>
/// <param name="reader">The input stream.</param>
/// <returns>The descriptor.</returns>
public static ComInterfaceMarshalDescriptor FromReader(NativeType type, ref BinaryStreamReader reader)
{
var result = new ComInterfaceMarshalDescriptor(type);
if (reader.TryReadCompressedUInt32(out uint value))
result.IidParameterIndex = (int) value;
return result;
}
/// <summary>
/// Creates a new instance of the <see cref="ComInterfaceMarshalDescriptor"/> class.
/// </summary>
/// <param name="nativeType">The type of COM interface to marshal to.</param>
public ComInterfaceMarshalDescriptor(NativeType nativeType)
{
switch (nativeType)
{
case NativeType.Interface:
case NativeType.IUnknown:
case NativeType.IDispatch:
NativeType = nativeType;
break;
default:
throw new ArgumentOutOfRangeException(nameof(nativeType));
}
}
/// <inheritdoc />
public override NativeType NativeType
{
get;
}
/// <summary>
/// Gets or sets the index of the parameter containing the COM IID of the interface.
/// </summary>
public int? IidParameterIndex
{
get;
set;
}
/// <inheritdoc />
protected override void WriteContents(in BlobSerializationContext context)
{
var writer = context.Writer;
writer.WriteByte((byte) NativeType);
if (IidParameterIndex.HasValue)
writer.WriteCompressedUInt32((uint) IidParameterIndex.Value);
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Signatures\MethodSignatureTest.cs | AsmResolver.DotNet.Tests.Signatures
| MethodSignatureTest | ['private readonly ModuleDefinition _module;'] | ['System.IO', 'System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.PE.DotNet.Cil', 'Xunit'] | xUnit | net8.0 | public class MethodSignatureTest
{
private readonly ModuleDefinition _module;
public MethodSignatureTest()
{
_module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
}
[Fact]
public void MakeInstanceShouldHaveHasThisFlagSet()
{
var signature = MethodSignature.CreateInstance(_module.CorLibTypeFactory.Void);
Assert.True(signature.HasThis);
Assert.False(signature.IsGeneric);
}
[Fact]
public void MakeStaticShouldNotHaveHasThisFlagSet()
{
var signature = MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void);
Assert.False(signature.HasThis);
Assert.False(signature.IsGeneric);
}
[Fact]
public void MakeGenericInstanceShouldHaveHasThisAndGenericFlagSet()
{
var signature = MethodSignature.CreateInstance(_module.CorLibTypeFactory.Void, 1);
Assert.True(signature.HasThis);
Assert.True(signature.IsGeneric);
}
[Fact]
public void MakeGenericStaticShouldNotHaveHasThisAndGenericFlagSet()
{
var signature = MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void, 1);
Assert.False(signature.HasThis);
Assert.True(signature.IsGeneric);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SentinelParameterTypes(bool rebuild)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.ArgListTest, TestReaderParameters);
if (rebuild)
{
using var stream = new MemoryStream();
module.Write(stream);
module = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters);
}
var reference = (MemberReference) module.ManagedEntryPointMethod!.CilMethodBody!
.Instructions.First(i => i.OpCode.Code == CilCode.Call)
.Operand!;
var signature = Assert.IsAssignableFrom<MethodSignature>(reference.Signature);
var type = Assert.Single(signature.SentinelParameterTypes);
Assert.Equal(module.CorLibTypeFactory.String, type, SignatureComparer.Default);
}
} | 180 | 2,599 | using System.Collections.Generic;
using System.Linq;
using AsmResolver.IO;
using AsmResolver.Shims;
namespace AsmResolver.DotNet.Signatures
{
/// <summary>
/// Represents an instantiation of a generic method.
/// </summary>
public class GenericInstanceMethodSignature : CallingConventionSignature, IGenericArgumentsProvider
{
internal static GenericInstanceMethodSignature? FromReader(
ref BlobReaderContext context,
ref BinaryStreamReader reader)
{
if (!reader.CanRead(sizeof(byte)))
{
context.ReaderContext.BadImage("Insufficient data for a generic method instance signature.");
return null;
}
var attributes = (CallingConventionAttributes) reader.ReadByte();
if (!reader.TryReadCompressedUInt32(out uint count))
{
context.ReaderContext.BadImage("Invalid number of type arguments in generic method signature.");
return new GenericInstanceMethodSignature(attributes);
}
var result = new GenericInstanceMethodSignature(attributes, (int) count);
for (int i = 0; i < count; i++)
result.TypeArguments.Add(TypeSignature.FromReader(ref context, ref reader));
return result;
}
/// <summary>
/// Creates a new instantiation signature for a generic method.
/// </summary>
/// <param name="attributes">The attributes.</param>
public GenericInstanceMethodSignature(CallingConventionAttributes attributes)
: this(attributes, Enumerable.Empty<TypeSignature>())
{
}
/// <summary>
/// Creates a new instantiation signature for a generic method.
/// </summary>
/// <param name="attributes">The attributes.</param>
/// <param name="capacity">The initial number of elements that the <see cref="TypeArguments"/> property can store.</param>
public GenericInstanceMethodSignature(CallingConventionAttributes attributes, int capacity)
: base(attributes)
{
TypeArguments = new List<TypeSignature>(capacity);
}
/// <summary>
/// Creates a new instantiation signature for a generic method with the provided type arguments.
/// </summary>
/// <param name="typeArguments">The type arguments to use for the instantiation.</param>
public GenericInstanceMethodSignature(params TypeSignature[] typeArguments)
: this(CallingConventionAttributes.GenericInstance, typeArguments)
{
}
/// <summary>
/// Creates a new instantiation signature for a generic method with the provided type arguments.
/// </summary>
/// <param name="typeArguments">The type arguments to use for the instantiation.</param>
public GenericInstanceMethodSignature(IEnumerable<TypeSignature> typeArguments)
: this(CallingConventionAttributes.GenericInstance, typeArguments)
{
}
/// <summary>
/// Creates a new instantiation signature for a generic method with the provided type arguments.
/// </summary>
/// <param name="attributes">The attributes.</param>
/// <param name="typeArguments">The type arguments to use for the instantiation.</param>
public GenericInstanceMethodSignature(CallingConventionAttributes attributes, IEnumerable<TypeSignature> typeArguments)
: base(attributes | CallingConventionAttributes.GenericInstance)
{
TypeArguments = new List<TypeSignature>(typeArguments);
}
/// <summary>
/// Gets a collection of type arguments that are used to instantiate the method.
/// </summary>
public IList<TypeSignature> TypeArguments
{
get;
}
/// <inheritdoc />
protected override void WriteContents(in BlobSerializationContext context)
{
var writer = context.Writer;
writer.WriteByte((byte) Attributes);
writer.WriteCompressedUInt32((uint) TypeArguments.Count);
for (int i = 0; i < TypeArguments.Count; i++)
TypeArguments[i].Write(context);
}
/// <inheritdoc />
public override bool IsImportedInModule(ModuleDefinition module)
{
for (int i = 0; i < TypeArguments.Count; i++)
{
if (!TypeArguments[i].IsImportedInModule(module))
return false;
}
return true;
}
/// <summary>
/// Imports the generic method instantiation signature using the provided reference importer object.
/// </summary>
/// <param name="importer">The reference importer to us.</param>
/// <returns>The imported signature.</returns>
public GenericInstanceMethodSignature ImportWith(ReferenceImporter importer) =>
importer.ImportGenericInstanceMethodSignature(this);
/// <inheritdoc />
protected override CallingConventionSignature ImportWithInternal(ReferenceImporter importer) =>
ImportWith(importer);
/// <inheritdoc />
public override string ToString()
{
return $"<{StringShim.Join(", ", TypeArguments)}>";
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Signatures\SignatureComparerTest.cs | AsmResolver.DotNet.Tests.Signatures
| SignatureComparerTest | ['private readonly SignatureComparer _comparer;', 'private readonly AssemblyReference _someAssemblyReference =\n new AssemblyReference("SomeAssembly", new Version(1, 2, 3, 4));'] | ['System', 'System.Collections.Generic', 'System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class SignatureComparerTest
{
private readonly SignatureComparer _comparer;
private readonly AssemblyReference _someAssemblyReference =
new AssemblyReference("SomeAssembly", new Version(1, 2, 3, 4));
public SignatureComparerTest()
{
_comparer = new SignatureComparer();
}
[Fact]
public void MatchCorLibTypeSignatures()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Equal(module.CorLibTypeFactory.Boolean, module.CorLibTypeFactory.Boolean, _comparer);
}
[Fact]
public void MatchDifferentCorLibTypeSignatures()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.NotEqual(module.CorLibTypeFactory.Byte, module.CorLibTypeFactory.Boolean, _comparer);
}
[Fact]
public void MatchTopLevelTypeRefTypeRef()
{
var reference1 = new TypeReference(_someAssemblyReference, "SomeNamespace", "SomeType");
var reference2 = new TypeReference(_someAssemblyReference, "SomeNamespace", "SomeType");
Assert.Equal(reference1, reference2, _comparer);
}
[Fact]
public void MatchTopLevelTypeRefTypeRefDifferentName()
{
var reference1 = new TypeReference(_someAssemblyReference, "SomeNamespace", "SomeType");
var reference2 = new TypeReference(_someAssemblyReference, "SomeNamespace", "SomeOtherType");
Assert.NotEqual(reference1, reference2, _comparer);
}
[Fact]
public void MatchTopLevelTypeRefTypeRefDifferentNamespace()
{
var reference1 = new TypeReference(_someAssemblyReference, "SomeNamespace", "SomeType");
var reference2 = new TypeReference(_someAssemblyReference, "SomeOtherNamespace", "SomeType");
Assert.NotEqual(reference1, reference2, _comparer);
}
[Fact]
public void MatchTopLevelTypeRefTypeDef()
{
var assembly = new AssemblyDefinition(_someAssemblyReference.Name, _someAssemblyReference.Version);
var module = new ModuleDefinition(assembly.Name + ".dll");
assembly.Modules.Add(module);
var definition = new TypeDefinition("SomeNamespace", "SomeType", TypeAttributes.Public);
module.TopLevelTypes.Add(definition);
var reference = new TypeReference(_someAssemblyReference, "SomeNamespace", "SomeType");
Assert.Equal((ITypeDefOrRef) definition, reference, _comparer);
}
[Fact]
public void MatchTopLevelTypeRefTypeDefDifferentScope()
{
var assembly = new AssemblyDefinition(_someAssemblyReference.Name + "2", _someAssemblyReference.Version);
var module = new ModuleDefinition(assembly.Name + ".dll");
assembly.Modules.Add(module);
var definition = new TypeDefinition("SomeNamespace", "SomeType", TypeAttributes.Public);
module.TopLevelTypes.Add(definition);
var reference = new TypeReference(_someAssemblyReference, "SomeNamespace", "SomeType");
Assert.NotEqual((ITypeDefOrRef) definition, reference, _comparer);
}
[Fact]
public void MatchTypeDefOrRefSignatures()
{
var reference = new TypeReference(_someAssemblyReference, "SomeNamespace", "SomeType");
var typeSig1 = new TypeDefOrRefSignature(reference);
var typeSig2 = new TypeDefOrRefSignature(reference);
Assert.Equal(typeSig1, typeSig2, _comparer);
}
[Fact]
public void MatchTypeDefOrRefSignaturesDifferentClass()
{
var reference1 = new TypeReference(_someAssemblyReference, "SomeNamespace", "SomeType");
var reference2 = new TypeReference(_someAssemblyReference, "SomeNamespace", "SomeOtherType");
var typeSig1 = new TypeDefOrRefSignature(reference1);
var typeSig2 = new TypeDefOrRefSignature(reference2);
Assert.NotEqual(typeSig1, typeSig2, _comparer);
}
[Fact]
public void MatchPropertySignature()
{
var type = new TypeReference(_someAssemblyReference, "SomeNamespace", "SomeType");
var signature1 = PropertySignature.CreateStatic(type.ToTypeSignature());
var signature2 = PropertySignature.CreateStatic(type.ToTypeSignature());
Assert.Equal(signature1, signature2, _comparer);
}
[Fact]
public void NestedTypesWithSameNameButDifferentDeclaringTypeShouldNotMatch()
{
var nestedTypes = ModuleDefinition.FromFile(typeof(SignatureComparerTest).Assembly.Location, TestReaderParameters)
.GetAllTypes().First(t => t.Name == nameof(SignatureComparerTest))
.NestedTypes.First(t => t.Name == nameof(NestedTypes));
var firstType = nestedTypes.NestedTypes
.First(t => t.Name == nameof(NestedTypes.FirstType)).NestedTypes
.First(t => t.Name == nameof(NestedTypes.FirstType.TypeWithCommonName));
var secondType = nestedTypes.NestedTypes
.First(t => t.Name == nameof(NestedTypes.SecondType)).NestedTypes
.First(t => t.Name == nameof(NestedTypes.SecondType.TypeWithCommonName));
Assert.NotEqual(firstType, secondType, _comparer);
}
[Fact]
public void MatchForwardedNestedTypes()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.ForwarderRefTest, TestReaderParameters);
var forwarder = ModuleDefinition.FromBytes(Properties.Resources.ForwarderLibrary, TestReaderParameters).Assembly!;
var library = ModuleDefinition.FromBytes(Properties.Resources.ActualLibrary, TestReaderParameters).Assembly!;
module.MetadataResolver.AssemblyResolver.AddToCache(forwarder, forwarder);
module.MetadataResolver.AssemblyResolver.AddToCache(library, library);
forwarder.ManifestModule!.MetadataResolver.AssemblyResolver.AddToCache(library, library);
var referencedTypes = module.ManagedEntryPointMethod!.CilMethodBody!.Instructions
.Where(i => i.OpCode.Code == CilCode.Call)
.Select(i => ((IMethodDefOrRef) i.Operand!).DeclaringType)
.Where(t => t.Name == "MyNestedClass")
.ToArray();
var type1 = referencedTypes[0]!;
var type2 = referencedTypes[1]!;
var resolvedType1 = type1.Resolve();
var resolvedType2 = type2.Resolve();
Assert.Equal(type1, resolvedType1, _comparer);
Assert.Equal(type2, resolvedType2, _comparer);
Assert.NotEqual(type1, type2, _comparer);
Assert.NotEqual(type1, resolvedType2, _comparer); // Fails
Assert.NotEqual(type2, resolvedType1, _comparer); // Fails
}
[Fact]
public void AssemblyHashCodeStrict()
{
var assembly1 = new AssemblyReference("SomeAssembly", new Version(1, 2, 3, 4));
var assembly2 = new AssemblyReference("SomeAssembly", new Version(1, 2, 3, 4));
Assert.Equal(
_comparer.GetHashCode((AssemblyDescriptor) assembly1),
_comparer.GetHashCode((AssemblyDescriptor) assembly2));
}
[Fact]
public void AssemblyHashCodeVersionAgnostic()
{
var assembly1 = new AssemblyReference("SomeAssembly", new Version(1, 2, 3, 4));
var assembly2 = new AssemblyReference("SomeAssembly", new Version(5, 6, 7, 8));
var comparer = new SignatureComparer(SignatureComparisonFlags.VersionAgnostic);
Assert.Equal(
comparer.GetHashCode((AssemblyDescriptor) assembly1),
comparer.GetHashCode((AssemblyDescriptor) assembly2));
}
[Fact]
public void CorlibComparison()
{
// https://github.com/Washi1337/AsmResolver/issues/427
var comparer = new SignatureComparer(SignatureComparisonFlags.VersionAgnostic);
var reference1 = KnownCorLibs.SystemRuntime_v5_0_0_0;
var reference2 = KnownCorLibs.SystemRuntime_v6_0_0_0;
Assert.Equal(reference1, reference2, comparer);
var set = new HashSet<AssemblyReference>(comparer);
Assert.True(set.Add(reference1));
Assert.False(set.Add(reference2));
}
[Fact]
public void CompareSimpleTypeDescriptors()
{
var assembly = new DotNetFrameworkAssemblyResolver().Resolve(KnownCorLibs.MsCorLib_v4_0_0_0);
var definition = assembly.ManifestModule!.TopLevelTypes.First(x => x.IsTypeOf("System.IO", "Stream"));
var reference = definition.ToTypeReference();
var signature = reference.ToTypeSignature();
Assert.Equal((ITypeDescriptor) reference, signature, _comparer);
Assert.Equal((ITypeDescriptor) definition, signature, _comparer);
Assert.Equal(_comparer.GetHashCode(reference), _comparer.GetHashCode(signature));
Assert.Equal(_comparer.GetHashCode(definition), _comparer.GetHashCode(signature));
}
private class NestedTypes
{
public class FirstType
{
public class TypeWithCommonName
{
}
}
public class SecondType
{
public class TypeWithCommonName
{
}
}
}
} | 258 | 10,247 | using System.Collections.Generic;
namespace AsmResolver.DotNet.Signatures
{
/// <summary>
/// Provides a mechanism for comparing signatures of members defined in a .NET assembly by their contents.
/// </summary>
public partial class SignatureComparer :
IEqualityComparer<byte[]>
{
private const int ElementTypeOffset = 8;
private const SignatureComparisonFlags DefaultFlags = SignatureComparisonFlags.ExactVersion;
/// <summary>
/// An immutable default instance of <see cref="SignatureComparer"/>.
/// </summary>
public static SignatureComparer Default { get; } = new();
/// <summary>
/// Flags for controlling comparison behavior.
/// </summary>
public SignatureComparisonFlags Flags { get; }
/// <summary>
/// The default <see cref="SignatureComparer"/> constructor.
/// </summary>
public SignatureComparer()
{
Flags = DefaultFlags;
}
/// <summary>
/// A <see cref="SignatureComparer"/> constructor with a parameter for specifying the <see cref="Flags"/>
/// used in comparisons.
/// </summary>
/// <param name="flags">The <see cref="Flags"/> used in comparisons.</param>
public SignatureComparer(SignatureComparisonFlags flags)
{
Flags = flags;
}
/// <inheritdoc />
public bool Equals(byte[]? x, byte[]? y) => ByteArrayEqualityComparer.Instance.Equals(x, y);
/// <inheritdoc />
public int GetHashCode(byte[] obj) => ByteArrayEqualityComparer.Instance.GetHashCode(obj);
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Signatures\TypeNameBuilderTest.cs | AsmResolver.DotNet.Tests.Signatures
| TypeNameBuilderTest | ['private readonly ModuleDefinition _module;'] | ['AsmResolver.DotNet.Signatures.Parsing', 'Xunit'] | xUnit | net8.0 | public class TypeNameBuilderTest
{
private readonly ModuleDefinition _module;
public TypeNameBuilderTest()
{
_module = new ModuleDefinition("DummyModule", KnownCorLibs.SystemPrivateCoreLib_v4_0_0_0);
}
[Fact]
public void NameWithDotShouldBeEscaped()
{
var type = new TypeReference(_module, _module, "Company.ProductName", "Class.Name");
string name = TypeNameBuilder.GetAssemblyQualifiedName(type.ToTypeSignature());
Assert.Contains("Class\\.Name", name);
}
[Fact]
public void NameWithEqualsShouldNotBeEscaped()
{
var type = new TypeReference(_module, _module, "Company.ProductName", "#=abc");
string name = TypeNameBuilder.GetAssemblyQualifiedName(type.ToTypeSignature());
Assert.DoesNotContain('\\', name);
Assert.Contains("#=abc", name);
}
[Fact]
public void NamespaceShouldNotBeEscaped()
{
var type = new TypeReference(_module, _module, "Company.ProductName", "ClassName");
string name = TypeNameBuilder.GetAssemblyQualifiedName(type.ToTypeSignature());
Assert.DoesNotContain('\\', name);
Assert.Contains("Company.ProductName", name);
}
[Fact]
public void NamespaceWithEqualsShouldNotBeEscaped()
{
var type = new TypeReference(_module, _module, "#=abc", "ClassName");
string name = TypeNameBuilder.GetAssemblyQualifiedName(type.ToTypeSignature());
Assert.DoesNotContain('\\', name);
Assert.Contains("#=abc", name);
}
[Theory]
[InlineData("MyNamespace", "MyType", "MyNestedType")]
[InlineData("MyNamespace", "#=abc", "#=def")]
public void NestedTypeShouldContainPlus(string ns, string name, string nestedType)
{
var type = new TypeReference(_module, new TypeReference(_module, ns, name), null, nestedType);
string fullname = TypeNameBuilder.GetAssemblyQualifiedName(type.ToTypeSignature());
Assert.DoesNotContain('\\', fullname);
Assert.Contains($"{ns}.{name}+{nestedType}", fullname);
}
[Theory]
[InlineData("MyType", "MyNestedType")]
[InlineData("#=abc", "#=def")]
public void NestedTypeNoNamespaceShouldContainPlus(string name, string nestedType)
{
var type = new TypeReference(_module, new TypeReference(_module, null, name), null, nestedType);
string fullname = TypeNameBuilder.GetAssemblyQualifiedName(type.ToTypeSignature());
Assert.DoesNotContain('\\', fullname);
Assert.Contains($"{name}+{nestedType}", fullname);
}
[Fact]
public void CorLibWithoutFullScope()
{
var type = _module.CorLibTypeFactory.Object;
string name = TypeNameBuilder.GetAssemblyQualifiedName(type, true);
Assert.Contains(type.FullName, name);
Assert.DoesNotContain(type.Scope.Name, name);
}
[Fact]
public void CorLibWithFullScope()
{
var type = _module.CorLibTypeFactory.Object;
string name = TypeNameBuilder.GetAssemblyQualifiedName(type, false);
Assert.Contains(type.FullName, name);
Assert.Contains(type.Scope.Name, name);
}
} | 116 | 3,631 | using System;
using System.Collections.Generic;
using System.IO;
using AsmResolver.Shims;
namespace AsmResolver.DotNet.Signatures.Parsing
{
/// <summary>
/// Provides a mechanism for building up a fully qualified type names, as they are stored in custom attribute signatures.
/// </summary>
public sealed class TypeNameBuilder : ITypeSignatureVisitor<object?>
{
private readonly TextWriter _writer;
private readonly bool _omitCorLib;
private TypeNameBuilder(TextWriter writer, bool omitCorLib)
{
_writer = writer ?? throw new ArgumentNullException(nameof(writer));
_omitCorLib = omitCorLib;
}
/// <summary>
/// Builds up an assembly qualified type name.
/// </summary>
/// <param name="signature">The type to convert to a string.</param>
/// <returns>The built up type name.</returns>
public static string GetAssemblyQualifiedName(TypeSignature signature) =>
GetAssemblyQualifiedName(signature, true);
/// <summary>
/// Builds up an assembly qualified type name.
/// </summary>
/// <param name="signature">The type to convert to a string.</param>
/// <param name="omitCorLib">Indicates any reference to corlib should not be included explicitly.</param>
/// <returns>The built up type name.</returns>
public static string GetAssemblyQualifiedName(TypeSignature signature, bool omitCorLib)
{
var writer = new StringWriter();
var builder = new TypeNameBuilder(writer, omitCorLib);
builder.WriteTypeAssemblyQualifiedName(signature);
return writer.ToString();
}
private void WriteTypeAssemblyQualifiedName(TypeSignature type)
{
type.AcceptVisitor(this);
var assembly = type.Scope?.GetAssembly();
if (assembly is not null && assembly != type.Module?.Assembly)
{
if (assembly.IsCorLib && _omitCorLib)
return;
_writer.Write(", ");
WriteAssemblySpec(assembly);
}
}
/// <inheritdoc />
public object? VisitArrayType(ArrayTypeSignature signature)
{
signature.BaseType.AcceptVisitor(this);
_writer.Write('[');
for (int i = 0; i < signature.Dimensions.Count; i++)
_writer.Write(',');
_writer.Write(']');
return null;
}
/// <inheritdoc />
public object VisitBoxedType(BoxedTypeSignature signature) => throw new NotSupportedException();
/// <inheritdoc />
public object? VisitByReferenceType(ByReferenceTypeSignature signature)
{
signature.BaseType.AcceptVisitor(this);
_writer.Write('&');
return null;
}
/// <inheritdoc />
public object? VisitCorLibType(CorLibTypeSignature signature)
{
WriteIdentifier(signature.Namespace);
_writer.Write('.');
WriteIdentifier(signature.Name);
return null;
}
/// <inheritdoc />
public object VisitCustomModifierType(CustomModifierTypeSignature signature) => throw new NotSupportedException();
/// <inheritdoc />
public object? VisitGenericInstanceType(GenericInstanceTypeSignature signature)
{
WriteSimpleTypeName(signature.GenericType);
_writer.Write('[');
for (int i = 0; i < signature.TypeArguments.Count; i++)
{
_writer.Write('[');
WriteTypeAssemblyQualifiedName(signature.TypeArguments[i]);
_writer.Write(']');
if (i < signature.TypeArguments.Count - 1)
_writer.Write(',');
}
_writer.Write(']');
return null;
}
/// <inheritdoc />
public object VisitGenericParameter(GenericParameterSignature signature) => throw new NotSupportedException();
/// <inheritdoc />
public object VisitPinnedType(PinnedTypeSignature signature) => throw new NotSupportedException();
/// <inheritdoc />
public object? VisitPointerType(PointerTypeSignature signature)
{
signature.BaseType.AcceptVisitor(this);
_writer.Write('*');
return null;
}
/// <inheritdoc />
public object VisitSentinelType(SentinelTypeSignature signature) => throw new NotSupportedException();
/// <inheritdoc />
public object? VisitSzArrayType(SzArrayTypeSignature signature)
{
signature.BaseType.AcceptVisitor(this);
_writer.Write("[]");
return null;
}
/// <inheritdoc />
public object? VisitTypeDefOrRef(TypeDefOrRefSignature signature)
{
WriteSimpleTypeName(signature.Type);
return null;
}
/// <inheritdoc />
public object VisitFunctionPointerType(FunctionPointerTypeSignature signature) =>
throw new NotSupportedException("Function pointer type signatures are not supported in type name building.");
private void WriteSimpleTypeName(ITypeDefOrRef? type)
{
var ancestors = new List<ITypeDefOrRef>();
while (type is not null)
{
ancestors.Add(type);
type = type.DeclaringType;
}
string? ns = ancestors[ancestors.Count - 1].Namespace;
if (!string.IsNullOrEmpty(ns))
{
WriteIdentifier(ns, true);
_writer.Write('.');
}
WriteIdentifier(ancestors[ancestors.Count - 1].Name);
for (int i = ancestors.Count - 2; i >= 0; i--)
{
_writer.Write('+');
WriteIdentifier(ancestors[i].Name);
}
}
private void WriteAssemblySpec(AssemblyDescriptor assembly)
{
WriteIdentifier(assembly.Name, true);
_writer.Write(", Version=");
_writer.Write(assembly.Version.ToString());
_writer.Write(", PublicKeyToken=");
var token = assembly.GetPublicKeyToken();
if (token is null)
_writer.Write("null");
else
WriteHexBlob(token);
_writer.Write(", Culture=");
WriteIdentifier(assembly.Culture ?? "neutral");
}
private void WriteIdentifier(string? identifier, bool escapeDots = false)
{
if (string.IsNullOrEmpty(identifier))
return;
foreach (char c in identifier!)
{
if (TypeNameLexer.ReservedChars.Contains(c) && (c != '.' || !escapeDots))
_writer.Write('\\');
_writer.Write(c);
}
}
private void WriteHexBlob(byte[] token)
{
foreach (byte b in token)
_writer.Write(b.ToString("x2"));
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Signatures\TypeNameParserTest.cs | AsmResolver.DotNet.Tests.Signatures
| TypeNameParserTest | ['private readonly ModuleDefinition _module;', 'private readonly SignatureComparer _comparer;'] | ['System', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.Signatures.Parsing', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class TypeNameParserTest
{
private readonly ModuleDefinition _module;
private readonly SignatureComparer _comparer;
public TypeNameParserTest()
{
_module = new ModuleDefinition("DummyModule", KnownCorLibs.SystemRuntime_v4_2_2_0);
_comparer = new SignatureComparer();
}
[Theory]
[InlineData("MyType")]
[InlineData("#=abc")]
[InlineData("\u0002\u2007\u2007")]
public void SimpleTypeNoNamespace(string name)
{
var expected = new TypeReference(_module, null, name).ToTypeSignature();
var actual = TypeNameParser.Parse(_module, expected.Name);
Assert.Equal(expected, actual, _comparer);
}
[Theory]
[InlineData("MyNamespace")]
[InlineData("MyNamespace.SubNamespace")]
[InlineData("MyNamespace.SubNamespace.SubSubNamespace")]
[InlineData("#=abc.#=def")]
[InlineData("\u0002\u2007\u2007.\u0002\u2007\u2007")]
public void SimpleTypeWithNamespace(string ns)
{
var expected = new TypeReference(_module, ns, "MyType").ToTypeSignature();
var actual = TypeNameParser.Parse(_module, expected.FullName);
Assert.Equal(expected, actual, _comparer);
}
[Theory]
[InlineData("MyNamespace", "MyType", "MyNestedType")]
[InlineData("MyNamespace", "#=abc", "#=def")]
[InlineData("\u0002\u2007\u2007", "\u0002\u2007\u2007", "\u0002\u2007\u2007")]
public void NestedType(string ns, string name, string nestedType)
{
var expected = new TypeReference(
new TypeReference(_module, ns, name),
null,
nestedType)
.ToTypeSignature();
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}+{nestedType}");
Assert.Equal(expected, actual, _comparer);
}
[Theory]
[InlineData("MyType", "MyNestedType")]
[InlineData("#=abc", "#=def")]
[InlineData("\u0002\u2007\u2007", "\u0002\u2007\u2007")]
public void NestedTypeNoNamespace(string name, string nestedType)
{
var expected = new TypeReference(
new TypeReference(_module, null, name),
null,
nestedType)
.ToTypeSignature();
var actual = TypeNameParser.Parse(_module, $"{name}+{nestedType}");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void TypeWithAssemblyName()
{
const string ns = "MyNamespace";
const string name = "MyType";
var assemblyRef = new AssemblyReference("MyAssembly", new Version(1, 2, 3, 4));
var expected = new TypeReference(assemblyRef, ns, name).ToTypeSignature();
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}, {assemblyRef.FullName}");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void TypeWithAssemblyNameWithPublicKey()
{
const string ns = "MyNamespace";
const string name = "MyType";
var assemblyRef = new AssemblyReference(
"MyAssembly",
new Version(1, 2, 3, 4),
false,
new byte[] {1, 2, 3, 4, 5, 6, 7, 8});
var expected = new TypeReference(assemblyRef, ns, name).ToTypeSignature();
var actual = TypeNameParser.Parse(_module,
$"{ns}.{name}, {assemblyRef.FullName}");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void SimpleArrayType()
{
const string ns = "MyNamespace";
const string name = "MyType";
var elementType = new TypeReference(_module, ns, name).ToTypeSignature();
var expected = new SzArrayTypeSignature(elementType);
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}[]");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void MultidimensionalArray()
{
const string ns = "MyNamespace";
const string name = "MyType";
var elementType = new TypeReference(_module, ns, name).ToTypeSignature();
var expected = new ArrayTypeSignature(elementType, 4);
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}[,,,]");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void GenericTypeSingleBrackets()
{
const string ns = "MyNamespace";
const string name = "MyType";
var elementType = new TypeReference(_module, ns, name);
var argumentType = _module.CorLibTypeFactory.Object;
var expected = elementType.MakeGenericInstanceType(false, argumentType);
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}[{argumentType.Namespace}.{argumentType.Name}]");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void GenericTypeSingleBracketsMultiElements()
{
const string ns = "MyNamespace";
const string name = "MyType";
var elementType = new TypeReference(_module, ns, name);
var argumentType = _module.CorLibTypeFactory.Object;
var argumentType2 = _module.CorLibTypeFactory.Int32;
var expected = new GenericInstanceTypeSignature(elementType, false, argumentType, argumentType2);
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}[{argumentType.Namespace}.{argumentType.Name},{argumentType2.Namespace}.{argumentType2.Name}]");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void GenericTypeSingleBracketsMultiElementsWithPlus()
{
const string ns = "MyNamespace";
const string name = "MyType";
const string escapedPName = "MyType\\+WithPlus";
const string pname = "MyType+WithPlus";
var elementType = new TypeReference(_module, ns, name);
var argumentType = _module.CorLibTypeFactory.Object;
var argumentType2 = new TypeReference(_module, ns, pname).ToTypeSignature(); ;
var expected = new GenericInstanceTypeSignature(elementType, false, argumentType, argumentType2);
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}[{argumentType.Namespace}.{argumentType.Name},{ns}.{escapedPName}]");
Assert.Equal(expected, actual, _comparer);
}
[Theory]
[InlineData("System", "Object")]
[InlineData("System", "#=abc")]
[InlineData("#=abc", "#=def")]
public void GenericTypeMultiBrackets(string argNs, string argName)
{
const string ns = "MyNamespace";
const string name = "MyType";
var elementType = new TypeReference(_module, ns, name);
var argumentType = new TypeReference(_module, _module, argNs, argName)
.ToTypeSignature();
var expected = new GenericInstanceTypeSignature(elementType, false, argumentType);
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}[[{argumentType.Namespace}.{argumentType.Name}]]");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void GenericTypeMultiBracketsMultiElementsVersion()
{
const string ns = "MyNamespace";
const string name = "MyType";
var elementType = new TypeReference(_module, ns, name);
var argumentType = _module.CorLibTypeFactory.Object;
var argumentType2 = _module.CorLibTypeFactory.Int32;
var fullName = _module.CorLibTypeFactory.CorLibScope.GetAssembly().FullName;
var expected = new GenericInstanceTypeSignature(elementType, false, argumentType, argumentType2);
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}[[{argumentType.Namespace}.{argumentType.Name}, {fullName}],[{argumentType2.Namespace}.{argumentType2.Name}, {fullName}]]");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void SpacesInAssemblySpec()
{
const string ns = "MyNamespace";
const string name = "MyType";
const string assemblyRef = "Some Assembly";
var scope = new AssemblyReference(assemblyRef, new Version(1, 0, 0, 0));
var expected = new TypeReference(_module, scope, ns, name).ToTypeSignature();
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}, {assemblyRef}, Version={scope.Version}");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void ReadEscapedTypeName()
{
const string ns = "MyNamespace";
const string escapedName = "MyType\\+WithPlus";
const string name = "MyType+WithPlus";
var expected = new TypeReference(_module, ns, name).ToTypeSignature();
var actual = TypeNameParser.Parse(_module, $"{ns}.{escapedName}");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void ReadTypeInSameAssemblyWithoutScope()
{
const string ns = "MyNamespace";
const string name = "MyType";
var definition = new TypeDefinition(ns, name, TypeAttributes.Public, _module.CorLibTypeFactory.Object.Type);
_module.TopLevelTypes.Add(definition);
var expected = definition.ToTypeSignature();
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void ReadTypeInCorLibAssemblyWithoutScope()
{
const string ns = "System";
const string name = "Array";
var expected = new TypeReference(_module.CorLibTypeFactory.CorLibScope, ns, name).ToTypeSignature();
var actual = TypeNameParser.Parse(_module, $"{ns}.{name}");
Assert.Equal(expected, actual, _comparer);
}
[Fact]
public void ReadCorLibTypeShouldNotUpdateScopesOfUnderlyingTypes()
{
// https://github.com/Washi1337/AsmResolver/issues/263
var scope = _module.CorLibTypeFactory.Object.Type.Scope;
TypeNameParser.Parse(_module,
"System.Object, System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
Assert.Same(scope, _module.CorLibTypeFactory.Object.Type.Scope);
}
[Fact]
public void ReadTypeShouldReuseScopeInstanceWhenAvailable()
{
var type = TypeNameParser.Parse(_module,
"System.Array, System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
Assert.Contains(type.Scope!.GetAssembly(), _module.AssemblyReferences);
}
[Fact]
public void ReadTypeShouldUseNewScopeInstanceIfNotImportedYet()
{
var type = TypeNameParser.Parse(_module,
"SomeNamespace.SomeType, SomeAssembly, Version=1.2.3.4, Culture=neutral, PublicKeyToken=0123456789abcdef");
Assert.DoesNotContain(type.Scope!.GetAssembly(), _module.AssemblyReferences);
}
[Fact]
public void ReadTypeNameFromLocalModuleShouldResultInResolvableType()
{
var module = ModuleDefinition.FromFile(typeof(TypeNameParserTest).Assembly.Location, TestReaderParameters);
var type = TypeNameParser
.Parse(module, typeof(TypeNameParserTest).AssemblyQualifiedName!)
.GetUnderlyingTypeDefOrRef()!;
Assert.NotNull(type.Resolve());
Assert.NotNull(type.ImportWith(module.DefaultImporter).Resolve());
}
} | 215 | 12,577 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AsmResolver.Shims;
namespace AsmResolver.DotNet.Signatures.Parsing
{
/// <summary>
/// Provides a mechanism for parsing a fully assembly qualified name of a type.
/// </summary>
public struct TypeNameParser
{
// src/coreclr/src/vm/typeparse.cpp
// https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/specifying-fully-qualified-type-names
private static readonly SignatureComparer Comparer = new();
private readonly ModuleDefinition _module;
private TypeNameLexer _lexer;
private TypeNameParser(ModuleDefinition module, TypeNameLexer lexer)
{
_module = module ?? throw new ArgumentNullException(nameof(module));
_lexer = lexer;
}
/// <summary>
/// Parses a single fully assembly qualified name.
/// </summary>
/// <param name="module">The module containing the assembly qualified name.</param>
/// <param name="canonicalName">The fully qualified assembly name of the type.</param>
/// <returns>The parsed type.</returns>
public static TypeSignature Parse(ModuleDefinition module, string canonicalName)
{
var lexer = new TypeNameLexer(new StringReader(canonicalName));
var parser = new TypeNameParser(module, lexer);
return parser.ParseTypeSpec();
}
private TypeSignature ParseTypeSpec()
{
bool lastHasConsumedTypeName = _lexer.HasConsumedTypeName;
// Parse type signature.
_lexer.HasConsumedTypeName = false;
var typeSpec = ParseSimpleTypeSpec();
_lexer.HasConsumedTypeName = true;
// See if the type full name contains an assembly ref.
var scope = TryExpect(TypeNameTerminal.Comma).HasValue
? (IResolutionScope) ParseAssemblyNameSpec()
: null;
_lexer.HasConsumedTypeName = lastHasConsumedTypeName;
if (typeSpec.GetUnderlyingTypeDefOrRef() is TypeReference reference)
SetScope(reference, scope);
// Ensure corlib type sigs are used.
if (Comparer.Equals(typeSpec.Scope, _module.CorLibTypeFactory.CorLibScope))
{
var corlibType = _module.CorLibTypeFactory.FromType(typeSpec);
if (corlibType != null)
return corlibType;
}
return typeSpec;
}
private void SetScope(TypeReference reference, IResolutionScope? newScope)
{
// Find the top-most type.
while (reference.Scope is TypeReference declaringType)
reference = declaringType;
// If the scope is null, it means it was omitted from the fully qualified type name.
// In this case, the CLR first looks into the current assembly, and then into corlib.
if (newScope is not null)
{
// Update scope.
reference.Scope = newScope;
}
else
{
// First look into the current module.
reference.Scope = _module;
var definition = reference.Resolve();
if (definition is null)
{
// If that fails, try corlib.
reference.Scope = _module.CorLibTypeFactory.CorLibScope;
definition = reference.Resolve();
// If both lookups fail, revert to the normal module as scope as a fallback.
if (definition is null)
reference.Scope = _module;
}
}
}
private TypeSignature ParseSimpleTypeSpec()
{
// Parse type name.
var typeName = ParseTypeName();
// Check for annotations.
while (true)
{
switch (_lexer.Peek().Terminal)
{
case TypeNameTerminal.Ampersand:
typeName = ParseByReferenceTypeSpec(typeName);
break;
case TypeNameTerminal.Star:
typeName = ParsePointerTypeSpec(typeName);
break;
case TypeNameTerminal.OpenBracket:
typeName = ParseArrayOrGenericTypeSpec(typeName);
break;
default:
return typeName;
}
}
}
private TypeSignature ParseByReferenceTypeSpec(TypeSignature typeName)
{
Expect(TypeNameTerminal.Ampersand);
return new ByReferenceTypeSignature(typeName);
}
private TypeSignature ParsePointerTypeSpec(TypeSignature typeName)
{
Expect(TypeNameTerminal.Star);
return new PointerTypeSignature(typeName);
}
private TypeSignature ParseArrayOrGenericTypeSpec(TypeSignature typeName)
{
Expect(TypeNameTerminal.OpenBracket);
switch (_lexer.Peek().Terminal)
{
case TypeNameTerminal.OpenBracket:
case TypeNameTerminal.Identifier:
return ParseGenericTypeSpec(typeName);
default:
return ParseArrayTypeSpec(typeName);
}
}
private TypeSignature ParseArrayTypeSpec(TypeSignature typeName)
{
var dimensions = new List<ArrayDimension>
{
ParseArrayDimension()
};
bool stop = false;
while (!stop)
{
var nextToken = Expect(TypeNameTerminal.CloseBracket, TypeNameTerminal.Comma);
switch (nextToken.Terminal)
{
case TypeNameTerminal.CloseBracket:
stop = true;
break;
case TypeNameTerminal.Comma:
dimensions.Add(ParseArrayDimension());
break;
}
}
if (dimensions.Count == 1 && dimensions[0].Size == null && dimensions[0].LowerBound == null)
return new SzArrayTypeSignature(typeName);
var result = new ArrayTypeSignature(typeName);
foreach (var dimension in dimensions)
result.Dimensions.Add(dimension);
return result;
}
private ArrayDimension ParseArrayDimension()
{
switch (_lexer.Peek().Terminal)
{
case TypeNameTerminal.CloseBracket:
case TypeNameTerminal.Comma:
return new ArrayDimension();
case TypeNameTerminal.Number:
int? size = null;
int? lowerBound = null;
int firstNumber = int.Parse(_lexer.Next().Text);
var dots = TryExpect(TypeNameTerminal.Ellipsis, TypeNameTerminal.DoubleDot);
if (dots.HasValue)
{
var secondNumberToken = TryExpect(TypeNameTerminal.Number);
if (secondNumberToken.HasValue)
{
int secondNumber = int.Parse(secondNumberToken.Value.Text);
size = secondNumber - firstNumber;
lowerBound = firstNumber;
}
else
{
lowerBound = firstNumber;
}
}
return new ArrayDimension(size, lowerBound);
default:
// Fail intentionally:
Expect(TypeNameTerminal.CloseBracket, TypeNameTerminal.Comma, TypeNameTerminal.Number);
return new ArrayDimension();
}
}
private TypeSignature ParseGenericTypeSpec(TypeSignature typeName)
{
var result = new GenericInstanceTypeSignature(typeName.ToTypeDefOrRef(), typeName.IsValueType);
result.TypeArguments.Add(ParseGenericTypeArgument(result));
bool stop = false;
while (!stop)
{
var nextToken = Expect(TypeNameTerminal.CloseBracket, TypeNameTerminal.Comma);
switch (nextToken.Terminal)
{
case TypeNameTerminal.CloseBracket:
stop = true;
break;
case TypeNameTerminal.Comma:
result.TypeArguments.Add(ParseGenericTypeArgument(result));
break;
}
}
return result;
}
private TypeSignature ParseGenericTypeArgument(GenericInstanceTypeSignature genericInstance)
{
var extraBracketToken = TryExpect(TypeNameTerminal.OpenBracket);
var result = !extraBracketToken.HasValue
? ParseSimpleTypeSpec()
: ParseTypeSpec();
if (extraBracketToken.HasValue)
Expect(TypeNameTerminal.CloseBracket);
return result;
}
private TypeSignature ParseTypeName()
{
// Note: This is a slight deviation from grammar (but is equivalent), to make the parsing easier.
// We read all components
(string? ns, var names) = ParseNamespaceTypeName();
TypeReference? result = null;
for (int i = 0; i < names.Count; i++)
{
result = result is null
? new TypeReference(_module, _module, ns, names[i])
: new TypeReference(_module, result, null, names[i]);
}
if (result is null)
throw new FormatException();
return result.ToTypeSignature();
}
private (string? Namespace, IList<string> TypeNames) ParseNamespaceTypeName()
{
var names = ParseDottedExpression(TypeNameTerminal.Identifier);
// The namespace is every name concatenated except for the last one.
string? ns;
if (names.Count > 1)
{
ns = StringShim.Join(".", names.Take(names.Count - 1));
names.RemoveRange(0, names.Count - 1);
}
else
{
ns = null;
}
// Check if we have any nested identifiers.
while (TryExpect(TypeNameTerminal.Plus).HasValue)
{
var nextIdentifier = Expect(TypeNameTerminal.Identifier);
names.Add(nextIdentifier.Text);
}
return (ns, names);
}
private List<string> ParseDottedExpression(TypeNameTerminal terminal)
{
var result = new List<string>();
while (true)
{
var nextIdentifier = TryExpect(terminal);
if (!nextIdentifier.HasValue)
break;
result.Add(nextIdentifier.Value.Text);
if (!TryExpect(TypeNameTerminal.Dot).HasValue)
break;
}
if (result.Count == 0)
throw new FormatException($"Expected {terminal}.");
return result;
}
private AssemblyReference ParseAssemblyNameSpec()
{
string assemblyName = StringShim.Join(".", ParseDottedExpression(TypeNameTerminal.Identifier));
var newReference = new AssemblyReference(assemblyName, new Version());
while (TryExpect(TypeNameTerminal.Comma).HasValue)
{
string propertyName = Expect(TypeNameTerminal.Identifier).Text;
Expect(TypeNameTerminal.Equals);
if (propertyName.Equals("version", StringComparison.OrdinalIgnoreCase))
{
newReference.Version = ParseVersion();
}
else if (propertyName.Equals("publickey", StringComparison.OrdinalIgnoreCase))
{
newReference.PublicKeyOrToken = ParseHexBlob();
newReference.HasPublicKey = true;
}
else if (propertyName.Equals("publickeytoken", StringComparison.OrdinalIgnoreCase))
{
newReference.PublicKeyOrToken = ParseHexBlob();
newReference.HasPublicKey = false;
}
else if (propertyName.Equals("culture", StringComparison.OrdinalIgnoreCase))
{
string culture = ParseCulture();
newReference.Culture = !culture.Equals("neutral", StringComparison.OrdinalIgnoreCase)
? culture
: null;
}
else
{
throw new FormatException($"Unsupported {propertyName} assembly property.");
}
}
// Reuse imported assembly reference instance if possible.
for (int i = 0; i < _module.AssemblyReferences.Count; i++)
{
var existingReference = _module.AssemblyReferences[i];
if (Comparer.Equals((AssemblyDescriptor) existingReference, newReference))
return existingReference;
}
return newReference;
}
private Version ParseVersion()
{
string versionString = StringShim.Join(".", ParseDottedExpression(TypeNameTerminal.Number));
return VersionShim.Parse(versionString);
}
private byte[]? ParseHexBlob()
{
string hexString = Expect(TypeNameTerminal.Identifier, TypeNameTerminal.Number).Text;
if (hexString == "null")
return null;
if (hexString.Length % 2 != 0)
throw new FormatException("Provided hex string does not have an even length.");
byte[] result = new byte[hexString.Length / 2];
for (int i = 0; i < hexString.Length; i += 2)
result[i / 2] = ParseHexByte(hexString, i);
return result;
}
private static byte ParseHexByte(string hexString, int index)
{
return (byte) ((ParseHexNibble(hexString[index]) << 4) | ParseHexNibble(hexString[index + 1]));
}
private static byte ParseHexNibble(char nibble) => nibble switch
{
>= '0' and <= '9' => (byte) (nibble - '0'),
>= 'A' and <= 'F' => (byte) (nibble - 'A' + 10),
>= 'a' and <= 'f' => (byte) (nibble - 'a' + 10),
_ => throw new FormatException()
};
private string ParseCulture()
{
return Expect(TypeNameTerminal.Identifier).Text;
}
private TypeNameToken Expect(TypeNameTerminal terminal)
{
return TryExpect(terminal)
?? throw new FormatException($"Expected {terminal}.");
}
private TypeNameToken? TryExpect(TypeNameTerminal terminal)
{
var token = _lexer.Peek();
if (terminal != token.Terminal)
return null;
_lexer.Next();
return token;
}
private TypeNameToken Expect(params TypeNameTerminal[] terminals)
{
return TryExpect(terminals)
?? throw new FormatException(
$"Expected one of {StringShim.Join(", ", terminals.Select(x => x.ToString()))}.");
}
private TypeNameToken? TryExpect(params TypeNameTerminal[] terminals)
{
var token = _lexer.Peek();
if (!terminals.Contains(token.Terminal))
return null;
_lexer.Next();
return token;
}
}
}
|
Washi1337 | AsmResolver | F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj | F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\Signatures\TypeSignatureTest.cs | AsmResolver.DotNet.Tests.Signatures
| TypeSignatureTest | ['private readonly TypeDefinition _dummyType = new("Namespace", "Type", TypeAttributes.Class);'] | ['System', 'System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Generics', 'AsmResolver.DotNet.TestCases.Types', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit'] | xUnit | net8.0 | public class TypeSignatureTest
{
private readonly TypeDefinition _dummyType = new("Namespace", "Type", TypeAttributes.Class);
[Fact]
public void GetTypeDefOrRefFullName()
{
Assert.Equal("Namespace.Type", _dummyType.ToTypeSignature().FullName);
}
[Fact]
public void GetArrayTypeFullName()
{
Assert.Equal("Namespace.Type[0...9, 0...19]", _dummyType
.ToTypeSignature()
.MakeArrayType(
new ArrayDimension(10),
new ArrayDimension(20))
.FullName);
}
[Fact]
public void GetByReferenceTypeFullName()
{
Assert.Equal("Namespace.Type&", _dummyType
.ToTypeSignature()
.MakeByReferenceType()
.FullName);
}
[Fact]
public void GetCorLibTypeFullName()
{
var module = new ModuleDefinition("Dummy");
Assert.Equal("System.String", module.CorLibTypeFactory.String.FullName);
}
[Fact]
public void GetFunctionPointerTypeFullName()
{
var module = new ModuleDefinition("Dummy");
Assert.Equal("method System.String *(System.Object, System.Int32)",
MethodSignature.CreateStatic(
module.CorLibTypeFactory.String,
module.CorLibTypeFactory.Object,
module.CorLibTypeFactory.Int32)
.MakeFunctionPointerType().FullName);
}
[Fact]
public void GetInstanceFunctionPointerTypeFullName()
{
var module = new ModuleDefinition("Dummy");
Assert.Equal("method instance System.String *(System.Object, System.Int32)",
MethodSignature.CreateInstance(
module.CorLibTypeFactory.String,
module.CorLibTypeFactory.Object,
module.CorLibTypeFactory.Int32)
.MakeFunctionPointerType().FullName);
}
[Fact]
public void GetGenericInstanceTypeFullName()
{
var module = new ModuleDefinition("Dummy");
var genericInstance = _dummyType.MakeGenericInstanceType(
module.CorLibTypeFactory.Int32,
_dummyType.MakeGenericInstanceType(module.CorLibTypeFactory.Object));
Assert.Equal("Type<System.Int32, Namespace.Type<System.Object>>", genericInstance.Name);
Assert.Equal("Namespace.Type<System.Int32, Namespace.Type<System.Object>>", genericInstance.FullName);
}
[Fact]
public void GetGenericParameterFullName()
{
Assert.Equal("!2", new GenericParameterSignature(GenericParameterType.Type, 2).FullName);
Assert.Equal("!!2", new GenericParameterSignature(GenericParameterType.Method, 2).FullName);
}
[Fact]
public void GetPointerTypeFullName()
{
Assert.Equal("Namespace.Type*", _dummyType
.ToTypeSignature()
.MakePointerType()
.FullName);
}
[Fact]
public void GetSzArrayTypeFullName()
{
Assert.Equal("Namespace.Type[]", _dummyType
.ToTypeSignature()
.MakeSzArrayType()
.FullName);
}
[Fact]
public void GetRequiredModifierTypeFullName()
{
Assert.Equal("Namespace.Type modreq(Namespace.Type)",
_dummyType
.ToTypeSignature()
.MakeModifierType(_dummyType, true)
.FullName);
}
[Fact]
public void GetOptionalModifierTypeFullName()
{
Assert.Equal("Namespace.Type modopt(Namespace.Type)",
_dummyType
.ToTypeSignature()
.MakeModifierType(_dummyType, false)
.FullName);
}
[Fact]
public void StripModifiersPinnedType()
{
var type = _dummyType.ToTypeSignature();
Assert.Equal(type, type.MakePinnedType().StripModifiers(), SignatureComparer.Default);
}
[Fact]
public void StripModifiersCustomModifierType()
{
var type = _dummyType.ToTypeSignature();
Assert.Equal(type, type.MakeModifierType(_dummyType, false).StripModifiers(), SignatureComparer.Default);
}
[Fact]
public void StripMultipleModifiers()
{
var type = _dummyType.ToTypeSignature();
Assert.Equal(type,
type
.MakeModifierType(_dummyType, false)
.MakeModifierType(_dummyType, true)
.MakePinnedType()
.StripModifiers(),
SignatureComparer.Default);
}
[Theory]
[InlineData(ElementType.I, ElementType.I)]
[InlineData(ElementType.I1, ElementType.I1)]
[InlineData(ElementType.I2, ElementType.I2)]
[InlineData(ElementType.I4, ElementType.I4)]
[InlineData(ElementType.I8, ElementType.I8)]
[InlineData(ElementType.U, ElementType.I)]
[InlineData(ElementType.U1, ElementType.I1)]
[InlineData(ElementType.U2, ElementType.I2)]
[InlineData(ElementType.U4, ElementType.I4)]
[InlineData(ElementType.U8, ElementType.I8)]
[InlineData(ElementType.String, ElementType.String)]
[InlineData(ElementType.Boolean, ElementType.Boolean)]
[InlineData(ElementType.Char, ElementType.Char)]
public void GetReducedTypeOfPrimitive(ElementType type, ElementType expected)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Equal(expected, module.CorLibTypeFactory.FromElementType(type)!.GetReducedType().ElementType);
}
[Theory]
[InlineData(typeof(Int32Enum), ElementType.I4)]
[InlineData(typeof(Int64Enum), ElementType.I8)]
public void GetReducedTypeOfEnum(Type type, ElementType expected)
{
var module = ModuleDefinition.FromFile(type.Assembly.Location, TestReaderParameters);
var signature = module.LookupMember<TypeDefinition>(type.MetadataToken).ToTypeSignature();
Assert.Equal(expected, signature.GetReducedType().ElementType);
}
[Fact]
public void GetReducedTypeOfNonPrimitive()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == "Program").ToTypeSignature(false);
Assert.Equal(type, type.GetReducedType());
}
[Theory]
[InlineData(ElementType.I, ElementType.I)]
[InlineData(ElementType.I1, ElementType.I1)]
[InlineData(ElementType.I2, ElementType.I2)]
[InlineData(ElementType.I4, ElementType.I4)]
[InlineData(ElementType.I8, ElementType.I8)]
[InlineData(ElementType.U, ElementType.I)]
[InlineData(ElementType.U1, ElementType.I1)]
[InlineData(ElementType.U2, ElementType.I2)]
[InlineData(ElementType.U4, ElementType.I4)]
[InlineData(ElementType.U8, ElementType.I8)]
[InlineData(ElementType.String, ElementType.String)]
[InlineData(ElementType.Boolean, ElementType.I1)]
[InlineData(ElementType.Char, ElementType.I2)]
public void GetVerificationTypeOfPrimitive(ElementType type, ElementType expected)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Equal(expected, module.CorLibTypeFactory.FromElementType(type)!.GetVerificationType().ElementType);
}
[Theory]
[InlineData(ElementType.I, ElementType.I)]
[InlineData(ElementType.I1, ElementType.I1)]
[InlineData(ElementType.I2, ElementType.I2)]
[InlineData(ElementType.I4, ElementType.I4)]
[InlineData(ElementType.I8, ElementType.I8)]
[InlineData(ElementType.U, ElementType.I)]
[InlineData(ElementType.U1, ElementType.I1)]
[InlineData(ElementType.U2, ElementType.I2)]
[InlineData(ElementType.U4, ElementType.I4)]
[InlineData(ElementType.U8, ElementType.I8)]
[InlineData(ElementType.String, ElementType.String)]
[InlineData(ElementType.Boolean, ElementType.I1)]
[InlineData(ElementType.Char, ElementType.I2)]
public void GetVerificationTypeOfManagedPrimitivePointer(ElementType type, ElementType expected)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var pointerType = module.CorLibTypeFactory.FromElementType(type)!.MakeByReferenceType();
var actualType = Assert.IsAssignableFrom<ByReferenceTypeSignature>(pointerType.GetVerificationType());
Assert.Equal(expected, actualType.BaseType.ElementType);
}
[Fact]
public void GetVerificationTypeOfNonPrimitive()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == "Program").ToTypeSignature(false);
Assert.Equal(type, type.GetVerificationType());
}
[Theory]
[InlineData(ElementType.I, ElementType.I)]
[InlineData(ElementType.I1, ElementType.I4)]
[InlineData(ElementType.I2, ElementType.I4)]
[InlineData(ElementType.I4, ElementType.I4)]
[InlineData(ElementType.I8, ElementType.I8)]
[InlineData(ElementType.U, ElementType.I)]
[InlineData(ElementType.U1, ElementType.I4)]
[InlineData(ElementType.U2, ElementType.I4)]
[InlineData(ElementType.U4, ElementType.I4)]
[InlineData(ElementType.U8, ElementType.I8)]
[InlineData(ElementType.String, ElementType.String)]
[InlineData(ElementType.Boolean, ElementType.I4)]
[InlineData(ElementType.Char, ElementType.I4)]
[InlineData(ElementType.R4, ElementType.R8)] // Technically incorrect, as it should be F.
[InlineData(ElementType.R8, ElementType.R8)]
public void GetIntermediateTypeOfPrimitive(ElementType type, ElementType expected)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
Assert.Equal(expected, module.CorLibTypeFactory.FromElementType(type)!.GetIntermediateType().ElementType);
}
[Fact]
public void GetIntermediateTypeOfNonPrimitive()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == "Program").ToTypeSignature(false);
Assert.Equal(type, type.GetIntermediateType());
}
[Fact]
public void GetDirectBaseClassOfArrayType()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var signature = module.CorLibTypeFactory.Object.MakeArrayType(3);
Assert.Equal("System.Array", signature.GetDirectBaseClass()!.FullName);
}
[Fact]
public void GetDirectBaseClassOfSzArrayType()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var signature = module.CorLibTypeFactory.Object.MakeSzArrayType();
Assert.Equal("System.Array", signature.GetDirectBaseClass()!.FullName);
}
[Fact]
public void GetDirectBaseClassOfInterfaceType()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var interfaceDefinition = new TypeDefinition("Namespace", "IName", TypeAttributes.Interface);
module.TopLevelTypes.Add(interfaceDefinition);
var interfaceSignature = interfaceDefinition.ToTypeSignature(false);
Assert.Equal("System.Object", interfaceSignature.GetDirectBaseClass()!.FullName);
}
[Fact]
public void GetDirectBaseClassOfNormalType()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var type = module.TopLevelTypes.First(t => t.Name == "Program").ToTypeSignature();
Assert.Equal("System.Object", type.GetDirectBaseClass()!.FullName);
}
[Fact]
public void GetDirectBaseClassOfNormalTypeWithBaseType()
{
var module = ModuleDefinition.FromFile(typeof(DerivedClass).Assembly.Location, TestReaderParameters);
var type = module.LookupMember<TypeDefinition>(typeof(DerivedClass).MetadataToken);
Assert.Equal(type.BaseType!.FullName, type.ToTypeSignature().GetDirectBaseClass()!.FullName);
}
[Fact]
public void GetDirectBaseClassOfGenericTypeInstance()
{
var module = ModuleDefinition.FromFile(typeof(GenericType<,,>).Assembly.Location, TestReaderParameters);
var genericInstanceType = module.LookupMember<TypeDefinition>(typeof(GenericType<,,>).MetadataToken)
.MakeGenericInstanceType(
module.CorLibTypeFactory.Int32,
module.CorLibTypeFactory.String,
module.CorLibTypeFactory.Object);
Assert.Equal("System.Object", genericInstanceType.GetDirectBaseClass()!.FullName);
}
[Fact]
public void GetDirectBaseClassOfGenericTypeInstanceWithGenericBaseClass()
{
var module = ModuleDefinition.FromFile(typeof(GenericDerivedType<,>).Assembly.Location, TestReaderParameters);
var genericInstanceType = module.LookupMember<TypeDefinition>(typeof(GenericDerivedType<,>).MetadataToken)
.MakeGenericInstanceType(
module.CorLibTypeFactory.Int32,
module.CorLibTypeFactory.Object);
var baseClass = Assert.IsAssignableFrom<GenericInstanceTypeSignature>(
genericInstanceType.GetDirectBaseClass());
Assert.Equal(typeof(GenericType<,,>).Namespace, baseClass.GenericType.Namespace);
Assert.Equal(typeof(GenericType<,,>).Name, baseClass.GenericType.Name);
Assert.Equal(new[]
{
"System.Int32",
"System.Object",
"System.String"
}, baseClass.TypeArguments.Select(t => t.FullName));
}
[Theory]
[InlineData(ElementType.I)]
[InlineData(ElementType.I1)]
[InlineData(ElementType.I2)]
[InlineData(ElementType.I4)]
[InlineData(ElementType.I8)]
[InlineData(ElementType.U)]
[InlineData(ElementType.U1)]
[InlineData(ElementType.U2)]
[InlineData(ElementType.U4)]
[InlineData(ElementType.U8)]
[InlineData(ElementType.R4)]
[InlineData(ElementType.R8)]
[InlineData(ElementType.String)]
[InlineData(ElementType.Boolean)]
[InlineData(ElementType.Char)]
public void IsCompatibleWithIdenticalPrimitiveTypes(ElementType elementType)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var type = module.CorLibTypeFactory.FromElementType(elementType)!;
Assert.True(type.IsCompatibleWith(type));
}
[Theory]
[InlineData(typeof(AbstractClass))]
[InlineData(typeof(DerivedClass))]
public void IsCompatibleWithIdenticalUserTypes(Type type)
{
var module = ModuleDefinition.FromFile(type.Assembly.Location, TestReaderParameters);
var signature = module.LookupMember<TypeDefinition>(type.MetadataToken).ToTypeSignature();
Assert.True(signature.IsCompatibleWith(signature));
}
[Theory]
[InlineData(typeof(DerivedClass), typeof(AbstractClass), true)]
[InlineData(typeof(DerivedDerivedClass), typeof(DerivedClass), true)]
[InlineData(typeof(DerivedDerivedClass), typeof(AbstractClass), true)]
[InlineData(typeof(AbstractClass), typeof(DerivedClass), false)]
[InlineData(typeof(AbstractClass), typeof(DerivedDerivedClass), false)]
public void IsCompatibleWithBaseClass(Type derivedType, Type baseType, bool expected)
{
var module = ModuleDefinition.FromFile(derivedType.Assembly.Location, TestReaderParameters);
var derivedSignature = module.LookupMember<TypeDefinition>(derivedType.MetadataToken).ToTypeSignature();
var abstractSignature = module.LookupMember<TypeDefinition>(baseType.MetadataToken).ToTypeSignature();
Assert.Equal(expected, derivedSignature.IsCompatibleWith(abstractSignature));
}
[Theory]
[InlineData(typeof(InterfaceImplementations), typeof(IInterface1), true)]
[InlineData(typeof(InterfaceImplementations), typeof(IInterface2), true)]
[InlineData(typeof(InterfaceImplementations), typeof(IInterface3), false)]
[InlineData(typeof(InterfaceImplementations), typeof(IInterface4), false)]
[InlineData(typeof(DerivedInterfaceImplementations), typeof(IInterface1), true)]
[InlineData(typeof(DerivedInterfaceImplementations), typeof(IInterface2), true)]
[InlineData(typeof(DerivedInterfaceImplementations), typeof(IInterface3), true)]
[InlineData(typeof(DerivedInterfaceImplementations), typeof(IInterface4), false)]
[InlineData(typeof(IInterface1), typeof(InterfaceImplementations), false)]
[InlineData(typeof(IInterface2), typeof(InterfaceImplementations), false)]
[InlineData(typeof(IInterface3), typeof(DerivedInterfaceImplementations), false)]
[InlineData(typeof(IInterface4), typeof(DerivedInterfaceImplementations), false)]
public void IsCompatibleWithInterface(Type derivedType, Type interfaceType, bool expected)
{
var module = ModuleDefinition.FromFile(typeof(DerivedClass).Assembly.Location, TestReaderParameters);
var derivedSignature = module.LookupMember<TypeDefinition>(derivedType.MetadataToken).ToTypeSignature();
var interfaceSignature = module.LookupMember<TypeDefinition>(interfaceType.MetadataToken).ToTypeSignature();
Assert.Equal(expected, derivedSignature.IsCompatibleWith(interfaceSignature));
}
[Theory]
[InlineData(new[] { ElementType.I4, ElementType.I4 }, new[] { ElementType.I4, ElementType.I4, ElementType.String }, true)]
[InlineData(new[] { ElementType.I4, ElementType.I8 }, new[] { ElementType.I4, ElementType.I4, ElementType.String }, false)]
[InlineData(new[] { ElementType.I4, ElementType.I4 }, new[] { ElementType.I4, ElementType.I8, ElementType.String }, false)]
[InlineData(new[] { ElementType.I4, ElementType.I4 }, new[] { ElementType.I4, ElementType.I4, ElementType.Boolean }, false)]
public void IsCompatibleWithGenericInterface(ElementType[] typeArguments1, ElementType[] typeArguments2, bool expected)
{
var module = ModuleDefinition.FromFile(typeof(GenericInterfaceImplementation<,>).Assembly.Location, TestReaderParameters);
var type1 = module.LookupMember<TypeDefinition>(typeof(GenericInterfaceImplementation<,>).MetadataToken)
.ToTypeSignature(false)
.MakeGenericInstanceType(
typeArguments1.Select(x => (TypeSignature) module.CorLibTypeFactory.FromElementType(x)!).ToArray()
);
var type2 = module.LookupMember<TypeDefinition>(typeof(IGenericInterface<,,>).MetadataToken)
.ToTypeSignature(false)
.MakeGenericInstanceType(
typeArguments2.Select(x => (TypeSignature) module.CorLibTypeFactory.FromElementType(x)!).ToArray()
);
Assert.Equal(expected, type1.IsCompatibleWith(type2));
}
[Theory]
[InlineData(ElementType.I1, ElementType.I1, true)]
[InlineData(ElementType.U1, ElementType.I1, true)]
[InlineData(ElementType.I1, ElementType.U1, true)]
[InlineData(ElementType.U1, ElementType.U1, true)]
[InlineData(ElementType.I1, ElementType.U2, false)]
[InlineData(ElementType.U2, ElementType.U1, false)]
[InlineData(ElementType.I4, ElementType.I4, true)]
[InlineData(ElementType.I4, ElementType.U4, true)]
[InlineData(ElementType.U4, ElementType.I4, true)]
public void IsCompatibleWithArray(ElementType elementType1, ElementType elementType2, bool expected)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var type1 = module.CorLibTypeFactory.FromElementType(elementType1)!.MakeSzArrayType();
var type2 = module.CorLibTypeFactory.FromElementType(elementType2)!.MakeSzArrayType();
Assert.Equal(expected, type1.IsCompatibleWith(type2));
}
[Theory]
[InlineData(ElementType.I1, ElementType.I1, true)]
[InlineData(ElementType.U1, ElementType.I1, true)]
[InlineData(ElementType.I1, ElementType.U1, true)]
[InlineData(ElementType.U1, ElementType.U1, true)]
[InlineData(ElementType.I1, ElementType.U2, false)]
[InlineData(ElementType.U2, ElementType.U1, false)]
[InlineData(ElementType.I4, ElementType.I4, true)]
[InlineData(ElementType.I4, ElementType.U4, true)]
[InlineData(ElementType.U4, ElementType.I4, true)]
public void IsCompatibleWithArrayAndIList(ElementType elementType1, ElementType elementType2, bool expected)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var type1 = module.CorLibTypeFactory.FromElementType(elementType1)!.MakeSzArrayType();
var type2 = module.CorLibTypeFactory.CorLibScope
.CreateTypeReference("System.Collections.Generic", "IList`1")
.ToTypeSignature(false)
.MakeGenericInstanceType(module.CorLibTypeFactory.FromElementType(elementType2)!);
Assert.Equal(expected, type1.IsCompatibleWith(type2));
}
[Fact]
public void IsCompatibleWithGenericInstanceAndObject()
{
var module = ModuleDefinition.FromFile(typeof(GenericType<,,>).Assembly.Location, TestReaderParameters);
var type1 = module
.LookupMember<TypeDefinition>(typeof(GenericType<,,>).MetadataToken)
.ToTypeSignature()
.MakeGenericInstanceType(
module.CorLibTypeFactory.Int32,
module.CorLibTypeFactory.Object,
module.CorLibTypeFactory.String);
Assert.True(type1.IsCompatibleWith(type1));
Assert.True(type1.IsCompatibleWith(module.CorLibTypeFactory.Object));
}
[Fact]
public void IsCompatibleWithGenericInstance()
{
var module = ModuleDefinition.FromFile(typeof(GenericDerivedType<,>).Assembly.Location, TestReaderParameters);
var type1 = module
.LookupMember<TypeDefinition>(typeof(GenericDerivedType<,>).MetadataToken)
.ToTypeSignature()
.MakeGenericInstanceType(
module.CorLibTypeFactory.Int32,
module.CorLibTypeFactory.Object);
var type2 = module
.LookupMember<TypeDefinition>(typeof(GenericType<,,>).MetadataToken)
.ToTypeSignature()
.MakeGenericInstanceType(
module.CorLibTypeFactory.Int32,
module.CorLibTypeFactory.Object,
module.CorLibTypeFactory.String);
var type3 = module
.LookupMember<TypeDefinition>(typeof(GenericType<,,>).MetadataToken)
.ToTypeSignature()
.MakeGenericInstanceType(
module.CorLibTypeFactory.Object,
module.CorLibTypeFactory.Int32,
module.CorLibTypeFactory.String);
Assert.True(type1.IsCompatibleWith(type2));
Assert.False(type1.IsCompatibleWith(type3));
}
[Theory]
[InlineData(ElementType.I1, ElementType.I1, true)]
[InlineData(ElementType.U1, ElementType.I1, true)]
[InlineData(ElementType.I1, ElementType.U1, true)]
[InlineData(ElementType.I1, ElementType.Boolean, true)]
[InlineData(ElementType.I2, ElementType.Char, true)]
[InlineData(ElementType.I4, ElementType.Boolean, false)]
[InlineData(ElementType.I1, ElementType.U2, false)]
public void IsCompatibleWithPointers(ElementType elementType1, ElementType elementType2, bool expected)
{
var module = ModuleDefinition.FromFile(typeof(GenericDerivedType<,>).Assembly.Location, TestReaderParameters);
var type1 = module.CorLibTypeFactory.FromElementType(elementType1)!.MakePointerType();
var type2 = module.CorLibTypeFactory.FromElementType(elementType2)!.MakePointerType();
Assert.Equal(expected, type1.IsCompatibleWith(type2));
}
[Theory]
[InlineData(ElementType.I1, ElementType.I4, true)]
[InlineData(ElementType.I2, ElementType.I4, true)]
[InlineData(ElementType.I4, ElementType.I4, true)]
[InlineData(ElementType.I8, ElementType.I4, false)]
[InlineData(ElementType.I4, ElementType.I1, true)]
[InlineData(ElementType.I4, ElementType.I2, true)]
[InlineData(ElementType.I4, ElementType.I8, false)]
[InlineData(ElementType.I, ElementType.I4, true)]
[InlineData(ElementType.I4, ElementType.I, true)]
public void IsAssignablePrimitives(ElementType elementType1, ElementType elementType2, bool expected)
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var type1 = module.CorLibTypeFactory.FromElementType(elementType1)!;
var type2 = module.CorLibTypeFactory.FromElementType(elementType2)!;
Assert.Equal(expected, type1.IsAssignableTo(type2));
}
[Fact]
public void IgnoreCustomModifiers()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var type1 = module.CorLibTypeFactory.Int32;
var type2 = module.CorLibTypeFactory.Int32.MakeModifierType(module.CorLibTypeFactory.CorLibScope
.CreateTypeReference("System.Runtime.CompilerServices", "IsVolatile")
.ImportWith(module.DefaultImporter),
true);
Assert.True(type1.IsCompatibleWith(type2));
Assert.True(type2.IsCompatibleWith(type1));
}
[Fact]
public void IgnoreNestedCustomModifiers()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var type1 = module.CorLibTypeFactory.Int32;
var type2 = module.CorLibTypeFactory.Int32.MakeModifierType(module.CorLibTypeFactory.CorLibScope
.CreateTypeReference("System.Runtime.CompilerServices", "IsVolatile")
.ImportWith(module.DefaultImporter),
true);
var genericType = module.CorLibTypeFactory.CorLibScope
.CreateTypeReference("System.Collections.Generic", "List`1")
.ImportWith(module.DefaultImporter);
var genericType1 = genericType.MakeGenericInstanceType(type1);
var genericType2 = genericType.MakeGenericInstanceType(type2);
Assert.True(genericType1.IsCompatibleWith(genericType2));
Assert.True(genericType2.IsCompatibleWith(genericType1));
}
[Fact]
public void IgnorePinnedModifiers()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var type1 = module.CorLibTypeFactory.Int32;
var type2 = module.CorLibTypeFactory.Int32.MakePinnedType();
Assert.True(type1.IsCompatibleWith(type2));
Assert.True(type2.IsCompatibleWith(type1));
}
[Fact]
public void GetModuleOfTypeDefOrRef()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters);
var signature = module.GetOrCreateModuleType().ToTypeSignature();
Assert.Same(module, signature.Module);
}
[Fact]
public void GetModuleOfTypeDefOrRefWithNullScope()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.TypeRefNullScope_CurrentModule, TestReaderParameters);
var signature = module
.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 2))
.ToTypeSignature();
Assert.Null(signature.Scope);
Assert.Same(module, signature.Module);
}
[Fact]
public void GetModuleOfSpecificationTypeWithNullScope()
{
var module = ModuleDefinition.FromBytes(Properties.Resources.TypeRefNullScope_CurrentModule, TestReaderParameters);
var signature = module
.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 2))
.ToTypeSignature()
.MakeSzArrayType();
Assert.Null(signature.Scope);
Assert.Same(module, signature.Module);
}
} | 278 | 30,962 | using System.Collections.Generic;
namespace AsmResolver.DotNet.Signatures
{
/// <summary>
/// Represents a type signature representing an array.
/// </summary>
public abstract class ArrayBaseTypeSignature : TypeSpecificationSignature
{
/// <summary>
/// Initializes an array type signature.
/// </summary>
/// <param name="baseType">The element type of the array.</param>
protected ArrayBaseTypeSignature(TypeSignature baseType)
: base(baseType)
{
}
/// <inheritdoc />
public override bool IsValueType => false;
/// <summary>
/// Gets the number of dimensions this array defines.
/// </summary>
public abstract int Rank
{
get;
}
/// <summary>
/// Obtains the dimensions this array defines.
/// </summary>
/// <returns>The dimensions.</returns>
public abstract IEnumerable<ArrayDimension> GetDimensions();
/// <inheritdoc />
protected override bool IsDirectlyCompatibleWith(TypeSignature other, SignatureComparer comparer)
{
if (base.IsDirectlyCompatibleWith(other, comparer))
return true;
TypeSignature? elementType = null;
if (other is ArrayBaseTypeSignature otherArrayType && Rank == otherArrayType.Rank)
{
// Arrays are only compatible if they have the same rank.
elementType = otherArrayType.BaseType;
}
else if (Rank == 1
&& other is GenericInstanceTypeSignature genericInstanceType
&& genericInstanceType.GenericType.IsTypeOf("System.Collections.Generic", "IList`1"))
{
// Arrays are also compatible with IList<T> if they've only one dimension.
elementType = genericInstanceType.TypeArguments[0];
}
if (elementType is null)
return false;
var v = BaseType.GetUnderlyingType();
var w = elementType.GetUnderlyingType();
return comparer.Equals(v.GetReducedType(), w.GetReducedType())
|| v.IsCompatibleWith(w, comparer);
}
}
}
|