├── .gitignore ├── .gitmodules ├── LICENSE ├── README.md ├── deps └── premake │ ├── asmjit.lua │ ├── discord-rpc.lua │ ├── gsl.lua │ ├── minhook.lua │ ├── protobuf.lua │ └── rapidjson.lua ├── generate.bat ├── premake5.lua ├── src ├── client │ ├── components │ │ ├── asset_limits.cpp │ │ ├── asset_limits.hpp │ │ ├── axios.cpp │ │ ├── bullet_depletion.cpp │ │ ├── console.cpp │ │ ├── console.hpp │ │ ├── discord.cpp │ │ ├── fastfiles.cpp │ │ ├── hotreload.cpp │ │ ├── lua.cpp │ │ ├── scheduler.cpp │ │ └── scheduler.hpp │ ├── game │ │ ├── dvars.cpp │ │ ├── dvars.hpp │ │ ├── game.cpp │ │ ├── game.hpp │ │ ├── structs.hpp │ │ └── symbols.hpp │ ├── havok │ │ ├── hks_api.cpp │ │ ├── hks_api.hpp │ │ ├── lua_api.cpp │ │ ├── lua_api.hpp │ │ ├── structs.cpp │ │ └── structs.hpp │ ├── loader │ │ ├── component_interface.hpp │ │ ├── component_loader.cpp │ │ └── component_loader.hpp │ ├── main.cpp │ ├── script │ │ ├── builtins.cpp │ │ └── builtins.hpp │ ├── std_include.cpp │ └── std_include.hpp └── common │ └── utils │ ├── HTTPRequest.hpp │ ├── concurrency.hpp │ ├── file_watcher.cpp │ ├── file_watcher.hpp │ ├── hook.cpp │ ├── hook.hpp │ ├── io.cpp │ ├── io.hpp │ ├── memory.cpp │ ├── memory.hpp │ ├── minlog.hpp │ ├── nt.cpp │ ├── nt.hpp │ ├── signature.cpp │ ├── signature.hpp │ ├── string.cpp │ ├── string.hpp │ ├── thread.cpp │ └── thread.hpp ├── tools ├── premake5.exe └── protoc.exe └── usage ├── dvar_hash_list.txt └── ui └── util ├── T7Overcharged.lua └── T7OverchargedUtil.lua /.gitignore: -------------------------------------------------------------------------------- 1 | ### Windows 2 | 3 | # Windows image file caches 4 | Thumbs.db 5 | ehthumbs.db 6 | 7 | # Folder config file 8 | Desktop.ini 9 | 10 | # Recycle Bin used on file shares 11 | $RECYCLE.BIN/ 12 | 13 | # Windows Installer files 14 | *.cab 15 | *.msi 16 | *.msm 17 | *.msp 18 | 19 | # Shortcuts 20 | *.lnk 21 | 22 | ### OSX 23 | 24 | .DS_Store 25 | .AppleDouble 26 | .LSOverride 27 | 28 | # Icon must end with two \r 29 | Icon 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear on external disk 35 | .Spotlight-V100 36 | .Trashes 37 | 38 | # Directories potentially created on remote AFP share 39 | .AppleDB 40 | .AppleDesktop 41 | Network Trash Folder 42 | Temporary Items 43 | .apdisk 44 | 45 | ### Visual Studio 46 | 47 | # User-specific files 48 | *.suo 49 | *.user 50 | *.userosscache 51 | *.sln.docstates 52 | 53 | # User-specific files (MonoDevelop/Xamarin Studio) 54 | *.userprefs 55 | 56 | # Build results 57 | build 58 | 59 | # Visual Studio 2015 cache/options directory 60 | .vs/ 61 | 62 | # MSTest test Results 63 | [Tt]est[Rr]esult*/ 64 | [Bb]uild[Ll]og.* 65 | 66 | *_i.c 67 | *_p.c 68 | *_i.h 69 | *.ilk 70 | *.meta 71 | *.obj 72 | *.pch 73 | *.pdb 74 | *.pgc 75 | *.pgd 76 | *.rsp 77 | *.sbr 78 | *.tlb 79 | *.tli 80 | *.tlh 81 | *.tmp 82 | *.tmp_proj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | *.dll 91 | 92 | # Visual C++ cache files 93 | ipch/ 94 | *.aps 95 | *.ncb 96 | *.opendb 97 | *.opensdf 98 | *.sdf 99 | *.cachefile 100 | 101 | # Visual Studio profiler 102 | *.psess 103 | *.vsp 104 | *.vspx 105 | *.sap 106 | 107 | # TFS 2012 Local Workspace 108 | $tf/ 109 | 110 | # Guidance Automation Toolkit 111 | *.gpState 112 | 113 | # Visual Studio cache files 114 | # files ending in .cache can be ignored 115 | *.[Cc]ache 116 | # but keep track of directories ending in .cache 117 | !*.[Cc]ache/ 118 | 119 | # Others 120 | ~$* 121 | *~ 122 | *.dbmdl 123 | *.dbproj.schemaview 124 | *.pfx 125 | *.publishsettings 126 | 127 | # Backup & report files from converting an old project file 128 | # to a newer Visual Studio version. Backup files are not needed, 129 | # because we have git ;-) 130 | _UpgradeReport_Files/ 131 | Backup*/ 132 | UpgradeLog*.XML 133 | UpgradeLog*.htm 134 | 135 | # SQL Server files 136 | *.mdf 137 | *.ldf 138 | 139 | ### IDA 140 | *.id0 141 | *.id1 142 | *.id2 143 | *.nam 144 | *.til 145 | 146 | ### Custom user files 147 | # User scripts 148 | user*.bat 149 | 150 | # Premake binary 151 | #premake5.exe -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "deps/GSL"] 2 | path = deps/GSL 3 | url = https://github.com/Microsoft/GSL.git 4 | [submodule "deps/asmjit"] 5 | path = deps/asmjit 6 | url = https://github.com/asmjit/asmjit.git 7 | [submodule "deps/rapidjson"] 8 | path = deps/rapidjson 9 | url = https://github.com/Tencent/rapidjson.git 10 | [submodule "deps/protobuf"] 11 | path = deps/protobuf 12 | url = https://github.com/google/protobuf.git 13 | branch = 3.17.x 14 | [submodule "deps/minhook"] 15 | path = deps/minhook 16 | url = https://github.com/TsudaKageyu/minhook.git 17 | [submodule "deps/discord-rpc"] 18 | path = deps/discord-rpc 19 | url = https://github.com/discord/discord-rpc.git 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) 2 | [![Releases](https://img.shields.io/github/downloads/JariKCoding/T7Overcharged/total.svg)](https://github.com/JariKCoding/T7Overcharged/) 3 | 4 | # T7Overcharged 5 | 6 | **T7Overcharged** gives Call of Duty: Black Ops 3 modders the ability to take their mods to the next level by providing an API between Lua and C++ and providing already worked out components. 7 | 8 | ## Features 9 | - Hot reloading of lua scripts 10 | - UI Errors now give a stack trace and don't cause a freeze 11 | - Extending the asset limits 12 | - External console and printing to the console from lua 13 | - HTTP requests from lua 14 | - Discord Rich Presence 15 | - Bullet depletion 16 | - More to come! 17 | 18 | ## How to use 19 | - Clone this repo or download the latest release. 20 | - Copy the lua files to the mod/map you want to use this in. 21 | - Copy the dll to the zone folder 22 | - Add the following lines to your zone file: 23 | ``` 24 | rawfile,ui/util/T7Overcharged.lua 25 | rawfile,ui/util/T7OverchargedUtil.lua 26 | ``` 27 | - Add the following lines in your main lua file: 28 | ``` 29 | require("ui.util.T7Overcharged") 30 | ``` 31 | - Under that add the following code but change variables to your map/mod's information 32 | 33 | for a mod: 34 | ``` 35 | InitializeT7Overcharged({ 36 | modname = "t7overcharged", 37 | filespath = [[.\mods\t7overcharged\]], 38 | workshopid = "45131545", 39 | discordAppId = nil,--"{{DISCORD_APP_ID}}" -- Not required, create your application at https://discord.com/developers/applications/ 40 | showExternalConsole = true 41 | }) 42 | ``` 43 | for a map: 44 | ``` 45 | InitializeT7Overcharged({ 46 | mapname = "zm_t7overcharged", 47 | filespath = [[.\usermaps\zm_t7overcharged\]], 48 | workshopid = "45131545", 49 | discordAppId = nil,--"{{DISCORD_APP_ID}}" -- Not required, create your application at https://discord.com/developers/applications/ 50 | showExternalConsole = true 51 | }) 52 | ``` 53 | The [dvar hash list](usage/dvar_hash_list.txt) as of now isn't shipped with the DLL, it has to be manually placed inside of the root folder of Black Ops 3. 54 | 55 | 56 | ## Download 57 | 58 | The latest version can be found on the [Releases Page](https://github.com/JariKCoding/T7Overcharged/releases). 59 | 60 | ## Compile from source 61 | 62 | - Clone the Git repo. Do NOT download it as ZIP, that won't work. 63 | - Update the submodules and run `premake5 vs2022` or simply use the delivered `generate.bat`. 64 | - Build via solution file in `build\T7Overcharged.sln`. 65 | 66 | ## Credits 67 | 68 | - [XLabsProjects](https://github.com/XLabsProject): Great project setup 69 | - [Approved](https://github.com/approved): Asset limit extension 70 | - [Serious](https://github.com/shiversoftdev): UI Error hash dvar 71 | 72 | ## License 73 | 74 | T7Overcharged is licensed under the GNUv3 license and its source code is free to use and modify. T7Overcharged comes with NO warranty, any damages caused are solely the responsibility of the user. See the LICENSE file for more information. -------------------------------------------------------------------------------- /deps/premake/asmjit.lua: -------------------------------------------------------------------------------- 1 | asmjit = { 2 | source = path.join(dependencies.basePath, "asmjit"), 3 | } 4 | 5 | function asmjit.import() 6 | links { "asmjit" } 7 | asmjit.includes() 8 | end 9 | 10 | function asmjit.includes() 11 | includedirs { 12 | path.join(asmjit.source, "src") 13 | } 14 | 15 | defines { 16 | "ASMJIT_STATIC" 17 | } 18 | end 19 | 20 | function asmjit.project() 21 | project "asmjit" 22 | language "C++" 23 | 24 | asmjit.includes() 25 | 26 | files { 27 | path.join(asmjit.source, "src/**.cpp"), 28 | } 29 | 30 | warnings "Off" 31 | kind "StaticLib" 32 | end 33 | 34 | table.insert(dependencies, asmjit) 35 | -------------------------------------------------------------------------------- /deps/premake/discord-rpc.lua: -------------------------------------------------------------------------------- 1 | discordrpc = { 2 | source = path.join(dependencies.basePath, "discord-rpc"), 3 | } 4 | 5 | function discordrpc.import() 6 | links { "discord-rpc" } 7 | discordrpc.includes() 8 | end 9 | 10 | function discordrpc.includes() 11 | includedirs { 12 | path.join(discordrpc.source, "include"), 13 | } 14 | end 15 | 16 | function discordrpc.project() 17 | project "discord-rpc" 18 | language "C++" 19 | 20 | discordrpc.includes() 21 | rapidjson.import(); 22 | 23 | files { 24 | path.join(discordrpc.source, "src/*.h"), 25 | path.join(discordrpc.source, "src/*.cpp"), 26 | } 27 | 28 | removefiles { 29 | path.join(discordrpc.source, "src/dllmain.cpp"), 30 | path.join(discordrpc.source, "src/*_linux.cpp"), 31 | path.join(discordrpc.source, "src/*_unix.cpp"), 32 | path.join(discordrpc.source, "src/*_osx.cpp"), 33 | } 34 | 35 | warnings "Off" 36 | kind "StaticLib" 37 | end 38 | 39 | table.insert(dependencies, discordrpc) 40 | -------------------------------------------------------------------------------- /deps/premake/gsl.lua: -------------------------------------------------------------------------------- 1 | gsl = { 2 | source = path.join(dependencies.basePath, "GSL"), 3 | } 4 | 5 | function gsl.import() 6 | gsl.includes() 7 | end 8 | 9 | function gsl.includes() 10 | includedirs { 11 | path.join(gsl.source, "include") 12 | } 13 | end 14 | 15 | function gsl.project() 16 | 17 | end 18 | 19 | table.insert(dependencies, gsl) 20 | -------------------------------------------------------------------------------- /deps/premake/minhook.lua: -------------------------------------------------------------------------------- 1 | minhook = { 2 | source = path.join(dependencies.basePath, "minhook"), 3 | } 4 | 5 | function minhook.import() 6 | links { "minhook" } 7 | minhook.includes() 8 | end 9 | 10 | function minhook.includes() 11 | includedirs { 12 | path.join(minhook.source, "include") 13 | } 14 | end 15 | 16 | function minhook.project() 17 | project "minhook" 18 | language "C" 19 | 20 | minhook.includes() 21 | 22 | files { 23 | path.join(minhook.source, "src/**.h"), 24 | path.join(minhook.source, "src/**.c"), 25 | } 26 | 27 | warnings "Off" 28 | kind "StaticLib" 29 | end 30 | 31 | table.insert(dependencies, minhook) 32 | -------------------------------------------------------------------------------- /deps/premake/protobuf.lua: -------------------------------------------------------------------------------- 1 | protobuf = { 2 | source = path.join(dependencies.basePath, "protobuf"), 3 | } 4 | 5 | function protobuf.import() 6 | links { 7 | "protobuf" 8 | } 9 | 10 | protobuf.includes() 11 | end 12 | 13 | function protobuf.includes() 14 | includedirs { 15 | path.join(protobuf.source, "src"), 16 | } 17 | end 18 | 19 | function protobuf.project() 20 | project "protobuf" 21 | language "C++" 22 | 23 | protobuf.includes() 24 | 25 | files { 26 | path.join(protobuf.source, "src/**.cc"), 27 | "./src/**.proto", 28 | } 29 | 30 | removefiles { 31 | path.join(protobuf.source, "src/**/*test.cc"), 32 | path.join(protobuf.source, "src/google/protobuf/*test*.cc"), 33 | 34 | path.join(protobuf.source, "src/google/protobuf/testing/**.cc"), 35 | path.join(protobuf.source, "src/google/protobuf/compiler/**.cc"), 36 | 37 | path.join(protobuf.source, "src/google/protobuf/arena_nc.cc"), 38 | path.join(protobuf.source, "src/google/protobuf/util/internal/error_listener.cc"), 39 | path.join(protobuf.source, "**/*_gcc.cc"), 40 | } 41 | 42 | rules { 43 | "ProtobufCompiler" 44 | } 45 | 46 | defines { 47 | "_SCL_SECURE_NO_WARNINGS", 48 | "_SILENCE_ALL_CXX17_DEPRECATION_WARNINGS", 49 | "_SILENCE_ALL_CXX20_DEPRECATION_WARNINGS", 50 | } 51 | 52 | linkoptions { 53 | "-IGNORE:4221" 54 | } 55 | 56 | warnings "Off" 57 | kind "StaticLib" 58 | end 59 | 60 | table.insert(dependencies, protobuf) 61 | -------------------------------------------------------------------------------- /deps/premake/rapidjson.lua: -------------------------------------------------------------------------------- 1 | rapidjson = { 2 | source = path.join(dependencies.basePath, "rapidjson"), 3 | } 4 | 5 | function rapidjson.import() 6 | rapidjson.includes() 7 | end 8 | 9 | function rapidjson.includes() 10 | includedirs { 11 | path.join(rapidjson.source, "include"), 12 | } 13 | end 14 | 15 | function rapidjson.project() 16 | 17 | end 18 | 19 | table.insert(dependencies, rapidjson) 20 | -------------------------------------------------------------------------------- /generate.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | git submodule update --init --recursive 3 | tools\premake5 %* vs2022 4 | -------------------------------------------------------------------------------- /premake5.lua: -------------------------------------------------------------------------------- 1 | gitVersioningCommand = "git describe --tags --dirty --always" 2 | gitCurrentBranchCommand = "git symbolic-ref -q --short HEAD" 3 | 4 | -- Quote the given string input as a C string 5 | function cstrquote(value) 6 | if value == nil then 7 | return "\"\"" 8 | end 9 | result = value:gsub("\\", "\\\\") 10 | result = result:gsub("\"", "\\\"") 11 | result = result:gsub("\n", "\\n") 12 | result = result:gsub("\t", "\\t") 13 | result = result:gsub("\r", "\\r") 14 | result = result:gsub("\a", "\\a") 15 | result = result:gsub("\b", "\\b") 16 | result = "\"" .. result .. "\"" 17 | return result 18 | end 19 | 20 | -- Converts tags in "vX.X.X" format and given revision number Y to an array of numbers {X,X,X,Y}. 21 | -- In the case where the format does not work fall back to padding with zeroes and just ending with the revision number. 22 | -- partscount can be either 3 or 4. 23 | function vertonumarr(value, vernumber, partscount) 24 | vernum = {} 25 | for num in string.gmatch(value or "", "%d+") do 26 | if #vernum < 3 then 27 | table.insert(vernum, tonumber(num)) 28 | end 29 | end 30 | while #vernum < 3 do 31 | table.insert(vernum, 0) 32 | end 33 | if #vernum < partscount then 34 | table.insert(vernum, tonumber(vernumber)) 35 | end 36 | return vernum 37 | end 38 | 39 | dependencies = { 40 | basePath = "./deps" 41 | } 42 | 43 | function dependencies.load() 44 | dir = path.join(dependencies.basePath, "premake/*.lua") 45 | deps = os.matchfiles(dir) 46 | 47 | for i, dep in pairs(deps) do 48 | dep = dep:gsub(".lua", "") 49 | require(dep) 50 | end 51 | end 52 | 53 | function dependencies.imports() 54 | for i, proj in pairs(dependencies) do 55 | if type(i) == 'number' then 56 | proj.import() 57 | end 58 | end 59 | end 60 | 61 | function dependencies.projects() 62 | for i, proj in pairs(dependencies) do 63 | if type(i) == 'number' then 64 | proj.project() 65 | end 66 | end 67 | end 68 | 69 | newoption { 70 | trigger = "copy-to", 71 | description = "Optional, copy the EXE to a custom folder after build, define the path here if wanted.", 72 | value = "PATH" 73 | } 74 | 75 | newoption { 76 | trigger = "dev-build", 77 | description = "Enable development builds of the client." 78 | } 79 | 80 | newaction { 81 | trigger = "version", 82 | description = "Returns the version string for the current commit of the source code.", 83 | onWorkspace = function(wks) 84 | -- get current version via git 85 | local proc = assert(io.popen(gitVersioningCommand, "r")) 86 | local gitDescribeOutput = assert(proc:read('*a')):gsub("%s+", "") 87 | proc:close() 88 | local version = gitDescribeOutput 89 | 90 | proc = assert(io.popen(gitCurrentBranchCommand, "r")) 91 | local gitCurrentBranchOutput = assert(proc:read('*a')):gsub("%s+", "") 92 | local gitCurrentBranchSuccess = proc:close() 93 | if gitCurrentBranchSuccess then 94 | -- We got a branch name, check if it is a feature branch 95 | if gitCurrentBranchOutput ~= "develop" and gitCurrentBranchOutput ~= "master" then 96 | version = version .. "-" .. gitCurrentBranchOutput 97 | end 98 | end 99 | 100 | print(version) 101 | os.exit(0) 102 | end 103 | } 104 | 105 | newaction { 106 | trigger = "generate-buildinfo", 107 | description = "Sets up build information file like version.h.", 108 | onWorkspace = function(wks) 109 | -- get old version number from version.hpp if any 110 | local oldVersion = "(none)" 111 | local oldVersionHeader = io.open(wks.location .. "/src/version.h", "r") 112 | if oldVersionHeader ~= nil then 113 | local oldVersionHeaderContent = assert(oldVersionHeader:read('*l')) 114 | while oldVersionHeaderContent do 115 | m = string.match(oldVersionHeaderContent, "#define GIT_DESCRIBE (.+)%s*$") 116 | if m ~= nil then 117 | oldVersion = m 118 | end 119 | 120 | oldVersionHeaderContent = oldVersionHeader:read('*l') 121 | end 122 | end 123 | 124 | -- get current version via git 125 | local proc = assert(io.popen(gitVersioningCommand, "r")) 126 | local gitDescribeOutput = assert(proc:read('*a')):gsub("%s+", "") 127 | proc:close() 128 | 129 | -- generate version.hpp with a revision number if not equal 130 | gitDescribeOutputQuoted = cstrquote(gitDescribeOutput) 131 | if oldVersion ~= gitDescribeOutputQuoted then 132 | -- get current git hash and write to version.txt (used by the preliminary updater) 133 | -- TODO - remove once proper updater and release versioning exists 134 | local proc = assert(io.popen("git rev-parse HEAD", "r")) 135 | local gitCommitHash = assert(proc:read('*a')):gsub("%s+", "") 136 | proc:close() 137 | 138 | -- get whether this is a clean revision (no uncommitted changes) 139 | proc = assert(io.popen("git status --porcelain", "r")) 140 | local revDirty = (assert(proc:read('*a')) ~= "") 141 | if revDirty then revDirty = 1 else revDirty = 0 end 142 | proc:close() 143 | 144 | -- get current tag name 145 | proc = assert(io.popen("git describe --tags --abbrev=0")) 146 | local tagName = proc:read('*l') 147 | 148 | -- get current branch name 149 | proc = assert(io.popen("git branch --show-current")) 150 | local branchName = proc:read('*l') 151 | 152 | -- branch for ci 153 | if branchName == nil or branchName == '' then 154 | proc = assert(io.popen("git show -s --pretty=%d HEAD")) 155 | local branchInfo = proc:read('*l') 156 | m = string.match(branchInfo, ".+,.+, ([^)]+)") 157 | if m ~= nil then 158 | branchName = m 159 | end 160 | end 161 | 162 | if branchName == nil then 163 | branchName = "develop" 164 | end 165 | 166 | print("Detected branch: " .. branchName) 167 | 168 | -- get revision number via git 169 | local proc = assert(io.popen("git rev-list --count HEAD", "r")) 170 | local revNumber = assert(proc:read('*a')):gsub("%s+", "") 171 | 172 | print ("Update " .. oldVersion .. " -> " .. gitDescribeOutputQuoted) 173 | 174 | -- write to version.txt for preliminary updater 175 | -- NOTE - remove this once we have a proper updater and proper release versioning 176 | local versionFile = assert(io.open(wks.location .. "/version.txt", "w")) 177 | versionFile:write(gitCommitHash) 178 | versionFile:close() 179 | 180 | -- write version header 181 | local versionHeader = assert(io.open(wks.location .. "/src/version.h", "w")) 182 | versionHeader:write("/*\n") 183 | versionHeader:write(" * Automatically generated by premake5.\n") 184 | versionHeader:write(" * Do not touch!\n") 185 | versionHeader:write(" */\n") 186 | versionHeader:write("\n") 187 | versionHeader:write("#define GIT_DESCRIBE " .. gitDescribeOutputQuoted .. "\n") 188 | versionHeader:write("#define GIT_DIRTY " .. revDirty .. "\n") 189 | versionHeader:write("#define GIT_HASH " .. cstrquote(gitCommitHash) .. "\n") 190 | versionHeader:write("#define GIT_TAG " .. cstrquote(tagName) .. "\n") 191 | versionHeader:write("#define GIT_BRANCH " .. cstrquote(branchName) .. "\n") 192 | versionHeader:write("\n") 193 | versionHeader:write("// Version transformed for RC files\n") 194 | versionHeader:write("#define VERSION_PRODUCT_RC " .. table.concat(vertonumarr(tagName, revNumber, 3), ",") .. "\n") 195 | versionHeader:write("#define VERSION_PRODUCT " .. cstrquote(table.concat(vertonumarr(tagName, revNumber, 3), ".")) .. "\n") 196 | versionHeader:write("#define VERSION_FILE_RC " .. table.concat(vertonumarr(tagName, revNumber, 4), ",") .. "\n") 197 | versionHeader:write("#define VERSION_FILE " .. cstrquote(table.concat(vertonumarr(tagName, revNumber, 4), ".")) .. "\n") 198 | versionHeader:write("\n") 199 | versionHeader:write("// Alias definitions\n") 200 | versionHeader:write("#define VERSION GIT_DESCRIBE\n") 201 | versionHeader:write("#define SHORTVERSION VERSION_PRODUCT\n") 202 | versionHeader:close() 203 | local versionHeader = assert(io.open(wks.location .. "/src/version.hpp", "w")) 204 | versionHeader:write("/*\n") 205 | versionHeader:write(" * Automatically generated by premake5.\n") 206 | versionHeader:write(" * Do not touch!\n") 207 | versionHeader:write(" *\n") 208 | versionHeader:write(" * This file exists for reasons of complying with our coding standards.\n") 209 | versionHeader:write(" *\n") 210 | versionHeader:write(" * The Resource Compiler will ignore any content from C++ header files if they're not from STDInclude.hpp.\n") 211 | versionHeader:write(" * That's the reason why we now place all version info in version.h instead.\n") 212 | versionHeader:write(" */\n") 213 | versionHeader:write("\n") 214 | versionHeader:write("#include \".\\version.h\"\n") 215 | versionHeader:close() 216 | end 217 | end 218 | } 219 | 220 | dependencies.load() 221 | 222 | workspace "T7Overcharged" 223 | startproject "client" 224 | location "./build" 225 | objdir "%{wks.location}/obj" 226 | targetdir "%{wks.location}/bin/%{cfg.platform}/%{cfg.buildcfg}" 227 | 228 | configurations {"Debug", "Release"} 229 | 230 | language "C++" 231 | cppdialect "C++20" 232 | 233 | architecture "x86_64" 234 | platforms "x64" 235 | 236 | systemversion "latest" 237 | symbols "On" 238 | staticruntime "On" 239 | editandcontinue "Off" 240 | warnings "Extra" 241 | characterset "ASCII" 242 | 243 | if _OPTIONS["dev-build"] then 244 | defines {"DEV_BUILD"} 245 | end 246 | 247 | if os.getenv("CI") then 248 | defines {"CI"} 249 | end 250 | 251 | flags {"NoIncrementalLink", "NoMinimalRebuild", "MultiProcessorCompile", "No64BitChecks"} 252 | 253 | filter "platforms:x64" 254 | defines {"_WINDOWS", "WIN32"} 255 | filter {} 256 | 257 | filter "configurations:Release" 258 | optimize "Size" 259 | buildoptions {"/GL"} 260 | linkoptions { "/IGNORE:4702", "/LTCG" } 261 | defines {"NDEBUG"} 262 | --flags {"FatalCompileWarnings"} 263 | filter {} 264 | 265 | filter "configurations:Debug" 266 | optimize "Debug" 267 | defines {"DEBUG", "_DEBUG"} 268 | filter {} 269 | 270 | project "common" 271 | kind "StaticLib" 272 | language "C++" 273 | 274 | files {"./src/common/**.hpp", "./src/common/**.cpp"} 275 | 276 | includedirs {"./src/common", "%{prj.location}/src"} 277 | 278 | resincludedirs {"$(ProjectDir)src"} 279 | 280 | dependencies.imports() 281 | 282 | project "client" 283 | kind "SharedLib" 284 | language "C++" 285 | 286 | targetname "T7Overcharged" 287 | 288 | pchheader "std_include.hpp" 289 | pchsource "src/client/std_include.cpp" 290 | 291 | linkoptions {"/IGNORE:4254", "/IGNORE:4244", "/DYNAMICBASE:NO", "/SAFESEH:NO", "/LARGEADDRESSAWARE", "/LAST:.main", "/PDBCompress"} 292 | 293 | files {"./src/client/**.rc", "./src/client/**.hpp", "./src/client/**.cpp", "./src/client/resources/**.*"} 294 | 295 | includedirs {"./src/client", "./src/common", "%{prj.location}/src"} 296 | 297 | resincludedirs {"$(ProjectDir)src"} 298 | 299 | --dependson {"tlsdll", "runner"} 300 | 301 | links {"common"} 302 | 303 | prebuildcommands {"pushd %{_MAIN_SCRIPT_DIR}", "tools\\premake5 generate-buildinfo", "popd"} 304 | 305 | if _OPTIONS["copy-to"] then 306 | postbuildcommands {"copy /y \"$(TargetPath)\" \"" .. _OPTIONS["copy-to"] .. "\""} 307 | end 308 | 309 | dependencies.imports() 310 | 311 | group "Dependencies" 312 | dependencies.projects() 313 | 314 | rule "ProtobufCompiler" 315 | display "Protobuf compiler" 316 | location "./build" 317 | fileExtension ".proto" 318 | buildmessage "Compiling %(Identity) with protoc..." 319 | buildcommands {'@echo off', 'path "$(SolutionDir)\\..\\tools"', 320 | 'if not exist "$(ProjectDir)\\src\\proto" mkdir "$(ProjectDir)\\src\\proto"', 321 | 'protoc --error_format=msvs -I=%(RelativeDir) --cpp_out=src\\proto %(Identity)'} 322 | buildoutputs {'$(ProjectDir)\\src\\proto\\%(Filename).pb.cc', '$(ProjectDir)\\src\\proto\\%(Filename).pb.h'} 323 | -------------------------------------------------------------------------------- /src/client/components/asset_limits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "asset_limits.hpp" 3 | #include "game/game.hpp" 4 | 5 | namespace asset_limits 6 | { 7 | void resize(game::XAssetType type, int newSize) 8 | { 9 | auto structSize = game::DB_GetXAssetTypeSize(type); 10 | auto assetPool = &game::DB_XAssetPool[type]; 11 | // TODO: Support resizing assetPools to be less than current size 12 | if (assetPool != 0 && assetPool->itemCount < newSize) 13 | { 14 | auto newBlock = (game::AssetLink*)calloc(newSize - assetPool->itemCount, structSize); 15 | if (newBlock != 0) 16 | { 17 | game::AssetLink* blockPtr = (game::AssetLink*)assetPool->pool; 18 | game::AssetLink* nextBlockPtr = newBlock; 19 | auto size_c = newSize - 1; 20 | do 21 | { 22 | if (!blockPtr->next) 23 | { 24 | blockPtr->next = nextBlockPtr; 25 | blockPtr = nextBlockPtr; 26 | nextBlockPtr = (game::AssetLink*)((uint8_t*)nextBlockPtr + structSize); 27 | } 28 | else 29 | { 30 | blockPtr = (game::AssetLink*)((uint8_t*)blockPtr + structSize); 31 | } 32 | --size_c; 33 | } while (size_c); 34 | assetPool->itemCount = newSize; 35 | } 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/client/components/asset_limits.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace asset_limits 4 | { 5 | void resize(game::XAssetType type, int newSize); 6 | } -------------------------------------------------------------------------------- /src/client/components/axios.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "loader/component_loader.hpp" 3 | #include "havok/hks_api.hpp" 4 | #include "havok/lua_api.hpp" 5 | 6 | namespace axios 7 | { 8 | int get(lua::lua_State* s) 9 | { 10 | auto url = lua::lua_tostring(s, 1); 11 | 12 | http::Request request{ url }; 13 | const auto response = request.send("GET"); 14 | 15 | const auto responseBody = std::string{ response.body.begin(), response.body.end() }; 16 | lua::lua_pushstring(s, responseBody.c_str()); 17 | 18 | return 1; 19 | } 20 | 21 | int post(lua::lua_State* s) 22 | { 23 | auto url = lua::lua_tostring(s, 1); 24 | auto body = lua::lua_tostring(s, 2); 25 | 26 | http::Request request{ url }; 27 | const auto response = request.send("POST", body, { 28 | {"Content-Type", "application/json"} 29 | }); 30 | 31 | const auto responseBody = std::string{ response.body.begin(), response.body.end() }; 32 | lua::lua_pushstring(s, responseBody.c_str()); 33 | 34 | return 1; 35 | } 36 | 37 | class component final : public component_interface 38 | { 39 | public: 40 | void lua_start() override 41 | { 42 | const lua::luaL_Reg AxiosLibrary[] = 43 | { 44 | {"Get", get}, 45 | {"Post", post}, 46 | {nullptr, nullptr}, 47 | }; 48 | hks::hksI_openlib(game::UI_luaVM, "Axios", AxiosLibrary, 0, 1); 49 | } 50 | }; 51 | } 52 | 53 | REGISTER_COMPONENT(axios::component) -------------------------------------------------------------------------------- /src/client/components/bullet_depletion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "loader/component_loader.hpp" 3 | 4 | #include "game/game.hpp" 5 | #include "utils/string.hpp" 6 | 7 | namespace bullet_depletion 8 | { 9 | utils::hook::detour cg_updateviewmodeldynamicbones_hook; 10 | utils::hook::detour CG_PlayRumbleOnEntity_hook; 11 | 12 | static bool bullet_depletion_enabled[2][2] = { {true, true}, {true, true} }; 13 | static bool bullet_depletion_reload_mode_enabled[2][2] = { {false, false}, {false, false} }; 14 | 15 | static const game::ScrString_t disable_bullet_depletion_right_str = game::GScr_AllocString("disable bullet depletion right"); 16 | static const game::ScrString_t enable_bullet_depletion_right_str = game::GScr_AllocString("enable bullet depletion right"); 17 | static const game::ScrString_t disable_reload_bullet_depletion_right_str = game::GScr_AllocString("disable reload mode bullet depletion right"); 18 | static const game::ScrString_t enable_reload_bullet_depletion_right_str = game::GScr_AllocString("enable reload mode bullet depletion right"); 19 | static const game::ScrString_t disable_bullet_depletion_left_str = game::GScr_AllocString("disable bullet depletion left"); 20 | static const game::ScrString_t enable_bullet_depletion_left_str = game::GScr_AllocString("enable bullet depletion left"); 21 | static const game::ScrString_t disable_reload_bullet_depletion_left_str = game::GScr_AllocString("disable reload mode bullet depletion left"); 22 | static const game::ScrString_t enable_reload_bullet_depletion_left_str = game::GScr_AllocString("enable reload mode bullet depletion left"); 23 | 24 | static std::vector bullet_depletion_notes 25 | { 26 | disable_bullet_depletion_right_str, 27 | enable_bullet_depletion_right_str, 28 | disable_reload_bullet_depletion_right_str, 29 | enable_reload_bullet_depletion_right_str, 30 | disable_bullet_depletion_left_str, 31 | enable_bullet_depletion_left_str, 32 | disable_reload_bullet_depletion_left_str, 33 | enable_reload_bullet_depletion_left_str 34 | }; 35 | 36 | enum handType : BYTE 37 | { 38 | HAND_RIGHT = 0x0, 39 | HAND_LEFT = 0x1 40 | }; 41 | 42 | void handle_bullet_depletion(game::LocalClientNum_t localClientNum, void* ps, void* obj, void* weapon, handType handType) 43 | { 44 | int clipSize = game::BG_GetClipSize(weapon); 45 | int ammoInClip = game::BG_GetAmmoInClip(ps, weapon); 46 | if (bullet_depletion_reload_mode_enabled[localClientNum][handType]) 47 | ammoInClip += game::BG_GetTotalAmmoReserve(ps, weapon); 48 | 49 | int i = 0; 50 | while (i < clipSize) 51 | { 52 | game::ScrString_t tname = game::GScr_AllocString(utils::string::va("tag_bullet_deplete_sqtl_%02d_animate%s", i, handType == handType::HAND_LEFT ? "_le" : "")); 53 | game::BoneIndex bone; 54 | if (game::DObjGetBoneIndex(obj, tname, &bone, -1)) 55 | { 56 | if (ammoInClip <= i) 57 | { 58 | game::vec3_t newOrigin = { 0, 0, -100000 }; 59 | game::vec3_t angles = { 0, 0, 0 }; 60 | int partBits[12]; 61 | game::PLmemset(partBits, 255LL, 48LL); 62 | game::DObjSetLocalTag(obj, partBits, bone, &newOrigin, &angles); 63 | } 64 | } 65 | else 66 | { 67 | // No bone for depletion 68 | break; 69 | } 70 | i++; 71 | } 72 | 73 | i = 0; 74 | while (i < clipSize) 75 | { 76 | game::ScrString_t tname = game::GScr_AllocString(utils::string::va("tag_bullet_deplete_swap_%02d_animate%s", i, handType == handType::HAND_LEFT ? "_le" : "")); 77 | game::BoneIndex bone; 78 | if (game::DObjGetBoneIndex(obj, tname, &bone, -1)) 79 | { 80 | if (ammoInClip != i) 81 | { 82 | game::vec3_t newOrigin = { 0, 0, -100000 }; 83 | game::vec3_t angles = { 0, 0, 0 }; 84 | int partBits[12]; 85 | game::PLmemset(partBits, 255LL, 48LL); 86 | game::DObjSetLocalTag(obj, partBits, bone, &newOrigin, &angles); 87 | } 88 | } 89 | else 90 | { 91 | // No bone for depletion 92 | break; 93 | } 94 | i++; 95 | } 96 | } 97 | 98 | void cg_updateviewmodeldynamicbones_internal(game::cg_t* cgameGlob, void* ps, void* obj, void* weapon, void* cent) 99 | { 100 | cg_updateviewmodeldynamicbones_hook.invoke(cgameGlob, ps, obj, weapon, cent); 101 | 102 | if (!cgameGlob) 103 | return; 104 | 105 | if (!obj || !game::Sys_IsMainThread()) 106 | return; 107 | 108 | auto localClientNum = game::DObjGetLocalClientIndex(obj); 109 | 110 | if (bullet_depletion_enabled[localClientNum][handType::HAND_RIGHT]) 111 | { 112 | handle_bullet_depletion(localClientNum, ps, obj, weapon, handType::HAND_RIGHT); 113 | } 114 | if (bullet_depletion_enabled[localClientNum][handType::HAND_LEFT] && game::BG_IsDualWield(weapon)) 115 | { 116 | auto leftWeapon = game::BG_GetDualWieldWeapon(weapon); 117 | handle_bullet_depletion(localClientNum, ps, obj, leftWeapon, handType::HAND_LEFT); 118 | } 119 | } 120 | 121 | void CG_PlayRumbleOnEntity_internal(game::LocalClientNum_t localClientNum, game::ScrString_t rumbleName, int entityNum) 122 | { 123 | // if it's a regular track proceed as normal 124 | if (std::find(bullet_depletion_notes.begin(), bullet_depletion_notes.end(), rumbleName) == bullet_depletion_notes.end()) 125 | return CG_PlayRumbleOnEntity_hook.invoke(localClientNum, rumbleName, entityNum); 126 | 127 | auto isLeftHand = rumbleName != enable_bullet_depletion_right_str && rumbleName != disable_bullet_depletion_right_str && 128 | rumbleName != enable_reload_bullet_depletion_right_str && rumbleName != disable_reload_bullet_depletion_right_str; 129 | 130 | if (rumbleName == enable_bullet_depletion_right_str || rumbleName == enable_bullet_depletion_left_str) 131 | { 132 | bullet_depletion_enabled[localClientNum][isLeftHand] = true; 133 | } 134 | else if (rumbleName == disable_bullet_depletion_right_str || rumbleName == disable_bullet_depletion_left_str) 135 | { 136 | bullet_depletion_enabled[localClientNum][isLeftHand] = false; 137 | } 138 | else if (rumbleName == enable_reload_bullet_depletion_right_str || rumbleName == enable_reload_bullet_depletion_left_str) 139 | { 140 | bullet_depletion_reload_mode_enabled[localClientNum][isLeftHand] = true; 141 | } 142 | else if (rumbleName == disable_reload_bullet_depletion_right_str || rumbleName == disable_reload_bullet_depletion_left_str) 143 | { 144 | bullet_depletion_reload_mode_enabled[localClientNum][isLeftHand] = false; 145 | } 146 | } 147 | 148 | class component final : public component_interface 149 | { 150 | public: 151 | void start_hooks() override 152 | { 153 | cg_updateviewmodeldynamicbones_hook.create(REBASE(0x14126EE90), &cg_updateviewmodeldynamicbones_internal); 154 | CG_PlayRumbleOnEntity_hook.create(REBASE(0x1409E6C90), &CG_PlayRumbleOnEntity_internal); 155 | } 156 | 157 | void destroy_hooks() override 158 | { 159 | cg_updateviewmodeldynamicbones_hook.clear(); 160 | CG_PlayRumbleOnEntity_hook.clear(); 161 | } 162 | }; 163 | } 164 | 165 | REGISTER_COMPONENT(bullet_depletion::component) -------------------------------------------------------------------------------- /src/client/components/console.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "loader/component_loader.hpp" 3 | #include "console.hpp" 4 | #include "havok/hks_api.hpp" 5 | #include "havok/lua_api.hpp" 6 | #include "script/builtins.hpp" 7 | #include "utils/string.hpp" 8 | #include 9 | 10 | namespace console 11 | { 12 | void print(std::string msg) 13 | { 14 | #ifdef DEBUG 15 | game::minlog.WriteLine(utils::string::va("Print: %s", msg.c_str())); 16 | #endif 17 | msg = "^7" + msg + "\n"; 18 | game::Com_Printf(game::consoleChannel_e::CON_CHANNEL_DONT_FILTER, game::consoleLabel_e::CON_LABEL_DEFAULT, msg.c_str()); 19 | } 20 | 21 | void print_info(std::string msg) 22 | { 23 | #ifdef DEBUG 24 | game::minlog.WriteLine(utils::string::va("print_info: %s", msg.c_str())); 25 | #endif 26 | msg = "^4" + msg + "\n"; 27 | game::Com_Printf(game::consoleChannel_e::CON_CHANNEL_DONT_FILTER, game::consoleLabel_e::CON_LABEL_DEFAULT, msg.c_str()); 28 | } 29 | 30 | void print_error(std::string msg) 31 | { 32 | #ifdef DEBUG 33 | game::minlog.WriteLine(utils::string::va("print_error: %s", msg.c_str())); 34 | #endif 35 | if (game::I_stristr(msg.c_str(), "error")) 36 | msg = "^1" + msg + "\n"; 37 | else 38 | msg = "^1Error: " + msg + "\n"; 39 | 40 | game::Com_Printf(game::consoleChannel_e::CON_CHANNEL_DONT_FILTER, game::consoleLabel_e::CON_LABEL_DEFAULT, msg.c_str()); 41 | } 42 | 43 | void print_warning(std::string msg) 44 | { 45 | #ifdef DEBUG 46 | game::minlog.WriteLine(utils::string::va("print_warning: %s", msg.c_str())); 47 | #endif 48 | msg = "^3" + msg + "\n"; 49 | game::Com_Printf(game::consoleChannel_e::CON_CHANNEL_DONT_FILTER, game::consoleLabel_e::CON_LABEL_DEFAULT, msg.c_str()); 50 | } 51 | 52 | int print(lua::lua_State* s) 53 | { 54 | if (hks::hksi_lua_gettop(s) != 1) 55 | { 56 | lua::luaL_error(s, "Print required 1 argment. Called with %i argument(s). Arguments expected: ( const char * info )", hks::hksi_lua_gettop(s)); 57 | } 58 | /*if (!hks::hksi_lua_isstring(s, 1)) 59 | { 60 | auto type = hks::hksi_lua_type(s, 1); 61 | lua::luaL_error(s, "Print requires argment 1 ( const char * info ) to be of type const char *. Received type %s.", hks::TypeName[type + 1]); 62 | }*/ 63 | auto text = lua::lua_tostring(s, 1); 64 | print(text); 65 | return 1; 66 | } 67 | 68 | int print_info(lua::lua_State* s) 69 | { 70 | auto text = lua::lua_tostring(s, 1); 71 | print_info(text); 72 | return 1; 73 | } 74 | 75 | int print_error(lua::lua_State* s) 76 | { 77 | auto text = lua::lua_tostring(s, 1); 78 | print_error(text); 79 | return 1; 80 | } 81 | 82 | int print_warning(lua::lua_State* s) 83 | { 84 | auto text = lua::lua_tostring(s, 1); 85 | print_warning(text); 86 | return 1; 87 | } 88 | 89 | utils::hook::detour Com_EventLoop_hook; 90 | static bool console_init = false; 91 | 92 | int show_external_console(lua::lua_State* s) 93 | { 94 | if (!console_init) 95 | { 96 | game::Sys_ShowConsole(); 97 | console_init = true; 98 | } 99 | return 1; 100 | } 101 | 102 | void Com_EventLoop(bool poll) 103 | { 104 | Com_EventLoop_hook.invoke(poll); 105 | 106 | if (!console_init) 107 | return; 108 | 109 | MSG msg{}; 110 | 111 | while (PeekMessageA(&msg, nullptr, 0, 0, 0)) 112 | { 113 | if (GetMessageA(&msg, nullptr, 0, 0)) 114 | { 115 | TranslateMessage(&msg); 116 | DispatchMessageA(&msg); 117 | } 118 | } 119 | } 120 | 121 | utils::hook::detour Dvar_GetDebugName_hook; 122 | 123 | const char* Dvar_GetDebugName(const game::dvar_t* dvar) 124 | { 125 | auto result = Dvar_GetDebugName_hook.invoke(dvar); 126 | 127 | auto it = game::dvarHashMap_s.find(dvar->name); 128 | if (it != game::dvarHashMap_s.end()) 129 | { 130 | return it->second.c_str(); 131 | } 132 | 133 | return result; 134 | } 135 | 136 | bool Dvar_IsSessionModeBaseDvar(const game::dvar_t* dvar) 137 | { 138 | return dvar->type == game::DVAR_TYPE_SESSIONMODE_BASE_DVAR; 139 | } 140 | 141 | bool Dvar_IsSessionModeSpecificDvar(const game::dvar_t* dvar) 142 | { 143 | return (dvar->flags & 0x8000) != 0; 144 | } 145 | 146 | utils::hook::detour Dvar_ForEachName_1_hook; 147 | utils::hook::detour Dvar_ForEachName_2_hook; 148 | 149 | //void Dvar_ForEachName_Complete(void (*callback)(const char*)) // this is for CompleteCommand only 150 | //{ 151 | // const char* DebugName; 152 | // game::dvar_t* dvar; 153 | // int dvarIter; 154 | 155 | // for (dvarIter = 0; dvarIter < *game::g_dvarCount; ++dvarIter) 156 | // { 157 | // dvar = &*game::s_dvarPool[dvarIter]; 158 | // if ((!game::Com_SessionMode_IsMode(game::MODE_COUNT) || !Dvar_IsSessionModeBaseDvar(dvar)) 159 | // && !Dvar_IsSessionModeSpecificDvar(dvar)) 160 | // { 161 | // DebugName = Dvar_GetDebugName(dvar); 162 | // callback(DebugName); 163 | // } 164 | // } 165 | //} 166 | 167 | void Dvar_ForEachName_Match(game::LocalClientNum_t localClientNum, void (*callback)(game::LocalClientNum_t, const char*)) 168 | { 169 | for (int dvarIter = 0; dvarIter < *game::g_dvarCount; ++dvarIter) 170 | { 171 | //TODO: don't ask 172 | auto dvar = reinterpret_cast(&game::s_dvarPool[160 * dvarIter]); 173 | 174 | if ((!game::Com_SessionMode_IsMode(game::MODE_COUNT) || !Dvar_IsSessionModeBaseDvar(dvar)) 175 | && !Dvar_IsSessionModeSpecificDvar(dvar)) 176 | { 177 | const char* DebugName = Dvar_GetDebugName(dvar); 178 | callback(localClientNum, DebugName); 179 | } 180 | } 181 | } 182 | 183 | utils::hook::detour Dvar_CanSetConfigDvar_hook; 184 | 185 | bool Dvar_CanSetConfigDvar(const game::dvar_t* dvar) 186 | { 187 | //TODO: ??? 188 | return true; 189 | } 190 | 191 | class component final : public component_interface 192 | { 193 | public: 194 | void lua_start() override 195 | { 196 | const lua::luaL_Reg ConsoleLibrary[] = 197 | { 198 | {"Print", print}, 199 | {"PrintInfo", print_info}, 200 | {"PrintError", print_error}, 201 | {"PrintWarning", print_warning}, 202 | {"ShowExternalConsole", show_external_console}, 203 | {nullptr, nullptr}, 204 | }; 205 | hks::hksI_openlib(game::UI_luaVM, "Console", ConsoleLibrary, 0, 1); 206 | } 207 | 208 | void start_hooks() override 209 | { 210 | utils::hook::nop(REBASE(0x1420EEFB0), 6); // Cmd_List_f, remove i->unknown 211 | utils::hook::nop(REBASE(0x1420EDED1), 10); // Cmd_ExecuteSingleCommandInternal, remove next->unknown 212 | utils::hook::nop(REBASE(0x1420EDF90), 6); // Cmd_ForEach, remove i->unknown 213 | utils::hook::nop(REBASE(0x142152652), 13); // Com_DvarDumpSingle, remove Dvar_GetFlags call 214 | utils::hook::nop(REBASE(0x1422B92B0), 6); // Dvar_CanChangeValue, remove (dvar->flags & 1) != 0 215 | utils::hook::nop(REBASE(0x142152973), 7); // Dvar_Command, remove (dvar->flags & 1) == 0 216 | //utils::hook::nop(REBASE(0x1422BD82A), 16); // Dvar_ForEachName_Match, remove (dvar->flags & 1) != 0, don't need rewrote function 217 | utils::hook::nop(REBASE(0x142152C80), 13); // Dvar_ListSingle, remove Dvar_GetFlags call 218 | utils::hook::nop(REBASE(0x142153233), 9); // Dvar_ToggleInternal, remove (dvar->flags & 1) == 0 219 | 220 | Com_EventLoop_hook.create(REBASE(0x1420F94B0), &Com_EventLoop); 221 | Dvar_CanSetConfigDvar_hook.create(REBASE(0x1422B92F0), &Dvar_CanSetConfigDvar); 222 | //Dvar_ForEachName_1_hook.create(0x22BD890, &Dvar_ForEachName_Complete); 223 | Dvar_ForEachName_2_hook.create(REBASE(0x1422BD7E0), &Dvar_ForEachName_Match); 224 | Dvar_GetDebugName_hook.create(REBASE(0x1422BDCB0), &Dvar_GetDebugName); 225 | } 226 | 227 | void destroy_hooks() override 228 | { 229 | Com_EventLoop_hook.clear(); 230 | Dvar_CanSetConfigDvar_hook.clear(); 231 | //Dvar_ForEachName_1_hook.clear(); 232 | Dvar_ForEachName_2_hook.clear(); 233 | Dvar_GetDebugName_hook.clear(); 234 | } 235 | }; 236 | } 237 | 238 | REGISTER_COMPONENT(console::component) -------------------------------------------------------------------------------- /src/client/components/console.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace console 4 | { 5 | void print_info(std::string msg); 6 | void print_error(std::string msg); 7 | void print_warning(std::string msg); 8 | } -------------------------------------------------------------------------------- /src/client/components/discord.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "loader/component_loader.hpp" 3 | #include "scheduler.hpp" 4 | #include "game/game.hpp" 5 | #include "game/dvars.hpp" 6 | #include "havok/hks_api.hpp" 7 | #include "havok/lua_api.hpp" 8 | 9 | #include 10 | 11 | #include 12 | 13 | namespace discord 14 | { 15 | DiscordRichPresence discord_presence; 16 | 17 | int roundsPlayed; 18 | int playerScore; 19 | int enemyScore; 20 | bool isIngame = false; 21 | 22 | void update_discord() 23 | { 24 | Discord_RunCallbacks(); 25 | 26 | if (!isIngame) 27 | { 28 | discord_presence.details = game::Com_SessionMode_IsMode(game::eModes::MODE_CAMPAIGN) ? "Campaign" : game::Com_SessionMode_IsMode(game::eModes::MODE_MULTIPLAYER) ? "Multiplayer" : "Zombies"; 29 | discord_presence.state = "Lobby"; 30 | roundsPlayed = 0; 31 | playerScore = 0; 32 | enemyScore = 0; 33 | 34 | discord_presence.startTimestamp = 0; 35 | 36 | discord_presence.largeImageKey = "t7overcharged"; 37 | } 38 | else 39 | { 40 | auto map = game::UI_SafeTranslateString(game::Com_GameInfo_GetMapRef(dvars::ui_mapname->current.string)); 41 | 42 | if (game::Com_SessionMode_IsMode(game::eModes::MODE_CAMPAIGN)) 43 | { 44 | discord_presence.state = "In-Game"; 45 | discord_presence.details = map; 46 | } 47 | else if (game::Com_SessionMode_IsMode(game::eModes::MODE_MULTIPLAYER)) 48 | { 49 | auto gametype = game::UI_SafeTranslateString(game::Com_GameInfo_GetGameTypeRef(dvars::ui_gametype->current.string)); 50 | discord_presence.details = utils::string::va("%s on %s", gametype, map); 51 | discord_presence.state = utils::string::va("%d - %d", playerScore, enemyScore); 52 | } 53 | else 54 | { 55 | discord_presence.state = utils::string::va("Round %d", roundsPlayed); 56 | discord_presence.details = map; 57 | } 58 | 59 | 60 | if (!discord_presence.startTimestamp) 61 | { 62 | discord_presence.startTimestamp = std::chrono::duration_cast( 63 | std::chrono::system_clock::now().time_since_epoch()).count(); 64 | } 65 | 66 | discord_presence.largeImageKey = dvars::ui_mapname->current.string; 67 | } 68 | 69 | discord_presence.partySize = game::LobbySession_GetClientCount(0, game::LobbyClientType::LOBBY_CLIENT_TYPE_ALL); 70 | discord_presence.partyMax = dvars::com_maxclients->current.integer; 71 | 72 | Discord_UpdatePresence(&discord_presence); 73 | } 74 | 75 | int enable(lua::lua_State* s); 76 | 77 | int set_rounds_played(lua::lua_State* s) 78 | { 79 | roundsPlayed = lua::lua_tonumber(s, 1); 80 | return 1; 81 | } 82 | 83 | int set_playerscore(lua::lua_State* s) 84 | { 85 | playerScore = lua::lua_tonumber(s, 1); 86 | return 1; 87 | } 88 | 89 | int set_enemyscore(lua::lua_State* s) 90 | { 91 | enemyScore = lua::lua_tonumber(s, 1); 92 | return 1; 93 | } 94 | 95 | class component final : public component_interface 96 | { 97 | public: 98 | static void start_discord_rpc(const char* applicationId) 99 | { 100 | if (initialized_) 101 | return; 102 | 103 | DiscordEventHandlers handlers; 104 | ZeroMemory(&handlers, sizeof(handlers)); 105 | handlers.ready = ready; 106 | handlers.errored = errored; 107 | handlers.disconnected = errored; 108 | handlers.joinGame = nullptr; 109 | handlers.spectateGame = nullptr; 110 | handlers.joinRequest = nullptr; 111 | 112 | Discord_Initialize(applicationId, &handlers, 1, nullptr); 113 | scheduler::loop(update_discord, scheduler::pipeline::async, 10s); 114 | 115 | initialized_ = true; 116 | } 117 | 118 | void lua_start() override 119 | { 120 | const lua::luaL_Reg HotReloadLibrary[] = 121 | { 122 | {"Enable", enable}, 123 | {"SetRoundsPlayed", set_rounds_played}, 124 | {"SetPlayerScore", set_playerscore}, 125 | {"SetEnemyScore", set_enemyscore}, 126 | {nullptr, nullptr}, 127 | }; 128 | hks::hksI_openlib(game::UI_luaVM, "DiscordRPC", HotReloadLibrary, 0, 1); 129 | } 130 | 131 | void start_hooks() override 132 | { 133 | isIngame = true; 134 | std::string raw_lua = 135 | "LUI.roots.UIRoot0:subscribeToGlobalModel(0, 'GameScore', 'roundsPlayed', function(model) " 136 | "local roundsPlayed = Engine.GetModelValue(model); " 137 | "if roundsPlayed then " 138 | "DiscordRPC.SetRoundsPlayed(roundsPlayed - 1); " 139 | "end; " 140 | "end); " 141 | "LUI.roots.UIRoot0:subscribeToGlobalModel(0, 'GameScore', 'playerScore', function(model) " 142 | "local playerScore = Engine.GetModelValue(model); " 143 | "if playerScore and not Engine.IsVisibilityBitSet( 0, Enum.UIVisibilityBit.BIT_IN_KILLCAM ) then " 144 | "DiscordRPC.SetPlayerScore(playerScore); " 145 | "end; " 146 | "end); " 147 | "LUI.roots.UIRoot0:subscribeToGlobalModel(0, 'GameScore', 'enemyScore', function(model) " 148 | "local enemyScore = Engine.GetModelValue(model); " 149 | "if enemyScore and not Engine.IsVisibilityBitSet( 0, Enum.UIVisibilityBit.BIT_IN_KILLCAM ) then " 150 | "DiscordRPC.SetEnemyScore(enemyScore); " 151 | "end; " 152 | "end); "; 153 | hks::execute_raw_lua(raw_lua, "DiscordScoreModels"); 154 | } 155 | 156 | void destroy_hooks() override 157 | { 158 | isIngame = false; 159 | } 160 | 161 | private: 162 | static inline bool initialized_ = false; 163 | 164 | static void ready(const DiscordUser*) 165 | { 166 | ZeroMemory(&discord_presence, sizeof(discord_presence)); 167 | 168 | discord_presence.instance = 1; 169 | 170 | Discord_UpdatePresence(&discord_presence); 171 | } 172 | 173 | static void errored(const int error_code, const char* message) 174 | { 175 | printf("Discord: (%i) %s", error_code, message); 176 | } 177 | }; 178 | 179 | 180 | int enable(lua::lua_State* s) 181 | { 182 | auto applicationId = lua::lua_tostring(s, 1); 183 | discord::component::start_discord_rpc(applicationId); 184 | return 1; 185 | } 186 | } 187 | 188 | REGISTER_COMPONENT(discord::component) -------------------------------------------------------------------------------- /src/client/components/fastfiles.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "loader/component_loader.hpp" 3 | 4 | #include "game/game.hpp" 5 | #include "utils/hook.hpp" 6 | #include "utils/string.hpp" 7 | 8 | namespace fastfiles 9 | { 10 | utils::hook::detour db_try_load_x_file_internal_hook; 11 | 12 | void db_try_load_x_file_internal(const char* zoneName, const int zone_flags, const int is_base_map) 13 | { 14 | game::minlog.WriteLine(utils::string::va("Loading fastfile %s\n", zoneName)); 15 | return db_try_load_x_file_internal_hook.invoke(zoneName, zone_flags, is_base_map); 16 | } 17 | 18 | class component final : public component_interface 19 | { 20 | public: 21 | void start_hooks() override 22 | { 23 | db_try_load_x_file_internal_hook.create(REBASE(0x141425010), &db_try_load_x_file_internal); 24 | } 25 | 26 | void destroy_hooks() override 27 | { 28 | db_try_load_x_file_internal_hook.clear(); 29 | } 30 | }; 31 | } 32 | 33 | #ifdef DEBUG 34 | REGISTER_COMPONENT(fastfiles::component) 35 | #endif -------------------------------------------------------------------------------- /src/client/components/hotreload.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "loader/component_loader.hpp" 3 | #include "havok/hks_api.hpp" 4 | #include "havok/lua_api.hpp" 5 | #include "game/dvars.hpp" 6 | 7 | #include "utils/io.hpp" 8 | #include "utils/string.hpp" 9 | #include "utils/thread.hpp" 10 | #include "utils/hook.hpp" 11 | 12 | namespace hotreload 13 | { 14 | // Folder where we are going to be looking for lua files 15 | static std::string reloadPath; 16 | // Map that stores when each lua files was last edited/inserted into the vm 17 | static std::map luaFilesMap = {}; 18 | // Thread that run the hotreload every second 19 | bool hot_reload_running = false; 20 | std::thread hot_reload_thread; 21 | 22 | std::vector search_for_new_files() 23 | { 24 | std::vector newFiles; 25 | 26 | for (auto& file : std::filesystem::recursive_directory_iterator(reloadPath)) { 27 | auto extension = file.path().extension(); 28 | if (extension != ".lua") 29 | continue; 30 | 31 | std::string filePath = file.path().string(); 32 | auto modifiedTime = std::filesystem::last_write_time(file); 33 | if (luaFilesMap.count(filePath) == 0) 34 | { 35 | luaFilesMap.insert({ filePath, modifiedTime }); 36 | newFiles.push_back(file); 37 | } 38 | else if (luaFilesMap[filePath] < modifiedTime) 39 | { 40 | luaFilesMap[filePath] = modifiedTime; 41 | newFiles.push_back(file); 42 | } 43 | } 44 | 45 | return newFiles; 46 | } 47 | 48 | void UI_DebugReload(const char* rootName, lua::lua_State* luaVM) 49 | { 50 | /*game::LUIElement* element; 51 | game::LUIScopedEvent luaEventStruct; 52 | element = game::UI_GetRootElement(rootName, luaVM); 53 | if (element) 54 | { 55 | element->currentAnimationState.flags &= 0xFFFFFFFFFFFFFFFDLL; 56 | game::GetLUIScopedEvent(&luaEventStruct, luaVM, rootName, "debug_reload"); 57 | while (!luaEventStruct._finished) 58 | { 59 | lua::Lua_SetTableString("mapname", game::Dvar_GetString(dvars::sv_mapname), luaEventStruct._vm); 60 | luaEventStruct._finished = 1; 61 | } 62 | game::ExecuteLUIScopedEvent(&luaEventStruct); 63 | }*/ 64 | auto mapname = game::Dvar_GetString(dvars::sv_mapname); 65 | auto eventCode = utils::string::va("LUI.roots.%s:processEvent( { name = 'debug_reload', mapname = '%s' } )", rootName, mapname); 66 | hks::execute_raw_lua(eventCode, "DebugReload"); 67 | } 68 | 69 | bool refreshGameplayRoots = false; 70 | 71 | int check_for_new_files(lua::lua_State* s) 72 | { 73 | std::vector newFiles = search_for_new_files(); 74 | 75 | if (newFiles.empty()) 76 | return 0; 77 | 78 | game::minlog.WriteLine(utils::string::va("Found: %d files to reload", newFiles.size())); 79 | 80 | for (unsigned int i = 0; i < newFiles.size(); ++i) 81 | { 82 | auto file = newFiles[i]; 83 | std::string filePath = file.path().string(); 84 | 85 | // Read the raw lua file 86 | std::string data; 87 | utils::io::read_file(filePath.c_str(), &data); 88 | // Get a proper chunkname 89 | auto fileName = filePath.erase(0, reloadPath.size()).c_str(); 90 | 91 | // Execute the lua from the rawfile 92 | if (hks::execute_raw_lua(data, fileName)) 93 | game::minlog.WriteLine(utils::string::va("Error reloading file: %s", fileName)); 94 | else 95 | game::minlog.WriteLine(utils::string::va("Reloaded file: %s", fileName)); 96 | } 97 | 98 | UI_DebugReload("UIRootFull", game::UI_luaVM); 99 | if (refreshGameplayRoots) 100 | { 101 | UI_DebugReload("UIRoot0", game::UI_luaVM); 102 | UI_DebugReload("UIRoot1", game::UI_luaVM); 103 | } 104 | 105 | return 1; 106 | } 107 | 108 | int start_hot_reload(lua::lua_State* s) 109 | { 110 | reloadPath = lua::lua_tostring(s, 1); 111 | 112 | check_for_new_files(s); 113 | 114 | std::string luaThreadCode = "local UIRootFull = LUI.roots.UIRootFull;" 115 | "UIRootFull.HUDRefreshTimer = LUI.UITimer.newElementTimer(1000, false, function()" 116 | "HotReload.CheckForNewFiles();" 117 | "end);" 118 | "UIRootFull:addElement(UIRootFull.HUDRefreshTimer);"; 119 | hks::execute_raw_lua(luaThreadCode, "HotReloadThread"); 120 | // Tried using a new thread to run this but that crashes the game when making lua calls 121 | // Another solution that doing loops in lua? 122 | /*/if (!hot_reload_running) 123 | { 124 | hot_reload_thread = utils::thread::create_named_thread("Lua Hot Reload", [] 125 | { 126 | while (hot_reload_running) { 127 | check_for_new_files(); 128 | std::this_thread::sleep_for(1000ms); 129 | } 130 | std::this_thread::yield(); 131 | }); 132 | hot_reload_running = true; 133 | }*/ 134 | hot_reload_running = true; 135 | 136 | return 1; 137 | } 138 | 139 | class component final : public component_interface 140 | { 141 | public: 142 | void lua_start() override 143 | { 144 | const lua::luaL_Reg HotReloadLibrary[] = 145 | { 146 | {"Start", start_hot_reload}, 147 | {"CheckForNewFiles", check_for_new_files}, 148 | {nullptr, nullptr}, 149 | }; 150 | hks::hksI_openlib(game::UI_luaVM, "HotReload", HotReloadLibrary, 0, 1); 151 | } 152 | 153 | void start_hooks() override 154 | { 155 | refreshGameplayRoots = true; 156 | if (hot_reload_running) 157 | { 158 | UI_DebugReload("UIRoot0", game::UI_luaVM); 159 | UI_DebugReload("UIRoot1", game::UI_luaVM); 160 | } 161 | } 162 | 163 | void destroy_hooks() override 164 | { 165 | refreshGameplayRoots = false; 166 | } 167 | }; 168 | } 169 | 170 | REGISTER_COMPONENT(hotreload::component) -------------------------------------------------------------------------------- /src/client/components/lua.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "loader/component_loader.hpp" 3 | 4 | #include "game/dvars.hpp" 5 | #include "havok/hks_api.hpp" 6 | #include "havok/lua_api.hpp" 7 | 8 | namespace lua 9 | { 10 | int remove(lua::lua_State* s) 11 | { 12 | if (dvars::ui_error_callstack_ship->flags == 0) 13 | return 1; 14 | 15 | dvars::ui_error_callstack_ship->flags = (game::dvarFlags_e)0; 16 | game::Dvar_SetFromStringByName("ui_error_callstack_ship", "1", true); 17 | 18 | dvars::ui_error_report_delay->flags = (game::dvarFlags_e)0; 19 | game::Dvar_SetFromStringByName("ui_error_report_delay", "0", true); 20 | 21 | return 0; 22 | } 23 | 24 | utils::hook::detour Lua_CoD_LuaStateManager_Interface_ErrorPrint_hook; 25 | 26 | void Lua_CoD_LuaStateManager_Interface_ErrorPrint(game::consoleLabel_e comLabel, const char* formatString, ...) 27 | { 28 | char string[4096]{}; 29 | va_list ap; 30 | 31 | va_start(ap, formatString); 32 | game::vsnprintf(string, 0x1000u, formatString, ap); 33 | string[4095] = 0; 34 | va_end(ap); 35 | 36 | game::Com_Printf(game::CON_CHANNEL_ERROR, game::CON_LABEL_LUA, "%s", string); 37 | } 38 | 39 | class component final : public component_interface 40 | { 41 | public: 42 | void lua_start() override 43 | { 44 | const lua::luaL_Reg UIErrorHashLibrary[] = 45 | { 46 | {"Remove", remove}, 47 | {nullptr, nullptr}, 48 | }; 49 | hks::hksI_openlib(game::UI_luaVM, "UIErrorHash", UIErrorHashLibrary, 0, 1); 50 | } 51 | 52 | void start_hooks() override 53 | { 54 | Lua_CoD_LuaStateManager_Interface_ErrorPrint_hook.create(REBASE(0x141F132B0), &Lua_CoD_LuaStateManager_Interface_ErrorPrint); 55 | } 56 | 57 | void destroy_hooks() override 58 | { 59 | Lua_CoD_LuaStateManager_Interface_ErrorPrint_hook.clear(); 60 | } 61 | }; 62 | } 63 | 64 | REGISTER_COMPONENT(lua::component) -------------------------------------------------------------------------------- /src/client/components/scheduler.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "loader/component_loader.hpp" 3 | #include "scheduler.hpp" 4 | #include "game/game.hpp" 5 | #include 6 | #include 7 | #include 8 | 9 | namespace scheduler 10 | { 11 | namespace 12 | { 13 | struct task 14 | { 15 | std::function handler{}; 16 | std::chrono::milliseconds interval{}; 17 | std::chrono::high_resolution_clock::time_point last_call{}; 18 | }; 19 | 20 | using task_list = std::vector; 21 | 22 | class task_pipeline 23 | { 24 | public: 25 | void add(task&& task) 26 | { 27 | new_callbacks_.access([&task](task_list& tasks) 28 | { 29 | tasks.emplace_back(std::move(task)); 30 | }); 31 | } 32 | 33 | void execute() 34 | { 35 | callbacks_.access([&](task_list& tasks) 36 | { 37 | this->merge_callbacks(); 38 | 39 | for (auto i = tasks.begin(); i != tasks.end();) 40 | { 41 | const auto now = std::chrono::high_resolution_clock::now(); 42 | const auto diff = now - i->last_call; 43 | 44 | if (diff < i->interval) 45 | { 46 | ++i; 47 | continue; 48 | } 49 | 50 | i->last_call = now; 51 | 52 | const auto res = i->handler(); 53 | if (res == cond_end) 54 | { 55 | i = tasks.erase(i); 56 | } 57 | else 58 | { 59 | ++i; 60 | } 61 | } 62 | }); 63 | } 64 | 65 | private: 66 | utils::concurrency::container new_callbacks_; 67 | utils::concurrency::container callbacks_; 68 | 69 | void merge_callbacks() 70 | { 71 | callbacks_.access([&](task_list& tasks) 72 | { 73 | new_callbacks_.access([&](task_list& new_tasks) 74 | { 75 | tasks.insert(tasks.end(), std::move_iterator(new_tasks.begin()), std::move_iterator(new_tasks.end())); 76 | new_tasks = {}; 77 | }); 78 | }); 79 | } 80 | }; 81 | 82 | volatile bool kill = false; 83 | std::thread thread; 84 | task_pipeline pipelines[pipeline::count]; 85 | utils::hook::detour r_end_frame_hook; 86 | 87 | void execute(const pipeline type) 88 | { 89 | assert(type >= 0 && type < pipeline::count); 90 | pipelines[type].execute(); 91 | } 92 | 93 | void r_end_frame_stub() 94 | { 95 | execute(pipeline::renderer); 96 | r_end_frame_hook.invoke(); 97 | } 98 | 99 | void server_frame_stub() 100 | { 101 | //game::G_Glass_Update(); 102 | execute(pipeline::server); 103 | } 104 | 105 | void main_frame_stub() 106 | { 107 | execute(pipeline::main); 108 | //game::Com_Frame_Try_Block_Function(); 109 | } 110 | } 111 | 112 | void schedule(const std::function& callback, const pipeline type, 113 | const std::chrono::milliseconds delay) 114 | { 115 | assert(type >= 0 && type < pipeline::count); 116 | 117 | task task; 118 | task.handler = callback; 119 | task.interval = delay; 120 | task.last_call = std::chrono::high_resolution_clock::now(); 121 | 122 | pipelines[type].add(std::move(task)); 123 | } 124 | 125 | void loop(const std::function& callback, const pipeline type, 126 | const std::chrono::milliseconds delay) 127 | { 128 | schedule([callback]() 129 | { 130 | callback(); 131 | return cond_continue; 132 | }, type, delay); 133 | } 134 | 135 | void once(const std::function& callback, const pipeline type, 136 | const std::chrono::milliseconds delay) 137 | { 138 | schedule([callback]() 139 | { 140 | callback(); 141 | return cond_end; 142 | }, type, delay); 143 | } 144 | 145 | void on_game_initialized(const std::function& callback, const pipeline type, 146 | const std::chrono::milliseconds delay) 147 | { 148 | schedule([=]() 149 | { 150 | //const auto dw_init = game::environment::is_sp() || game::Live_SyncOnlineDataFlags(0) == 0; 151 | if (/*dw_init &&*/ game::Sys_IsDatabaseReady2()) 152 | { 153 | once(callback, type, delay); 154 | return cond_end; 155 | } 156 | 157 | return cond_continue; 158 | }, pipeline::main); 159 | } 160 | 161 | class component final : public component_interface 162 | { 163 | public: 164 | void post_start() override 165 | { 166 | thread = utils::thread::create_named_thread("Async Scheduler", []() 167 | { 168 | while (!kill) 169 | { 170 | execute(pipeline::async); 171 | std::this_thread::sleep_for(10ms); 172 | } 173 | }); 174 | } 175 | 176 | void start_hooks() override 177 | { 178 | r_end_frame_hook.create(REBASE(0x141CDAE90), scheduler::r_end_frame_stub); 179 | 180 | //utils::hook::call(SELECT_VALUE(0x1403BC922, 0x140413142), scheduler::main_frame_stub); 181 | //utils::hook::call(SELECT_VALUE(0x1403185FD, 0x1403A0AF9), scheduler::server_frame_stub); 182 | } 183 | 184 | void destroy_hooks() override 185 | { 186 | r_end_frame_hook.clear(); 187 | } 188 | 189 | void pre_destroy() override 190 | { 191 | kill = true; 192 | if (thread.joinable()) 193 | { 194 | thread.join(); 195 | } 196 | } 197 | }; 198 | } 199 | 200 | REGISTER_COMPONENT(scheduler::component) 201 | -------------------------------------------------------------------------------- /src/client/components/scheduler.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace scheduler 4 | { 5 | enum pipeline 6 | { 7 | // Asynchronuous pipeline, disconnected from the game 8 | async = 0, 9 | 10 | // The game's rendering pipeline 11 | renderer, 12 | 13 | // The game's server thread 14 | server, 15 | 16 | // The game's main thread 17 | main, 18 | 19 | count, 20 | }; 21 | 22 | static const bool cond_continue = false; 23 | static const bool cond_end = true; 24 | 25 | void schedule(const std::function& callback, pipeline type = pipeline::async, 26 | std::chrono::milliseconds delay = 0ms); 27 | void loop(const std::function& callback, pipeline type = pipeline::async, 28 | std::chrono::milliseconds delay = 0ms); 29 | void once(const std::function& callback, pipeline type = pipeline::async, 30 | std::chrono::milliseconds delay = 0ms); 31 | void on_game_initialized(const std::function& callback, pipeline type = pipeline::async, 32 | std::chrono::milliseconds delay = 0ms); 33 | } 34 | -------------------------------------------------------------------------------- /src/client/game/dvars.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define GET_DVAR(ptr) ((game::dvar_t*)((*(INT64*)(((uintptr_t)GetModuleHandle(NULL) + ptr))))) 4 | 5 | namespace dvars 6 | { 7 | game::dvar_t* ui_error_report = GET_DVAR(0x168F0EA8); 8 | game::dvar_t* ui_error_report_delay = GET_DVAR(0x168F0EB0); 9 | game::dvar_t* ui_error_callstack_ship = GET_DVAR(0x168EFCA0); 10 | 11 | game::dvar_t* sv_mapname = GET_DVAR(0x177C77D0); 12 | game::dvar_t* ui_mapname = GET_DVAR(0x179E1AC0); 13 | game::dvar_t* ui_gametype = GET_DVAR(0x179E1AD0); 14 | 15 | game::dvar_t* com_maxclients = GET_DVAR(0x168EF850); 16 | } -------------------------------------------------------------------------------- /src/client/game/dvars.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | namespace dvars 5 | { 6 | extern game::dvar_t* ui_error_report; 7 | extern game::dvar_t* ui_error_report_delay; 8 | extern game::dvar_t* ui_error_callstack_ship; 9 | 10 | extern game::dvar_t* sv_mapname; 11 | extern game::dvar_t* ui_mapname; 12 | extern game::dvar_t* ui_gametype; 13 | 14 | extern game::dvar_t* com_maxclients; 15 | } -------------------------------------------------------------------------------- /src/client/game/game.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "game.hpp" 3 | #include "dvars.hpp" 4 | #include "havok/hks_api.hpp" 5 | #include "havok/lua_api.hpp" 6 | #include "utils/string.hpp" 7 | #include "utils/io.hpp" 8 | #include "utils/hook.hpp" 9 | #include "utils/thread.hpp" 10 | #include "components/console.hpp" 11 | 12 | #include 13 | #include 14 | 15 | namespace game 16 | { 17 | uintptr_t base = (uintptr_t)GetModuleHandle(NULL); 18 | MinLog minlog = MinLog(); 19 | std::unordered_map dvarHashMap_s; 20 | 21 | void LoadDvarHashMap() 22 | { 23 | auto file = utils::io::read_file("dvar_hash_list.txt"); 24 | // remove carriage return because std::getline is lame 25 | file.erase(std::ranges::remove(file, '\r').begin(), file.end()); 26 | 27 | std::istringstream file_str{ file }; 28 | std::string line; 29 | 30 | while (std::getline(file_str, line, '\n')) 31 | { 32 | const auto separator = line.find(','); 33 | 34 | if (separator == std::string::npos) 35 | continue; 36 | 37 | // doing name (hash),debugName since we search for the hash instead 38 | const auto hashValue = strtoul(line.substr(separator + 1).c_str(), nullptr, 16); 39 | const auto debugName = line.substr(0, separator); 40 | 41 | dvarHashMap_s.emplace(std::make_pair(hashValue, debugName)); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/client/game/game.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "utils/minlog.hpp" 4 | 5 | namespace game 6 | { 7 | extern uintptr_t base; 8 | extern MinLog minlog; 9 | extern std::unordered_map dvarHashMap_s; 10 | 11 | void LoadDvarHashMap(); 12 | 13 | template 14 | class symbol 15 | { 16 | public: 17 | symbol(const uintptr_t address) 18 | : object_(reinterpret_cast(address)) 19 | { 20 | } 21 | 22 | T* get() const 23 | { 24 | return object_; 25 | } 26 | 27 | operator T* () const 28 | { 29 | return this->get(); 30 | } 31 | 32 | T* operator->() const 33 | { 34 | return this->get(); 35 | } 36 | 37 | private: 38 | T* object_; 39 | }; 40 | } 41 | #include "symbols.hpp" -------------------------------------------------------------------------------- /src/client/game/symbols.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define WEAK __declspec(selectany) 4 | 5 | namespace game 6 | { 7 | #define REBASE(address) (uintptr_t)((address - 0x140000000) + game::base) 8 | #define OFFSET(address) (uintptr_t)((address - 0x140000000) + (uintptr_t)GetModuleHandle(NULL)) 9 | 10 | /* BG */ 11 | WEAK symbol BG_GetAmmoInClip{ OFFSET(0x1426E7310) }; 12 | WEAK symbol BG_GetTotalAmmoReserve{ OFFSET(0x1426E7AB0) }; 13 | WEAK symbol BG_GetClipSize{ OFFSET(0x1426E75D0) }; 14 | WEAK symbol BG_IsLeftHandWeapon{ OFFSET(0x1426F4A90) }; 15 | WEAK symbol BG_IsDualWield{ OFFSET(0x1426F4820) }; 16 | WEAK symbol BG_GetDualWieldWeapon{ OFFSET(0x1426EFFD0) }; 17 | 18 | /* BUILT-IN */ 19 | WEAK symbol I_stristr{ OFFSET(0x1422EA2B0) }; 20 | WEAK symbol<__int64(int* a1, __int64 a2, __int64 a3)> PLmemset{ OFFSET(0x142C3EA20) }; 21 | WEAK symbol vsnprintf{ OFFSET(0x142C3DB30) }; 22 | 23 | /* CG */ 24 | WEAK symbol CG_ProcessClientNote{ OFFSET(0x140255C70) }; 25 | 26 | /* CMD */ 27 | // Variables 28 | WEAK symbol cmd_functions{ OFFSET(0x15689FF58) }; 29 | 30 | /* COM */ 31 | WEAK symbol Com_Error_{ OFFSET(0x1420F8BD0) }; 32 | WEAK symbol Com_GameInfo_GetGameTypeRefCaps{ OFFSET(0x1420F4090) }; 33 | WEAK symbol Com_GameInfo_GetGameTypeRef{ OFFSET(0x1420F4010) }; 34 | WEAK symbol Com_GameInfo_GetMapRef{ OFFSET(0x1420F4280) }; 35 | WEAK symbol Com_IsRunningUILevel{ OFFSET(0x142148DB0) }; 36 | WEAK symbol Com_Printf{ OFFSET(0x1421499C0) }; 37 | WEAK symbol Com_PrintMessage{ OFFSET(0x142149660) }; 38 | WEAK symbol Com_SessionMode_IsGameMode{ OFFSET(0x1420F7D90) }; 39 | WEAK symbol Com_SessionMode_IsMode{ OFFSET(0x1420F7DD0) }; 40 | WEAK symbol Com_sprintf{ OFFSET(0x142C3D620) }; 41 | 42 | /* CSC/GSC */ 43 | WEAK symbol GScr_AllocString{ OFFSET(0x141A83520) }; 44 | WEAK symbol Scr_GetInt{ OFFSET(0x1412EB7F0) }; 45 | WEAK symbol Scr_GetString{ OFFSET(0x1412EBAA0) }; 46 | // Variables 47 | WEAK symbol isProfileBuildFunctionDef{ OFFSET(0x1432D9D70) }; 48 | 49 | /* DB */ 50 | WEAK symbol DB_GetXAssetTypeSize{ OFFSET(0x1413E9DD0) }; 51 | // Variables 52 | static XAssetPool* DB_XAssetPool = reinterpret_cast(OFFSET(0x1494093F0)); 53 | static bool s_luaInFrontend = ((bool)OFFSET(0x143415BD8)); 54 | static lua::lua_State* UI_luaVM = ((lua::lua_State*)((*(INT64*)OFFSET(0x159C78D88)))); 55 | 56 | /* DObj */ 57 | WEAK symbol DObjGetBoneIndex{ OFFSET(0x14233DF70) }; 58 | WEAK symbol DObjGetLocalClientIndex{ OFFSET(0x142337A30) }; 59 | WEAK symbol DObjSetLocalTag{ OFFSET(0x14233EDE0) }; 60 | 61 | /* DVAR */ 62 | WEAK symbol Dvar_GenerateHash{ OFFSET(0x14133DBF0) }; 63 | WEAK symbol Dvar_GetBool{ OFFSET(0x1422BD930) }; 64 | WEAK symbol Dvar_GetString{ OFFSET(0x1422BFFF0) }; 65 | WEAK symbol Dvar_SetFromStringByName{ OFFSET(0x1422C7F60) }; 66 | // Variables 67 | WEAK symbol s_dvarPool{ OFFSET(0x157AC8220) }; 68 | WEAK symbol g_dvarCount{ OFFSET(0x157AC81CC) }; 69 | 70 | /* LOBBYSESSION */ 71 | WEAK symbol LobbySession_GetClientCount{ OFFSET(0x141ED8B30) }; 72 | 73 | /* LUA / UI */ 74 | WEAK symbol UI_SafeTranslateString{ OFFSET(0x14228F7B0) }; 75 | WEAK symbol UI_GetRootElement{ OFFSET(0x1427056C0) }; 76 | WEAK symbol GetLUIScopedEvent{ OFFSET(0x1426FF350) }; 77 | WEAK symbol ExecuteLUIScopedEvent{ OFFSET(0x1426FF580) }; 78 | 79 | /* MATERIAL */ 80 | WEAK symbol Material_RegisterHandle{ OFFSET(0x141CD4B90) }; 81 | 82 | /* SYS */ 83 | WEAK symbol Sys_IsDatabaseReady2{ OFFSET(0x142184490) }; 84 | WEAK symbol Sys_ShowConsole{ OFFSET(0x142333F80) }; 85 | WEAK symbol Sys_IsMainThread{ OFFSET(0x1421844F0) }; 86 | } 87 | -------------------------------------------------------------------------------- /src/client/havok/hks_api.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "hks_api.hpp" 3 | 4 | namespace hks 5 | { 6 | int hks_obj_type(const lua::HksObject* obj) 7 | { 8 | lua::hksUint32 v2; 9 | int obj_4; 10 | 11 | v2 = obj->t & 0xF; 12 | if (v2 == 9 || v2 == 10) 13 | obj_4 = 6; 14 | else 15 | obj_4 = obj->t & 0xF; 16 | return obj_4; 17 | } 18 | 19 | int hksi_lua_type(lua::lua_State* s, int index) 20 | { 21 | //lua::HksErrorFunctionType v2; 22 | int v4; 23 | lua::HksObject* v5; 24 | int failure; 25 | 26 | if (index <= -10000) 27 | { 28 | failure = 0; 29 | switch (index) 30 | { 31 | case -10000: 32 | v5 = &s->m_global->m_registry; 33 | break; 34 | case -10002: 35 | v5 = &s->globals; 36 | break; 37 | case -10001: 38 | s->m_cEnv.v.cClosure = (lua::cclosure*)s->m_apistack.base[-1].v.cClosure->m_env; 39 | s->m_cEnv.t = 5; 40 | v5 = &s->m_cEnv; 41 | break; 42 | default: 43 | v5 = (lua::HksObject*)(&s->m_apistack.base[-1].v.cClosure->m_numUpvalues + 8 * (-10002 - index)); 44 | break; 45 | } 46 | } 47 | else if (index <= 0) 48 | { 49 | if (index >= 0) 50 | { 51 | failure = 1; 52 | v5 = 0LL; 53 | } 54 | else if (&s->m_apistack.top[index] < s->m_apistack.base) 55 | { 56 | failure = 1; 57 | v5 = 0LL; 58 | } 59 | else 60 | { 61 | failure = 0; 62 | v5 = &s->m_apistack.top[index]; 63 | } 64 | } 65 | else if (&s->m_apistack.base[index - 1] >= s->m_apistack.top) 66 | { 67 | failure = 1; 68 | v5 = 0LL; 69 | } 70 | else 71 | { 72 | failure = 0; 73 | v5 = &s->m_apistack.base[index - 1]; 74 | } 75 | if (failure) 76 | v4 = -1; 77 | else 78 | v4 = hks_obj_type(v5); 79 | return v4; 80 | } 81 | 82 | int hks_obj_isstring(const lua::HksObject* x) 83 | { 84 | return (x->t & 0xF) == 4 || (x->t & 0xF) == 3; 85 | } 86 | 87 | int hksi_lua_isstring(lua::lua_State* s, int index) 88 | { 89 | //lua::HksErrorFunctionType v2; 90 | int v4; 91 | lua::HksObject* v5; 92 | int failure; 93 | 94 | if (index <= -10000) 95 | { 96 | failure = 0; 97 | switch (index) 98 | { 99 | case -10000: 100 | v5 = &s->m_global->m_registry; 101 | break; 102 | case -10002: 103 | v5 = &s->globals; 104 | break; 105 | case -10001: 106 | s->m_cEnv.v.cClosure = (lua::cclosure*)s->m_apistack.base[-1].v.cClosure->m_env; 107 | s->m_cEnv.t = 5; 108 | v5 = &s->m_cEnv; 109 | break; 110 | default: 111 | v5 = (lua::HksObject*)(&s->m_apistack.base[-1].v.cClosure->m_numUpvalues + 8 * (-10002 - index)); 112 | break; 113 | } 114 | } 115 | else if (index <= 0) 116 | { 117 | if (index >= 0) 118 | { 119 | failure = 1; 120 | v5 = 0LL; 121 | } 122 | else if (&s->m_apistack.top[index] < s->m_apistack.base) 123 | { 124 | failure = 1; 125 | v5 = 0LL; 126 | } 127 | else 128 | { 129 | failure = 0; 130 | v5 = &s->m_apistack.top[index]; 131 | } 132 | } 133 | else if (&s->m_apistack.base[index - 1] >= s->m_apistack.top) 134 | { 135 | failure = 1; 136 | v5 = 0LL; 137 | } 138 | else 139 | { 140 | failure = 0; 141 | v5 = &s->m_apistack.base[index - 1]; 142 | } 143 | if (failure) 144 | v4 = 0; 145 | else 146 | v4 = hks_obj_isstring(v5); 147 | return v4; 148 | } 149 | 150 | int hksi_lua_gettop(lua::lua_State* s) 151 | { 152 | return s->m_apistack.top - s->m_apistack.base; 153 | } 154 | 155 | int execute_raw_lua(std::string source, const char* chunkName) 156 | { 157 | lua::HksCompilerSettings hks_compiler_settings; 158 | // Enable compiling with source lua 159 | game::UI_luaVM->m_global->m_bytecodeSharingMode = lua::HKS_BYTECODE_SHARING_ON; 160 | // Compile the source lua 161 | hks::hksi_hksL_loadbuffer(game::UI_luaVM, &hks_compiler_settings, source.c_str(), source.size(), chunkName); 162 | // Turn off raw compiling so compiled files can be loaded again 163 | game::UI_luaVM->m_global->m_bytecodeSharingMode = lua::HKS_BYTECODE_SHARING_SECURE; 164 | 165 | return hks::hksi_lua_pcall(game::UI_luaVM, 0, 0, 0); 166 | } 167 | } -------------------------------------------------------------------------------- /src/client/havok/hks_api.hpp: -------------------------------------------------------------------------------- 1 | #include "game/game.hpp" 2 | #define WEAK __declspec(selectany) 3 | 4 | namespace hks 5 | { 6 | WEAK game::symbol hksI_openlib { (uintptr_t)GetModuleHandle(NULL) + 0x1D49440 }; 7 | WEAK game::symbol hksi_hksL_loadbuffer{ (uintptr_t)GetModuleHandle(NULL) + 0x1D4BD80 }; 8 | WEAK game::symbol hks_pushnamedcclosure{ (uintptr_t)GetModuleHandle(NULL) + 0x1D4BA70 }; 9 | WEAK game::symbol hksi_lua_pushvfstring{ (uintptr_t)GetModuleHandle(NULL) + 0x1D4E630 }; 10 | WEAK game::symbol hks_obj_tolstring{ (uintptr_t)GetModuleHandle(NULL) + 0x1D4B6C0 }; 11 | WEAK game::symbol hksi_luaL_error{ (uintptr_t)GetModuleHandle(NULL) + 0x1D4D050 }; 12 | WEAK game::symbol vm_call_internal{ (uintptr_t)GetModuleHandle(NULL) + 0x1D71070 }; 13 | WEAK game::symbol hksi_lua_pcall{ (uintptr_t)GetModuleHandle(NULL) + 0x1D4E420 }; 14 | 15 | 16 | WEAK game::symbol Lua_CoD_LuaStateManager_Error{ (uintptr_t)GetModuleHandle(NULL) + 0x1F12640 }; 17 | 18 | 19 | static const char** TypeName = ((const char**)((*(INT64*)(((uintptr_t)GetModuleHandle(NULL) + 0x337D4B8))))); 20 | 21 | int hks_obj_type(const lua::HksObject* obj); 22 | int hksi_lua_type(lua::lua_State* s, int index); 23 | int hks_obj_isstring(const lua::HksObject* x); 24 | int hksi_lua_isstring(lua::lua_State* s, int index); 25 | int hksi_lua_gettop(lua::lua_State* s); 26 | int execute_raw_lua(std::string source, const char* chunkName); 27 | } -------------------------------------------------------------------------------- /src/client/havok/lua_api.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "lua_api.hpp" 3 | #include "hks_api.hpp" 4 | 5 | namespace lua 6 | { 7 | HksObject getObjectForIndex(lua_State* s, int index) 8 | { 9 | //HksNumber result; 10 | HksObject* object; 11 | int failure; 12 | 13 | if (index <= LUA_REGISTRYINDEX) 14 | { 15 | failure = 0; 16 | switch (index) 17 | { 18 | case LUA_REGISTRYINDEX: 19 | object = &s->m_global->m_registry; 20 | break; 21 | case LUA_GLOBALSINDEX: 22 | object = &s->globals; 23 | break; 24 | case LUA_ENVIRONINDEX: 25 | s->m_cEnv.v.cClosure = (cclosure*)s->m_apistack.base[-1].v.cClosure->m_env; 26 | s->m_cEnv.t = 5; 27 | object = &s->m_cEnv; 28 | break; 29 | default: 30 | object = (HksObject*)(&s->m_apistack.base[-1].v.cClosure->m_numUpvalues + 8 * (LUA_GLOBALSINDEX - index)); 31 | break; 32 | } 33 | } 34 | else if (index <= 0) 35 | { 36 | if (index >= 0) 37 | { 38 | failure = 1; 39 | object = 0LL; 40 | } 41 | else if (&s->m_apistack.top[index] < s->m_apistack.base) 42 | { 43 | failure = 1; 44 | object = 0LL; 45 | } 46 | else 47 | { 48 | failure = 0; 49 | object = &s->m_apistack.top[index]; 50 | } 51 | } 52 | else if (&s->m_apistack.base[index - 1] >= s->m_apistack.top) 53 | { 54 | failure = 1; 55 | object = 0LL; 56 | } 57 | else 58 | { 59 | failure = 0; 60 | object = &s->m_apistack.base[index - 1]; 61 | } 62 | // TODO: Handle failures 63 | return *object; 64 | } 65 | 66 | void luaL_register(lua_State* s, const char* libname, const luaL_Reg* l) 67 | { 68 | hks::hksI_openlib(s, libname, l, 0, 1); 69 | } 70 | 71 | void lua_setglobal(lua_State* s, const char* k) 72 | { 73 | lua_setfield(s, LUA_GLOBALSINDEX, k); 74 | } 75 | 76 | void lua_pop(lua_State* s, int n) 77 | { 78 | s->m_apistack.top -= n; 79 | } 80 | 81 | HksNumber lua_tonumber(lua_State* s, int index) 82 | { 83 | auto object = getObjectForIndex(s, index); 84 | return object.v.number; 85 | } 86 | 87 | const char* lua_tostring(lua_State* s, int index) 88 | { 89 | auto object = getObjectForIndex(s, index); 90 | return hks::hks_obj_tolstring(s, &object, 0); 91 | } 92 | 93 | void lua_pushnumber(lua_State* s, HksNumber n) 94 | { 95 | auto top = s->m_apistack.top; 96 | top->v.number = n; 97 | top->t = TNUMBER; 98 | s->m_apistack.top = top + 1; 99 | } 100 | 101 | void lua_pushinteger(lua_State* s, int n) 102 | { 103 | auto top = s->m_apistack.top; 104 | top->v.number = float(n); 105 | top->t = TNUMBER; 106 | s->m_apistack.top = top + 1; 107 | } 108 | 109 | void lua_pushnil(lua_State* s) 110 | { 111 | auto top = s->m_apistack.top; 112 | top->v.number = 0; 113 | top->t = TNIL; 114 | s->m_apistack.top = top + 1; 115 | } 116 | 117 | void lua_pushboolean(lua_State* s, int b) 118 | { 119 | auto top = s->m_apistack.top; 120 | top->v.boolean = b; 121 | top->t = TBOOLEAN; 122 | s->m_apistack.top = top + 1; 123 | } 124 | 125 | void lua_pushvalue(lua_State* s, int index) 126 | { 127 | HksObject* st; 128 | auto object = getObjectForIndex(s, index); 129 | st = s->m_apistack.top; 130 | *st = object; 131 | s->m_apistack.top = st + 1; 132 | } 133 | 134 | void lua_pushfstring(lua_State* s, const char* fmt, ...) 135 | { 136 | va_list va; 137 | va_start(va, fmt); 138 | hks::hksi_lua_pushvfstring(s, fmt, &va); 139 | } 140 | 141 | void lua_pushvfstring(lua_State* s, const char* fmt, va_list* argp) 142 | { 143 | hks::hksi_lua_pushvfstring(s, fmt, argp); 144 | } 145 | 146 | void lua_getfield(lua_State* s, int index, const char*) 147 | { 148 | auto object = getObjectForIndex(s, index); 149 | 150 | //const HksRegister v16; 151 | 152 | auto top = --s->m_apistack.top; 153 | top->v.cClosure = object.v.cClosure; 154 | s->m_apistack.top = top++; 155 | } 156 | 157 | void lua_getglobal(lua_State* s, const char* k) 158 | { 159 | lua_getfield(s, LUA_GLOBALSINDEX, k); 160 | } 161 | } -------------------------------------------------------------------------------- /src/client/havok/lua_api.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "game/game.hpp" 3 | #define WEAK __declspec(selectany) 4 | 5 | #define LUA_REGISTRYINDEX (-10000) 6 | #define LUA_ENVIRONINDEX (-10001) 7 | #define LUA_GLOBALSINDEX (-10002) 8 | 9 | namespace lua 10 | { 11 | WEAK game::symbol luaL_argerror{ (uintptr_t)GetModuleHandle(NULL) + 0x1D4CE50 }; 12 | WEAK game::symbol lua_pcall{ (uintptr_t)GetModuleHandle(NULL) + 0x1D53E40 }; 13 | WEAK game::symbol lua_setfield{ (uintptr_t)GetModuleHandle(NULL) + 0x1429680 }; 14 | WEAK game::symbol lua_topointer{ (uintptr_t)GetModuleHandle(NULL) + 0x1D4F020 }; 15 | WEAK game::symbol lua_toboolean{ (uintptr_t)GetModuleHandle(NULL) + 0x14373D0 }; 16 | WEAK game::symbol lua_toui64{ (uintptr_t)GetModuleHandle(NULL) + 0x1D4C8A0 }; 17 | WEAK game::symbol lua_pushlstring{ (uintptr_t)GetModuleHandle(NULL) + 0xA18430 }; 18 | WEAK game::symbol luaL_findtable{ (uintptr_t)GetModuleHandle(NULL) + 0x1D530E0 }; 19 | WEAK game::symbol lua_pushstring{ (uintptr_t)GetModuleHandle(NULL) + 0xA186B0 }; 20 | 21 | //WEAK game::symbol lua_pushstring{ (uintptr_t)GetModuleHandle(NULL) + 0x1D52F50 }; 22 | WEAK game::symbol luaL_error{ (uintptr_t)GetModuleHandle(NULL) + 0x1D53050 }; 23 | 24 | WEAK game::symbol lua_isnumber{ (uintptr_t)GetModuleHandle(NULL) + 0x1429350 }; 25 | 26 | WEAK game::symbol<__int64 (const char* key, const char* value, lua_State* luaVM)> Lua_SetTableString{ (uintptr_t)GetModuleHandle(NULL) + 0x32534688 }; 27 | 28 | void luaL_register(lua_State* s, const char* libname, const luaL_Reg* l); 29 | void lua_setglobal(lua_State* s, const char* k); 30 | void lua_pop(lua_State* s, int n); 31 | HksNumber lua_tonumber(lua_State* s, int index); 32 | const char* lua_tostring(lua_State* s, int index); 33 | void lua_pushnumber(lua_State* s, HksNumber n); 34 | void lua_pushinteger(lua_State* s, int n); 35 | void lua_pushnil(lua_State* s); 36 | void lua_pushboolean(lua_State* s, int b); 37 | void lua_pushvalue(lua_State* s, int index); 38 | void lua_pushfstring(lua_State* s, const char* fmt, ...); 39 | void lua_pushvfstring(lua_State* s, const char* fmt, va_list* argp); 40 | void lua_getfield(lua_State* s, int index, const char* k); 41 | void lua_getglobal(lua_State* s, const char* k); 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/client/havok/structs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "structs.hpp" 3 | 4 | namespace lua 5 | { 6 | int hks_identity_map(const char*, int lua_line) 7 | { 8 | return lua_line; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/client/havok/structs.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace lua 4 | { 5 | typedef int hksBool; 6 | typedef char hksChar; 7 | typedef unsigned __int8 hksByte; 8 | typedef __int16 hksShort16; 9 | typedef unsigned __int16 hksUshort16; 10 | typedef float HksNumber; 11 | typedef int hksInt32; 12 | typedef unsigned int hksUint32; 13 | typedef __int64 hksInt64; 14 | typedef unsigned __int64 hksUint64; 15 | typedef size_t hksSize; 16 | typedef int ErrorCode; 17 | 18 | struct _jmp_buf 19 | { 20 | void* _jb[12]; 21 | }; 22 | struct lua_State; 23 | 24 | typedef hksUint32 hksBytecodeInstruction; 25 | typedef hksUint32 HksNativeValueAsInt; 26 | typedef void* (*lua_Alloc)(void*, void*, size_t, size_t); 27 | typedef int (*hks_debug_map)(const char*, int); 28 | typedef hksInt32(*lua_CFunction)(lua_State*); 29 | struct lua_Debug; 30 | typedef void (*lua_Hook)(lua_State*, lua_Debug*); 31 | 32 | typedef hksInt32(*HksErrorFunctionType)(const hksChar*, const hksInt32, const hksChar*, const hksUint32, const hksChar*, const hksChar*); 33 | 34 | 35 | enum HksError : __int32 36 | { 37 | HKS_NO_ERROR = 0x0, 38 | LUA_ERRSYNTAX = -1, 39 | LUA_ERRFILE = -2, 40 | LUA_ERRRUN = -3, 41 | LUA_ERRMEM = -4, 42 | LUA_ERRERR = -5, 43 | HKS_THROWING_ERROR = -6, 44 | HKS_GC_YIELD = 0x1, 45 | }; 46 | 47 | enum HksBytecodeEndianness : __int32 48 | { 49 | HKS_BYTECODE_DEFAULT_ENDIAN = 0x0, 50 | HKS_BYTECODE_BIG_ENDIAN = 0x1, 51 | HKS_BYTECODE_LITTLE_ENDIAN = 0x2, 52 | }; 53 | 54 | enum HksBytecodeSharingMode : __int64 55 | { 56 | HKS_BYTECODE_SHARING_OFF = 0, 57 | HKS_BYTECODE_SHARING_ON = 1, 58 | HKS_BYTECODE_SHARING_SECURE = 2 59 | }; 60 | 61 | enum HksObjectType : __int32 62 | { 63 | TANY = -2, 64 | TNONE = -1, 65 | TNIL = 0x0, 66 | TBOOLEAN = 0x1, 67 | TLIGHTUSERDATA = 0x2, 68 | TNUMBER = 0x3, 69 | TSTRING = 0x4, 70 | TTABLE = 0x5, 71 | TFUNCTION = 0x6, 72 | TUSERDATA = 0x7, 73 | TTHREAD = 0x8, 74 | TIFUNCTION = 0x9, 75 | TCFUNCTION = 0xA, 76 | TUI64 = 0xB, 77 | TSTRUCT = 0xC, 78 | NUM_TYPE_OBJECTS = 0xE, 79 | }; 80 | 81 | int hks_identity_map(const char* filename, int lua_line); 82 | 83 | struct HksCompilerSettings 84 | { 85 | enum BytecodeSharingFormat : __int32 86 | { 87 | BYTECODE_DEFAULT = 0x0, 88 | BYTECODE_INPLACE = 0x1, 89 | BYTECODE_REFERENCED = 0x2, 90 | }; 91 | 92 | 93 | enum IntLiteralOptions : __int32 94 | { 95 | INT_LITERALS_NONE = 0x0, 96 | INT_LITERALS_LUD = 0x1, 97 | INT_LITERALS_32BIT = 0x1, 98 | INT_LITERALS_UI64 = 0x2, 99 | INT_LITERALS_64BIT = 0x2, 100 | INT_LITERALS_ALL = 0x3, 101 | }; 102 | 103 | hksBool m_emitStructCode = 0; 104 | int padding; 105 | const hksChar** m_stripNames = 0; 106 | BytecodeSharingFormat m_bytecodeSharingFormat = BYTECODE_INPLACE; 107 | IntLiteralOptions m_enableIntLiterals = INT_LITERALS_NONE; 108 | 109 | hks_debug_map m_debugMap = hks_identity_map; 110 | }; 111 | 112 | struct GenericChunkHeader 113 | { 114 | hksSize m_flags; 115 | }; 116 | 117 | struct ChunkHeader : GenericChunkHeader 118 | { 119 | ChunkHeader* m_next; 120 | }; 121 | 122 | struct ChunkList 123 | { 124 | ChunkHeader m_head; 125 | }; 126 | 127 | struct InternString : GenericChunkHeader 128 | { 129 | hksSize m_lengthbits; 130 | hksUint32 m_hash; 131 | char m_data[30]; 132 | char padding[6]; 133 | }; 134 | 135 | struct StructInst; 136 | struct cclosure; 137 | struct HksClosure; 138 | struct HashTable; 139 | struct UserData; 140 | struct StructInst; 141 | struct InternString; 142 | 143 | union HksValue 144 | { 145 | cclosure* cClosure; 146 | HksClosure* closure; 147 | UserData* userData; 148 | HashTable* table; 149 | StructInst* tstruct; 150 | InternString* str; 151 | lua_State* thread; 152 | void* ptr; 153 | HksNumber number; 154 | HksNativeValueAsInt native; 155 | hksInt32 boolean; 156 | }; 157 | 158 | typedef struct HksObject 159 | { 160 | hksUint32 t; 161 | HksValue v; 162 | } HksObject; 163 | 164 | typedef HksObject HksRegister; 165 | 166 | struct StringPinner 167 | { 168 | struct Node 169 | { 170 | InternString* m_strings[32]; 171 | Node* m_prev; 172 | }; 173 | 174 | lua_State* const m_state; 175 | StringPinner* const m_prev; 176 | InternString** m_nextStringsPlace; 177 | Node m_firstNode; 178 | Node* m_currentNode; 179 | }; 180 | 181 | struct StringTable 182 | { 183 | InternString** m_data; 184 | hksUint32 m_count; 185 | hksUint32 m_mask; 186 | StringPinner* m_pinnedStrings; 187 | }; 188 | 189 | 190 | struct Metatable 191 | { 192 | __int8 gap0[1]; 193 | }; 194 | 195 | struct HashTable : ChunkHeader 196 | { 197 | struct Node 198 | { 199 | HksRegister m_key; 200 | HksRegister m_value; 201 | }; 202 | 203 | Metatable* m_meta; 204 | hksUint32 m_mask; 205 | Node* m_hashPart; 206 | HksRegister* m_arrayPart; 207 | hksUint32 m_arraySize; 208 | Node* m_freeNode; 209 | }; 210 | 211 | struct StaticStringCache 212 | { 213 | HksObject m_objects[42]; 214 | }; 215 | 216 | struct hksInstruction 217 | { 218 | hksBytecodeInstruction code; 219 | }; 220 | 221 | struct UserData : ChunkHeader 222 | { 223 | HashTable* m_env; 224 | Metatable* m_meta; 225 | char m_data[8]; 226 | }; 227 | 228 | struct RuntimeProfileData 229 | { 230 | struct Stats 231 | { 232 | hksUint64 hksTime; 233 | hksUint64 callbackTime; 234 | hksUint64 gcTime; 235 | hksUint64 cFinalizerTime; 236 | hksUint64 compilerTime; 237 | hksUint32 hkssTimeSamples; 238 | hksUint32 callbackTimeSamples; 239 | hksUint32 gcTimeSamples; 240 | hksUint32 compilerTimeSamples; 241 | hksUint32 num_newuserdata; 242 | hksUint32 num_tablerehash; 243 | hksUint32 num_pushstring; 244 | hksUint32 num_pushcfunction; 245 | hksUint32 num_newtables; 246 | int padding; 247 | }; 248 | 249 | hksInt64 stackDepth; 250 | hksInt64 callbackDepth; 251 | hksUint64 lastTimer; 252 | Stats frameStats; 253 | hksUint64 gcStartTime; 254 | hksUint64 finalizerStartTime; 255 | hksUint64 compilerStartTime; 256 | hksUint64 compilerStartGCTime; 257 | hksUint64 compilerStartGCFinalizerTime; 258 | hksUint64 compilerCallbackStartTime; 259 | hksInt64 compilerDepth; 260 | void* outFile; 261 | lua_State* rootState; 262 | }; 263 | 264 | struct cclosure : ChunkHeader 265 | { 266 | lua_CFunction m_function; 267 | HashTable* m_env; 268 | hksShort16 m_numUpvalues; 269 | hksShort16 m_flags; 270 | InternString* m_name; 271 | HksObject m_upvalues[1]; 272 | }; 273 | 274 | struct UpValue : ChunkHeader 275 | { 276 | HksObject m_storage; 277 | HksObject* loc; 278 | UpValue* m_next; 279 | }; 280 | 281 | struct Method : ChunkHeader 282 | { 283 | struct hksInstructionArray 284 | { 285 | hksUint32 size; 286 | const hksInstruction* data; 287 | }; 288 | 289 | struct HksObjectArray 290 | { 291 | hksUint32 size; 292 | HksObject* data; 293 | }; 294 | 295 | struct MethodArray 296 | { 297 | hksUint32 size; 298 | Method** data; 299 | }; 300 | 301 | struct LocalInfo 302 | { 303 | InternString* name; 304 | hksInt32 start_pc; 305 | hksInt32 end_pc; 306 | }; 307 | 308 | struct hksUint32Array 309 | { 310 | hksUint32 size; 311 | unsigned int* data; 312 | }; 313 | 314 | struct LocalInfoArray 315 | { 316 | hksUint32 size; 317 | LocalInfo* data; 318 | }; 319 | 320 | struct InternStringArray 321 | { 322 | hksUint32 size; 323 | InternString** data; 324 | }; 325 | 326 | typedef hksInstructionArray Instructions; 327 | typedef HksObjectArray Constants; 328 | typedef MethodArray Children; 329 | typedef LocalInfoArray Locals; 330 | typedef hksUint32Array LineInfo; 331 | typedef InternStringArray UpValueInfo; 332 | 333 | struct DebugInfo 334 | { 335 | hksUint32 line_defined; 336 | hksUint32 last_line_defined; 337 | LineInfo lineInfo; 338 | UpValueInfo upvalInfo; 339 | InternString* source; 340 | InternString* name; 341 | Locals localInfo; 342 | }; 343 | 344 | hksUint32 hash; 345 | hksUshort16 num_upvals; 346 | hksUshort16 m_numRegisters; 347 | hksByte num_params; 348 | hksByte m_flags; 349 | Instructions instructions; 350 | Constants constants; 351 | Children children; 352 | DebugInfo* m_debug; 353 | }; 354 | 355 | struct HksClosure : ChunkHeader 356 | { 357 | struct MethodCache 358 | { 359 | const HksObject* consts; 360 | const hksInstruction* inst; 361 | hksUshort16 m_numRegisters; 362 | hksByte m_flags; 363 | hksByte num_params; 364 | }; 365 | 366 | Method* m_method; 367 | HashTable* m_env; 368 | hksByte m_mayHaveUpvalues; 369 | MethodCache m_cache; 370 | UpValue* m_upvalues[1]; 371 | }; 372 | 373 | struct lua_Debug 374 | { 375 | hksInt32 event; 376 | const char* name; 377 | const char* namewhat; 378 | const char* what; 379 | const char* source; 380 | hksInt32 currentline; 381 | hksInt32 nups; 382 | hksInt32 nparams; 383 | hksBool ishksfunc; 384 | hksInt32 linedefined; 385 | hksInt32 lastlinedefined; 386 | char short_src[512]; 387 | hksInt32 callstack_level; 388 | hksBool is_tail_call; 389 | }; 390 | 391 | struct DebugHook 392 | { 393 | lua_Hook m_callback; 394 | hksInt32 m_mask; 395 | hksInt32 m_count; 396 | hksInt32 m_counter; 397 | bool m_inuse; 398 | const hksInstruction* m_prevPC; 399 | }; 400 | 401 | struct DebugInstance 402 | { 403 | struct RuntimeProfilerStats 404 | { 405 | hksInt32 hksTime; 406 | hksInt32 callbackTime; 407 | hksInt32 gcTime; 408 | hksInt32 cFinalizerTime; 409 | hksInt64 heapSize; 410 | hksInt64 num_newuserdata; 411 | hksInt64 num_pushstring; 412 | }; 413 | 414 | int m_savedObjects; 415 | int m_keepAliveObjects; 416 | lua_State* m_activeState; 417 | lua_State* m_mainState; 418 | void* m_owner; 419 | hksInt32 m_DebuggerLevel; 420 | hksInt32 stored_Hook_level; 421 | bool m_clearHook; 422 | const hksInstruction* stored_Hook_return_addr; 423 | hksInt32 m_debugStepLastLine; 424 | DebugInstance* m_next; 425 | const hksInstruction* m_activePC; 426 | hksInt32 runtimeProfileSendBufferWritePosition; 427 | RuntimeProfilerStats runtimeProfileSendBuffer[30]; 428 | }; 429 | 430 | typedef void (*HksLogFunc)(lua_State*, const char*, ...); 431 | typedef void (*HksEmergencyGCFailFunc)(lua_State*, size_t); 432 | 433 | struct MemoryManager 434 | { 435 | enum ChunkColor : __int32 436 | { 437 | WHITE = 0x0, 438 | BLACK = 0x1, 439 | }; 440 | 441 | lua_Alloc m_allocator; 442 | void* m_allocatorUd; 443 | ChunkColor m_chunkColor; 444 | hksSize m_used; 445 | hksSize m_highwatermark; 446 | ChunkList m_allocationList; 447 | ChunkList m_sweepList; 448 | ChunkHeader* m_lastKeptChunk; 449 | lua_State* m_state; 450 | }; 451 | 452 | typedef int HksGcCost; 453 | 454 | struct HksGcWeights 455 | { 456 | HksGcCost m_removeString; 457 | HksGcCost m_finalizeUserdataNoMM; 458 | HksGcCost m_finalizeUserdataGcMM; 459 | HksGcCost m_cleanCoroutine; 460 | HksGcCost m_removeWeak; 461 | HksGcCost m_markObject; 462 | HksGcCost m_traverseString; 463 | HksGcCost m_traverseUserdata; 464 | HksGcCost m_traverseCoroutine; 465 | HksGcCost m_traverseWeakTable; 466 | HksGcCost m_freeChunk; 467 | HksGcCost m_sweepTraverse; 468 | }; 469 | 470 | struct ResumeData_Header 471 | { 472 | HksObjectType m_type; 473 | }; 474 | 475 | enum GCResumePhase : __int32 476 | { 477 | GC_STATE_MARKING_UPVALUES = 0x0, 478 | GC_STATE_MARKING_GLOBAL_TABLE = 0x1, 479 | GC_STATE_MARKING_REGISTRY = 0x2, 480 | GC_STATE_MARKING_PROTOTYPES = 0x3, 481 | GC_STATE_MARKING_SCRIPT_PROFILER = 0x4, 482 | GC_STATE_MARKING_FINALIZER_STATE = 0x5, 483 | GC_TABLE_MARKING_ARRAY = 0x6, 484 | GC_TABLE_MARKING_HASH = 0x7, 485 | }; 486 | 487 | struct ResumeData_State 488 | { 489 | ResumeData_Header h; 490 | int padding; 491 | lua_State* m_state; 492 | GCResumePhase m_phase; 493 | int padding2; 494 | UpValue* m_pending; 495 | }; 496 | 497 | struct ResumeData_Table 498 | { 499 | ResumeData_Header h; 500 | int padding; 501 | HashTable* m_table; 502 | hksUint32 m_arrayIndex; 503 | hksUint32 m_hashIndex; 504 | hksInt32 m_weakness; 505 | int padding2; 506 | }; 507 | 508 | struct ResumeData_Closure 509 | { 510 | ResumeData_Header h; 511 | int padding; 512 | HksClosure* m_closure; 513 | hksInt32 m_index; 514 | int padding2; 515 | }; 516 | 517 | struct ResumeData_CClosure 518 | { 519 | ResumeData_Header h; 520 | int padding; 521 | cclosure* m_cclosure; 522 | hksInt32 m_upvalueIndex; 523 | int padding2; 524 | }; 525 | 526 | /* 2620 */ 527 | struct ResumeData_Userdata 528 | { 529 | ResumeData_Header h; 530 | int padding; 531 | UserData* m_data; 532 | }; 533 | 534 | union ResumeData_Entry 535 | { 536 | ResumeData_State State; 537 | ResumeData_Table HashTable; 538 | ResumeData_Closure Closure; 539 | ResumeData_CClosure CClosure; 540 | ResumeData_Userdata Userdata; 541 | }; 542 | 543 | struct GarbageCollector 544 | { 545 | struct ResumeStack 546 | { 547 | ResumeData_Entry* m_storage; 548 | hksInt32 m_numEntries; 549 | hksUint32 m_numAllocated; 550 | }; 551 | 552 | struct GreyStack 553 | { 554 | HksObject* m_storage; 555 | hksSize m_numEntries; 556 | hksSize m_numAllocated; 557 | }; 558 | 559 | struct RemarkStack 560 | { 561 | HashTable** m_storage; 562 | hksSize m_numAllocated; 563 | hksSize m_numEntries; 564 | }; 565 | 566 | struct WeakStack_Entry 567 | { 568 | hksInt32 m_weakness; 569 | HashTable* m_table; 570 | }; 571 | 572 | struct WeakStack 573 | { 574 | WeakStack_Entry* m_storage; 575 | hksInt32 m_numEntries; 576 | hksUint32 m_numAllocated; 577 | }; 578 | 579 | HksGcCost m_target; 580 | HksGcCost m_stepsLeft; 581 | HksGcCost m_stepLimit; 582 | HksGcWeights m_costs; 583 | HksGcCost m_unit; 584 | void* m_jumpPoint; 585 | lua_State* m_mainState; 586 | lua_State* m_finalizerState; 587 | MemoryManager* m_memory; 588 | void* m_emergencyGCMemory; 589 | hksInt32 m_phase; 590 | ResumeStack m_resumeStack; 591 | GreyStack m_greyStack; 592 | RemarkStack m_remarkStack; 593 | WeakStack m_weakStack; 594 | hksBool m_finalizing; 595 | HksObject m_safeTableValue; 596 | lua_State* m_startOfStateStackList; 597 | lua_State* m_endOfStateStackList; 598 | lua_State* m_currentState; 599 | HksObject m_safeValue; 600 | void* m_compiler; 601 | void* m_bytecodeReader; 602 | void* m_bytecodeWriter; 603 | hksInt32 m_pauseMultiplier; 604 | HksGcCost m_stepMultiplier; 605 | hksSize m_emergencyMemorySize; 606 | bool m_stopped; 607 | lua_CFunction m_gcPolicy; 608 | hksSize m_pauseTriggerMemoryUsage; 609 | hksInt32 m_stepTriggerCountdown; 610 | hksUint32 m_stringTableIndex; 611 | hksUint32 m_stringTableSize; 612 | UserData* m_lastBlackUD; 613 | UserData* m_activeUD; 614 | }; 615 | 616 | struct HksGlobal 617 | { 618 | MemoryManager m_memory; 619 | GarbageCollector m_collector; 620 | StringTable m_stringTable; 621 | __int64 padding3; 622 | HksBytecodeSharingMode m_bytecodeSharingMode; 623 | int padding; 624 | HksObject m_registry; 625 | ChunkList m_userDataList; 626 | lua_State* m_root; 627 | StaticStringCache m_staticStringCache; 628 | DebugInstance* m_debugger; 629 | void* m_profiler; 630 | RuntimeProfileData m_runProfilerData; 631 | HksCompilerSettings m_compilerSettings; 632 | lua_CFunction m_panicFunction; 633 | void* m_luaplusObjectList; 634 | int m_heapAssertionFrequency; 635 | int m_heapAssertionCount; 636 | HksLogFunc m_logFunction; 637 | HksEmergencyGCFailFunc m_emergencyGCFailFunction; 638 | HksBytecodeEndianness m_bytecodeDumpEndianness; 639 | int padding2; 640 | }; 641 | 642 | struct ApiStack 643 | { 644 | HksObject* top; 645 | HksObject* base; 646 | HksObject* alloc_top; 647 | HksObject* bottom; 648 | }; 649 | 650 | struct CallStack 651 | { 652 | struct ActivationRecord 653 | { 654 | HksObject* m_base; 655 | const hksInstruction* m_returnAddress; 656 | hksShort16 m_tailCallDepth; 657 | hksShort16 m_numVarargs; 658 | hksInt32 m_numExpectedReturns; 659 | }; 660 | 661 | ActivationRecord* m_records; 662 | ActivationRecord* m_lastrecord; 663 | ActivationRecord* m_current; 664 | const hksInstruction* m_current_lua_pc; 665 | const hksInstruction* m_hook_return_addr; 666 | hksInt32 m_hook_level; 667 | hksInt32 padding; 668 | }; 669 | 670 | struct CallSite 671 | { 672 | _jmp_buf m_jumpBuffer; 673 | CallSite* m_prev; 674 | }; 675 | typedef CallSite* ErrorHandler; 676 | 677 | enum LuaStateStatus : __int32 678 | { 679 | NEW = 0x1, 680 | RUNNING = 0x2, 681 | YIELDED = 0x3, 682 | DEAD_ERROR = 0x4, 683 | }; 684 | 685 | struct lua_State 686 | { 687 | enum Status : __int32 688 | { 689 | NEW = 0x1, 690 | RUNNING = 0x2, 691 | YIELDED = 0x3, 692 | DEAD_ERROR = 0x4, 693 | }; 694 | 695 | ChunkHeader baseclass; 696 | HksGlobal* m_global; 697 | CallStack m_callStack; 698 | ApiStack m_apistack; 699 | UpValue* pending; 700 | HksObject globals; 701 | HksObject m_cEnv; 702 | ErrorHandler m_callsites; 703 | hksInt32 m_numberOfCCalls; 704 | void* m_context; 705 | InternString* m_name; 706 | lua_State* m_next; 707 | lua_State* m_nextStateStack; 708 | Status m_status; 709 | HksError m_error; 710 | DebugHook m_debugHook; 711 | }; 712 | 713 | typedef hksInt32(*lua_CFunction)(lua_State*); 714 | 715 | typedef struct luaL_Reg 716 | { 717 | const char* name; 718 | lua_CFunction func; 719 | } luaL_Reg; 720 | } 721 | 722 | 723 | -------------------------------------------------------------------------------- /src/client/loader/component_interface.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class component_interface 4 | { 5 | public: 6 | virtual ~component_interface() 7 | { 8 | } 9 | 10 | virtual void post_start() 11 | { 12 | } 13 | 14 | virtual void lua_start() 15 | { 16 | } 17 | 18 | virtual void pre_destroy() 19 | { 20 | } 21 | 22 | virtual void start_hooks() 23 | { 24 | } 25 | 26 | virtual void destroy_hooks() 27 | { 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /src/client/loader/component_loader.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "component_loader.hpp" 3 | #include "havok/hks_api.hpp" 4 | #include "game/game.hpp" 5 | #include "utils/string.hpp" 6 | 7 | void component_loader::register_component(std::unique_ptr&& component_) 8 | { 9 | get_components().push_back(std::move(component_)); 10 | } 11 | 12 | static utils::hook::detour com_loadfrontend_hook; 13 | static bool com_loadfrontend_hooked = false; 14 | 15 | __int64 com_loadfrontend_internal() 16 | { 17 | game::minlog.WriteLine("Com_LoadFrontEnd hook called, destroying hooks"); 18 | component_loader::destroy_hooks(); 19 | __int64 result = com_loadfrontend_hook.invoke<__int64>(); 20 | com_loadfrontend_hook.clear(); 21 | com_loadfrontend_hooked = false; 22 | return result; 23 | } 24 | 25 | int hook_cycle_create(lua::lua_State* s) 26 | { 27 | if (com_loadfrontend_hooked) 28 | { 29 | game::minlog.WriteDebug("Hooks already active"); 30 | return 0; 31 | } 32 | component_loader::start_hooks(); 33 | com_loadfrontend_hook.create(REBASE(0x142148E20), &com_loadfrontend_internal); 34 | com_loadfrontend_hooked = true; 35 | game::minlog.WriteDebug("Hooks started"); 36 | return 1; 37 | } 38 | 39 | void component_loader::initialize_hook_cycle() 40 | { 41 | if (!game::Com_IsRunningUILevel()) 42 | { 43 | game::minlog.WriteDebug("Creating first snapshot event handler"); 44 | // Add a function that we can call from lua 45 | const lua::luaL_Reg HookCycleLibrary[] = 46 | { 47 | {"Create", hook_cycle_create}, 48 | {nullptr, nullptr}, 49 | }; 50 | hks::hksI_openlib(game::UI_luaVM, "HookCycle", HookCycleLibrary, 0, 1); 51 | 52 | // Create a event handler for when the hud is created, at this point it is safe to start hooks 53 | std::string hookCycleEvent = 54 | "LUI.roots.UIRootFull.HUDRefreshTimer = LUI.UITimer.newElementTimer(1000, true, function() " 55 | "local root = LUI.roots.UIRoot0; " 56 | "local rootChildExists = root:getFirstChild(); " 57 | "if rootChildExists and rootChildExists.menuName and rootChildExists.menuName == 'HUD' then " 58 | "local oldSnapshotEvent = rootChildExists.m_eventHandlers['first_snapshot']; " 59 | "rootChildExists:registerEventHandler( 'first_snapshot', function( element, event ) " 60 | "oldSnapshotEvent( element, event ); " 61 | "HookCycle.Create(); " 62 | "end ); " 63 | "return; " 64 | "end; " 65 | "local oldEvent = root.m_eventHandlers['addmenu']; " 66 | "root:registerEventHandler( 'addmenu', function( element, event ) " 67 | "oldEvent( element, event ); " 68 | "local rootChild = element:getFirstChild(); " 69 | "local oldSnapshotEvent = rootChild.m_eventHandlers['first_snapshot']; " 70 | "rootChild:registerEventHandler( 'first_snapshot', function( element, event ) " 71 | "oldSnapshotEvent( element, event ); " 72 | "HookCycle.Create(); " 73 | "end ); " 74 | "end ); " 75 | "end); " 76 | "LUI.roots.UIRootFull:addElement(LUI.roots.UIRootFull.HUDRefreshTimer);"; 77 | 78 | hks::execute_raw_lua(hookCycleEvent, "HookCycleEvent"); 79 | } 80 | else 81 | { 82 | game::minlog.WriteDebug("Frontend active, can't add hooks here"); 83 | } 84 | } 85 | 86 | bool component_loader::post_start() 87 | { 88 | lua_start(); 89 | 90 | static auto handled = false; 91 | if (handled) return true; 92 | handled = true; 93 | 94 | try 95 | { 96 | for (const auto& component_ : get_components()) 97 | { 98 | component_->post_start(); 99 | } 100 | } 101 | catch (premature_shutdown_trigger&) 102 | { 103 | return false; 104 | } 105 | 106 | return true; 107 | } 108 | 109 | bool component_loader::lua_start() 110 | { 111 | try 112 | { 113 | for (const auto& component_ : get_components()) 114 | { 115 | component_->lua_start(); 116 | } 117 | } 118 | catch (premature_shutdown_trigger&) 119 | { 120 | return false; 121 | } 122 | 123 | initialize_hook_cycle(); 124 | 125 | return true; 126 | } 127 | 128 | bool component_loader::pre_destroy() 129 | { 130 | static auto handled = false; 131 | if (handled) return true; 132 | handled = true; 133 | 134 | try 135 | { 136 | for (const auto& component_ : get_components()) 137 | { 138 | component_->pre_destroy(); 139 | } 140 | } 141 | catch (premature_shutdown_trigger&) 142 | { 143 | return false; 144 | } 145 | 146 | return true; 147 | } 148 | 149 | bool component_loader::start_hooks() 150 | { 151 | static auto handled = false; 152 | if (handled) return true; 153 | handled = true; 154 | 155 | try 156 | { 157 | for (const auto& component_ : get_components()) 158 | { 159 | component_->start_hooks(); 160 | } 161 | } 162 | catch (premature_shutdown_trigger&) 163 | { 164 | return false; 165 | } 166 | 167 | return true; 168 | } 169 | 170 | bool component_loader::destroy_hooks() 171 | { 172 | static auto handled = false; 173 | if (handled) return true; 174 | handled = true; 175 | 176 | try 177 | { 178 | for (const auto& component_ : get_components()) 179 | { 180 | component_->destroy_hooks(); 181 | } 182 | } 183 | catch (premature_shutdown_trigger&) 184 | { 185 | return false; 186 | } 187 | 188 | return true; 189 | } 190 | 191 | void component_loader::trigger_premature_shutdown() 192 | { 193 | throw premature_shutdown_trigger(); 194 | } 195 | 196 | std::vector>& component_loader::get_components() 197 | { 198 | using component_vector = std::vector>; 199 | using component_vector_container = std::unique_ptr>; 200 | 201 | static component_vector_container components(new component_vector, [](component_vector* component_vector) 202 | { 203 | pre_destroy(); 204 | delete component_vector; 205 | }); 206 | 207 | return *components; 208 | } 209 | -------------------------------------------------------------------------------- /src/client/loader/component_loader.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "component_interface.hpp" 3 | #include "utils/hook.hpp" 4 | 5 | class component_loader final 6 | { 7 | public: 8 | class premature_shutdown_trigger final : public std::exception 9 | { 10 | [[nodiscard]] const char* what() const noexcept override 11 | { 12 | return "Premature shutdown requested"; 13 | } 14 | }; 15 | 16 | template 17 | class installer final 18 | { 19 | static_assert(std::is_base_of::value, "component has invalid base class"); 20 | 21 | public: 22 | installer() 23 | { 24 | register_component(std::make_unique()); 25 | } 26 | }; 27 | 28 | template 29 | static T* get() 30 | { 31 | for (const auto& component_ : get_components()) 32 | { 33 | if (typeid(*component_.get()) == typeid(T)) 34 | { 35 | return reinterpret_cast(component_.get()); 36 | } 37 | } 38 | 39 | return nullptr; 40 | } 41 | 42 | static void register_component(std::unique_ptr&& component); 43 | 44 | static void initialize_hook_cycle(); 45 | 46 | static bool post_start(); 47 | static bool lua_start(); 48 | static bool pre_destroy(); 49 | static bool start_hooks(); 50 | static bool destroy_hooks(); 51 | 52 | static void trigger_premature_shutdown(); 53 | 54 | private: 55 | static std::vector>& get_components(); 56 | }; 57 | 58 | #define REGISTER_COMPONENT(name) \ 59 | namespace \ 60 | { \ 61 | static component_loader::installer __component; \ 62 | } 63 | -------------------------------------------------------------------------------- /src/client/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "game/game.hpp" 4 | #include "havok/hks_api.hpp" 5 | #include "loader/component_loader.hpp" 6 | 7 | extern "C" 8 | { 9 | int __declspec(dllexport) init(lua::lua_State* L) 10 | { 11 | game::minlog.WriteLine("T7Overchared initiating"); 12 | 13 | const lua::luaL_Reg T7OverchargedLibrary[] = 14 | { 15 | {nullptr, nullptr}, 16 | }; 17 | hks::hksI_openlib(L, "T7Overcharged", T7OverchargedLibrary, 0, 1); 18 | 19 | if (!component_loader::post_start()) 20 | { 21 | game::Com_Error_("", 0, 0x200u, "Error while loading T7Overcharged components"); 22 | game::minlog.WriteLine("Error while loading T7Overcharged components"); 23 | return 0; 24 | } 25 | 26 | game::minlog.WriteLine("T7Overchared initiated"); 27 | 28 | game::LoadDvarHashMap(); 29 | return 1; 30 | } 31 | } -------------------------------------------------------------------------------- /src/client/script/builtins.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "loader/component_loader.hpp" 4 | #include "game/game.hpp" 5 | #include "utils/string.hpp" 6 | 7 | namespace builtins 8 | { 9 | static std::unordered_map custom_functions; 10 | 11 | void register_function(const char* name, void(*funcPtr)(game::scriptInstance_t inst)) 12 | { 13 | custom_functions[fnv1a(name)] = funcPtr; 14 | } 15 | 16 | void is_profile_build_interval(game::scriptInstance_t inst) 17 | { 18 | auto functionHash = game::Scr_GetInt(inst, 0); 19 | if (custom_functions.find(functionHash) == custom_functions.end()) 20 | return game::minlog.WriteLine(utils::string::va("Unknown built-in function: %h", functionHash)); 21 | 22 | custom_functions[functionHash](inst); 23 | } 24 | 25 | class component final : public component_interface 26 | { 27 | public: 28 | void post_start() override 29 | { 30 | game::isProfileBuildFunctionDef->max_args = 255; 31 | game::isProfileBuildFunctionDef->actionFunc = is_profile_build_interval; 32 | } 33 | }; 34 | } 35 | 36 | REGISTER_COMPONENT(builtins::component) -------------------------------------------------------------------------------- /src/client/script/builtins.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace builtins 4 | { 5 | void register_function(const char* name, void(*funcPtr)(game::scriptInstance_t inst)); 6 | } -------------------------------------------------------------------------------- /src/client/std_include.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | -------------------------------------------------------------------------------- /src/client/std_include.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define WIN32_LEAN_AND_MEAN 4 | #include 5 | #pragma comment(lib, "ws2_32.lib") 6 | #include 7 | 8 | #include "havok/structs.hpp" 9 | #include "game/structs.hpp" 10 | 11 | #pragma warning(push) 12 | #pragma warning(disable: 4100) 13 | #pragma warning(disable: 4127) 14 | #pragma warning(disable: 4244) 15 | #pragma warning(disable: 4458) 16 | #pragma warning(disable: 4702) 17 | #pragma warning(disable: 4996) 18 | #pragma warning(disable: 5054) 19 | #pragma warning(disable: 5056) 20 | #pragma warning(disable: 6011) 21 | #pragma warning(disable: 6297) 22 | #pragma warning(disable: 6385) 23 | #pragma warning(disable: 6386) 24 | #pragma warning(disable: 6387) 25 | #pragma warning(disable: 26110) 26 | #pragma warning(disable: 26451) 27 | #pragma warning(disable: 26444) 28 | #pragma warning(disable: 26451) 29 | #pragma warning(disable: 26489) 30 | #pragma warning(disable: 26495) 31 | #pragma warning(disable: 26498) 32 | #pragma warning(disable: 26812) 33 | #pragma warning(disable: 28020) 34 | 35 | #define WIN32_LEAN_AND_MEAN 36 | 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | #include 51 | #include 52 | #include 53 | #include 54 | #include 55 | 56 | // min and max is required by gdi, therefore NOMINMAX won't work 57 | #ifdef max 58 | #undef max 59 | #endif 60 | 61 | #ifdef min 62 | #undef min 63 | #endif 64 | 65 | #include 66 | #include 67 | #include 68 | #include 69 | #include 70 | #include 71 | #include 72 | #include 73 | #include 74 | #include 75 | #include 76 | #include 77 | #include 78 | #include 79 | #include 80 | #include 81 | #include 82 | 83 | #include 84 | #include 85 | 86 | #include 87 | #include 88 | #include 89 | 90 | #include 91 | #include 92 | 93 | #include 94 | 95 | #pragma warning(pop) 96 | #pragma warning(disable: 4100) 97 | 98 | #pragma comment(lib, "ntdll.lib") 99 | #pragma comment(lib, "ws2_32.lib") 100 | #pragma comment(lib, "urlmon.lib" ) 101 | #pragma comment(lib, "iphlpapi.lib") 102 | #pragma comment(lib, "Crypt32.lib") 103 | 104 | using namespace std::literals; 105 | 106 | inline uint32_t fnv1a(const char* key) { 107 | 108 | const char* data = key; 109 | uint32_t hash = 0x4B9ACE2F; 110 | while (*data) 111 | { 112 | hash ^= tolower(*data); 113 | hash *= 0x1000193; 114 | data++; 115 | } 116 | hash *= 0x1000193; 117 | return hash; 118 | } 119 | -------------------------------------------------------------------------------- /src/common/utils/concurrency.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | namespace utils::concurrency 6 | { 7 | template 8 | class container 9 | { 10 | public: 11 | template 12 | R access(F&& accessor) const 13 | { 14 | std::lock_guard _{ mutex_ }; 15 | return accessor(object_); 16 | } 17 | 18 | template 19 | R access(F&& accessor) 20 | { 21 | std::lock_guard _{ mutex_ }; 22 | return accessor(object_); 23 | } 24 | 25 | template 26 | R access_with_lock(F&& accessor) const 27 | { 28 | std::unique_lock lock{ mutex_ }; 29 | return accessor(object_, lock); 30 | } 31 | 32 | template 33 | R access_with_lock(F&& accessor) 34 | { 35 | std::unique_lock lock{ mutex_ }; 36 | return accessor(object_, lock); 37 | } 38 | 39 | T& get_raw() { return object_; } 40 | const T& get_raw() const { return object_; } 41 | 42 | private: 43 | mutable MutexType mutex_{}; 44 | T object_{}; 45 | }; 46 | } 47 | -------------------------------------------------------------------------------- /src/common/utils/file_watcher.cpp: -------------------------------------------------------------------------------- 1 | #include "file_watcher.hpp" 2 | file_watcher::file_watcher() 3 | { 4 | stopWatching(); 5 | timeout = std::chrono::duration(10 * 1000); 6 | watcher_ = std::thread(&file_watcher::watcherFunction, this); 7 | } 8 | 9 | file_watcher& file_watcher::setTimeout(std::chrono::duration timer) 10 | { 11 | timeout = timer; 12 | return *this; 13 | } 14 | 15 | file_watcher::~file_watcher() 16 | { 17 | stopWatching(); 18 | } 19 | 20 | file_watcher& file_watcher::startWatching() 21 | { 22 | watching_ = true; 23 | return *this; 24 | } 25 | 26 | file_watcher& file_watcher::stopWatching() 27 | { 28 | watching_ = false; 29 | return *this; 30 | } 31 | 32 | file_watcher& file_watcher::addFileToWatch(const std::string file) 33 | { 34 | const std::filesystem::path file_path = file; 35 | std::optional value = std::nullopt; 36 | 37 | const std::lock_guard lock(paths_mutex_); 38 | if (paths_.contains(file_path) || std::filesystem::is_directory(file_path)) 39 | return *this; 40 | 41 | if (std::filesystem::exists(file_path)) 42 | value = std::optional(std::filesystem::last_write_time(file_path)); 43 | 44 | paths_[file_path] = value; 45 | return *this; 46 | } 47 | 48 | file_watcher& file_watcher::addFolderToWatch(const std::string folder) 49 | { 50 | const std::filesystem::path folder_path = folder; 51 | const std::lock_guard lock(paths_mutex_); 52 | 53 | if (paths_.contains(folder_path)) 54 | return *this; 55 | 56 | std::optional value = std::nullopt; 57 | 58 | if (std::filesystem::exists(folder_path)) { 59 | value = std::optional(std::filesystem::last_write_time(folder_path)); 60 | 61 | for (auto const path : std::filesystem::recursive_directory_iterator(folder_path)) 62 | { 63 | paths_[path.path()] = std::filesystem::last_write_time(path); 64 | } 65 | } 66 | 67 | paths_[folder_path] = value; 68 | folders_.insert(folder_path); 69 | 70 | return *this; 71 | } 72 | 73 | file_watcher& file_watcher::addFileAction(const std::function& action) 74 | { 75 | const std::lock_guard lock(file_actions_mutex_); 76 | 77 | file_actions_.push_back(action); 78 | return *this; 79 | } 80 | 81 | file_watcher& file_watcher::addFolderAction(const std::function& action) 82 | { 83 | const std::lock_guard lock(folder_actions_mutex_); 84 | 85 | folder_actions_.push_back(action); 86 | return *this; 87 | } 88 | 89 | 90 | void file_watcher::watcherFunction() 91 | { 92 | while (true) 93 | { 94 | std::this_thread::sleep_for(timeout); 95 | if (!watching_) 96 | { 97 | continue; 98 | } 99 | const std::lock_guard lock_files(paths_mutex_); 100 | for (auto const path : paths_) 101 | { 102 | if (!std::filesystem::exists(path.first)) 103 | { 104 | if (path.second.has_value()) 105 | { 106 | //File has been deleted 107 | if (folders_.contains(path.first)) 108 | { 109 | folder_changes_[path.first] = Folder_status::erased; 110 | } 111 | else 112 | { 113 | file_changes_[path.first] = File_status::erased; 114 | 115 | } 116 | paths_[path.first] = std::nullopt; 117 | } 118 | } 119 | else 120 | { 121 | std::optional newValue(std::filesystem::last_write_time(path.first)); 122 | bool is_directory = (folders_.contains(path.first)); 123 | if (!path.second.has_value()) 124 | { 125 | if (is_directory) 126 | { 127 | folder_changes_[path.first] = Folder_status::created; 128 | } 129 | else 130 | { 131 | file_changes_[path.first] = File_status::created; 132 | } 133 | 134 | paths_[path.first] = newValue; 135 | } 136 | else if (paths_[path.first] != newValue) 137 | { 138 | if (is_directory) 139 | { 140 | folder_changes_[path.first] = Folder_status::modified; 141 | } 142 | else 143 | { 144 | file_changes_[path.first] = File_status::modified; 145 | } 146 | paths_[path.first] = newValue; 147 | } 148 | if (is_directory) 149 | { 150 | for (auto const dirpath : std::filesystem::recursive_directory_iterator(path.first)) 151 | { 152 | if (!paths_.contains(dirpath.path())) 153 | { 154 | paths_[dirpath.path()] = std::filesystem::last_write_time(dirpath); 155 | if (std::filesystem::is_directory(dirpath.path())) 156 | { 157 | folders_.insert(dirpath.path()); 158 | folder_changes_[dirpath.path()] = Folder_status::created; 159 | } 160 | else 161 | { 162 | file_changes_[dirpath.path()] = File_status::created; 163 | } 164 | } 165 | } 166 | } 167 | } 168 | } 169 | 170 | const std::lock_guard lock_file_actions(file_actions_mutex_); 171 | fireFileActions(); 172 | 173 | const std::lock_guard lock_folder_actions(folder_actions_mutex_); 174 | fireFolderActions(); 175 | } 176 | } 177 | 178 | 179 | void file_watcher::fireFileActions() 180 | { 181 | for (const auto action : file_actions_) 182 | { 183 | for (const auto change : file_changes_) 184 | { 185 | action(change.first.string(), change.second); 186 | } 187 | } 188 | file_changes_.clear(); 189 | } 190 | 191 | void file_watcher::fireFolderActions() 192 | { 193 | for (const auto action : folder_actions_) 194 | { 195 | for (const auto change : folder_changes_) 196 | { 197 | action(change.first.string(), change.second); 198 | } 199 | } 200 | folder_changes_.clear(); 201 | } -------------------------------------------------------------------------------- /src/common/utils/file_watcher.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | enum class File_status { created, modified, erased }; 15 | enum class Folder_status { created, modified, erased }; 16 | 17 | class file_watcher 18 | { 19 | private: 20 | std::atomic watching_; 21 | std::chrono::duration timeout; 22 | std::mutex paths_mutex_; 23 | std::mutex file_actions_mutex_; 24 | std::mutex folder_actions_mutex_; 25 | std::map> paths_; 26 | std::list> file_actions_; 27 | std::list> folder_actions_; 28 | std::set folders_; 29 | std::map file_changes_; 30 | std::map folder_changes_; 31 | std::thread watcher_; 32 | void watcherFunction(); 33 | void fireFileActions(); 34 | void fireFolderActions(); 35 | 36 | public: 37 | file_watcher(); 38 | ~file_watcher(); 39 | file_watcher& startWatching(); 40 | file_watcher& stopWatching(); 41 | file_watcher& setTimeout(std::chrono::duration); 42 | file_watcher& addFileToWatch(const std::string); 43 | file_watcher& addFolderToWatch(const std::string); 44 | file_watcher& addFileAction(const std::function&); 45 | file_watcher& addFolderAction(const std::function&); 46 | }; -------------------------------------------------------------------------------- /src/common/utils/hook.cpp: -------------------------------------------------------------------------------- 1 | #include "hook.hpp" 2 | #include "string.hpp" 3 | 4 | #include 5 | 6 | namespace utils::hook 7 | { 8 | namespace 9 | { 10 | [[maybe_unused]] class _ 11 | { 12 | public: 13 | _() 14 | { 15 | if (MH_Initialize() != MH_OK) 16 | { 17 | throw std::runtime_error("Failed to initialize MinHook"); 18 | } 19 | } 20 | 21 | ~_() 22 | { 23 | MH_Uninitialize(); 24 | } 25 | } __; 26 | } 27 | 28 | void assembler::pushad64() 29 | { 30 | this->push(rax); 31 | this->push(rcx); 32 | this->push(rdx); 33 | this->push(rbx); 34 | this->push(rsp); 35 | this->push(rbp); 36 | this->push(rsi); 37 | this->push(rdi); 38 | 39 | this->sub(rsp, 0x40); 40 | } 41 | 42 | void assembler::popad64() 43 | { 44 | this->add(rsp, 0x40); 45 | 46 | this->pop(rdi); 47 | this->pop(rsi); 48 | this->pop(rbp); 49 | this->pop(rsp); 50 | this->pop(rbx); 51 | this->pop(rdx); 52 | this->pop(rcx); 53 | this->pop(rax); 54 | } 55 | 56 | void assembler::prepare_stack_for_call() 57 | { 58 | const auto reserve_callee_space = this->newLabel(); 59 | const auto stack_unaligned = this->newLabel(); 60 | 61 | this->test(rsp, 0xF); 62 | this->jnz(stack_unaligned); 63 | 64 | this->sub(rsp, 0x8); 65 | this->push(rsp); 66 | 67 | this->push(rax); 68 | this->mov(rax, ptr(rsp, 8, 8)); 69 | this->add(rax, 0x8); 70 | this->mov(ptr(rsp, 8, 8), rax); 71 | this->pop(rax); 72 | 73 | this->jmp(reserve_callee_space); 74 | 75 | this->bind(stack_unaligned); 76 | this->push(rsp); 77 | 78 | this->bind(reserve_callee_space); 79 | this->sub(rsp, 0x40); 80 | } 81 | 82 | void assembler::restore_stack_after_call() 83 | { 84 | this->lea(rsp, ptr(rsp, 0x40)); 85 | this->pop(rsp); 86 | } 87 | 88 | asmjit::Error assembler::call(void* target) 89 | { 90 | return Assembler::call(size_t(target)); 91 | } 92 | 93 | asmjit::Error assembler::jmp(void* target) 94 | { 95 | return Assembler::jmp(size_t(target)); 96 | } 97 | 98 | detour::detour(const size_t place, void* target) : detour(reinterpret_cast(place), target) 99 | { 100 | } 101 | 102 | detour::detour(void* place, void* target) 103 | { 104 | this->create(place, target); 105 | } 106 | 107 | detour::~detour() 108 | { 109 | this->clear(); 110 | } 111 | 112 | void detour::enable() const 113 | { 114 | MH_EnableHook(this->place_); 115 | } 116 | 117 | void detour::disable() const 118 | { 119 | MH_DisableHook(this->place_); 120 | } 121 | 122 | void detour::create(void* place, void* target) 123 | { 124 | this->clear(); 125 | this->place_ = place; 126 | 127 | if (MH_CreateHook(this->place_, target, &this->original_) != MH_OK) 128 | { 129 | throw std::runtime_error(string::va("Unable to create hook at location: %p", this->place_)); 130 | } 131 | 132 | this->enable(); 133 | } 134 | 135 | void detour::create(const size_t place, void* target) 136 | { 137 | this->create(reinterpret_cast(place), target); 138 | } 139 | 140 | void detour::clear() 141 | { 142 | if (this->place_) 143 | { 144 | MH_RemoveHook(this->place_); 145 | } 146 | 147 | this->place_ = nullptr; 148 | this->original_ = nullptr; 149 | } 150 | 151 | void* detour::get_original() const 152 | { 153 | return this->original_; 154 | } 155 | 156 | bool iat(const nt::library& library, const std::string& target_library, const std::string& process, void* stub) 157 | { 158 | if (!library.is_valid()) return false; 159 | 160 | auto* const ptr = library.get_iat_entry(target_library, process); 161 | if (!ptr) return false; 162 | 163 | DWORD protect; 164 | VirtualProtect(ptr, sizeof(*ptr), PAGE_EXECUTE_READWRITE, &protect); 165 | 166 | *ptr = stub; 167 | 168 | VirtualProtect(ptr, sizeof(*ptr), protect, &protect); 169 | return true; 170 | } 171 | 172 | void nop(void* place, const size_t length) 173 | { 174 | DWORD old_protect{}; 175 | VirtualProtect(place, length, PAGE_EXECUTE_READWRITE, &old_protect); 176 | 177 | std::memset(place, 0x90, length); 178 | 179 | VirtualProtect(place, length, old_protect, &old_protect); 180 | FlushInstructionCache(GetCurrentProcess(), place, length); 181 | } 182 | 183 | void nop(const size_t place, const size_t length) 184 | { 185 | nop(reinterpret_cast(place), length); 186 | } 187 | 188 | void copy(void* place, const void* data, const size_t length) 189 | { 190 | DWORD old_protect{}; 191 | VirtualProtect(place, length, PAGE_EXECUTE_READWRITE, &old_protect); 192 | 193 | std::memmove(place, data, length); 194 | 195 | VirtualProtect(place, length, old_protect, &old_protect); 196 | FlushInstructionCache(GetCurrentProcess(), place, length); 197 | } 198 | 199 | void copy(const size_t place, const void* data, const size_t length) 200 | { 201 | copy(reinterpret_cast(place), data, length); 202 | } 203 | 204 | bool is_relatively_far(const void* pointer, const void* data, const int offset) 205 | { 206 | const int64_t diff = size_t(data) - (size_t(pointer) + offset); 207 | const auto small_diff = int32_t(diff); 208 | return diff != int64_t(small_diff); 209 | } 210 | 211 | void call(void* pointer, void* data) 212 | { 213 | if (is_relatively_far(pointer, data)) 214 | { 215 | throw std::runtime_error("Too far away to create 32bit relative branch"); 216 | } 217 | 218 | auto* patch_pointer = PBYTE(pointer); 219 | set(patch_pointer, 0xE8); 220 | set(patch_pointer + 1, int32_t(size_t(data) - (size_t(pointer) + 5))); 221 | } 222 | 223 | void call(const size_t pointer, void* data) 224 | { 225 | return call(reinterpret_cast(pointer), data); 226 | } 227 | 228 | void call(const size_t pointer, const size_t data) 229 | { 230 | return call(pointer, reinterpret_cast(data)); 231 | } 232 | 233 | void jump(void* pointer, void* data, const bool use_far) 234 | { 235 | static const unsigned char jump_data[] = { 236 | 0x48, 0xb8, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0xff, 0xe0 237 | }; 238 | 239 | if (!use_far && is_relatively_far(pointer, data)) 240 | { 241 | throw std::runtime_error("Too far away to create 32bit relative branch"); 242 | } 243 | 244 | auto* patch_pointer = PBYTE(pointer); 245 | 246 | if (use_far) 247 | { 248 | copy(patch_pointer, jump_data, sizeof(jump_data)); 249 | copy(patch_pointer + 2, &data, sizeof(data)); 250 | } 251 | else 252 | { 253 | set(patch_pointer, 0xE9); 254 | set(patch_pointer + 1, int32_t(size_t(data) - (size_t(pointer) + 5))); 255 | } 256 | } 257 | 258 | void jump(const size_t pointer, void* data, const bool use_far) 259 | { 260 | return jump(reinterpret_cast(pointer), data, use_far); 261 | } 262 | 263 | void jump(const size_t pointer, const size_t data, const bool use_far) 264 | { 265 | return jump(pointer, reinterpret_cast(data), use_far); 266 | } 267 | 268 | void* assemble(const std::function& asm_function) 269 | { 270 | static asmjit::JitRuntime runtime; 271 | 272 | asmjit::CodeHolder code; 273 | code.init(runtime.environment()); 274 | 275 | assembler a(&code); 276 | 277 | asm_function(a); 278 | 279 | void* result = nullptr; 280 | runtime.add(&result, &code); 281 | 282 | return result; 283 | } 284 | 285 | void inject(void* pointer, const void* data) 286 | { 287 | if (is_relatively_far(pointer, data, 4)) 288 | { 289 | throw std::runtime_error("Too far away to create 32bit relative branch"); 290 | } 291 | 292 | set(pointer, int32_t(size_t(data) - (size_t(pointer) + 4))); 293 | } 294 | 295 | void inject(const size_t pointer, const void* data) 296 | { 297 | return inject(reinterpret_cast(pointer), data); 298 | } 299 | 300 | void* follow_branch(void* address) 301 | { 302 | auto* const data = static_cast(address); 303 | if (*data != 0xE8 && *data != 0xE9) 304 | { 305 | throw std::runtime_error("No branch instruction found"); 306 | } 307 | 308 | return extract(data + 1); 309 | } 310 | } 311 | -------------------------------------------------------------------------------- /src/common/utils/hook.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "signature.hpp" 3 | 4 | #include 5 | #include 6 | 7 | using namespace asmjit::x86; 8 | 9 | namespace utils::hook 10 | { 11 | class assembler : public Assembler 12 | { 13 | public: 14 | using Assembler::Assembler; 15 | using Assembler::call; 16 | using Assembler::jmp; 17 | 18 | void pushad64(); 19 | void popad64(); 20 | 21 | void prepare_stack_for_call(); 22 | void restore_stack_after_call(); 23 | 24 | template 25 | void call_aligned(T&& target) 26 | { 27 | this->prepare_stack_for_call(); 28 | this->call(std::forward(target)); 29 | this->restore_stack_after_call(); 30 | } 31 | 32 | asmjit::Error call(void* target); 33 | asmjit::Error jmp(void* target); 34 | }; 35 | 36 | class detour 37 | { 38 | public: 39 | detour() = default; 40 | detour(void* place, void* target); 41 | detour(size_t place, void* target); 42 | ~detour(); 43 | 44 | detour(detour&& other) noexcept 45 | { 46 | this->operator=(std::move(other)); 47 | } 48 | 49 | detour& operator=(detour&& other) noexcept 50 | { 51 | if (this != &other) 52 | { 53 | this->~detour(); 54 | 55 | this->place_ = other.place_; 56 | this->original_ = other.original_; 57 | 58 | other.place_ = nullptr; 59 | other.original_ = nullptr; 60 | } 61 | 62 | return *this; 63 | } 64 | 65 | detour(const detour&) = delete; 66 | detour& operator=(const detour&) = delete; 67 | 68 | void enable() const; 69 | void disable() const; 70 | 71 | void create(void* place, void* target); 72 | void create(size_t place, void* target); 73 | void clear(); 74 | 75 | template 76 | T* get() const 77 | { 78 | return static_cast(this->get_original()); 79 | } 80 | 81 | template 82 | T invoke(Args ... args) 83 | { 84 | return static_cast(this->get_original())(args...); 85 | } 86 | 87 | [[nodiscard]] void* get_original() const; 88 | 89 | private: 90 | void* place_{}; 91 | void* original_{}; 92 | }; 93 | 94 | bool iat(const nt::library& library, const std::string& target_library, const std::string& process, void* stub); 95 | 96 | void nop(void* place, size_t length); 97 | void nop(size_t place, size_t length); 98 | 99 | void copy(void* place, const void* data, size_t length); 100 | void copy(size_t place, const void* data, size_t length); 101 | 102 | bool is_relatively_far(const void* pointer, const void* data, int offset = 5); 103 | 104 | void call(void* pointer, void* data); 105 | void call(size_t pointer, void* data); 106 | void call(size_t pointer, size_t data); 107 | 108 | void jump(void* pointer, void* data, bool use_far = false); 109 | void jump(size_t pointer, void* data, bool use_far = false); 110 | void jump(size_t pointer, size_t data, bool use_far = false); 111 | 112 | void* assemble(const std::function& asm_function); 113 | 114 | void inject(void* pointer, const void* data); 115 | void inject(size_t pointer, const void* data); 116 | 117 | template 118 | T extract(void* address) 119 | { 120 | auto* const data = static_cast(address); 121 | const auto offset = *reinterpret_cast(data); 122 | return reinterpret_cast(data + offset + 4); 123 | } 124 | 125 | void* follow_branch(void* address); 126 | 127 | template 128 | static void set(void* place, T value) 129 | { 130 | DWORD old_protect; 131 | VirtualProtect(place, sizeof(T), PAGE_EXECUTE_READWRITE, &old_protect); 132 | 133 | *static_cast(place) = value; 134 | 135 | VirtualProtect(place, sizeof(T), old_protect, &old_protect); 136 | FlushInstructionCache(GetCurrentProcess(), place, sizeof(T)); 137 | } 138 | 139 | template 140 | static void set(const size_t place, T value) 141 | { 142 | return set(reinterpret_cast(place), value); 143 | } 144 | 145 | template 146 | static T invoke(size_t func, Args ... args) 147 | { 148 | return reinterpret_cast(func)(args...); 149 | } 150 | 151 | template 152 | static T invoke(void* func, Args ... args) 153 | { 154 | return static_cast(func)(args...); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/common/utils/io.cpp: -------------------------------------------------------------------------------- 1 | #include "io.hpp" 2 | #include "nt.hpp" 3 | #include 4 | 5 | namespace utils::io 6 | { 7 | bool remove_file(const std::string& file) 8 | { 9 | return DeleteFileA(file.data()) == TRUE; 10 | } 11 | 12 | bool move_file(const std::string& src, const std::string& target) 13 | { 14 | return MoveFileA(src.data(), target.data()) == TRUE; 15 | } 16 | 17 | bool file_exists(const std::string& file) 18 | { 19 | return std::ifstream(file).good(); 20 | } 21 | 22 | bool write_file(const std::string& file, const std::string& data, const bool append) 23 | { 24 | const auto pos = file.find_last_of("/\\"); 25 | if (pos != std::string::npos) 26 | { 27 | create_directory(file.substr(0, pos)); 28 | } 29 | 30 | std::ofstream stream( 31 | file, std::ios::binary | std::ofstream::out | (append ? std::ofstream::app : 0)); 32 | 33 | if (stream.is_open()) 34 | { 35 | stream.write(data.data(), data.size()); 36 | stream.close(); 37 | return true; 38 | } 39 | 40 | return false; 41 | } 42 | 43 | std::string read_file(const std::string& file) 44 | { 45 | std::string data; 46 | read_file(file, &data); 47 | return data; 48 | } 49 | 50 | bool read_file(const std::string& file, std::string* data) 51 | { 52 | if (!data) return false; 53 | data->clear(); 54 | 55 | if (file_exists(file)) 56 | { 57 | std::ifstream stream(file, std::ios::binary); 58 | if (!stream.is_open()) return false; 59 | 60 | stream.seekg(0, std::ios::end); 61 | const std::streamsize size = stream.tellg(); 62 | stream.seekg(0, std::ios::beg); 63 | 64 | if (size > -1) 65 | { 66 | data->resize(static_cast(size)); 67 | stream.read(const_cast(data->data()), size); 68 | stream.close(); 69 | return true; 70 | } 71 | } 72 | 73 | return false; 74 | } 75 | 76 | size_t file_size(const std::string& file) 77 | { 78 | if (file_exists(file)) 79 | { 80 | std::ifstream stream(file, std::ios::binary); 81 | 82 | if (stream.good()) 83 | { 84 | stream.seekg(0, std::ios::end); 85 | return static_cast(stream.tellg()); 86 | } 87 | } 88 | 89 | return 0; 90 | } 91 | 92 | bool create_directory(const std::string& directory) 93 | { 94 | return std::filesystem::create_directories(directory); 95 | } 96 | 97 | bool directory_exists(const std::string& directory) 98 | { 99 | return std::filesystem::is_directory(directory); 100 | } 101 | 102 | bool directory_is_empty(const std::string& directory) 103 | { 104 | return std::filesystem::is_empty(directory); 105 | } 106 | 107 | std::vector list_files(const std::string& directory) 108 | { 109 | std::vector files; 110 | 111 | for (auto& file : std::filesystem::directory_iterator(directory)) 112 | { 113 | files.push_back(file.path().generic_string()); 114 | } 115 | 116 | return files; 117 | } 118 | 119 | void copy_folder(const std::filesystem::path& src, const std::filesystem::path& target) 120 | { 121 | std::filesystem::copy(src, target, std::filesystem::copy_options::overwrite_existing | std::filesystem::copy_options::recursive); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/common/utils/io.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | namespace utils::io 8 | { 9 | bool remove_file(const std::string& file); 10 | bool move_file(const std::string& src, const std::string& target); 11 | bool file_exists(const std::string& file); 12 | bool write_file(const std::string& file, const std::string& data, bool append = false); 13 | bool read_file(const std::string& file, std::string* data); 14 | std::string read_file(const std::string& file); 15 | size_t file_size(const std::string& file); 16 | bool create_directory(const std::string& directory); 17 | bool directory_exists(const std::string& directory); 18 | bool directory_is_empty(const std::string& directory); 19 | std::vector list_files(const std::string& directory); 20 | void copy_folder(const std::filesystem::path& src, const std::filesystem::path& target); 21 | } 22 | -------------------------------------------------------------------------------- /src/common/utils/memory.cpp: -------------------------------------------------------------------------------- 1 | #include "memory.hpp" 2 | #include "nt.hpp" 3 | 4 | namespace utils 5 | { 6 | memory::allocator memory::mem_allocator_; 7 | 8 | memory::allocator::~allocator() 9 | { 10 | this->clear(); 11 | } 12 | 13 | void memory::allocator::clear() 14 | { 15 | std::lock_guard _(this->mutex_); 16 | 17 | for (auto& data : this->pool_) 18 | { 19 | memory::free(data); 20 | } 21 | 22 | this->pool_.clear(); 23 | } 24 | 25 | void memory::allocator::free(void* data) 26 | { 27 | std::lock_guard _(this->mutex_); 28 | 29 | const auto j = std::find(this->pool_.begin(), this->pool_.end(), data); 30 | if (j != this->pool_.end()) 31 | { 32 | memory::free(data); 33 | this->pool_.erase(j); 34 | } 35 | } 36 | 37 | void memory::allocator::free(const void* data) 38 | { 39 | this->free(const_cast(data)); 40 | } 41 | 42 | void* memory::allocator::allocate(const size_t length) 43 | { 44 | std::lock_guard _(this->mutex_); 45 | 46 | const auto data = memory::allocate(length); 47 | this->pool_.push_back(data); 48 | return data; 49 | } 50 | 51 | bool memory::allocator::empty() const 52 | { 53 | return this->pool_.empty(); 54 | } 55 | 56 | char* memory::allocator::duplicate_string(const std::string& string) 57 | { 58 | std::lock_guard _(this->mutex_); 59 | 60 | const auto data = memory::duplicate_string(string); 61 | this->pool_.push_back(data); 62 | return data; 63 | } 64 | 65 | void* memory::allocate(const size_t length) 66 | { 67 | return calloc(length, 1); 68 | } 69 | 70 | char* memory::duplicate_string(const std::string& string) 71 | { 72 | const auto new_string = allocate_array(string.size() + 1); 73 | std::memcpy(new_string, string.data(), string.size()); 74 | return new_string; 75 | } 76 | 77 | void memory::free(void* data) 78 | { 79 | if (data) 80 | { 81 | ::free(data); 82 | } 83 | } 84 | 85 | void memory::free(const void* data) 86 | { 87 | free(const_cast(data)); 88 | } 89 | 90 | bool memory::is_set(const void* mem, const char chr, const size_t length) 91 | { 92 | const auto mem_arr = static_cast(mem); 93 | 94 | for (size_t i = 0; i < length; ++i) 95 | { 96 | if (mem_arr[i] != chr) 97 | { 98 | return false; 99 | } 100 | } 101 | 102 | return true; 103 | } 104 | 105 | bool memory::is_bad_read_ptr(const void* ptr) 106 | { 107 | MEMORY_BASIC_INFORMATION mbi = {}; 108 | if (VirtualQuery(ptr, &mbi, sizeof(mbi))) 109 | { 110 | const DWORD mask = (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | 111 | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY); 112 | auto b = !(mbi.Protect & mask); 113 | // check the page is not a guard page 114 | if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) b = true; 115 | 116 | return b; 117 | } 118 | return true; 119 | } 120 | 121 | bool memory::is_bad_code_ptr(const void* ptr) 122 | { 123 | MEMORY_BASIC_INFORMATION mbi = {}; 124 | if (VirtualQuery(ptr, &mbi, sizeof(mbi))) 125 | { 126 | const DWORD mask = (PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY); 127 | auto b = !(mbi.Protect & mask); 128 | // check the page is not a guard page 129 | if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) b = true; 130 | 131 | return b; 132 | } 133 | return true; 134 | } 135 | 136 | bool memory::is_rdata_ptr(void* pointer) 137 | { 138 | const std::string rdata = ".rdata"; 139 | const auto pointer_lib = utils::nt::library::get_by_address(pointer); 140 | 141 | for (const auto& section : pointer_lib.get_section_headers()) 142 | { 143 | const auto size = sizeof(section->Name); 144 | char name[size + 1]; 145 | name[size] = 0; 146 | std::memcpy(name, section->Name, size); 147 | 148 | if (name == rdata) 149 | { 150 | const auto target = size_t(pointer); 151 | const size_t source_start = size_t(pointer_lib.get_ptr()) + section->PointerToRawData; 152 | const size_t source_end = source_start + section->SizeOfRawData; 153 | 154 | return target >= source_start && target <= source_end; 155 | } 156 | } 157 | 158 | return false; 159 | } 160 | 161 | memory::allocator* memory::get_allocator() 162 | { 163 | return &memory::mem_allocator_; 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /src/common/utils/memory.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | namespace utils 7 | { 8 | class memory final 9 | { 10 | public: 11 | class allocator final 12 | { 13 | public: 14 | ~allocator(); 15 | 16 | void clear(); 17 | 18 | void free(void* data); 19 | 20 | void free(const void* data); 21 | 22 | void* allocate(size_t length); 23 | 24 | template 25 | inline T* allocate() 26 | { 27 | return this->allocate_array(1); 28 | } 29 | 30 | template 31 | inline T* allocate_array(const size_t count = 1) 32 | { 33 | return static_cast(this->allocate(count * sizeof(T))); 34 | } 35 | 36 | bool empty() const; 37 | 38 | char* duplicate_string(const std::string& string); 39 | 40 | private: 41 | std::mutex mutex_; 42 | std::vector pool_; 43 | }; 44 | 45 | static void* allocate(size_t length); 46 | 47 | template 48 | static inline T* allocate() 49 | { 50 | return allocate_array(1); 51 | } 52 | 53 | template 54 | static inline T* allocate_array(const size_t count = 1) 55 | { 56 | return static_cast(allocate(count * sizeof(T))); 57 | } 58 | 59 | static char* duplicate_string(const std::string& string); 60 | 61 | static void free(void* data); 62 | static void free(const void* data); 63 | 64 | static bool is_set(const void* mem, char chr, size_t length); 65 | 66 | static bool is_bad_read_ptr(const void* ptr); 67 | static bool is_bad_code_ptr(const void* ptr); 68 | static bool is_rdata_ptr(void* ptr); 69 | 70 | static allocator* get_allocator(); 71 | 72 | private: 73 | static allocator mem_allocator_; 74 | }; 75 | } 76 | -------------------------------------------------------------------------------- /src/common/utils/minlog.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | 6 | #ifndef MINLOG_OUT_FILE 7 | #define MINLOG_OUT_FILE "MinLog.log" 8 | #endif 9 | 10 | #ifndef MINLOG_OUT_DIR 11 | #define MINLOG_OUT_DIR "logs" 12 | #endif 13 | 14 | class MinLog 15 | { 16 | private: 17 | std::ofstream OutputStream; 18 | bool _isOpen = false; 19 | 20 | public: 21 | static MinLog& Instance() 22 | { 23 | static MinLog _instance = MinLog(MINLOG_OUT_FILE, MINLOG_OUT_DIR); 24 | return _instance; 25 | } 26 | 27 | MinLog() { } 28 | 29 | MinLog(const char* filename, const char* dir = "") 30 | { 31 | Open(filename, dir); 32 | } 33 | 34 | void Open(const char* filename, const char* dir = "") 35 | { 36 | if (_isOpen) return; 37 | std::filesystem::path const directory = std::filesystem::current_path() / dir; 38 | std::filesystem::create_directories(directory); 39 | MinLog::OutputStream = std::ofstream(directory / filename); 40 | _isOpen = true; 41 | } 42 | 43 | void Write(const char* value) 44 | { 45 | MinLog::OutputStream << value; 46 | std::cout << value; 47 | } 48 | 49 | void WriteLine(const char* value) 50 | { 51 | MinLog::OutputStream << value << std::endl; 52 | std::cout << value << std::endl; 53 | } 54 | 55 | void WriteDebug(const char* value) 56 | { 57 | #ifdef DEBUG 58 | MinLog::OutputStream << value << std::endl; 59 | std::cout << value << std::endl; 60 | #endif 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /src/common/utils/nt.cpp: -------------------------------------------------------------------------------- 1 | #include "nt.hpp" 2 | 3 | namespace utils::nt 4 | { 5 | library library::load(const std::string& name) 6 | { 7 | return library(LoadLibraryA(name.data())); 8 | } 9 | 10 | library library::load(const std::filesystem::path& path) 11 | { 12 | return library::load(path.generic_string()); 13 | } 14 | 15 | library library::get_by_address(void* address) 16 | { 17 | HMODULE handle = nullptr; 18 | GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, static_cast(address), &handle); 19 | return library(handle); 20 | } 21 | 22 | library::library() 23 | { 24 | this->module_ = GetModuleHandleA(nullptr); 25 | } 26 | 27 | library::library(const std::string& name) 28 | { 29 | this->module_ = GetModuleHandleA(name.data()); 30 | } 31 | 32 | library::library(const HMODULE handle) 33 | { 34 | this->module_ = handle; 35 | } 36 | 37 | bool library::operator==(const library& obj) const 38 | { 39 | return this->module_ == obj.module_; 40 | } 41 | 42 | library::operator bool() const 43 | { 44 | return this->is_valid(); 45 | } 46 | 47 | library::operator HMODULE() const 48 | { 49 | return this->get_handle(); 50 | } 51 | 52 | PIMAGE_NT_HEADERS library::get_nt_headers() const 53 | { 54 | if (!this->is_valid()) return nullptr; 55 | return reinterpret_cast(this->get_ptr() + this->get_dos_header()->e_lfanew); 56 | } 57 | 58 | PIMAGE_DOS_HEADER library::get_dos_header() const 59 | { 60 | return reinterpret_cast(this->get_ptr()); 61 | } 62 | 63 | PIMAGE_OPTIONAL_HEADER library::get_optional_header() const 64 | { 65 | if (!this->is_valid()) return nullptr; 66 | return &this->get_nt_headers()->OptionalHeader; 67 | } 68 | 69 | std::vector library::get_section_headers() const 70 | { 71 | std::vector headers; 72 | 73 | auto nt_headers = this->get_nt_headers(); 74 | auto section = IMAGE_FIRST_SECTION(nt_headers); 75 | 76 | for (uint16_t i = 0; i < nt_headers->FileHeader.NumberOfSections; ++i, ++section) 77 | { 78 | if (section) headers.push_back(section); 79 | else OutputDebugStringA("There was an invalid section :O"); 80 | } 81 | 82 | return headers; 83 | } 84 | 85 | std::uint8_t* library::get_ptr() const 86 | { 87 | return reinterpret_cast(this->module_); 88 | } 89 | 90 | void library::unprotect() const 91 | { 92 | if (!this->is_valid()) return; 93 | 94 | DWORD protection; 95 | VirtualProtect(this->get_ptr(), this->get_optional_header()->SizeOfImage, PAGE_EXECUTE_READWRITE, 96 | &protection); 97 | } 98 | 99 | size_t library::get_relative_entry_point() const 100 | { 101 | if (!this->is_valid()) return 0; 102 | return this->get_nt_headers()->OptionalHeader.AddressOfEntryPoint; 103 | } 104 | 105 | void* library::get_entry_point() const 106 | { 107 | if (!this->is_valid()) return nullptr; 108 | return this->get_ptr() + this->get_relative_entry_point(); 109 | } 110 | 111 | bool library::is_valid() const 112 | { 113 | return this->module_ != nullptr && this->get_dos_header()->e_magic == IMAGE_DOS_SIGNATURE; 114 | } 115 | 116 | std::string library::get_name() const 117 | { 118 | if (!this->is_valid()) return ""; 119 | 120 | auto path = this->get_path(); 121 | const auto pos = path.find_last_of("/\\"); 122 | if (pos == std::string::npos) return path; 123 | 124 | return path.substr(pos + 1); 125 | } 126 | 127 | std::string library::get_path() const 128 | { 129 | if (!this->is_valid()) return ""; 130 | 131 | char name[MAX_PATH] = {0}; 132 | GetModuleFileNameA(this->module_, name, sizeof name); 133 | 134 | return name; 135 | } 136 | 137 | std::string library::get_folder() const 138 | { 139 | if (!this->is_valid()) return ""; 140 | 141 | const auto path = std::filesystem::path(this->get_path()); 142 | return path.parent_path().generic_string(); 143 | } 144 | 145 | void library::free() 146 | { 147 | if (this->is_valid()) 148 | { 149 | FreeLibrary(this->module_); 150 | this->module_ = nullptr; 151 | } 152 | } 153 | 154 | HMODULE library::get_handle() const 155 | { 156 | return this->module_; 157 | } 158 | 159 | void** library::get_iat_entry(const std::string& module_name, const std::string& proc_name) const 160 | { 161 | if (!this->is_valid()) return nullptr; 162 | 163 | const library other_module(module_name); 164 | if (!other_module.is_valid()) return nullptr; 165 | 166 | const auto target_function = other_module.get_proc(proc_name); 167 | if (!target_function) return nullptr; 168 | 169 | auto* header = this->get_optional_header(); 170 | if (!header) return nullptr; 171 | 172 | auto* import_descriptor = reinterpret_cast(this->get_ptr() + header->DataDirectory 173 | [IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); 174 | 175 | while (import_descriptor->Name) 176 | { 177 | if (!_stricmp(reinterpret_cast(this->get_ptr() + import_descriptor->Name), module_name.data())) 178 | { 179 | auto* original_thunk_data = reinterpret_cast(import_descriptor-> 180 | OriginalFirstThunk + this->get_ptr()); 181 | auto* thunk_data = reinterpret_cast(import_descriptor->FirstThunk + this-> 182 | get_ptr()); 183 | 184 | while (original_thunk_data->u1.AddressOfData) 185 | { 186 | const size_t ordinal_number = original_thunk_data->u1.AddressOfData & 0xFFFFFFF; 187 | 188 | if (ordinal_number > 0xFFFF) continue; 189 | 190 | if (GetProcAddress(other_module.module_, reinterpret_cast(ordinal_number)) == 191 | target_function) 192 | { 193 | return reinterpret_cast(&thunk_data->u1.Function); 194 | } 195 | 196 | ++original_thunk_data; 197 | ++thunk_data; 198 | } 199 | 200 | //break; 201 | } 202 | 203 | ++import_descriptor; 204 | } 205 | 206 | return nullptr; 207 | } 208 | 209 | void raise_hard_exception() 210 | { 211 | int data = false; 212 | const library ntdll("ntdll.dll"); 213 | ntdll.invoke_pascal("RtlAdjustPrivilege", 19, true, false, &data); 214 | ntdll.invoke_pascal("NtRaiseHardError", 0xC000007B, 0, nullptr, nullptr, 6, &data); 215 | } 216 | 217 | std::string load_resource(const int id) 218 | { 219 | auto* const res = FindResource(library(), MAKEINTRESOURCE(id), RT_RCDATA); 220 | if (!res) return {}; 221 | 222 | auto* const handle = LoadResource(nullptr, res); 223 | if (!handle) return {}; 224 | 225 | return std::string(LPSTR(LockResource(handle)), SizeofResource(nullptr, res)); 226 | } 227 | 228 | void relaunch_self() 229 | { 230 | const utils::nt::library self; 231 | 232 | STARTUPINFOA startup_info; 233 | PROCESS_INFORMATION process_info; 234 | 235 | ZeroMemory(&startup_info, sizeof(startup_info)); 236 | ZeroMemory(&process_info, sizeof(process_info)); 237 | startup_info.cb = sizeof(startup_info); 238 | 239 | char current_dir[MAX_PATH]; 240 | GetCurrentDirectoryA(sizeof(current_dir), current_dir); 241 | auto* const command_line = GetCommandLineA(); 242 | 243 | CreateProcessA(self.get_path().data(), command_line, nullptr, nullptr, false, NULL, nullptr, current_dir, 244 | &startup_info, &process_info); 245 | 246 | if (process_info.hThread && process_info.hThread != INVALID_HANDLE_VALUE) CloseHandle(process_info.hThread); 247 | if (process_info.hProcess && process_info.hProcess != INVALID_HANDLE_VALUE) CloseHandle(process_info.hProcess); 248 | } 249 | 250 | void terminate(const uint32_t code) 251 | { 252 | TerminateProcess(GetCurrentProcess(), code); 253 | } 254 | } 255 | -------------------------------------------------------------------------------- /src/common/utils/nt.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define WIN32_LEAN_AND_MEAN 4 | #include 5 | 6 | // min and max is required by gdi, therefore NOMINMAX won't work 7 | #ifdef max 8 | #undef max 9 | #endif 10 | 11 | #ifdef min 12 | #undef min 13 | #endif 14 | 15 | #include 16 | #include 17 | #include 18 | 19 | namespace utils::nt 20 | { 21 | class library final 22 | { 23 | public: 24 | static library load(const std::string& name); 25 | static library load(const std::filesystem::path& path); 26 | static library get_by_address(void* address); 27 | 28 | library(); 29 | explicit library(const std::string& name); 30 | explicit library(HMODULE handle); 31 | 32 | library(const library& a) : module_(a.module_) 33 | { 34 | } 35 | 36 | bool operator!=(const library& obj) const { return !(*this == obj); }; 37 | bool operator==(const library& obj) const; 38 | 39 | operator bool() const; 40 | operator HMODULE() const; 41 | 42 | void unprotect() const; 43 | void* get_entry_point() const; 44 | size_t get_relative_entry_point() const; 45 | 46 | bool is_valid() const; 47 | std::string get_name() const; 48 | std::string get_path() const; 49 | std::string get_folder() const; 50 | std::uint8_t* get_ptr() const; 51 | void free(); 52 | 53 | HMODULE get_handle() const; 54 | 55 | template 56 | T get_proc(const std::string& process) const 57 | { 58 | if (!this->is_valid()) T{}; 59 | return reinterpret_cast(GetProcAddress(this->module_, process.data())); 60 | } 61 | 62 | template 63 | std::function get(const std::string& process) const 64 | { 65 | if (!this->is_valid()) return std::function(); 66 | return static_cast(this->get_proc(process)); 67 | } 68 | 69 | template 70 | T invoke(const std::string& process, Args ... args) const 71 | { 72 | auto method = this->get(process); 73 | if (method) return method(args...); 74 | return T(); 75 | } 76 | 77 | template 78 | T invoke_pascal(const std::string& process, Args ... args) const 79 | { 80 | auto method = this->get(process); 81 | if (method) return method(args...); 82 | return T(); 83 | } 84 | 85 | template 86 | T invoke_this(const std::string& process, void* this_ptr, Args ... args) const 87 | { 88 | auto method = this->get(this_ptr, process); 89 | if (method) return method(args...); 90 | return T(); 91 | } 92 | 93 | std::vector get_section_headers() const; 94 | 95 | PIMAGE_NT_HEADERS get_nt_headers() const; 96 | PIMAGE_DOS_HEADER get_dos_header() const; 97 | PIMAGE_OPTIONAL_HEADER get_optional_header() const; 98 | 99 | void** get_iat_entry(const std::string& module_name, const std::string& proc_name) const; 100 | 101 | private: 102 | HMODULE module_; 103 | }; 104 | 105 | __declspec(noreturn) void raise_hard_exception(); 106 | std::string load_resource(int id); 107 | 108 | void relaunch_self(); 109 | __declspec(noreturn) void terminate(uint32_t code = 0); 110 | } 111 | -------------------------------------------------------------------------------- /src/common/utils/signature.cpp: -------------------------------------------------------------------------------- 1 | #include "signature.hpp" 2 | #include 3 | #include 4 | 5 | #include 6 | 7 | namespace utils::hook 8 | { 9 | void signature::load_pattern(const std::string& pattern) 10 | { 11 | this->mask_.clear(); 12 | this->pattern_.clear(); 13 | 14 | uint8_t nibble = 0; 15 | auto has_nibble = false; 16 | 17 | for(auto val : pattern) 18 | { 19 | if (val == ' ') continue; 20 | if(val == '?') 21 | { 22 | this->mask_.push_back(val); 23 | this->pattern_.push_back(0); 24 | } 25 | else 26 | { 27 | if((val < '0' || val > '9') && (val < 'A' || val > 'F') && (val < 'a' || val> 'f')) 28 | { 29 | throw std::runtime_error("Invalid pattern"); 30 | } 31 | 32 | char str[] = { val, 0 }; 33 | const auto current_nibble = static_cast(strtol(str, nullptr, 16)); 34 | 35 | if(!has_nibble) 36 | { 37 | has_nibble = true; 38 | nibble = current_nibble; 39 | } 40 | else 41 | { 42 | has_nibble = false; 43 | const uint8_t byte = current_nibble | (nibble << 4); 44 | 45 | this->mask_.push_back('x'); 46 | this->pattern_.push_back(byte); 47 | } 48 | } 49 | } 50 | 51 | while (!this->mask_.empty() && this->mask_.back() == '?') 52 | { 53 | this->mask_.pop_back(); 54 | this->pattern_.pop_back(); 55 | } 56 | 57 | if(this->has_sse_support()) 58 | { 59 | while (this->pattern_.size() < 16) 60 | { 61 | this->pattern_.push_back(0); 62 | } 63 | } 64 | 65 | if(has_nibble) 66 | { 67 | throw std::runtime_error("Invalid pattern"); 68 | } 69 | } 70 | 71 | std::vector signature::process_range(uint8_t* start, const size_t length) const 72 | { 73 | if (this->has_sse_support()) return this->process_range_vectorized(start, length); 74 | return this->process_range_linear(start, length); 75 | } 76 | 77 | std::vector signature::process_range_linear(uint8_t* start, const size_t length) const 78 | { 79 | std::vector result; 80 | 81 | for (size_t i = 0; i < length; ++i) 82 | { 83 | const auto address = start + i; 84 | 85 | size_t j = 0; 86 | for (; j < this->mask_.size(); ++j) 87 | { 88 | if (this->mask_[j] != '?' && this->pattern_[j] != address[j]) 89 | { 90 | break; 91 | } 92 | } 93 | 94 | if (j == this->mask_.size()) 95 | { 96 | result.push_back(size_t(address)); 97 | } 98 | } 99 | 100 | return result; 101 | } 102 | 103 | std::vector signature::process_range_vectorized(uint8_t* start, const size_t length) const 104 | { 105 | std::vector result; 106 | __declspec(align(16)) char desired_mask[16] = { 0 }; 107 | 108 | for (size_t i = 0; i < this->mask_.size(); i++) 109 | { 110 | desired_mask[i / 8] |= (this->mask_[i] == '?' ? 0 : 1) << i % 8; 111 | } 112 | 113 | const auto mask = _mm_load_si128(reinterpret_cast(desired_mask)); 114 | const auto comparand = _mm_loadu_si128(reinterpret_cast(this->pattern_.data())); 115 | 116 | for (size_t i = 0; i < length; ++i) 117 | { 118 | const auto address = start + i; 119 | const auto value = _mm_loadu_si128(reinterpret_cast(address)); 120 | const auto comparison = _mm_cmpestrm(value, 16, comparand, static_cast(this->mask_.size()), _SIDD_CMP_EQUAL_EACH); 121 | 122 | const auto matches = _mm_and_si128(mask, comparison); 123 | const auto equivalence = _mm_xor_si128(mask, matches); 124 | 125 | if (_mm_test_all_zeros(equivalence, equivalence)) 126 | { 127 | result.push_back(size_t(address)); 128 | } 129 | } 130 | 131 | return result; 132 | } 133 | 134 | signature::signature_result signature::process() const 135 | { 136 | const auto range = this->length_ - this->mask_.size(); 137 | const auto cores = std::max(1u, std::thread::hardware_concurrency()); 138 | 139 | if (range <= cores * 10ull) return this->process_serial(); 140 | return this->process_parallel(); 141 | } 142 | 143 | signature::signature_result signature::process_serial() const 144 | { 145 | const auto sub = this->has_sse_support() ? 16 : this->mask_.size(); 146 | return { this->process_range(this->start_, this->length_ - sub) }; 147 | } 148 | 149 | signature::signature_result signature::process_parallel() const 150 | { 151 | const auto sub = this->has_sse_support() ? 16 : this->mask_.size(); 152 | const auto range = this->length_ - sub; 153 | const auto cores = std::max(1u, std::thread::hardware_concurrency() / 2); // Only use half of the available cores 154 | const auto grid = range / cores; 155 | 156 | std::mutex mutex; 157 | std::vector result; 158 | std::vector threads; 159 | 160 | for(auto i = 0u; i < cores; ++i) 161 | { 162 | const auto start = this->start_ + (grid * i); 163 | const auto length = (i + 1 == cores) ? (this->start_ + this->length_ - sub) - start : grid; 164 | threads.emplace_back([&, start, length]() 165 | { 166 | auto local_result = this->process_range(start, length); 167 | if (local_result.empty()) return; 168 | 169 | std::lock_guard _(mutex); 170 | for(const auto& address : local_result) 171 | { 172 | result.push_back(address); 173 | } 174 | }); 175 | } 176 | 177 | for(auto& t : threads) 178 | { 179 | if(t.joinable()) 180 | { 181 | t.join(); 182 | } 183 | } 184 | 185 | std::sort(result.begin(), result.end()); 186 | return { std::move(result) }; 187 | } 188 | 189 | bool signature::has_sse_support() const 190 | { 191 | if (this->mask_.size() <= 16) 192 | { 193 | int cpu_id[4]; 194 | __cpuid(cpu_id, 0); 195 | 196 | if (cpu_id[0] >= 1) 197 | { 198 | __cpuidex(cpu_id, 1, 0); 199 | return (cpu_id[2] & (1 << 20)) != 0; 200 | } 201 | } 202 | 203 | return false; 204 | } 205 | } 206 | 207 | utils::hook::signature::signature_result operator"" _sig(const char* str, const size_t len) 208 | { 209 | return utils::hook::signature(std::string(str, len)).process(); 210 | } 211 | -------------------------------------------------------------------------------- /src/common/utils/signature.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "nt.hpp" 3 | #include 4 | 5 | namespace utils::hook 6 | { 7 | class signature final 8 | { 9 | public: 10 | class signature_result 11 | { 12 | public: 13 | signature_result(std::vector&& matches) : matches_(std::move(matches)) 14 | { 15 | 16 | } 17 | 18 | [[nodiscard]] uint8_t* get(const size_t index) const 19 | { 20 | if(index >= this->count()) 21 | { 22 | throw std::runtime_error("Invalid index"); 23 | } 24 | 25 | return reinterpret_cast(this->matches_[index]); 26 | } 27 | 28 | [[nodiscard]] size_t count() const 29 | { 30 | return this->matches_.size(); 31 | } 32 | 33 | private: 34 | std::vector matches_; 35 | }; 36 | 37 | explicit signature(const std::string& pattern, const nt::library library = {}) 38 | : signature(pattern, library.get_ptr(), library.get_optional_header()->SizeOfImage) 39 | { 40 | } 41 | 42 | signature(const std::string& pattern, void* start, void* end) 43 | : signature(pattern, start, size_t(end) - size_t(start)) 44 | { 45 | } 46 | 47 | signature(const std::string& pattern, void* start, const size_t length) 48 | : start_(static_cast(start)), length_(length) 49 | { 50 | this->load_pattern(pattern); 51 | } 52 | 53 | signature_result process() const; 54 | 55 | private: 56 | std::string mask_; 57 | std::basic_string pattern_; 58 | 59 | uint8_t* start_; 60 | size_t length_; 61 | 62 | void load_pattern(const std::string& pattern); 63 | 64 | signature_result process_parallel() const; 65 | signature_result process_serial() const; 66 | std::vector process_range(uint8_t* start, size_t length) const; 67 | std::vector process_range_linear(uint8_t* start, size_t length) const; 68 | std::vector process_range_vectorized(uint8_t* start, size_t length) const; 69 | 70 | bool has_sse_support() const; 71 | }; 72 | } 73 | 74 | utils::hook::signature::signature_result operator"" _sig(const char* str, size_t len); 75 | -------------------------------------------------------------------------------- /src/common/utils/string.cpp: -------------------------------------------------------------------------------- 1 | #include "string.hpp" 2 | #include 3 | #include 4 | #include 5 | 6 | #include "nt.hpp" 7 | 8 | namespace utils::string 9 | { 10 | const char* va(const char* fmt, ...) 11 | { 12 | static thread_local va_provider<8, 256> provider; 13 | 14 | va_list ap; 15 | va_start(ap, fmt); 16 | 17 | const char* result = provider.get(fmt, ap); 18 | 19 | va_end(ap); 20 | return result; 21 | } 22 | 23 | std::vector split(const std::string& s, const char delim) 24 | { 25 | std::stringstream ss(s); 26 | std::string item; 27 | std::vector elems; 28 | 29 | while (std::getline(ss, item, delim)) 30 | { 31 | elems.push_back(item); // elems.push_back(std::move(item)); // if C++11 (based on comment from @mchiasson) 32 | } 33 | 34 | return elems; 35 | } 36 | 37 | std::string to_lower(std::string text) 38 | { 39 | std::transform(text.begin(), text.end(), text.begin(), [](const char input) 40 | { 41 | return static_cast(tolower(input)); 42 | }); 43 | 44 | return text; 45 | } 46 | 47 | std::string to_upper(std::string text) 48 | { 49 | std::transform(text.begin(), text.end(), text.begin(), [](const char input) 50 | { 51 | return static_cast(toupper(input)); 52 | }); 53 | 54 | return text; 55 | } 56 | 57 | bool starts_with(const std::string& text, const std::string& substring) 58 | { 59 | return text.find(substring) == 0; 60 | } 61 | 62 | bool ends_with(const std::string& text, const std::string& substring) 63 | { 64 | if (substring.size() > text.size()) return false; 65 | return std::equal(substring.rbegin(), substring.rend(), text.rbegin()); 66 | } 67 | 68 | bool is_numeric(const std::string& text) 69 | { 70 | return std::to_string(atoi(text.data())) == text; 71 | } 72 | 73 | std::string dump_hex(const std::string& data, const std::string& separator) 74 | { 75 | std::string result; 76 | 77 | for (unsigned int i = 0; i < data.size(); ++i) 78 | { 79 | if (i > 0) 80 | { 81 | result.append(separator); 82 | } 83 | 84 | result.append(va("%02X", data[i] & 0xFF)); 85 | } 86 | 87 | return result; 88 | } 89 | 90 | std::string get_clipboard_data() 91 | { 92 | if (OpenClipboard(nullptr)) 93 | { 94 | std::string data; 95 | 96 | auto* const clipboard_data = GetClipboardData(1u); 97 | if (clipboard_data) 98 | { 99 | auto* const cliptext = static_cast(GlobalLock(clipboard_data)); 100 | if (cliptext) 101 | { 102 | data.append(cliptext); 103 | GlobalUnlock(clipboard_data); 104 | } 105 | } 106 | CloseClipboard(); 107 | 108 | return data; 109 | } 110 | return {}; 111 | } 112 | 113 | void strip(const char* in, char* out, int max) 114 | { 115 | if (!in || !out) return; 116 | 117 | max--; 118 | auto current = 0; 119 | while (*in != 0 && current < max) 120 | { 121 | const auto color_index = (*(in + 1) - 48) >= 0xC ? 7 : (*(in + 1) - 48); 122 | 123 | if (*in == '^' && (color_index != 7 || *(in + 1) == '7')) 124 | { 125 | ++in; 126 | } 127 | else 128 | { 129 | *out = *in; 130 | ++out; 131 | ++current; 132 | } 133 | 134 | ++in; 135 | } 136 | *out = '\0'; 137 | } 138 | 139 | #pragma warning(push) 140 | #pragma warning(disable: 4100) 141 | std::string convert(const std::wstring& wstr) 142 | { 143 | std::string result; 144 | result.reserve(wstr.size()); 145 | 146 | for(const auto& chr : wstr) 147 | { 148 | result.push_back(static_cast(chr)); 149 | } 150 | 151 | return result; 152 | } 153 | 154 | std::wstring convert(const std::string& str) 155 | { 156 | std::wstring result; 157 | result.reserve(str.size()); 158 | 159 | for(const auto& chr : str) 160 | { 161 | result.push_back(static_cast(chr)); 162 | } 163 | 164 | return result; 165 | } 166 | #pragma warning(pop) 167 | 168 | std::string replace(std::string str, const std::string& from, const std::string& to) 169 | { 170 | if (from.empty()) 171 | { 172 | return str; 173 | } 174 | 175 | size_t start_pos = 0; 176 | while ((start_pos = str.find(from, start_pos)) != std::string::npos) 177 | { 178 | str.replace(start_pos, from.length(), to); 179 | start_pos += to.length(); 180 | } 181 | 182 | return str; 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/common/utils/string.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "memory.hpp" 3 | #include 4 | 5 | #ifndef ARRAYSIZE 6 | template 7 | size_t ARRAYSIZE(Type (&)[n]) { return n; } 8 | #endif 9 | 10 | namespace utils::string 11 | { 12 | template 13 | class va_provider final 14 | { 15 | public: 16 | static_assert(Buffers != 0 && MinBufferSize != 0, "Buffers and MinBufferSize mustn't be 0"); 17 | 18 | va_provider() : current_buffer_(0) 19 | { 20 | } 21 | 22 | char* get(const char* format, const va_list ap) 23 | { 24 | ++this->current_buffer_ %= ARRAYSIZE(this->string_pool_); 25 | auto entry = &this->string_pool_[this->current_buffer_]; 26 | 27 | if (!entry->size || !entry->buffer) 28 | { 29 | throw std::runtime_error("String pool not initialized"); 30 | } 31 | 32 | while (true) 33 | { 34 | const int res = vsnprintf_s(entry->buffer, entry->size, _TRUNCATE, format, ap); 35 | if (res > 0) break; // Success 36 | if (res == 0) return nullptr; // Error 37 | 38 | entry->double_size(); 39 | } 40 | 41 | return entry->buffer; 42 | } 43 | 44 | private: 45 | class entry final 46 | { 47 | public: 48 | explicit entry(const size_t _size = MinBufferSize) : size(_size), buffer(nullptr) 49 | { 50 | if (this->size < MinBufferSize) this->size = MinBufferSize; 51 | this->allocate(); 52 | } 53 | 54 | ~entry() 55 | { 56 | if (this->buffer) memory::get_allocator()->free(this->buffer); 57 | this->size = 0; 58 | this->buffer = nullptr; 59 | } 60 | 61 | void allocate() 62 | { 63 | if (this->buffer) memory::get_allocator()->free(this->buffer); 64 | this->buffer = memory::get_allocator()->allocate_array(this->size + 1); 65 | } 66 | 67 | void double_size() 68 | { 69 | this->size *= 2; 70 | this->allocate(); 71 | } 72 | 73 | size_t size; 74 | char* buffer; 75 | }; 76 | 77 | size_t current_buffer_; 78 | entry string_pool_[Buffers]; 79 | }; 80 | 81 | const char* va(const char* fmt, ...); 82 | 83 | std::vector split(const std::string& s, char delim); 84 | 85 | std::string to_lower(std::string text); 86 | std::string to_upper(std::string text); 87 | bool starts_with(const std::string& text, const std::string& substring); 88 | bool ends_with(const std::string& text, const std::string& substring); 89 | bool is_numeric(const std::string& text); 90 | 91 | std::string dump_hex(const std::string& data, const std::string& separator = " "); 92 | 93 | std::string get_clipboard_data(); 94 | 95 | void strip(const char* in, char* out, int max); 96 | 97 | std::string convert(const std::wstring& wstr); 98 | std::wstring convert(const std::string& str); 99 | 100 | std::string replace(std::string str, const std::string& from, const std::string& to); 101 | } 102 | -------------------------------------------------------------------------------- /src/common/utils/thread.cpp: -------------------------------------------------------------------------------- 1 | #include "thread.hpp" 2 | #include "string.hpp" 3 | 4 | #include 5 | 6 | #include 7 | 8 | namespace utils::thread 9 | { 10 | bool set_name(const HANDLE t, const std::string& name) 11 | { 12 | const nt::library kernel32("kernel32.dll"); 13 | if (!kernel32) 14 | { 15 | return false; 16 | } 17 | 18 | const auto set_description = kernel32.get_proc("SetThreadDescription"); 19 | if (!set_description) 20 | { 21 | return false; 22 | } 23 | 24 | return SUCCEEDED(set_description(t, string::convert(name).data())); 25 | } 26 | 27 | bool set_name(const DWORD id, const std::string& name) 28 | { 29 | auto* const t = OpenThread(THREAD_SET_LIMITED_INFORMATION, FALSE, id); 30 | if (!t) return false; 31 | 32 | const auto _ = gsl::finally([t]() 33 | { 34 | CloseHandle(t); 35 | }); 36 | 37 | return set_name(t, name); 38 | } 39 | 40 | bool set_name(std::thread& t, const std::string& name) 41 | { 42 | return set_name(t.native_handle(), name); 43 | } 44 | 45 | bool set_name(const std::string& name) 46 | { 47 | return set_name(GetCurrentThread(), name); 48 | } 49 | 50 | std::vector get_thread_ids() 51 | { 52 | auto* const h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, GetCurrentProcessId()); 53 | if (h == INVALID_HANDLE_VALUE) 54 | { 55 | return {}; 56 | } 57 | 58 | const auto _ = gsl::finally([h]() 59 | { 60 | CloseHandle(h); 61 | }); 62 | 63 | THREADENTRY32 entry{}; 64 | entry.dwSize = sizeof(entry); 65 | if (!Thread32First(h, &entry)) 66 | { 67 | return {}; 68 | } 69 | 70 | std::vector ids{}; 71 | 72 | do 73 | { 74 | const auto check_size = entry.dwSize < FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) 75 | + sizeof(entry.th32OwnerProcessID); 76 | entry.dwSize = sizeof(entry); 77 | 78 | if (check_size && entry.th32OwnerProcessID == GetCurrentProcessId()) 79 | { 80 | ids.emplace_back(entry.th32ThreadID); 81 | } 82 | } 83 | while (Thread32Next(h, &entry)); 84 | 85 | return ids; 86 | } 87 | 88 | void for_each_thread(const std::function& callback) 89 | { 90 | const auto ids = get_thread_ids(); 91 | 92 | for (const auto& id : ids) 93 | { 94 | auto* const thread = OpenThread(THREAD_ALL_ACCESS, FALSE, id); 95 | if (thread != nullptr) 96 | { 97 | const auto _ = gsl::finally([thread]() 98 | { 99 | CloseHandle(thread); 100 | }); 101 | 102 | callback(thread); 103 | } 104 | } 105 | } 106 | 107 | void suspend_other_threads() 108 | { 109 | for_each_thread([](const HANDLE thread) 110 | { 111 | if (GetThreadId(thread) != GetCurrentThreadId()) 112 | { 113 | SuspendThread(thread); 114 | } 115 | }); 116 | } 117 | 118 | void resume_other_threads() 119 | { 120 | for_each_thread([](const HANDLE thread) 121 | { 122 | if (GetThreadId(thread) != GetCurrentThreadId()) 123 | { 124 | ResumeThread(thread); 125 | } 126 | }); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/common/utils/thread.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "nt.hpp" 4 | 5 | namespace utils::thread 6 | { 7 | bool set_name(HANDLE t, const std::string& name); 8 | bool set_name(DWORD id, const std::string& name); 9 | bool set_name(std::thread& t, const std::string& name); 10 | bool set_name(const std::string& name); 11 | 12 | template 13 | std::thread create_named_thread(const std::string& name, Args&&... args) 14 | { 15 | auto t = std::thread(std::forward(args)...); 16 | set_name(t, name); 17 | return t; 18 | } 19 | 20 | std::vector get_thread_ids(); 21 | void for_each_thread(const std::function& callback); 22 | 23 | void suspend_other_threads(); 24 | void resume_other_threads(); 25 | } 26 | -------------------------------------------------------------------------------- /tools/premake5.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JariKCoding/T7Overcharged/e5f96c89ed7033c140f5a68a11373ed1088b8c41/tools/premake5.exe -------------------------------------------------------------------------------- /tools/protoc.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JariKCoding/T7Overcharged/e5f96c89ed7033c140f5a68a11373ed1088b8c41/tools/protoc.exe -------------------------------------------------------------------------------- /usage/ui/util/T7Overcharged.lua: -------------------------------------------------------------------------------- 1 | EnableGlobals(); 2 | 3 | require("ui.util.T7OverchargedUtil") 4 | 5 | -- Initialize everything, table needs to have the following properties: 6 | -- mapname or modname: Enables debug mode and hot reloading when launched via the launcher 7 | -- filespath: The path to the mod or map files that will be used for hot reloading eg [[.\maps\zm_factory\]] 8 | -- workshopid: The id of the workshop item so the dll can be found 9 | -- discordAppId: The application id of the discord app, can be found here https://discord.com/developers/applications/ 10 | -- showExternalConsole: Whether to show external console when launching the game 11 | function InitializeT7Overcharged(options) 12 | if T7Overcharged then return false end 13 | 14 | local debug = false 15 | if options.mapname and Engine.GetCurrentMap() == options.mapname or 16 | options.modname and Engine.UsingModsUgcName() == options.modname then 17 | debug = true 18 | end 19 | 20 | -- The path that we copy the dll's from 21 | local dllPath = debug and options.filespath .. [[zone\]] or [[..\..\workshop\content\311210\]] .. options.workshopid .. "\\" 22 | local dll = "T7Overcharged.dll" 23 | 24 | SafeCall(function() 25 | EnableGlobals() 26 | local dllInit = require("package").loadlib(dllPath..dll, "init") 27 | 28 | -- Check if the dll was properly loaded 29 | if not dllInit then 30 | Engine.ComError( Enum.errorCode.ERROR_UI, "Unable to initialize T7Overcharged install the latest VCRedist" ) 31 | return 32 | end 33 | 34 | -- Execute the dll 35 | dllInit() 36 | end) 37 | 38 | UIErrorHash.Remove() 39 | if options.discordAppId then 40 | DiscordRPC.Enable(options.discordAppId) 41 | end 42 | if options.showExternalConsole and debug then 43 | Console.ShowExternalConsole() 44 | end 45 | 46 | if debug then 47 | HotReload.Start(options.filespath) 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /usage/ui/util/T7OverchargedUtil.lua: -------------------------------------------------------------------------------- 1 | 2 | 3 | -- Function that we can use to safely call io and dll functions without crashing the client 4 | function SafeCall( FunctionRef ) 5 | local ok, result = pcall( FunctionRef ) 6 | 7 | if not ok and result then 8 | Engine.ComError( Enum.errorCode.ERROR_UI, "SafeCall error: " .. result ) 9 | elseif result then 10 | return result 11 | end 12 | end 13 | --------------------------------------------------------------------------------