Skip to content

Commit

Permalink
Add logging!
Browse files Browse the repository at this point in the history
  • Loading branch information
atrexus committed Aug 14, 2024
1 parent ae96652 commit 2350e5a
Show file tree
Hide file tree
Showing 11 changed files with 90 additions and 16 deletions.
15 changes: 11 additions & 4 deletions src/Unluau.CLI/Commands/Dissasemble.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.CommandLine;
using Microsoft.Extensions.Logging;
using System.CommandLine;
using Unluau.CLI.Utils;
using Unluau.IR;
using Unluau.IR.Writers;

Expand Down Expand Up @@ -36,19 +38,24 @@ public class Disassemble : Command
return null;
});

private readonly Option<bool> _debugFlag = new(
["--debug", "-d"],
description: "Enables debug logging");

public Disassemble() : base("disassemble", "Disassembles a Luau bytecode file")
{
AddOption(_inputOption);
AddOption(_outputOption);
AddOption(_formatOption);
AddOption(_debugFlag);

this.SetHandler((inputOpt, outputOpt, formatOpt) =>
this.SetHandler((inputOpt, outputOpt, formatOpt, debugFlag) =>
{
Stream input = inputOpt ?? Console.OpenStandardInput();
Stream output = outputOpt ?? Console.OpenStandardOutput();
string format = formatOpt ?? "ir";
var result = new Lifter(input).LiftSource();
var result = new Lifter(input, Logging.CreateLoggerFactory(debugFlag)).LiftSource();
Writer writer = format switch
{
Expand All @@ -58,7 +65,7 @@ public Disassemble() : base("disassemble", "Disassembles a Luau bytecode file")
};
writer.Write(result);
}, _inputOption, _outputOption, _formatOption);
}, _inputOption, _outputOption, _formatOption, _debugFlag);
}
}
}
17 changes: 16 additions & 1 deletion src/Unluau.CLI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using System.CommandLine;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging;
using System.CommandLine;
using System.CommandLine.Parsing;
using Microsoft.Extensions.Logging.Abstractions;

namespace Unluau.CLI
{
Expand All @@ -15,4 +18,16 @@ static async Task<int> Main(string[] args)
return await rootCommand.InvokeAsync(args);
}
}

// Custom Console Formatter for UNIX Timestamp
public class UnixTimestampConsoleFormatter : ConsoleFormatter
{
public UnixTimestampConsoleFormatter() : base("unix") { }

public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter)
{
var unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
textWriter.Write($"{unixTimestamp}: {logEntry.Formatter(logEntry.State, logEntry.Exception)}{Environment.NewLine}");
}
}
}
1 change: 1 addition & 0 deletions src/Unluau.CLI/Unluau.CLI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="9.0.0-preview.7.24405.7" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
</ItemGroup>

Expand Down
26 changes: 26 additions & 0 deletions src/Unluau.CLI/Utils/Logging.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Console;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Unluau.CLI.Utils
{
public class Logging
{
public static ILoggerFactory CreateLoggerFactory(bool debug)
{
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddSimpleConsole().AddConsole();
builder.SetMinimumLevel(debug ? LogLevel.Debug : LogLevel.Information);
});

return loggerFactory;
}
}
}

