DebugLibrary.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. using Lua.CodeAnalysis;
  2. using System.Runtime.CompilerServices;
  3. using Lua.Runtime;
  4. using Lua.Internal;
  5. namespace Lua.Standard;
  6. public class DebugLibrary
  7. {
  8. public static readonly DebugLibrary Instance = new();
  9. public DebugLibrary()
  10. {
  11. var libraryName = "debug";
  12. Functions =
  13. [
  14. new(libraryName, "getlocal", GetLocal),
  15. new(libraryName, "setlocal", SetLocal),
  16. new(libraryName, "getupvalue", GetUpValue),
  17. new(libraryName, "setupvalue", SetUpValue),
  18. new(libraryName, "getmetatable", GetMetatable),
  19. new(libraryName, "setmetatable", SetMetatable),
  20. new(libraryName, "getuservalue", GetUserValue),
  21. new(libraryName, "setuservalue", SetUserValue),
  22. new(libraryName, "traceback", Traceback),
  23. new(libraryName, "getregistry", GetRegistry),
  24. new(libraryName, "upvalueid", UpValueId),
  25. new(libraryName, "upvaluejoin", UpValueJoin),
  26. new(libraryName, "gethook", GetHook),
  27. new(libraryName, "sethook", SetHook),
  28. new(libraryName, "getinfo", GetInfo)
  29. ];
  30. }
  31. public readonly LibraryFunction[] Functions;
  32. static LuaState GetLuaThread(in LuaFunctionExecutionContext context, out int argOffset)
  33. {
  34. if (context.ArgumentCount < 1)
  35. {
  36. argOffset = 0;
  37. return context.State;
  38. }
  39. if (context.GetArgument(0).TryRead<LuaState>(out var state))
  40. {
  41. argOffset = 1;
  42. return state;
  43. }
  44. argOffset = 0;
  45. return context.State;
  46. }
  47. static ref LuaValue FindLocal(LuaState state, int level, int index, out string? name)
  48. {
  49. if (index == 0)
  50. {
  51. name = null;
  52. return ref Unsafe.NullRef<LuaValue>();
  53. }
  54. var callStack = state.GetCallStackFrames();
  55. var frame = callStack[^(level + 1)];
  56. if (index < 0)
  57. {
  58. index = -index - 1;
  59. var frameVariableArgumentCount = frame.VariableArgumentCount;
  60. if (frameVariableArgumentCount > 0 && index < frameVariableArgumentCount)
  61. {
  62. name = "(*vararg)";
  63. return ref state.Stack.Get(frame.Base - frameVariableArgumentCount + index);
  64. }
  65. name = null;
  66. return ref Unsafe.NullRef<LuaValue>();
  67. }
  68. index -= 1;
  69. var frameBase = frame.Base;
  70. if (frame.Function is LuaClosure closure)
  71. {
  72. var locals = closure.Proto.LocalVariables;
  73. var nextFrame = callStack[^level];
  74. var currentPc = nextFrame.CallerInstructionIndex;
  75. {
  76. var nextFrameBase = closure.Proto.Code[currentPc].OpCode is OpCode.Call or OpCode.TailCall ? nextFrame.Base - 1 : nextFrame.Base;
  77. if (nextFrameBase - 1 < frameBase + index)
  78. {
  79. name = null;
  80. return ref Unsafe.NullRef<LuaValue>();
  81. }
  82. }
  83. var localId = index + 1;
  84. foreach (var l in locals)
  85. {
  86. if (currentPc < l.StartPc)
  87. {
  88. break;
  89. }
  90. if (l.EndPc <= currentPc)
  91. {
  92. continue;
  93. }
  94. localId--;
  95. if (localId == 0)
  96. {
  97. name = l.Name;
  98. return ref state.Stack.Get(frameBase + index);
  99. }
  100. }
  101. }
  102. else
  103. {
  104. var nextFrameBase = level != 0 ? callStack[^level].Base : state.Stack.Count;
  105. if (nextFrameBase - 1 < frameBase + index)
  106. {
  107. name = null;
  108. return ref Unsafe.NullRef<LuaValue>();
  109. }
  110. }
  111. name = "(*temporary)";
  112. return ref state.Stack.Get(frameBase + index);
  113. }
  114. public ValueTask<int> GetLocal(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  115. {
  116. static LuaValue GetParam(LuaFunction function, int index)
  117. {
  118. if (function is LuaClosure closure)
  119. {
  120. var paramCount = closure.Proto.ParameterCount;
  121. if (0 <= index && index < paramCount)
  122. {
  123. return closure.Proto.LocalVariables[index].Name;
  124. }
  125. }
  126. return LuaValue.Nil;
  127. }
  128. var state = GetLuaThread(context, out var argOffset);
  129. var index = context.GetArgument<int>(argOffset + 1);
  130. if (context.GetArgument(argOffset).TryReadFunction(out var f))
  131. {
  132. return new(context.Return(GetParam(f, index - 1)));
  133. }
  134. var level = context.GetArgument<int>(argOffset);
  135. if (level < 0 || level >= state.GetCallStackFrames().Length)
  136. {
  137. context.ThrowBadArgument(1, "level out of range");
  138. }
  139. ref var local = ref FindLocal(state, level, index, out var name);
  140. if (name is null)
  141. {
  142. return new(context.Return(LuaValue.Nil));
  143. }
  144. return new(context.Return(name, local));
  145. }
  146. public ValueTask<int> SetLocal(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  147. {
  148. var state = GetLuaThread(context, out var argOffset);
  149. var value = context.GetArgument(argOffset + 2);
  150. var index = context.GetArgument<int>(argOffset + 1);
  151. var level = context.GetArgument<int>(argOffset);
  152. if (level < 0 || level >= state.GetCallStackFrames().Length)
  153. {
  154. context.ThrowBadArgument(1, "level out of range");
  155. }
  156. ref var local = ref FindLocal(state, level, index, out var name);
  157. if (name is null)
  158. {
  159. return new(context.Return(LuaValue.Nil));
  160. }
  161. local = value;
  162. return new(context.Return(name));
  163. }
  164. public ValueTask<int> GetUpValue(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  165. {
  166. var func = context.GetArgument<LuaFunction>(0);
  167. var index = context.GetArgument<int>(1) - 1;
  168. if (func is not LuaClosure closure)
  169. {
  170. if (func is CSharpClosure csClosure)
  171. {
  172. var upValues = csClosure.UpValues;
  173. if (index < 0 || index >= upValues.Length)
  174. {
  175. return new(context.Return());
  176. }
  177. return new(context.Return("", upValues[index]));
  178. }
  179. return new(context.Return());
  180. }
  181. {
  182. var upValues = closure.UpValues;
  183. var descriptions = closure.Proto.UpValues;
  184. if (index < 0 || index >= descriptions.Length)
  185. {
  186. return new(context.Return());
  187. }
  188. var description = descriptions[index];
  189. return new(context.Return(description.Name.ToString(), upValues[index].GetValue()));
  190. }
  191. }
  192. public ValueTask<int> SetUpValue(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  193. {
  194. var func = context.GetArgument<LuaFunction>(0);
  195. var index = context.GetArgument<int>(1) - 1;
  196. var value = context.GetArgument(2);
  197. if (func is not LuaClosure closure)
  198. {
  199. if (func is CSharpClosure csClosure)
  200. {
  201. var upValues = csClosure.UpValues;
  202. if (index >= 0 && index < upValues.Length)
  203. {
  204. upValues[index] = value;
  205. return new(context.Return(""));
  206. }
  207. }
  208. return new(context.Return());
  209. }
  210. {
  211. var upValues = closure.UpValues;
  212. var descriptions = closure.Proto.UpValues;
  213. if (index < 0 || index >= descriptions.Length)
  214. {
  215. return new(context.Return());
  216. }
  217. var description = descriptions[index];
  218. upValues[index].SetValue(value);
  219. return new(context.Return(description.Name.ToString()));
  220. }
  221. }
  222. public ValueTask<int> GetMetatable(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  223. {
  224. var arg0 = context.GetArgument(0);
  225. if (context.GlobalState.TryGetMetatable(arg0, out var table))
  226. {
  227. return new(context.Return(table));
  228. }
  229. else
  230. {
  231. return new(context.Return(LuaValue.Nil));
  232. }
  233. }
  234. public ValueTask<int> SetMetatable(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  235. {
  236. var arg0 = context.GetArgument(0);
  237. var arg1 = context.GetArgument(1);
  238. if (arg1.Type is not (LuaValueType.Nil or LuaValueType.Table))
  239. {
  240. LuaRuntimeException.BadArgument(context.State, 2, [LuaValueType.Nil, LuaValueType.Table], arg1.Type);
  241. }
  242. context.GlobalState.SetMetatable(arg0, arg1.UnsafeRead<LuaTable>());
  243. return new(context.Return(arg0));
  244. }
  245. public ValueTask<int> GetUserValue(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  246. {
  247. if (!context.GetArgumentOrDefault(0).TryRead<ILuaUserData>(out var iUserData))
  248. {
  249. return new(context.Return(LuaValue.Nil));
  250. }
  251. var index = 1; // context.GetArgument<int>(1); //for lua 5.4
  252. var userValues = iUserData.UserValues;
  253. if (index > userValues.Length /* index < 1 || // for lua 5.4 */)
  254. {
  255. return new(context.Return(LuaValue.Nil));
  256. }
  257. return new(context.Return(userValues[index - 1]));
  258. }
  259. public ValueTask<int> SetUserValue(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  260. {
  261. var iUserData = context.GetArgument<ILuaUserData>(0);
  262. var value = context.GetArgument(1);
  263. var index = 1; // context.GetArgument<int>(2); // for lua 5.4
  264. var userValues = iUserData.UserValues;
  265. if (index > userValues.Length /* || index < 1 // for lua 5.4 */)
  266. {
  267. return new(context.Return(LuaValue.Nil));
  268. }
  269. userValues[index - 1] = value;
  270. return new(context.Return(new LuaValue(iUserData)));
  271. }
  272. public ValueTask<int> Traceback(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  273. {
  274. var state = GetLuaThread(context, out var argOffset);
  275. var message = context.GetArgumentOrDefault(argOffset);
  276. var level = context.GetArgumentOrDefault(argOffset + 1, argOffset == 0 ? 1 : 0);
  277. if (message.Type is not (LuaValueType.Nil or LuaValueType.String or LuaValueType.Number))
  278. {
  279. return new(context.Return(message));
  280. }
  281. if (level < 0)
  282. {
  283. return new(context.Return(LuaValue.Nil));
  284. }
  285. if (state is { IsCoroutine: true, LuaTraceback: { } traceback })
  286. {
  287. return new(context.Return(traceback.ToString(level)));
  288. }
  289. var callStack = state.GetCallStackFrames();
  290. if (callStack.Length == 0)
  291. {
  292. return new(context.Return("stack traceback:"));
  293. }
  294. var skipCount = Math.Min(Math.Max(level - 1, 0), callStack.Length - 1);
  295. var frames = callStack[..^skipCount];
  296. return new(context.Return(Runtime.Traceback.CreateTracebackMessage(context.GlobalState, frames, message, level == 1 ? 1 : 0)));
  297. }
  298. public ValueTask<int> GetRegistry(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  299. {
  300. return new(context.Return(context.GlobalState.Registry));
  301. }
  302. public ValueTask<int> UpValueId(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  303. {
  304. var n1 = context.GetArgument<int>(1);
  305. var f1 = context.GetArgument<LuaFunction>(0);
  306. if (f1 is not LuaClosure closure)
  307. {
  308. return new(context.Return(LuaValue.Nil));
  309. }
  310. var upValues = closure.GetUpValuesSpan();
  311. if (n1 <= 0 || n1 > upValues.Length)
  312. {
  313. return new(context.Return(LuaValue.Nil));
  314. }
  315. return new(context.Return(LuaValue.FromObject(upValues[n1 - 1])));
  316. }
  317. public ValueTask<int> UpValueJoin(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  318. {
  319. var n2 = context.GetArgument<int>(3);
  320. var f2 = context.GetArgument<LuaFunction>(2);
  321. var n1 = context.GetArgument<int>(1);
  322. var f1 = context.GetArgument<LuaFunction>(0);
  323. if (f1 is not LuaClosure closure1 || f2 is not LuaClosure closure2)
  324. {
  325. return new(context.Return(LuaValue.Nil));
  326. }
  327. var upValues1 = closure1.GetUpValuesSpan();
  328. var upValues2 = closure2.GetUpValuesSpan();
  329. if (n1 <= 0 || n1 > upValues1.Length)
  330. {
  331. context.ThrowBadArgument(1, "invalid upvalue index");
  332. }
  333. if (n2 < 0 || n2 > upValues2.Length)
  334. {
  335. context.ThrowBadArgument(3, "invalid upvalue index");
  336. }
  337. upValues1[n1 - 1] = upValues2[n2 - 1];
  338. return new(0);
  339. }
  340. public async ValueTask<int> SetHook(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  341. {
  342. var state = GetLuaThread(context, out var argOffset);
  343. var hook = context.GetArgumentOrDefault<LuaFunction?>(argOffset);
  344. var mask = context.GetArgumentOrDefault<string?>(argOffset + 1) ?? "";
  345. var count = context.GetArgumentOrDefault<int>(argOffset + 2);
  346. state.SetHook(hook, mask, count);
  347. if (hook is null)
  348. {
  349. return 0;
  350. }
  351. if (state.IsReturnHookEnabled && context.State == state)
  352. {
  353. var stack = state.Stack;
  354. var top = stack.Count;
  355. stack.Push("return");
  356. stack.Push(LuaValue.Nil);
  357. context.State.IsInHook = true;
  358. var frame = context.State.CreateCallStackFrame(hook, 2, top, 0);
  359. context.State.PushCallStackFrame(frame);
  360. LuaFunctionExecutionContext funcContext = new() { State = context.State, ArgumentCount = stack.Count - frame.Base, ReturnFrameBase = frame.ReturnBase };
  361. try
  362. {
  363. await hook.Func(funcContext, cancellationToken);
  364. }
  365. finally
  366. {
  367. context.State.IsInHook = false;
  368. context.State.PopCallStackFrameWithStackPop();
  369. }
  370. }
  371. return 0;
  372. }
  373. public ValueTask<int> GetHook(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  374. {
  375. var state = GetLuaThread(context, out _);
  376. if (state.Hook is null)
  377. {
  378. return new(context.Return(LuaValue.Nil, LuaValue.Nil, LuaValue.Nil));
  379. }
  380. return new(context.Return(state.Hook,
  381. (state.IsCallHookEnabled ? "c" : "") +
  382. (state.IsReturnHookEnabled ? "r" : "") +
  383. (state.IsLineHookEnabled ? "l" : "")
  384. , state.BaseHookCount));
  385. }
  386. public ValueTask<int> GetInfo(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  387. {
  388. // return new(0);
  389. var state = GetLuaThread(context, out var argOffset);
  390. var what = context.GetArgumentOrDefault(argOffset + 1, "flnStu");
  391. CallStackFrame? previousFrame = null;
  392. CallStackFrame? currentFrame = null;
  393. var pc = 0;
  394. var arg1 = context.GetArgument(argOffset);
  395. if (arg1.TryReadFunction(out var functionToInspect))
  396. {
  397. // what = ">" + what;
  398. }
  399. else if (arg1.TryReadNumber(out _))
  400. {
  401. var level = context.GetArgument<int>(argOffset) + 1;
  402. var callStack = state.GetCallStackFrames();
  403. if (level <= 0 || level > callStack.Length)
  404. {
  405. return new(context.Return(LuaValue.Nil));
  406. }
  407. currentFrame = state.GetCallStackFrames()[^level];
  408. previousFrame = level + 1 <= callStack.Length ? callStack[^(level + 1)] : null;
  409. if (level != 1)
  410. {
  411. pc = state.GetCallStackFrames()[^(level - 1)].CallerInstructionIndex;
  412. }
  413. functionToInspect = currentFrame.Value.Function;
  414. }
  415. else
  416. {
  417. context.ThrowBadArgument(argOffset, "function or level expected");
  418. }
  419. using var debug = LuaDebug.Create(context.GlobalState, previousFrame, currentFrame, functionToInspect, pc, what, out var isValid);
  420. if (!isValid)
  421. {
  422. context.ThrowBadArgument(argOffset + 1, "invalid option");
  423. }
  424. LuaTable table = new(0, 1);
  425. if (what.Contains('S'))
  426. {
  427. table["source"] = debug.Source ?? LuaValue.Nil;
  428. table["short_src"] = debug.ShortSource.ToString();
  429. table["linedefined"] = debug.LineDefined;
  430. table["lastlinedefined"] = debug.LastLineDefined;
  431. table["what"] = debug.What ?? LuaValue.Nil;
  432. ;
  433. }
  434. if (what.Contains('l'))
  435. {
  436. table["currentline"] = debug.CurrentLine;
  437. }
  438. if (what.Contains('u'))
  439. {
  440. table["nups"] = debug.UpValueCount;
  441. table["nparams"] = debug.ParameterCount;
  442. table["isvararg"] = debug.IsVarArg;
  443. }
  444. if (what.Contains('n'))
  445. {
  446. table["name"] = debug.Name ?? LuaValue.Nil;
  447. table["namewhat"] = debug.NameWhat ?? LuaValue.Nil;
  448. }
  449. if (what.Contains('t'))
  450. {
  451. table["istailcall"] = debug.IsTailCall;
  452. }
  453. if (what.Contains('f'))
  454. {
  455. table["func"] = functionToInspect;
  456. }
  457. if (what.Contains('L'))
  458. {
  459. if (functionToInspect is LuaClosure closure)
  460. {
  461. LuaTable activeLines = new(0, 8);
  462. foreach (var line in closure.Proto.LineInfo)
  463. {
  464. activeLines[line] = true;
  465. }
  466. table["activelines"] = activeLines;
  467. }
  468. }
  469. return new(context.Return(table));
  470. }
  471. }