├── .gitignore ├── .gitmodules ├── LICENSE ├── LogManager ├── LogManager.json ├── Makefile ├── include │ └── stratosphere │ │ ├── lm.hpp │ │ └── lm │ │ ├── impl │ │ ├── lm_log_packet.hpp │ │ └── lm_scoped_log_file.hpp │ │ └── lm_types.hpp └── source │ ├── lm_main.cpp │ ├── lm_service.cpp │ ├── lm_service.hpp │ └── stratosphere │ └── lm │ └── impl │ ├── lm_log_packet.cpp │ └── lm_scoped_log_file.cpp ├── README.md └── binlog_reader.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.nsp 2 | *.elf 3 | *.nso 4 | *.npdm 5 | build/ -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "Atmosphere-libs"] 2 | path = Atmosphere-libs 3 | url = https://github.com/Atmosphere-NX/Atmosphere-libs 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /LogManager/LogManager.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "LogManager", 3 | "title_id": "0x0100000000000015", 4 | "title_id_range_min": "0x0100000000000015", 5 | "title_id_range_max": "0x0100000000000015", 6 | "main_thread_stack_size": "0x00004000", 7 | "main_thread_priority": 10, 8 | "default_cpu_id": 3, 9 | "process_category": 0, 10 | "is_retail": true, 11 | "pool_partition": 2, 12 | "is_64_bit": true, 13 | "address_space_type": 1, 14 | "filesystem_access": { 15 | "permissions": "0xFFFFFFFFFFFFFFFF" 16 | }, 17 | "service_access": [ "fsp-srv", "pm:info", "psc:m" ], 18 | "service_host": [ "lm" ], 19 | "kernel_capabilities": [ 20 | { 21 | "type": "kernel_flags", 22 | "value": { 23 | "highest_thread_priority": 63, 24 | "lowest_thread_priority": 8, 25 | "lowest_cpu_id": 3, 26 | "highest_cpu_id": 3 27 | } 28 | }, 29 | { 30 | "type": "syscalls", 31 | "value": { 32 | "svcSetHeapSize": "0x01", 33 | "svcSetMemoryPermission": "0x02", 34 | "svcSetMemoryAttribute": "0x03", 35 | "svcMapMemory": "0x04", 36 | "svcUnmapMemory": "0x05", 37 | "svcQueryMemory": "0x06", 38 | "svcExitProcess": "0x07", 39 | "svcCreateThread": "0x08", 40 | "svcStartThread": "0x09", 41 | "svcExitThread": "0x0a", 42 | "svcSleepThread": "0x0b", 43 | "svcGetThreadPriority": "0x0c", 44 | "svcSetThreadPriority": "0x0d", 45 | "svcGetThreadCoreMask": "0x0e", 46 | "svcSetThreadCoreMask": "0x0f", 47 | "svcGetCurrentProcessorNumber": "0x10", 48 | "svcSignalEvent": "0x11", 49 | "svcClearEvent": "0x12", 50 | "svcMapSharedMemory": "0x13", 51 | "svcUnmapSharedMemory": "0x14", 52 | "svcCreateTransferMemory": "0x15", 53 | "svcCloseHandle": "0x16", 54 | "svcResetSignal": "0x17", 55 | "svcWaitSynchronization": "0x18", 56 | "svcCancelSynchronization": "0x19", 57 | "svcArbitrateLock": "0x1a", 58 | "svcArbitrateUnlock": "0x1b", 59 | "svcWaitProcessWideKeyAtomic": "0x1c", 60 | "svcSignalProcessWideKey": "0x1d", 61 | "svcGetSystemTick": "0x1e", 62 | "svcConnectToNamedPort": "0x1f", 63 | "svcSendSyncRequestLight": "0x20", 64 | "svcSendSyncRequest": "0x21", 65 | "svcSendSyncRequestWithUserBuffer": "0x22", 66 | "svcSendAsyncRequestWithUserBuffer": "0x23", 67 | "svcGetProcessId": "0x24", 68 | "svcGetThreadId": "0x25", 69 | "svcBreak": "0x26", 70 | "svcOutputDebugString": "0x27", 71 | "svcReturnFromException": "0x28", 72 | "svcGetInfo": "0x29", 73 | "svcWaitForAddress": "0x34", 74 | "svcSignalToAddress": "0x35", 75 | "svcCreateSession": "0x40", 76 | "svcAcceptSession": "0x41", 77 | "svcReplyAndReceiveLight": "0x42", 78 | "svcReplyAndReceive": "0x43", 79 | "svcReplyAndReceiveWithUserBuffer": "0x44", 80 | "svcCreateEvent": "0x45", 81 | "svcDebugActiveProcess": "0x60", 82 | "svcGetDebugEvent": "0x63", 83 | "svcGetThreadList": "0x66", 84 | "svcGetDebugThreadContext": "0x67", 85 | "svcQueryDebugProcessMemory": "0x69", 86 | "svcReadDebugProcessMemory": "0x6a", 87 | "svcGetDebugThreadParam": "0x6d", 88 | "svcCallSecureMonitor": "0x7F" 89 | } 90 | }, 91 | { 92 | "type": "min_kernel_version", 93 | "value": "0x0030" 94 | }, 95 | { 96 | "type": "debug_flags", 97 | "value": { 98 | "allow_debug": false, 99 | "force_debug": true 100 | } 101 | } 102 | ] 103 | } -------------------------------------------------------------------------------- /LogManager/Makefile: -------------------------------------------------------------------------------- 1 | #--------------------------------------------------------------------------------- 2 | # pull in (modded) common stratosphere sysmodule configuration 3 | #--------------------------------------------------------------------------------- 4 | include $(dir $(abspath $(lastword $(MAKEFILE_LIST))))/../Atmosphere-libs/config/templates/stratosphere.mk 5 | 6 | #--------------------------------------------------------------------------------- 7 | # no real need to edit anything past this point unless you need to add additional 8 | # rules for different file extensions 9 | #--------------------------------------------------------------------------------- 10 | ifneq ($(BUILD),$(notdir $(CURDIR))) 11 | #--------------------------------------------------------------------------------- 12 | 13 | export OUTPUT := $(CURDIR)/$(TARGET) 14 | export TOPDIR := $(CURDIR) 15 | 16 | export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ 17 | $(foreach dir,$(DATA),$(CURDIR)/$(dir)) 18 | 19 | export DEPSDIR := $(CURDIR)/$(BUILD) 20 | 21 | 22 | CFILES := $(foreach dir,$(SOURCES),$(filter-out $(notdir $(wildcard $(dir)/*.arch.*.c)) $(notdir $(wildcard $(dir)/*.board.*.c)) $(notdir $(wildcard $(dir)/*.os.*.c)), \ 23 | $(notdir $(wildcard $(dir)/*.c)))) 24 | CFILES += $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.arch.$(ATMOSPHERE_ARCH_NAME).c))) 25 | CFILES += $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.board.$(ATMOSPHERE_BOARD_NAME).c))) 26 | CFILES += $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.os.$(ATMOSPHERE_OS_NAME).c))) 27 | 28 | CPPFILES := $(foreach dir,$(SOURCES),$(filter-out $(notdir $(wildcard $(dir)/*.arch.*.cpp)) $(notdir $(wildcard $(dir)/*.board.*.cpp)) $(notdir $(wildcard $(dir)/*.os.*.cpp)), \ 29 | $(notdir $(wildcard $(dir)/*.cpp)))) 30 | CPPFILES += $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.arch.$(ATMOSPHERE_ARCH_NAME).cpp))) 31 | CPPFILES += $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.board.$(ATMOSPHERE_BOARD_NAME).cpp))) 32 | CPPFILES += $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.os.$(ATMOSPHERE_OS_NAME).cpp))) 33 | 34 | SFILES := $(foreach dir,$(SOURCES),$(filter-out $(notdir $(wildcard $(dir)/*.arch.*.s)) $(notdir $(wildcard $(dir)/*.board.*.s)) $(notdir $(wildcard $(dir)/*.os.*.s)), \ 35 | $(notdir $(wildcard $(dir)/*.s)))) 36 | SFILES += $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.arch.$(ATMOSPHERE_ARCH_NAME).s))) 37 | SFILES += $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.board.$(ATMOSPHERE_BOARD_NAME).s))) 38 | SFILES += $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.os.$(ATMOSPHERE_OS_NAME).s))) 39 | 40 | BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) 41 | 42 | #--------------------------------------------------------------------------------- 43 | # use CXX for linking C++ projects, CC for standard C 44 | #--------------------------------------------------------------------------------- 45 | ifeq ($(strip $(CPPFILES)),) 46 | #--------------------------------------------------------------------------------- 47 | export LD := $(CC) 48 | #--------------------------------------------------------------------------------- 49 | else 50 | #--------------------------------------------------------------------------------- 51 | export LD := $(CXX) 52 | #--------------------------------------------------------------------------------- 53 | endif 54 | #--------------------------------------------------------------------------------- 55 | 56 | export OFILES := $(addsuffix .o,$(BINFILES)) \ 57 | $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) 58 | 59 | export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ 60 | $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ 61 | -I$(CURDIR)/$(BUILD) 62 | 63 | export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) 64 | 65 | export BUILD_EXEFS_SRC := $(TOPDIR)/$(EXEFS_SRC) 66 | 67 | ifeq ($(strip $(CONFIG_JSON)),) 68 | jsons := $(wildcard *.json) 69 | ifneq (,$(findstring $(TARGET).json,$(jsons))) 70 | export APP_JSON := $(TOPDIR)/$(TARGET).json 71 | else 72 | ifneq (,$(findstring config.json,$(jsons))) 73 | export APP_JSON := $(TOPDIR)/config.json 74 | endif 75 | endif 76 | else 77 | export APP_JSON := $(TOPDIR)/$(CONFIG_JSON) 78 | endif 79 | 80 | .PHONY: $(BUILD) clean all 81 | 82 | #--------------------------------------------------------------------------------- 83 | all: $(BUILD) 84 | 85 | $(BUILD): 86 | @[ -d $@ ] || mkdir -p $@ 87 | @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile 88 | 89 | #--------------------------------------------------------------------------------- 90 | clean: 91 | @echo clean ... 92 | @rm -fr $(BUILD) $(TARGET).nsp $(TARGET).npdm $(TARGET).nso $(TARGET).elf 93 | 94 | 95 | #--------------------------------------------------------------------------------- 96 | else 97 | .PHONY: all 98 | 99 | DEPENDS := $(OFILES:.o=.d) 100 | 101 | #--------------------------------------------------------------------------------- 102 | # main targets 103 | #--------------------------------------------------------------------------------- 104 | all : $(OUTPUT).nsp 105 | 106 | ifeq ($(strip $(APP_JSON)),) 107 | $(OUTPUT).nsp : $(OUTPUT).nso 108 | else 109 | $(OUTPUT).nsp : $(OUTPUT).nso $(OUTPUT).npdm 110 | endif 111 | 112 | $(OUTPUT).nso : $(OUTPUT).elf 113 | 114 | $(OUTPUT).elf : $(OFILES) 115 | 116 | #--------------------------------------------------------------------------------- 117 | # you need a rule like this for each extension you use as binary data 118 | #--------------------------------------------------------------------------------- 119 | %.bin.o : %.bin 120 | #--------------------------------------------------------------------------------- 121 | @echo $(notdir $<) 122 | @$(bin2o) 123 | 124 | -include $(DEPENDS) 125 | 126 | #--------------------------------------------------------------------------------------- 127 | endif 128 | #--------------------------------------------------------------------------------------- -------------------------------------------------------------------------------- /LogManager/include/stratosphere/lm.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018-2020 Atmosphère-NX 3 | * 4 | * This program is free software; you can redistribute it and/or modify it 5 | * under the terms and conditions of the GNU General Public License, 6 | * version 2, as published by the Free Software Foundation. 7 | * 8 | * This program is distributed in the hope it will be useful, but WITHOUT 9 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 10 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 11 | * more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this program. If not, see . 15 | */ 16 | #pragma once 17 | 18 | #include "lm/lm_types.hpp" 19 | #include "lm/impl/lm_log_packet.hpp" 20 | -------------------------------------------------------------------------------- /LogManager/include/stratosphere/lm/impl/lm_log_packet.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | #include 4 | #include "../lm_types.hpp" 5 | 6 | namespace ams::lm::impl { 7 | 8 | enum class LogDataChunkKey : u8 { 9 | SessionBegin = 0, 10 | SessionEnd = 1, 11 | TextLog = 2, 12 | LineNumber = 3, 13 | FileName = 4, 14 | FunctionName = 5, 15 | ModuleName = 6, 16 | ThreadName = 7, 17 | LogPacketDropCount = 8, 18 | UserSystemClock = 9, 19 | ProcessName = 10, 20 | }; 21 | 22 | enum class LogSeverity : u8 { 23 | Trace = 0, 24 | Info = 1, 25 | Warn = 2, 26 | Error = 3, 27 | Fatal = 4, 28 | }; 29 | 30 | enum LogPacketFlags : u8 { 31 | LogPacketFlags_Head = BIT(0), 32 | LogPacketFlags_Tail = BIT(1), 33 | }; 34 | 35 | struct LogPacketHeader { 36 | u64 process_id; 37 | u64 thread_id; 38 | u8 flags; 39 | u8 pad; 40 | u8 severity; 41 | u8 verbosity; 42 | u32 payload_size; 43 | 44 | inline constexpr bool IsHead() { 45 | /* Head -> a packet list is being sent, with this packet being the initial one. */ 46 | return this->flags & LogPacketFlags_Head; 47 | } 48 | 49 | inline constexpr bool IsTail() { 50 | /* Tail -> this is the final packet of the packet list. */ 51 | return this->flags & LogPacketFlags_Tail; 52 | } 53 | 54 | } PACKED; 55 | static_assert(sizeof(LogPacketHeader) == 0x18, "LogPacketHeader definition"); 56 | 57 | /* Log data chunk base type. */ 58 | 59 | struct LogDataChunkTypeHeader { 60 | u8 key; 61 | u8 chunk_length; 62 | } PACKED; 63 | 64 | template 65 | struct LogDataChunkType { 66 | LogDataChunkTypeHeader header; 67 | T value; 68 | 69 | inline constexpr bool IsEmpty() { 70 | /* If it's not present, its length will not be set. */ 71 | return this->header.chunk_length == 0; 72 | } 73 | 74 | } PACKED; 75 | 76 | /* Since the length is stored as a single byte, the string will never be larger than 0xFF */ 77 | struct LogDataChunkStringType : public LogDataChunkType {}; 78 | 79 | /* Actual chunk base types. */ 80 | 81 | struct LogDataChunkSessionBeginType : public LogDataChunkType {}; 82 | struct LogDataChunkSessionEndType : public LogDataChunkType {}; 83 | struct LogDataChunkTextLogType : public LogDataChunkStringType {}; 84 | struct LogDataChunkLineNumberType : public LogDataChunkType {}; 85 | struct LogDataChunkFileNameType : public LogDataChunkStringType {}; 86 | struct LogDataChunkFunctionNameType : public LogDataChunkStringType {}; 87 | struct LogDataChunkModuleNameType : public LogDataChunkStringType {}; 88 | struct LogDataChunkThreadNameType : public LogDataChunkStringType {}; 89 | struct LogDataChunkLogPacketDropCountLogType : public LogDataChunkType {}; 90 | struct LogDataChunkUserSystemClockType : public LogDataChunkType {}; 91 | struct LogDataChunkProcessNameType : public LogDataChunkStringType {}; 92 | 93 | /* One of each chunk type. */ 94 | 95 | struct LogPacketPayload { 96 | LogDataChunkSessionBeginType session_begin; 97 | LogDataChunkSessionEndType session_end; 98 | LogDataChunkTextLogType text_log; 99 | LogDataChunkLineNumberType line_number; 100 | LogDataChunkFileNameType file_name; 101 | LogDataChunkFunctionNameType function_name; 102 | LogDataChunkModuleNameType module_name; 103 | LogDataChunkThreadNameType thread_name; 104 | LogDataChunkLogPacketDropCountLogType log_packet_drop_count; 105 | LogDataChunkUserSystemClockType user_system_clock; 106 | LogDataChunkProcessNameType process_name; 107 | }; 108 | 109 | struct LogPacket { 110 | LogPacketHeader header; 111 | LogPacketPayload payload; 112 | }; 113 | 114 | template 115 | inline C ParseStringChunkType(const u8 *chunk_buf) { 116 | static_assert(std::is_base_of_v, "Invalid type"); 117 | 118 | auto chunk_header = *reinterpret_cast(chunk_buf); 119 | auto type = *reinterpret_cast(chunk_buf); 120 | auto chunk_str_buf = reinterpret_cast(chunk_buf + sizeof(LogDataChunkTypeHeader)); 121 | 122 | /* Zero the string and copy it from the log buffer. */ 123 | /* This chunk type can't be directly read like the rest, since the string size isn't fixed like with the other types. */ 124 | __builtin_memset(type.value, 0, sizeof(type.value)); 125 | strncpy(type.value, chunk_str_buf, chunk_header.chunk_length); 126 | return type; 127 | } 128 | 129 | inline LogPacket ParseLogPacket(const void *buf, size_t size) { 130 | LogPacket packet = {}; 131 | auto buf8 = reinterpret_cast(buf); 132 | packet.header = *reinterpret_cast(buf); 133 | auto payload_buf = buf8 + sizeof(LogPacketHeader); 134 | size_t offset = 0; 135 | while(offset < packet.header.payload_size) { 136 | /* Each chunk data consists on: u8 id, u8 length, u8 data[length]; */ 137 | auto chunk_buf = payload_buf + offset; 138 | auto chunk_header = *reinterpret_cast(chunk_buf); 139 | /* Parse the chunk depending on the type (strings require special parsing) */ 140 | switch(static_cast(chunk_header.key)) { 141 | case LogDataChunkKey::SessionBegin: 142 | packet.payload.session_begin = *reinterpret_cast(chunk_buf); 143 | break; 144 | case LogDataChunkKey::SessionEnd: 145 | packet.payload.session_end = *reinterpret_cast(chunk_buf); 146 | break; 147 | case LogDataChunkKey::TextLog: 148 | packet.payload.text_log = ParseStringChunkType(chunk_buf); 149 | break; 150 | case LogDataChunkKey::LineNumber: 151 | packet.payload.line_number = *reinterpret_cast(chunk_buf); 152 | break; 153 | case LogDataChunkKey::FileName: 154 | packet.payload.file_name = ParseStringChunkType(chunk_buf); 155 | break; 156 | case LogDataChunkKey::FunctionName: 157 | packet.payload.function_name = ParseStringChunkType(chunk_buf); 158 | break; 159 | case LogDataChunkKey::ModuleName: 160 | packet.payload.module_name = ParseStringChunkType(chunk_buf); 161 | break; 162 | case LogDataChunkKey::ThreadName: 163 | packet.payload.thread_name = ParseStringChunkType(chunk_buf); 164 | break; 165 | case LogDataChunkKey::LogPacketDropCount: 166 | packet.payload.log_packet_drop_count = *reinterpret_cast(chunk_buf); 167 | break; 168 | case LogDataChunkKey::UserSystemClock: 169 | packet.payload.user_system_clock = *reinterpret_cast(chunk_buf); 170 | break; 171 | case LogDataChunkKey::ProcessName: 172 | packet.payload.process_name = ParseStringChunkType(chunk_buf); 173 | break; 174 | } 175 | offset += sizeof(LogDataChunkTypeHeader); 176 | offset += chunk_header.chunk_length; 177 | } 178 | return packet; 179 | } 180 | 181 | void SetCanAccessFs(bool can_access); 182 | void WriteLogPackets(const char *log_path, std::vector &packet_list, u64 program_id, LogDestination destination); 183 | 184 | } -------------------------------------------------------------------------------- /LogManager/include/stratosphere/lm/impl/lm_scoped_log_file.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | #include 4 | 5 | namespace ams::lm::impl { 6 | 7 | /* Based on creport's ScopedFile. */ 8 | 9 | class ScopedLogFile { 10 | NON_COPYABLE(ScopedLogFile); 11 | NON_MOVEABLE(ScopedLogFile); 12 | private: 13 | fs::FileHandle file; 14 | s64 offset; 15 | bool opened; 16 | public: 17 | ScopedLogFile(const char *path) : file(), offset(), opened(false) { 18 | /* Ensure that the file exists. */ 19 | fs::CreateFile(path, 0); 20 | this->opened = R_SUCCEEDED(fs::OpenFile(std::addressof(this->file), path, fs::OpenMode_Write | fs::OpenMode_AllowAppend)); 21 | if(this->opened) { 22 | /* Set current file size as offset to properly append the logs after each other. */ 23 | fs::GetFileSize(&this->offset, this->file); 24 | } 25 | } 26 | 27 | ~ScopedLogFile() { 28 | if(this->opened) { 29 | fs::CloseFile(file); 30 | } 31 | } 32 | 33 | bool IsOpen() const { 34 | return this->opened; 35 | } 36 | 37 | void WriteString(const char *str); 38 | void WriteFormat(const char *fmt, ...) __attribute__((format(printf, 2, 3))); 39 | 40 | void Write(const void *data, size_t size); 41 | }; 42 | 43 | } -------------------------------------------------------------------------------- /LogManager/include/stratosphere/lm/lm_types.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | #include 4 | 5 | namespace ams::lm { 6 | 7 | enum class LogDestination : u32 { 8 | TMA = 1, 9 | UART = 2, 10 | UARTSleeping = 4, 11 | All = 0xFFFF, 12 | }; 13 | 14 | } -------------------------------------------------------------------------------- /LogManager/source/lm_main.cpp: -------------------------------------------------------------------------------- 1 | #include "lm_service.hpp" 2 | 3 | extern "C" { 4 | 5 | extern u32 __start__; 6 | u32 __nx_applet_type = AppletType_None; 7 | u32 __nx_fs_num_sessions = 1; 8 | 9 | #define INNER_HEAP_SIZE 0x10000 10 | size_t nx_inner_heap_size = INNER_HEAP_SIZE; 11 | char nx_inner_heap[INNER_HEAP_SIZE]; 12 | 13 | void __libnx_initheap(void); 14 | void __appInit(void); 15 | void __appExit(void); 16 | 17 | } 18 | 19 | namespace ams { 20 | 21 | ncm::ProgramId CurrentProgramId = ncm::SystemProgramId::LogManager; 22 | 23 | namespace result { 24 | 25 | /* Fatal is launched way later after we are launched, so disable this. */ 26 | bool CallFatalOnResultAssertion = false; 27 | 28 | } 29 | 30 | } 31 | 32 | using namespace ams; 33 | 34 | void __libnx_initheap(void) { 35 | void* addr = nx_inner_heap; 36 | size_t size = nx_inner_heap_size; 37 | 38 | /* Newlib */ 39 | extern char* fake_heap_start; 40 | extern char* fake_heap_end; 41 | 42 | fake_heap_start = (char*)addr; 43 | fake_heap_end = (char*)addr + size; 44 | } 45 | 46 | void __appInit(void) { 47 | hos::InitializeForStratosphere(); 48 | 49 | /* Initialize services. */ 50 | sm::DoWithSession([&]() { 51 | R_ABORT_UNLESS(pminfoInitialize()); 52 | R_ABORT_UNLESS(fsInitialize()); 53 | R_ABORT_UNLESS(pscmInitialize()); 54 | }); 55 | 56 | R_ABORT_UNLESS(fs::MountSdCard("sdmc")); 57 | ams::CheckApiVersion(); 58 | } 59 | 60 | void __appExit(void) { 61 | /* Cleanup services. */ 62 | fs::Unmount("sdmc"); 63 | pscmExit(); 64 | fsExit(); 65 | pminfoExit(); 66 | } 67 | 68 | namespace { 69 | 70 | /* TODO: this domain/domain object amounts work fine, but which ones does N's LogManager actually use? */ 71 | 72 | struct ServerOptions { 73 | static constexpr size_t PointerBufferSize = 0; 74 | static constexpr size_t MaxDomains = 0x40; 75 | static constexpr size_t MaxDomainObjects = 0x200; 76 | }; 77 | 78 | constexpr sm::ServiceName LmServiceName = sm::ServiceName::Encode("lm"); 79 | constexpr size_t LmMaxSessions = 30; 80 | 81 | /* lm */ 82 | constexpr size_t NumServers = 1; 83 | sf::hipc::ServerManager g_server_manager; 84 | 85 | psc::PmModule g_pm_module; 86 | os::WaitableHolderType g_module_waitable_holder; 87 | 88 | } 89 | 90 | namespace ams::lm { 91 | 92 | void StartAndLoopProcess() { 93 | /* Get our psc:m module to handle requests. */ 94 | R_ABORT_UNLESS(g_pm_module.Initialize(psc::PmModuleId_Lm, nullptr, 0, os::EventClearMode_ManualClear)); 95 | os::InitializeWaitableHolder(std::addressof(g_module_waitable_holder), g_pm_module.GetEventPointer()->GetBase()); 96 | os::SetWaitableHolderUserData(std::addressof(g_module_waitable_holder), static_cast(psc::PmModuleId_Lm)); 97 | g_server_manager.AddUserWaitableHolder(std::addressof(g_module_waitable_holder)); 98 | 99 | psc::PmState pm_state; 100 | psc::PmFlagSet pm_flags; 101 | while(true) { 102 | auto *signaled_holder = g_server_manager.WaitSignaled(); 103 | if(signaled_holder != std::addressof(g_module_waitable_holder)) { 104 | R_ABORT_UNLESS(g_server_manager.Process(signaled_holder)); 105 | } 106 | else { 107 | g_pm_module.GetEventPointer()->Clear(); 108 | if(R_SUCCEEDED(g_pm_module.GetRequest(std::addressof(pm_state), std::addressof(pm_flags)))) { 109 | switch(pm_state) { 110 | case psc::PmState_Awake: 111 | case psc::PmState_ReadyAwaken: 112 | /* Awake, enable logging. */ 113 | impl::SetCanAccessFs(true); 114 | break; 115 | case psc::PmState_ReadySleep: 116 | case psc::PmState_ReadyShutdown: 117 | /* Sleep, disable logging. */ 118 | impl::SetCanAccessFs(false); 119 | break; 120 | default: 121 | break; 122 | } 123 | R_ABORT_UNLESS(g_pm_module.Acknowledge(pm_state, ResultSuccess())); 124 | } 125 | g_server_manager.AddUserWaitableHolder(signaled_holder); 126 | } 127 | } 128 | } 129 | 130 | } 131 | 132 | int main(int argc, char **argv) { 133 | /* Set thread name. */ 134 | os::SetThreadNamePointer(os::GetCurrentThread(), "ams.lm.IpcServer"); 135 | AMS_ASSERT(os::GetThreadPriority(os::GetCurrentThread()) == -18); 136 | 137 | /* Add service to manager. */ 138 | R_ABORT_UNLESS(g_server_manager.RegisterServer(LmServiceName, LmMaxSessions)); 139 | 140 | /* Loop forever, servicing our services. */ 141 | lm::StartAndLoopProcess(); 142 | 143 | return 0; 144 | } -------------------------------------------------------------------------------- /LogManager/source/lm_service.cpp: -------------------------------------------------------------------------------- 1 | #include "lm_service.hpp" 2 | 3 | namespace ams::lm { 4 | 5 | void Logger::WriteAndClearQueuedPackets() { 6 | impl::WriteLogPackets(this->log_path, this->queued_packets, this->program_id, this->destination); 7 | this->queued_packets.clear(); 8 | } 9 | 10 | void Logger::Log(const sf::InAutoSelectBuffer &buf) { 11 | auto packet = impl::ParseLogPacket(buf.GetPointer(), buf.GetSize()); 12 | /* Check if there's a queue already started. */ 13 | const bool has_queued_packets = !this->queued_packets.empty(); 14 | /* Initially always push the packet. */ 15 | this->queued_packets.push_back(packet); 16 | if(has_queued_packets && packet.header.IsTail()) { 17 | /* This is the final packet of the queue - write and clear it. */ 18 | this->WriteAndClearQueuedPackets(); 19 | } 20 | else if(!has_queued_packets && !packet.header.IsHead()) { 21 | /* No head flag and queue not started, so just log the packet and don't start a queue. */ 22 | this->WriteAndClearQueuedPackets(); 23 | } 24 | /* Otherwise, the packet is a regular packet of a list, so push it and continue. */ 25 | } 26 | 27 | void Logger::SetDestination(LogDestination destination) { 28 | this->destination = destination; 29 | } 30 | 31 | void LogService::OpenLogger(const sf::ClientProcessId &client_pid, sf::Out> out_logger) { 32 | u64 program_id = 0; 33 | /* Apparently lm succeeds on many/all commands, so we will succeed on them too. */ 34 | pminfoGetProgramId(&program_id, static_cast(client_pid.GetValue())); 35 | auto logger = std::make_shared(program_id); 36 | out_logger.SetValue(std::move(logger)); 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /LogManager/source/lm_service.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | #include "stratosphere/lm.hpp" 4 | 5 | namespace ams::lm { 6 | 7 | static constexpr const char LogsDirectory[] = "sdmc:/atmosphere/debug_logs"; 8 | 9 | class Logger : public sf::IServiceObject { 10 | 11 | private: 12 | enum class CommandId { 13 | Log = 0, 14 | SetDestination = 1, 15 | }; 16 | 17 | private: 18 | u64 program_id; 19 | LogDestination destination; 20 | std::vector queued_packets; 21 | char log_path[FS_MAX_PATH]; 22 | 23 | void WriteAndClearQueuedPackets(); 24 | public: 25 | Logger(u64 program_id) : program_id(program_id), destination(LogDestination::TMA), queued_packets(), log_path() { 26 | /* Ensure that the logs directory exists. */ 27 | fs::CreateDirectory(LogsDirectory); 28 | sprintf(this->log_path, "%s/%016lX.log", LogsDirectory, program_id); 29 | } 30 | 31 | private: 32 | void Log(const sf::InAutoSelectBuffer &buf); 33 | void SetDestination(LogDestination destination); 34 | 35 | public: 36 | DEFINE_SERVICE_DISPATCH_TABLE { 37 | MAKE_SERVICE_COMMAND_META(Log), 38 | MAKE_SERVICE_COMMAND_META(SetDestination, hos::Version_3_0_0), 39 | }; 40 | 41 | }; 42 | 43 | class LogService : public sf::IServiceObject { 44 | private: 45 | enum class CommandId { 46 | OpenLogger = 0, 47 | }; 48 | 49 | private: 50 | void OpenLogger(const sf::ClientProcessId &client_pid, sf::Out> out_logger); 51 | 52 | public: 53 | DEFINE_SERVICE_DISPATCH_TABLE { 54 | MAKE_SERVICE_COMMAND_META(OpenLogger), 55 | }; 56 | 57 | }; 58 | 59 | } -------------------------------------------------------------------------------- /LogManager/source/stratosphere/lm/impl/lm_log_packet.cpp: -------------------------------------------------------------------------------- 1 | #include "stratosphere/lm/impl/lm_log_packet.hpp" 2 | #include "stratosphere/lm/impl/lm_scoped_log_file.hpp" 3 | 4 | namespace ams::lm::impl { 5 | 6 | namespace { 7 | 8 | bool can_access_fs = true; 9 | os::Mutex fs_access_lock(false); 10 | 11 | } 12 | 13 | void SetCanAccessFs(bool can_access) { 14 | std::scoped_lock lk(fs_access_lock); 15 | can_access_fs = can_access; 16 | } 17 | 18 | void WriteLogPackets(const char *log_path, std::vector &packet_list, u64 program_id, LogDestination destination) { 19 | std::scoped_lock lk(fs_access_lock); 20 | if(!can_access_fs) { 21 | /* Only write log if we can access fs. */ 22 | return; 23 | } 24 | if(packet_list.empty()) { 25 | /* This shouldn't happen... */ 26 | return; 27 | } 28 | 29 | /* For everything except the text log, use the first/head packet. */ 30 | auto &head_packet = packet_list.front(); 31 | const bool is_single_packet = packet_list.size() == 1; 32 | ScopedLogFile log_file(log_path); 33 | log_file.WriteFormat("\n"); 34 | log_file.WriteFormat("/----------------------------------------------------------------------------------------------------\\\n"); 35 | log_file.WriteFormat("|\n"); 36 | log_file.WriteFormat("| Log - %s (0x%016lX)\n", is_single_packet ? "single packet" : "multiple packets", program_id); 37 | 38 | /* Log severity. */ 39 | log_file.WriteFormat("| Log severity (Trace, Info, Warn, Error, Fatal): "); 40 | switch(static_cast(head_packet.header.severity)) { 41 | case LogSeverity::Trace: 42 | log_file.WriteFormat("Trace"); 43 | break; 44 | case LogSeverity::Info: 45 | log_file.WriteFormat("Info"); 46 | break; 47 | case LogSeverity::Warn: 48 | log_file.WriteFormat("Warn"); 49 | break; 50 | case LogSeverity::Error: 51 | log_file.WriteFormat("Error"); 52 | break; 53 | case LogSeverity::Fatal: 54 | log_file.WriteFormat("Fatal"); 55 | break; 56 | default: 57 | log_file.WriteFormat("Unknown"); 58 | break; 59 | } 60 | log_file.WriteFormat("\n"); 61 | 62 | /* Log verbosity. */ 63 | log_file.WriteFormat("| Log verbosity: %d\n", head_packet.header.verbosity); 64 | 65 | /* Log destination. */ 66 | log_file.WriteFormat("| Log destination: "); 67 | switch(destination) { 68 | case LogDestination::TMA: 69 | log_file.WriteFormat("TMA"); 70 | break; 71 | case LogDestination::UART: 72 | log_file.WriteFormat("UART"); 73 | break; 74 | case LogDestination::UARTSleeping: 75 | log_file.WriteFormat("UART (when sleeping)"); 76 | break; 77 | case LogDestination::All: 78 | log_file.WriteFormat("All (TMA and UART)"); 79 | break; 80 | default: 81 | log_file.WriteFormat("Unknown"); 82 | break; 83 | } 84 | log_file.WriteFormat("\n"); 85 | log_file.WriteFormat("|\n"); 86 | 87 | /* Process ID and thread ID. */ 88 | log_file.WriteFormat("| Process ID: 0x%016lX\n", head_packet.header.process_id); 89 | log_file.WriteFormat("| Thread ID: 0x%016lX\n", head_packet.header.thread_id); 90 | 91 | /* File name, line number, function name. */ 92 | if(!head_packet.payload.file_name.IsEmpty()) { 93 | /* At */ 94 | log_file.WriteFormat("| At %s", head_packet.payload.file_name.value); 95 | if(!head_packet.payload.function_name.IsEmpty()) { 96 | /* If function name is present, line number is present too. */ 97 | /* At : () */ 98 | log_file.WriteFormat(":%d (%s)", head_packet.payload.line_number.value, head_packet.payload.function_name.value); 99 | } 100 | log_file.WriteFormat("\n"); 101 | } 102 | if(!head_packet.payload.process_name.IsEmpty()) { 103 | log_file.WriteFormat("| Process name: %s\n", head_packet.payload.process_name.value); 104 | } 105 | if(!head_packet.payload.module_name.IsEmpty()) { 106 | log_file.WriteFormat("| Module name: %s\n", head_packet.payload.module_name.value); 107 | } 108 | if(!head_packet.payload.thread_name.IsEmpty()) { 109 | log_file.WriteFormat("| Thread name: %s\n", head_packet.payload.thread_name.value); 110 | } 111 | 112 | if(!head_packet.payload.log_packet_drop_count.IsEmpty()) { 113 | /* Log packet drop count (what is this used for...?) */ 114 | log_file.WriteFormat("| Log packet drop count: %ld\n", head_packet.payload.log_packet_drop_count.value); 115 | } 116 | 117 | if(!head_packet.payload.user_system_clock.IsEmpty()) { 118 | /* User system clock - seconds since the title has started. */ 119 | log_file.WriteFormat("| Time since title started: %lds\n", head_packet.payload.user_system_clock.value); 120 | } 121 | 122 | log_file.WriteFormat("|\n"); 123 | log_file.WriteFormat("\\----------------------------------------------------------------------------------------------------/\n"); 124 | 125 | if(!head_packet.payload.text_log.IsEmpty()) { 126 | /* Concatenate all the packets' messages. */ 127 | for(auto &packet: packet_list) { 128 | log_file.WriteFormat("%s", packet.payload.text_log.value); 129 | } 130 | log_file.WriteFormat("\n"); 131 | } 132 | } 133 | } -------------------------------------------------------------------------------- /LogManager/source/stratosphere/lm/impl/lm_scoped_log_file.cpp: -------------------------------------------------------------------------------- 1 | #include "stratosphere/lm/impl/lm_scoped_log_file.hpp" 2 | 3 | namespace ams::lm::impl { 4 | 5 | namespace { 6 | 7 | os::Mutex g_log_lock(true); 8 | 9 | /* Longest strings will be slightly bigger than 0x100 bytes, so this will be enough. */ 10 | char g_log_format_buffer[0x400]; 11 | 12 | } 13 | 14 | void ScopedLogFile::WriteString(const char *str) { 15 | std::scoped_lock lk(g_log_lock); 16 | 17 | this->Write(str, std::strlen(str)); 18 | } 19 | 20 | void ScopedLogFile::WriteFormat(const char *fmt, ...) { 21 | std::scoped_lock lk(g_log_lock); 22 | 23 | /* Format to the buffer. */ 24 | { 25 | std::va_list vl; 26 | va_start(vl, fmt); 27 | std::vsnprintf(g_log_format_buffer, sizeof(g_log_format_buffer), fmt, vl); 28 | va_end(vl); 29 | } 30 | 31 | /* Write data. */ 32 | this->WriteString(g_log_format_buffer); 33 | } 34 | 35 | void ScopedLogFile::Write(const void *data, size_t size) { 36 | std::scoped_lock lk(g_log_lock); 37 | 38 | /* If we're not open, we can't write. */ 39 | if (!this->IsOpen()) { 40 | return; 41 | } 42 | 43 | /* Advance, if we write successfully. */ 44 | if (R_SUCCEEDED(fs::WriteFile(this->file, this->offset, data, size, fs::WriteOption::Flush))) { 45 | this->offset += size; 46 | } 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LogManager-reimpl 2 | Custom reimplementation of LogManager service, redirecting logs to SD card 3 | -------------------------------------------------------------------------------- /binlog_reader.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import struct 4 | from enum import IntEnum 5 | from datetime import datetime 6 | 7 | class LogDataChunkKey(IntEnum): 8 | SessionBegin = 0 9 | SessionEnd = 1 10 | TextLog = 2 11 | LineNumber = 3 12 | FileName = 4 13 | FunctionName = 5 14 | ModuleName = 6 15 | ThreadName = 7 16 | LogPacketDropCount = 8 17 | UserSystemClock = 9 18 | ProcessName = 10 19 | 20 | class LogSeverity(IntEnum): 21 | Trace = 0, 22 | Info = 1, 23 | Warn = 2, 24 | Error = 3, 25 | Fatal = 4, 26 | 27 | class LogPacketHeader: 28 | def __init__(self, process_id, thread_id, severity, verbosity, size): 29 | self.process_id = process_id 30 | self.thread_id = thread_id 31 | self.severity = severity 32 | self.verbosity = verbosity 33 | self.size = size 34 | 35 | class LogDataChunk: 36 | def __init__(self, chunk_key, chunk_size, chunk_data): 37 | self.chunk_key = chunk_key 38 | self.chunk_size = chunk_size 39 | self.chunk_data = chunk_data 40 | 41 | def read_string(self): 42 | return str(self.chunk_data, "utf-8") 43 | 44 | def read_n(self, fmt): 45 | tpl = struct.unpack(fmt, self.chunk_data) 46 | return tpl[0] 47 | 48 | def read_u32(self): 49 | return self.read_n("I") 50 | 51 | def read_u64(self): 52 | return self.read_n("Q") 53 | 54 | def read_bool(self): 55 | return bool(self.read_n("B")) 56 | 57 | def format_data(self): 58 | if self.chunk_key is LogDataChunkKey.UserSystemClock: 59 | return str(self.read_u64()) 60 | elif self.chunk_key is LogDataChunkKey.LineNumber: 61 | return str(self.read_u32()) 62 | elif self.chunk_key is LogDataChunkKey.ThreadName: 63 | return self.read_string() 64 | elif self.chunk_key is LogDataChunkKey.FileName: 65 | return self.read_string() 66 | elif self.chunk_key is LogDataChunkKey.FunctionName: 67 | return self.read_string() 68 | elif self.chunk_key is LogDataChunkKey.FileName: 69 | return self.read_string() 70 | elif self.chunk_key is LogDataChunkKey.TextLog: 71 | return self.read_string() 72 | elif self.chunk_key is LogDataChunkKey.ProcessName: 73 | return self.read_string() 74 | elif self.chunk_key is LogDataChunkKey.ModuleName: 75 | return self.read_string() 76 | else: 77 | return "" 78 | 79 | def main(): 80 | if len(sys.argv) >= 2: 81 | binlog_sz = os.stat(sys.argv[1]).st_size 82 | if binlog_sz >= 0x18: 83 | with open(sys.argv[1], "rb") as binlog: 84 | header_data = binlog.read(0x18) 85 | (process_id, thread_id, _pad, severity, verbosity, payload_size) = struct.unpack("QQHBBI", header_data) 86 | print(" - Process ID: 0x%X" % process_id) 87 | print(" - Thread ID: 0x%X" % thread_id) 88 | print(" - Log severity: %s" % LogSeverity(severity).name) 89 | print(" - Log verbosity: %s" % str(bool(verbosity))) 90 | print(" - Payload size: %r" % payload_size) 91 | print("\n *** Data chunks / log fields ***\n") 92 | offset = 0 93 | while offset < payload_size: 94 | chunk_info = binlog.read(2) 95 | offset += 2 96 | chunk_key = LogDataChunkKey(int(chunk_info[0])) 97 | chunk_size = int(chunk_info[1]) 98 | chunk_data = binlog.read(chunk_size) 99 | chunk = LogDataChunk(chunk_key, chunk_size, chunk_data) 100 | chunk_str = chunk.format_data() 101 | if len(chunk_str) == 0: 102 | chunk_str = "" 103 | print(" - %s\n%s\n" % (chunk_key.name, chunk_str)) 104 | offset += chunk_size 105 | else: 106 | print("Invalid binlog file size (smaller than 24 bytes)") 107 | else: 108 | print("No binlog specified.") 109 | 110 | if __name__ == "__main__": 111 | main() 112 | --------------------------------------------------------------------------------