Binary file removed src/Unluau.CLI/test/Control4.luau
Binary file not shown.
33 changes: 29 additions & 4 deletions src/Unluau/IR/Lifter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using Unluau.IR.ProtoTypes;
Expand All @@ -16,9 +17,10 @@ namespace Unluau.IR
/// <remarks>
/// Creates a new instance of <see cref="Lifter"/>.
/// </remarks>
/// <param name="source">The source file name.</param>
/// <param name="input">The input stream.</param>
public class Lifter(Stream input, string source = "input-file.luau", Decoder? decoder = null) : BinaryReader(input)
/// <param name="loggerFactory">The logger factory.</param>
/// <param name="source">The source file name.</param>
public class Lifter(Stream input, ILoggerFactory loggerFactory, string source = "input-file.luau", Decoder? decoder = null) : BinaryReader(input)
{
/// <summary>
/// The bit that indicates if a type is optional or not.
Expand All @@ -30,11 +32,13 @@ public class Lifter(Stream input, string source = "input-file.luau", Decoder? de
private readonly List<ProtoType> _protoTypes = [];
private readonly Decoder _decoder = decoder ?? new();

private readonly ILogger _logger = loggerFactory.CreateLogger<Lifter>();

/// <summary>
/// Creates a new instance of <see cref="Lifter"/>.
/// </summary>
/// <param name="fileInfo">The file.</param>
public Lifter(FileInfo fileInfo) : this(fileInfo.OpenRead(), fileInfo.Name)
public Lifter(FileInfo fileInfo, ILoggerFactory loggerFactory) : this(fileInfo.OpenRead(), loggerFactory, fileInfo.Name)
{
}

Expand Down Expand Up @@ -70,19 +74,29 @@ public Module LiftModule()

_version = LiftVersion();

_logger.LogDebug("lifting module with version {}", _version);

// Now we read the symbol table. We will use this globally to reference strings.
var stringCount = Read7BitEncodedInt();

_logger.LogDebug("lifting {} strings", stringCount);

for (var i = 0; i < stringCount; i++)
_symbolTable.Add(ReadString());

// Now we read all of the function prototypes in this module.
var protoTypeCount = Read7BitEncodedInt();

_logger.LogDebug("lifting {} prototypes", protoTypeCount);

for (var i = 0; i < protoTypeCount; i++)
_protoTypes.Add(LiftProtoType());

// The entry point is the index of the function prototype that is the entry point.
var entryPoint = Read7BitEncodedInt();

_logger.LogDebug("entry point is prototype #{}", entryPoint);

_protoTypes[entryPoint].IsMain = true;

return new Module
Expand Down Expand Up @@ -119,12 +133,17 @@ public ProtoType LiftProtoType()

// As of right now I see no way to use type info unless compiled natively. Therefore, we just skip it.
if (typeSize > 0)
{
_logger.LogWarning("skipping {} bytes of type information (not supported)", typeSize);
FillBuffer(typeSize);
}
}

// Now we read all of the instructions in the function prototype.
var instructionCount = Read7BitEncodedInt();

_logger.LogDebug("lifting {} instructions", instructionCount);

for (int i = 0; i < instructionCount; i++)
{
var instruction = LiftInstruction();
Expand Down Expand Up @@ -154,6 +173,8 @@ public ProtoType LiftProtoType()
// Read the line information flag. If it is set, then we read the line information.
if (ReadBoolean())
{
_logger.LogDebug("lifting line information for prototype {:x}", protoType.GetHashCode());

// Now we read the line information for each instruction.
var lineGapLog2 = ReadByte();

Expand Down Expand Up @@ -195,6 +216,8 @@ public ProtoType LiftProtoType()
// Read the debug information flag. If it is set, then we read the debug information.
if (ReadBoolean())
{
_logger.LogDebug("lifting debug information for prototype {:x}", protoType.GetHashCode());

var localVariableCount = Read7BitEncodedInt();

for (int i = 0; i < localVariableCount; i++)
Expand Down Expand Up @@ -332,6 +355,8 @@ public List<Constant> LiftConstants()
{
var constantCount = Read7BitEncodedInt();

_logger.LogDebug("lifting {} constants", constantCount);

var constants = new Constant[constantCount];

for (int i = 0; i < constantCount; i++)
Expand Down
2 changes: 1 addition & 1 deletion src/Unluau/IR/ProtoTypes/ProtoType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public override void Accept(Visitor visitor)
foreach (var constant in Constants)
constant.Accept(visitor);

ControlFlow.Accept(visitor);
ControlFlow!.Accept(visitor);
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/Unluau/IR/Versions/TypedVersion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,7 @@ public override void Accept(Visitor visitor)
{
visitor.Visit(this);
}

public override string ToString() => $"{Number}.{(int)Kind}";
}
}
2 changes: 2 additions & 0 deletions src/Unluau/IR/Versions/Version.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public override void Accept(Visitor visitor)
visitor.Visit(this);
}

public override string ToString() => $"{Number}";

/// <summary>
/// Returns whether the version is supported.
/// </summary>
Expand Down
7 changes: 1 addition & 6 deletions src/Unluau/IR/Writers/IRWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,7 @@ public class IRWriter(Stream stream) : Writer(stream)
/// <param name="module">The module.</param>
public override bool Visit(Module module)
{
var version = new StringBuilder(module.Version.Number.ToString());

if (module.Version is TypedVersion typedVersion)
version.Append($".{(byte)typedVersion.Kind}");

_writer.WriteLine($"{module.Checksum.Source}: Luau bytecode executable, version {version}, hash: 0x{module.Checksum}\n");
_writer.WriteLine($"{module.Checksum.Source}: Luau bytecode executable, version {module.Version}, hash: 0x{module.Checksum}\n");

_module = module;
return true;
Expand Down
1 change: 1 addition & 0 deletions src/Unluau/Unluau.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

<ItemGroup>
<PackageReference Include="DotNetGraph" Version="3.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0-preview.7.24405.7" />
</ItemGroup>

</Project>

0 comments on commit 2350e5a

Please sign in to comment.