Skip to content

Instantly share code, notes, and snippets.

@Konctantin
Created June 5, 2013 04:53
Show Gist options
  • Select an option

  • Save Konctantin/5711696 to your computer and use it in GitHub Desktop.

Select an option

Save Konctantin/5711696 to your computer and use it in GitHub Desktop.
#region Inject
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public unsafe byte[] Assemble(string source)
{
var passesLimit = 0x100;
#if DEBUG
Console.WriteLine("AsmSource:\n{0}", source);
#endif
var tbuffer = new byte[source.Length * passesLimit];
fasm_Assemble(source, tbuffer, tbuffer.Length, passesLimit, 0);
fixed (byte* pointer = tbuffer)
{
var fasm_result = *(FasmState*)pointer;
if (fasm_result.condition == FasmCondition.ERROR)
throw new Exception(string.Format("Fasm Syntax Error: {0}, at line {1}",
fasm_result.error_code, fasm_result.error_data->line_number));
if (fasm_result.condition != FasmCondition.OK && fasm_result.condition != FasmCondition.ERROR)
throw new Exception(string.Format("Fasm Error: {0}", fasm_result.condition));
byte[] buffer = new byte[fasm_result.output_lenght];
Marshal.Copy(new IntPtr(fasm_result.output_data), buffer, 0, fasm_result.output_lenght);
#if DEBUG
Console.WriteLine("ByteCode:\n{0}", string.Join(" ", buffer.Select(n => n.ToString("X2"))));
#endif
return buffer;
}
}
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <param name="address"></param>
public void Inject(IEnumerable<string> source, uint address)
{
this.Inject(string.Join("\n", source), address);
}
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <param name="address"></param>
public void Inject(string source, uint address)
{
var sb = new StringBuilder("use32")
.AppendLine();
sb.AppendFormat("org 0x{0:X8}", address)
.AppendLine();
sb.AppendLine(source);
var src = sb.ToString();
var bytes = Assemble(src);
this.WriteBytes(address, bytes);
}
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment