├── .gitignore ├── LICENSE ├── LuaDecompiler.sln ├── LuaDecompiler ├── FileReader.cs ├── Generator.cs ├── Lua │ ├── Constant.cs │ ├── Function.cs │ ├── Instruction.cs │ └── Local.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs └── tests │ ├── out.lua │ ├── test-d.luac │ ├── test-r.luac │ └── test.lua └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | build/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studo 2015 cache/options directory 26 | .vs/ 27 | 28 | # MSTest test Results 29 | [Tt]est[Rr]esult*/ 30 | [Bb]uild[Ll]og.* 31 | 32 | # NUNIT 33 | *.VisualState.xml 34 | TestResult.xml 35 | 36 | # Build Results of an ATL Project 37 | [Dd]ebugPS/ 38 | [Rr]eleasePS/ 39 | dlldata.c 40 | 41 | *_i.c 42 | *_p.c 43 | *_i.h 44 | *.ilk 45 | *.meta 46 | *.obj 47 | *.pch 48 | *.pdb 49 | *.pgc 50 | *.pgd 51 | *.rsp 52 | *.sbr 53 | *.tlb 54 | *.tli 55 | *.tlh 56 | *.tmp 57 | *.tmp_proj 58 | *.log 59 | *.vspscc 60 | *.vssscc 61 | .builds 62 | *.pidb 63 | *.svclog 64 | *.scc 65 | 66 | # Chutzpah Test files 67 | _Chutzpah* 68 | 69 | # Visual C++ cache files 70 | ipch/ 71 | *.aps 72 | *.ncb 73 | *.opensdf 74 | *.sdf 75 | *.cachefile 76 | 77 | # Visual Studio profiler 78 | *.psess 79 | *.vsp 80 | *.vspx 81 | 82 | # TFS 2012 Local Workspace 83 | $tf/ 84 | 85 | # Guidance Automation Toolkit 86 | *.gpState 87 | 88 | # ReSharper is a .NET coding add-in 89 | _ReSharper*/ 90 | *.[Rr]e[Ss]harper 91 | *.DotSettings.user 92 | 93 | # JustCode is a .NET coding addin-in 94 | .JustCode 95 | 96 | # TeamCity is a build add-in 97 | _TeamCity* 98 | 99 | # DotCover is a Code Coverage Tool 100 | *.dotCover 101 | 102 | # NCrunch 103 | _NCrunch_* 104 | .*crunch*.local.xml 105 | 106 | # MightyMoose 107 | *.mm.* 108 | AutoTest.Net/ 109 | 110 | # Web workbench (sass) 111 | .sass-cache/ 112 | 113 | # Installshield output folder 114 | [Ee]xpress/ 115 | 116 | # DocProject is a documentation generator add-in 117 | DocProject/buildhelp/ 118 | DocProject/Help/*.HxT 119 | DocProject/Help/*.HxC 120 | DocProject/Help/*.hhc 121 | DocProject/Help/*.hhk 122 | DocProject/Help/*.hhp 123 | DocProject/Help/Html2 124 | DocProject/Help/html 125 | 126 | # Click-Once directory 127 | publish/ 128 | 129 | # Publish Web Output 130 | *.[Pp]ublish.xml 131 | *.azurePubxml 132 | # TODO: Comment the next line if you want to checkin your web deploy settings 133 | # but database connection strings (with potential passwords) will be unencrypted 134 | *.pubxml 135 | *.publishproj 136 | 137 | # NuGet Packages 138 | *.nupkg 139 | # The packages folder can be ignored because of Package Restore 140 | **/packages/* 141 | # except build/, which is used as an MSBuild target. 142 | !**/packages/build/ 143 | # Uncomment if necessary however generally it will be regenerated when needed 144 | #!**/packages/repositories.config 145 | 146 | # Windows Azure Build Output 147 | csx/ 148 | *.build.csdef 149 | 150 | # Windows Store app package directory 151 | AppPackages/ 152 | 153 | # Others 154 | *.[Cc]ache 155 | ClientBin/ 156 | [Ss]tyle[Cc]op.* 157 | ~$* 158 | *~ 159 | *.dbmdl 160 | *.dbproj.schemaview 161 | *.pfx 162 | *.publishsettings 163 | node_modules/ 164 | bower_components/ 165 | 166 | # RIA/Silverlight projects 167 | Generated_Code/ 168 | 169 | # Backup & report files from converting an old project file 170 | # to a newer Visual Studio version. Backup files are not needed, 171 | # because we have git ;-) 172 | _UpgradeReport_Files/ 173 | Backup*/ 174 | UpgradeLog*.XML 175 | UpgradeLog*.htm 176 | 177 | # SQL Server files 178 | *.mdf 179 | *.ldf 180 | 181 | # Business Intelligence projects 182 | *.rdl.data 183 | *.bim.layout 184 | *.bim_*.settings 185 | 186 | # Microsoft Fakes 187 | FakesAssemblies/ 188 | 189 | # Node.js Tools for Visual Studio 190 | .ntvs_analysis.dat 191 | 192 | # Visual Studio 6 build log 193 | *.plg 194 | 195 | # Visual Studio 6 workspace options file 196 | *.opt 197 | 198 | # more crap 199 | *.config 200 | *.csproj 201 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Alec Iverson 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /LuaDecompiler.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.23107.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LuaDecompiler", "LuaDecompiler\LuaDecompiler.csproj", "{A5983BEC-77DF-4F5E-B55A-68AF9BB90BC5}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {A5983BEC-77DF-4F5E-B55A-68AF9BB90BC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {A5983BEC-77DF-4F5E-B55A-68AF9BB90BC5}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {A5983BEC-77DF-4F5E-B55A-68AF9BB90BC5}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {A5983BEC-77DF-4F5E-B55A-68AF9BB90BC5}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /LuaDecompiler/FileReader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace LuaDecompiler 8 | { 9 | public struct FileHeader 10 | { 11 | public const int HeaderSize = 12; 12 | 13 | public const int SignatureBytes = 0x1B4C7561; 14 | public const byte Lua51Version = 0x51; 15 | 16 | public string signature; // should be ".Lua" or SignatureBytes 17 | public byte version; // 0x51 (81) for Lua 5.1 18 | public byte format; // 0 for official Lua version 19 | public bool isLittleEndian; 20 | public byte intSize; // in bytes. default 4 21 | public byte size_tSize; // in bytes. default 4 22 | public byte instructionSize; // in bytes. default 4 23 | public byte lua_NumberSize; // in bytes. default 8 24 | public bool isIntegral; // true = integral number type, false = floating point 25 | 26 | // default header bytes on x86: 27 | // 1B4C7561 51000104 04040800 28 | 29 | public override string ToString() 30 | { 31 | StringBuilder sb = new StringBuilder(); 32 | 33 | sb.AppendFormat("signature: {0}\n", signature); 34 | sb.AppendFormat("version: {0}\n", version); 35 | sb.AppendFormat("format: {0}\n", format); 36 | sb.AppendFormat("isLittleEndian: {0}\n", isLittleEndian); 37 | sb.AppendFormat("intSize: {0}\n", intSize); 38 | sb.AppendFormat("size_tSize: {0}\n", size_tSize); 39 | sb.AppendFormat("instructionSize: {0}\n", instructionSize); 40 | sb.AppendFormat("lua_NumberSize: {0}\n", lua_NumberSize); 41 | sb.AppendFormat("isIntegral: {0}\n", isIntegral); 42 | 43 | return sb.ToString(); 44 | } 45 | } 46 | 47 | public class FileReader : IDisposable 48 | { 49 | private FileStream fileStream; 50 | private BinaryReader reader; 51 | 52 | private FileHeader header; 53 | 54 | public FileHeader Header 55 | { 56 | get { return header; } 57 | } 58 | 59 | public FileReader(string file) 60 | { 61 | try 62 | { 63 | fileStream = new FileStream(file, FileMode.Open); 64 | reader = new BinaryReader(fileStream, Encoding.ASCII); 65 | } 66 | catch(FileNotFoundException fnfe) 67 | { 68 | Console.WriteLine("File " + file + " does not exist: " + fnfe); 69 | return; 70 | } 71 | 72 | ReadHeader(); 73 | } 74 | 75 | public Lua.Function NextFunctionBlock() 76 | { 77 | long bytesLeft = fileStream.Length - 1 - fileStream.Position; 78 | 79 | if(bytesLeft == 0) 80 | return null; 81 | 82 | Lua.Function data = new Lua.Function(); 83 | 84 | data.sourceName = ReadString(); 85 | data.lineNumber = ReadInteger(header.intSize); 86 | data.lastLineNumber = ReadInteger(header.intSize); 87 | data.numUpvalues = reader.ReadByte(); 88 | data.numParameters = reader.ReadByte(); 89 | data.varArgFlag = (Lua.Function.VarArg)reader.ReadByte(); 90 | data.maxStackSize = reader.ReadByte(); 91 | 92 | data.instructions = ReadInstructions(); 93 | data.constants = ReadConstants(); 94 | data.functions = ReadFunctions(); 95 | data.sourceLinePositions = ReadLineNumbers(); 96 | data.locals = ReadLocals(); 97 | data.upvalues = ReadUpvalues(); 98 | 99 | return data; 100 | } 101 | 102 | public void Dispose() 103 | { 104 | reader.Dispose(); 105 | fileStream.Dispose(); 106 | } 107 | 108 | private void ReadHeader() 109 | { 110 | header = new FileHeader(); 111 | 112 | List bytes = reader.ReadBytes(12).ToList(); 113 | 114 | char[] sig = { (char)bytes[0], (char)bytes[1], (char)bytes[2], (char)bytes[3] }; 115 | 116 | header.signature = new string(sig); 117 | 118 | if(header.signature != (char)27 + "Lua") 119 | throw new InvalidDataException("File does not appear to be a Lua bytecode file."); 120 | 121 | header.version = bytes[4]; 122 | 123 | if(header.version != FileHeader.Lua51Version) 124 | throw new NotImplementedException("Only Lua 5.1 is supported."); 125 | 126 | header.format = bytes[5]; 127 | header.isLittleEndian = bytes[6] != 0; 128 | header.intSize = bytes[7]; 129 | header.size_tSize = bytes[8]; 130 | header.instructionSize = bytes[9]; 131 | header.lua_NumberSize = bytes[10]; 132 | header.isIntegral = bytes[11] != 0; 133 | } 134 | 135 | private List ReadInstructions() 136 | { 137 | int numInstrs = ReadInteger(header.intSize); 138 | 139 | List instrs = new List(numInstrs); 140 | 141 | for(int i = 0; i < numInstrs; ++i) 142 | { 143 | instrs.Add(new Lua.Instruction(ReadInteger(header.instructionSize))); 144 | } 145 | 146 | return instrs; 147 | } 148 | 149 | private List ReadConstants() 150 | { 151 | int numConsts = ReadInteger(header.intSize); 152 | 153 | List consts = new List(numConsts); 154 | 155 | for(int i = 0; i < numConsts; ++i) 156 | { 157 | byte type = reader.ReadByte(); 158 | 159 | switch((Lua.LuaType)type) 160 | { 161 | case Lua.LuaType.Nil: 162 | consts.Add(new Lua.NilConstant()); 163 | break; 164 | case Lua.LuaType.Bool: 165 | consts.Add(new Lua.BoolConstant(reader.ReadBoolean())); 166 | break; 167 | case Lua.LuaType.Number: 168 | consts.Add(new Lua.NumberConstant(ReadNumber(header.lua_NumberSize))); 169 | break; 170 | case Lua.LuaType.String: 171 | consts.Add(new Lua.StringConstant(ReadString())); 172 | break; 173 | } 174 | } 175 | 176 | return consts; 177 | } 178 | 179 | private List ReadFunctions() 180 | { 181 | int numFuncs = ReadInteger(header.intSize); 182 | 183 | List funcs = new List(numFuncs); 184 | 185 | for(int i = 0; i < numFuncs; ++i) 186 | { 187 | funcs.Add(NextFunctionBlock()); 188 | } 189 | 190 | return funcs; 191 | } 192 | 193 | private List ReadLineNumbers() 194 | { 195 | int numLinePos = ReadInteger(header.intSize); 196 | 197 | List linePos = new List(numLinePos); 198 | 199 | for(int i = 0; i < numLinePos; ++i) 200 | { 201 | // subtract 1 to index from 0, not 1 202 | linePos.Add(ReadInteger(header.intSize) - 1); 203 | } 204 | 205 | return linePos; 206 | } 207 | 208 | private List ReadLocals() 209 | { 210 | int numLocals = ReadInteger(header.intSize); 211 | 212 | List locals = new List((int)numLocals); 213 | 214 | for(int i = 0; i < numLocals; ++i) 215 | { 216 | locals.Add(new Lua.Local(ReadString(), ReadInteger(header.intSize), ReadInteger(header.intSize))); 217 | } 218 | 219 | return locals; 220 | } 221 | 222 | private List ReadUpvalues() 223 | { 224 | int numUpvalues = ReadInteger(header.intSize); 225 | 226 | List upvalues = new List((int)numUpvalues); 227 | 228 | for(int i = 0; i < numUpvalues; ++i) 229 | { 230 | upvalues.Add(ReadString()); 231 | } 232 | 233 | return upvalues; 234 | } 235 | 236 | private string ReadString() 237 | { 238 | int stringSize = ReadInteger(header.size_tSize); 239 | 240 | byte[] bytes = reader.ReadBytes((int)stringSize); 241 | 242 | char[] chars = new char[bytes.Length]; 243 | 244 | for(int i = 0; i < bytes.Length; ++i) 245 | { 246 | chars[i] = (char)bytes[i]; 247 | } 248 | 249 | return new string(chars); 250 | } 251 | 252 | private int ReadInteger(byte intSize) 253 | { 254 | byte[] bytes = reader.ReadBytes(intSize); 255 | int ret = 0; 256 | 257 | if(header.isLittleEndian) 258 | { 259 | for(int i = 0; i < intSize; ++i) 260 | { 261 | ret += bytes[i] << i * 8; 262 | } 263 | } 264 | else 265 | { 266 | for(int i = 0; i < intSize; ++i) 267 | { 268 | ret += bytes[i] >> i * 8; 269 | } 270 | } 271 | 272 | return ret; 273 | } 274 | 275 | private double ReadNumber(byte numSize) 276 | { 277 | byte[] bytes = reader.ReadBytes(numSize); 278 | double ret = 0; 279 | 280 | if(numSize == 8) 281 | { 282 | ret = BitConverter.ToDouble(bytes, 0); 283 | } 284 | else if(numSize == 4) 285 | { 286 | ret = BitConverter.ToSingle(bytes, 0); 287 | } 288 | else 289 | { 290 | throw new NotImplementedException("Uhm..."); 291 | } 292 | 293 | return ret; 294 | } 295 | } 296 | } 297 | -------------------------------------------------------------------------------- /LuaDecompiler/Generator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Text; 4 | 5 | namespace LuaDecompiler 6 | { 7 | public class Generator : IDisposable 8 | { 9 | private FileStream fileStream; 10 | private StreamWriter writer; 11 | 12 | private uint functionCount; 13 | 14 | public Generator(string path) 15 | { 16 | fileStream = new FileStream(path, FileMode.Create); 17 | writer = new StreamWriter(fileStream, Encoding.ASCII); 18 | writer.NewLine = "\n"; 19 | writer.AutoFlush = true; 20 | 21 | functionCount = 0; 22 | } 23 | 24 | public void Write(Lua.Function function, int indentLevel = 0) 25 | { 26 | // top level function 27 | if(function.lineNumber == 0 && function.lastLineNumber == 0) 28 | { 29 | // WriteConstants(function); 30 | 31 | WriteChildFunctions(function); 32 | 33 | WriteInstructions(function); 34 | } 35 | else 36 | { 37 | string indents = new string('\t', indentLevel); 38 | 39 | string functionHeader = indents + "function func" + functionCount + "("; 40 | 41 | for(int i = 0; i < function.numParameters; ++i) 42 | { 43 | functionHeader += "arg" + i + (i + 1 != function.numParameters ? ", " : ")"); 44 | } 45 | 46 | writer.Write(functionHeader); 47 | ++functionCount; 48 | 49 | // WriteConstants(function, indentLevel + 1); 50 | 51 | WriteChildFunctions(function, indentLevel + 1); 52 | 53 | WriteInstructions(function, indentLevel + 1); 54 | } 55 | } 56 | 57 | public void Dispose() 58 | { 59 | writer.Dispose(); 60 | fileStream.Dispose(); 61 | } 62 | 63 | private void WriteConstants(Lua.Function function, int indentLevel = 0) 64 | { 65 | uint constCount = 0; 66 | 67 | string indents = new string('\t', indentLevel); 68 | 69 | foreach(var c in function.constants) 70 | { 71 | writer.WriteLine("{2}const{0} = {1}", constCount, c.ToString(), indents); 72 | ++constCount; 73 | } 74 | } 75 | 76 | private void WriteChildFunctions(Lua.Function function, int indentLevel = 0) 77 | { 78 | foreach(var f in function.functions) 79 | { 80 | Write(f, indentLevel + 1); 81 | } 82 | } 83 | 84 | private void WriteInstructions(Lua.Function function, int indentLevel = 0) 85 | { 86 | string indents = new string('\t', indentLevel); 87 | 88 | foreach(var i in function.instructions) 89 | { 90 | switch(i.OpCode) 91 | { 92 | case Lua.Instruction.Op.Move: 93 | writer.WriteLine("{2}var{0} = var{1}", i.A, i.B, indents); 94 | break; 95 | 96 | case Lua.Instruction.Op.LoadK: 97 | writer.WriteLine("{2}var{0} = {1}", i.A, GetConstant(i.Bx, function), indents); 98 | break; 99 | 100 | case Lua.Instruction.Op.LoadBool: 101 | writer.WriteLine("{2}var{0} = {1}", i.A, (i.B != 0 ? "true" : "false"), indents); 102 | break; 103 | 104 | case Lua.Instruction.Op.LoadNil: 105 | for(int x = i.A; x < i.B + 1; ++x) 106 | writer.WriteLine("{1}var{0} = nil", x, indents); 107 | break; 108 | 109 | case Lua.Instruction.Op.GetUpVal: 110 | writer.WriteLine("{2}var{0} = upvalue[{1}]", i.A, i.B, indents); 111 | break; 112 | 113 | case Lua.Instruction.Op.GetGlobal: 114 | writer.WriteLine("{2}var{0} = _G[{1}]", i.A, GetConstant(i.Bx, function), indents); 115 | break; 116 | 117 | case Lua.Instruction.Op.GetTable: 118 | writer.WriteLine("{3}var{0} = var{1}[{2}]", i.A, i.B, WriteIndex(i.C, function), indents); 119 | break; 120 | 121 | case Lua.Instruction.Op.SetGlobal: 122 | writer.WriteLine("{2}_G[{0}] = var{1}", GetConstant(i.Bx, function), i.A, indents); 123 | break; 124 | 125 | case Lua.Instruction.Op.SetUpVal: 126 | writer.WriteLine("{2}upvalue[{0}] = var{1}", i.B, i.A, indents); 127 | break; 128 | 129 | case Lua.Instruction.Op.SetTable: 130 | writer.WriteLine("{3}var{0}[{1}] = {2}", i.A, WriteIndex(i.B, function), WriteIndex(i.C, function), indents); 131 | break; 132 | 133 | case Lua.Instruction.Op.NewTable: 134 | writer.WriteLine("{1}var{0} = {{}}", i.A, indents); 135 | break; 136 | 137 | case Lua.Instruction.Op.Self: 138 | writer.WriteLine("{2}var{0} = var{1}", i.A + 1, i.B, indents); 139 | writer.WriteLine("{3}var{0} = var{1}[{2}]", i.A, i.B, WriteIndex(i.C, function), indents); 140 | break; 141 | 142 | case Lua.Instruction.Op.Add: 143 | writer.WriteLine("{3}var{0} = var{1} + var{2}", i.A, i.B, i.C, indents); 144 | break; 145 | 146 | case Lua.Instruction.Op.Sub: 147 | writer.WriteLine("{3}var{0} = var{1} - var{2}", i.A, i.B, i.C, indents); 148 | break; 149 | 150 | case Lua.Instruction.Op.Mul: 151 | writer.WriteLine("{3}var{0} = var{1} * var{2}", i.A, i.B, i.C, indents); 152 | break; 153 | 154 | case Lua.Instruction.Op.Div: 155 | writer.WriteLine("{3}var{0} = var{1} / var{2}", i.A, i.B, i.C, indents); 156 | break; 157 | 158 | case Lua.Instruction.Op.Mod: 159 | writer.WriteLine("{3}var{0} = var{1} % var{2}", i.A, i.B, i.C, indents); 160 | break; 161 | 162 | case Lua.Instruction.Op.Pow: 163 | writer.WriteLine("{3}var{0} = var{1} ^ var{2}", i.A, i.B, i.C, indents); 164 | break; 165 | 166 | case Lua.Instruction.Op.Unm: 167 | writer.WriteLine("{2}var{0} = -var{1}", i.A, i.B, indents); 168 | break; 169 | 170 | case Lua.Instruction.Op.Not: 171 | writer.WriteLine("{2}var{0} = not var{1}", i.A, i.B, indents); 172 | break; 173 | 174 | case Lua.Instruction.Op.Len: 175 | writer.WriteLine("{2}var{0} = #var{1}", i.A, i.B, indents); 176 | break; 177 | 178 | case Lua.Instruction.Op.Concat: 179 | writer.Write("{1}var{0} = ", i.A, indents); 180 | 181 | for(int x = i.B; x < i.C; ++x) 182 | writer.Write("var{0} .. ", x); 183 | 184 | writer.WriteLine("var{0}", i.C); 185 | break; 186 | 187 | case Lua.Instruction.Op.Jmp: 188 | throw new NotImplementedException("Jmp"); 189 | 190 | case Lua.Instruction.Op.Eq: 191 | writer.WriteLine("{3}if ({0} == {1}) ~= {2} then", WriteIndex(i.B, function), WriteIndex(i.C, function), i.A, indents); 192 | break; 193 | 194 | case Lua.Instruction.Op.Lt: 195 | writer.WriteLine("{3}if ({0} < {1}) ~= {2} then", WriteIndex(i.B, function), WriteIndex(i.C, function), i.A, indents); 196 | break; 197 | 198 | case Lua.Instruction.Op.Le: 199 | writer.WriteLine("{3}if ({0} <= {1}) ~= {2} then", WriteIndex(i.B, function), WriteIndex(i.C, function), i.A, indents); 200 | break; 201 | 202 | case Lua.Instruction.Op.Test: 203 | writer.WriteLine("{2}if not var{0} <=> {1} then", i.A, i.C, indents); 204 | break; 205 | 206 | case Lua.Instruction.Op.TestSet: 207 | writer.WriteLine("{2}if var{0} <=> {1} then", i.B, i.C, indents); 208 | writer.WriteLine("{2}\tvar{0} = var{1}", i.A, i.B, indents); 209 | writer.WriteLine("end"); 210 | break; 211 | 212 | case Lua.Instruction.Op.Call: 213 | StringBuilder sb = new StringBuilder(); 214 | 215 | if(i.C != 0) 216 | { 217 | sb.Append(indents); 218 | var indentLen = sb.Length; 219 | 220 | // return values 221 | for(int x = i.A; x < i.A + i.C - 2; ++x) 222 | sb.AppendFormat("var{0}, ", x); 223 | 224 | if(sb.Length - indentLen > 2) 225 | { 226 | sb.Remove(sb.Length - 2, 2); 227 | sb.Append(" = "); 228 | } 229 | } 230 | else 231 | { 232 | throw new NotImplementedException("i.C == 0"); 233 | } 234 | 235 | // function 236 | sb.AppendFormat("var{0}(", i.A); 237 | 238 | if(i.B != 0) 239 | { 240 | var preArgsLen = sb.Length; 241 | 242 | // arguments 243 | for(int x = i.A; x < i.A + i.B - 1; ++x) 244 | sb.AppendFormat("var{0}, ", x + 1); 245 | 246 | if(sb.Length - preArgsLen > 2) 247 | sb.Remove(sb.Length - 2, 2); 248 | 249 | sb.Append(')'); 250 | } 251 | else 252 | { 253 | throw new NotImplementedException("i.B == 0"); 254 | } 255 | 256 | writer.WriteLine(sb.ToString()); 257 | 258 | break; 259 | 260 | case Lua.Instruction.Op.TailCall: 261 | throw new NotImplementedException("TailCall"); 262 | 263 | case Lua.Instruction.Op.Return: 264 | writer.WriteLine("return"); 265 | break; 266 | 267 | case Lua.Instruction.Op.ForLoop: 268 | throw new NotImplementedException("ForLoop"); 269 | 270 | case Lua.Instruction.Op.ForPrep: 271 | throw new NotImplementedException("ForPrep"); 272 | 273 | case Lua.Instruction.Op.TForLoop: 274 | throw new NotImplementedException("TForLoop"); 275 | 276 | case Lua.Instruction.Op.SetList: 277 | throw new NotImplementedException("SetList"); 278 | 279 | case Lua.Instruction.Op.Close: 280 | throw new NotImplementedException("Close"); 281 | 282 | case Lua.Instruction.Op.Closure: 283 | throw new NotImplementedException("Closure"); 284 | 285 | case Lua.Instruction.Op.VarArg: 286 | throw new NotImplementedException("VarArg"); 287 | } 288 | } 289 | } 290 | 291 | private string GetConstant(int idx, Lua.Function function) 292 | { 293 | return function.constants[idx].ToString(); 294 | } 295 | 296 | private int ToIndex(int value, out bool isConstant) 297 | { 298 | // this is the logic from lua's source code (lopcodes.h) 299 | if(isConstant = (value & 1 << 8) != 0) 300 | return value & ~(1 << 8); 301 | else 302 | return value; 303 | } 304 | 305 | private string WriteIndex(int value, Lua.Function function) 306 | { 307 | bool constant; 308 | int idx = ToIndex(value, out constant); 309 | 310 | if(constant) 311 | return function.constants[idx].ToString(); 312 | else 313 | return "var" + idx; 314 | } 315 | } 316 | } 317 | -------------------------------------------------------------------------------- /LuaDecompiler/Lua/Constant.cs: -------------------------------------------------------------------------------- 1 | // Representation of a constant in Lua 2 | 3 | namespace LuaDecompiler.Lua 4 | { 5 | public enum LuaType 6 | { 7 | Nil = 0, 8 | Bool = 1, 9 | Number = 3, 10 | String = 4, 11 | } 12 | 13 | public abstract class Constant 14 | { 15 | public LuaType Type 16 | { 17 | get; 18 | protected set; 19 | } 20 | 21 | public override abstract string ToString(); 22 | } 23 | 24 | public class Constant : Constant 25 | { 26 | public T Value 27 | { 28 | get; 29 | private set; 30 | } 31 | 32 | protected Constant(LuaType type, T value) 33 | { 34 | Type = type; 35 | Value = value; 36 | } 37 | 38 | public override string ToString() 39 | { 40 | return Value.ToString(); 41 | } 42 | } 43 | 44 | public class NilConstant : Constant 45 | { 46 | public NilConstant() : base(LuaType.Nil, null) 47 | { } 48 | 49 | public override string ToString() 50 | { 51 | return "nil"; 52 | } 53 | } 54 | 55 | public class BoolConstant : Constant 56 | { 57 | public BoolConstant(bool value) : base(LuaType.Bool, value) 58 | { } 59 | 60 | public override string ToString() 61 | { 62 | return Value ? "true" : "false"; 63 | } 64 | } 65 | 66 | public class NumberConstant : Constant 67 | { 68 | public NumberConstant(double value) : base(LuaType.Number, value) 69 | { } 70 | } 71 | 72 | public class StringConstant : Constant 73 | { 74 | public StringConstant(string value) : base(LuaType.String, value) 75 | { } 76 | 77 | public override string ToString() 78 | { 79 | // substring to avoid printing out NULL character 80 | return '\"' + Value.Substring(0, Value.Length - 1) + '\"'; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /LuaDecompiler/Lua/Function.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace LuaDecompiler.Lua 4 | { 5 | public class Function 6 | { 7 | public enum VarArg 8 | { 9 | Has = 1, 10 | Is = 2, 11 | Needs = 4, 12 | } 13 | 14 | public string sourceName; 15 | public int lineNumber; 16 | public int lastLineNumber; 17 | public byte numUpvalues; 18 | public byte numParameters; 19 | public VarArg varArgFlag; 20 | public byte maxStackSize; 21 | 22 | public List instructions; 23 | public List constants; 24 | public List functions; 25 | 26 | // Debug data 27 | public List sourceLinePositions; 28 | public List locals; 29 | public List upvalues; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LuaDecompiler/Lua/Instruction.cs: -------------------------------------------------------------------------------- 1 | // Representation of a Lua VM Instruction 2 | 3 | namespace LuaDecompiler.Lua 4 | { 5 | public class Instruction 6 | { 7 | public enum Op 8 | { 9 | Move, // copy value between registers 10 | LoadK, // Load constant to register 11 | LoadBool, // load bool to register 12 | LoadNil, // load nil values into a range of registers 13 | GetUpVal, // read upvalue into register 14 | GetGlobal, // read global into register 15 | GetTable, // read table element into register 16 | SetGlobal, // write register value to a global variable 17 | SetUpVal, // write register value to an upvalue 18 | SetTable, // write register value into table element 19 | NewTable, // create a new table 20 | Self, // prepare object for method call 21 | Add, // addition 22 | Sub, // subtraction 23 | Mul, // multiplication 24 | Div, // division 25 | Mod, // modulus 26 | Pow, // exponentiation 27 | Unm, // unary minus 28 | Not, // logical not 29 | Len, // length operator 30 | Concat, // concatenate a range of registers 31 | Jmp, // unconditional jump 32 | Eq, // equality test 33 | Lt, // less than test 34 | Le, // less than or equal test 35 | Test, // boolean test with conditional jump 36 | TestSet, // boolean test with conditional jump and assignment 37 | Call, // call a closure 38 | TailCall, // perform a tail call 39 | Return, // return from function call 40 | ForLoop, // iterate a numeric for loop 41 | ForPrep, // initialization for a numeric for loop 42 | TForLoop, // iterate a generic for loop 43 | SetList, // set a range of array elements for a table 44 | Close, // close a range of locals being used as upvalues 45 | Closure, // create a closure of a function 46 | VarArg, // assign vararg function args to registers 47 | } 48 | 49 | private const int HalfMax18Bit = 2 << 17; // == 2^18 / 2 == 131071 50 | 51 | public int Data 52 | { 53 | get; 54 | private set; 55 | } 56 | 57 | public Op OpCode 58 | { 59 | get; 60 | private set; 61 | } 62 | 63 | public int A 64 | { 65 | get; 66 | private set; 67 | } 68 | 69 | public int B 70 | { 71 | get; 72 | private set; 73 | } 74 | 75 | public int C 76 | { 77 | get; 78 | private set; 79 | } 80 | 81 | public int Bx 82 | { 83 | get { return ((B << 9) & 0xFFE00 | C) & 0x3FFFF; } 84 | } 85 | 86 | public int sBx 87 | { 88 | get { return Bx - HalfMax18Bit; } 89 | } 90 | 91 | public bool HasBx 92 | { 93 | get; 94 | private set; 95 | } 96 | 97 | public bool Signed 98 | { 99 | get; 100 | private set; 101 | } 102 | 103 | public Instruction(int data) 104 | { 105 | Data = data; 106 | 107 | OpCode = (Op)(data & 0x3F); 108 | A = (data >> 6) & 0xFF; 109 | B = (data >> 23) & 0x1FF; 110 | C = (data >> 14) & 0x1FF; 111 | 112 | switch(OpCode) 113 | { 114 | case Op.Jmp: 115 | case Op.ForLoop: 116 | case Op.ForPrep: 117 | Signed = true; 118 | goto case Op.LoadK; 119 | 120 | case Op.LoadK: 121 | case Op.GetGlobal: 122 | case Op.SetGlobal: 123 | case Op.Closure: 124 | HasBx = true; 125 | break; 126 | 127 | default: 128 | HasBx = false; 129 | Signed = false; 130 | break; 131 | } 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /LuaDecompiler/Lua/Local.cs: -------------------------------------------------------------------------------- 1 | // Representation of a Lua local variable 2 | 3 | namespace LuaDecompiler.Lua 4 | { 5 | public class Local 6 | { 7 | public string Name 8 | { 9 | get; 10 | private set; 11 | } 12 | 13 | public int ScopeStart 14 | { 15 | get; 16 | private set; 17 | } 18 | 19 | public int ScopeEnd 20 | { 21 | get; 22 | private set; 23 | } 24 | 25 | public Local(string name, int scopeStart, int scopeEnd) 26 | { 27 | Name = name; 28 | ScopeStart = scopeStart; 29 | ScopeEnd = scopeEnd; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LuaDecompiler/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace LuaDecompiler 4 | { 5 | class Program 6 | { 7 | public static void Main(string[] args) 8 | { 9 | if(args.Length < 2) 10 | { 11 | Console.WriteLine("Must be 2 arguments (input file, output file)."); 12 | return; 13 | } 14 | 15 | string inputFile = args[0]; 16 | string outputFile = args[1]; 17 | 18 | FileHeader header; 19 | Lua.Function function = null; 20 | 21 | try 22 | { 23 | using(FileReader reader = new FileReader(inputFile)) 24 | { 25 | header = reader.Header; 26 | function = reader.NextFunctionBlock(); 27 | } 28 | 29 | Console.WriteLine(header); 30 | 31 | using(Generator gen = new Generator(outputFile)) 32 | { 33 | gen.Write(function); 34 | } 35 | 36 | Console.WriteLine("\nDone!"); 37 | } 38 | catch(Exception ex) 39 | { 40 | Console.WriteLine("\nError: {0}", ex); 41 | } 42 | 43 | Console.WriteLine("Press Enter to continue."); 44 | Console.ReadLine(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /LuaDecompiler/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("LuaDecompiler")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("LuaDecompiler")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("a5983bec-77df-4f5e-b55a-68af9bb90bc5")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /LuaDecompiler/tests/out.lua: -------------------------------------------------------------------------------- 1 | var0 = _G["io"] 2 | var0 = var0["write"] 3 | var1 = "Hello, World!" 4 | var0(var1) 5 | if (5 == 5) ~= 0 then 6 | -------------------------------------------------------------------------------- /LuaDecompiler/tests/test-d.luac: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabbertorres/LuaDecompiler/373b9c56d4ed81a0e0c245f133d7c96006b43b56/LuaDecompiler/tests/test-d.luac -------------------------------------------------------------------------------- /LuaDecompiler/tests/test-r.luac: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dabbertorres/LuaDecompiler/373b9c56d4ed81a0e0c245f133d7c96006b43b56/LuaDecompiler/tests/test-r.luac -------------------------------------------------------------------------------- /LuaDecompiler/tests/test.lua: -------------------------------------------------------------------------------- 1 | io.write("Hello, World!") 2 | 3 | if 5 == 5 then 4 | io.write("true") 5 | else 6 | io.write("false") 7 | end 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LuaDecompiler 2 | A decompiler for Lua bytecode compiled with luac. Currently targeted at Lua 5.1. 3 | --------------------------------------------------------------------------------