GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — ReClass.NET/ReClass.NET/CodeGenerator/CppCodeGenerator.cs at master · ReClassNET/ReClass.NET Expand file tree/ Copy pathCppCodeGenerator.csMore file actions 651 lines (559 loc) · 18.7 KB / Copy pathCppCodeGenerator.csFile metadata and controls651 lines (559 loc) · 18.7 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Drawing; using System.IO; using System.Linq; using System.Text; using ReClassNET.Controls; using ReClassNET.Extensions; using ReClassNET.Logger; using ReClassNET.Nodes; using ReClassNET.Project; namespace ReClassNET.CodeGenerator { public delegate void WriteNodeFunc(IndentedTextWriter writer, BaseNode node, ILogger logger); public delegate string GetTypeDefinitionFunc(BaseNode node, ILogger logger); public delegate string ResolveWrappedTypeFunc(BaseNode node, bool isAnonymousExpression, ILogger logger); /// <summary> /// A C++ code generator for custom nodes. /// </summary> public abstract class CustomCppCodeGenerator { /// <summary> /// Returns <c>true</c> if the code generator can handle the given node. /// </summary> /// <param name="node">The node to check.</param> /// <returns>True if the code generator can handle the given node, false otherwise.</returns> public abstract bool CanHandle(BaseNode node); /// <summary> /// Outputs the C++ code for the node to the <see cref="TextWriter"/> instance. /// </summary> /// <param name="writer">The writer to output to.</param> /// <param name="node">The node to output.</param> /// <param name="defaultWriteNodeFunc">The default implementation of <see cref="CppCodeGenerator.WriteNode"/>.</param> /// <param name="logger">The logger.</param> /// <returns>True if the code generator has processed the node, false otherwise. If this method returns false, the default implementation is used.</returns> public virtual bool WriteNode(IndentedTextWriter writer, BaseNode node, WriteNodeFunc defaultWriteNodeFunc, ILogger logger) { return false; } /// <summary> /// Transforms the given node if necessary. /// </summary> /// <param name="node">The node to transform.</param> /// <returns>The transformed node.</returns> public virtual BaseNode TransformNode(BaseNode node) { return node; } /// <summary> /// Gets the type definition for the node. If the node is not a simple node <c>null</c> is returned. /// </summary> /// <param name="node">The node.</param> /// <param name="defaultGetTypeDefinitionFunc">The default implementation of <see cref="CppCodeGenerator.GetTypeDefinition"/>.</param> /// <param name="defaultResolveWrappedTypeFunc">The default implementation of <see cref="CppCodeGenerator.ResolveWrappedType"/>.</param> /// <param name="logger">The logger.</param> /// <returns>The type definition for the node or null if no simple type is available.</returns> public virtual string GetTypeDefinition(BaseNode node, GetTypeDefinitionFunc defaultGetTypeDefinitionFunc, ResolveWrappedTypeFunc defaultResolveWrappedTypeFunc, ILogger logger) { return null; } } public class CppCodeGenerator : ICodeGenerator { #region Custom Code Generators private static readonly ISet<CustomCppCodeGenerator> customGenerators = new HashSet<CustomCppCodeGenerator>(); public static void Add(CustomCppCodeGenerator generator) { customGenerators.Add(generator); } public static void Remove(CustomCppCodeGenerator generator) { customGenerators.Remove(generator); } private static CustomCppCodeGenerator GetCustomCodeGeneratorForNode(BaseNode node) { return customGenerators.FirstOrDefault(g => g.CanHandle(node)); } #endregion private readonly Dictionary<Type, string> nodeTypeToTypeDefinationMap; #region HelperNodes private class Utf8CharacterNode : BaseNode { public override int MemorySize => throw new NotImplementedException(); public override void GetUserInterfaceInfo(out string name, out Image icon) => throw new NotImplementedException(); public override Size Draw(DrawContext context, int x, int y) => throw new NotImplementedException(); public override int CalculateDrawnHeight(DrawContext context) => throw new NotImplementedException(); } private class Utf16CharacterNode : BaseNode { public override int MemorySize => throw new NotImplementedException(); public override void GetUserInterfaceInfo(out string name, out Image icon) => throw new NotImplementedException(); public override Size Draw(DrawContext context, int x, int y) => throw new NotImplementedException(); public override int CalculateDrawnHeight(DrawContext context) => throw new NotImplementedException(); } private class Utf32CharacterNode : BaseNode { public override int MemorySize => throw new NotImplementedException(); public override void GetUserInterfaceInfo(out string name, out Image icon) => throw new NotImplementedException(); public override Size Draw(DrawContext context, int x, int y) => throw new NotImplementedException(); public override int CalculateDrawnHeight(DrawContext context) => throw new NotImplementedException(); } #endregion public Language Language => Language.Cpp; public CppCodeGenerator(CppTypeMapping typeMapping) { nodeTypeToTypeDefinationMap = new Dictionary<Type, string> { [typeof(BoolNode)] = typeMapping.TypeBool, [typeof(DoubleNode)] = typeMapping.TypeDouble, [typeof(FloatNode)] = typeMapping.TypeFloat, [typeof(FunctionPtrNode)] = typeMapping.TypeFunctionPtr, [typeof(Int8Node)] = typeMapping.TypeInt8, [typeof(Int16Node)] = typeMapping.TypeInt16, [typeof(Int32Node)] = typeMapping.TypeInt32, [typeof(Int64Node)] = typeMapping.TypeInt64, [typeof(NIntNode)] = typeMapping.TypeNInt, [typeof(Matrix3x3Node)] = typeMapping.TypeMatrix3x3, [typeof(Matrix3x4Node)] = typeMapping.TypeMatrix3x4, [typeof(Matrix4x4Node)] = typeMapping.TypeMatrix4x4, [typeof(UInt8Node)] = typeMapping.TypeUInt8, [typeof(UInt16Node)] = typeMapping.TypeUInt16, [typeof(UInt32Node)] = typeMapping.TypeUInt32, [typeof(UInt64Node)] = typeMapping.TypeUInt64, [typeof(NUIntNode)] = typeMapping.TypeNUInt, [typeof(Utf8CharacterNode)] = typeMapping.TypeUtf8Text, [typeof(Utf16CharacterNode)] = typeMapping.TypeUtf16Text, [typeof(Utf32CharacterNode)] = typeMapping.TypeUtf32Text, [typeof(Vector2Node)] = typeMapping.TypeVector2, [typeof(Vector3Node)] = typeMapping.TypeVector3, [typeof(Vector4Node)] = typeMapping.TypeVector4 }; } public string GenerateCode(IReadOnlyList<ClassNode> classes, IReadOnlyList<EnumDescription> enums, ILogger logger) { using var sw = new StringWriter(); using var iw = new IndentedTextWriter(sw, "\t"); iw.WriteLine($"// Created with {Constants.ApplicationName} {Constants.ApplicationVersion} by {Constants.Author}"); iw.WriteLine(); using (var en = enums.GetEnumerator()) { if (en.MoveNext()) { WriteEnum(iw, en.Current); while (en.MoveNext()) { iw.WriteLine(); WriteEnum(iw, en.Current); } iw.WriteLine(); } } var alreadySeen = new HashSet<ClassNode>(); IEnumerable<ClassNode> GetReversedClassHierarchy(ClassNode node) { Contract.Requires(node != null); Contract.Ensures(Contract.Result<IEnumerable<ClassNode>>() != null); if (!alreadySeen.Add(node)) { return Enumerable.Empty<ClassNode>(); } var classNodes = node.Nodes .OfType<BaseContainerNode>() .SelectMany(c => c.Nodes) .Concat(node.Nodes) .OfType<BaseWrapperNode>() .Where(w => !w.IsNodePresentInChain<PointerNode>()) // Pointers are forward declared .Select(w => w.ResolveMostInnerNode() as ClassNode) .Where(n => n != null); return classNodes .SelectMany(GetReversedClassHierarchy) .Append(node); } var classesToWrite = classes .Where(c => c.Nodes.None(n => n is FunctionNode)) // Skip class which contains FunctionNodes because these are not data classes. .SelectMany(GetReversedClassHierarchy) // Order the classes by their use hierarchy. .Distinct(); using (var en = classesToWrite.GetEnumerator()) { if (en.MoveNext()) { WriteClass(iw, en.Current, classes, logger); while (en.MoveNext()) { iw.WriteLine(); WriteClass(iw, en.Current, classes, logger); } } } return sw.ToString(); } /// <summary> /// Outputs the C++ code for the given enum to the <see cref="TextWriter"/> instance. /// </summary> /// <param name="writer">The writer to output to.</param> /// <param name="enum">The enum to output.</param> private void WriteEnum(IndentedTextWriter writer, EnumDescription @enum) { Contract.Requires(writer != null); Contract.Requires(@enum != null); writer.Write($"enum class {@enum.Name} : "); switch (@enum.Size) { case EnumDescription.UnderlyingTypeSize.OneByte: writer.WriteLine(nodeTypeToTypeDefinationMap[typeof(Int8Node)]); break; case EnumDescription.UnderlyingTypeSize.TwoBytes: writer.WriteLine(nodeTypeToTypeDefinationMap[typeof(Int16Node)]); break; case EnumDescription.UnderlyingTypeSize.FourBytes: writer.WriteLine(nodeTypeToTypeDefinationMap[typeof(Int32Node)]); break; case EnumDescription.UnderlyingTypeSize.EightBytes: writer.WriteLine(nodeTypeToTypeDefinationMap[typeof(Int64Node)]); break; } writer.WriteLine("{"); writer.Indent++; for (var j = 0; j < @enum.Values.Count; ++j) { var kv = @enum.Values[j]; writer.Write(kv.Key); writer.Write(" = "); writer.Write(kv.Value); if (j < @enum.Values.Count - 1) { writer.Write(","); } writer.WriteLine(); } writer.Indent--; writer.WriteLine("};"); } /// <summary> /// Outputs the C++ code for the given class to the <see cref="TextWriter"/> instance. /// </summary> /// <param name="writer">The writer to output to.</param> /// <param name="class">The class to output.</param> /// <param name="classes">The list of all available classes.</param> /// <param name="logger">The logger.</param> private void WriteClass(IndentedTextWriter writer, ClassNode @class, IEnumerable<ClassNode> classes, ILogger logger) { Contract.Requires(writer != null); Contract.Requires(@class != null); Contract.Requires(classes != null); writer.Write("class "); writer.Write(@class.Name); var skipFirstMember = false; if (@class.Nodes.FirstOrDefault() is ClassInstanceNode inheritedFromNode) { skipFirstMember = true; writer.Write(" : public "); writer.Write(inheritedFromNode.InnerNode.Name); } if (!string.IsNullOrEmpty(@class.Comment)) { writer.Write(" // "); writer.Write(@class.Comment); } writer.WriteLine(); writer.WriteLine("{"); writer.WriteLine("public:"); writer.Indent++; var nodes = @class.Nodes .Skip(skipFirstMember ? 1 : 0) .WhereNot(n => n is FunctionNode); WriteNodes(writer, nodes, logger); var vTableNodes = @class.Nodes.OfType<VirtualMethodTableNode>().ToList(); if (vTableNodes.Any()) { writer.WriteLine(); var virtualMethodNodes = vTableNodes .SelectMany(vt => vt.Nodes) .OfType<VirtualMethodNode>(); foreach (var node in virtualMethodNodes) { writer.Write("virtual void "); writer.Write(node.MethodName); writer.WriteLine("();"); } } var functionNodes = classes .SelectMany(c2 => c2.Nodes) .OfType<FunctionNode>() .Where(f => f.BelongsToClass == @class) .ToList(); if (functionNodes.Any()) { writer.WriteLine(); foreach (var node in functionNodes) { writer.Write(node.Signature); writer.WriteLine("{ }"); } } writer.Indent--; writer.Write("}; //Size: 0x"); writer.WriteLine($"{@class.MemorySize:X04}"); writer.WriteLine($"static_assert(sizeof({@class.Name}) == 0x{@class.MemorySize:X});"); } /// <summary> /// Outputs the C++ code for the given nodes to the <see cref="TextWriter"/> instance. /// </summary> /// <param name="writer">The writer to output to.</param> /// <param name="nodes">The nodes to output.</param> /// <param name="logger">The logger.</param> private void WriteNodes(IndentedTextWriter writer, IEnumerable<BaseNode> nodes, ILogger logger) { Contract.Requires(writer != null); Contract.Requires(nodes != null); var fill = 0; var fillStart = 0; static BaseNode CreatePaddingMember(int offset, int count) { var node = new ArrayNode { Offset = offset, Count = count, Name = $"pad_{offset:X04}" }; node.ChangeInnerNode(new Utf8CharacterNode()); return node; } foreach (var member in nodes.WhereNot(m => m is VirtualMethodTableNode)) { if (member is BaseHexNode) { if (fill == 0) { fillStart = member.Offset; } fill += member.MemorySize; continue; } if (fill != 0) { WriteNode(writer, CreatePaddingMember(fillStart, fill), logger); fill = 0; } WriteNode(writer, member, logger); } if (fill != 0) { WriteNode(writer, CreatePaddingMember(fillStart, fill), logger); } } /// <summary> /// Outputs the C++ code for the given node to the <see cref="TextWriter"/> instance. /// </summary> /// <param name="writer">The writer to output to.</param> /// <param name="node">The node to output.</param> /// <param name="logger">The logger.</param> private void WriteNode(IndentedTextWriter writer, BaseNode node, ILogger logger) { Contract.Requires(writer != null); Contract.Requires(node != null); var custom = GetCustomCodeGeneratorForNode(node); if (custom != null) { if (custom.WriteNode(writer, node, WriteNode, logger)) { return; } } node = TransformNode(node); var simpleType = GetTypeDefinition(node, logger); if (simpleType != null) { //$"{type} {node.Name}; //0x{node.Offset.ToInt32():X04} {node.Comment}".Trim(); writer.Write(simpleType); writer.Write(" "); writer.Write(node.Name); writer.Write("; //0x"); writer.Write($"{node.Offset:X04}"); if (!string.IsNullOrEmpty(node.Comment)) { writer.Write(" "); writer.Write(node.Comment); } writer.WriteLine(); } else if (node is BaseWrapperNode) { writer.Write(ResolveWrappedType(node, false, logger)); writer.Write("; //0x"); writer.Write($"{node.Offset:X04}"); if (!string.IsNullOrEmpty(node.Comment)) { writer.Write(" "); writer.Write(node.Comment); } writer.WriteLine(); } else if (node is UnionNode unionNode) { writer.Write("union //0x"); writer.Write($"{node.Offset:X04}"); if (!string.IsNullOrEmpty(node.Comment)) { writer.Write(" "); writer.Write(node.Comment); } writer.WriteLine(); writer.WriteLine("{"); writer.Indent++; WriteNodes(writer, unionNode.Nodes, logger); writer.Indent--; writer.WriteLine("};"); } else { logger.Log(LogLevel.Error, $"Skipping node with unhandled type: {node.GetType()}"); } } /// <summary> /// Transforms the given node into some other node if necessary. /// </summary> /// <param name="node">The node to transform.</param> /// <returns>The transformed node.</returns> private static BaseNode TransformNode(BaseNode node) { var custom = GetCustomCodeGeneratorForNode(node); if (custom != null) { return custom.TransformNode(node); } static BaseNode GetCharacterNodeForEncoding(Encoding encoding) { if (encoding.IsSameCodePage(Encoding.Unicode)) { return new Utf16CharacterNode(); } if (encoding.IsSameCodePage(Encoding.UTF32)) { return new Utf32CharacterNode(); } return new Utf8CharacterNode(); } switch (node) { case BaseTextNode textNode: { var arrayNode = new ArrayNode { Count = textNode.Length }; arrayNode.CopyFromNode(node); arrayNode.ChangeInnerNode(GetCharacterNodeForEncoding(textNode.Encoding)); return arrayNode; } case BaseTextPtrNode textPtrNode: { var pointerNode = new PointerNode(); pointerNode.CopyFromNode(node); pointerNode.ChangeInnerNode(GetCharacterNodeForEncoding(textPtrNode.Encoding)); return pointerNode; } case BitFieldNode bitFieldNode: { var underlayingNode = bitFieldNode.GetUnderlayingNode(); underlayingNode.CopyFromNode(node); return underlayingNode; } case BaseHexNode hexNode: { var arrayNode = new ArrayNode { Count = hexNode.MemorySize }; arrayNode.CopyFromNode(node); arrayNode.ChangeInnerNode(new Utf8CharacterNode()); return arrayNode; } } return node; } /// <summary> /// Gets the type definition for the given node. If the node is not a simple node <c>null</c> is returned. /// </summary> /// <param name="node">The target node.</param> /// <param name="logger">The logger.</param> /// <returns>The type definition for the node or null if no simple type is available.</returns> private string GetTypeDefinition(BaseNode node, ILogger logger) { Contract.Requires(node != null); var custom = GetCustomCodeGeneratorForNode(node); if (custom != null) { return custom.GetTypeDefinition(node, GetTypeDefinition, ResolveWrappedType, logger); } if (nodeTypeToTypeDefinationMap.TryGetValue(node.GetType(), out var type)) { return type; } switch (node) { case ClassInstanceNode classInstanceNode: return $"class {classInstanceNode.InnerNode.Name}"; case EnumNode enumNode: return enumNode.Enum.Name; } return null; } /// <summary> /// Resolves the type of a <see cref="BaseWrapperNode"/> node (<see cref="PointerNode"/> and <see cref="ArrayNode"/>). /// </summary> /// <param name="node">The node to resolve.</param> /// <param name="isAnonymousExpression">Specify if the expression should be anonymous.</param> /// <param name="logger">The logger.</param> /// <returns>The resolved type of the node.</returns> private string ResolveWrappedType(BaseNode node, bool isAnonymousExpression, ILogger logger) { Contract.Requires(node != null); var sb = new StringBuilder(); if (!isAnonymousExpression) { sb.Append(node.Name); } BaseNode lastWrapperNode = null; var currentNode = node; while (true) { currentNode = TransformNode(currentNode); if (currentNode is PointerNode pointerNode) { sb.Prepend('*'); if (pointerNode.InnerNode == null) // void* { if (!isAnonymousExpression) { sb.Prepend(' '); } sb.Prepend("void"); break; } lastWrapperNode = pointerNode; currentNode = pointerNode.InnerNode; } else if (currentNode is ArrayNode arrayNode) { if (lastWrapperNode is PointerNode) { sb.Prepend('('); sb.Append(')'); } sb.Append($"[{arrayNode.Count}]"); lastWrapperNode = arrayNode; currentNode = arrayNode.InnerNode; } else { var simpleType = GetTypeDefinition(currentNode, logger); if (!isAnonymousExpression) { sb.Prepend(' '); } sb.Prepend(simpleType); break; } } return sb.ToString().Trim(); } } } |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |