diff --git a/desmume/AUTHORS b/AUTHORS similarity index 100% rename from desmume/AUTHORS rename to AUTHORS diff --git a/desmume/COPYING b/COPYING similarity index 100% rename from desmume/COPYING rename to COPYING diff --git a/desmume/ChangeLog b/ChangeLog similarity index 97% rename from desmume/ChangeLog rename to ChangeLog index bf4d6a822..d8b6a9cb2 100644 --- a/desmume/ChangeLog +++ b/ChangeLog @@ -1,22 +1,3 @@ -0.9.4 -> ??? (r2437-r???) - -Highlights: - * win32: lua engine, path configuration, 7z dearchiving support - -General/Core: - bug: fix cflash directory support for non-windows - bug: fix freeze in cart irq - bug: correctly emulate dma to/from tcm - enh: ideas-style debugging prints - -Graphics: - bug: fixing of obj blending and bmp obj rendering - bug: swrast: add clear image emulation - bug: swrast: add edge marking - -Windows: - bug: improve map view tool - 0.9.2 -> 0.9.4 (r1844->r2352->r2437) 0.9.3 was skipped due to emu news sites sneaking it out of our staging area and diff --git a/desmume/Makefile.am b/Makefile.am similarity index 100% rename from desmume/Makefile.am rename to Makefile.am diff --git a/desmume/NEWS b/NEWS similarity index 100% rename from desmume/NEWS rename to NEWS diff --git a/desmume/README b/README similarity index 100% rename from desmume/README rename to README diff --git a/desmume/README.LIN b/README.LIN similarity index 100% rename from desmume/README.LIN rename to README.LIN diff --git a/desmume/README.MAC b/README.MAC similarity index 100% rename from desmume/README.MAC rename to README.MAC diff --git a/desmume/README.TRANSLATION b/README.TRANSLATION similarity index 100% rename from desmume/README.TRANSLATION rename to README.TRANSLATION diff --git a/desmume/README.WIN b/README.WIN similarity index 53% rename from desmume/README.WIN rename to README.WIN index 5b45f54f0..18ee2e817 100644 --- a/desmume/README.WIN +++ b/README.WIN @@ -50,6 +50,7 @@ Contents # 1.1.4.8 Config | Emulation Settings # 1.1.4.9 Config | Frame Skip # 1.1.4.10 Config | Language + # 1.1.4.11 Config | Background Pause + 1.1.5 Tools Menu # 1.1.5.1 Tools | Disassembler # 1.1.5.2 Tools | View Memory @@ -70,603 +71,573 @@ Contents # 1.1.6.3 Help | Submit a bug report # 1.1.6.4 Help | About -Quick Getting Started Guide -When you start the emulator for the first time, you probably just want to play a certain game. You can do this by going to 'File' in the menu, and selecting 'Open Rom'. This will open up an explorer window, within which you can browse to the rom (nds file) that you wish to play. Once the game has finished loading (and this should only take a few seconds at most), your game will automatically start running. But if you want, you can also compile from source. See the article Installing DeSmuME from source on Windows for details. -Menu Layout += Quick Getting Started Guide = +When you start the emulator for the first time, you probably just want to play a certain game. You can do this by going to 'File' in the menu, and selecting 'Open Rom'. This will open up an explorer window, within which you can browse to the rom (nds file) that you wish to play. Once the game has finished loading (and this should only take a few seconds at most), your game will automatically start running. But if you want, you can also compile from source. See the article [[Installing DeSmuME from source on Windows]] for details. +== Menu Layout == The rest of this manual will be spend on explaining all the other options in the menu. -File Menu -File | Open Rom +=== File Menu === + + +==== File | Open Rom ==== This option is for loading games. A game is typically called a rom file. Just use the explorer window to browse to the file, and click on open. The game should just load and start. The desmume windows port is also able to load some compressed formats, like zip and gz. Just as long as there is a valid game (rom) file in the compressed archive ending with an .nds extension, it should load fine. -File | Recent Rom +==== File | Recent Rom ==== This menu option contains a list of the roms that you have most recently loaded. You can quickly access a game that way, without having browse to the right directory with the 'Open Rom' option. -File | Rom Info +==== File | Rom Info ==== This option offers some information about the internals of the rom file, like name, code, manufacturer, and size. This should not concern the casual gamer, but may come in handy for developers. -File | Save State As... +==== File | Save State As... ==== Imagine you have gotten to a certian point in a game, and you need to do something else. The emulator let's you save the current state of the game, so that you can continue the game later at precisely the same point somewhere in the future. Please note that the use of SAVESTATES is discouraged, as these are likely to break between emulator versions. Instead use SAVE FILES. These are likely to survive between emulator versions. This means that you will have to use save points within the game. SAVE FILES are stored in .sav files. -File | Load State As... +==== File | Load State As... ==== Once you have saved a game's position, or 'state', you can load it again with this option. -File | Save State +==== File | Save State ==== This option works fairly similair to the 'Save As' option, altough it let's you save numbers instead os specifying a chosen name. Also, All the states saved via this option end up with a pre-determined name of 'game (rom) name'.dsx. So if the game is called MyGame, the first savefile will be called MyGame.ds0, the second one MyGame.ds1, etc. -File | Load State +==== File | Load State ==== This option let's you load the states that you saved via the 'File | Save State' option -File | Import Backup Memory +==== File | Import Backup Memory ==== Backup Memory is the data the game uses to remember its own state. It is stored on the cart in a normal game. Desmume uses the .dsv extension and file format; other formats which can be imported are .duc and raw .sav. People use pro action replays to capture duc files from their card and post it online without using emulators. These are frequently found on gamefaqs.com. See the faq for details on how to use this function, where it has been documented better. -File | Export Backup Memory +==== File | Export Backup Memory ==== This lets you export the game's state for use in other Nintendo DS Emulators. It will write a 'raw' sav file. -File | Save Screenshot As... +==== File | Save Screenshot As... ==== This lets you take a screenshot of the current view of the emulator, and specify it's name to save as a bitmap (.bmp) file. -File | Quick Screenshot +==== File | Quick Screenshot ==== This option also dumps a screencapture, but it has a pre-determied filename and location. It will be called printscreen.bmp, and located in the current directory. In Windows, this is probably the same folder as where your desmume binary is located. -File | Record AVI +==== File | Record AVI ==== This option lets you capture what's going on in the emulator, and save it in an avi file. -File | Stop AVI +==== File | Stop AVI ==== The 'Record AVI' option continues to record the game, untill you press the 'Stop Avi' option. -File | Record WAV -This option lets you capture the sound played in the emulator, and save it in a wav file. -File | Record Movie +==== File | Record WAV ==== +This option lets you capture the sound played in the emulator, and save it in a wav file. +==== File | Record Movie ==== This option lets you record the gameplay in TAS format, see http://tasvideos.org for details on TAS (tool-assisted speedruns). -File | Play Movie +==== File | Play Movie ==== This option lets you playback a pre-recorded TAS movie. -File | Stop Movie +==== File | Stop Movie ==== This options lets you stop recording a TAS movie. -File | Quit +==== File | Quit ==== Choosing this option exits the emulator. -Emulation Menu -Emulation | Pause +=== Emulation Menu === + + +==== Emulation | Pause ==== This option will pause the emulation, freezing it at the current moment of execution. Selecting it again will resume the execution of the ROM at the exact moment where you paused it. -Emulation | Reset +==== Emulation | Reset ==== This option will reset the ROM that is currently loaded to the very start of the ROM, just as if you chose 'File | Open Rom' again. -Emulation | Clear Sound +==== Emulation | Clear Sound ==== This option turns off all the sound. -Emulation | GBA Slot -This menu option pop-ups a new window, which lets you specirfy what to do with the GBA slot of the Nintendo DS. It has the following choices : NONE, Compact Flash, Rumble Pack, GBA Game. Rumble pack allows some games to use vibration. Memory extension... Extends memory. And some DS games can have bonuses, unlockable by GBA cart. For example in Megaman ZX you can fight some Megaman Zero Bosses when correct cartridge is inserted. There are also other GBA slot extensions, like... a Guitar hero controller. But these are currently not emulated by desmume. Flash Cartridge is used for homebrew software emulation, for example that uses DLDI ( Dynamically Linked Device Interface). -Emulation | Cheats +==== Emulation | GBA Slot ==== +This menu option pop-ups a new window, which lets you specirfy what to do with the GBA slot of the Nintendo DS. It has the following choices : +NONE, Compact Flash, Rumble Pack, GBA Game. Rumble pack allows some games to use vibration. Memory extension... Extends memory. And some DS games can have bonuses, unlockable by GBA cart. For example in Megaman ZX you can fight some Megaman Zero Bosses when correct cartridge is inserted. There are also other GBA slot extensions, like... a Guitar hero controller. But these are currently not emulated by desmume. Flash Cartridge is used for homebrew software emulation, for example that uses DLDI ( Dynamically Linked Device Interface). -This option pulls down a drop-down menu, and presents the options list and search. Be aware though, that cheats are sort of half baked right now. If you are not having luck, wait for some news on an improved cheat system. Also, it is impossible yet to use "commercial" codes, such as Action Replay and Codebreaker, so what you'll have to do is manually search for, and alter the memory positions to your advantage. They are called 'raw' or 'internal' cheats. There's an excellent article in the wiki on Using Cheats in DeSmuMe . In post-0.9.2 development builds, there is also the support for Action Replay cheat codes. -Emulation | Cheats | List +==== Emulation | Cheats ==== +This option pulls down a drop-down menu, and presents the options list and search. Be aware though, that cheats are sort of half baked right now. If you are not having luck, wait for some news on an improved cheat system. Also, it is impossible yet to use "commercial" codes, such as Action Replay and Codebreaker, so what you'll have to do is manually search for, and alter the memory positions to your advantage. They are called 'raw' or 'internal' cheats. There's an excellent article in the wiki on [[Using Cheats in DeSmuMe ]]. In post-0.9.2 development builds, there is also the support for Action Replay cheat codes. -Choosing 'list' will list all the currently known cheats. Please refer to the article Using Cheats in DeSmuMe for further details on how to use the cheat mechanism in desmume. -Emulation | Cheats | Search +==== Emulation | Cheats | List ==== +Choosing 'list' will list all the currently known cheats. Please refer to the article [[Using Cheats in DeSmuMe ]] for further details on how to use the cheat mechanism in desmume. -Choosing 'search' will let you search for cheats. Please refer to the article Using Cheats in DeSmuMe for further details on how to use the cheat mechanism in desmume. -View Menu -View | Rotation +==== Emulation | Cheats | Search ==== +Choosing 'search' will let you search for cheats. Please refer to the article [[Using Cheats in DeSmuMe ]] for further details on how to use the cheat mechanism in desmume. +=== View Menu === + + +==== View | Rotation ==== This option will let you rotate the screen a pre-determined amount of degrees in order to adjust the angle of the display. Some programs require that you normally turn the DS on its side. You can set it up in that manner using this. The options are 0 (no rotation),90 ,180, and 270. -View | Window size -This option will let you enlarge the windows a pre-determined size. The resize options are: 1x, 1.5x, 2x, 3x, and 4x the default size. You can also adjust the window size by clicking on the edge of the window, and dragging the mouse. -View | Screen Separation +==== View | Window size ==== +This option will let you enlarge the windows a pre-determined size. The resize options are: 1x, 1.5x, 2x, 3x, and 4x the default size. You can also adjust the window size by clicking on the edge of the window, and dragging the mouse. +==== View | Screen Separation ==== This option controls how far the two windows should be apart of each other, in other words: how big the border between them should be. Valid choices are: None (which is the default), narrow border (which is slightly larger), DS (which is about the wsame amount of room there is on a real Nintendo DS). -View | Force Maintain Ratio +==== View | Force Maintain Ratio ==== Here you can choose, when re-sizing the windows, if you wan to maintain the ratio of the windows. Sometimes when the window size is changed it doesn't look correct on the screen. This option forces the window to maintain a correct ratio so it looks correct. You can select or de-select this option. -View | Display Frame Counter +==== View | Display Frame Counter ==== Selecting this option causes a counter to run, that counts all the frames that have been displayed. -View | Display FPS +==== View | Display FPS ==== Selecting this option causes the 'frames-per-second' (or 'fps', for short) to be displayed. It also displays an additional '3D' counter, which tells how frequently the game is updating its 3d graphics. But unlike the fps counter, the 3d counter has nothing to do with the power of your system. If it is low, then the game is running slow on a retail cart, and so it runs slow in an emulator. -View | Display Input -Selecting this option displays the keys you press on the keyboard, which is the input -View | Display Lag Counter +==== View | Display Input ==== +Selecting this option displays the keys you press on the keyboard, which is the input +==== View | Display Lag Counter ==== This option causes a counter to display that counts frames where the game doesn't poll input. -View | HUD Editing Mode +==== View | HUD Editing Mode ==== This option will let you drag around hud elements to pick their position. -Config Menu -Config | Save Type +=== Config Menu === + +==== Config | Save Type ==== This option lets you specify the save type of a particular game. The default is 'automatic'. However, this is not fail-safe in all cases, so you might need to manually select one of the other savetypes. -Config | 3D Settings -This option lets you select the method that is used to draw the screen. You can choose between OpenGL (an open standard) or SoftRasterizer (a desmume specific method). +==== Config | 3D Settings ==== +This option lets you select the method that is used to draw the screen. You can choose between OpenGL (an open standard) or SoftRasterizer (a desmume specific method). Furthermore, you have two checkboxes that you can either enable or disable: - * Unrealistically High-Precision Color Interpolation. Presently only effective for SoftRasterizer. - * Alternate Flush Mode. This fixes some games with flickering graphics. This is apllicable to both the OpenGl and the SoftRasterizer. - -Config | Control Config +* Unrealistically High-Precision Color Interpolation. Presently only effective for SoftRasterizer. +* Alternate Flush Mode. This fixes some games with flickering graphics. This is apllicable to both the OpenGl and the SoftRasterizer. +==== Config | Control Config ==== This option lets you configure keyboard keys or a joystick. The joystick support is implemented using a DirectInput control interface. -Here are the default key mappings (they may be subject to change): +Here are the default key mappings (they may be subject to +change): - Up arrow - Up - Left arrow - Left - Down arrow - Down - Right arrow - Right - x - A button - z - B button - s - X button - a - Y button - q - Left Trigger - w - Right Trigger - Enter - Start button - Right Shift - Select button - Backspace - Lid fold/unfold - - n - Frame advance - Space - Pause/Unpause - p - Load current state - 1,2,3,4,5,6,7,8,9,0 - Select current state - F1-F10 - Load relevant state - Shift+F1-F10 - Save relevant state - -Config | Hotkey Config + Up arrow - Up + Left arrow - Left + Down arrow - Down + Right arrow - Right + x - A button + z - B button + s - X button + a - Y button + q - Left Trigger + w - Right Trigger + Enter - Start button + Right Shift - Select button + Backspace - Lid fold/unfold + + n - Frame advance + Space - Pause/Unpause + p - Load current state + 1,2,3,4,5,6,7,8,9,0 - Select current state + F1-F10 - Load relevant state + Shift+F1-F10 - Save relevant state +==== Config | Hotkey Config ==== This menu option lets you define keys, that can be used to quickly select other options without having to go through the entire menu structure. Some examples are a hotkey for 'pause', or a hotkey for loading a specific savestate. -Config | Sound Settings -This option lets you choose between different sound generating methods, which currectly are 'Direct Sound Interface' and 'WAV Write sound Interface'. You can set the interpolation to choose between better quality and faster emulation. It also let's you specify the size of the buffer to buffer the sound. For performance improvements, you can turn on the sound option "ADPCM Caching". 'ADPCM' is a type of sound compression which is supposed to be fast to decode. This is new and experimental, and will break some things, but it should offer a substantial speedup in some cases. And lastly, you can also set the sound volume in this dialog. -Config | WIFI Settings +==== Config | Sound Settings ==== +This option lets you choose between different sound generating methods, which currectly are 'Direct Sound Interface' and 'WAV Write sound Interface'. You can set the interpolation to choose between better quality and faster emulation. It also let's you specify the size of the buffer to buffer the sound. +For performance improvements, you can turn on the sound option "ADPCM Caching". 'ADPCM' is a type of sound compression which is supposed to be fast to decode. This is new and experimental, and will break some things, but it should offer a substantial speedup in some cases. And lastly, you can also set the sound volume in this dialog. +==== Config | WIFI Settings ==== WIFI support is currently under heavy development, but it is not useful yet. Therefore, you may find this option missing, or simply 'greyed-out' for now. Even if you can fiddle with it, it won't do anything useful. -Config | Firmware Settings +==== Config | Firmware Settings ==== This option provides you with the same set of options that a real Nintendo DS firmware does. The most important here is the language, because multi-lingual games will often look at how this option is set. -Config | Emulation Settings +==== Config | Emulation Settings ==== These options let you boot from the extracted BIOS and Firmware of a real Nintendo DS. unless you have extracted/downloaded the firmware or bios from a Nintendo DS that you actually own yourself, these settings have no value for you qas desmume does not require them to run correctly. -Config | Frame Skip +==== Config | Frame Skip ==== This option lets you select how many frames should not be displayed, in order to gain speed improvements. The default is 'Auto'. If you have speed problems, you could decide to skip (not display) one or more frames in order to improve the speed. 'Limit Frameskip' let's you limit the frame rate to 60fps maximum. 60fps is essentially the speed that the game plays at on the actual console itself. So by selecting this option, you're limiting the framerate to the actual speed of the actual console. -Config | Language +==== Config | Language ==== This lets you set the langguage the emulator displays it's menu's and options in. -Tools Menu -Tools | Disassembler -This option displays the ARM9 and ARM7 disassembler. Be aware though, that the windows are drawn exactly on top of each other, so that you have to move (drag n drop) the first windows before the second window shows. -Tools | View Memory +==== Config | Background Pause ==== +Selecting this oiption will pause the emulation whenever you put desmume in the background, or the window loses focus. +=== Tools Menu === + +==== Tools | Disassembler ==== +This option displays the ARM9 and ARM7 disassembler. Be aware though, that the windows are drawn exactly on top of each other, so that you have to move (drag n drop) the first windows before the second window shows. + +==== Tools | View Memory ==== This tool displays the ARM7 and ARM9 memory. Be aware though, that the windows are drawn exactly on top of each other, so that you have to move (drag n drop) the first windows before the second window shows. The "View mode" radio buttons allow you to choose how the memory will be shown: - - * 8-bit : shows the memory as bytes - * 16-bit : shows the memory as words - * 32-bit : shows the memory as dwords +* 8-bit : shows the memory as bytes +* 16-bit : shows the memory as words +* 32-bit : shows the memory as dwords The "View address" textbox and button allow you to jump to a different address: - - * Enter an hexadecimal address without 0x prefix, with up to 8 digits - * Click "Go" to jump to the entered address +* Enter an hexadecimal address without 0x prefix, with up to 8 digits +* Click "Go" to jump to the entered address The "View dump" buttons allow you to dump the current view: - - * Text dump : dumps the view to a text file, in an human-readable form - * Raw dump : dumps the memory directly to a binary file which can be read with an hex editor - +* Text dump : dumps the view to a text file, in an human-readable form +* Raw dump : dumps the memory directly to a binary file which can be read with an hex editor Note that if you dump memory to a file already containing (a) dump(s), the new dump will be appended to the existing one(s). The scrollbar... well, you surely know how a scrollbar works. -The viewers additionally allow to edit the memory. For it, click on the value you want to edit, then type the new value. The new value is applied only once you've entirely entered it. -Tools | View Registers +The viewers additionally allow to edit the memory. For it, click on the value you want to edit, then type the new value. +The new value is applied only once you've entirely entered it. +==== Tools | View Registers ==== This option lets you view the ARM7 and ARM9 I/O registers. -Tools | View Palette +==== Tools | View Palette ==== This option lets you view the palette in detail. -Tools | View Tiles +==== Tools | View Tiles ==== This option lets you view the tiles in detail. -Tools | View Maps +==== Tools | View Maps ==== This option lets you view the maps in detail. -Tools | View OAM +==== Tools | View OAM ==== This option lets you view the OAM layer in detail. -Tools | View Matrices +==== Tools | View Matrices ==== This option lets you view the matrices in detail. -Tools | View Lights +==== Tools | View Lights ==== This option lets you view the lights in detail. -Tools | View Sound State +==== Tools | View Sound State ==== This option displays the sound output. -View | RAM Watch +==== View | RAM Watch ==== This option will pop-up a new window, with extensive and advanced features to watch the emulated RAM memory. -View | RAM Search +==== View | RAM Search ==== This option will pop-up a new window, with extensive and advanced features to search through the emulated RAM memory. -Tools | View Layers +==== Tools | View Layers ==== This option lets you view the Layers one by one. -Help Menu -Help | Website +=== Help Menu === +==== Help | Website ==== This option directs your browser to the desmume homepage. -Help | Forums +==== Help | Forums ==== This option directs your browser to the desmume forums. -Help | Submit a bug report +==== Help | Submit a bug report ==== This option directs your browser to the SourceForge bugtracker for desmume. -Help | About +==== Help | About ==== This option displays the authors of the emulator. + Retrieved from "http://wiki.desmume.org/index.php?title=DeSmuME_Manual_for_the_Windows_port" -This page was last modified on 17 June 2009, at 04:59. +This page was last modified on 26 June 2009, at 20:57. ==================================================================== DesMuMe Faq -If the FAQ is unable to answer your question(s), then please make sure that you also consult the manual. -Contents - * 1 General Questions - o 1.1 What does desmume emulate and on what systems? - o 1.2 What does DeSmuME mean? - o 1.3 Under what license is desmume distributed ? - o 1.4 Can I freely copy desmume ? - o 1.5 Why doesn't my desmume play this game? - o 1.6 Why does this game fail to save? or, I get the error: "Data could not be accessed. Turn off the power and reinsert the DS card." - o 1.7 I get the error: "Unable to write data. Please turn off the power and reinsert the game card." - o 1.8 Why did you change the save file format and extension from .sav to .dsv ? - o 1.9 Can I use my save states across versions ? - o 1.10 Can I convert an ideas or no$gba nocash .sav savefile to desmume .dsv ? - o 1.11 Why can't I find a mac binary? - o 1.12 Why does my mac binary say something about being unsupported? - o 1.13 Where can I report bugs? - o 1.14 Can I attach files to bug reports I did not create myself ? - o 1.15 How do I get the latest svn code and build desmume myself? - o 1.16 Whats 'svn' ? - o 1.17 What compilers are supported for building desmume from source ? - o 1.18 Im Compiling using MSVC Express On Windows, and I get the error : "ml.exe" not found. - o 1.19 Im a developer, and would like to contribute to the codebase. What can I do ? - o 1.20 Im not a developer, but would like to help out anyway. What can I do ? - o 1.21 It is hard to zoom in on a widescreen display due to the weird aspect ratio of the DS. - o 1.22 Why doesn't my openGL 3d work in linux? - o 1.23 Why doesn't my openGL 3d work in windows? - o 1.24 Why doesn't a menu option or tool exist in my linux or mac build? - o 1.25 Why does music sound bad sometimes? - o 1.26 Why doesn't my game boot or progress into the main game engine? - o 1.27 What hardware features are emulated? - o 1.28 Does the GDB stub still work? - o 1.29 How do I enable the GDB stub on the Windows port ? - o 1.30 Where/what is IRC? - o 1.31 Where is the manual? - o 1.32 How do I enter 'cheat codes' in desmume ? - o 1.33 Why is the emulator slow? - o 1.34 What does the number/percentage in the desmume title bar mean ? - o 1.35 What's the difference between the the Windows 'desmume' and 'desmume_nosse' versions ? - o 1.36 Does desmume make use of multiple CPU's or multiple cores ? - o 1.37 What are the minimum hardware requirements for desmume ? - o 1.38 What are the recommended hardware requirements for desmume ? - o 1.39 Does desmume support wifi ? - o 1.40 Why do I get an assert in wifi.cpp which keeps me from playing a game? - o 1.41 OK, then why does it make my firewall alert since 0.9.2 ? - o 1.42 OK, so then why did my build come with winpcap.dll? Or why do I get crashes when I run desmume on vista which mumble something about winpcap? - o 1.43 What is WFC / WIFI Connection - o 1.44 Does desmume support the microphone ? - o 1.45 Where can I find technical details on the Nintendo DS and GBA ? - o 1.46 Does the 'GBA slot' option let me play GBA games ? - o 1.47 What is DLDI ? - o 1.48 How can I post a savefile or avi capture on the desmume forum ? - o 1.49 How can I post a large log or other text file on the desmume IRC chat room ? - o 1.50 My display is incorrect or corrupted - o 1.51 My display has flickering graphics in a certain game - o 1.52 How do I easily capture the ASM code for troubleshooting purposes ? - o 1.53 How do I make pokemon save? - o 1.54 I got a gameplay related question - o 1.55 What are the origins of DeSmuME ? +If the FAQ is unable to answer your question(s), then please make sure that you also consult the [[manual]]. -General Questions - -What does desmume emulate and on what systems? +== General Questions == +=== What does desmume emulate and on what systems? === Desmume attempts to emulate, as faithfully as possible, the Nintendo DS and Nintendo DS Lite handheld game consoles (nds). It currently runs on Windows, Linux, and mac OSX. DSi is not supported. -What does DeSmuME mean? -DeSmuME is a Nintendo DS emulator and the name is a play of words - DS Emu + ME (like FlashMe - firmware hack and PassMe mod-chip for DS) The name DeSmuME derives from the popular use of ME in Nintendo DS products by homebrew developers. So DeSmuME would equal DSemuMe. Other popular uses of ME include: +=== What does DeSmuME mean? === - * LoadMe - a generic patcher for commercial DS roms that works with any GBA Flash Card - * PassMe - "mod-chip" using which takes authentication from an original DS card an allows execution of unauthenticated DS rom code - from the GBA cartridge slot / GBA flash card. - * FlashMe - a hacked firmware for DS that allows you to start code in DS mode from a flash card in the GBA slot. - * WifiMe - are a set of a custom drivers and software by FireFly for RALink based wireless network cards enabling to boot homebrew code on DS via Nintendo Wireless Multiboot method. +DeSmuME is a Nintendo DS emulator and the name is a play of words - DS Emu + ME (like FlashMe - firmware hack and PassMe mod-chip for DS) +The name DeSmuME derives from the popular use of ME in Nintendo DS products by homebrew developers. So DeSmuME would equal DSemuMe. Other popular uses of ME include: +* LoadMe - a generic patcher for commercial DS roms that works with any GBA Flash Card +* PassMe - "mod-chip" using which takes authentication from an original DS card an allows execution of unauthenticated DS rom code - from the GBA cartridge slot / GBA flash card. +* FlashMe - a hacked firmware for DS that allows you to start code in DS mode from a flash card in the GBA slot. +* WifiMe - are a set of a custom drivers and software by FireFly for RALink based wireless network cards enabling to boot homebrew code on DS via Nintendo Wireless Multiboot method. Its name is derived from emu which is short for emulator, DS and me. It's possibly supposed to mean "DS emulator for me". -Under what license is desmume distributed ? +=== Under what license is desmume distributed ? === Desmume is distributed under the Gnu General Public License, or GPL: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html -Can I freely copy desmume ? +=== Can I freely copy desmume ? === Yes you can, as long as you adhere to the license as specified in the GNU GPL. -Why doesn't my desmume play this game? -Go to desmume.org and make sure you are using the latest version. The latest version is 0.9.3. Hint: desmume 0.8 and 0.3.4 are very old, being numbers smaller than the latest version. Older versions will not be supported, under any circumstances. +=== Why doesn't my desmume play this game? === +Go to desmume.org and make sure you are using the latest version. The latest version is 0.9.4. Hint: desmume 0.8 and 0.3.4 are very old, being numbers smaller than the latest version. Older versions will not be supported, under any circumstances. -Why does this game fail to save? or, I get the error: "Data could not be accessed. Turn off the power and reinsert the DS card." -Until version 0.9.3 desmume's save size autodetection was poor. With 0.9.3, autodetection should work almost all the time. In fact, here is the entire list of games we know of that fail to autodetect correctly: +=== Why does this game fail to save? or, I get the error: "Data could not be accessed. Turn off the power and reinsert the DS card." === +Until version 0.9.4 desmume's save size autodetection was poor. With 0.9.4, autodetection should work almost all the time. In fact, here is the entire list of games we know of that fail to autodetect correctly: +* Spider-Man 3 +If you find any other game for which automatic savetype detection does not work, please let the developers know by posting on the forum or submitting a bug. If you want to fix it yourself, you may need to manually specify the correct save type for your game. Consult the manual for details on how to do this for your platform. You may also consult http://www.advanscene.com/ to easily identify the save type for your game. - * Spider-Man 3 - -If you find any other game for which automatic savetype detection does not work, please let the developers know by posting on the forum or submitting a bug. If you want to fix it yourself, you may need to manually specify the correct save type for your game. Consult the manual for details on how to do this for your platform. You may also consult http://www.advanscene.com/ to easily identify the save type for your game. - -I get the error: "Unable to write data. Please turn off the power and reinsert the game card." +=== I get the error: "Unable to write data. Please turn off the power and reinsert the game card." === Same problem and resolution as the previous question. -Why did you change the save file format and extension from .sav to .dsv ? +=== Why did you change the save file format and extension from .sav to .dsv ? === Because it is better now. These raw save files that everyone uses aren't good enough and were causing problems with autodetection. See our bug tracker or forum for more details; the dsv format has been documented in the svn source tree as dsv.txt and if you don't like the degree of interoperability with other emulators, then go tell the other emulators to support our format. -Can I use my save states across versions ? -Maybe, maybe not. Due to constant internal changes in desmume, it is possible that a save state created with one version may not work with another version of desmume. Savestate compatibility is preserved wherever possible, but it is not always possible. Please note that for easily confused gamers, the use of SAVESTATES is discouraged, as these are likely to break between emulator versions. Instead use SAVE FILES. These are likely to survive between emulator versions. This means that you will have to use save points within the game. SAVE FILES are stored in .dsv files. Also, see this article for further details : Savefile or savestate +=== Can I use my save states across versions ? === +Maybe, maybe not. Due to constant internal changes in desmume, it is possible that a save state created with one version may not work with another version of desmume. Savestate compatibility is preserved wherever possible, but it is not always possible. Please note that for easily confused gamers, the use of SAVESTATES is discouraged, as these are likely to break between emulator versions. Instead use SAVE FILES. These are likely to survive between emulator versions. This means that you will have to use save points within the game. SAVE FILES are stored in .dsv files. Also, see this article for further details : [[Savefile or savestate]] -Can I convert an ideas or no$gba nocash .sav savefile to desmume .dsv ? +=== Can I convert an ideas or no$gba nocash .sav savefile to desmume .dsv ? === +1. Convert the save file using http://shunyweb.info/convert.php ; the target format should be "Acekard RPG | EZFlash V | RAW Format [Autodetection] (.sav)" +2. Load the game. Let it get to the main menu +3. Select the correct backup size*, as specified by advanscene.com (which is not always right, by the way) +4. Use File > Import Backup Memory and pick the converted save file +5. Reset the game +*Step 3 is not always necessary, if you are smart, however, it will never hurt to do it. -1. Convert the save file using http://shunyweb.info/convert.php ; the target format should be "Acekard RPG | EZFlash V | RAW Format [Autodetection] (.sav)" 2. Load the game. Let it get to the main menu 3. Select the correct backup size*, as specified by advanscene.com (which is not always right, by the way) 4. Use File > Import Backup Memory and pick the converted save file 5. Reset the game +=== Why can't I find a mac binary? === +Maybe we haven't made it yet. There arent a lot of people willing to compile mac software. Just to be sure, go to https://sourceforge.net/project/showfiles.php?group_id=164579&package_id=186413 - * Step 3 is not always necessary, if you are smart, however, it will never hurt to do it. - -Why can't I find a mac binary? -Maybe we haven't made it yet. There arent a lot of people willing to compile mac software. Just to be sure, go to https://sourceforge.net/project/showfiles.php?group_id=164579&package_id=186413 - -Why does my mac binary say something about being unsupported? +=== Why does my mac binary say something about being unsupported? === You have probably downloaded the i386 version of desmume for MAC, and are running on the PPC platform (or the other way around). Please verify if you're running on Intel (i386) hardware, or on PPC (G4, G5) hardware, and download the appropriate binary. -Where can I report bugs? -In the official bug tracker. Feel free to post to the bug tracker as long as you are willing to take ownership of testing that bug and letting the developers know when it is resolved to your satisfaction. Just don't submit a bug report and run. You may also request features around the same location, too, but in the other trackers. +=== Where can I report bugs? === +In the [http://sourceforge.net/tracker/?group_id=164579&atid=832291 official bug tracker]. Feel free to post to the bug tracker as long as you are willing to take ownership of testing that bug and letting the developers know when it is resolved to your satisfaction. Just don't submit a bug report and run. You may also request features around the same location, too, but in the other trackers. -Can I attach files to bug reports I did not create myself ? +=== Can I attach files to bug reports I did not create myself ? === SourceForge likes for folks to only respond on items they submit. If you see a ticket that represents something you are encountering, SourceForge doesn't necessarily want you commenting on that. The reasoning for this given by SourceForge is that they feel it is best to open your own ticket, which helps appreciate the extent of issues in many cases. The authors of desmume may or may not agree with this point of view from SourceForge. -How do I get the latest svn code and build desmume myself? -Please check out the instructions related to your platform, over at Installing DeSmuME from source +=== How do I get the latest svn code and build desmume myself? === +Please check out the instructions related to your platform, over at [[Installing DeSmuME from source]] -Whats 'svn' ? -svn is a developers tool. It's used to let multiple developers work on the same codebase without conflicts. If youre an end-user, don't worry about it. And if you're a developer, see the question on how to get the latest svn code and build desmume yourself. See wikipedia for more info -What compilers are supported for building desmume from source ? +=== Whats 'svn' ? === +[http://subversion.tigris.org/ svn] is a developers tool. It's used to let multiple developers work on the same codebase without conflicts. If youre an end-user, don't worry about it. And if you're a developer, see the question on how to get the latest svn code and build desmume yourself. See [http://en.wikipedia.org/wiki/Subversion_(software) wikipedia] for more info - * At the moment, for Windows Microsoft Visual C++ 2005 and 2008 are the only supported compilers. Dev-c++ is not supported. Why won't you just download visual c++ express? - * For Linux, any recent version of GCC and toolchain should work. +=== What compilers are supported for building desmume from source ? === +* At the moment, for Windows Microsoft Visual C++ 2005 and 2008 are the only supported compilers. Dev-c++ is not supported. Why won't you just download visual c++ express? +* For Linux, any recent version of GCC and toolchain should work. -Im Compiling using MSVC Express On Windows, and I get the error : "ml.exe" not found. -ml.exe was not included in earlier downloads of MSVC++ 2008 Express Edition. Uninstall, redownload and install again. See http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=326875 for details. ml.exe shoud be located in the "Microsoft Visual Studio 9.0\VC\bin" directory. +=== Im Compiling using MSVC Express On Windows, and I get the error : "ml.exe" not found. === +ml.exe was not included in earlier downloads of MSVC++ 2008 Express Edition. Uninstall, redownload and install again. +See http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=326875 for details. ml.exe shoud be located in the "Microsoft Visual Studio 9.0\VC\bin" directory. -Im a developer, and would like to contribute to the codebase. What can I do ? +=== Im a developer, and would like to contribute to the codebase. What can I do ? === To start you off in the right direction, the best thing you can do is join the developer team on IRC and discuss your intentions with the developers. -Im not a developer, but would like to help out anyway. What can I do ? +=== Im not a developer, but would like to help out anyway. What can I do ? === The most helpful thing you can do is use desmume, learn its ins and outs, and learn how to compile svn builds. Then monitor it for regressions and report bugs. You can patrol the bug tracker for bugs which could use elucidation or which, based on your awareness of how the emulator is changing, might be fixed without us having specifically addressed the bug. Basically, be a super user. And hang out on irc. Also, adding to or perfecting the documentation in the wiki is useful. You could also watch for and answer questions placed on the desmume forum. -It is hard to zoom in on a widescreen display due to the weird aspect ratio of the DS. -In fact it is hard to zoom in on a 4:3 screen, too. Proposals involve tearing apart windows and floating them side by side or separately or something. This may happen one day, in the form of side by side windows. +=== What is this Lua stuff I see? === +It is sort of a macro language for interacting with the running game software. Here is an example of it working with an NES game in another emulator, and youtubing for "fceux lua" should suffice to explain it if you don't get the picture from this url: http://www.youtube.com/watch?v=1XNTjVScm_8 -Why doesn't my openGL 3d work in linux? +=== What is 'TAS' ? === +TAS lets you record the gameplay in TAS format, see http://tasvideos.org for details on TAS (tool-assisted speedruns). + +=== It is hard to zoom in on a widescreen display due to the weird aspect ratio of the DS. === +In fact it is hard to zoom in on a 4:3 screen, too. Proposals involve tearing apart windows and floating them side by side or separately or something. This may happen one day, in the form of side by side windows. + +=== Why doesn't my openGL 3d work in linux? === Blame nvidia and ati for putting out shoddy and/or closed source drivers. Then switch to software rasterizer. -Why doesn't my openGL 3d work in windows? +=== Why doesn't my openGL 3d work in windows? === You are probably using an ATI video card. ATI driver support of OpenGL is known to be poor. Get an nvidia. Do not argue with that, we are professional programmers and know what we're talking about. Or, switch to software rasterizer -Why doesn't a menu option or tool exist in my linux or mac build? -Because making portable tools and platform harnesses are not our cup of tea and so a developer puts a feature into whichever ports he cares about. This policy is never going to change, although some features might migrate to other platforms over time. Better check the manual. +=== Why doesn't a menu option or tool exist in my linux or mac build? === +Because making portable tools and platform harnesses are not our cup of tea and so a developer puts a feature into whichever ports he cares about. This policy is never going to change, although some features might migrate to other platforms over time. Better check the [http://wiki.desmume.org/index.php?title=Manual manual]. -Why does music sound bad sometimes? -Most DS music is sequenced music, loaded from the cart entirely when the level loads. This works fine. Your music that doesn't work is probably streaming music, which loads from the cart on the fly and goes straight to the speakers. This is much harder to emulate as it requires correct timing, which is not one of desmume's strengths right now. This may not be fixed for a while. +=== Why does music and FMV sound bad sometimes? === +Most DS music is sequenced music, loaded from the cart entirely when the level loads. This works fine. Your music that doesn't work is probably streaming music, which loads from the cart on the fly and goes straight to the speakers, and possibly decoded along the way. This includes FMVs. This is much harder to emulate as it requires correct timing, which is not one of desmume's strengths right now. This may not be fixed for a while. -Why doesn't my game boot or progress into the main game engine? +=== Why doesn't my game boot or progress into the main game engine? === Desmume is not perfect yet. Some games may fail due to wifi emulation. Apparently if you search the web correctly you can find ways to patch games to work better on emulators. Your mileage may vary. If it really doesn't boot up, you can submit a bug report for the game on the sourceforge bugtracker. -What hardware features are emulated? - * All known 2d graphics features are correct. Mosaics work but are imperfect. There may be small issues with colors as the correct color bit depths are not used at all points in the pipeline. +=== What hardware features are emulated? === +* All known 2d graphics features are correct. Mosaics work but are imperfect. There may be small issues with colors as the correct color bit depths are not used at all points in the pipeline. - * All 3d features are emulated, except for: tests, wireframes, edge marking, fog, and antialising. The opengl engine is near its limit and renders some things incorrectly. Eventually the software rasterizer (will support more features and be far more precise in the basic features. Both engines have trouble with some shadows, but software rasterizer is better. Software rasterizer has some noticeable texturing issues right now, especially in 2d games. Software rasterizer supports more correct lighting interpolation than opengl ever will (e.g. glitches at the edge of the screen while scrolling.) In software rasterizer, there are issues similar to 2d with incorrect bit depth being used in the pipeline. There are inaccurate edge conditions in each renderer; in opengl, textures tend to get overdrawn; in software rasterizer, edges of textures tend to be jittery. +* All 3d features are emulated, except for: tests, wireframes, edge marking, fog, and antialising. The opengl engine is near its limit and renders some things incorrectly. Eventually the software rasterizer (will support more features and be far more precise in the basic features. Both engines have trouble with some shadows, but software rasterizer is better. Software rasterizer has some noticeable texturing issues right now, especially in 2d games. Software rasterizer supports more correct lighting interpolation than opengl ever will (e.g. glitches at the edge of the screen while scrolling.) In software rasterizer, there are issues similar to 2d with incorrect bit depth being used in the pipeline. There are inaccurate edge conditions in each renderer; in opengl, textures tend to get overdrawn; in software rasterizer, edges of textures tend to be jittery. One last thing -- if buttons and labels and menus rendering on the 3d screen are obscured (for example, a button but no label is on it) then you may need to use the software rasterizer. Or you may need to use openGL instead. Each renderer has strengths and weaknesses, which is why both are provided. - * All sound features are emulated. The microphone support is new and the manual should be consulted, where you will find out, among other things, that it is only supported in windows right now. +* All sound features are emulated. The microphone support is new and the manual should be consulted, where you will find out, among other things, that it is only supported in windows right now. - * Wifi is not supported. It is currently under slow and incomplete development. Therefore, you may find this option missing, or simply 'greyed-out' for now. Also, since WIFI support does not work yet, don't ask any questions about it's functioning because it still is unfinished and does not work yet. +* Wifi is not supported. It is currently under slow and incomplete development. Therefore, you may find this option missing, or simply 'greyed-out' for now. Also, since WIFI support does not work yet, don't ask any questions about it's functioning because it still is unfinished and does not work yet. - * We are unaware of any outstanding issues in the core system hardware (cpu, dma, mmu) but there are certainly still some. The instruction and memory timings are quite incorrect; however, this seems not to hurt most softwares. - - * DLDI (does anybody know if this still works?) +* We are unaware of any outstanding issues in the core system hardware (cpu, dma, mmu) but there are certainly still some. The instruction and memory timings are quite incorrect; however, this seems not to hurt most softwares. +* DLDI (does anybody know if this still works?) Dynamically Linked Driver Interface, commonly known as DLDI, is a driver framework that allows NDS and GBA homebrew to easily read and write to any number of different devices, just by substituting a driver file. - * RTC (real-time clock) works; If it didnt, then the time in your games stays at 00:00:00, and your random number values always come up the same. +* RTC (real-time clock) works; If it didnt, then the time in your games stays at 00:00:00, and your random number values always come up the same. -Does the GDB stub still work? +=== Does the GDB stub still work? === It seems as if it works in 0.9.3, tested with the Insight GDB variant on windows with a recent devkitpro. This support has been compiled into the dev+ build. -How do I enable the GDB stub on the Windows port ? +=== How do I enable the GDB stub on the Windows port ? === Add #define GDB_STUB to src/windows/userconfig/userconfig.h which you have created according to the instructions in src/windows/defaultconfig/userconfig.h ; sorry for this confusing system, but that's how it is for now. -Where/what is IRC? -IRC is an on-line communication system. +=== Where/what is IRC? === +[http://en.wikipedia.org/wiki/IRC IRC] is an on-line communication system. data you need: - - * server: irc.freenode.net - * port: 6667 - * channel: #desmume +* server: irc.freenode.net +* port: 6667 +* channel: #desmume what to use: +* mIRC - windows +* ChatZilla - FireFox add-on +* xchat - X +* plenty other, see [http://en.wikipedia.org/wiki/Comparison_of_Internet_Relay_Chat_clients wikipedia] - * mIRC - windows - * ChatZilla - FireFox add-on - * xchat - X - * plenty other, see wikipedia - -Where is the manual? +=== Where is the manual? === A manual for desmume is over at http://wiki.desmume.org/index.php?title=Manual. It may not have the information that other entries in this FAQ promised that it would. -How do I enter 'cheat codes' in desmume ? -Action Replay and 'raw' or 'internal' cheats work as of 0.9.3. There are also cheat-finding facilities where you may manually search for and alter the memory positions which work to your advantage. There's an excellent article in the wiki on Using Cheats in DeSmuMe . +=== Where is release 0.9.3 ? === +Who cares? 0.9.4 is out now +Desmume 0.9.3 does not exist. It was sneaked out of our staging area. It has bugs, which is why we hadn't released it yet. So we decided not to release it at all. Any release claiming to be 0.9.3 wont be supported. -Why is the emulator slow? -Because nobody pays us to work on it full time and it runs fast enough for us to be happy. Well, almost. +=== How do I enter 'cheat codes' in desmume ? === +Action Replay and 'raw' or 'internal' cheats work as of 0.9.4. There are also cheat-finding facilities where you may manually search for and alter the memory positions which work to your advantage. There's an excellent article in the wiki on [[Using Cheats in DeSmuMe ]]. -0.9.3 May be a step backwards in some (or many) cases from 0.9.2 in terms of speed. The development between these versions focused on compatibility and bugfixes. Once we better understand how some things need to be emulated, then some speed can return. However, in order to mitigate some of this backsliding, we have introduced a few speed hacks which you may find helpful. +=== Why is the emulator slow? === +Because nobody pays us to work on it full time and it runs fast enough for us to be happy. Well, almost. - * The cheapest way to get 60fps is to buy the cart. - * If you are in Windows, make sure you have tried the SSE build which helps a little bit. - * If you are using someone else's unofficial "svn" build it probably is not fully optimized since we make our Windows releases using some profiler-guided optimization which helps by several FPS. For all I know they are also carriers of viruses, and lately they tend to crash on vista. - * If you can handle it, turn off the sound. - * Use frame skip. Even frameskipping 1 will help and many games will stay playable. Frameskipping was improved in 0.9.3 to get more bang for the buck, but beware that dual screen 3d games may not work well under frameskip. - * (0.9.3+) In the sound options, set interpolation to none which should help a little bit. - * (0.9.3+) Turn on the sound option "ADPCM Caching"; this is new and experimental, and will break some things, but it should offer a substantial speedup in some cases. - * (0.9.3+) There is now the option of disabling an entire screen. (Tools > View Layers > Main GPU, etc) Consider disabling a screen which is useless in the game you are playing. - * Try the software rasterizer. In many cases, especially games which make only light use of the 3d hardware, this will actually run faster, by as many as 10 FPS. But it might also run slower, again, by as many as 10 FPS. - * Buying a newer, faster computer is somewhat more expensive, but it has other side benefits. - * A faster CPU is more helpful than a bleeding edge graphics card. Desmume is more CPU intensive than it is GPU intensive. It just needs a graphics card that is glitch-free, and currently the nvidia cards have a better track record. A newer graphics card has a slim possibility of increasing speed. +0.9.4 May be a step backwards in some (or many) cases from 0.9.2 in terms of speed. The development between these versions focused on compatibility and bugfixes. Once we better understand how some things need to be emulated, then some speed can return. However, in order to mitigate some of this backsliding, we have introduced a few speed hacks which you may find helpful. -What does the number/percentage in the desmume title bar mean ? +* The cheapest way to get 60fps is to buy the cart. +* If you are in Windows, make sure you have tried the SSE build which helps a little bit. +* If you are using someone else's unofficial "svn" build it probably is not fully optimized since we make our Windows releases using some profiler-guided optimization which helps by several FPS. For all I know they are also carriers of viruses, and lately they tend to crash on vista. +* If you can handle it, turn off the sound. +* Use frame skip. Even frameskipping 1 will help and many games will stay playable. Frameskipping was improved in 0.9.3 to get more bang for the buck, but beware that dual screen 3d games may not work well under frameskip. +* (0.9.4+) In the sound options, set interpolation to none which should help a little bit. +* (0.9.4+) Turn on the sound option "ADPCM Caching"; this is new and experimental, and will break some things, but it should offer a substantial speedup in some cases. +* (0.9.4+) There is now the option of disabling an entire screen. (Tools > View Layers > Main GPU, etc) Consider disabling a screen which is useless in the game you are playing. +* Try the software rasterizer. In many cases, especially games which make only light use of the 3d hardware, this will actually run faster, by as many as 10 FPS. But it might also run slower, again, by as many as 10 FPS. +* Buying a newer, faster computer is somewhat more expensive, but it has other side benefits. +* A faster CPU is more helpful than a bleeding edge graphics card. Desmume is more CPU intensive than it is GPU intensive. It just needs a graphics card that is glitch-free, and currently the nvidia cards have a better track record. A newer graphics card has a slim possibility of increasing speed. - * For the windows port, the percentage is the emulated arm9 CPU load average. The CPU in an actual Nintendo DS is an ARM9 CPU. The percentage shows us how busy the emulated CPU is. This number isnt really for you. We really ought to just take it out. - * For the Linux GTK and Glade ports, it's frames per second (fps). +=== Why does the emulator take a million years to start up and/or devastate my system or unarchiver when I run it? === +This is a problem with the desmume 0.9.2 that some people impolitely distribute themselves. Redownload 0.9.2 from sourceforge.net or get a newer version. It isn't a virus or anything, it is a bug in the application that can just bring a system to its knees. It tries to allocate 1GB of virtual memory. This also crashes or freezes some virus scanners (I've seen it on AVG). -What's the difference between the the Windows 'desmume' and 'desmume_nosse' versions ? +=== What does the number/percentage in the desmume title bar mean ? === +* For the windows port, the percentage is the emulated arm9 CPU load average. The CPU in an actual Nintendo DS is an ARM9 CPU. The percentage shows us how busy the emulated CPU is. This number isnt really for you. We really ought to just take it out. +* For the Linux GTK and Glade ports, it's frames per second (fps). + +=== What's the difference between the the Windows 'desmume' and 'desmume_nosse' versions ? === desmume uses some SSE2 optimizations for 3D matrix calculations. If your CPU supports SSE2, better use this version. Otherwise use desmume_nosse. Any modern Intel CPU (AMD or intel) will support SSE2. -Does desmume make use of multiple CPU's or multiple cores ? +=== Does desmume make use of multiple CPU's or multiple cores ? === Currently, there are no multi core optimizations. Everything runs in a single thread. You benefit MUCH more from a single greater Ghz cpu than from multiple cores or from multiple CPU's. -What are the minimum hardware requirements for desmume ? +=== What are the minimum hardware requirements for desmume ? === From a purely technical viewpoint, there are no minimum requirements. However, for 'real-world' playable speeds, you would need at least the following : - * Windows OS: Windows XP or Vista - * Linux OS: Any recent Linux distribution with a 2.6 kernel. - * 2 GHz Processor - * 512 MB Available System Memory - * Available Hard Drive Space: A few MB for the emulator - * 128 MB 3D Video Card (Nvidia GeForce 6800 or better), ATI cards are not recommended. - * Optional: Sound Card, if you want sound support - * Optional: Microphone, if you wish to make use the Windows Microphone feature +* Windows OS: Windows XP or Vista +* Linux OS: Any recent Linux distribution with a 2.6 kernel. +* 2 GHz Processor +* 512 MB Available System Memory +* Available Hard Drive Space: A few MB for the emulator +* 128 MB 3D Video Card (Nvidia GeForce 6800 or better), ATI cards are not recommended. +* Optional: Sound Card, if you want sound support +* Optional: Microphone, if you wish to make use the Windows Microphone feature -What are the recommended hardware requirements for desmume ? +=== What are the recommended hardware requirements for desmume ? === From a purely technical viewpoint, there are no recommended requirements. However, for 'real-world' playable speeds, the following gives you good performance: - * Windows OS: Windows XP or Vista - * Linux OS: Any recent Linux distribution with a 2.6 kernel. - * 3 GHz Processor - * 1 GB Available System Memory - * Available Hard Drive Space: A few MB for desmume, 100MB or so for a bunch of savestates and savefiles. - * 512 MB 3D Video Card (Nvidia GeForce), ATI cards are not recommended. - * Sound Card. - * Microphone. +* Windows OS: Windows XP or Vista +* Linux OS: Any recent Linux distribution with a 2.6 kernel. +* 3 GHz Processor +* 1 GB Available System Memory +* Available Hard Drive Space: A few MB for desmume, 100MB or so for a bunch of savestates and savefiles. +* 512 MB 3D Video Card (Nvidia GeForce), ATI cards are not recommended. +* Sound Card. +* Microphone. In general, the more Ghz, the better. The faster memory, the better. Desmume currently won't benefit from multiple cores. Desmume currently is, unfortunately, slower than no$gba. -Does desmume support wifi ? +=== Does desmume support wifi ? === Wifi is not supported. It is currently under slow and incomplete development. Therefore, you may find this option missing, or simply 'greyed-out' for now. Also, since WIFI support does not work yet, don't ask any questions about it's functioning because it still is unfinished and does not work yet. Furthermore, current development activities focus mainly on the Windows build. -Why do I get an assert in wifi.cpp which keeps me from playing a game? +=== Why do I get an assert in wifi.cpp which keeps me from playing a game? === This was a glitch in 0.9.2 release. Why arent you using 0.9.3? -OK, then why does it make my firewall alert since 0.9.2 ? +=== OK, then why does it make my firewall alert since 0.9.2 ? === Your firewall is stupid, or winsock is stupid, (I am not sure which yet) for alerting just when winsock gets initialized. The emulator hasnt actually tried to connect to the internet yet. How could it? There isn't any wifi. All we are doing is some network initialization code. For those of you who are still not satisfied, then I will admit that there is actually some wifi code--but it doesnt actually do anything yet! Except alert your firewall. Sorry. Also, maybe that is actually a good, unobtrusive time for firewalls to alert. But I am not sorry for calling them stupid. They are hyperactive crybabies. -OK, so then why did my build come with winpcap.dll? Or why do I get crashes when I run desmume on vista which mumble something about winpcap? +=== OK, so then why did my build come with winpcap.dll? Or why do I get crashes when I run desmume on vista which mumble something about winpcap? === Because you are running an unofficial build, from dubious origins, made by unknown people. The desmume team cannot support builds it did not create itself. Therefore, you are advised to stop using unofficial builds, as you can expect no support from the desmume team or on the desmume forums. Only use builds you downloaded from the desmume website. -What is WFC / WIFI Connection -See the article Nintendo wifi config utility -Does desmume support the microphone ? +=== What is WFC / WIFI Connection === +See the article [[Nintendo wifi config utility]] +=== Does desmume support the microphone ? === Yes, but only on the Windows port. You do have to have an actual microphone attached to your PC, though. And perhaps somewhat confusing, the Linux ports do report 'Microphone successfully initialized' on startup of the emulator - but currently this is just a piece of stub (dummy) code used only to correctly start the emulator. In 0.9.2 the microphone in windows really only works for noise, but this was fixed in 0.9.3; it still hasn't been tested very well. -Where can I find technical details on the Nintendo DS and GBA ? +=== Where can I find technical details on the Nintendo DS and GBA ? === http://nocash.emubase.de/gbatek.htm -Does the 'GBA slot' option let me play GBA games ? -No. A 'real' DS can use the gba slot to play gba games, but desmume does not emulate this. But a 'real' DS can also use the gba slot to access gba roms and sram so that ds games can import savefiles, and that part is emulated by desmume. (please note that this is reportedly buggy for some games, including pokemon) If you are looking for a Game Boy Advance (GBA) emulator, perhaps you can try mednafen or visualboy advance. -What is DLDI ? +=== Does the 'GBA slot' option let me play GBA games ? === +No. A 'real' DS can use the gba slot to play gba games, but desmume does not emulate this. But a 'real' DS can also use the gba slot to access gba roms and sram so that ds games can import savefiles, and that part is emulated by desmume. (please note that this is reportedly buggy for some games, including pokemon) If you are looking for a Game Boy Advance (GBA) emulator, perhaps you can try mednafen or visualboy advance. -let me give you an overview on DLDI. You should know that there are many various flash cartridges for DS. They use different file allocation systems, different storage's, etc. They are used for launching homebrew. So to make one program run on all cards. You’d have to write support for each and every card so that it worked for everyone. But none needs support for other cards than their own. And then a genial solution was found. There was an universal IO unit made that’s just interface to IO operations. And compiled program does not know how to handle file system etc. And then user can append IO routines for his own card. “DLDI patch”. So, now when I have an M3 cart, I download rom, patch it with m3 DLDI patch, and it works on my cart. Say you had Supercard instead. You’d have to download very same rom and apply Supercart DLDI patch to it. DLDI patch is the same for all roms. So it’s easy for both developer and end user. -How can I post a savefile or avi capture on the desmume forum ? +=== How do I "Close the DS" ? === +We call this the 'lid' command or key. You can do so with the key BACKSPACE (you can change the mapping on the control configuration) +=== What is DLDI ? === +let me give you an overview on DLDI. You should know that there are many various flash cartridges for DS. They use different file allocation systems, different storage's, etc. They are used for launching homebrew. So to make one program run on all cards. You’d have to write support for each and every card so that it worked for everyone. But none needs support for other cards than their own. +And then a genial solution was found. There was an universal IO unit made that’s just interface to IO operations. And compiled program does not know how to handle file system etc. And then user can append IO routines for his own card. “DLDI patch”. So, now when I have an M3 cart, I download rom, patch it with m3 DLDI patch, and it works on my cart. Say you had Supercard instead. You’d have to download very same rom and apply Supercart DLDI patch to it. DLDI patch is the same for all roms. So it’s easy for both developer and end user. + +=== How can I post a savefile or avi capture on the desmume forum ? === After you created it, you can upload it to a free external service provider like MediaFire (http://www.mediafire.com/), and then put the provided links to the page in the message you post on the forum. -How can I post a large log or other text file on the desmume IRC chat room ? +=== How can I post a large log or other text file on the desmume IRC chat room ? === Make use of the external service provider 'pastebin' (http://pastebin.com/), and post the url to it on the IRC channel. -My display is incorrect or corrupted +=== My display is incorrect or corrupted === Try switching the 3D Renderer from opengl or SoftRasterizer, or vice versa, to see if that resolves the bug. In windows, the default hotkey to do this quickly is numpad minus. -My display has flickering graphics in a certain game -In the Windows port, you can choose 'Alternate Flush Mode' in the 'Config | 3D Settings' menu. This fixes some games with flickering graphics. -How do I easily capture the ASM code for troubleshooting purposes ? +=== My display has flickering graphics in a certain game === +In the Windows port, you can choose 'Alternate Flush Mode' in the 'Config | 3D Settings' menu. This fixes some games with flickering graphics. +=== How do I easily capture the ASM code for troubleshooting purposes ? === Savestate during the problem or just before your problem occurs, and #define WANTASMLISTING in armcpu.cpp. Recompile. Then redirect stdout to a file. I know it aint easy but its what we got for now. -How do I make pokemon save? + +A newer, and possibly better way, is to search for LOG_ARM9 in ndssystem.cpp and uncomment it. You will also need to trigger the condition for logging by setting dolog=true. Beware that this is very verbose, on the order of 100MBytes per frame. + +=== How do I make pokemon save? === Use 0.9.3 where this works correctly without you having to perform rituals beyond your capabilities or comprehension. -I got a gameplay related question -Please check a site like http://www.gamefaqs.com, and dont post gameplay related questions on the forum or IRC *unless* you believe there is a bug in the emulation of desmume. +=== I got a gameplay related question === +Please check a site like http://www.gamefaqs.com, and dont post gameplay related questions on the forum or IRC *unless* you believe there is a bug in the emulation of desmume. + +=== What are the origins of DeSmuME ? === -What are the origins of DeSmuME ? DeSmuME is a freeware emulator for the Nintendo DS originally created by YopYop156. The original website was http://yopyop156.ifrance.com Due to change in French laws regarding emulation YopYop decided to stop development of DeSmuME. However, he released the source under the GPL, and other programmers have picked it up and kept it under active development. -Yopyop said: - - It’s release under GPL. I have just removed the new 3D engine because it’s too much bugged. Hopefully it will be helpful for some of you. +Yopyop said: +:It’s release under GPL. I have just removed the new 3D engine because it’s too much bugged. Hopefully it will be helpful for some of you. The latest statement heard from yopyop was : - DeSmuMe project is over. - You may don’t know but there are a new law in France that could put me in big trouble. - With DeSmuMe, I have closed the doors of game company but I can not offer to pay for it. +:DeSmuMe project is over. +:You may don’t know but there are a new law in France that could put me in big trouble. +:With DeSmuMe, I have closed the doors of game company but I can not offer to pay for it. - The worst thing is that I have found the bad coded instructions. - For those how have download the sources you have to look in sbc, rsbc instructions the Carry flag updating is wrong. - Sorry for the home brew programmers. +:The worst thing is that I have found the bad coded instructions. +:For those how have download the sources you have to look in sbc, rsbc instructions the Carry flag updating is wrong. +:Sorry for the home brew programmers. - For the illegality the demonstration seemed to me convincing thus without proof clarify I prefer to stick to this decision. +:For the illegality the demonstration seemed to me convincing thus without proof clarify I prefer to stick to this decision. - It is also the fact that few people seem interested by the project. Put besides some people who sent demonstrations to me which did not go, I received only malls to wonder to make function such or such plays or to ask me why moved is in French . - Thus I will not do something of useless and illegal. +:It is also the fact that few people seem interested by the project. Put besides some people who sent demonstrations to me which did not go, I received only malls to wonder to make function such or such plays or to ask me why moved is in French . +:Thus I will not do something of useless and illegal. - For the site it would not obstruct me if there were not the bond on the left which does nothing but add to confusion on the goal of the project. +:For the site it would not obstruct me if there were not the bond on the left which does nothing but add to confusion on the goal of the project. - And for the sources it is the same problem as for the project. +:And for the sources it is the same problem as for the project. - good week end +:good week end - yopyop +:yopyop - edit the law relates to the royalties and the rights close, not? +:edit the law relates to the royalties and the rights close, not? -Retrieved from "http://wiki.desmume.org/index.php?title=Faq_093" -This page was last modified on 17 June 2009, at 04:30. +Retrieved from http://wiki.desmume.org/index.php?title=Faq +This page was last modified on 2 July 2009, at 02:52. diff --git a/desmume/TODO b/TODO similarity index 100% rename from desmume/TODO rename to TODO diff --git a/desmume/autogen.sh b/autogen.sh similarity index 100% rename from desmume/autogen.sh rename to autogen.sh diff --git a/desmume/autopackage/default.apspec.in b/autopackage/default.apspec.in similarity index 100% rename from desmume/autopackage/default.apspec.in rename to autopackage/default.apspec.in diff --git a/desmume/compile b/compile similarity index 100% rename from desmume/compile rename to compile diff --git a/desmume/configure.ac b/configure.ac similarity index 93% rename from desmume/configure.ac rename to configure.ac index a8625d0ec..4da9057ce 100644 --- a/desmume/configure.ac +++ b/configure.ac @@ -1,7 +1,7 @@ dnl --- Package name is first argument to AC_INIT dnl --- Release version is second argument to AC_INIT -AC_INIT(desmume, [svn]) +AC_INIT(desmume, [0.9.4]) dnl -- find target architecture for some os specific libraries AC_CANONICAL_TARGET @@ -130,26 +130,11 @@ AC_PROVIDE_IFELSE([PKG_PROG_PKG_CONFIG], [ dnl uninstalled glade ui dir AC_DEFINE_UNQUOTED(GLADEUI_UNINSTALLED_DIR,"`pwd`/src/gtk-glade/glade/",[path to glade ui dir]) AC_SUBST(GLADEUI_UNINSTALLED_DIR) - - # Need check for both lua and lua5.1 to run on debian, see mysql bug #29945 - PKG_CHECK_MODULES(LUA, - $LUAPC >= 5.1, - HAVE_LUA=yes, - HAVE_LUA=no) - PKG_CHECK_MODULES(LUA, - lua5.1 >= 5.1, - HAVE_LUA=yes, - HAVE_LUA=no) - AC_SUBST(LUA_CFLAGS) - AC_SUBST(LUA_LIBS) fi ],[ - echo "WARNING: pkg-config is not available therefore gtk, gtk-glade UIs and lua scripting are not available either." + echo "WARNING: pkg-config is not available therefore gtk and gtk-glade UIs are not available either." ]) -dnl -- force lua disabled -AM_CONDITIONAL([HAVE_LUA], [test "${HAVE_LUA}x" = "yes"]) - dnl - set conditional for glib, needed to avoid commandline.cpp compilation for cli frontend since it depends on glib AM_CONDITIONAL([HAVE_GLIB], [test "${FOUND_GLIB}" = "yes"]) diff --git a/desmume/src/PACKED_END.h b/desmume/src/PACKED_END.h deleted file mode 100644 index 4c0798dd0..000000000 --- a/desmume/src/PACKED_END.h +++ /dev/null @@ -1,3 +0,0 @@ -#ifndef __GNUC__ -#pragma pack(pop) -#endif diff --git a/desmume/src/fat.h b/desmume/src/fat.h deleted file mode 100644 index 6d2b7300b..000000000 --- a/desmume/src/fat.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - FAT.H - Mic, 2006 - Structures taken from Michael Chisholm's FAT library -*/ - -#ifndef __FAT_H__ -#define __FAT_H__ - -#include "types.h" -#include "PACKED.h" -#include "PACKED_END.h" - -#define ATTRIB_DIR 0x10 -#define ATTRIB_LFN 0x0F - -#define FILE_FREE 0xE5 -/* Name and extension maximum length */ -#define NAME_LEN 8 -#define EXT_LEN 3 - -// Boot Sector - must be packed -#if defined(_MSC_VER) || defined(__INTEL_COMPILER) -#define DIR_SEP "\\" -#else -#define DIR_SEP "/" -#endif - -#include "PACKED.h" -typedef struct -{ - u8 jmpBoot[3] __PACKED; - u8 OEMName[8] __PACKED; - // BIOS Parameter Block - u16 bytesPerSector __PACKED; - u8 sectorsPerCluster __PACKED; - u16 reservedSectors __PACKED; - u8 numFATs __PACKED; - u16 rootEntries __PACKED; - u16 numSectorsSmall __PACKED; - u8 mediaDesc __PACKED; - u16 sectorsPerFAT __PACKED; - u16 sectorsPerTrk __PACKED; - u16 numHeads __PACKED; - u32 numHiddenSectors __PACKED; - u32 numSectors __PACKED; - - struct - { - // Ext BIOS Parameter Block for FAT16 - u8 driveNumber __PACKED; - u8 reserved1 __PACKED; - u8 extBootSig __PACKED; - u32 volumeID __PACKED; - u8 volumeLabel[11] __PACKED; - u8 fileSysType[8] __PACKED; - // Bootcode - u8 bootCode[448] __PACKED; - u16 signature __PACKED; - } __PACKED fat16; - -} __PACKED BOOT_RECORD; -#include "PACKED_END.h" - -// Directory entry - must be packed -#include "PACKED.h" -typedef struct -{ - u8 name[NAME_LEN] __PACKED; - u8 ext[EXT_LEN] __PACKED; - u8 attrib __PACKED; - u8 reserved __PACKED; - u8 cTime_ms __PACKED; - u16 cTime __PACKED; - u16 cDate __PACKED; - u16 aDate __PACKED; - u16 startClusterHigh __PACKED; - u16 mTime __PACKED; - u16 mDate __PACKED; - u16 startCluster __PACKED; - u32 fileSize __PACKED; -} __PACKED DIR_ENT; -#include "PACKED_END.h" - -#endif // diff --git a/desmume/src/lua-engine.cpp b/desmume/src/lua-engine.cpp deleted file mode 100644 index 8ca6aab7e..000000000 --- a/desmume/src/lua-engine.cpp +++ /dev/null @@ -1,5182 +0,0 @@ -#include "lua-engine.h" -#include "movie.h" -#include -#include -#include -#include -#include -#include "zlib.h" -#include "NDSSystem.h" -#include "movie.h" -#ifdef WIN32 -#include "main.h" -#include "windows.h" -#endif - -// the emulator must provide these so that we can implement -// the various functions the user can call from their lua script -// (this interface with the emulator needs cleanup, I know) -// adapted from gens-rr, nitsuja + upthorn -extern int (*Update_Frame)(); -extern int (*Update_Frame_Fast)(); - -extern "C" { - #include "lua.h" - #include "lauxlib.h" - #include "lualib.h" - #include "lstate.h" -}; - -enum SpeedMode -{ - SPEEDMODE_NORMAL, - SPEEDMODE_NOTHROTTLE, - SPEEDMODE_TURBO, - SPEEDMODE_MAXIMUM, -}; - -struct LuaContextInfo { - lua_State* L; // the Lua state - bool started; // script has been started and hasn't yet been terminated, although it may not be currently running - bool running; // script is currently running code (either the main call to the script or the callbacks it registered) - bool returned; // main call to the script has returned (but it may still be active if it registered callbacks) - bool crashed; // true if script has errored out - bool restart; // if true, tells the script-running code to restart the script when the script stops - bool restartLater; // set to true when a still-running script is stopped so that RestartAllLuaScripts can know which scripts to restart - unsigned int worryCount; // counts up as the script executes, gets reset when the application is able to process messages, triggers a warning prompt if it gets too high - bool stopWorrying; // set to true if the user says to let the script run forever despite appearing to be frozen - bool panic; // if set to true, tells the script to terminate as soon as it can do so safely (used because directly calling lua_close() or luaL_error() is unsafe in some contexts) - bool ranExit; // used to prevent a registered exit callback from ever getting called more than once - bool guiFuncsNeedDeferring; // true whenever GUI drawing would be cleared by the next emulation update before it would be visible, and thus needs to be deferred until after the next emulation update - int numDeferredGUIFuncs; // number of deferred function calls accumulated, used to impose an arbitrary limit to avoid running out of memory - bool ranFrameAdvance; // false if gens.frameadvance() hasn't been called yet - int transparencyModifier; // values less than 255 will scale down the opacity of whatever the GUI renders, values greater than 255 will increase the opacity of anything transparent the GUI renders - SpeedMode speedMode; // determines how gens.frameadvance() acts - char panicMessage [72]; // a message to print if the script terminates due to panic being set - std::string lastFilename; // path to where the script last ran from so that restart can work (note: storing the script in memory instead would not be useful because we always want the most up-to-date script from file) - std::string nextFilename; // path to where the script should run from next, mainly used in case the restart flag is true - unsigned int dataSaveKey; // crc32 of the save data key, used to decide which script should get which data... by default (if no key is specified) it's calculated from the script filename - unsigned int dataLoadKey; // same as dataSaveKey but set through registerload instead of registersave if the two differ - bool dataSaveLoadKeySet; // false if the data save keys are unset or set to their default value - bool rerecordCountingDisabled; // true if this script has disabled rerecord counting for the savestates it loads - std::vector persistVars; // names of the global variables to persist, kept here so their associated values can be output when the script exits - LuaSaveData newDefaultData; // data about the default state of persisted global variables, which we save on script exit so we can detect when the default value has changed to make it easier to reset persisted variables - unsigned int numMemHooks; // number of registered memory functions (1 per hooked byte) - // callbacks into the lua window... these don't need to exist per context the way I'm using them, but whatever - void(*print)(int uid, const char* str); - void(*onstart)(int uid); - void(*onstop)(int uid, bool statusOK); -}; -std::map luaContextInfo; -std::map luaStateToUIDMap; -int g_numScriptsStarted = 0; -bool g_anyScriptsHighSpeed = false; -bool g_stopAllScriptsEnabled = true; - -#define USE_INFO_STACK -#ifdef USE_INFO_STACK - std::vector infoStack; - #define GetCurrentInfo() *infoStack.front() // should be faster but relies on infoStack correctly being updated to always have the current info in the first element -#else - std::map luaStateToContextMap; - #define GetCurrentInfo() *luaStateToContextMap[L] // should always work but might be slower -#endif - -//#define ASK_USER_ON_FREEZE // dialog on freeze is disabled now because it seems to be unnecessary, but this can be re-defined to enable it - - -static std::map s_cFuncInfoMap; - -// using this macro you can define a callable-from-Lua function -// while associating with it some information about its arguments. -// that information will show up if the user tries to print the function -// or otherwise convert it to a string. -// (for example, "writebyte=function(addr,value)" instead of "writebyte=function:0A403490") -// note that the user can always use addressof(func) if they want to retrieve the address. -#define DEFINE_LUA_FUNCTION(name, argstring) \ - static int name(lua_State* L); \ - static const char* name##_args = s_cFuncInfoMap[name] = argstring; \ - static int name(lua_State* L) - -#ifdef _MSC_VER - #define snprintf _snprintf - #define vscprintf _vscprintf -#else - #define stricmp strcasecmp - #define strnicmp strncasecmp - #define __forceinline __attribute__((always_inline)) -#endif - - -static const char* luaCallIDStrings [] = -{ - "CALL_BEFOREEMULATION", - "CALL_AFTEREMULATION", - "CALL_AFTEREMULATIONGUI", - "CALL_BEFOREEXIT", - "CALL_BEFORESAVE", - "CALL_AFTERLOAD", - "CALL_ONSTART", - - "CALL_HOTKEY_1", - "CALL_HOTKEY_2", - "CALL_HOTKEY_3", - "CALL_HOTKEY_4", - "CALL_HOTKEY_5", - "CALL_HOTKEY_6", - "CALL_HOTKEY_7", - "CALL_HOTKEY_8", - "CALL_HOTKEY_9", - "CALL_HOTKEY_10", - "CALL_HOTKEY_11", - "CALL_HOTKEY_12", - "CALL_HOTKEY_13", - "CALL_HOTKEY_14", - "CALL_HOTKEY_15", - "CALL_HOTKEY_16", -}; -static const int _makeSureWeHaveTheRightNumberOfStrings [sizeof(luaCallIDStrings)/sizeof(*luaCallIDStrings) == LUACALL_COUNT ? 1 : 0]; - -static const char* luaMemHookTypeStrings [] = -{ - "MEMHOOK_WRITE", - "MEMHOOK_READ", - "MEMHOOK_EXEC", - - "MEMHOOK_WRITE_SUB", - "MEMHOOK_READ_SUB", - "MEMHOOK_EXEC_SUB", -}; -static const int _makeSureWeHaveTheRightNumberOfStrings2 [sizeof(luaMemHookTypeStrings)/sizeof(*luaMemHookTypeStrings) == LUAMEMHOOK_COUNT ? 1 : 0]; - -void StopScriptIfFinished(int uid, bool justReturned = false); -void SetSaveKey(LuaContextInfo& info, const char* key); -void SetLoadKey(LuaContextInfo& info, const char* key); -void RefreshScriptStartedStatus(); -void RefreshScriptSpeedStatus(); - -static char* rawToCString(lua_State* L, int idx=0); -static const char* toCString(lua_State* L, int idx=0); - -static void CalculateMemHookRegions(LuaMemHookType hookType); - -static int memory_registerHook(lua_State* L, LuaMemHookType hookType, int defaultSize) -{ - // get first argument: address - unsigned int addr = luaL_checkinteger(L,1); - if((addr & ~0xFFFFFF) == ~0xFFFFFF) - addr &= 0xFFFFFF; - - // get optional second argument: size - int size = defaultSize; - int funcIdx = 2; - if(lua_isnumber(L,2)) - { - size = luaL_checkinteger(L,2); - if(size < 0) - { - size = -size; - addr -= size; - } - funcIdx++; - } - - // check last argument: callback function - bool clearing = lua_isnil(L,funcIdx); - if(!clearing) - luaL_checktype(L, funcIdx, LUA_TFUNCTION); - lua_settop(L,funcIdx); - - // get the address-to-callback table for this hook type of the current script - lua_getfield(L, LUA_REGISTRYINDEX, luaMemHookTypeStrings[hookType]); - - // count how many callback functions we'll be displacing - int numFuncsAfter = clearing ? 0 : size; - int numFuncsBefore = 0; - for(unsigned int i = addr; i != addr+size; i++) - { - lua_rawgeti(L, -1, i); - if(lua_isfunction(L, -1)) - numFuncsBefore++; - lua_pop(L,1); - } - - // put the callback function in the address slots - for(unsigned int i = addr; i != addr+size; i++) - { - lua_pushvalue(L, -2); - lua_rawseti(L, -2, i); - } - - // adjust the count of active hooks - LuaContextInfo& info = GetCurrentInfo(); - info.numMemHooks += numFuncsAfter - numFuncsBefore; - - // re-cache regions of hooked memory across all scripts - CalculateMemHookRegions(hookType); - - StopScriptIfFinished(luaStateToUIDMap[L]); - return 0; -} - -LuaMemHookType MatchHookTypeToCPU(lua_State* L, LuaMemHookType hookType) -{ - int cpuID = 0; - - int cpunameIndex = 0; - if(lua_type(L,2) == LUA_TSTRING) - cpunameIndex = 2; - else if(lua_type(L,3) == LUA_TSTRING) - cpunameIndex = 3; - - if(cpunameIndex) - { - const char* cpuName = lua_tostring(L, cpunameIndex); - if(!stricmp(cpuName, "sub") || !stricmp(cpuName, "s68k")) - cpuID = 1; - lua_remove(L, cpunameIndex); - } - - switch(cpuID) - { - case 0: // m68k: - return hookType; - - case 1: // s68k: - switch(hookType) - { - case LUAMEMHOOK_WRITE: return LUAMEMHOOK_WRITE_SUB; - case LUAMEMHOOK_READ: return LUAMEMHOOK_READ_SUB; - case LUAMEMHOOK_EXEC: return LUAMEMHOOK_EXEC_SUB; - } - } - return hookType; -} - -DEFINE_LUA_FUNCTION(memory_registerwrite, "address,[size=1,][cpuname=\"main\",]func") -{ - return memory_registerHook(L, MatchHookTypeToCPU(L,LUAMEMHOOK_WRITE), 1); -} -DEFINE_LUA_FUNCTION(memory_registerread, "address,[size=1,][cpuname=\"main\",]func") -{ - return memory_registerHook(L, MatchHookTypeToCPU(L,LUAMEMHOOK_READ), 1); -} -DEFINE_LUA_FUNCTION(memory_registerexec, "address,[size=2,][cpuname=\"main\",]func") -{ - return memory_registerHook(L, MatchHookTypeToCPU(L,LUAMEMHOOK_EXEC), 2); -} - - -DEFINE_LUA_FUNCTION(emu_registerbefore, "func") -{ - if (!lua_isnil(L,1)) - luaL_checktype(L, 1, LUA_TFUNCTION); - lua_settop(L,1); - lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEMULATION]); - lua_insert(L,1); - lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEMULATION]); - StopScriptIfFinished(luaStateToUIDMap[L]); - return 1; -} -DEFINE_LUA_FUNCTION(emu_registerafter, "func") -{ - if (!lua_isnil(L,1)) - luaL_checktype(L, 1, LUA_TFUNCTION); - lua_settop(L,1); - lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTEREMULATION]); - lua_insert(L,1); - lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTEREMULATION]); - StopScriptIfFinished(luaStateToUIDMap[L]); - return 1; -} -DEFINE_LUA_FUNCTION(emu_registerexit, "func") -{ - if (!lua_isnil(L,1)) - luaL_checktype(L, 1, LUA_TFUNCTION); - lua_settop(L,1); - lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEXIT]); - lua_insert(L,1); - lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEXIT]); - StopScriptIfFinished(luaStateToUIDMap[L]); - return 1; -}/* -DEFINE_LUA_FUNCTION(emu_registerstart, "func") -{ - if (!lua_isnil(L,1)) - luaL_checktype(L, 1, LUA_TFUNCTION); - lua_settop(L,1); - lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_ONSTART]); - lua_insert(L,1); - lua_pushvalue(L,-1); // copy the function so we can also call it - lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_ONSTART]); - if (!lua_isnil(L,-1) && ((Genesis_Started)||(SegaCD_Started)||(_32X_Started))) - lua_call(L,0,0); // call the function now since the game has already started and this start function hasn't been called yet - StopScriptIfFinished(luaStateToUIDMap[L]); - return 1; -}*/ -DEFINE_LUA_FUNCTION(gui_register, "func") -{ - if (!lua_isnil(L,1)) - luaL_checktype(L, 1, LUA_TFUNCTION); - lua_settop(L,1); - lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTEREMULATIONGUI]); - lua_insert(L,1); - lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTEREMULATIONGUI]); - StopScriptIfFinished(luaStateToUIDMap[L]); - return 1; -} -DEFINE_LUA_FUNCTION(state_registersave, "func[,savekey]") -{ - if (!lua_isnil(L,1)) - luaL_checktype(L, 1, LUA_TFUNCTION); - if (!lua_isnoneornil(L,2)) - SetSaveKey(GetCurrentInfo(), rawToCString(L,2)); - lua_settop(L,1); - lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFORESAVE]); - lua_insert(L,1); - lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFORESAVE]); - StopScriptIfFinished(luaStateToUIDMap[L]); - return 1; -} -DEFINE_LUA_FUNCTION(state_registerload, "func[,loadkey]") -{ - if (!lua_isnil(L,1)) - luaL_checktype(L, 1, LUA_TFUNCTION); - if (!lua_isnoneornil(L,2)) - SetLoadKey(GetCurrentInfo(), rawToCString(L,2)); - lua_settop(L,1); - lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTERLOAD]); - lua_insert(L,1); - lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTERLOAD]); - StopScriptIfFinished(luaStateToUIDMap[L]); - return 1; -} - -DEFINE_LUA_FUNCTION(input_registerhotkey, "keynum,func") -{ - int hotkeyNumber = luaL_checkinteger(L,1); - if(hotkeyNumber < 1 || hotkeyNumber > 16) - { - luaL_error(L, "input.registerhotkey(n,func) requires 1 <= n <= 16, but got n = %d.", hotkeyNumber); - return 0; - } - else - { - const char* key = luaCallIDStrings[LUACALL_SCRIPT_HOTKEY_1 + hotkeyNumber-1]; - lua_getfield(L, LUA_REGISTRYINDEX, key); - lua_replace(L,1); - if (!lua_isnil(L,2)) - luaL_checktype(L, 2, LUA_TFUNCTION); - lua_settop(L,2); - lua_setfield(L, LUA_REGISTRYINDEX, key); - StopScriptIfFinished(luaStateToUIDMap[L]); - return 1; - } -} - -static int doPopup(lua_State* L, const char* deftype, const char* deficon) -{ - const char* str = toCString(L,1); - const char* type = lua_type(L,2) == LUA_TSTRING ? lua_tostring(L,2) : deftype; - const char* icon = lua_type(L,3) == LUA_TSTRING ? lua_tostring(L,3) : deficon; - - int itype = -1, iters = 0; - while(itype == -1 && iters++ < 2) - { - if(!stricmp(type, "ok")) itype = 0; - else if(!stricmp(type, "yesno")) itype = 1; - else if(!stricmp(type, "yesnocancel")) itype = 2; - else if(!stricmp(type, "okcancel")) itype = 3; - else if(!stricmp(type, "abortretryignore")) itype = 4; - else type = deftype; - } - assert(itype >= 0 && itype <= 4); - if(!(itype >= 0 && itype <= 4)) itype = 0; - - int iicon = -1; iters = 0; - while(iicon == -1 && iters++ < 2) - { - if(!stricmp(icon, "message") || !stricmp(icon, "notice")) iicon = 0; - else if(!stricmp(icon, "question")) iicon = 1; - else if(!stricmp(icon, "warning")) iicon = 2; - else if(!stricmp(icon, "error")) iicon = 3; - else icon = deficon; - } - assert(iicon >= 0 && iicon <= 3); - if(!(iicon >= 0 && iicon <= 3)) iicon = 0; - - static const char * const titles [] = {"Notice", "Question", "Warning", "Error"}; - const char* answer = "ok"; -#ifdef _WIN32 - static const int etypes [] = {MB_OK, MB_YESNO, MB_YESNOCANCEL, MB_OKCANCEL, MB_ABORTRETRYIGNORE}; - static const int eicons [] = {MB_ICONINFORMATION, MB_ICONQUESTION, MB_ICONWARNING, MB_ICONERROR}; -// DialogsOpen++; - int uid = luaStateToUIDMap[L]; - EnableWindow(MainWindow->getHWnd(), false); -// if (Full_Screen) -// { -// while (ShowCursor(false) >= 0); -// while (ShowCursor(true) < 0); -// } - int ianswer = MessageBox((HWND)uid, str, titles[iicon], etypes[itype] | eicons[iicon]); - EnableWindow(MainWindow->getHWnd(), true); -// DialogsOpen--; - switch(ianswer) - { - case IDOK: answer = "ok"; break; - case IDCANCEL: answer = "cancel"; break; - case IDABORT: answer = "abort"; break; - case IDRETRY: answer = "retry"; break; - case IDIGNORE: answer = "ignore"; break; - case IDYES: answer = "yes"; break; - case IDNO: answer = "no"; break; - } -#else - // NYI (assume first answer for now) - switch(itype) - { - case 0: case 3: answer = "ok"; break; - case 1: case 2: answer = "yes"; break; - case 4: answer = "abort"; break; - } -#endif - - lua_pushstring(L, answer); - return 1; -} - -// string gui.popup(string message, string type = "ok", string icon = "message") -// string input.popup(string message, string type = "yesno", string icon = "question") -DEFINE_LUA_FUNCTION(gui_popup, "message[,type=\"ok\"[,icon=\"message\"]]") -{ - return doPopup(L, "ok", "message"); -} -DEFINE_LUA_FUNCTION(input_popup, "message[,type=\"yesno\"[,icon=\"question\"]]") -{ - return doPopup(L, "yesno", "question"); -} - -static const char* FilenameFromPath(const char* path) -{ - const char* slash1 = strrchr(path, '\\'); - const char* slash2 = strrchr(path, '/'); - if(slash1) slash1++; - if(slash2) slash2++; - const char* rv = path; - rv = std::max(rv, slash1); - rv = std::max(rv, slash2); - if(!rv) rv = ""; - return rv; -} - - -static void toCStringConverter(lua_State* L, int i, char*& ptr, int& remaining); - -// compare the contents of two items on the Lua stack to determine if they differ -// only works for relatively simple, saveable items (numbers, strings, bools, nil, and possibly-nested tables of those, up to a certain max length) -// not the best implementation, but good enough for what it's currently used for -static bool luaValueContentsDiffer(lua_State* L, int idx1, int idx2) -{ - static const int maxLen = 8192; - static char str1[maxLen]; - static char str2[maxLen]; - str1[0] = 0; - str2[0] = 0; - char* ptr1 = str1; - char* ptr2 = str2; - int remaining1 = maxLen; - int remaining2 = maxLen; - toCStringConverter(L, idx1, ptr1, remaining1); - toCStringConverter(L, idx2, ptr2, remaining2); - return (remaining1 != remaining2) || (strcmp(str1,str2) != 0); -} - - -// fills output with the path -// also returns a pointer to the first character in the filename (non-directory) part of the path -static char* ConstructScriptSaveDataPath(char* output, int bufferSize, LuaContextInfo& info) -{ -// Get_State_File_Name(output); TODO - char* slash1 = strrchr(output, '\\'); - char* slash2 = strrchr(output, '/'); - if(slash1) slash1[1] = '\0'; - if(slash2) slash2[1] = '\0'; - char* rv = output + strlen(output); - strncat(output, "u.", bufferSize-(strlen(output)+1)); - if(!info.dataSaveLoadKeySet) - strncat(output, FilenameFromPath(info.lastFilename.c_str()), bufferSize-(strlen(output)+1)); - else - snprintf(output+strlen(output), bufferSize-(strlen(output)+1), "%X", info.dataSaveKey); - strncat(output, ".luasav", bufferSize-(strlen(output)+1)); - return rv; -} - -// gens.persistglobalvariables({ -// variable1 = defaultvalue1, -// variable2 = defaultvalue2, -// etc -// }) -// takes a table with variable names as the keys and default values as the values, -// and defines each of those variables names as a global variable, -// setting them equal to the values they had the last time the script exited, -// or (if that isn't available) setting them equal to the provided default values. -// as a special case, if you want the default value for a variable to be nil, -// then put the variable name alone in quotes as an entry in the table without saying "= nil". -// this special case is because tables in lua don't store nil valued entries. -// also, if you change the default value that will reset the variable to the new default. -DEFINE_LUA_FUNCTION(emu_persistglobalvariables, "variabletable") -{ - int uid = luaStateToUIDMap[L]; - LuaContextInfo& info = GetCurrentInfo(); - - // construct a path we can load the persistent variables from - char path [1024] = {0}; - char* pathTypeChrPtr = ConstructScriptSaveDataPath(path, 1024, info); - - // load the previously-saved final variable values from file - LuaSaveData exitData; - { - *pathTypeChrPtr = 'e'; - FILE* persistFile = fopen(path, "rb"); - if(persistFile) - { - exitData.ImportRecords(persistFile); - fclose(persistFile); - } - } - - // load the previously-saved default variable values from file - LuaSaveData defaultData; - { - *pathTypeChrPtr = 'd'; - FILE* defaultsFile = fopen(path, "rb"); - if(defaultsFile) - { - defaultData.ImportRecords(defaultsFile); - fclose(defaultsFile); - } - } - - // loop through the passed-in variables, - // exposing a global variable to the script for each one - // while also keeping a record of their names - // so we can save them (to the persistFile) later when the script exits - int numTables = lua_gettop(L); - for(int i = 1; i <= numTables; i++) - { - luaL_checktype(L, i, LUA_TTABLE); - - lua_pushnil(L); // before first key - int keyIndex = lua_gettop(L); - int valueIndex = keyIndex + 1; - while(lua_next(L, i)) - { - int keyType = lua_type(L, keyIndex); - int valueType = lua_type(L, valueIndex); - if(keyType == LUA_TSTRING && valueType <= LUA_TTABLE && valueType != LUA_TLIGHTUSERDATA) - { - // variablename = defaultvalue, - - // duplicate the key first because lua_next() needs to eat that - lua_pushvalue(L, keyIndex); - lua_insert(L, keyIndex); - } - else if(keyType == LUA_TNUMBER && valueType == LUA_TSTRING) - { - // "variablename", - // or [index] = "variablename", - - // defaultvalue is assumed to be nil - lua_pushnil(L); - } - else - { - luaL_error(L, "'%s' = '%s' entries are not allowed in the table passed to gens.persistglobalvariables()", lua_typename(L,keyType), lua_typename(L,valueType)); - } - - int varNameIndex = valueIndex; - int defaultIndex = valueIndex+1; - - // keep track of the variable name for later - const char* varName = lua_tostring(L, varNameIndex); - info.persistVars.push_back(varName); - unsigned int varNameCRC = crc32(0, (const unsigned char*)varName, strlen(varName)); - info.newDefaultData.SaveRecordPartial(uid, varNameCRC, defaultIndex); - - // load the previous default value for this variable if it exists. - // if the new default is different than the old one, - // assume the user wants to set the value to the new default value - // instead of the previously-saved exit value. - bool attemptPersist = true; - defaultData.LoadRecord(uid, varNameCRC, 1); - lua_pushnil(L); - if(luaValueContentsDiffer(L, defaultIndex, defaultIndex+1)) - attemptPersist = false; - lua_settop(L, defaultIndex); - - if(attemptPersist) - { - // load the previous saved value for this variable if it exists - exitData.LoadRecord(uid, varNameCRC, 1); - if(lua_gettop(L) > defaultIndex) - lua_remove(L, defaultIndex); // replace value with loaded record - lua_settop(L, defaultIndex); - } - - // set the global variable - lua_settable(L, LUA_GLOBALSINDEX); - - assert(lua_gettop(L) == keyIndex); - } - } - - return 0; -} - -static const char* deferredGUIIDString = "lazygui"; - -// store the most recent C function call from Lua (and all its arguments) -// for later evaluation -void DeferFunctionCall(lua_State* L, const char* idstring) -{ - // there might be a cleaner way of doing this using lua_pushcclosure and lua_getref - - int num = lua_gettop(L); - - // get the C function pointer - //lua_CFunction cf = lua_tocfunction(L, -(num+1)); - lua_CFunction cf = (L->ci->func)->value.gc->cl.c.f; - assert(cf); - lua_pushcfunction(L,cf); - - // make a list of the function and its arguments (and also pop those arguments from the stack) - lua_createtable(L, num+1, 0); - lua_insert(L, 1); - for(int n = num+1; n > 0; n--) - lua_rawseti(L, 1, n); - - // put the list into a global array - lua_getfield(L, LUA_REGISTRYINDEX, idstring); - lua_insert(L, 1); - int curSize = lua_objlen(L, 1); - lua_rawseti(L, 1, curSize+1); - - // clean the stack - lua_settop(L, 0); -} -void CallDeferredFunctions(lua_State* L, const char* idstring) -{ - lua_settop(L, 0); - lua_getfield(L, LUA_REGISTRYINDEX, idstring); - int numCalls = lua_objlen(L, 1); - for(int i = 1; i <= numCalls; i++) - { - lua_rawgeti(L, 1, i); // get the function+arguments list - int listSize = lua_objlen(L, 2); - - // push the arguments and the function - for(int j = 1; j <= listSize; j++) - lua_rawgeti(L, 2, j); - - // get and pop the function - lua_CFunction cf = lua_tocfunction(L, -1); - lua_pop(L, 1); - - // shift first argument to slot 1 and call the function - lua_remove(L, 2); - lua_remove(L, 1); - cf(L); - - // prepare for next iteration - lua_settop(L, 0); - lua_getfield(L, LUA_REGISTRYINDEX, idstring); - } - - // clear the list of deferred functions - lua_newtable(L); - lua_setfield(L, LUA_REGISTRYINDEX, idstring); - LuaContextInfo& info = GetCurrentInfo(); - info.numDeferredGUIFuncs = 0; - - // clean the stack - lua_settop(L, 0); -} - -#define MAX_DEFERRED_COUNT 16384 - -bool DeferGUIFuncIfNeeded(lua_State* L) -{ - LuaContextInfo& info = GetCurrentInfo(); - if(info.speedMode == SPEEDMODE_MAXIMUM) - { - // if the mode is "maximum" then discard all GUI function calls - // and pretend it was because we deferred them - return true; - } - if(info.guiFuncsNeedDeferring) - { - if(info.numDeferredGUIFuncs < MAX_DEFERRED_COUNT) - { - // defer whatever function called this one until later - DeferFunctionCall(L, deferredGUIIDString); - info.numDeferredGUIFuncs++; - } - else - { - // too many deferred functions on the same frame - // silently discard the rest - } - return true; - } - - // ok to run the function right now - return false; -} - -void worry(lua_State* L, int intensity) -{ - LuaContextInfo& info = GetCurrentInfo(); - info.worryCount += intensity; -} - -static inline bool isalphaorunderscore(char c) -{ - return isalpha(c) || c == '_'; -} - -static std::vector s_tableAddressStack; // prevents infinite recursion of a table within a table (when cycle is found, print something like table:parent) -static std::vector s_metacallStack; // prevents infinite recursion if something's __tostring returns another table that contains that something (when cycle is found, print the inner result without using __tostring) - -#define APPENDPRINT { int _n = snprintf(ptr, remaining, -#define END ); if(_n >= 0) { ptr += _n; remaining -= _n; } else { remaining = 0; } } -static void toCStringConverter(lua_State* L, int i, char*& ptr, int& remaining) -{ - if(remaining <= 0) - return; - - const char* str = ptr; // for debugging - - // if there is a __tostring metamethod then call it - int usedMeta = luaL_callmeta(L, i, "__tostring"); - if(usedMeta) - { - std::vector::const_iterator foundCycleIter = std::find(s_metacallStack.begin(), s_metacallStack.end(), lua_topointer(L,i)); - if(foundCycleIter != s_metacallStack.end()) - { - lua_pop(L, 1); - usedMeta = false; - } - else - { - s_metacallStack.push_back(lua_topointer(L,i)); - i = lua_gettop(L); - } - } - - switch(lua_type(L, i)) - { - case LUA_TNONE: break; - case LUA_TNIL: APPENDPRINT "nil" END break; - case LUA_TBOOLEAN: APPENDPRINT lua_toboolean(L,i) ? "true" : "false" END break; - case LUA_TSTRING: APPENDPRINT "%s",lua_tostring(L,i) END break; - case LUA_TNUMBER: APPENDPRINT "%.12Lg",lua_tonumber(L,i) END break; - case LUA_TFUNCTION: - if((L->base + i-1)->value.gc->cl.c.isC) - { - lua_CFunction func = lua_tocfunction(L, i); - std::map::iterator iter = s_cFuncInfoMap.find(func); - if(iter == s_cFuncInfoMap.end()) - goto defcase; - APPENDPRINT "function(%s)", iter->second END - } - else - { - APPENDPRINT "function(" END - Proto* p = (L->base + i-1)->value.gc->cl.l.p; - int numParams = p->numparams + (p->is_vararg?1:0); - for (int n=0; nnumparams; n++) - { - APPENDPRINT "%s", getstr(p->locvars[n].varname) END - if(n != numParams-1) - APPENDPRINT "," END - } - if(p->is_vararg) - APPENDPRINT "..." END - APPENDPRINT ")" END - } - break; -defcase:default: APPENDPRINT "%s:%p",luaL_typename(L,i),lua_topointer(L,i) END break; - case LUA_TTABLE: - { - // first make sure there's enough stack space - if(!lua_checkstack(L, 4)) - { - // note that even if lua_checkstack never returns false, - // that doesn't mean we didn't need to call it, - // because calling it retrieves stack space past LUA_MINSTACK - goto defcase; - } - - std::vector::const_iterator foundCycleIter = std::find(s_tableAddressStack.begin(), s_tableAddressStack.end(), lua_topointer(L,i)); - if(foundCycleIter != s_tableAddressStack.end()) - { - int parentNum = s_tableAddressStack.end() - foundCycleIter; - if(parentNum > 1) - APPENDPRINT "%s:parent^%d",luaL_typename(L,i),parentNum END - else - APPENDPRINT "%s:parent",luaL_typename(L,i) END - } - else - { - s_tableAddressStack.push_back(lua_topointer(L,i)); - struct Scope { ~Scope(){ s_tableAddressStack.pop_back(); } } scope; - - APPENDPRINT "{" END - - lua_pushnil(L); // first key - int keyIndex = lua_gettop(L); - int valueIndex = keyIndex + 1; - bool first = true; - bool skipKey = true; // true if we're still in the "array part" of the table - lua_Number arrayIndex = (lua_Number)0; - while(lua_next(L, i)) - { - if(first) - first = false; - else - APPENDPRINT ", " END - if(skipKey) - { - arrayIndex += (lua_Number)1; - bool keyIsNumber = (lua_type(L, keyIndex) == LUA_TNUMBER); - skipKey = keyIsNumber && (lua_tonumber(L, keyIndex) == arrayIndex); - } - if(!skipKey) - { - bool keyIsString = (lua_type(L, keyIndex) == LUA_TSTRING); - bool invalidLuaIdentifier = (!keyIsString || !isalphaorunderscore(*lua_tostring(L, keyIndex))); - if(invalidLuaIdentifier) - if(keyIsString) - APPENDPRINT "['" END - else - APPENDPRINT "[" END - - toCStringConverter(L, keyIndex, ptr, remaining); // key - - if(invalidLuaIdentifier) - if(keyIsString) - APPENDPRINT "']=" END - else - APPENDPRINT "]=" END - else - APPENDPRINT "=" END - } - - bool valueIsString = (lua_type(L, valueIndex) == LUA_TSTRING); - if(valueIsString) - APPENDPRINT "'" END - - toCStringConverter(L, valueIndex, ptr, remaining); // value - - if(valueIsString) - APPENDPRINT "'" END - - lua_pop(L, 1); - - if(remaining <= 0) - { - lua_settop(L, keyIndex-1); // stack might not be clean yet if we're breaking early - break; - } - } - APPENDPRINT "}" END - } - } break; - } - - if(usedMeta) - { - s_metacallStack.pop_back(); - lua_pop(L, 1); - } -} - -static const int s_tempStrMaxLen = 64 * 1024; -static char s_tempStr [s_tempStrMaxLen]; - -static char* rawToCString(lua_State* L, int idx) -{ - int a = idx>0 ? idx : 1; - int n = idx>0 ? idx : lua_gettop(L); - - char* ptr = s_tempStr; - *ptr = 0; - - int remaining = s_tempStrMaxLen; - for(int i = a; i <= n; i++) - { - toCStringConverter(L, i, ptr, remaining); - if(i != n) - APPENDPRINT " " END - } - - if(remaining < 3) - { - while(remaining < 6) - remaining++, ptr--; - APPENDPRINT "..." END - } - APPENDPRINT "\r\n" END - // the trailing newline is so print() can avoid having to do wasteful things to print its newline - // (string copying would be wasteful and calling info.print() twice can be extremely slow) - // at the cost of functions that don't want the newline needing to trim off the last two characters - // (which is a very fast operation and thus acceptable in this case) - - return s_tempStr; -} -#undef APPENDPRINT -#undef END - - -// replacement for luaB_tostring() that is able to show the contents of tables (and formats numbers better, and show function prototypes) -// can be called directly from lua via tostring(), assuming tostring hasn't been reassigned -DEFINE_LUA_FUNCTION(tostring, "...") -{ - char* str = rawToCString(L); - str[strlen(str)-2] = 0; // hack: trim off the \r\n (which is there to simplify the print function's task) - lua_pushstring(L, str); - return 1; -} - -// like rawToCString, but will check if the global Lua function tostring() -// has been replaced with a custom function, and call that instead if so -static const char* toCString(lua_State* L, int idx) -{ - int a = idx>0 ? idx : 1; - int n = idx>0 ? idx : lua_gettop(L); - lua_getglobal(L, "tostring"); - lua_CFunction cf = lua_tocfunction(L,-1); - if(cf == tostring) // optimization: if using our own C tostring function, we can bypass the call through Lua and all the string object allocation that would entail - { - lua_pop(L,1); - return rawToCString(L, idx); - } - else // if the user overrided the tostring function, we have to actually call it and store the temporarily allocated string it returns - { - lua_pushstring(L, ""); - for (int i=a; i<=n; i++) { - lua_pushvalue(L, -2); // function to be called - lua_pushvalue(L, i); // value to print - lua_call(L, 1, 1); - if(lua_tostring(L, -1) == NULL) - luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print")); - lua_pushstring(L, (iUSR_InfoMessage(str); - return 0; -} - -// provides an easy way to copy a table from Lua -// (simple assignment only makes an alias, but sometimes an independent table is desired) -// currently this function only performs a shallow copy, -// but I think it should be changed to do a deep copy (possibly of configurable depth?) -// that maintains the internal table reference structure -DEFINE_LUA_FUNCTION(copytable, "origtable") -{ - int origIndex = 1; // we only care about the first argument - int origType = lua_type(L, origIndex); - if(origType == LUA_TNIL) - { - lua_pushnil(L); - return 1; - } - if(origType != LUA_TTABLE) - { - luaL_typerror(L, 1, lua_typename(L, LUA_TTABLE)); - lua_pushnil(L); - return 1; - } - - lua_createtable(L, lua_objlen(L,1), 0); - int copyIndex = lua_gettop(L); - - lua_pushnil(L); // first key - int keyIndex = lua_gettop(L); - int valueIndex = keyIndex + 1; - - while(lua_next(L, origIndex)) - { - lua_pushvalue(L, keyIndex); - lua_pushvalue(L, valueIndex); - lua_rawset(L, copyIndex); // copytable[key] = value - lua_pop(L, 1); - } - - // copy the reference to the metatable as well, if any - if(lua_getmetatable(L, origIndex)) - lua_setmetatable(L, copyIndex); - - return 1; // return the new table -} - -// because print traditionally shows the address of tables, -// and the print function I provide instead shows the contents of tables, -// I also provide this function -// (otherwise there would be no way to see a table's address, AFAICT) -DEFINE_LUA_FUNCTION(addressof, "table_or_function") -{ - const void* ptr = lua_topointer(L,-1); - lua_pushinteger(L, (lua_Integer)ptr); - return 1; -} - -DEFINE_LUA_FUNCTION(bitand, "...[integers]") -{ - int rv = ~0; - int numArgs = lua_gettop(L); - for(int i = 1; i <= numArgs; i++) - rv &= luaL_checkinteger(L,i); - lua_settop(L,0); - lua_pushinteger(L,rv); - return 1; -} -DEFINE_LUA_FUNCTION(bitor, "...[integers]") -{ - int rv = 0; - int numArgs = lua_gettop(L); - for(int i = 1; i <= numArgs; i++) - rv |= luaL_checkinteger(L,i); - lua_settop(L,0); - lua_pushinteger(L,rv); - return 1; -} -DEFINE_LUA_FUNCTION(bitxor, "...[integers]") -{ - int rv = 0; - int numArgs = lua_gettop(L); - for(int i = 1; i <= numArgs; i++) - rv ^= luaL_checkinteger(L,i); - lua_settop(L,0); - lua_pushinteger(L,rv); - return 1; -} -DEFINE_LUA_FUNCTION(bitshift, "num,shift") -{ - int num = luaL_checkinteger(L,1); - int shift = luaL_checkinteger(L,2); - if(shift < 0) - num <<= -shift; - else - num >>= shift; - lua_settop(L,0); - lua_pushinteger(L,num); - return 1; -} -DEFINE_LUA_FUNCTION(bitbit, "whichbit") -{ - int rv = 0; - int numArgs = lua_gettop(L); - for(int i = 1; i <= numArgs; i++) - rv |= (1 << luaL_checkinteger(L,i)); - lua_settop(L,0); - lua_pushinteger(L,rv); - return 1; -} - -//int gens_wait(lua_State* L); - -void indicateBusy(lua_State* L, bool busy) -{ - // disabled because there have been complaints about this message being useless spam. - // the script window's title changing should be sufficient, I guess. -/* if(busy) - { - const char* fmt = "script became busy (frozen?)"; - va_list argp; - va_start(argp, fmt); - luaL_where(L, 0); - lua_pushvfstring(L, fmt, argp); - va_end(argp); - lua_concat(L, 2); - LuaContextInfo& info = GetCurrentInfo(); - int uid = luaStateToUIDMap[L]; - if(info.print) - { - info.print(uid, lua_tostring(L,-1)); - info.print(uid, "\r\n"); - } - else - { - fprintf(stderr, "%s\n", lua_tostring(L,-1)); - } - lua_pop(L, 1); - } -*/ -#ifdef _WIN32 - int uid = luaStateToUIDMap[L]; - HWND hDlg = (HWND)uid; - char str [1024]; - GetWindowText(hDlg, str, 1000); - char* extra = strchr(str, '<'); - if(busy) - { - if(!extra) - extra = str + strlen(str), *extra++ = ' '; - strcpy(extra, ""); - } - else - { - if(extra) - extra[-1] = 0; - } - SetWindowText(hDlg, str); -#endif -} - -#define HOOKCOUNT 4096 -#define MAX_WORRY_COUNT 6000 -void LuaRescueHook(lua_State* L, lua_Debug *dbg) -{ - LuaContextInfo& info = GetCurrentInfo(); - - info.worryCount++; - - if(info.stopWorrying && !info.panic) - { - if(info.worryCount > (MAX_WORRY_COUNT >> 2)) - { - // the user already said they're OK with the script being frozen, - // but we don't trust their judgement completely, - // so periodically update the main loop so they have a chance to manually stop it - info.worryCount = 0; -// gens_wait(L); - info.stopWorrying = true; - } - return; - } - - if(info.worryCount > MAX_WORRY_COUNT || info.panic) - { - info.worryCount = 0; - info.stopWorrying = false; - - bool stoprunning = true; - bool stopworrying = true; - if(!info.panic) - { -// Clear_Sound_Buffer(); -#if defined(ASK_USER_ON_FREEZE) && defined(_WIN32) - DialogsOpen++; - int answer = MessageBox(HWnd, "A Lua script has been running for quite a while. Maybe it is in an infinite loop.\n\nWould you like to stop the script?\n\n(Yes to stop it now,\n No to keep running and not ask again,\n Cancel to keep running but ask again later)", "Lua Alert", MB_YESNOCANCEL | MB_DEFBUTTON3 | MB_ICONASTERISK); - DialogsOpen--; - if(answer == IDNO) - stoprunning = false; - if(answer == IDCANCEL) - stopworrying = false; -#else - stoprunning = false; -#endif - } - - if(!stoprunning && stopworrying) - { - info.stopWorrying = true; // don't remove the hook because we need it still running for RequestAbortLuaScript to work - indicateBusy(info.L, true); - } - - if(stoprunning) - { - //lua_sethook(L, NULL, 0, 0); - assert(L->errfunc || L->errorJmp); - luaL_error(L, info.panic ? info.panicMessage : "terminated by user"); - } - - info.panic = false; - } -} - -void printfToOutput(const char* fmt, ...) -{ - va_list list; - va_start(list, fmt); - int len = vscprintf(fmt, list); - char* str = new char[len+1]; - vsprintf(str, fmt, list); - va_end(list); - LuaContextInfo& info = GetCurrentInfo(); - if(info.print) - { - lua_State* L = info.L; - int uid = luaStateToUIDMap[L]; - info.print(uid, str); - info.print(uid, "\r\n"); - worry(L,300); - } - else - { - fprintf(stdout, "%s\n", str); - } - delete[] str; -} - -bool FailVerifyAtFrameBoundary(lua_State* L, const char* funcName, int unstartedSeverity=2, int inframeSeverity=2) -{//TODO -/* if (!((Genesis_Started)||(SegaCD_Started)||(_32X_Started))) - { - static const char* msg = "cannot call %s() when emulation has not started."; - switch(unstartedSeverity) - { - case 0: break; - case 1: printfToOutput(msg, funcName); break; - default: case 2: luaL_error(L, msg, funcName); break; - } - return true; - } - if(Inside_Frame) - { - static const char* msg = "cannot call %s() inside an emulation frame."; - switch(inframeSeverity) - { - case 0: break; - case 1: printfToOutput(msg, funcName); break; - default: case 2: luaL_error(L, msg, funcName); break; - } - return true; - }*/ - return false; -} -/* -// acts similar to normal emulation update -// except without the user being able to activate emulator commands -DEFINE_LUA_FUNCTION(gens_emulateframe, "") -{ - if(FailVerifyAtFrameBoundary(L, "gens.emulateframe", 0,1)) - return 0; - - Update_Emulation_One(HWnd); - Prevent_Next_Frame_Skipping(); // so we don't skip a whole bunch of frames immediately after emulating many frames by this method - - worry(L,300); - return 0; -} - -// acts as a fast-forward emulation update that still renders every frame -// and the user is unable to activate emulator commands during it -DEFINE_LUA_FUNCTION(gens_emulateframefastnoskipping, "") -{ - if(FailVerifyAtFrameBoundary(L, "gens.emulateframefastnoskipping", 0,1)) - return 0; - - Update_Emulation_One_Before(HWnd); - Update_Frame_Hook(); - Update_Emulation_After_Controlled(HWnd, true); - Prevent_Next_Frame_Skipping(); // so we don't skip a whole bunch of frames immediately after a bout of fast-forward frames - - worry(L,200); - return 0; -} - -// acts as a (very) fast-forward emulation update -// where the user is unable to activate emulator commands -DEFINE_LUA_FUNCTION(gens_emulateframefast, "") -{ - if(FailVerifyAtFrameBoundary(L, "gens.emulateframefast", 0,1)) - return 0; - - disableVideoLatencyCompensationCount = VideoLatencyCompensation + 1; - - Update_Emulation_One_Before(HWnd); - - if(FrameCount%16 == 0) // skip rendering 15 out of 16 frames - { - // update once and render - Update_Frame_Hook(); - Update_Emulation_After_Controlled(HWnd, true); - } - else - { - // update once but skip rendering - Update_Frame_Fast_Hook(); - Update_Emulation_After_Controlled(HWnd, false); - } - - Prevent_Next_Frame_Skipping(); // so we don't skip a whole bunch of frames immediately AFTER a bout of fast-forward frames - - worry(L,150); - return 0; -} - -// acts as an extremely-fast-forward emulation update -// that also doesn't render any graphics or generate any sounds, -// and the user is unable to activate emulator commands during it. -// if you load a savestate after calling this function, -// it should leave no trace of having been called, -// so you can do things like generate future emulation states every frame -// while the user continues to see and hear normal emulation -DEFINE_LUA_FUNCTION(gens_emulateframeinvisible, "") -{ - if(FailVerifyAtFrameBoundary(L, "gens.emulateframeinvisible", 0,1)) - return 0; - - int oldDisableSound2 = disableSound2; - int oldDisableRamSearchUpdate = disableRamSearchUpdate; - disableSound2 = true; - disableRamSearchUpdate = true; - - Update_Emulation_One_Before_Minimal(); - Update_Frame_Fast(); - UpdateLagCount(); - - disableSound2 = oldDisableSound2; - disableRamSearchUpdate = oldDisableRamSearchUpdate; - - // disable video latency compensation for a few frames - // because it can get pretty slow if that's doing prediction updates every frame - // when the lua script is also doing prediction updates - disableVideoLatencyCompensationCount = VideoLatencyCompensation + 1; - - worry(L,100); - return 0; -} - -DEFINE_LUA_FUNCTION(gens_speedmode, "mode") -{ - SpeedMode newSpeedMode = SPEEDMODE_NORMAL; - if(lua_isnumber(L,1)) - newSpeedMode = (SpeedMode)luaL_checkinteger(L,1); - else - { - const char* str = luaL_checkstring(L,1); - if(!stricmp(str, "normal")) - newSpeedMode = SPEEDMODE_NORMAL; - else if(!stricmp(str, "nothrottle")) - newSpeedMode = SPEEDMODE_NOTHROTTLE; - else if(!stricmp(str, "turbo")) - newSpeedMode = SPEEDMODE_TURBO; - else if(!stricmp(str, "maximum")) - newSpeedMode = SPEEDMODE_MAXIMUM; - } - - LuaContextInfo& info = GetCurrentInfo(); - info.speedMode = newSpeedMode; - RefreshScriptSpeedStatus(); - return 0; -} - -// tells Gens to wait while the script is doing calculations -// can call this periodically instead of gens.frameadvance -// note that the user can use hotkeys at this time -// (e.g. a savestate could possibly get loaded before gens.wait() returns) -DEFINE_LUA_FUNCTION(gens_wait, "") -{ - LuaContextInfo& info = GetCurrentInfo(); - - switch(info.speedMode) - { - default: - case SPEEDMODE_NORMAL: - Step_Gens_MainLoop(true, false); - break; - case SPEEDMODE_NOTHROTTLE: - case SPEEDMODE_TURBO: - case SPEEDMODE_MAXIMUM: - Step_Gens_MainLoop(Paused!=0, false); - break; - } - - return 0; -} -*/ - - - -/* -DEFINE_LUA_FUNCTION(gens_frameadvance, "") -{ - if(FailVerifyAtFrameBoundary(L, "gens.frameadvance", 0,1)) - return gens_wait(L); - - int uid = luaStateToUIDMap[L]; - LuaContextInfo& info = GetCurrentInfo(); - - if(!info.ranFrameAdvance) - { - // otherwise we'll never see the first frame of GUI drawing - if(info.speedMode != SPEEDMODE_MAXIMUM) - Show_Genesis_Screen(); - info.ranFrameAdvance = true; - } - - switch(info.speedMode) - { - default: - case SPEEDMODE_NORMAL: - while(!Step_Gens_MainLoop(true, true) && !info.panic); - break; - case SPEEDMODE_NOTHROTTLE: - while(!Step_Gens_MainLoop(Paused!=0, false) && !info.panic); - if(!(FastForwardKeyDown && (GetActiveWindow()==HWnd || BackgroundInput))) - gens_emulateframefastnoskipping(L); - else - gens_emulateframefast(L); - break; - case SPEEDMODE_TURBO: - while(!Step_Gens_MainLoop(Paused!=0, false) && !info.panic); - gens_emulateframefast(L); - break; - case SPEEDMODE_MAXIMUM: - while(!Step_Gens_MainLoop(Paused!=0, false) && !info.panic); - gens_emulateframeinvisible(L); - break; - } - return 0; -} - -DEFINE_LUA_FUNCTION(gens_pause, "") -{ - LuaContextInfo& info = GetCurrentInfo(); - - Paused = 1; - while(!Step_Gens_MainLoop(true, false) && !info.panic); - - // allow the user to not have to manually unpause - // after restarting a script that used gens.pause() - if(info.panic) - Paused = 0; - - return 0; -} - -DEFINE_LUA_FUNCTION(gens_unpause, "") -{ - LuaContextInfo& info = GetCurrentInfo(); - - Paused = 0; - return 0; -} - -DEFINE_LUA_FUNCTION(gens_redraw, "") -{ - Show_Genesis_Screen(); - worry(L,250); - return 0; -} - -*/ - -DEFINE_LUA_FUNCTION(memory_readbyte, "address") -{ - int address = luaL_checkinteger(L,1); - unsigned char value = (unsigned char)(_MMU_read08(address) & 0xFF); - lua_settop(L,0); - lua_pushinteger(L, value); - return 1; // we return the number of return values -} -DEFINE_LUA_FUNCTION(memory_readbytesigned, "address") -{ - int address = luaL_checkinteger(L,1); - signed char value = (signed char)(_MMU_read08(address) & 0xFF); - lua_settop(L,0); - lua_pushinteger(L, value); - return 1; -} -DEFINE_LUA_FUNCTION(memory_readword, "address") -{ - int address = luaL_checkinteger(L,1); - unsigned short value = (unsigned short)(_MMU_read16(address) & 0xFFFF); - lua_settop(L,0); - lua_pushinteger(L, value); - return 1; -} -DEFINE_LUA_FUNCTION(memory_readwordsigned, "address") -{ - int address = luaL_checkinteger(L,1); - signed short value = (signed short)(_MMU_read16(address) & 0xFFFF); - lua_settop(L,0); - lua_pushinteger(L, value); - return 1; -} -DEFINE_LUA_FUNCTION(memory_readdword, "address") -{ - int address = luaL_checkinteger(L,1); - unsigned long value = (unsigned long)(_MMU_read32(address)); - lua_settop(L,0); - lua_pushinteger(L, value); - return 1; -} -DEFINE_LUA_FUNCTION(memory_readdwordsigned, "address") -{ - int address = luaL_checkinteger(L,1); - signed long value = (signed long)(_MMU_read32(address)); - lua_settop(L,0); - lua_pushinteger(L, value); - return 1; -} - -DEFINE_LUA_FUNCTION(memory_writebyte, "address,value") -{ - int address = luaL_checkinteger(L,1); - unsigned char value = (unsigned char)(luaL_checkinteger(L,2) & 0xFF); - _MMU_write08(address, value); - return 0; -} -DEFINE_LUA_FUNCTION(memory_writeword, "address,value") -{ - int address = luaL_checkinteger(L,1); - unsigned short value = (unsigned short)(luaL_checkinteger(L,2) & 0xFFFF); - _MMU_write16(address, value); - return 0; -} -DEFINE_LUA_FUNCTION(memory_writedword, "address,value") -{ - int address = luaL_checkinteger(L,1); - unsigned long value = (unsigned long)(luaL_checkinteger(L,2)); - _MMU_write32(address, value); - return 0; -} - -DEFINE_LUA_FUNCTION(memory_readbyterange, "address,length") -{ - int address = luaL_checkinteger(L,1); - int length = luaL_checkinteger(L,2); - - if(length < 0) - { - address += length; - length = -length; - } - - // push the array - lua_createtable(L, abs(length), 0); - - // put all the values into the (1-based) array - for(int a = address, n = 1; n <= length; a++, n++) - { -// if(IsHardwareAddressValid(a)) -// { - unsigned char value = (unsigned char)(_MMU_read08(address) & 0xFF); - lua_pushinteger(L, value); - lua_rawseti(L, -2, n); -// } - // else leave the value nil - } - - return 1; -} -/* -DEFINE_LUA_FUNCTION(memory_isvalid, "address") -{ - int address = luaL_checkinteger(L,1); - lua_settop(L,0); - lua_pushboolean(L, IsHardwareAddressValid(address)); - return 1; -} -*/ -struct registerPointerMap -{ - const char* registerName; - unsigned int* pointer; - int dataSize; -}; - -#define RPM_ENTRY(name,var) {name, (unsigned int*)&var, sizeof(var)}, - -registerPointerMap m68kPointerMap [] = { -/* RPM_ENTRY("a0", main68k_context.areg[0]) - RPM_ENTRY("a1", main68k_context.areg[1]) - RPM_ENTRY("a2", main68k_context.areg[2]) - RPM_ENTRY("a3", main68k_context.areg[3]) - RPM_ENTRY("a4", main68k_context.areg[4]) - RPM_ENTRY("a5", main68k_context.areg[5]) - RPM_ENTRY("a6", main68k_context.areg[6]) - RPM_ENTRY("a7", main68k_context.areg[7]) - RPM_ENTRY("d0", main68k_context.dreg[0]) - RPM_ENTRY("d1", main68k_context.dreg[1]) - RPM_ENTRY("d2", main68k_context.dreg[2]) - RPM_ENTRY("d3", main68k_context.dreg[3]) - RPM_ENTRY("d4", main68k_context.dreg[4]) - RPM_ENTRY("d5", main68k_context.dreg[5]) - RPM_ENTRY("d6", main68k_context.dreg[6]) - RPM_ENTRY("d7", main68k_context.dreg[7]) - RPM_ENTRY("pc", main68k_context.pc) - RPM_ENTRY("sr", main68k_context.sr)*/ - {} -}; -registerPointerMap s68kPointerMap [] = {/* - RPM_ENTRY("a0", sub68k_context.areg[0]) - RPM_ENTRY("a1", sub68k_context.areg[1]) - RPM_ENTRY("a2", sub68k_context.areg[2]) - RPM_ENTRY("a3", sub68k_context.areg[3]) - RPM_ENTRY("a4", sub68k_context.areg[4]) - RPM_ENTRY("a5", sub68k_context.areg[5]) - RPM_ENTRY("a6", sub68k_context.areg[6]) - RPM_ENTRY("a7", sub68k_context.areg[7]) - RPM_ENTRY("d0", sub68k_context.dreg[0]) - RPM_ENTRY("d1", sub68k_context.dreg[1]) - RPM_ENTRY("d2", sub68k_context.dreg[2]) - RPM_ENTRY("d3", sub68k_context.dreg[3]) - RPM_ENTRY("d4", sub68k_context.dreg[4]) - RPM_ENTRY("d5", sub68k_context.dreg[5]) - RPM_ENTRY("d6", sub68k_context.dreg[6]) - RPM_ENTRY("d7", sub68k_context.dreg[7]) - RPM_ENTRY("pc", sub68k_context.pc) - RPM_ENTRY("sr", sub68k_context.sr)*/ - {} -}; - -struct cpuToRegisterMap -{ - const char* cpuName; - registerPointerMap* rpmap; -} -cpuToRegisterMaps [] = -{ - {"m68k.", m68kPointerMap}, - {"main.", m68kPointerMap}, - {"s68k.", s68kPointerMap}, - {"sub.", s68kPointerMap}, - {"", m68kPointerMap}, -}; - - -DEFINE_LUA_FUNCTION(memory_getregister, "cpu_dot_registername_string") -{ - const char* qualifiedRegisterName = luaL_checkstring(L,1); - lua_settop(L,0); - for(int cpu = 0; cpu < sizeof(cpuToRegisterMaps)/sizeof(*cpuToRegisterMaps); cpu++) - { - cpuToRegisterMap ctrm = cpuToRegisterMaps[cpu]; - int cpuNameLen = strlen(ctrm.cpuName); - if(!strnicmp(qualifiedRegisterName, ctrm.cpuName, cpuNameLen)) - { - qualifiedRegisterName += cpuNameLen; - for(int reg = 0; ctrm.rpmap[reg].dataSize; reg++) - { - registerPointerMap rpm = ctrm.rpmap[reg]; - if(!stricmp(qualifiedRegisterName, rpm.registerName)) - { - switch(rpm.dataSize) - { default: - case 1: lua_pushinteger(L, *(unsigned char*)rpm.pointer); break; - case 2: lua_pushinteger(L, *(unsigned short*)rpm.pointer); break; - case 4: lua_pushinteger(L, *(unsigned long*)rpm.pointer); break; - } - return 1; - } - } - lua_pushnil(L); - return 1; - } - } - lua_pushnil(L); - return 1; -} -DEFINE_LUA_FUNCTION(memory_setregister, "cpu_dot_registername_string,value") -{ - const char* qualifiedRegisterName = luaL_checkstring(L,1); - unsigned long value = (unsigned long)(luaL_checkinteger(L,2)); - lua_settop(L,0); - for(int cpu = 0; cpu < sizeof(cpuToRegisterMaps)/sizeof(*cpuToRegisterMaps); cpu++) - { - cpuToRegisterMap ctrm = cpuToRegisterMaps[cpu]; - int cpuNameLen = strlen(ctrm.cpuName); - if(!strnicmp(qualifiedRegisterName, ctrm.cpuName, cpuNameLen)) - { - qualifiedRegisterName += cpuNameLen; - for(int reg = 0; ctrm.rpmap[reg].dataSize; reg++) - { - registerPointerMap rpm = ctrm.rpmap[reg]; - if(!stricmp(qualifiedRegisterName, rpm.registerName)) - { - switch(rpm.dataSize) - { default: - case 1: *(unsigned char*)rpm.pointer = (unsigned char)(value & 0xFF); break; - case 2: *(unsigned short*)rpm.pointer = (unsigned short)(value & 0xFFFF); break; - case 4: *(unsigned long*)rpm.pointer = value; break; - } - return 0; - } - } - return 0; - } - } - return 0; -} - -/* -DEFINE_LUA_FUNCTION(state_create, "[location]") -{ - if(lua_isnumber(L,1)) - { - // simply return the integer that got passed in - // (that's as good a savestate object as any for a numbered savestate slot) - lua_settop(L,1); - return 1; - } - - int len = GENESIS_STATE_LENGTH; - if (SegaCD_Started) len += SEGACD_LENGTH_EX; - if (_32X_Started) len += G32X_LENGTH_EX; - if (!((Genesis_Started)||(SegaCD_Started)||(_32X_Started))) - len += std::max(SEGACD_LENGTH_EX, G32X_LENGTH_EX); - - // allocate the in-memory/anonymous savestate - unsigned char* stateBuffer = (unsigned char*)lua_newuserdata(L, len + 16); // 16 is for performance alignment reasons - stateBuffer[0] = 0; - - return 1; -} - -// savestate.save(location [, option]) -// saves the current emulation state to the given location -// you can pass in either a savestate file number (an integer), -// OR you can pass in a savestate object that was returned by savestate.create() -// if option is "quiet" then any warning messages will be suppressed -// if option is "scriptdataonly" then the state will not actually be saved, but any save callbacks will still get called and their results will be saved (see savestate.registerload()/savestate.registersave()) -DEFINE_LUA_FUNCTION(state_save, "location[,option]") -{ - const char* option = (lua_type(L,2) == LUA_TSTRING) ? lua_tostring(L,2) : NULL; - if(option) - { - if(!stricmp(option, "quiet")) // I'm not sure if saving can generate warning messages, but we might as well support suppressing them should they turn out to exist - g_disableStatestateWarnings = true; - else if(!stricmp(option, "scriptdataonly")) - g_onlyCallSavestateCallbacks = true; - } - struct Scope { ~Scope(){ g_disableStatestateWarnings = false; g_onlyCallSavestateCallbacks = false; } } scope; // needs to run even if the following code throws an exception... maybe I should have put this in a "finally" block instead, but this project seems to have something against using the "try" statement - - if(!g_onlyCallSavestateCallbacks && FailVerifyAtFrameBoundary(L, "savestate.save", 2,2)) - return 0; - - int type = lua_type(L,1); - switch(type) - { - case LUA_TNUMBER: // numbered save file - default: - { - int stateNumber = luaL_checkinteger(L,1); - Set_Current_State(stateNumber, false,false); - char Name [1024] = {0}; - Get_State_File_Name(Name); - Save_State(Name); - } return 0; - case LUA_TUSERDATA: // in-memory save slot - { - unsigned char* stateBuffer = (unsigned char*)lua_touserdata(L,1); - if(stateBuffer) - { - stateBuffer += ((16 - (int)stateBuffer) & 15); // for performance alignment reasons - Save_State_To_Buffer(stateBuffer); - } - } return 0; - } -} - -// savestate.load(location [, option]) -// loads the current emulation state from the given location -// you can pass in either a savestate file number (an integer), -// OR you can pass in a savestate object that was returned by savestate.create() and has already saved to with savestate.save() -// if option is "quiet" then any warning messages will be suppressed -// if option is "scriptdataonly" then the state will not actually be loaded, but load callbacks will still get called and supplied with the data saved by save callbacks (see savestate.registerload()/savestate.registersave()) -DEFINE_LUA_FUNCTION(state_load, "location[,option]") -{ - const char* option = (lua_type(L,2) == LUA_TSTRING) ? lua_tostring(L,2) : NULL; - if(option) - { - if(!stricmp(option, "quiet")) - g_disableStatestateWarnings = true; - else if(!stricmp(option, "scriptdataonly")) - g_onlyCallSavestateCallbacks = true; - } - struct Scope { ~Scope(){ g_disableStatestateWarnings = false; g_onlyCallSavestateCallbacks = false; } } scope; // needs to run even if the following code throws an exception... maybe I should have put this in a "finally" block instead, but this project seems to have something against using the "try" statement - - if(!g_onlyCallSavestateCallbacks && FailVerifyAtFrameBoundary(L, "savestate.load", 2,2)) - return 0; - - g_disableStatestateWarnings = lua_toboolean(L,2) != 0; - - int type = lua_type(L,1); - switch(type) - { - case LUA_TNUMBER: // numbered save file - default: - { - LuaContextInfo& info = GetCurrentInfo(); - if(info.rerecordCountingDisabled) - SkipNextRerecordIncrement = true; - int stateNumber = luaL_checkinteger(L,1); - Set_Current_State(stateNumber, false,!g_disableStatestateWarnings); - char Name [1024] = {0}; - Get_State_File_Name(Name); - Load_State(Name); - } return 0; - case LUA_TUSERDATA: // in-memory save slot - { - unsigned char* stateBuffer = (unsigned char*)lua_touserdata(L,1); - if(stateBuffer) - { - stateBuffer += ((16 - (int)stateBuffer) & 15); // for performance alignment reasons - if(stateBuffer[0]) - Load_State_From_Buffer(stateBuffer); - else // the first byte of a valid savestate is never 0 - luaL_error(L, "attempted to load an anonymous savestate before saving it"); - } - } return 0; - } -} -*/ -// savestate.loadscriptdata(location) -// returns the user data associated with the given savestate -// without actually loading the rest of that savestate or calling any callbacks. -// you can pass in either a savestate file number (an integer), -// OR you can pass in a savestate object that was returned by savestate.create() -// but note that currently only non-anonymous savestates can have associated scriptdata -// -// also note that this returns the same values -// that would be passed into a registered load function. -// the main reason this exists also is so you can register a load function that -// chooses whether or not to load the scriptdata instead of always loading it, -// and also to provide a nicer interface for loading scriptdata -// without needing to trigger savestate loading first -//DEFINE_LUA_FUNCTION(state_loadscriptdata, "location") -//{ -// int type = lua_type(L,1); -// switch(type) -// { -// case LUA_TNUMBER: // numbered save file -// default: -// { -// int stateNumber = luaL_checkinteger(L,1); -// Set_Current_State(stateNumber, false,false); -// char Name [1024] = {0}; -// Get_State_File_Name(Name); -// { -// LuaSaveData saveData; -// -// char luaSaveFilename [512]; -// strncpy(luaSaveFilename, Name, 512); -// luaSaveFilename[512-(1+7/*strlen(".luasav")*/)] = '\0'; -// strcat(luaSaveFilename, ".luasav"); -// FILE* luaSaveFile = fopen(luaSaveFilename, "rb"); -// if(luaSaveFile) -// { -// saveData.ImportRecords(luaSaveFile); -// fclose(luaSaveFile); -// -// int uid = luaStateToUIDMap[L]; -// LuaContextInfo& info = GetCurrentInfo(); -// -// lua_settop(L, 0); -// saveData.LoadRecord(uid, info.dataLoadKey, (unsigned int)-1); -// return lua_gettop(L); -// } -// } -// } return 0; -// case LUA_TUSERDATA: // in-memory save slot -// { // there can be no user data associated with those, at least not yet -// } return 0; -// } -//} - -// savestate.savescriptdata(location) -// same as savestate.save(location, "scriptdataonly") -// only provided for consistency with savestate.loadscriptdata(location) -/*DEFINE_LUA_FUNCTION(state_savescriptdata, "location") -{ - lua_settop(L, 1); - lua_pushstring(L, "scriptdataonly"); - return state_save(L); -} -*/ - -//joypad lib - -static const char *button_mappings[] = { -"debug","r","l","x","y","a","b","start","select","up","down","left","right" -}; - -// table joypad.read(int which = 1) -// -// Reads the joypads as inputted by the user. -static int joy_get(lua_State *L) { - - uint16 buttons = nds.pad; - - lua_newtable(L); - - int i; - for (i = 0; i < 16; i++) { - if (buttons & (1<= 2) color |= 0xFF; - return color; - } - else for(int i = 0; i 255) value = 255; - switch(key) - { - case 1: case 'r': color |= value << 24; break; - case 2: case 'g': color |= value << 16; break; - case 3: case 'b': color |= value << 8; break; - case 4: case 'a': color = (color & ~0xFF) | value; break; - } - lua_pop(L, 1); - } - return color; - } break; - case LUA_TFUNCTION: - return 0; - } - return defaultColor; -} -int getcolor(lua_State *L, int idx, int defaultColor) -{ - int color = getcolor_unmodified(L, idx, defaultColor); - LuaContextInfo& info = GetCurrentInfo(); - if(info.transparencyModifier != 255) - { - int alpha = (((color & 0xFF) * info.transparencyModifier) / 255); - if(alpha > 255) alpha = 255; - color = (color & ~0xFF) | alpha; - } - return color; -} - -// r,g,b,a = gui.parsecolor(color) -// examples: -// local r,g,b = gui.parsecolor("green") -// local r,g,b,a = gui.parsecolor(0x7F3FFF7F) -DEFINE_LUA_FUNCTION(gui_parsecolor, "color") -{ - int color = getcolor_unmodified(L, 1, 0); - int r = (color & 0xFF000000) >> 24; - int g = (color & 0x00FF0000) >> 16; - int b = (color & 0x0000FF00) >> 8; - int a = (color & 0x000000FF); - lua_pushinteger(L, r); - lua_pushinteger(L, g); - lua_pushinteger(L, b); - lua_pushinteger(L, a); - return 4; -} -/* -DEFINE_LUA_FUNCTION(gui_text, "x,y,str[,color=\"white\"[,outline=\"black\"]]") -{ - if(DeferGUIFuncIfNeeded(L)) - return 0; // we have to wait until later to call this function because gens hasn't emulated the next frame yet - // (the only way to avoid this deferring is to be in a gui.register or gens.registerafter callback) - - int x = luaL_checkinteger(L,1) & 0xFFFF; - int y = luaL_checkinteger(L,2) & 0xFFFF; - const char* str = toCString(L,3); // better than using luaL_checkstring here (more permissive) - - if(str && *str) - { - int foreColor = getcolor(L,4,0xFFFFFFFF); - int backColor = getcolor(L,5,0x000000FF); - PutText2(str, x, y, foreColor, backColor); - } - - return 0; -} - -static inline void ApplyShaderToPixel(int off, std::map& cachedShaderResults, lua_State* L, int idx) -{ - int color; - if (Bits32) - color = MD_Screen32[off]; - else - color = DrawUtil::Pix16To32(MD_Screen[off]); - - int result; - std::map::const_iterator found = cachedShaderResults.find(color); - if(found != cachedShaderResults.end()) - { - result = found->second; - } - else - { - int b = (color & 0x000000FF); - int g = (color & 0x0000FF00) >> 8; - int r = (color & 0x00FF0000) >> 16; - - lua_pushvalue(L, idx); - lua_pushinteger(L, r); - lua_pushinteger(L, g); - lua_pushinteger(L, b); - - lua_call(L, 3, 3); - - int rout = lua_tointeger(L, -3); - int gout = lua_tointeger(L, -2); - int bout = lua_tointeger(L, -1); - lua_pop(L,3); - if(rout < 0) rout = 0; if(rout > 255) rout = 255; - if(gout < 0) gout = 0; if(gout > 255) gout = 255; - if(bout < 0) bout = 0; if(bout > 255) bout = 255; - - result = DrawUtil::Make32(rout,gout,bout); - cachedShaderResults[color] = result; - } - if (Bits32) - MD_Screen32[off] = result; - else - MD_Screen[off] = DrawUtil::Pix32To16(result); -} - -#define SWAP_INTEGERS(x,y) x^=y, y^=x, x^=y - -// performance note: for me, this function is extremely slow in debug builds, -// but when compiled with full optimizations turned on it becomes very fast. -void ApplyShaderToBox(int x1, int y1, int x2, int y2, lua_State* L, int idx) -{ - if((x1 < 0 && x2 < 0) || (x1 > 319 && x2 > 319) || (y1 < 0 && y2 < 0) || (y1 > 223 && y2 > 223)) - return; - - // require x1,y1 <= x2,y2 - if (x1 > x2) SWAP_INTEGERS(x1,x2); - if (y1 > y2) SWAP_INTEGERS(y1,y2); - - // avoid trying to draw any offscreen pixels - if (x1 < 0) x1 = 0; - if (x1 > 319) x1 = 319; - if (x2 < 0) x2 = 0; - if (x2 > 319) x2 = 319; - if (y1 < 0) y1 = 0; - if (y1 > 223) y1 = 223; - if (y2 < 0) y2 = 0; - if (y2 > 223) y2 = 223; - - std::map cachedShaderResults; - - for(short y = y1; y <= y2; y++) - { - int off = (y * 336) + x1 + 8; - for(short x = x1; x <= x2; x++, off++) - { - ApplyShaderToPixel(off, cachedShaderResults, L, idx); - } - } -} - -void ApplyShaderToBoxOutline(int x1, int y1, int x2, int y2, lua_State* L, int idx) -{ - // require x1,y1 <= x2,y2 - if (x1 > x2) SWAP_INTEGERS(x1,x2); - if (y1 > y2) SWAP_INTEGERS(y1,y2); - - // avoid trying to draw any offscreen pixels - if (x1 < -1) x1 = -1; - if (x1 > 320) x1 = 320; - if (x2 < -1) x2 = -1; - if (x2 > 320) x2 = 320; - if (y1 < -1) y1 = -1; - if (y1 > 224) y1 = 224; - if (y2 < -1) y2 = -1; - if (y2 > 224) y2 = 224; - - std::map cachedShaderResults; - - if(y1 >= 0 && y1 < 224) - for (short x = x1+1; x < x2; x++) - ApplyShaderToPixel((y1 * 336) + x + 8, cachedShaderResults, L, idx); - if(x1 >= 0 && x1 < 320) - for (short y = y1; y <= y2; y++) - ApplyShaderToPixel((y * 336) + x1 + 8, cachedShaderResults, L, idx); - if(y1 != y2 && y2 >= 0 && y2 < 224) - for (short x = x1+1; x < x2; x++) - ApplyShaderToPixel((y2 * 336) + x + 8, cachedShaderResults, L, idx); - if(x1 != x2 && x2 >= 0 && x2 < 320) - for (short y = y1; y <= y2; y++) - ApplyShaderToPixel((y * 336) + x2 + 8, cachedShaderResults, L, idx); -} - -int amplifyShader(lua_State* L) -{ - int rin = lua_tointeger(L, 1); - int gin = lua_tointeger(L, 2); - int bin = lua_tointeger(L, 3); - lua_pushvalue(L, lua_upvalueindex(1)); - lua_insert(L, 1); - lua_call(L, 3, 3); - int rout = lua_tointeger(L, 1); - int gout = lua_tointeger(L, 2); - int bout = lua_tointeger(L, 3); - lua_settop(L, 0); - lua_pushinteger(L, rout*4 - rin*3); - lua_pushinteger(L, gout*4 - gin*3); - lua_pushinteger(L, bout*4 - bin*3); - return 3; -}*/ -/* -DEFINE_LUA_FUNCTION(gui_box, "x1,y1,x2,y2[,fill[,outline]]") -{ - if(DeferGUIFuncIfNeeded(L)) - return 0; - - int x1 = luaL_checkinteger(L,1); // & 0xFFFF removed because it was turning -1 into 65535 which screwed up the out-of-bounds checking in ApplyShaderToBox - int y1 = luaL_checkinteger(L,2); - int x2 = luaL_checkinteger(L,3); - int y2 = luaL_checkinteger(L,4); - int fillcolor = getcolor(L,5,0xFFFFFF3F); - int outlinecolor = getcolor(L,6,fillcolor|0xFF); - if(!lua_isfunction(L,5) || !lua_isnoneornil(L,6)) - { - DrawBoxPP2(x1, y1, x2, y2, fillcolor, outlinecolor); - if(lua_isfunction(L,5)) - ApplyShaderToBox(x1+1,y1+1,x2-1,y2-1, L,5); - if(lua_isfunction(L,6)) - ApplyShaderToBoxOutline(x1,y1,x2,y2, L,6); - } - else // fill is a shader and outline is not specified, so make the outline a more "opaque" version of the shader to match up with the default color behavior - { - ApplyShaderToBox(x1+1,y1+1,x2-1,y2-1, L,5); - lua_settop(L, 5); - lua_pushvalue(L, 5); - lua_pushcclosure(L, amplifyShader, 1); - ApplyShaderToBoxOutline(x1,y1,x2,y2, L,6); - } - - return 0; -} -// gui.setpixel(x,y,color) -// color can be a RGB web color like '#ff7030', or with alpha RGBA like '#ff703060' -// or it can be an RGBA hex number like 0xFF703060 -// or it can be a preset color like 'red', 'orange', 'blue', 'white', etc. -DEFINE_LUA_FUNCTION(gui_pixel, "x,y[,color=\"white\"]") -{ - if(DeferGUIFuncIfNeeded(L)) - return 0; - - int x = luaL_checkinteger(L,1) & 0xFFFF; - int y = luaL_checkinteger(L,2) & 0xFFFF; - int color = getcolor(L,3,0xFFFFFFFF); - int color32 = color>>8; - int color16 = DrawUtil::Pix32To16(color32); - int Opac = color & 0xFF; - - if(Opac) - Pixel(x, y, color32, color16, 0, Opac); - - return 0; -} -// r,g,b = gui.getpixel(x,y) -DEFINE_LUA_FUNCTION(gui_getpixel, "x,y") -{ - int x = luaL_checkinteger(L,1); - int y = luaL_checkinteger(L,2); - - int xres = ((VDP_Reg.Set4 & 0x1) || Debug || !Game || !FrameCount) ? 320 : 256; - int yres = ((VDP_Reg.Set2 & 0x8) && !(Debug || !Game || !FrameCount)) ? 240 : 224; - - x = std::max(0,std::min(xres,x)); - y = std::max(0,std::min(yres,y)); - - int off = (y * 336) + x + 8; - - int color; - if (Bits32) - color = MD_Screen32[off]; - else - color = DrawUtil::Pix16To32(MD_Screen[off]); - - int b = (color & 0x000000FF); - int g = (color & 0x0000FF00) >> 8; - int r = (color & 0x00FF0000) >> 16; - - lua_pushinteger(L, r); - lua_pushinteger(L, g); - lua_pushinteger(L, b); - - return 3; -} -DEFINE_LUA_FUNCTION(gui_line, "x1,y1,x2,y2[,color=\"white\"[,skipfirst=false]]") -{ - if(DeferGUIFuncIfNeeded(L)) - return 0; - - int x1 = luaL_checkinteger(L,1) & 0xFFFF; - int y1 = luaL_checkinteger(L,2) & 0xFFFF; - int x2 = luaL_checkinteger(L,3) & 0xFFFF; - int y2 = luaL_checkinteger(L,4) & 0xFFFF; - int color = getcolor(L,5,0xFFFFFFFF); - int color32 = color>>8; - int color16 = DrawUtil::Pix32To16(color32); - int Opac = color & 0xFF; - - if(Opac) - { - int skipFirst = lua_toboolean(L,6); - DrawLine(x1, y1, x2, y2, color32, color16, 0, Opac, skipFirst); - } - - return 0; -} - -// gui.opacity(number alphaValue) -// sets the transparency of subsequent draw calls -// 0.0 is completely transparent, 1.0 is completely opaque -// non-integer values are supported and meaningful, as are values greater than 1.0 -// it is not necessary to use this function to get transparency (or the less-recommended gui.transparency() either), -// because you can provide an alpha value in the color argument of each draw call. -// however, it can be convenient to be able to globally modify the drawing transparency -DEFINE_LUA_FUNCTION(gui_setopacity, "alpha_0_to_1") -{ - lua_Number opacF = luaL_checknumber(L,1); - opacF *= 255.0; - if(opacF < 0) opacF = 0; - int opac; - lua_number2int(opac, opacF); - LuaContextInfo& info = GetCurrentInfo(); - info.transparencyModifier = opac; - return 0; -} - -// gui.transparency(number transparencyValue) -// sets the transparency of subsequent draw calls -// 0.0 is completely opaque, 4.0 is completely transparent -// non-integer values are supported and meaningful, as are values less than 0.0 -// this is a legacy function, and the range is from 0 to 4 solely for this reason -// it does the exact same thing as gui.opacity() but with a different argument range -DEFINE_LUA_FUNCTION(gui_settransparency, "transparency_4_to_0") -{ - lua_Number transp = luaL_checknumber(L,1); - lua_Number opacF = 4 - transp; - opacF *= 255.0 / 4.0; - if(opacF < 0) opacF = 0; - int opac; - lua_number2int(opac, opacF); - LuaContextInfo& info = GetCurrentInfo(); - info.transparencyModifier = opac; - return 0; -} - -// takes a screenshot and returns it in gdstr format -// example: gd.createFromGdStr(gui.gdscreenshot()):png("outputimage.png") -DEFINE_LUA_FUNCTION(gui_gdscreenshot, "") -{ - int width = ((VDP_Reg.Set4 & 0x1) || Debug || !Game || !FrameCount) ? 320 : 256; - int height = ((VDP_Reg.Set2 & 0x8) && !(Debug || !Game || !FrameCount)) ? 240 : 224; - int size = 11 + width * height * 4; - - char* str = new char[size+1]; - str[size] = 0; - unsigned char* ptr = (unsigned char*)str; - - // GD format header for truecolor image (11 bytes) - *ptr++ = (65534 >> 8) & 0xFF; - *ptr++ = (65534 ) & 0xFF; - *ptr++ = (width >> 8) & 0xFF; - *ptr++ = (width ) & 0xFF; - *ptr++ = (height >> 8) & 0xFF; - *ptr++ = (height ) & 0xFF; - *ptr++ = 1; - *ptr++ = 255; - *ptr++ = 255; - *ptr++ = 255; - *ptr++ = 255; - - unsigned char *Src = Bits32 ? (unsigned char*)(MD_Screen32+8) : (unsigned char*)(MD_Screen+8); - - if(Bits32) - { - for(int y = 0; y < height; y++, Src += 336*4) - { - for(int x = 0; x < width; x++) - { - *ptr++ = Src[4*x+3]; - *ptr++ = Src[4*x+2]; - *ptr++ = Src[4*x+1]; - *ptr++ = Src[4*x+0]; - } - } - } - else if((Mode_555 & 1) == 0) - { - for(int y = 0; y < height; y++, Src += 336*2) - { - for(int x = 0; x < width; x++) - { - int pix = DrawUtil::Pix16To32((pix16)(Src[2*x]+(Src[2*x+1]<<8))); - *ptr++ = ((unsigned char*)&pix)[3]; - *ptr++ = ((unsigned char*)&pix)[2]; - *ptr++ = ((unsigned char*)&pix)[1]; - *ptr++ = ((unsigned char*)&pix)[0]; - } - } - } - else - { - for(int y = 0; y < height; y++, Src += 336*2) - { - for(int x = 0; x < width; x++) - { - int pix = DrawUtil::Pix15To32((pix15)(Src[2*x]+(Src[2*x+1]<<8))); - *ptr++ = ((unsigned char*)&pix)[3]; - *ptr++ = ((unsigned char*)&pix)[2]; - *ptr++ = ((unsigned char*)&pix)[1]; - *ptr++ = ((unsigned char*)&pix)[0]; - } - } - } - - lua_pushlstring(L, str, size); - delete[] str; - return 1; -} - -// draws a gd image that's in gdstr format to the screen -// example: gui.gdoverlay(gd.createFromPng("myimage.png"):gdStr()) -DEFINE_LUA_FUNCTION(gui_gdoverlay, "[x=0,y=0,]gdimage[,alphamul]") -{ - if(DeferGUIFuncIfNeeded(L)) - return 0; - - int xStart = 0; - int yStart = 0; - - int index = 1; - if(lua_type(L,index) == LUA_TNUMBER) - { - xStart = lua_tointeger(L,index++); - if(lua_type(L,index) == LUA_TNUMBER) - yStart = lua_tointeger(L,index++); - } - - luaL_checktype(L,index,LUA_TSTRING); - const unsigned char* ptr = (const unsigned char*)lua_tostring(L,index++); - - // GD format header for truecolor image (11 bytes) - ptr++; - ptr++; - int width = *ptr++ << 8; - width |= *ptr++; - int height = *ptr++ << 8; - height |= *ptr++; - ptr += 5; - - int maxWidth = ((VDP_Reg.Set4 & 0x1) || Debug || !Game || !FrameCount) ? 320 : 256; - int maxHeight = ((VDP_Reg.Set2 & 0x8) && !(Debug || !Game || !FrameCount)) ? 240 : 224; - - unsigned char *Dst = Bits32 ? (unsigned char*)(MD_Screen32+8) : (unsigned char*)(MD_Screen+8); - - LuaContextInfo& info = GetCurrentInfo(); - int alphaMul = info.transparencyModifier; - if(lua_isnumber(L, index)) - alphaMul = (int)(alphaMul * lua_tonumber(L, index++)); - if(alphaMul <= 0) - return 0; - - // since there aren't that many possible opacity levels, - // do the opacity modification calculations beforehand instead of per pixel - int opacMap[256]; - for(int i = 0; i < 256; i++) - { - int opac = 255 - (i << 1); // not sure why, but gdstr seems to divide each alpha value by 2 - opac = (opac * alphaMul) / 255; - if(opac < 0) opac = 0; - if(opac > 255) opac = 255; - opacMap[i] = 255 - opac; - } - - if(Bits32) - { - Dst += yStart * 336*4; - for(int y = yStart; y < height+yStart && y < maxHeight; y++, Dst += 336*4) - { - if(y < 0) - ptr += width * 4; - else - { - int xA = (xStart < 0 ? 0 : xStart); - int xB = (xStart+width > maxWidth ? maxWidth : xStart+width); - ptr += (xA - xStart) * 4; - for(int x = xA; x < xB; x++) - { - //Dst[4*x+3] = *ptr++; - //Dst[4*x+2] = *ptr++; - //Dst[4*x+1] = *ptr++; - //Dst[4*x+0] = *ptr++; - - int opac = opacMap[ptr[0]]; - pix32 pix = (ptr[3]|(ptr[2]<<8)|(ptr[1]<<16)); - pix32 prev = Dst[4*x] | (Dst[4*x+1] << 8) | (Dst[4*x+2] << 16); - pix = DrawUtil::Blend(prev, pix, opac); - Dst[4*x] = pix & 0xFF; - Dst[4*x+1] = (pix>>8) & 0xFF; - Dst[4*x+2] = (pix>>16) & 0xFF; - ptr += 4; - } - ptr += (xStart+width - xB) * 4; - } - } - } - else if((Mode_555 & 1) == 0) - { - Dst += yStart * 336*2; - for(int y = yStart; y < height+yStart && y < maxHeight; y++, Dst += 336*2) - { - if(y < 0) - ptr += width * 4; - else - { - int xA = (xStart < 0 ? 0 : xStart); - int xB = (xStart+width > maxWidth ? maxWidth : xStart+width); - ptr += (xA - xStart) * 4; - for(int x = xA; x < xB; x++) - { - int opac = opacMap[ptr[0]]; - pix32 pixh = (ptr[3]|(ptr[2]<<8)|(ptr[1]<<16)); - pix32 prev = DrawUtil::Pix16To32(Dst[2*x] | (Dst[2*x+1] << 8)); - pix16 pix = DrawUtil::Pix32To16(DrawUtil::Blend(prev, pixh, opac)); - Dst[2*x] = pix & 0xFF; - Dst[2*x+1] = (pix>>8) & 0xFF; - ptr += 4; - } - ptr += (xStart+width - xB) * 4; - } - } - } - else - { - Dst += yStart * 336*2; - for(int y = yStart; y < height+yStart && y < maxHeight; y++, Dst += 336*2) - { - if(y < 0) - ptr += width * 4; - else - { - int xA = (xStart < 0 ? 0 : xStart); - int xB = (xStart+width > maxWidth ? maxWidth : xStart+width); - ptr += (xA - xStart) * 4; - for(int x = xA; x < xB; x++) - { - int opac = opacMap[ptr[0]]; - pix32 pixh = (ptr[3]|(ptr[2]<<8)|(ptr[1]<<16)); - pix32 prev = DrawUtil::Pix15To32(Dst[2*x] | (Dst[2*x+1] << 8)); - pix15 pix = DrawUtil::Pix32To15(DrawUtil::Blend(prev, pixh, opac)); - Dst[2*x] = pix & 0xFF; - Dst[2*x+1] = (pix>>8) & 0xFF; - ptr += 4; - } - ptr += (xStart+width - xB) * 4; - } - } - } - - return 0; -} -*/ -static void GetCurrentScriptDir(char* buffer, int bufLen) -{ - LuaContextInfo& info = GetCurrentInfo(); - strncpy(buffer, info.lastFilename.c_str(), bufLen); - buffer[bufLen-1] = 0; - char* slash = std::max(strrchr(buffer, '/'), strrchr(buffer, '\\')); - if(slash) - slash[1] = 0; -} - -DEFINE_LUA_FUNCTION(emu_openscript, "filename") -{ -#ifdef WIN32 - char curScriptDir[1024]; GetCurrentScriptDir(curScriptDir, 1024); // make sure we can always find scripts that are in the same directory as the current script - const char* filename = lua_isstring(L,1) ? lua_tostring(L,1) : NULL; - extern const char* OpenLuaScript(const char* filename, const char* extraDirToCheck, bool makeSubservient); - const char* errorMsg = OpenLuaScript(filename, curScriptDir, true); - if(errorMsg) - luaL_error(L, errorMsg); -#endif - return 0; -} -/* -DEFINE_LUA_FUNCTION(gens_loadrom, "filename") -{ - struct Temp { Temp() {EnableStopAllLuaScripts(false);} ~Temp() {EnableStopAllLuaScripts(true);}} dontStopScriptsHere; - const char* filename = lua_isstring(L,1) ? lua_tostring(L,1) : NULL; - char curScriptDir[1024]; GetCurrentScriptDir(curScriptDir, 1024); - filename = MakeRomPathAbsolute(filename, curScriptDir); - int result = GensLoadRom(filename); - if(result <= 0) - luaL_error(L, "Failed to load ROM \"%s\": %s", filename, result ? "invalid or unsupported" : "cancelled or not found"); - CallRegisteredLuaFunctions(LUACALL_ONSTART); - return 0; -} -*/ -DEFINE_LUA_FUNCTION(emu_getframecount, "") -{ - lua_pushinteger(L, currFrameCounter); - return 1; -} -DEFINE_LUA_FUNCTION(emu_getlagcount, "") -{ - lua_pushinteger(L, TotalLagFrames); - return 1; -} -DEFINE_LUA_FUNCTION(emu_lagged, "") -{ - lua_pushboolean(L, LagFrameFlag); - return 1; -}/* -DEFINE_LUA_FUNCTION(gens_emulating, "") -{ - lua_pushboolean(L, Genesis_Started||SegaCD_Started||_32X_Started); - return 1; -} -DEFINE_LUA_FUNCTION(gens_atframeboundary, "") -{ - lua_pushboolean(L, !Inside_Frame); - return 1; -}*/ -DEFINE_LUA_FUNCTION(movie_getlength, "") -{ - lua_pushinteger(L, currMovieData.records.size()); - return 1; -} -DEFINE_LUA_FUNCTION(movie_isactive, "") -{ - if(movieMode != MOVIEMODE_INACTIVE); - lua_pushboolean(L, true); - return 1; -} -DEFINE_LUA_FUNCTION(movie_rerecordcount, "") -{ - lua_pushinteger(L, currMovieData.rerecordCount); - return 1; -}/* -DEFINE_LUA_FUNCTION(movie_setrerecordcount, "") -{ - MainMovie.NbRerecords = luaL_checkinteger(L, 1); - return 0; -}*/ -DEFINE_LUA_FUNCTION(emu_rerecordcounting, "[enabled]") -{ - LuaContextInfo& info = GetCurrentInfo(); - if(lua_gettop(L) == 0) - { - // if no arguments given, return the current value - lua_pushboolean(L, !info.rerecordCountingDisabled); - return 1; - } - else - { - // set rerecord disabling - info.rerecordCountingDisabled = !lua_toboolean(L,1); - return 0; - } -} -DEFINE_LUA_FUNCTION(movie_getreadonly, "") -{ - lua_pushboolean(L, movie_readonly); - return 1; -} -DEFINE_LUA_FUNCTION(movie_setreadonly, "readonly") -{ - int readonly = lua_toboolean(L,1) ? 1 : 0; - if(!movie_readonly) - movie_readonly = true; - else - movie_readonly = false; -// else if(!movie_readonly) -// luaL_error(L, "movie.setreadonly failed: write permission denied"); - - return 0; -} -DEFINE_LUA_FUNCTION(movie_isrecording, "") -{ - lua_pushboolean(L, movieMode == MOVIEMODE_RECORD); - return 1; -} -DEFINE_LUA_FUNCTION(movie_isplaying, "") -{ - lua_pushboolean(L, movieMode == MOVIEMODE_PLAY); - return 1; -} -DEFINE_LUA_FUNCTION(movie_getmode, "") -{ - switch(movieMode) - { - case MOVIEMODE_PLAY: - lua_pushstring(L, "playback"); - break; - case MOVIEMODE_RECORD: - lua_pushstring(L, "record"); - break; - case MOVIEMODE_INACTIVE: - lua_pushstring(L, "inactive"); - break; - default: - lua_pushnil(L); - break; - } - return 1; -} -DEFINE_LUA_FUNCTION(movie_getname, "") -{ - extern char curMovieFilename[512]; - lua_pushstring(L, curMovieFilename); - return 1; -} -// movie.play() -- plays a movie of the user's choice -// movie.play(filename) -- starts playing a particular movie -// throws an error (with a description) if for whatever reason the movie couldn't be played -DEFINE_LUA_FUNCTION(movie_play, "[filename]") -{ - const char* filename = lua_isstring(L,1) ? lua_tostring(L,1) : NULL; - FCEUI_LoadMovie(filename, true, false, 0); -// const char* errorMsg = -// if(errorMsg) -// luaL_error(L, errorMsg); - return 0; -} /* -DEFINE_LUA_FUNCTION(movie_replay, "") -{ - if(MainMovie.File) - GensReplayMovie(); - else - luaL_error(L, "it is invalid to call movie.replay when no movie open."); - return 0; -} */ -DEFINE_LUA_FUNCTION(movie_close, "") -{ - - FCEUI_StopMovie(); - return 0; -} - -DEFINE_LUA_FUNCTION(sound_clear, "") -{ -// Clear_Sound_Buffer(); - return 0; -} - -#ifdef _WIN32 -const char* s_keyToName[256] = -{ - NULL, - "leftclick", - "rightclick", - NULL, - "middleclick", - NULL, - NULL, - NULL, - "backspace", - "tab", - NULL, - NULL, - NULL, - "enter", - NULL, - NULL, - "shift", // 0x10 - "control", - "alt", - "pause", - "capslock", - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - "escape", - NULL, - NULL, - NULL, - NULL, - "space", // 0x20 - "pageup", - "pagedown", - "end", - "home", - "left", - "up", - "right", - "down", - NULL, - NULL, - NULL, - NULL, - "insert", - "delete", - NULL, - "0","1","2","3","4","5","6","7","8","9", - NULL, NULL, NULL, NULL, NULL, NULL, NULL, - "A","B","C","D","E","F","G","H","I","J", - "K","L","M","N","O","P","Q","R","S","T", - "U","V","W","X","Y","Z", - NULL, - NULL, - NULL, - NULL, - NULL, - "numpad0","numpad1","numpad2","numpad3","numpad4","numpad5","numpad6","numpad7","numpad8","numpad9", - "numpad*","numpad+", - NULL, - "numpad-","numpad.","numpad/", - "F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12", - "F13","F14","F15","F16","F17","F18","F19","F20","F21","F22","F23","F24", - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - "numlock", - "scrolllock", - NULL, // 0x92 - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, // 0xB9 - "semicolon", - "plus", - "comma", - "minus", - "period", - "slash", - "tilde", - NULL, // 0xC1 - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, // 0xDA - "leftbracket", - "backslash", - "rightbracket", - "quote", -}; -#endif - - -// input.get() -// takes no input, returns a lua table of entries representing the current input state, -// independent of the joypad buttons the emulated game thinks are pressed -// for example: -// if the user is holding the W key and the left mouse button -// and has the mouse at the bottom-right corner of the game screen, -// then this would return {W=true, leftclick=true, xmouse=319, ymouse=223} -DEFINE_LUA_FUNCTION(input_getcurrentinputstatus, "") -{ - lua_newtable(L); - -#ifdef _WIN32 - // keyboard and mouse button status - { - int BackgroundInput = 0;//TODO - - unsigned char keys [256]; - if(!BackgroundInput) - { - if(GetKeyboardState(keys)) - { - for(int i = 1; i < 255; i++) - { - int mask = (i == VK_CAPITAL || i == VK_NUMLOCK || i == VK_SCROLL) ? 0x01 : 0x80; - if(keys[i] & mask) - { - const char* name = s_keyToName[i]; - if(name) - { - lua_pushboolean(L, true); - lua_setfield(L, -2, name); - } - } - } - } - } - else // use a slightly different method that will detect background input: - { - for(int i = 1; i < 255; i++) - { - const char* name = s_keyToName[i]; - if(name) - { - int active; - if(i == VK_CAPITAL || i == VK_NUMLOCK || i == VK_SCROLL) - active = GetKeyState(i) & 0x01; - else - active = GetAsyncKeyState(i) & 0x8000; - if(active) - { - lua_pushboolean(L, true); - lua_setfield(L, -2, name); - } - } - } - } - } - // mouse position in game screen pixel coordinates - { -/* POINT point; - RECT rect, srcRectUnused; - float xRatioUnused, yRatioUnused; - int depUnused; - GetCursorPos(&point); - ScreenToClient(MainWindow->getHWnd(), &point); - GetClientRect(MainWindow->getHWnd(), &rect); - void CalculateDrawArea(int Render_Mode, RECT& RectDest, RECT& RectSrc, float& Ratio_X, float& Ratio_Y, int& Dep); - CalculateDrawArea(Full_Screen ? Render_FS : Render_W, rect, srcRectUnused, xRatioUnused, yRatioUnused, depUnused); - int xres = ((VDP_Reg.Set4 & 0x1) || Debug || !Game || !FrameCount) ? 320 : 256; - int yres = ((VDP_Reg.Set2 & 0x8) && !(Debug || !Game || !FrameCount)) ? 240 : 224; - int x = ((point.x - rect.left) * xres) / max(1, rect.right - rect.left); - int y = ((point.y - rect.top) * yres) / max(1, rect.bottom - rect.top);*/ - int x = 0, y = 0; - lua_pushinteger(L, x); - lua_setfield(L, -2, "xmouse"); - lua_pushinteger(L, y); - lua_setfield(L, -2, "ymouse"); - } -#else - // NYI (well, return an empty table) -#endif - - return 1; -} - - -// resets our "worry" counter of the Lua state -int dontworry(LuaContextInfo& info) -{ - if(info.stopWorrying) - { - info.stopWorrying = false; - if(info.worryCount) - indicateBusy(info.L, false); - } - info.worryCount = 0; - return 0; -} - -//start placeholder drawing funcs--------------------------------------------------- -//TODO a real drawing lib - -// I'm going to use this a lot in here -#define swap(T, one, two) { \ - T temp = one; \ - one = two; \ - two = temp; \ -} - - -// gui.drawbox(x1, y1, x2, y2, colour) -static int gui_box(lua_State *L) { - - int x1,y1,x2,y2; - uint8 colour; - int i; - - x1 = luaL_checkinteger(L,1); - y1 = luaL_checkinteger(L,2); - x2 = luaL_checkinteger(L,3); - y2 = luaL_checkinteger(L,4); -// y1 += FSettings.FirstSLine; -// y2 += FSettings.FirstSLine; -// colour = gui_getcolour(L,5); - -// if (x1 < 0 || x1 >= 256 || y1 < 0 || y1 > 384) -// luaL_error(L,"bad coordinates"); - -// if (x2 < 0 || x2 >= 256 || y2 < 0 || y2 > 384) -// luaL_error(L,"bad coordinates"); - - -// gui_prepare(); - - // For simplicity, we mandate that x1,y1 be the upper-left corner - if (x1 > x2) - swap(int, x1, x2); - if (y1 > y2) - swap(int, y1, y2); - - // top surface - for (i=x1; i <= x2; i++) -// gui_data[y1*256 + i] = colour; - osd->addFixed(i, y1, "%s", "."); - - // bottom surface - for (i=x1; i <= x2; i++) -// gui_data[y2*256 + i] = colour; - osd->addFixed(i, y2, "%s", "."); - - // left surface - for (i=y1; i <= y2; i++) -// gui_data[i*256+x1] = colour; - osd->addFixed(x1, i, "%s", "."); - - // right surface - for (i=y1; i <= y2; i++) -// gui_data[i*256+x2] = colour; - osd->addFixed(x2, i, "%s", "."); - - - return 0; -} - -// gui.drawline(x1,y1,x2,y2,type colour) -static int gui_line(lua_State *L) { - - int x1,y1,x2,y2; - uint8 colour; - x1 = luaL_checkinteger(L,1); - y1 = luaL_checkinteger(L,2); - x2 = luaL_checkinteger(L,3); - y2 = luaL_checkinteger(L,4); -// y1 += FSettings.FirstSLine; -// y2 += FSettings.FirstSLine; -// colour = gui_getcolour(L,5); - -// if (x1 < 0 || x1 >= 256 || y1 < FSettings.FirstSLine || y1 > FSettings.LastSLine) -// luaL_error(L,"bad coordinates"); - -// if (x2 < 0 || x2 >= 256 || y2 < FSettings.FirstSLine || y2 > FSettings.LastSLine) -// luaL_error(L,"bad coordinates"); - -// gui_prepare(); - - - // Horizontal line? - if (y1 == y2) { - if (x1 > x2) - swap(int, x1, x2); - int i; - for (i=x1; i <= x2; i++) - osd->addFixed(i, y1, "%s", "."); -// gui_data[y1*256+i] = colour; - } else if (x1 == x2) { // Vertical line? - if (y1 > y2) - swap(int, y1, y2); - int i; - for (i=y1; i < y2; i++) - osd->addFixed(x1, i, "%s", "."); -// gui_data[i*256+x1] = colour; - } else { - // Some very real slope. We want to increase along the x value, so we swap for that. - if (x1 > x2) { - swap(int, x1, x2); - swap(int, y1, y2); - } - - - double slope = ((double)y2-(double)y1) / ((double)x2-(double)x1); - int myX = x1, myY = y1; - double accum = 0; - - while (myX <= x2) { - // Draw the current pixel - //gui_data[myY*256 + myX] = colour; - osd->addFixed(myX, myY, "%s", "."); - - // If it's above 1, we knock 1 off it and go up 1 pixel - if (accum >= 1.0) { - myY += 1; - accum -= 1.0; - } else if (accum <= -1.0) { - myY -= 1; - accum += 1.0; - } else { - myX += 1; - accum += slope; // Step up - - } - } - - - } - - return 0; -} - -//end placeholder drawing funcs--------------------------------------------------- - -// gui.text(int x, int y, string msg) -// -// Displays the given text on the screen, using the same font and techniques as the -// main HUD. -static int gui_text(lua_State *L) { - const char *msg; - int x, y; - - x = luaL_checkinteger(L,1); - y = luaL_checkinteger(L,2); - msg = luaL_checkstring(L,3); - - osd->addFixed(x, y, "%s", msg); - - return 0; -} - -static int stylus_read(lua_State *L){ - - lua_newtable(L); - - lua_pushinteger(L, nds.touchX >> 4); - lua_setfield(L, -2, "x"); - lua_pushinteger(L, nds.touchY >> 4); - lua_setfield(L, -2, "y"); - lua_pushinteger(L, nds.isTouch); - lua_setfield(L, -2, "touch"); - - return 1; -} - -static const struct luaL_reg styluslib [] = -{ - {"read", stylus_read}, - {NULL, NULL} -}; - -static const struct luaL_reg emulib [] = -{ -// {"frameadvance", emu_frameadvance}, -// {"speedmode", emu_speedmode}, -// {"wait", emu_wait}, -// {"pause", emu_pause}, -// {"unpause", emu_unpause}, -// {"emulateframe", emu_emulateframe}, - //{"emulateframefastnoskipping", emu_emulateframefastnoskipping}, // removed from library because probably nobody would notice the difference from emu_emulateframe -// {"emulateframefast", emu_emulateframefast}, -// {"emulateframeinvisible", emu_emulateframeinvisible}, -// {"redraw", emu_redraw}, - {"framecount", emu_getframecount}, - {"lagcount", emu_getlagcount}, - {"lagged", emu_lagged}, -// {"emulating", emu_emulating}, -// {"atframeboundary", emu_atframeboundary}, - {"registerbefore", emu_registerbefore}, - {"registerafter", emu_registerafter}, -// {"registerstart", emu_registerstart}, - {"registerexit", emu_registerexit}, - {"persistglobalvariables", emu_persistglobalvariables}, - {"message", emu_message}, - {"print", print}, // sure, why not - {"openscript", emu_openscript}, -// {"loadrom", emu_loadrom}, - // alternative names -// {"openrom", emu_loadrom}, - {NULL, NULL} -}; -static const struct luaL_reg guilib [] = -{ -// {"register", gui_register}, - {"text", gui_text}, - {"box", gui_box}, - {"line", gui_line}, -// {"pixel", gui_pixel}, -// {"getpixel", gui_getpixel}, -// {"opacity", gui_setopacity}, -// {"transparency", gui_settransparency}, - {"popup", gui_popup}, - {"parsecolor", gui_parsecolor}, -// {"gdscreenshot", gui_gdscreenshot}, -// {"gdoverlay", gui_gdoverlay}, -// {"redraw", emu_redraw}, // some people might think of this as more of a GUI function - // alternative names - {"drawtext", gui_text}, - {"drawbox", gui_box}, - {"drawline", gui_line}, -// {"drawpixel", gui_pixel}, -// {"setpixel", gui_pixel}, -// {"writepixel", gui_pixel}, -// {"readpixel", gui_getpixel}, -// {"rect", gui_box}, -// {"drawrect", gui_box}, -// {"drawimage", gui_gdoverlay}, -// {"image", gui_gdoverlay}, - {NULL, NULL} -}; -static const struct luaL_reg statelib [] = -{ -// {"create", state_create}, -// {"save", state_save}, -// {"load", state_load}, -// {"loadscriptdata", state_loadscriptdata}, -// {"savescriptdata", state_savescriptdata}, - {"registersave", state_registersave}, - {"registerload", state_registerload}, - {NULL, NULL} -}; -static const struct luaL_reg memorylib [] = -{ - {"readbyte", memory_readbyte}, - {"readbytesigned", memory_readbytesigned}, - {"readword", memory_readword}, - {"readwordsigned", memory_readwordsigned}, - {"readdword", memory_readdword}, - {"readdwordsigned", memory_readdwordsigned}, - {"readbyterange", memory_readbyterange}, - {"writebyte", memory_writebyte}, - {"writeword", memory_writeword}, - {"writedword", memory_writedword}, -// {"isvalid", memory_isvalid}, - {"getregister", memory_getregister}, - {"setregister", memory_setregister}, - // alternate naming scheme for word and double-word and unsigned - {"readbyteunsigned", memory_readbyte}, - {"readwordunsigned", memory_readword}, - {"readdwordunsigned", memory_readdword}, - {"readshort", memory_readword}, - {"readshortunsigned", memory_readword}, - {"readshortsigned", memory_readwordsigned}, - {"readlong", memory_readdword}, - {"readlongunsigned", memory_readdword}, - {"readlongsigned", memory_readdwordsigned}, - {"writeshort", memory_writeword}, - {"writelong", memory_writedword}, - - // memory hooks -// {"registerwrite", memory_registerwrite}, -// {"registerread", memory_registerread}, -// {"registerexec", memory_registerexec}, - // alternate names -// {"register", memory_registerwrite}, -// {"registerrun", memory_registerexec}, -// {"registerexecute", memory_registerexec}, - - {NULL, NULL} -}; -static const struct luaL_reg joylib [] = -{ - {"get", joy_get}, -// {"getdown", joy_getdown}, -// {"getup", joy_getup}, -// {"peek", joy_peek}, -// {"peekdown", joy_peekdown}, -// {"peekup", joy_peekup}, -// {"set", joy_set}, - // alternative names - {"read", joy_get}, -// {"write", joy_set}, -// {"readdown", joy_getdown}, -// {"readup", joy_getup}, - {NULL, NULL} -}; -static const struct luaL_reg inputlib [] = -{ - {"get", input_getcurrentinputstatus}, - {"registerhotkey", input_registerhotkey}, - {"popup", input_popup}, - // alternative names - {"read", input_getcurrentinputstatus}, - {NULL, NULL} -}; -static const struct luaL_reg movielib [] = -{ - {"active", movie_isactive}, - {"recording", movie_isrecording}, - {"playing", movie_isplaying}, - {"mode", movie_getmode}, - - {"length", movie_getlength}, - {"name", movie_getname}, - {"rerecordcount", movie_rerecordcount}, -// {"setrerecordcount", movie_setrerecordcount}, - - {"rerecordcounting", emu_rerecordcounting}, - {"readonly", movie_getreadonly}, - {"setreadonly", movie_setreadonly}, - {"framecount", emu_getframecount}, // for those familiar with other emulators that have movie.framecount() instead of emulatorname.framecount() - - {"play", movie_play}, -// {"replay", movie_replay}, - {"stop", movie_close}, - - // alternative names - {"open", movie_play}, - {"close", movie_close}, - {"getname", movie_getname}, - {"playback", movie_play}, - {"getreadonly", movie_getreadonly}, - {NULL, NULL} -}; -static const struct luaL_reg soundlib [] = -{ -// {"clear", sound_clear}, - {NULL, NULL} -}; - -static const struct CFuncInfo -{ - const char* library; - const char* name; - const char* args; - bool registry; -} -cFuncInfo [] = // this info is stored here to avoid having to change all of Lua's libraries to use something like DEFINE_LUA_FUNCTION -{ - {LUA_STRLIBNAME, "byte", "str[,start[,end]]"}, - {LUA_STRLIBNAME, "char", "...[bytes]"}, - {LUA_STRLIBNAME, "dump", "func"}, - {LUA_STRLIBNAME, "find", "str,pattern[,init[,plain]]"}, - {LUA_STRLIBNAME, "format", "formatstring,..."}, - {LUA_STRLIBNAME, "gfind", "!deprecated!"}, - {LUA_STRLIBNAME, "gmatch", "str,pattern"}, - {LUA_STRLIBNAME, "gsub", "str,pattern,repl[,n]"}, - {LUA_STRLIBNAME, "len", "str"}, - {LUA_STRLIBNAME, "lower", "str"}, - {LUA_STRLIBNAME, "match", "str,pattern[,init]"}, - {LUA_STRLIBNAME, "rep", "str,n"}, - {LUA_STRLIBNAME, "reverse", "str"}, - {LUA_STRLIBNAME, "sub", "str,start[,end]"}, - {LUA_STRLIBNAME, "upper", "str"}, - {NULL, "module", "name[,...]"}, - {NULL, "require", "modname"}, - {LUA_LOADLIBNAME, "loadlib", "libname,funcname"}, - {LUA_LOADLIBNAME, "seeall", "module"}, - {LUA_COLIBNAME, "create", "func"}, - {LUA_COLIBNAME, "resume", "co[,val1,...]"}, - {LUA_COLIBNAME, "running", ""}, - {LUA_COLIBNAME, "status", "co"}, - {LUA_COLIBNAME, "wrap", "func"}, - {LUA_COLIBNAME, "yield", "..."}, - {NULL, "assert", "cond[,message]"}, - {NULL, "collectgarbage", "opt[,arg]"}, - {NULL, "gcinfo", ""}, - {NULL, "dofile", "filename"}, - {NULL, "error", "message[,level]"}, - {NULL, "getfenv", "[level_or_func]"}, - {NULL, "getmetatable", "object"}, - {NULL, "ipairs", "arraytable"}, - {NULL, "load", "func[,chunkname]"}, - {NULL, "loadfile", "[filename]"}, - {NULL, "loadstring", "str[,chunkname]"}, - {NULL, "next", "table[,index]"}, - {NULL, "pairs", "table"}, - {NULL, "pcall", "func,arg1,..."}, - {NULL, "rawequal", "v1,v2"}, - {NULL, "rawget", "table,index"}, - {NULL, "rawset", "table,index,value"}, - {NULL, "select", "index,..."}, - {NULL, "setfenv", "level_or_func,envtable"}, - {NULL, "setmetatable", "table,metatable"}, - {NULL, "tonumber", "str_or_num[,base]"}, - {NULL, "type", "obj"}, - {NULL, "unpack", "list[,i=1[,j=#list]]"}, - {NULL, "xpcall", "func,errhandler"}, - {NULL, "newproxy", "hasmeta"}, - {LUA_MATHLIBNAME, "abs", "x"}, - {LUA_MATHLIBNAME, "acos", "x"}, - {LUA_MATHLIBNAME, "asin", "x"}, - {LUA_MATHLIBNAME, "atan", "x"}, - {LUA_MATHLIBNAME, "atan2", "y,x"}, - {LUA_MATHLIBNAME, "ceil", "x"}, - {LUA_MATHLIBNAME, "cos", "rads"}, - {LUA_MATHLIBNAME, "cosh", "x"}, - {LUA_MATHLIBNAME, "deg", "rads"}, - {LUA_MATHLIBNAME, "exp", "x"}, - {LUA_MATHLIBNAME, "floor", "x"}, - {LUA_MATHLIBNAME, "fmod", "x,y"}, - {LUA_MATHLIBNAME, "frexp", "x"}, - {LUA_MATHLIBNAME, "ldexp", "m,e"}, - {LUA_MATHLIBNAME, "log", "x"}, - {LUA_MATHLIBNAME, "log10", "x"}, - {LUA_MATHLIBNAME, "max", "x,..."}, - {LUA_MATHLIBNAME, "min", "x,..."}, - {LUA_MATHLIBNAME, "modf", "x"}, - {LUA_MATHLIBNAME, "pow", "x,y"}, - {LUA_MATHLIBNAME, "rad", "degs"}, - {LUA_MATHLIBNAME, "random", "[m[,n]]"}, - {LUA_MATHLIBNAME, "randomseed", "x"}, - {LUA_MATHLIBNAME, "sin", "rads"}, - {LUA_MATHLIBNAME, "sinh", "x"}, - {LUA_MATHLIBNAME, "sqrt", "x"}, - {LUA_MATHLIBNAME, "tan", "rads"}, - {LUA_MATHLIBNAME, "tanh", "x"}, - {LUA_IOLIBNAME, "close", "[file]"}, - {LUA_IOLIBNAME, "flush", ""}, - {LUA_IOLIBNAME, "input", "[file]"}, - {LUA_IOLIBNAME, "lines", "[filename]"}, - {LUA_IOLIBNAME, "open", "filename[,mode=\"r\"]"}, - {LUA_IOLIBNAME, "output", "[file]"}, - {LUA_IOLIBNAME, "popen", "prog,[model]"}, - {LUA_IOLIBNAME, "read", "..."}, - {LUA_IOLIBNAME, "tmpfile", ""}, - {LUA_IOLIBNAME, "type", "obj"}, - {LUA_IOLIBNAME, "write", "..."}, - {LUA_OSLIBNAME, "clock", ""}, - {LUA_OSLIBNAME, "date", "[format[,time]]"}, - {LUA_OSLIBNAME, "difftime", "t2,t1"}, - {LUA_OSLIBNAME, "execute", "[command]"}, - {LUA_OSLIBNAME, "exit", "[code]"}, - {LUA_OSLIBNAME, "getenv", "varname"}, - {LUA_OSLIBNAME, "remove", "filename"}, - {LUA_OSLIBNAME, "rename", "oldname,newname"}, - {LUA_OSLIBNAME, "setlocale", "locale[,category]"}, - {LUA_OSLIBNAME, "time", "[timetable]"}, - {LUA_OSLIBNAME, "tmpname", ""}, - {LUA_DBLIBNAME, "debug", ""}, - {LUA_DBLIBNAME, "getfenv", "o"}, - {LUA_DBLIBNAME, "gethook", "[thread]"}, - {LUA_DBLIBNAME, "getinfo", "[thread,]function[,what]"}, - {LUA_DBLIBNAME, "getlocal", "[thread,]level,local"}, - {LUA_DBLIBNAME, "getmetatable", "[object]"}, - {LUA_DBLIBNAME, "getregistry", ""}, - {LUA_DBLIBNAME, "getupvalue", "func,up"}, - {LUA_DBLIBNAME, "setfenv", "object,table"}, - {LUA_DBLIBNAME, "sethook", "[thread,]hook,mask[,count]"}, - {LUA_DBLIBNAME, "setlocal", "[thread,]level,local,value"}, - {LUA_DBLIBNAME, "setmetatable", "object,table"}, - {LUA_DBLIBNAME, "setupvalue", "func,up,value"}, - {LUA_DBLIBNAME, "traceback", "[thread,][message][,level]"}, - {LUA_TABLIBNAME, "concat", "table[,sep[,i[,j]]]"}, - {LUA_TABLIBNAME, "insert", "table,[pos,]value"}, - {LUA_TABLIBNAME, "maxn", "table"}, - {LUA_TABLIBNAME, "remove", "table[,pos]"}, - {LUA_TABLIBNAME, "sort", "table[,comp]"}, - {LUA_TABLIBNAME, "foreach", "table,func"}, - {LUA_TABLIBNAME, "foreachi", "table,func"}, - {LUA_TABLIBNAME, "getn", "table"}, - {LUA_TABLIBNAME, "maxn", "table"}, - {LUA_TABLIBNAME, "setn", "table,value"}, // I know some of these are obsolete but they should still have argument info if they're exposed to the user - {LUA_FILEHANDLE, "setvbuf", "mode[,size]", true}, - {LUA_FILEHANDLE, "lines", "", true}, - {LUA_FILEHANDLE, "read", "...", true}, - {LUA_FILEHANDLE, "flush", "", true}, - {LUA_FILEHANDLE, "seek", "[whence][,offset]", true}, - {LUA_FILEHANDLE, "write", "...", true}, - {LUA_FILEHANDLE, "__tostring", "obj", true}, - {LUA_FILEHANDLE, "__gc", "", true}, - {"_LOADLIB", "__gc", "", true}, -}; - -void registerLibs(lua_State* L) -{ - luaL_openlibs(L); - - luaL_register(L, "emu", emulib); - luaL_register(L, "gui", guilib); - luaL_register(L, "stylus", styluslib); - luaL_register(L, "savestate", statelib); - luaL_register(L, "memory", memorylib); - luaL_register(L, "joypad", joylib); // for game input - luaL_register(L, "input", inputlib); // for user input - luaL_register(L, "movie", movielib); - luaL_register(L, "sound", soundlib); - - lua_settop(L, 0); // clean the stack, because each call to luaL_register leaves a table on top - - // register a few utility functions outside of libraries (in the global namespace) - lua_register(L, "print", print); - lua_register(L, "tostring", tostring); - lua_register(L, "addressof", addressof); - lua_register(L, "copytable", copytable); - lua_register(L, "AND", bitand); - lua_register(L, "OR", bitor); - lua_register(L, "XOR", bitxor); - lua_register(L, "SHIFT", bitshift); - lua_register(L, "BIT", bitbit); - - // populate s_cFuncInfoMap the first time - static bool once = true; - if(once) - { - once = false; - - for(int i = 0; i < sizeof(cFuncInfo)/sizeof(*cFuncInfo); i++) - { - const CFuncInfo& cfi = cFuncInfo[i]; - if(cfi.registry) - { - lua_getregistry(L); - lua_getfield(L, -1, cfi.library); - lua_remove(L, -2); - lua_getfield(L, -1, cfi.name); - lua_remove(L, -2); - } - else if(cfi.library) - { - lua_getfield(L, LUA_GLOBALSINDEX, cfi.library); - lua_getfield(L, -1, cfi.name); - lua_remove(L, -2); - } - else - { - lua_getfield(L, LUA_GLOBALSINDEX, cfi.name); - } - - lua_CFunction func = lua_tocfunction(L, -1); - s_cFuncInfoMap[func] = cfi.args; - lua_pop(L, 1); - } - - // deal with some stragglers - lua_getfield(L, LUA_GLOBALSINDEX, "package"); - lua_getfield(L, -1, "loaders"); - lua_remove(L, -2); - if(lua_istable(L, -1)) - { - for(int i=1;;i++) - { - lua_rawgeti(L, -1, i); - lua_CFunction func = lua_tocfunction(L, -1); - lua_pop(L,1); - if(!func) - break; - s_cFuncInfoMap[func] = "name"; - } - } - lua_pop(L,1); - } - - // push arrays for storing hook functions in - for(int i = 0; i < LUAMEMHOOK_COUNT; i++) - { - lua_newtable(L); - lua_setfield(L, LUA_REGISTRYINDEX, luaMemHookTypeStrings[i]); - } -} - -void ResetInfo(LuaContextInfo& info) -{ - info.L = NULL; - info.started = false; - info.running = false; - info.returned = false; - info.crashed = false; - info.restart = false; - info.restartLater = false; - info.worryCount = 0; - info.stopWorrying = false; - info.panic = false; - info.ranExit = false; - info.numDeferredGUIFuncs = 0; - info.ranFrameAdvance = false; - info.transparencyModifier = 255; - info.speedMode = SPEEDMODE_NORMAL; - info.guiFuncsNeedDeferring = false; - info.dataSaveKey = 0; - info.dataLoadKey = 0; - info.dataSaveLoadKeySet = false; - info.rerecordCountingDisabled = false; - info.numMemHooks = 0; - info.persistVars.clear(); - info.newDefaultData.ClearRecords(); -} - -void OpenLuaContext(int uid, void(*print)(int uid, const char* str), void(*onstart)(int uid), void(*onstop)(int uid, bool statusOK)) -{ - LuaContextInfo* newInfo = new LuaContextInfo(); - ResetInfo(*newInfo); - newInfo->print = print; - newInfo->onstart = onstart; - newInfo->onstop = onstop; - luaContextInfo[uid] = newInfo; -} - -void RunLuaScriptFile(int uid, const char* filenameCStr) -{ - if(luaContextInfo.find(uid) == luaContextInfo.end()) - return; - StopLuaScript(uid); - - LuaContextInfo& info = *luaContextInfo[uid]; - -#ifdef USE_INFO_STACK - infoStack.insert(infoStack.begin(), &info); - struct Scope { ~Scope(){ infoStack.erase(infoStack.begin()); } } scope; // doing it like this makes sure that the info stack gets cleaned up even if an exception is thrown -#endif - - info.nextFilename = filenameCStr; - - if(info.running) - { - // it's a little complicated, but... the call to luaL_dofile below - // could call a C function that calls this very function again - // additionally, if that happened then the above call to StopLuaScript - // probably couldn't stop the script yet, so instead of continuing, - // we'll set a flag that tells the first call of this function to loop again - // when the script is able to stop safely - info.restart = true; - return; - } - - do - { - std::string filename = info.nextFilename; - - lua_State* L = lua_open(); -#ifndef USE_INFO_STACK - luaStateToContextMap[L] = &info; -#endif - luaStateToUIDMap[L] = uid; - ResetInfo(info); - info.L = L; - info.guiFuncsNeedDeferring = true; - info.lastFilename = filename; - - SetSaveKey(info, FilenameFromPath(filename.c_str())); - info.dataSaveLoadKeySet = false; - - registerLibs(L); - - // register a function to periodically check for inactivity - lua_sethook(L, LuaRescueHook, LUA_MASKCOUNT, HOOKCOUNT); - - // deferred evaluation table - lua_newtable(L); - lua_setfield(L, LUA_REGISTRYINDEX, deferredGUIIDString); - - info.started = true; - RefreshScriptStartedStatus(); - if(info.onstart) - info.onstart(uid); - info.running = true; - RefreshScriptSpeedStatus(); - info.returned = false; - int errorcode = luaL_dofile(L,filename.c_str()); - info.running = false; - RefreshScriptSpeedStatus(); - info.returned = true; - - if (errorcode) - { - info.crashed = true; - if(info.print) - { - info.print(uid, lua_tostring(L,-1)); - info.print(uid, "\r\n"); - } - else - { - fprintf(stderr, "%s\n", lua_tostring(L,-1)); - } - StopLuaScript(uid); - } - else - { -// Show_Genesis_Screen(); - StopScriptIfFinished(uid, true); - } - } while(info.restart); -} - -void StopScriptIfFinished(int uid, bool justReturned) -{ - LuaContextInfo& info = *luaContextInfo[uid]; - if(!info.returned) - return; - - // the script has returned, but it is not necessarily done running - // because it may have registered a function that it expects to keep getting called - // so check if it has any registered functions and stop the script only if it doesn't - - bool keepAlive = (info.numMemHooks != 0); - for(int calltype = 0; calltype < LUACALL_COUNT && !keepAlive; calltype++) - { - lua_State* L = info.L; - if(L) - { - const char* idstring = luaCallIDStrings[calltype]; - lua_getfield(L, LUA_REGISTRYINDEX, idstring); - bool isFunction = lua_isfunction(L, -1); - lua_pop(L, 1); - - if(isFunction) - keepAlive = true; - } - } - - if(keepAlive) - { - if(justReturned) - { - if(info.print) - info.print(uid, "script returned but is still running registered functions\r\n"); - else - fprintf(stderr, "%s\n", "script returned but is still running registered functions"); - } - } - else - { - if(info.print) - info.print(uid, "script finished running\r\n"); - else - fprintf(stderr, "%s\n", "script finished running"); - - StopLuaScript(uid); - } -} - -void RequestAbortLuaScript(int uid, const char* message) -{ - if(luaContextInfo.find(uid) == luaContextInfo.end()) - return; - LuaContextInfo& info = *luaContextInfo[uid]; - lua_State* L = info.L; - if(L) - { - // this probably isn't the right way to do it - // but calling luaL_error here is positively unsafe - // (it seemingly works fine but sometimes corrupts the emulation state in colorful ways) - // and this works pretty well and is definitely safe, so screw it - info.L->hookcount = 1; // run hook function as soon as possible - info.panic = true; // and call luaL_error once we're inside the hook function - if(message) - { - strncpy(info.panicMessage, message, sizeof(info.panicMessage)); - info.panicMessage[sizeof(info.panicMessage)-1] = 0; - } - else - { - // attach file/line info because this is the case where it's most necessary to see that, - // and often it won't be possible for the later luaL_error call to retrieve it otherwise. - // this means sometimes printing multiple file/line numbers if luaL_error does find something, - // but that's fine since more information is probably better anyway. - luaL_where(L,0); // should be 0 and not 1 here to get useful (on force stop) messages - const char* whereString = lua_tostring(L,-1); - snprintf(info.panicMessage, sizeof(info.panicMessage), "%sscript terminated", whereString); - lua_pop(L,1); - } - } -} - -void SetSaveKey(LuaContextInfo& info, const char* key) -{ - info.dataSaveKey = crc32(0, (const unsigned char*)key, strlen(key)); - - if(!info.dataSaveLoadKeySet) - { - info.dataLoadKey = info.dataSaveKey; - info.dataSaveLoadKeySet = true; - } -} -void SetLoadKey(LuaContextInfo& info, const char* key) -{ - info.dataLoadKey = crc32(0, (const unsigned char*)key, strlen(key)); - - if(!info.dataSaveLoadKeySet) - { - info.dataSaveKey = info.dataLoadKey; - info.dataSaveLoadKeySet = true; - } -} - -void HandleCallbackError(lua_State* L, LuaContextInfo& info, int uid, bool stopScript) -{ - info.crashed = true; - if(L->errfunc || L->errorJmp) - luaL_error(L, lua_tostring(L,-1)); - else - { - if(info.print) - { - info.print(uid, lua_tostring(L,-1)); - info.print(uid, "\r\n"); - } - else - { - fprintf(stderr, "%s\n", lua_tostring(L,-1)); - } - if(stopScript) - StopLuaScript(uid); - } -} - -void CallExitFunction(int uid) -{ - LuaContextInfo& info = *luaContextInfo[uid]; - lua_State* L = info.L; - - if(!L) - return; - - dontworry(info); - - // first call the registered exit function if there is one - if(!info.ranExit) - { - info.ranExit = true; - -#ifdef USE_INFO_STACK - infoStack.insert(infoStack.begin(), &info); - struct Scope { ~Scope(){ infoStack.erase(infoStack.begin()); } } scope; -#endif - - lua_settop(L, 0); - lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEXIT]); - - int errorcode = 0; - if (lua_isfunction(L, -1)) - { - bool wasRunning = info.running; - info.running = true; - RefreshScriptSpeedStatus(); - - bool wasPanic = info.panic; - info.panic = false; // otherwise we could barely do anything in the exit function - - errorcode = lua_pcall(L, 0, 0, 0); - - info.panic |= wasPanic; // restore panic - - info.running = wasRunning; - RefreshScriptSpeedStatus(); - } - - // save persisted variable info after the exit function runs (even if it crashed) - { - // gather the final value of the variables we're supposed to persist - LuaSaveData newExitData; - { - int numPersistVars = info.persistVars.size(); - for(int i = 0; i < numPersistVars; i++) - { - const char* varName = info.persistVars[i].c_str(); - lua_getfield(L, LUA_GLOBALSINDEX, varName); - int type = lua_type(L,-1); - unsigned int varNameCRC = crc32(0, (const unsigned char*)varName, strlen(varName)); - newExitData.SaveRecordPartial(uid, varNameCRC, -1); - lua_pop(L,1); - } - } - - char path [1024] = {0}; - char* pathTypeChrPtr = ConstructScriptSaveDataPath(path, 1024, info); - - *pathTypeChrPtr = 'd'; - if(info.newDefaultData.recordList) - { - FILE* defaultsFile = fopen(path, "wb"); - if(defaultsFile) - { - info.newDefaultData.ExportRecords(defaultsFile); - fclose(defaultsFile); - } - } - else unlink(path); - - *pathTypeChrPtr = 'e'; - if(newExitData.recordList) - { - FILE* persistFile = fopen(path, "wb"); - if(persistFile) - { - newExitData.ExportRecords(persistFile); - fclose(persistFile); - } - } - else unlink(path); - } - - if (errorcode) - HandleCallbackError(L,info,uid,false); - - } -} - -void StopLuaScript(int uid) -{ - LuaContextInfo* infoPtr = luaContextInfo[uid]; - if(!infoPtr) - return; - - LuaContextInfo& info = *infoPtr; - - if(info.running) - { - // if it's currently running then we can't stop it now without crashing - // so the best we can do is politely request for it to go kill itself - RequestAbortLuaScript(uid); - return; - } - - lua_State* L = info.L; - if(L) - { - CallExitFunction(uid); - - if(info.onstop) - { - info.stopWorrying = true, info.worryCount++, dontworry(info); // clear "busy" status - info.onstop(uid, !info.crashed); // must happen before closing L and after the exit function, otherwise the final GUI state of the script won't be shown properly or at all - } - - if(info.started) // this check is necessary - { - lua_close(L); -#ifndef USE_INFO_STACK - luaStateToContextMap.erase(L); -#endif - luaStateToUIDMap.erase(L); - info.L = NULL; - info.started = false; - - info.numMemHooks = 0; - for(int i = 0; i < LUAMEMHOOK_COUNT; i++) - CalculateMemHookRegions((LuaMemHookType)i); - } - RefreshScriptStartedStatus(); - } -} - -void CloseLuaContext(int uid) -{ - StopLuaScript(uid); - delete luaContextInfo[uid]; - luaContextInfo.erase(uid); -} - - -// the purpose of this structure is to provide a way of -// QUICKLY determining whether a memory address range has a hook associated with it, -// with a bias toward fast rejection because the majority of addresses will not be hooked. -// (it must not use any part of Lua or perform any per-script operations, -// otherwise it would definitely be too slow.) -// calculating the regions when a hook is added/removed may be slow, -// but this is an intentional tradeoff to obtain a high speed of checking during later execution -struct TieredRegion -{ - template - struct Region - { - struct Island - { - unsigned int start; - unsigned int end; - __forceinline bool Contains(unsigned int address, int size) const { return address < end && address+size > start; } - }; - std::vector islands; - - void Calculate(const std::vector& bytes) - { - islands.clear(); - - unsigned int lastEnd = ~0; - - std::vector::const_iterator iter = bytes.begin(); - std::vector::const_iterator end = bytes.end(); - for(; iter != end; ++iter) - { - unsigned int addr = *iter; - if(addr < lastEnd || addr > lastEnd + (long long)maxGap) - { - islands.push_back(Island()); - islands.back().start = addr; - } - islands.back().end = addr+1; - lastEnd = addr+1; - } - } - - bool Contains(unsigned int address, int size) const - { - std::vector::const_iterator iter = islands.begin(); - std::vector::const_iterator end = islands.end(); - for(; iter != end; ++iter) - if(iter->Contains(address, size)) - return true; - return false; - } - }; - - Region<0xFFFFFFFF> broad; - Region<0x1000> mid; - Region<0> narrow; - - void Calculate(std::vector& bytes) - { - std::sort(bytes.begin(), bytes.end()); - - broad.Calculate(bytes); - mid.Calculate(bytes); - narrow.Calculate(bytes); - } - - TieredRegion() - { - Calculate(std::vector()); - } - - __forceinline int NotEmpty() - { - return broad.islands.size(); - } - - // note: it is illegal to call this if NotEmpty() returns 0 - __forceinline bool Contains(unsigned int address, int size) - { - return broad.islands[0].Contains(address,size) && - mid.Contains(address,size) && - narrow.Contains(address,size); - } -}; -TieredRegion hookedRegions [LUAMEMHOOK_COUNT]; - - -static void CalculateMemHookRegions(LuaMemHookType hookType) -{ - std::vector hookedBytes; - std::map::iterator iter = luaContextInfo.begin(); - std::map::iterator end = luaContextInfo.end(); - while(iter != end) - { - LuaContextInfo& info = *iter->second; - if(info.numMemHooks) - { - lua_State* L = info.L; - if(L) - { - lua_settop(L, 0); - lua_getfield(L, LUA_REGISTRYINDEX, luaMemHookTypeStrings[hookType]); - lua_pushnil(L); - while(lua_next(L, -2)) - { - if(lua_isfunction(L, -1)) - { - unsigned int addr = lua_tointeger(L, -2); - hookedBytes.push_back(addr); - } - lua_pop(L, 1); - } - lua_settop(L, 0); - } - } - ++iter; - } - hookedRegions[hookType].Calculate(hookedBytes); -} - - - - - -static void CallRegisteredLuaMemHook_LuaMatch(unsigned int address, int size, unsigned int value, LuaMemHookType hookType) -{ - std::map::iterator iter = luaContextInfo.begin(); - std::map::iterator end = luaContextInfo.end(); - while(iter != end) - { - LuaContextInfo& info = *iter->second; - if(info.numMemHooks) - { - lua_State* L = info.L; - if(L && !info.panic) - { -#ifdef USE_INFO_STACK - infoStack.insert(infoStack.begin(), &info); - struct Scope { ~Scope(){ infoStack.erase(infoStack.begin()); } } scope; -#endif - lua_settop(L, 0); - lua_getfield(L, LUA_REGISTRYINDEX, luaMemHookTypeStrings[hookType]); - for(int i = address; i != address+size; i++) - { - lua_rawgeti(L, -1, i); - if (lua_isfunction(L, -1)) - { - bool wasRunning = info.running; - info.running = true; - RefreshScriptSpeedStatus(); - lua_pushinteger(L, address); - lua_pushinteger(L, size); - int errorcode = lua_pcall(L, 2, 0, 0); - info.running = wasRunning; - RefreshScriptSpeedStatus(); - if (errorcode) - { - int uid = iter->first; - HandleCallbackError(L,info,uid,true); - } - break; - } - else - { - lua_pop(L,1); - } - } - lua_settop(L, 0); - } - } - ++iter; - } -} -void CallRegisteredLuaMemHook(unsigned int address, int size, unsigned int value, LuaMemHookType hookType) -{ - // performance critical! (called VERY frequently) - // I suggest timing a large number of calls to this function in Release if you change anything in here, - // before and after, because even the most innocent change can make it become 30% to 400% slower. - // a good amount to test is: 100000000 calls with no hook set, and another 100000000 with a hook set. - // (on my system that consistently took 200 ms total in the former case and 350 ms total in the latter case) - if(hookedRegions[hookType].NotEmpty()) - { - if((hookType <= LUAMEMHOOK_EXEC) && (address >= 0xE00000)) - address |= 0xFF0000; // account for mirroring of RAM - if(hookedRegions[hookType].Contains(address, size)) - CallRegisteredLuaMemHook_LuaMatch(address, size, value, hookType); // something has hooked this specific address - } -} - - - -void CallRegisteredLuaFunctions(LuaCallID calltype) -{ - assert((unsigned int)calltype < (unsigned int)LUACALL_COUNT); - const char* idstring = luaCallIDStrings[calltype]; - - std::map::iterator iter = luaContextInfo.begin(); - std::map::iterator end = luaContextInfo.end(); - while(iter != end) - { - int uid = iter->first; - LuaContextInfo& info = *iter->second; - lua_State* L = info.L; - if(L && (!info.panic || calltype == LUACALL_BEFOREEXIT)) - { -#ifdef USE_INFO_STACK - infoStack.insert(infoStack.begin(), &info); - struct Scope { ~Scope(){ infoStack.erase(infoStack.begin()); } } scope; -#endif - // handle deferred GUI function calls and disabling deferring when unnecessary - if(calltype == LUACALL_AFTEREMULATIONGUI || calltype == LUACALL_AFTEREMULATION) - info.guiFuncsNeedDeferring = false; - if(calltype == LUACALL_AFTEREMULATIONGUI) - CallDeferredFunctions(L, deferredGUIIDString); - - lua_settop(L, 0); - lua_getfield(L, LUA_REGISTRYINDEX, idstring); - - if (lua_isfunction(L, -1)) - { - bool wasRunning = info.running; - info.running = true; - RefreshScriptSpeedStatus(); - int errorcode = lua_pcall(L, 0, 0, 0); - info.running = wasRunning; - RefreshScriptSpeedStatus(); - if (errorcode) - HandleCallbackError(L,info,uid,true); - } - else - { - lua_pop(L, 1); - } - - info.guiFuncsNeedDeferring = true; - } - - ++iter; - } -} - -void CallRegisteredLuaSaveFunctions(int savestateNumber, LuaSaveData& saveData) -{ - const char* idstring = luaCallIDStrings[LUACALL_BEFORESAVE]; - - std::map::iterator iter = luaContextInfo.begin(); - std::map::iterator end = luaContextInfo.end(); - while(iter != end) - { - int uid = iter->first; - LuaContextInfo& info = *iter->second; - lua_State* L = info.L; - if(L) - { -#ifdef USE_INFO_STACK - infoStack.insert(infoStack.begin(), &info); - struct Scope { ~Scope(){ infoStack.erase(infoStack.begin()); } } scope; -#endif - - lua_settop(L, 0); - lua_getfield(L, LUA_REGISTRYINDEX, idstring); - - if (lua_isfunction(L, -1)) - { - bool wasRunning = info.running; - info.running = true; - RefreshScriptSpeedStatus(); - lua_pushinteger(L, savestateNumber); - int errorcode = lua_pcall(L, 1, LUA_MULTRET, 0); - info.running = wasRunning; - RefreshScriptSpeedStatus(); - if (errorcode) - HandleCallbackError(L,info,uid,true); - saveData.SaveRecord(uid, info.dataSaveKey); - } - else - { - lua_pop(L, 1); - } - } - - ++iter; - } -} - - -void CallRegisteredLuaLoadFunctions(int savestateNumber, const LuaSaveData& saveData) -{ - const char* idstring = luaCallIDStrings[LUACALL_AFTERLOAD]; - - std::map::iterator iter = luaContextInfo.begin(); - std::map::iterator end = luaContextInfo.end(); - while(iter != end) - { - int uid = iter->first; - LuaContextInfo& info = *iter->second; - lua_State* L = info.L; - if(L) - { -#ifdef USE_INFO_STACK - infoStack.insert(infoStack.begin(), &info); - struct Scope { ~Scope(){ infoStack.erase(infoStack.begin()); } } scope; -#endif - - lua_settop(L, 0); - lua_getfield(L, LUA_REGISTRYINDEX, idstring); - - if (lua_isfunction(L, -1)) - { - bool wasRunning = info.running; - info.running = true; - RefreshScriptSpeedStatus(); - - // since the scriptdata can be very expensive to load - // (e.g. the registered save function returned some huge tables) - // check the number of parameters the registered load function expects - // and don't bother loading the parameters it wouldn't receive anyway - int numParamsExpected = (L->top - 1)->value.gc->cl.l.p->numparams; - if(numParamsExpected) numParamsExpected--; // minus one for the savestate number we always pass in - - int prevGarbage = lua_gc(L, LUA_GCCOUNT, 0); - - lua_pushinteger(L, savestateNumber); - saveData.LoadRecord(uid, info.dataLoadKey, numParamsExpected); - int n = lua_gettop(L) - 1; - - int errorcode = lua_pcall(L, n, 0, 0); - info.running = wasRunning; - RefreshScriptSpeedStatus(); - if (errorcode) - HandleCallbackError(L,info,uid,true); - else - { - int newGarbage = lua_gc(L, LUA_GCCOUNT, 0); - if(newGarbage - prevGarbage > 50) - { - // now seems to be a very good time to run the garbage collector - // it might take a while now but that's better than taking 10 whiles 9 loads from now - lua_gc(L, LUA_GCCOLLECT, 0); - } - } - } - else - { - lua_pop(L, 1); - } - } - - ++iter; - } -} - -static const unsigned char* s_dbg_dataStart = NULL; -static int s_dbg_dataSize = 0; - - -// can't remember what the best way of doing this is... -#if defined(i386) || defined(__i386) || defined(__i386__) || defined(M_I86) || defined(_M_IX86) || defined(_WIN32) - #define IS_LITTLE_ENDIAN -#endif - -// push a value's bytes onto the output stack -template -void PushBinaryItem(T item, std::vector& output) -{ - unsigned char* buf = (unsigned char*)&item; -#ifdef IS_LITTLE_ENDIAN - for(int i = sizeof(T); i; i--) - output.push_back(*buf++); -#else - int vecsize = output.size(); - for(int i = sizeof(T); i; i--) - output.insert(output.begin() + vecsize, *buf++); -#endif -} -// read a value from the byte stream and advance the stream by its size -template -T AdvanceByteStream(const unsigned char*& data, unsigned int& remaining) -{ -#ifdef IS_LITTLE_ENDIAN - T rv = *(T*)data; - data += sizeof(T); -#else - T rv; unsigned char* rvptr = (unsigned char*)&rv; - for(int i = sizeof(T)-1; i>=0; i--) - rvptr[i] = *data++; -#endif - remaining -= sizeof(T); - return rv; -} -// advance the byte stream by a certain size without reading a value -void AdvanceByteStream(const unsigned char*& data, unsigned int& remaining, int amount) -{ - data += amount; - remaining -= amount; -} - -#define LUAEXT_TLONG 30 // 0x1E // 4-byte signed integer -#define LUAEXT_TUSHORT 31 // 0x1F // 2-byte unsigned integer -#define LUAEXT_TSHORT 32 // 0x20 // 2-byte signed integer -#define LUAEXT_TBYTE 33 // 0x21 // 1-byte unsigned integer -#define LUAEXT_TNILS 34 // 0x22 // multiple nils represented by a 4-byte integer (warning: becomes multiple stack entities) -#define LUAEXT_TTABLE 0x40 // 0x40 through 0x4F // tables of different sizes: -#define LUAEXT_BITS_1A 0x01 // size of array part fits in a 1-byte unsigned integer -#define LUAEXT_BITS_2A 0x02 // size of array part fits in a 2-byte unsigned integer -#define LUAEXT_BITS_4A 0x03 // size of array part fits in a 4-byte unsigned integer -#define LUAEXT_BITS_1H 0x04 // size of hash part fits in a 1-byte unsigned integer -#define LUAEXT_BITS_2H 0x08 // size of hash part fits in a 2-byte unsigned integer -#define LUAEXT_BITS_4H 0x0C // size of hash part fits in a 4-byte unsigned integer -#define BITMATCH(x,y) (((x) & (y)) == (y)) - -static void PushNils(std::vector& output, int& nilcount) -{ - int count = nilcount; - nilcount = 0; - - static const int minNilsWorthEncoding = 6; // because a LUAEXT_TNILS entry is 5 bytes - - if(count < minNilsWorthEncoding) - { - for(int i = 0; i < count; i++) - output.push_back(LUA_TNIL); - } - else - { - output.push_back(LUAEXT_TNILS); - PushBinaryItem(count, output); - } -} - - -static void LuaStackToBinaryConverter(lua_State* L, int i, std::vector& output) -{ - int type = lua_type(L, i); - - // the first byte of every serialized item says what Lua type it is - output.push_back(type & 0xFF); - - switch(type) - { - default: - { - //printf("wrote unknown type %d (0x%x)\n", type, type); - //assert(0); - - LuaContextInfo& info = GetCurrentInfo(); - if(info.print) - { - char errmsg [1024]; - sprintf(errmsg, "values of type \"%s\" are not allowed to be returned from registered save functions.\r\n", luaL_typename(L,i)); - info.print(luaStateToUIDMap[L], errmsg); - } - else - { - fprintf(stderr, "values of type \"%s\" are not allowed to be returned from registered save functions.\n", luaL_typename(L,i)); - } - } - break; - case LUA_TNIL: - // no information necessary beyond the type - break; - case LUA_TBOOLEAN: - // serialize as 0 or 1 - output.push_back(lua_toboolean(L,i)); - break; - case LUA_TSTRING: - // serialize as a 0-terminated string of characters - { - const char* str = lua_tostring(L,i); - while(*str) - output.push_back(*str++); - output.push_back('\0'); - } - break; - case LUA_TNUMBER: - { - double num = (double)lua_tonumber(L,i); - INT32 inum = (INT32)lua_tointeger(L,i); - if(num != inum) - { - PushBinaryItem(num, output); - } - else - { - if((inum & ~0xFF) == 0) - type = LUAEXT_TBYTE; - else if((UINT16)(inum & 0xFFFF) == inum) - type = LUAEXT_TUSHORT; - else if((INT16)(inum & 0xFFFF) == inum) - type = LUAEXT_TSHORT; - else - type = LUAEXT_TLONG; - output.back() = type; - switch(type) - { - case LUAEXT_TLONG: - PushBinaryItem(inum, output); - break; - case LUAEXT_TUSHORT: - PushBinaryItem(inum, output); - break; - case LUAEXT_TSHORT: - PushBinaryItem(inum, output); - break; - case LUAEXT_TBYTE: - output.push_back(inum); - break; - } - } - } - break; - case LUA_TTABLE: - // serialize as a type that describes how many bytes are used for storing the counts, - // followed by the number of array entries if any, then the number of hash entries if any, - // then a Lua value per array entry, then a (key,value) pair of Lua values per hashed entry - // note that the structure of table references are not faithfully serialized (yet) - { - int outputTypeIndex = output.size() - 1; - int arraySize = 0; - int hashSize = 0; - - if(lua_checkstack(L, 4) && std::find(s_tableAddressStack.begin(), s_tableAddressStack.end(), lua_topointer(L,i)) == s_tableAddressStack.end()) - { - s_tableAddressStack.push_back(lua_topointer(L,i)); - struct Scope { ~Scope(){ s_tableAddressStack.pop_back(); } } scope; - - bool wasnil = false; - int nilcount = 0; - arraySize = lua_objlen(L, i); - int arrayValIndex = lua_gettop(L) + 1; - for(int j = 1; j <= arraySize; j++) - { - lua_rawgeti(L, i, j); - bool isnil = lua_isnil(L, arrayValIndex); - if(isnil) - nilcount++; - else - { - if(wasnil) - PushNils(output, nilcount); - LuaStackToBinaryConverter(L, arrayValIndex, output); - } - lua_pop(L, 1); - wasnil = isnil; - } - if(wasnil) - PushNils(output, nilcount); - - if(arraySize) - lua_pushinteger(L, arraySize); // before first key - else - lua_pushnil(L); // before first key - - int keyIndex = lua_gettop(L); - int valueIndex = keyIndex + 1; - while(lua_next(L, i)) - { - assert(lua_type(L, keyIndex) && "nil key in Lua table, impossible"); - assert(lua_type(L, valueIndex) && "nil value in Lua table, impossible"); - LuaStackToBinaryConverter(L, keyIndex, output); - LuaStackToBinaryConverter(L, valueIndex, output); - lua_pop(L, 1); - hashSize++; - } - } - - int outputType = LUAEXT_TTABLE; - if(arraySize & 0xFFFF0000) - outputType |= LUAEXT_BITS_4A; - else if(arraySize & 0xFF00) - outputType |= LUAEXT_BITS_2A; - else if(arraySize & 0xFF) - outputType |= LUAEXT_BITS_1A; - if(hashSize & 0xFFFF0000) - outputType |= LUAEXT_BITS_4H; - else if(hashSize & 0xFF00) - outputType |= LUAEXT_BITS_2H; - else if(hashSize & 0xFF) - outputType |= LUAEXT_BITS_1H; - output[outputTypeIndex] = outputType; - - int insertIndex = outputTypeIndex; - if(BITMATCH(outputType,LUAEXT_BITS_4A) || BITMATCH(outputType,LUAEXT_BITS_2A) || BITMATCH(outputType,LUAEXT_BITS_1A)) - output.insert(output.begin() + (++insertIndex), arraySize & 0xFF); - if(BITMATCH(outputType,LUAEXT_BITS_4A) || BITMATCH(outputType,LUAEXT_BITS_2A)) - output.insert(output.begin() + (++insertIndex), (arraySize & 0xFF00) >> 8); - if(BITMATCH(outputType,LUAEXT_BITS_4A)) - output.insert(output.begin() + (++insertIndex), (arraySize & 0x00FF0000) >> 16), - output.insert(output.begin() + (++insertIndex), (arraySize & 0xFF000000) >> 24); - if(BITMATCH(outputType,LUAEXT_BITS_4H) || BITMATCH(outputType,LUAEXT_BITS_2H) || BITMATCH(outputType,LUAEXT_BITS_1H)) - output.insert(output.begin() + (++insertIndex), hashSize & 0xFF); - if(BITMATCH(outputType,LUAEXT_BITS_4H) || BITMATCH(outputType,LUAEXT_BITS_2H)) - output.insert(output.begin() + (++insertIndex), (hashSize & 0xFF00) >> 8); - if(BITMATCH(outputType,LUAEXT_BITS_4H)) - output.insert(output.begin() + (++insertIndex), (hashSize & 0x00FF0000) >> 16), - output.insert(output.begin() + (++insertIndex), (hashSize & 0xFF000000) >> 24); - - } break; - } -} - - -// complements LuaStackToBinaryConverter -void BinaryToLuaStackConverter(lua_State* L, const unsigned char*& data, unsigned int& remaining) -{ - assert(s_dbg_dataSize - (data - s_dbg_dataStart) == remaining); - - unsigned char type = AdvanceByteStream(data, remaining); - - switch(type) - { - default: - { - //printf("read unknown type %d (0x%x)\n", type, type); - //assert(0); - - LuaContextInfo& info = GetCurrentInfo(); - if(info.print) - { - char errmsg [1024]; - if(type <= 10 && type != LUA_TTABLE) - sprintf(errmsg, "values of type \"%s\" are not allowed to be loaded into registered load functions. The save state's Lua save data file might be corrupted.\r\n", lua_typename(L,type)); - else - sprintf(errmsg, "The save state's Lua save data file seems to be corrupted.\r\n"); - info.print(luaStateToUIDMap[L], errmsg); - } - else - { - if(type <= 10 && type != LUA_TTABLE) - fprintf(stderr, "values of type \"%s\" are not allowed to be loaded into registered load functions. The save state's Lua save data file might be corrupted.\n", lua_typename(L,type)); - else - fprintf(stderr, "The save state's Lua save data file seems to be corrupted.\n"); - } - } - break; - case LUA_TNIL: - lua_pushnil(L); - break; - case LUA_TBOOLEAN: - lua_pushboolean(L, AdvanceByteStream(data, remaining)); - break; - case LUA_TSTRING: - lua_pushstring(L, (const char*)data); - AdvanceByteStream(data, remaining, strlen((const char*)data) + 1); - break; - case LUA_TNUMBER: - lua_pushnumber(L, AdvanceByteStream(data, remaining)); - break; - case LUAEXT_TLONG: - lua_pushinteger(L, AdvanceByteStream(data, remaining)); - break; - case LUAEXT_TUSHORT: - lua_pushinteger(L, AdvanceByteStream(data, remaining)); - break; - case LUAEXT_TSHORT: - lua_pushinteger(L, AdvanceByteStream(data, remaining)); - break; - case LUAEXT_TBYTE: - lua_pushinteger(L, AdvanceByteStream(data, remaining)); - break; - case LUAEXT_TTABLE: - case LUAEXT_TTABLE | LUAEXT_BITS_1A: - case LUAEXT_TTABLE | LUAEXT_BITS_2A: - case LUAEXT_TTABLE | LUAEXT_BITS_4A: - case LUAEXT_TTABLE | LUAEXT_BITS_1H: - case LUAEXT_TTABLE | LUAEXT_BITS_2H: - case LUAEXT_TTABLE | LUAEXT_BITS_4H: - case LUAEXT_TTABLE | LUAEXT_BITS_1A | LUAEXT_BITS_1H: - case LUAEXT_TTABLE | LUAEXT_BITS_2A | LUAEXT_BITS_1H: - case LUAEXT_TTABLE | LUAEXT_BITS_4A | LUAEXT_BITS_1H: - case LUAEXT_TTABLE | LUAEXT_BITS_1A | LUAEXT_BITS_2H: - case LUAEXT_TTABLE | LUAEXT_BITS_2A | LUAEXT_BITS_2H: - case LUAEXT_TTABLE | LUAEXT_BITS_4A | LUAEXT_BITS_2H: - case LUAEXT_TTABLE | LUAEXT_BITS_1A | LUAEXT_BITS_4H: - case LUAEXT_TTABLE | LUAEXT_BITS_2A | LUAEXT_BITS_4H: - case LUAEXT_TTABLE | LUAEXT_BITS_4A | LUAEXT_BITS_4H: - { - unsigned int arraySize = 0; - if(BITMATCH(type,LUAEXT_BITS_4A) || BITMATCH(type,LUAEXT_BITS_2A) || BITMATCH(type,LUAEXT_BITS_1A)) - arraySize |= AdvanceByteStream(data, remaining); - if(BITMATCH(type,LUAEXT_BITS_4A) || BITMATCH(type,LUAEXT_BITS_2A)) - arraySize |= ((UINT16)AdvanceByteStream(data, remaining)) << 8; - if(BITMATCH(type,LUAEXT_BITS_4A)) - arraySize |= ((UINT32)AdvanceByteStream(data, remaining)) << 16, - arraySize |= ((UINT32)AdvanceByteStream(data, remaining)) << 24; - - unsigned int hashSize = 0; - if(BITMATCH(type,LUAEXT_BITS_4H) || BITMATCH(type,LUAEXT_BITS_2H) || BITMATCH(type,LUAEXT_BITS_1H)) - hashSize |= AdvanceByteStream(data, remaining); - if(BITMATCH(type,LUAEXT_BITS_4H) || BITMATCH(type,LUAEXT_BITS_2H)) - hashSize |= ((UINT16)AdvanceByteStream(data, remaining)) << 8; - if(BITMATCH(type,LUAEXT_BITS_4H)) - hashSize |= ((UINT32)AdvanceByteStream(data, remaining)) << 16, - hashSize |= ((UINT32)AdvanceByteStream(data, remaining)) << 24; - - lua_createtable(L, arraySize, hashSize); - - unsigned int n = 1; - while(n <= arraySize) - { - if(*data == LUAEXT_TNILS) - { - AdvanceByteStream(data, remaining, 1); - n += AdvanceByteStream(data, remaining); - } - else - { - BinaryToLuaStackConverter(L, data, remaining); // push value - lua_rawseti(L, -2, n); // table[n] = value - n++; - } - } - - for(unsigned int h = 1; h <= hashSize; h++) - { - BinaryToLuaStackConverter(L, data, remaining); // push key - BinaryToLuaStackConverter(L, data, remaining); // push value - lua_rawset(L, -3); // table[key] = value - } - } - break; - } -} - -static const unsigned char luaBinaryMajorVersion = 9; -static const unsigned char luaBinaryMinorVersion = 1; - -unsigned char* LuaStackToBinary(lua_State* L, unsigned int& size) -{ - int n = lua_gettop(L); - if(n == 0) - return NULL; - - std::vector output; - output.push_back(luaBinaryMajorVersion); - output.push_back(luaBinaryMinorVersion); - - for(int i = 1; i <= n; i++) - LuaStackToBinaryConverter(L, i, output); - - unsigned char* rv = new unsigned char [output.size()]; - memcpy(rv, &output.front(), output.size()); - size = output.size(); - return rv; -} - -void BinaryToLuaStack(lua_State* L, const unsigned char* data, unsigned int size, unsigned int itemsToLoad) -{ - unsigned char major = *data++; - unsigned char minor = *data++; - size -= 2; - if(luaBinaryMajorVersion != major || luaBinaryMinorVersion != minor) - return; - - while(size > 0 && itemsToLoad > 0) - { - BinaryToLuaStackConverter(L, data, size); - itemsToLoad--; - } -} - -// saves Lua stack into a record and pops it -void LuaSaveData::SaveRecord(int uid, unsigned int key) -{ - LuaContextInfo& info = *luaContextInfo[uid]; - lua_State* L = info.L; - if(!L) - return; - - Record* cur = new Record(); - cur->key = key; - cur->data = LuaStackToBinary(L, cur->size); - cur->next = NULL; - - lua_settop(L,0); - - if(cur->size <= 0) - { - delete cur; - return; - } - - Record* last = recordList; - while(last && last->next) - last = last->next; - if(last) - last->next = cur; - else - recordList = cur; -} - -// pushes a record's data onto the Lua stack -void LuaSaveData::LoadRecord(int uid, unsigned int key, unsigned int itemsToLoad) const -{ - LuaContextInfo& info = *luaContextInfo[uid]; - lua_State* L = info.L; - if(!L) - return; - - Record* cur = recordList; - while(cur) - { - if(cur->key == key) - { - s_dbg_dataStart = cur->data; - s_dbg_dataSize = cur->size; - BinaryToLuaStack(L, cur->data, cur->size, itemsToLoad); - return; - } - cur = cur->next; - } -} - -// saves part of the Lua stack (at the given index) into a record and does NOT pop anything -void LuaSaveData::SaveRecordPartial(int uid, unsigned int key, int idx) -{ - LuaContextInfo& info = *luaContextInfo[uid]; - lua_State* L = info.L; - if(!L) - return; - - if(idx < 0) - idx += lua_gettop(L)+1; - - Record* cur = new Record(); - cur->key = key; - cur->next = NULL; - - if(idx <= lua_gettop(L)) - { - std::vector output; - output.push_back(luaBinaryMajorVersion); - output.push_back(luaBinaryMinorVersion); - - LuaStackToBinaryConverter(L, idx, output); - - unsigned char* rv = new unsigned char [output.size()]; - memcpy(rv, &output.front(), output.size()); - cur->size = output.size(); - cur->data = rv; - } - - if(cur->size <= 0) - { - delete cur; - return; - } - - Record* last = recordList; - while(last && last->next) - last = last->next; - if(last) - last->next = cur; - else - recordList = cur; -} - -void fwriteint(unsigned int value, FILE* file) -{ - for(int i=0;i<4;i++) - { - int w = value & 0xFF; - fwrite(&w, 1, 1, file); - value >>= 8; - } -} -void freadint(unsigned int& value, FILE* file) -{ - int rv = 0; - for(int i=0;i<4;i++) - { - int r = 0; - fread(&r, 1, 1, file); - rv |= r << (i*8); - } - value = rv; -} - -// writes all records to an already-open file -void LuaSaveData::ExportRecords(void* fileV) const -{ - FILE* file = (FILE*)fileV; - if(!file) - return; - - Record* cur = recordList; - while(cur) - { - fwriteint(cur->key, file); - fwriteint(cur->size, file); - fwrite(cur->data, cur->size, 1, file); - cur = cur->next; - } -} - -// reads records from an already-open file -void LuaSaveData::ImportRecords(void* fileV) -{ - FILE* file = (FILE*)fileV; - if(!file) - return; - - ClearRecords(); - - Record rec; - Record* cur = &rec; - Record* last = NULL; - while(1) - { - freadint(cur->key, file); - freadint(cur->size, file); - - if(feof(file) || ferror(file)) - break; - - cur->data = new unsigned char [cur->size]; - fread(cur->data, cur->size, 1, file); - - Record* next = new Record(); - memcpy(next, cur, sizeof(Record)); - next->next = NULL; - - if(last) - last->next = next; - else - recordList = next; - last = next; - } -} - -void LuaSaveData::ClearRecords() -{ - Record* cur = recordList; - while(cur) - { - Record* del = cur; - cur = cur->next; - - delete[] del->data; - delete del; - } - - recordList = NULL; -} - - - -void DontWorryLua() // everything's going to be OK -{ - std::map::const_iterator iter = luaContextInfo.begin(); - std::map::const_iterator end = luaContextInfo.end(); - while(iter != end) - { - dontworry(*iter->second); - ++iter; - } -} - -void EnableStopAllLuaScripts(bool enable) -{ - g_stopAllScriptsEnabled = enable; -} - -void StopAllLuaScripts() -{ - if(!g_stopAllScriptsEnabled) - return; - - std::map::const_iterator iter = luaContextInfo.begin(); - std::map::const_iterator end = luaContextInfo.end(); - while(iter != end) - { - int uid = iter->first; - LuaContextInfo& info = *iter->second; - bool wasStarted = info.started; - StopLuaScript(uid); - info.restartLater = wasStarted; - ++iter; - } -} - -void RestartAllLuaScripts() -{ - if(!g_stopAllScriptsEnabled) - return; - - std::map::const_iterator iter = luaContextInfo.begin(); - std::map::const_iterator end = luaContextInfo.end(); - while(iter != end) - { - int uid = iter->first; - LuaContextInfo& info = *iter->second; - if(info.restartLater || info.started) - { - info.restartLater = false; - RunLuaScriptFile(uid, info.lastFilename.c_str()); - } - ++iter; - } -} - -// sets anything that needs to depend on the total number of scripts running -void RefreshScriptStartedStatus() -{ - int numScriptsStarted = 0; - - std::map::const_iterator iter = luaContextInfo.begin(); - std::map::const_iterator end = luaContextInfo.end(); - while(iter != end) - { - LuaContextInfo& info = *iter->second; - if(info.started) - numScriptsStarted++; - ++iter; - } - -// frameadvSkipLagForceDisable = (numScriptsStarted != 0); // disable while scripts are running because currently lag skipping makes lua callbacks get called twice per frame advance - g_numScriptsStarted = numScriptsStarted; -} - -// sets anything that needs to depend on speed mode or running status of scripts -void RefreshScriptSpeedStatus() -{ - g_anyScriptsHighSpeed = false; - - std::map::const_iterator iter = luaContextInfo.begin(); - std::map::const_iterator end = luaContextInfo.end(); - while(iter != end) - { - LuaContextInfo& info = *iter->second; - if(info.running) - if(info.speedMode == SPEEDMODE_TURBO || info.speedMode == SPEEDMODE_MAXIMUM) - g_anyScriptsHighSpeed = true; - ++iter; - } -} - diff --git a/desmume/src/lua-engine.h b/desmume/src/lua-engine.h deleted file mode 100644 index 31846b6c3..000000000 --- a/desmume/src/lua-engine.h +++ /dev/null @@ -1,95 +0,0 @@ -#ifndef LUA_SCRIPT_H -#define LUA_SCRIPT_H - - -void OpenLuaContext(int uid, void(*print)(int uid, const char* str) = 0, void(*onstart)(int uid) = 0, void(*onstop)(int uid, bool statusOK) = 0); -void RunLuaScriptFile(int uid, const char* filename); -void StopLuaScript(int uid); -void RequestAbortLuaScript(int uid, const char* message = 0); -void CloseLuaContext(int uid); - -enum LuaCallID -{ - LUACALL_BEFOREEMULATION, - LUACALL_AFTEREMULATION, - LUACALL_AFTEREMULATIONGUI, - LUACALL_BEFOREEXIT, - LUACALL_BEFORESAVE, - LUACALL_AFTERLOAD, - LUACALL_ONSTART, - - LUACALL_SCRIPT_HOTKEY_1, - LUACALL_SCRIPT_HOTKEY_2, - LUACALL_SCRIPT_HOTKEY_3, - LUACALL_SCRIPT_HOTKEY_4, - LUACALL_SCRIPT_HOTKEY_5, - LUACALL_SCRIPT_HOTKEY_6, - LUACALL_SCRIPT_HOTKEY_7, - LUACALL_SCRIPT_HOTKEY_8, - LUACALL_SCRIPT_HOTKEY_9, - LUACALL_SCRIPT_HOTKEY_10, - LUACALL_SCRIPT_HOTKEY_11, - LUACALL_SCRIPT_HOTKEY_12, - LUACALL_SCRIPT_HOTKEY_13, - LUACALL_SCRIPT_HOTKEY_14, - LUACALL_SCRIPT_HOTKEY_15, - LUACALL_SCRIPT_HOTKEY_16, - - LUACALL_COUNT -}; -void CallRegisteredLuaFunctions(LuaCallID calltype); - -enum LuaMemHookType -{ - LUAMEMHOOK_WRITE, - LUAMEMHOOK_READ, - LUAMEMHOOK_EXEC, - LUAMEMHOOK_WRITE_SUB, - LUAMEMHOOK_READ_SUB, - LUAMEMHOOK_EXEC_SUB, - - LUAMEMHOOK_COUNT -}; -void CallRegisteredLuaMemHook(unsigned int address, int size, unsigned int value, LuaMemHookType hookType); - -struct LuaSaveData -{ - LuaSaveData() { recordList = 0; } - ~LuaSaveData() { ClearRecords(); } - - struct Record - { - unsigned int key; // crc32 - unsigned int size; // size of data - unsigned char* data; - Record* next; - }; - - Record* recordList; - - void SaveRecord(int uid, unsigned int key); // saves Lua stack into a record and pops it - void LoadRecord(int uid, unsigned int key, unsigned int itemsToLoad) const; // pushes a record's data onto the Lua stack - void SaveRecordPartial(int uid, unsigned int key, int idx); // saves part of the Lua stack (at the given index) into a record and does NOT pop anything - - void ExportRecords(void* file) const; // writes all records to an already-open file - void ImportRecords(void* file); // reads records from an already-open file - void ClearRecords(); // deletes all record data - -private: - // disallowed, it's dangerous to call this - // (because the memory the destructor deletes isn't refcounted and shouldn't need to be copied) - // so pass LuaSaveDatas by reference and this should never get called - LuaSaveData(const LuaSaveData& copy) {} -}; -void CallRegisteredLuaSaveFunctions(int savestateNumber, LuaSaveData& saveData); -void CallRegisteredLuaLoadFunctions(int savestateNumber, const LuaSaveData& saveData); - -void StopAllLuaScripts(); -void RestartAllLuaScripts(); -void EnableStopAllLuaScripts(bool enable); -void DontWorryLua(); - - - -#endif - diff --git a/desmume/src/windows/7z/7zip.lib b/desmume/src/windows/7z/7zip.lib deleted file mode 100644 index abcc91a6d..000000000 Binary files a/desmume/src/windows/7z/7zip.lib and /dev/null differ diff --git a/desmume/src/windows/7z/7zip.vcproj b/desmume/src/windows/7z/7zip.vcproj deleted file mode 100644 index 6900df317..000000000 --- a/desmume/src/windows/7z/7zip.vcproj +++ /dev/null @@ -1,4045 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/desmume/src/windows/7z/C/7zCrc.c b/desmume/src/windows/7z/C/7zCrc.c deleted file mode 100644 index 92c47de0d..000000000 --- a/desmume/src/windows/7z/C/7zCrc.c +++ /dev/null @@ -1,35 +0,0 @@ -/* 7zCrc.c -- CRC32 calculation -2008-08-05 -Igor Pavlov -Public domain */ - -#include "7zCrc.h" - -#define kCrcPoly 0xEDB88320 -UInt32 g_CrcTable[256]; - -void MY_FAST_CALL CrcGenerateTable(void) -{ - UInt32 i; - for (i = 0; i < 256; i++) - { - UInt32 r = i; - int j; - for (j = 0; j < 8; j++) - r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1)); - g_CrcTable[i] = r; - } -} - -UInt32 MY_FAST_CALL CrcUpdate(UInt32 v, const void *data, size_t size) -{ - const Byte *p = (const Byte *)data; - for (; size > 0 ; size--, p++) - v = CRC_UPDATE_BYTE(v, *p); - return v; -} - -UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size) -{ - return CrcUpdate(CRC_INIT_VAL, data, size) ^ 0xFFFFFFFF; -} diff --git a/desmume/src/windows/7z/C/7zCrc.h b/desmume/src/windows/7z/C/7zCrc.h deleted file mode 100644 index ae230991e..000000000 --- a/desmume/src/windows/7z/C/7zCrc.h +++ /dev/null @@ -1,24 +0,0 @@ -/* 7zCrc.h -- CRC32 calculation -2008-03-13 -Igor Pavlov -Public domain */ - -#ifndef __7Z_CRC_H -#define __7Z_CRC_H - -#include - -#include "Types.h" - -extern UInt32 g_CrcTable[]; - -void MY_FAST_CALL CrcGenerateTable(void); - -#define CRC_INIT_VAL 0xFFFFFFFF -#define CRC_GET_DIGEST(crc) ((crc) ^ 0xFFFFFFFF) -#define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8)) - -UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void *data, size_t size); -UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size); - -#endif diff --git a/desmume/src/windows/7z/C/Aes.c b/desmume/src/windows/7z/C/Aes.c deleted file mode 100644 index 8c185f20b..000000000 --- a/desmume/src/windows/7z/C/Aes.c +++ /dev/null @@ -1,262 +0,0 @@ -/* Aes.c -- AES encryption / decryption -2008-08-05 -Igor Pavlov -Public domain */ - -#include "Aes.h" -#include "CpuArch.h" - -static UInt32 T[256 * 4]; -static Byte Sbox[256] = { - 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, - 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, - 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, - 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, - 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, - 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, - 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, - 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, - 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, - 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, - 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, - 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, - 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, - 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, - 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, - 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16}; - -static UInt32 D[256 * 4]; -static Byte InvS[256]; - -static Byte Rcon[11] = { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 }; - -#define xtime(x) ((((x) << 1) ^ (((x) & 0x80) != 0 ? 0x1B : 0)) & 0xFF) - -#define Ui32(a0, a1, a2, a3) ((UInt32)(a0) | ((UInt32)(a1) << 8) | ((UInt32)(a2) << 16) | ((UInt32)(a3) << 24)) - -#define gb0(x) ( (x) & 0xFF) -#define gb1(x) (((x) >> ( 8)) & 0xFF) -#define gb2(x) (((x) >> (16)) & 0xFF) -#define gb3(x) (((x) >> (24)) & 0xFF) - -void AesGenTables(void) -{ - unsigned i; - for (i = 0; i < 256; i++) - InvS[Sbox[i]] = (Byte)i; - for (i = 0; i < 256; i++) - { - { - UInt32 a1 = Sbox[i]; - UInt32 a2 = xtime(a1); - UInt32 a3 = xtime(a1) ^ a1; - T[ i] = Ui32(a2, a1, a1, a3); - T[0x100 + i] = Ui32(a3, a2, a1, a1); - T[0x200 + i] = Ui32(a1, a3, a2, a1); - T[0x300 + i] = Ui32(a1, a1, a3, a2); - } - { - UInt32 a1 = InvS[i]; - UInt32 a2 = xtime(a1); - UInt32 a4 = xtime(a2); - UInt32 a8 = xtime(a4); - UInt32 a9 = a8 ^ a1; - UInt32 aB = a8 ^ a2 ^ a1; - UInt32 aD = a8 ^ a4 ^ a1; - UInt32 aE = a8 ^ a4 ^ a2; - D[ i] = Ui32(aE, a9, aD, aB); - D[0x100 + i] = Ui32(aB, aE, a9, aD); - D[0x200 + i] = Ui32(aD, aB, aE, a9); - D[0x300 + i] = Ui32(a9, aD, aB, aE); - } - } -} - -#define HT(i, x, s) (T + (x << 8))[gb ## x(s[(i + x) & 3])] -#define HT4(m, i, s, p) m[i] = \ - HT(i, 0, s) ^ \ - HT(i, 1, s) ^ \ - HT(i, 2, s) ^ \ - HT(i, 3, s) ^ w[p + i] -/* such order (2031) in HT16 is for VC6/K8 speed optimization) */ -#define HT16(m, s, p) \ - HT4(m, 2, s, p); \ - HT4(m, 0, s, p); \ - HT4(m, 3, s, p); \ - HT4(m, 1, s, p); \ - -#define FT(i, x) Sbox[gb ## x(m[(i + x) & 3])] -#define FT4(i) dest[i] = Ui32(FT(i, 0), FT(i, 1), FT(i, 2), FT(i, 3)) ^ w[i]; - -#define HD(i, x, s) (D + (x << 8))[gb ## x(s[(i - x) & 3])] -#define HD4(m, i, s, p) m[i] = \ - HD(i, 0, s) ^ \ - HD(i, 1, s) ^ \ - HD(i, 2, s) ^ \ - HD(i, 3, s) ^ w[p + i]; -/* such order (0231) in HD16 is for VC6/K8 speed optimization) */ -#define HD16(m, s, p) \ - HD4(m, 0, s, p); \ - HD4(m, 2, s, p); \ - HD4(m, 3, s, p); \ - HD4(m, 1, s, p); \ - -#define FD(i, x) InvS[gb ## x(m[(i - x) & 3])] -#define FD4(i) dest[i] = Ui32(FD(i, 0), FD(i, 1), FD(i, 2), FD(i, 3)) ^ w[i]; - -void Aes_SetKeyEncode(CAes *p, const Byte *key, unsigned keySize) -{ - unsigned i, wSize; - UInt32 *w; - keySize /= 4; - p->numRounds2 = keySize / 2 + 3; - - wSize = (p->numRounds2 * 2 + 1) * 4; - w = p->rkey; - - for (i = 0; i < keySize; i++, key += 4) - w[i] = Ui32(key[0], key[1], key[2], key[3]); - - for (; i < wSize; i++) - { - UInt32 t = w[i - 1]; - unsigned rem = i % keySize; - if (rem == 0) - t = Ui32(Sbox[gb1(t)] ^ Rcon[i / keySize], Sbox[gb2(t)], Sbox[gb3(t)], Sbox[gb0(t)]); - else if (keySize > 6 && rem == 4) - t = Ui32(Sbox[gb0(t)], Sbox[gb1(t)], Sbox[gb2(t)], Sbox[gb3(t)]); - w[i] = w[i - keySize] ^ t; - } -} - -void Aes_SetKeyDecode(CAes *p, const Byte *key, unsigned keySize) -{ - unsigned i, num; - UInt32 *w; - Aes_SetKeyEncode(p, key, keySize); - num = p->numRounds2 * 8 - 4; - w = p->rkey + 4; - for (i = 0; i < num; i++) - { - UInt32 r = w[i]; - w[i] = - D[ Sbox[gb0(r)]] ^ - D[0x100 + Sbox[gb1(r)]] ^ - D[0x200 + Sbox[gb2(r)]] ^ - D[0x300 + Sbox[gb3(r)]]; - } -} - -static void AesEncode32(UInt32 *dest, const UInt32 *src, const UInt32 *w, unsigned numRounds2) -{ - UInt32 s[4]; - UInt32 m[4]; - s[0] = src[0] ^ w[0]; - s[1] = src[1] ^ w[1]; - s[2] = src[2] ^ w[2]; - s[3] = src[3] ^ w[3]; - w += 4; - for (;;) - { - HT16(m, s, 0); - if (--numRounds2 == 0) - break; - HT16(s, m, 4); - w += 8; - } - w += 4; - FT4(0); FT4(1); FT4(2); FT4(3); -} - -static void AesDecode32(UInt32 *dest, const UInt32 *src, const UInt32 *w, unsigned numRounds2) -{ - UInt32 s[4]; - UInt32 m[4]; - w += numRounds2 * 8; - s[0] = src[0] ^ w[0]; - s[1] = src[1] ^ w[1]; - s[2] = src[2] ^ w[2]; - s[3] = src[3] ^ w[3]; - for (;;) - { - w -= 8; - HD16(m, s, 4); - if (--numRounds2 == 0) - break; - HD16(s, m, 0); - } - FD4(0); FD4(1); FD4(2); FD4(3); -} - -void Aes_Encode32(const CAes *p, UInt32 *dest, const UInt32 *src) -{ - AesEncode32(dest, src, p->rkey, p->numRounds2); -} - -void Aes_Decode32(const CAes *p, UInt32 *dest, const UInt32 *src) -{ - AesDecode32(dest, src, p->rkey, p->numRounds2); -} - -void AesCbc_Init(CAesCbc *p, const Byte *iv) -{ - unsigned i; - for (i = 0; i < 4; i++) - p->prev[i] = GetUi32(iv + i * 4); -} - -SizeT AesCbc_Encode(CAesCbc *p, Byte *data, SizeT size) -{ - SizeT i; - if (size == 0) - return 0; - if (size < AES_BLOCK_SIZE) - return AES_BLOCK_SIZE; - size -= AES_BLOCK_SIZE; - for (i = 0; i <= size; i += AES_BLOCK_SIZE, data += AES_BLOCK_SIZE) - { - p->prev[0] ^= GetUi32(data); - p->prev[1] ^= GetUi32(data + 4); - p->prev[2] ^= GetUi32(data + 8); - p->prev[3] ^= GetUi32(data + 12); - - AesEncode32(p->prev, p->prev, p->aes.rkey, p->aes.numRounds2); - - SetUi32(data, p->prev[0]); - SetUi32(data + 4, p->prev[1]); - SetUi32(data + 8, p->prev[2]); - SetUi32(data + 12, p->prev[3]); - } - return i; -} - -SizeT AesCbc_Decode(CAesCbc *p, Byte *data, SizeT size) -{ - SizeT i; - UInt32 in[4], out[4]; - if (size == 0) - return 0; - if (size < AES_BLOCK_SIZE) - return AES_BLOCK_SIZE; - size -= AES_BLOCK_SIZE; - for (i = 0; i <= size; i += AES_BLOCK_SIZE, data += AES_BLOCK_SIZE) - { - in[0] = GetUi32(data); - in[1] = GetUi32(data + 4); - in[2] = GetUi32(data + 8); - in[3] = GetUi32(data + 12); - - AesDecode32(out, in, p->aes.rkey, p->aes.numRounds2); - - SetUi32(data, p->prev[0] ^ out[0]); - SetUi32(data + 4, p->prev[1] ^ out[1]); - SetUi32(data + 8, p->prev[2] ^ out[2]); - SetUi32(data + 12, p->prev[3] ^ out[3]); - - p->prev[0] = in[0]; - p->prev[1] = in[1]; - p->prev[2] = in[2]; - p->prev[3] = in[3]; - } - return i; -} diff --git a/desmume/src/windows/7z/C/Aes.h b/desmume/src/windows/7z/C/Aes.h deleted file mode 100644 index 98ef0c6ea..000000000 --- a/desmume/src/windows/7z/C/Aes.h +++ /dev/null @@ -1,48 +0,0 @@ -/* Aes.h -- AES encryption / decryption -2008-08-05 -Igor Pavlov -Public domain */ - -#ifndef __AES_H -#define __AES_H - -#include "Types.h" - -#define AES_BLOCK_SIZE 16 - -typedef struct -{ - unsigned numRounds2; /* = numRounds / 2 */ - UInt32 rkey[(14 + 1) * 4]; -} CAes; - -/* Call AesGenTables one time before other AES functions */ -void AesGenTables(void); - -/* keySize = 16 or 24 or 32 (bytes) */ -void Aes_SetKeyEncode(CAes *p, const Byte *key, unsigned keySize); -void Aes_SetKeyDecode(CAes *p, const Byte *key, unsigned keySize); - -/* Aes_Encode32 and Aes_Decode32 functions work with little-endian words. - src and dest are pointers to 4 UInt32 words. - arc and dest can point to same block */ -void Aes_Encode32(const CAes *p, UInt32 *dest, const UInt32 *src); -void Aes_Decode32(const CAes *p, UInt32 *dest, const UInt32 *src); - -typedef struct -{ - UInt32 prev[4]; - CAes aes; -} CAesCbc; - -void AesCbc_Init(CAesCbc *p, const Byte *iv); /* iv size is AES_BLOCK_SIZE */ - -/* AesCbc_Encode and AesCbc_Decode: - if (res <= size): Filter have converted res bytes - if (res > size): Filter have not converted anything. And it needs at - least res = AES_BLOCK_SIZE bytes to convert one block */ - -SizeT AesCbc_Encode(CAesCbc *p, Byte *data, SizeT size); -SizeT AesCbc_Decode(CAesCbc *p, Byte *data, SizeT size); - -#endif diff --git a/desmume/src/windows/7z/C/Alloc.c b/desmume/src/windows/7z/C/Alloc.c deleted file mode 100644 index bb24a772b..000000000 --- a/desmume/src/windows/7z/C/Alloc.c +++ /dev/null @@ -1,127 +0,0 @@ -/* Alloc.c -- Memory allocation functions -2008-09-24 -Igor Pavlov -Public domain */ - -#ifdef _WIN32 -#include -#endif -#include - -#include "Alloc.h" - -/* #define _SZ_ALLOC_DEBUG */ - -/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */ -#ifdef _SZ_ALLOC_DEBUG -#include -int g_allocCount = 0; -int g_allocCountMid = 0; -int g_allocCountBig = 0; -#endif - -void *MyAlloc(size_t size) -{ - if (size == 0) - return 0; - #ifdef _SZ_ALLOC_DEBUG - { - void *p = malloc(size); - fprintf(stderr, "\nAlloc %10d bytes, count = %10d, addr = %8X", size, g_allocCount++, (unsigned)p); - return p; - } - #else - return malloc(size); - #endif -} - -void MyFree(void *address) -{ - #ifdef _SZ_ALLOC_DEBUG - if (address != 0) - fprintf(stderr, "\nFree; count = %10d, addr = %8X", --g_allocCount, (unsigned)address); - #endif - free(address); -} - -#ifdef _WIN32 - -void *MidAlloc(size_t size) -{ - if (size == 0) - return 0; - #ifdef _SZ_ALLOC_DEBUG - fprintf(stderr, "\nAlloc_Mid %10d bytes; count = %10d", size, g_allocCountMid++); - #endif - return VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE); -} - -void MidFree(void *address) -{ - #ifdef _SZ_ALLOC_DEBUG - if (address != 0) - fprintf(stderr, "\nFree_Mid; count = %10d", --g_allocCountMid); - #endif - if (address == 0) - return; - VirtualFree(address, 0, MEM_RELEASE); -} - -#ifndef MEM_LARGE_PAGES -#undef _7ZIP_LARGE_PAGES -#endif - -#ifdef _7ZIP_LARGE_PAGES -SIZE_T g_LargePageSize = 0; -typedef SIZE_T (WINAPI *GetLargePageMinimumP)(); -#endif - -void SetLargePageSize() -{ - #ifdef _7ZIP_LARGE_PAGES - SIZE_T size = 0; - GetLargePageMinimumP largePageMinimum = (GetLargePageMinimumP) - GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetLargePageMinimum"); - if (largePageMinimum == 0) - return; - size = largePageMinimum(); - if (size == 0 || (size & (size - 1)) != 0) - return; - g_LargePageSize = size; - #endif -} - - -void *BigAlloc(size_t size) -{ - if (size == 0) - return 0; - #ifdef _SZ_ALLOC_DEBUG - fprintf(stderr, "\nAlloc_Big %10d bytes; count = %10d", size, g_allocCountBig++); - #endif - - #ifdef _7ZIP_LARGE_PAGES - if (g_LargePageSize != 0 && g_LargePageSize <= (1 << 30) && size >= (1 << 18)) - { - void *res = VirtualAlloc(0, (size + g_LargePageSize - 1) & (~(g_LargePageSize - 1)), - MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE); - if (res != 0) - return res; - } - #endif - return VirtualAlloc(0, size, MEM_COMMIT, PAGE_READWRITE); -} - -void BigFree(void *address) -{ - #ifdef _SZ_ALLOC_DEBUG - if (address != 0) - fprintf(stderr, "\nFree_Big; count = %10d", --g_allocCountBig); - #endif - - if (address == 0) - return; - VirtualFree(address, 0, MEM_RELEASE); -} - -#endif diff --git a/desmume/src/windows/7z/C/Alloc.h b/desmume/src/windows/7z/C/Alloc.h deleted file mode 100644 index a396c6b9e..000000000 --- a/desmume/src/windows/7z/C/Alloc.h +++ /dev/null @@ -1,32 +0,0 @@ -/* Alloc.h -- Memory allocation functions -2008-03-13 -Igor Pavlov -Public domain */ - -#ifndef __COMMON_ALLOC_H -#define __COMMON_ALLOC_H - -#include - -void *MyAlloc(size_t size); -void MyFree(void *address); - -#ifdef _WIN32 - -void SetLargePageSize(); - -void *MidAlloc(size_t size); -void MidFree(void *address); -void *BigAlloc(size_t size); -void BigFree(void *address); - -#else - -#define MidAlloc(size) MyAlloc(size) -#define MidFree(address) MyFree(address) -#define BigAlloc(size) MyAlloc(size) -#define BigFree(address) MyFree(address) - -#endif - -#endif diff --git a/desmume/src/windows/7z/C/Bra.c b/desmume/src/windows/7z/C/Bra.c deleted file mode 100644 index 3b75f0ccb..000000000 --- a/desmume/src/windows/7z/C/Bra.c +++ /dev/null @@ -1,133 +0,0 @@ -/* Bra.c -- Converters for RISC code -2008-10-04 : Igor Pavlov : Public domain */ - -#include "Bra.h" - -SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - SizeT i; - if (size < 4) - return 0; - size -= 4; - ip += 8; - for (i = 0; i <= size; i += 4) - { - if (data[i + 3] == 0xEB) - { - UInt32 dest; - UInt32 src = ((UInt32)data[i + 2] << 16) | ((UInt32)data[i + 1] << 8) | (data[i + 0]); - src <<= 2; - if (encoding) - dest = ip + (UInt32)i + src; - else - dest = src - (ip + (UInt32)i); - dest >>= 2; - data[i + 2] = (Byte)(dest >> 16); - data[i + 1] = (Byte)(dest >> 8); - data[i + 0] = (Byte)dest; - } - } - return i; -} - -SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - SizeT i; - if (size < 4) - return 0; - size -= 4; - ip += 4; - for (i = 0; i <= size; i += 2) - { - if ((data[i + 1] & 0xF8) == 0xF0 && - (data[i + 3] & 0xF8) == 0xF8) - { - UInt32 dest; - UInt32 src = - (((UInt32)data[i + 1] & 0x7) << 19) | - ((UInt32)data[i + 0] << 11) | - (((UInt32)data[i + 3] & 0x7) << 8) | - (data[i + 2]); - - src <<= 1; - if (encoding) - dest = ip + (UInt32)i + src; - else - dest = src - (ip + (UInt32)i); - dest >>= 1; - - data[i + 1] = (Byte)(0xF0 | ((dest >> 19) & 0x7)); - data[i + 0] = (Byte)(dest >> 11); - data[i + 3] = (Byte)(0xF8 | ((dest >> 8) & 0x7)); - data[i + 2] = (Byte)dest; - i += 2; - } - } - return i; -} - -SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - SizeT i; - if (size < 4) - return 0; - size -= 4; - for (i = 0; i <= size; i += 4) - { - if ((data[i] >> 2) == 0x12 && (data[i + 3] & 3) == 1) - { - UInt32 src = ((UInt32)(data[i + 0] & 3) << 24) | - ((UInt32)data[i + 1] << 16) | - ((UInt32)data[i + 2] << 8) | - ((UInt32)data[i + 3] & (~3)); - - UInt32 dest; - if (encoding) - dest = ip + (UInt32)i + src; - else - dest = src - (ip + (UInt32)i); - data[i + 0] = (Byte)(0x48 | ((dest >> 24) & 0x3)); - data[i + 1] = (Byte)(dest >> 16); - data[i + 2] = (Byte)(dest >> 8); - data[i + 3] &= 0x3; - data[i + 3] |= dest; - } - } - return i; -} - -SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - UInt32 i; - if (size < 4) - return 0; - size -= 4; - for (i = 0; i <= size; i += 4) - { - if (data[i] == 0x40 && (data[i + 1] & 0xC0) == 0x00 || - data[i] == 0x7F && (data[i + 1] & 0xC0) == 0xC0) - { - UInt32 src = - ((UInt32)data[i + 0] << 24) | - ((UInt32)data[i + 1] << 16) | - ((UInt32)data[i + 2] << 8) | - ((UInt32)data[i + 3]); - UInt32 dest; - - src <<= 2; - if (encoding) - dest = ip + i + src; - else - dest = src - (ip + i); - dest >>= 2; - - dest = (((0 - ((dest >> 22) & 1)) << 22) & 0x3FFFFFFF) | (dest & 0x3FFFFF) | 0x40000000; - - data[i + 0] = (Byte)(dest >> 24); - data[i + 1] = (Byte)(dest >> 16); - data[i + 2] = (Byte)(dest >> 8); - data[i + 3] = (Byte)dest; - } - } - return i; -} diff --git a/desmume/src/windows/7z/C/Bra.h b/desmume/src/windows/7z/C/Bra.h deleted file mode 100644 index b9018eb99..000000000 --- a/desmume/src/windows/7z/C/Bra.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Bra.h -- Branch converters for executables -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __BRA_H -#define __BRA_H - -#include "Types.h" - -/* -These functions convert relative addresses to absolute addresses -in CALL instructions to increase the compression ratio. - - In: - data - data buffer - size - size of data - ip - current virtual Instruction Pinter (IP) value - state - state variable for x86 converter - encoding - 0 (for decoding), 1 (for encoding) - - Out: - state - state variable for x86 converter - - Returns: - The number of processed bytes. If you call these functions with multiple calls, - you must start next call with first byte after block of processed bytes. - - Type Endian Alignment LookAhead - - x86 little 1 4 - ARMT little 2 2 - ARM little 4 0 - PPC big 4 0 - SPARC big 4 0 - IA64 little 16 0 - - size must be >= Alignment + LookAhead, if it's not last block. - If (size < Alignment + LookAhead), converter returns 0. - - Example: - - UInt32 ip = 0; - for () - { - ; size must be >= Alignment + LookAhead, if it's not last block - SizeT processed = Convert(data, size, ip, 1); - data += processed; - size -= processed; - ip += processed; - } -*/ - -#define x86_Convert_Init(state) { state = 0; } -SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding); -SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); - -#endif diff --git a/desmume/src/windows/7z/C/Bra86.c b/desmume/src/windows/7z/C/Bra86.c deleted file mode 100644 index c3eda016e..000000000 --- a/desmume/src/windows/7z/C/Bra86.c +++ /dev/null @@ -1,85 +0,0 @@ -/* Bra86.c -- Converter for x86 code (BCJ) -2008-10-04 : Igor Pavlov : Public domain */ - -#include "Bra.h" - -#define Test86MSByte(b) ((b) == 0 || (b) == 0xFF) - -const Byte kMaskToAllowedStatus[8] = {1, 1, 1, 0, 1, 0, 0, 0}; -const Byte kMaskToBitNumber[8] = {0, 1, 2, 2, 3, 3, 3, 3}; - -SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding) -{ - SizeT bufferPos = 0, prevPosT; - UInt32 prevMask = *state & 0x7; - if (size < 5) - return 0; - ip += 5; - prevPosT = (SizeT)0 - 1; - - for (;;) - { - Byte *p = data + bufferPos; - Byte *limit = data + size - 4; - for (; p < limit; p++) - if ((*p & 0xFE) == 0xE8) - break; - bufferPos = (SizeT)(p - data); - if (p >= limit) - break; - prevPosT = bufferPos - prevPosT; - if (prevPosT > 3) - prevMask = 0; - else - { - prevMask = (prevMask << ((int)prevPosT - 1)) & 0x7; - if (prevMask != 0) - { - Byte b = p[4 - kMaskToBitNumber[prevMask]]; - if (!kMaskToAllowedStatus[prevMask] || Test86MSByte(b)) - { - prevPosT = bufferPos; - prevMask = ((prevMask << 1) & 0x7) | 1; - bufferPos++; - continue; - } - } - } - prevPosT = bufferPos; - - if (Test86MSByte(p[4])) - { - UInt32 src = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]); - UInt32 dest; - for (;;) - { - Byte b; - int index; - if (encoding) - dest = (ip + (UInt32)bufferPos) + src; - else - dest = src - (ip + (UInt32)bufferPos); - if (prevMask == 0) - break; - index = kMaskToBitNumber[prevMask] * 8; - b = (Byte)((dest >> (24 - index)) & 0xFF); - if (!Test86MSByte(b)) - break; - src = dest ^ ((1 << (32 - index)) - 1); - } - p[4] = (Byte)((~(((dest >> 24) & 1) - 1)) & 0xFF); - p[3] = (Byte)((dest >> 16) & 0xFF); - p[2] = (Byte)((dest >> 8) & 0xFF); - p[1] = (Byte)(dest & 0xFF); - bufferPos += 5; - } - else - { - prevMask = ((prevMask << 1) & 0x7) | 1; - bufferPos++; - } - } - prevPosT = bufferPos - prevPosT; - *state = ((prevPosT > 3) ? 0 : ((prevMask << ((int)prevPosT - 1)) & 0x7)); - return bufferPos; -} diff --git a/desmume/src/windows/7z/C/BraIA64.c b/desmume/src/windows/7z/C/BraIA64.c deleted file mode 100644 index f359f16a3..000000000 --- a/desmume/src/windows/7z/C/BraIA64.c +++ /dev/null @@ -1,67 +0,0 @@ -/* BraIA64.c -- Converter for IA-64 code -2008-10-04 : Igor Pavlov : Public domain */ - -#include "Bra.h" - -static const Byte kBranchTable[32] = -{ - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 4, 4, 6, 6, 0, 0, 7, 7, - 4, 4, 0, 0, 4, 4, 0, 0 -}; - -SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding) -{ - SizeT i; - if (size < 16) - return 0; - size -= 16; - for (i = 0; i <= size; i += 16) - { - UInt32 instrTemplate = data[i] & 0x1F; - UInt32 mask = kBranchTable[instrTemplate]; - UInt32 bitPos = 5; - int slot; - for (slot = 0; slot < 3; slot++, bitPos += 41) - { - UInt32 bytePos, bitRes; - UInt64 instruction, instNorm; - int j; - if (((mask >> slot) & 1) == 0) - continue; - bytePos = (bitPos >> 3); - bitRes = bitPos & 0x7; - instruction = 0; - for (j = 0; j < 6; j++) - instruction += (UInt64)data[i + j + bytePos] << (8 * j); - - instNorm = instruction >> bitRes; - if (((instNorm >> 37) & 0xF) == 0x5 && ((instNorm >> 9) & 0x7) == 0) - { - UInt32 src = (UInt32)((instNorm >> 13) & 0xFFFFF); - UInt32 dest; - src |= ((UInt32)(instNorm >> 36) & 1) << 20; - - src <<= 4; - - if (encoding) - dest = ip + (UInt32)i + src; - else - dest = src - (ip + (UInt32)i); - - dest >>= 4; - - instNorm &= ~((UInt64)(0x8FFFFF) << 13); - instNorm |= ((UInt64)(dest & 0xFFFFF) << 13); - instNorm |= ((UInt64)(dest & 0x100000) << (36 - 20)); - - instruction &= (1 << bitRes) - 1; - instruction |= (instNorm << bitRes); - for (j = 0; j < 6; j++) - data[i + j + bytePos] = (Byte)(instruction >> (8 * j)); - } - } - } - return i; -} diff --git a/desmume/src/windows/7z/C/BwtSort.c b/desmume/src/windows/7z/C/BwtSort.c deleted file mode 100644 index d6b545e83..000000000 --- a/desmume/src/windows/7z/C/BwtSort.c +++ /dev/null @@ -1,516 +0,0 @@ -/* BwtSort.c -- BWT block sorting -2008-08-17 -Igor Pavlov -Public domain */ - -#include "BwtSort.h" -#include "Sort.h" - -/* #define BLOCK_SORT_USE_HEAP_SORT */ - -#define NO_INLINE MY_FAST_CALL - -/* Don't change it !!! */ -#define kNumHashBytes 2 -#define kNumHashValues (1 << (kNumHashBytes * 8)) - -/* kNumRefBitsMax must be < (kNumHashBytes * 8) = 16 */ -#define kNumRefBitsMax 12 - -#define BS_TEMP_SIZE kNumHashValues - -#ifdef BLOCK_SORT_EXTERNAL_FLAGS - -/* 32 Flags in UInt32 word */ -#define kNumFlagsBits 5 -#define kNumFlagsInWord (1 << kNumFlagsBits) -#define kFlagsMask (kNumFlagsInWord - 1) -#define kAllFlags 0xFFFFFFFF - -#else - -#define kNumBitsMax 20 -#define kIndexMask ((1 << kNumBitsMax) - 1) -#define kNumExtraBits (32 - kNumBitsMax) -#define kNumExtra0Bits (kNumExtraBits - 2) -#define kNumExtra0Mask ((1 << kNumExtra0Bits) - 1) - -#define SetFinishedGroupSize(p, size) \ - { *(p) |= ((((size) - 1) & kNumExtra0Mask) << kNumBitsMax); \ - if ((size) > (1 << kNumExtra0Bits)) { \ - *(p) |= 0x40000000; *((p) + 1) |= ((((size) - 1)>> kNumExtra0Bits) << kNumBitsMax); } } \ - -static void SetGroupSize(UInt32 *p, UInt32 size) -{ - if (--size == 0) - return; - *p |= 0x80000000 | ((size & kNumExtra0Mask) << kNumBitsMax); - if (size >= (1 << kNumExtra0Bits)) - { - *p |= 0x40000000; - p[1] |= ((size >> kNumExtra0Bits) << kNumBitsMax); - } -} - -#endif - -/* -SortGroup - is recursive Range-Sort function with HeapSort optimization for small blocks - "range" is not real range. It's only for optimization. -returns: 1 - if there are groups, 0 - no more groups -*/ - -UInt32 NO_INLINE SortGroup(UInt32 BlockSize, UInt32 NumSortedBytes, UInt32 groupOffset, UInt32 groupSize, int NumRefBits, UInt32 *Indices - #ifndef BLOCK_SORT_USE_HEAP_SORT - , UInt32 left, UInt32 range - #endif - ) -{ - UInt32 *ind2 = Indices + groupOffset; - UInt32 *Groups; - if (groupSize <= 1) - { - /* - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetFinishedGroupSize(ind2, 1); - #endif - */ - return 0; - } - Groups = Indices + BlockSize + BS_TEMP_SIZE; - if (groupSize <= ((UInt32)1 << NumRefBits) - #ifndef BLOCK_SORT_USE_HEAP_SORT - && groupSize <= range - #endif - ) - { - UInt32 *temp = Indices + BlockSize; - UInt32 j; - UInt32 mask, thereAreGroups, group, cg; - { - UInt32 gPrev; - UInt32 gRes = 0; - { - UInt32 sp = ind2[0] + NumSortedBytes; - if (sp >= BlockSize) sp -= BlockSize; - gPrev = Groups[sp]; - temp[0] = (gPrev << NumRefBits); - } - - for (j = 1; j < groupSize; j++) - { - UInt32 sp = ind2[j] + NumSortedBytes; - UInt32 g; - if (sp >= BlockSize) sp -= BlockSize; - g = Groups[sp]; - temp[j] = (g << NumRefBits) | j; - gRes |= (gPrev ^ g); - } - if (gRes == 0) - { - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetGroupSize(ind2, groupSize); - #endif - return 1; - } - } - - HeapSort(temp, groupSize); - mask = ((1 << NumRefBits) - 1); - thereAreGroups = 0; - - group = groupOffset; - cg = (temp[0] >> NumRefBits); - temp[0] = ind2[temp[0] & mask]; - - { - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 *Flags = Groups + BlockSize; - #else - UInt32 prevGroupStart = 0; - #endif - - for (j = 1; j < groupSize; j++) - { - UInt32 val = temp[j]; - UInt32 cgCur = (val >> NumRefBits); - - if (cgCur != cg) - { - cg = cgCur; - group = groupOffset + j; - - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - { - UInt32 t = group - 1; - Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask)); - } - #else - SetGroupSize(temp + prevGroupStart, j - prevGroupStart); - prevGroupStart = j; - #endif - } - else - thereAreGroups = 1; - { - UInt32 ind = ind2[val & mask]; - temp[j] = ind; - Groups[ind] = group; - } - } - - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetGroupSize(temp + prevGroupStart, j - prevGroupStart); - #endif - } - - for (j = 0; j < groupSize; j++) - ind2[j] = temp[j]; - return thereAreGroups; - } - - /* Check that all strings are in one group (cannot sort) */ - { - UInt32 group, j; - UInt32 sp = ind2[0] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize; - group = Groups[sp]; - for (j = 1; j < groupSize; j++) - { - sp = ind2[j] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize; - if (Groups[sp] != group) - break; - } - if (j == groupSize) - { - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetGroupSize(ind2, groupSize); - #endif - return 1; - } - } - - #ifndef BLOCK_SORT_USE_HEAP_SORT - { - /* ---------- Range Sort ---------- */ - UInt32 i; - UInt32 mid; - for (;;) - { - UInt32 j; - if (range <= 1) - { - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetGroupSize(ind2, groupSize); - #endif - return 1; - } - mid = left + ((range + 1) >> 1); - j = groupSize; - i = 0; - do - { - UInt32 sp = ind2[i] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize; - if (Groups[sp] >= mid) - { - for (j--; j > i; j--) - { - sp = ind2[j] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize; - if (Groups[sp] < mid) - { - UInt32 temp = ind2[i]; ind2[i] = ind2[j]; ind2[j] = temp; - break; - } - } - if (i >= j) - break; - } - } - while (++i < j); - if (i == 0) - { - range = range - (mid - left); - left = mid; - } - else if (i == groupSize) - range = (mid - left); - else - break; - } - - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - { - UInt32 t = (groupOffset + i - 1); - UInt32 *Flags = Groups + BlockSize; - Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask)); - } - #endif - - { - UInt32 j; - for (j = i; j < groupSize; j++) - Groups[ind2[j]] = groupOffset + i; - } - - { - UInt32 res = SortGroup(BlockSize, NumSortedBytes, groupOffset, i, NumRefBits, Indices, left, mid - left); - return res | SortGroup(BlockSize, NumSortedBytes, groupOffset + i, groupSize - i, NumRefBits, Indices, mid, range - (mid - left)); - } - - } - - #else - - /* ---------- Heap Sort ---------- */ - - { - UInt32 j; - for (j = 0; j < groupSize; j++) - { - UInt32 sp = ind2[j] + NumSortedBytes; if (sp >= BlockSize) sp -= BlockSize; - ind2[j] = sp; - } - - HeapSortRef(ind2, Groups, groupSize); - - /* Write Flags */ - { - UInt32 sp = ind2[0]; - UInt32 group = Groups[sp]; - - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 *Flags = Groups + BlockSize; - #else - UInt32 prevGroupStart = 0; - #endif - - for (j = 1; j < groupSize; j++) - { - sp = ind2[j]; - if (Groups[sp] != group) - { - group = Groups[sp]; - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - { - UInt32 t = groupOffset + j - 1; - Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask)); - } - #else - SetGroupSize(ind2 + prevGroupStart, j - prevGroupStart); - prevGroupStart = j; - #endif - } - } - - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - SetGroupSize(ind2 + prevGroupStart, j - prevGroupStart); - #endif - } - { - /* Write new Groups values and Check that there are groups */ - UInt32 thereAreGroups = 0; - for (j = 0; j < groupSize; j++) - { - UInt32 group = groupOffset + j; - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 subGroupSize = ((ind2[j] & ~0xC0000000) >> kNumBitsMax); - if ((ind2[j] & 0x40000000) != 0) - subGroupSize += ((ind2[j + 1] >> kNumBitsMax) << kNumExtra0Bits); - subGroupSize++; - for (;;) - { - UInt32 original = ind2[j]; - UInt32 sp = original & kIndexMask; - if (sp < NumSortedBytes) sp += BlockSize; sp -= NumSortedBytes; - ind2[j] = sp | (original & ~kIndexMask); - Groups[sp] = group; - if (--subGroupSize == 0) - break; - j++; - thereAreGroups = 1; - } - #else - UInt32 *Flags = Groups + BlockSize; - for (;;) - { - UInt32 sp = ind2[j]; if (sp < NumSortedBytes) sp += BlockSize; sp -= NumSortedBytes; - ind2[j] = sp; - Groups[sp] = group; - if ((Flags[(groupOffset + j) >> kNumFlagsBits] & (1 << ((groupOffset + j) & kFlagsMask))) == 0) - break; - j++; - thereAreGroups = 1; - } - #endif - } - return thereAreGroups; - } - } - #endif -} - -/* conditions: blockSize > 0 */ -UInt32 BlockSort(UInt32 *Indices, const Byte *data, UInt32 blockSize) -{ - UInt32 *counters = Indices + blockSize; - UInt32 i; - UInt32 *Groups; - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 *Flags; - #endif - - /* Radix-Sort for 2 bytes */ - for (i = 0; i < kNumHashValues; i++) - counters[i] = 0; - for (i = 0; i < blockSize - 1; i++) - counters[((UInt32)data[i] << 8) | data[i + 1]]++; - counters[((UInt32)data[i] << 8) | data[0]]++; - - Groups = counters + BS_TEMP_SIZE; - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - Flags = Groups + blockSize; - { - UInt32 numWords = (blockSize + kFlagsMask) >> kNumFlagsBits; - for (i = 0; i < numWords; i++) - Flags[i] = kAllFlags; - } - #endif - - { - UInt32 sum = 0; - for (i = 0; i < kNumHashValues; i++) - { - UInt32 groupSize = counters[i]; - if (groupSize > 0) - { - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 t = sum + groupSize - 1; - Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask)); - #endif - sum += groupSize; - } - counters[i] = sum - groupSize; - } - - for (i = 0; i < blockSize - 1; i++) - Groups[i] = counters[((UInt32)data[i] << 8) | data[i + 1]]; - Groups[i] = counters[((UInt32)data[i] << 8) | data[0]]; - - for (i = 0; i < blockSize - 1; i++) - Indices[counters[((UInt32)data[i] << 8) | data[i + 1]]++] = i; - Indices[counters[((UInt32)data[i] << 8) | data[0]]++] = i; - - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - { - UInt32 prev = 0; - for (i = 0; i < kNumHashValues; i++) - { - UInt32 prevGroupSize = counters[i] - prev; - if (prevGroupSize == 0) - continue; - SetGroupSize(Indices + prev, prevGroupSize); - prev = counters[i]; - } - } - #endif - } - - { - int NumRefBits; - UInt32 NumSortedBytes; - for (NumRefBits = 0; ((blockSize - 1) >> NumRefBits) != 0; NumRefBits++); - NumRefBits = 32 - NumRefBits; - if (NumRefBits > kNumRefBitsMax) - NumRefBits = kNumRefBitsMax; - - for (NumSortedBytes = kNumHashBytes; ; NumSortedBytes <<= 1) - { - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - UInt32 finishedGroupSize = 0; - #endif - UInt32 newLimit = 0; - for (i = 0; i < blockSize;) - { - UInt32 groupSize; - #ifdef BLOCK_SORT_EXTERNAL_FLAGS - - if ((Flags[i >> kNumFlagsBits] & (1 << (i & kFlagsMask))) == 0) - { - i++; - continue; - } - for (groupSize = 1; - (Flags[(i + groupSize) >> kNumFlagsBits] & (1 << ((i + groupSize) & kFlagsMask))) != 0; - groupSize++); - - groupSize++; - - #else - - groupSize = ((Indices[i] & ~0xC0000000) >> kNumBitsMax); - { - Bool finishedGroup = ((Indices[i] & 0x80000000) == 0); - if ((Indices[i] & 0x40000000) != 0) - { - groupSize += ((Indices[i + 1] >> kNumBitsMax) << kNumExtra0Bits); - Indices[i + 1] &= kIndexMask; - } - Indices[i] &= kIndexMask; - groupSize++; - if (finishedGroup || groupSize == 1) - { - Indices[i - finishedGroupSize] &= kIndexMask; - if (finishedGroupSize > 1) - Indices[i - finishedGroupSize + 1] &= kIndexMask; - { - UInt32 newGroupSize = groupSize + finishedGroupSize; - SetFinishedGroupSize(Indices + i - finishedGroupSize, newGroupSize); - finishedGroupSize = newGroupSize; - } - i += groupSize; - continue; - } - finishedGroupSize = 0; - } - - #endif - - if (NumSortedBytes >= blockSize) - { - UInt32 j; - for (j = 0; j < groupSize; j++) - { - UInt32 t = (i + j); - /* Flags[t >> kNumFlagsBits] &= ~(1 << (t & kFlagsMask)); */ - Groups[Indices[t]] = t; - } - } - else - if (SortGroup(blockSize, NumSortedBytes, i, groupSize, NumRefBits, Indices - #ifndef BLOCK_SORT_USE_HEAP_SORT - , 0, blockSize - #endif - ) != 0) - newLimit = i + groupSize; - i += groupSize; - } - if (newLimit == 0) - break; - } - } - #ifndef BLOCK_SORT_EXTERNAL_FLAGS - for (i = 0; i < blockSize;) - { - UInt32 groupSize = ((Indices[i] & ~0xC0000000) >> kNumBitsMax); - if ((Indices[i] & 0x40000000) != 0) - { - groupSize += ((Indices[i + 1] >> kNumBitsMax) << kNumExtra0Bits); - Indices[i + 1] &= kIndexMask; - } - Indices[i] &= kIndexMask; - groupSize++; - i += groupSize; - } - #endif - return Groups[0]; -} - diff --git a/desmume/src/windows/7z/C/BwtSort.h b/desmume/src/windows/7z/C/BwtSort.h deleted file mode 100644 index 84c50339c..000000000 --- a/desmume/src/windows/7z/C/BwtSort.h +++ /dev/null @@ -1,24 +0,0 @@ -/* BwtSort.h -- BWT block sorting -2008-03-26 -Igor Pavlov -Public domain */ - -#ifndef __BWTSORT_H -#define __BWTSORT_H - -#include "Types.h" - -/* use BLOCK_SORT_EXTERNAL_FLAGS if blockSize can be > 1M */ -/* #define BLOCK_SORT_EXTERNAL_FLAGS */ - -#ifdef BLOCK_SORT_EXTERNAL_FLAGS -#define BLOCK_SORT_EXTERNAL_SIZE(blockSize) ((((blockSize) + 31) >> 5)) -#else -#define BLOCK_SORT_EXTERNAL_SIZE(blockSize) 0 -#endif - -#define BLOCK_SORT_BUF_SIZE(blockSize) ((blockSize) * 2 + BLOCK_SORT_EXTERNAL_SIZE(blockSize) + (1 << 16)) - -UInt32 BlockSort(UInt32 *indices, const Byte *data, UInt32 blockSize); - -#endif diff --git a/desmume/src/windows/7z/C/CpuArch.h b/desmume/src/windows/7z/C/CpuArch.h deleted file mode 100644 index 006361f2f..000000000 --- a/desmume/src/windows/7z/C/CpuArch.h +++ /dev/null @@ -1,69 +0,0 @@ -/* CpuArch.h -2008-08-05 -Igor Pavlov -Public domain */ - -#ifndef __CPUARCH_H -#define __CPUARCH_H - -/* -LITTLE_ENDIAN_UNALIGN means: - 1) CPU is LITTLE_ENDIAN - 2) it's allowed to make unaligned memory accesses -if LITTLE_ENDIAN_UNALIGN is not defined, it means that we don't know -about these properties of platform. -*/ - -#if defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64) || defined(__i386__) || defined(__x86_64__) -#define LITTLE_ENDIAN_UNALIGN -#endif - -#ifdef LITTLE_ENDIAN_UNALIGN - -#define GetUi16(p) (*(const UInt16 *)(p)) -#define GetUi32(p) (*(const UInt32 *)(p)) -#define GetUi64(p) (*(const UInt64 *)(p)) -#define SetUi32(p, d) *(UInt32 *)(p) = (d); - -#else - -#define GetUi16(p) (((const Byte *)(p))[0] | ((UInt16)((const Byte *)(p))[1] << 8)) - -#define GetUi32(p) ( \ - ((const Byte *)(p))[0] | \ - ((UInt32)((const Byte *)(p))[1] << 8) | \ - ((UInt32)((const Byte *)(p))[2] << 16) | \ - ((UInt32)((const Byte *)(p))[3] << 24)) - -#define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32)) - -#define SetUi32(p, d) { UInt32 _x_ = (d); \ - ((Byte *)(p))[0] = (Byte)_x_; \ - ((Byte *)(p))[1] = (Byte)(_x_ >> 8); \ - ((Byte *)(p))[2] = (Byte)(_x_ >> 16); \ - ((Byte *)(p))[3] = (Byte)(_x_ >> 24); } - -#endif - -#if defined(LITTLE_ENDIAN_UNALIGN) && defined(_WIN64) && (_MSC_VER >= 1300) - -#pragma intrinsic(_byteswap_ulong) -#pragma intrinsic(_byteswap_uint64) -#define GetBe32(p) _byteswap_ulong(*(const UInt32 *)(const Byte *)(p)) -#define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const Byte *)(p)) - -#else - -#define GetBe32(p) ( \ - ((UInt32)((const Byte *)(p))[0] << 24) | \ - ((UInt32)((const Byte *)(p))[1] << 16) | \ - ((UInt32)((const Byte *)(p))[2] << 8) | \ - ((const Byte *)(p))[3] ) - -#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) - -#endif - -#define GetBe16(p) (((UInt16)((const Byte *)(p))[0] << 8) | ((const Byte *)(p))[1]) - -#endif diff --git a/desmume/src/windows/7z/C/HuffEnc.c b/desmume/src/windows/7z/C/HuffEnc.c deleted file mode 100644 index 2d31ad596..000000000 --- a/desmume/src/windows/7z/C/HuffEnc.c +++ /dev/null @@ -1,148 +0,0 @@ -/* HuffEnc.c -- functions for Huffman encoding -2008-08-05 -Igor Pavlov -Public domain */ - -#include "HuffEnc.h" -#include "Sort.h" - -#define kMaxLen 16 -#define NUM_BITS 10 -#define MASK ((1 << NUM_BITS) - 1) - -#define NUM_COUNTERS 64 - -#define HUFFMAN_SPEED_OPT - -void Huffman_Generate(const UInt32 *freqs, UInt32 *p, Byte *lens, UInt32 numSymbols, UInt32 maxLen) -{ - UInt32 num = 0; - /* if (maxLen > 10) maxLen = 10; */ - { - UInt32 i; - - #ifdef HUFFMAN_SPEED_OPT - - UInt32 counters[NUM_COUNTERS]; - for (i = 0; i < NUM_COUNTERS; i++) - counters[i] = 0; - for (i = 0; i < numSymbols; i++) - { - UInt32 freq = freqs[i]; - counters[(freq < NUM_COUNTERS - 1) ? freq : NUM_COUNTERS - 1]++; - } - - for (i = 1; i < NUM_COUNTERS; i++) - { - UInt32 temp = counters[i]; - counters[i] = num; - num += temp; - } - - for (i = 0; i < numSymbols; i++) - { - UInt32 freq = freqs[i]; - if (freq == 0) - lens[i] = 0; - else - p[counters[((freq < NUM_COUNTERS - 1) ? freq : NUM_COUNTERS - 1)]++] = i | (freq << NUM_BITS); - } - counters[0] = 0; - HeapSort(p + counters[NUM_COUNTERS - 2], counters[NUM_COUNTERS - 1] - counters[NUM_COUNTERS - 2]); - - #else - - for (i = 0; i < numSymbols; i++) - { - UInt32 freq = freqs[i]; - if (freq == 0) - lens[i] = 0; - else - p[num++] = i | (freq << NUM_BITS); - } - HeapSort(p, num); - - #endif - } - - if (num < 2) - { - int minCode = 0; - int maxCode = 1; - if (num == 1) - { - maxCode = (int)(p[0] & MASK); - if (maxCode == 0) - maxCode++; - } - p[minCode] = 0; - p[maxCode] = 1; - lens[minCode] = lens[maxCode] = 1; - return; - } - - { - UInt32 b, e, i; - - i = b = e = 0; - do - { - UInt32 n, m, freq; - n = (i != num && (b == e || (p[i] >> NUM_BITS) <= (p[b] >> NUM_BITS))) ? i++ : b++; - freq = (p[n] & ~MASK); - p[n] = (p[n] & MASK) | (e << NUM_BITS); - m = (i != num && (b == e || (p[i] >> NUM_BITS) <= (p[b] >> NUM_BITS))) ? i++ : b++; - freq += (p[m] & ~MASK); - p[m] = (p[m] & MASK) | (e << NUM_BITS); - p[e] = (p[e] & MASK) | freq; - e++; - } - while (num - e > 1); - - { - UInt32 lenCounters[kMaxLen + 1]; - for (i = 0; i <= kMaxLen; i++) - lenCounters[i] = 0; - - p[--e] &= MASK; - lenCounters[1] = 2; - while (e > 0) - { - UInt32 len = (p[p[--e] >> NUM_BITS] >> NUM_BITS) + 1; - p[e] = (p[e] & MASK) | (len << NUM_BITS); - if (len >= maxLen) - for (len = maxLen - 1; lenCounters[len] == 0; len--); - lenCounters[len]--; - lenCounters[len + 1] += 2; - } - - { - UInt32 len; - i = 0; - for (len = maxLen; len != 0; len--) - { - UInt32 num; - for (num = lenCounters[len]; num != 0; num--) - lens[p[i++] & MASK] = (Byte)len; - } - } - - { - UInt32 nextCodes[kMaxLen + 1]; - { - UInt32 code = 0; - UInt32 len; - for (len = 1; len <= kMaxLen; len++) - nextCodes[len] = code = (code + lenCounters[len - 1]) << 1; - } - /* if (code + lenCounters[kMaxLen] - 1 != (1 << kMaxLen) - 1) throw 1; */ - - { - UInt32 i; - for (i = 0; i < numSymbols; i++) - p[i] = nextCodes[lens[i]]++; - } - } - } - } -} diff --git a/desmume/src/windows/7z/C/HuffEnc.h b/desmume/src/windows/7z/C/HuffEnc.h deleted file mode 100644 index c0617b33e..000000000 --- a/desmume/src/windows/7z/C/HuffEnc.h +++ /dev/null @@ -1,21 +0,0 @@ -/* HuffEnc.h -- functions for Huffman encoding -2008-03-26 -Igor Pavlov -Public domain */ - -#ifndef __HUFFENC_H -#define __HUFFENC_H - -#include "Types.h" - -/* -Conditions: - num <= 1024 = 2 ^ NUM_BITS - Sum(freqs) < 4M = 2 ^ (32 - NUM_BITS) - maxLen <= 16 = kMaxLen - Num_Items(p) >= HUFFMAN_TEMP_SIZE(num) -*/ - -void Huffman_Generate(const UInt32 *freqs, UInt32 *p, Byte *lens, UInt32 num, UInt32 maxLen); - -#endif diff --git a/desmume/src/windows/7z/C/LzFind.c b/desmume/src/windows/7z/C/LzFind.c deleted file mode 100644 index e0ebe6235..000000000 --- a/desmume/src/windows/7z/C/LzFind.c +++ /dev/null @@ -1,751 +0,0 @@ -/* LzFind.c -- Match finder for LZ algorithms -2008-10-04 : Igor Pavlov : Public domain */ - -#include - -#include "LzFind.h" -#include "LzHash.h" - -#define kEmptyHashValue 0 -#define kMaxValForNormalize ((UInt32)0xFFFFFFFF) -#define kNormalizeStepMin (1 << 10) /* it must be power of 2 */ -#define kNormalizeMask (~(kNormalizeStepMin - 1)) -#define kMaxHistorySize ((UInt32)3 << 30) - -#define kStartMaxLen 3 - -static void LzInWindow_Free(CMatchFinder *p, ISzAlloc *alloc) -{ - if (!p->directInput) - { - alloc->Free(alloc, p->bufferBase); - p->bufferBase = 0; - } -} - -/* keepSizeBefore + keepSizeAfter + keepSizeReserv must be < 4G) */ - -static int LzInWindow_Create(CMatchFinder *p, UInt32 keepSizeReserv, ISzAlloc *alloc) -{ - UInt32 blockSize = p->keepSizeBefore + p->keepSizeAfter + keepSizeReserv; - if (p->directInput) - { - p->blockSize = blockSize; - return 1; - } - if (p->bufferBase == 0 || p->blockSize != blockSize) - { - LzInWindow_Free(p, alloc); - p->blockSize = blockSize; - p->bufferBase = (Byte *)alloc->Alloc(alloc, (size_t)blockSize); - } - return (p->bufferBase != 0); -} - -Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; } -Byte MatchFinder_GetIndexByte(CMatchFinder *p, Int32 index) { return p->buffer[index]; } - -UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return p->streamPos - p->pos; } - -void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue) -{ - p->posLimit -= subValue; - p->pos -= subValue; - p->streamPos -= subValue; -} - -static void MatchFinder_ReadBlock(CMatchFinder *p) -{ - if (p->streamEndWasReached || p->result != SZ_OK) - return; - for (;;) - { - Byte *dest = p->buffer + (p->streamPos - p->pos); - size_t size = (p->bufferBase + p->blockSize - dest); - if (size == 0) - return; - p->result = p->stream->Read(p->stream, dest, &size); - if (p->result != SZ_OK) - return; - if (size == 0) - { - p->streamEndWasReached = 1; - return; - } - p->streamPos += (UInt32)size; - if (p->streamPos - p->pos > p->keepSizeAfter) - return; - } -} - -void MatchFinder_MoveBlock(CMatchFinder *p) -{ - memmove(p->bufferBase, - p->buffer - p->keepSizeBefore, - (size_t)(p->streamPos - p->pos + p->keepSizeBefore)); - p->buffer = p->bufferBase + p->keepSizeBefore; -} - -int MatchFinder_NeedMove(CMatchFinder *p) -{ - /* if (p->streamEndWasReached) return 0; */ - return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter); -} - -void MatchFinder_ReadIfRequired(CMatchFinder *p) -{ - if (p->streamEndWasReached) - return; - if (p->keepSizeAfter >= p->streamPos - p->pos) - MatchFinder_ReadBlock(p); -} - -static void MatchFinder_CheckAndMoveAndRead(CMatchFinder *p) -{ - if (MatchFinder_NeedMove(p)) - MatchFinder_MoveBlock(p); - MatchFinder_ReadBlock(p); -} - -static void MatchFinder_SetDefaultSettings(CMatchFinder *p) -{ - p->cutValue = 32; - p->btMode = 1; - p->numHashBytes = 4; - /* p->skipModeBits = 0; */ - p->directInput = 0; - p->bigHash = 0; -} - -#define kCrcPoly 0xEDB88320 - -void MatchFinder_Construct(CMatchFinder *p) -{ - UInt32 i; - p->bufferBase = 0; - p->directInput = 0; - p->hash = 0; - MatchFinder_SetDefaultSettings(p); - - for (i = 0; i < 256; i++) - { - UInt32 r = i; - int j; - for (j = 0; j < 8; j++) - r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1)); - p->crc[i] = r; - } -} - -static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->hash); - p->hash = 0; -} - -void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc) -{ - MatchFinder_FreeThisClassMemory(p, alloc); - LzInWindow_Free(p, alloc); -} - -static CLzRef* AllocRefs(UInt32 num, ISzAlloc *alloc) -{ - size_t sizeInBytes = (size_t)num * sizeof(CLzRef); - if (sizeInBytes / sizeof(CLzRef) != num) - return 0; - return (CLzRef *)alloc->Alloc(alloc, sizeInBytes); -} - -int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, - UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, - ISzAlloc *alloc) -{ - UInt32 sizeReserv; - if (historySize > kMaxHistorySize) - { - MatchFinder_Free(p, alloc); - return 0; - } - sizeReserv = historySize >> 1; - if (historySize > ((UInt32)2 << 30)) - sizeReserv = historySize >> 2; - sizeReserv += (keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + (1 << 19); - - p->keepSizeBefore = historySize + keepAddBufferBefore + 1; - p->keepSizeAfter = matchMaxLen + keepAddBufferAfter; - /* we need one additional byte, since we use MoveBlock after pos++ and before dictionary using */ - if (LzInWindow_Create(p, sizeReserv, alloc)) - { - UInt32 newCyclicBufferSize = (historySize /* >> p->skipModeBits */) + 1; - UInt32 hs; - p->matchMaxLen = matchMaxLen; - { - p->fixedHashSize = 0; - if (p->numHashBytes == 2) - hs = (1 << 16) - 1; - else - { - hs = historySize - 1; - hs |= (hs >> 1); - hs |= (hs >> 2); - hs |= (hs >> 4); - hs |= (hs >> 8); - hs >>= 1; - /* hs >>= p->skipModeBits; */ - hs |= 0xFFFF; /* don't change it! It's required for Deflate */ - if (hs > (1 << 24)) - { - if (p->numHashBytes == 3) - hs = (1 << 24) - 1; - else - hs >>= 1; - } - } - p->hashMask = hs; - hs++; - if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size; - if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size; - if (p->numHashBytes > 4) p->fixedHashSize += kHash4Size; - hs += p->fixedHashSize; - } - - { - UInt32 prevSize = p->hashSizeSum + p->numSons; - UInt32 newSize; - p->historySize = historySize; - p->hashSizeSum = hs; - p->cyclicBufferSize = newCyclicBufferSize; - p->numSons = (p->btMode ? newCyclicBufferSize * 2 : newCyclicBufferSize); - newSize = p->hashSizeSum + p->numSons; - if (p->hash != 0 && prevSize == newSize) - return 1; - MatchFinder_FreeThisClassMemory(p, alloc); - p->hash = AllocRefs(newSize, alloc); - if (p->hash != 0) - { - p->son = p->hash + p->hashSizeSum; - return 1; - } - } - } - MatchFinder_Free(p, alloc); - return 0; -} - -static void MatchFinder_SetLimits(CMatchFinder *p) -{ - UInt32 limit = kMaxValForNormalize - p->pos; - UInt32 limit2 = p->cyclicBufferSize - p->cyclicBufferPos; - if (limit2 < limit) - limit = limit2; - limit2 = p->streamPos - p->pos; - if (limit2 <= p->keepSizeAfter) - { - if (limit2 > 0) - limit2 = 1; - } - else - limit2 -= p->keepSizeAfter; - if (limit2 < limit) - limit = limit2; - { - UInt32 lenLimit = p->streamPos - p->pos; - if (lenLimit > p->matchMaxLen) - lenLimit = p->matchMaxLen; - p->lenLimit = lenLimit; - } - p->posLimit = p->pos + limit; -} - -void MatchFinder_Init(CMatchFinder *p) -{ - UInt32 i; - for (i = 0; i < p->hashSizeSum; i++) - p->hash[i] = kEmptyHashValue; - p->cyclicBufferPos = 0; - p->buffer = p->bufferBase; - p->pos = p->streamPos = p->cyclicBufferSize; - p->result = SZ_OK; - p->streamEndWasReached = 0; - MatchFinder_ReadBlock(p); - MatchFinder_SetLimits(p); -} - -static UInt32 MatchFinder_GetSubValue(CMatchFinder *p) -{ - return (p->pos - p->historySize - 1) & kNormalizeMask; -} - -void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems) -{ - UInt32 i; - for (i = 0; i < numItems; i++) - { - UInt32 value = items[i]; - if (value <= subValue) - value = kEmptyHashValue; - else - value -= subValue; - items[i] = value; - } -} - -static void MatchFinder_Normalize(CMatchFinder *p) -{ - UInt32 subValue = MatchFinder_GetSubValue(p); - MatchFinder_Normalize3(subValue, p->hash, p->hashSizeSum + p->numSons); - MatchFinder_ReduceOffsets(p, subValue); -} - -static void MatchFinder_CheckLimits(CMatchFinder *p) -{ - if (p->pos == kMaxValForNormalize) - MatchFinder_Normalize(p); - if (!p->streamEndWasReached && p->keepSizeAfter == p->streamPos - p->pos) - MatchFinder_CheckAndMoveAndRead(p); - if (p->cyclicBufferPos == p->cyclicBufferSize) - p->cyclicBufferPos = 0; - MatchFinder_SetLimits(p); -} - -static UInt32 * Hc_GetMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, - UInt32 *distances, UInt32 maxLen) -{ - son[_cyclicBufferPos] = curMatch; - for (;;) - { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - return distances; - { - const Byte *pb = cur - delta; - curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)]; - if (pb[maxLen] == cur[maxLen] && *pb == *cur) - { - UInt32 len = 0; - while (++len != lenLimit) - if (pb[len] != cur[len]) - break; - if (maxLen < len) - { - *distances++ = maxLen = len; - *distances++ = delta - 1; - if (len == lenLimit) - return distances; - } - } - } - } -} - -UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, - UInt32 *distances, UInt32 maxLen) -{ - CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1; - CLzRef *ptr1 = son + (_cyclicBufferPos << 1); - UInt32 len0 = 0, len1 = 0; - for (;;) - { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - { - *ptr0 = *ptr1 = kEmptyHashValue; - return distances; - } - { - CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); - const Byte *pb = cur - delta; - UInt32 len = (len0 < len1 ? len0 : len1); - if (pb[len] == cur[len]) - { - if (++len != lenLimit && pb[len] == cur[len]) - while (++len != lenLimit) - if (pb[len] != cur[len]) - break; - if (maxLen < len) - { - *distances++ = maxLen = len; - *distances++ = delta - 1; - if (len == lenLimit) - { - *ptr1 = pair[0]; - *ptr0 = pair[1]; - return distances; - } - } - } - if (pb[len] < cur[len]) - { - *ptr1 = curMatch; - ptr1 = pair + 1; - curMatch = *ptr1; - len1 = len; - } - else - { - *ptr0 = curMatch; - ptr0 = pair; - curMatch = *ptr0; - len0 = len; - } - } - } -} - -static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue) -{ - CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1; - CLzRef *ptr1 = son + (_cyclicBufferPos << 1); - UInt32 len0 = 0, len1 = 0; - for (;;) - { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - { - *ptr0 = *ptr1 = kEmptyHashValue; - return; - } - { - CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); - const Byte *pb = cur - delta; - UInt32 len = (len0 < len1 ? len0 : len1); - if (pb[len] == cur[len]) - { - while (++len != lenLimit) - if (pb[len] != cur[len]) - break; - { - if (len == lenLimit) - { - *ptr1 = pair[0]; - *ptr0 = pair[1]; - return; - } - } - } - if (pb[len] < cur[len]) - { - *ptr1 = curMatch; - ptr1 = pair + 1; - curMatch = *ptr1; - len1 = len; - } - else - { - *ptr0 = curMatch; - ptr0 = pair; - curMatch = *ptr0; - len0 = len; - } - } - } -} - -#define MOVE_POS \ - ++p->cyclicBufferPos; \ - p->buffer++; \ - if (++p->pos == p->posLimit) MatchFinder_CheckLimits(p); - -#define MOVE_POS_RET MOVE_POS return offset; - -static void MatchFinder_MovePos(CMatchFinder *p) { MOVE_POS; } - -#define GET_MATCHES_HEADER2(minLen, ret_op) \ - UInt32 lenLimit; UInt32 hashValue; const Byte *cur; UInt32 curMatch; \ - lenLimit = p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \ - cur = p->buffer; - -#define GET_MATCHES_HEADER(minLen) GET_MATCHES_HEADER2(minLen, return 0) -#define SKIP_HEADER(minLen) GET_MATCHES_HEADER2(minLen, continue) - -#define MF_PARAMS(p) p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue - -#define GET_MATCHES_FOOTER(offset, maxLen) \ - offset = (UInt32)(GetMatchesSpec1(lenLimit, curMatch, MF_PARAMS(p), \ - distances + offset, maxLen) - distances); MOVE_POS_RET; - -#define SKIP_FOOTER \ - SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); MOVE_POS; - -static UInt32 Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 offset; - GET_MATCHES_HEADER(2) - HASH2_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - offset = 0; - GET_MATCHES_FOOTER(offset, 1) -} - -UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 offset; - GET_MATCHES_HEADER(3) - HASH_ZIP_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - offset = 0; - GET_MATCHES_FOOTER(offset, 2) -} - -static UInt32 Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 hash2Value, delta2, maxLen, offset; - GET_MATCHES_HEADER(3) - - HASH3_CALC; - - delta2 = p->pos - p->hash[hash2Value]; - curMatch = p->hash[kFix3HashSize + hashValue]; - - p->hash[hash2Value] = - p->hash[kFix3HashSize + hashValue] = p->pos; - - - maxLen = 2; - offset = 0; - if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) - { - for (; maxLen != lenLimit; maxLen++) - if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) - break; - distances[0] = maxLen; - distances[1] = delta2 - 1; - offset = 2; - if (maxLen == lenLimit) - { - SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); - MOVE_POS_RET; - } - } - GET_MATCHES_FOOTER(offset, maxLen) -} - -static UInt32 Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset; - GET_MATCHES_HEADER(4) - - HASH4_CALC; - - delta2 = p->pos - p->hash[ hash2Value]; - delta3 = p->pos - p->hash[kFix3HashSize + hash3Value]; - curMatch = p->hash[kFix4HashSize + hashValue]; - - p->hash[ hash2Value] = - p->hash[kFix3HashSize + hash3Value] = - p->hash[kFix4HashSize + hashValue] = p->pos; - - maxLen = 1; - offset = 0; - if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) - { - distances[0] = maxLen = 2; - distances[1] = delta2 - 1; - offset = 2; - } - if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur) - { - maxLen = 3; - distances[offset + 1] = delta3 - 1; - offset += 2; - delta2 = delta3; - } - if (offset != 0) - { - for (; maxLen != lenLimit; maxLen++) - if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) - break; - distances[offset - 2] = maxLen; - if (maxLen == lenLimit) - { - SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); - MOVE_POS_RET; - } - } - if (maxLen < 3) - maxLen = 3; - GET_MATCHES_FOOTER(offset, maxLen) -} - -static UInt32 Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 hash2Value, hash3Value, delta2, delta3, maxLen, offset; - GET_MATCHES_HEADER(4) - - HASH4_CALC; - - delta2 = p->pos - p->hash[ hash2Value]; - delta3 = p->pos - p->hash[kFix3HashSize + hash3Value]; - curMatch = p->hash[kFix4HashSize + hashValue]; - - p->hash[ hash2Value] = - p->hash[kFix3HashSize + hash3Value] = - p->hash[kFix4HashSize + hashValue] = p->pos; - - maxLen = 1; - offset = 0; - if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) - { - distances[0] = maxLen = 2; - distances[1] = delta2 - 1; - offset = 2; - } - if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur) - { - maxLen = 3; - distances[offset + 1] = delta3 - 1; - offset += 2; - delta2 = delta3; - } - if (offset != 0) - { - for (; maxLen != lenLimit; maxLen++) - if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) - break; - distances[offset - 2] = maxLen; - if (maxLen == lenLimit) - { - p->son[p->cyclicBufferPos] = curMatch; - MOVE_POS_RET; - } - } - if (maxLen < 3) - maxLen = 3; - offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p), - distances + offset, maxLen) - (distances)); - MOVE_POS_RET -} - -UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) -{ - UInt32 offset; - GET_MATCHES_HEADER(3) - HASH_ZIP_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p), - distances, 2) - (distances)); - MOVE_POS_RET -} - -static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - SKIP_HEADER(2) - HASH2_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - SKIP_FOOTER - } - while (--num != 0); -} - -void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - SKIP_HEADER(3) - HASH_ZIP_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - SKIP_FOOTER - } - while (--num != 0); -} - -static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - UInt32 hash2Value; - SKIP_HEADER(3) - HASH3_CALC; - curMatch = p->hash[kFix3HashSize + hashValue]; - p->hash[hash2Value] = - p->hash[kFix3HashSize + hashValue] = p->pos; - SKIP_FOOTER - } - while (--num != 0); -} - -static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - UInt32 hash2Value, hash3Value; - SKIP_HEADER(4) - HASH4_CALC; - curMatch = p->hash[kFix4HashSize + hashValue]; - p->hash[ hash2Value] = - p->hash[kFix3HashSize + hash3Value] = p->pos; - p->hash[kFix4HashSize + hashValue] = p->pos; - SKIP_FOOTER - } - while (--num != 0); -} - -static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - UInt32 hash2Value, hash3Value; - SKIP_HEADER(4) - HASH4_CALC; - curMatch = p->hash[kFix4HashSize + hashValue]; - p->hash[ hash2Value] = - p->hash[kFix3HashSize + hash3Value] = - p->hash[kFix4HashSize + hashValue] = p->pos; - p->son[p->cyclicBufferPos] = curMatch; - MOVE_POS - } - while (--num != 0); -} - -void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) -{ - do - { - SKIP_HEADER(3) - HASH_ZIP_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - p->son[p->cyclicBufferPos] = curMatch; - MOVE_POS - } - while (--num != 0); -} - -void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable) -{ - vTable->Init = (Mf_Init_Func)MatchFinder_Init; - vTable->GetIndexByte = (Mf_GetIndexByte_Func)MatchFinder_GetIndexByte; - vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinder_GetNumAvailableBytes; - vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinder_GetPointerToCurrentPos; - if (!p->btMode) - { - vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip; - } - else if (p->numHashBytes == 2) - { - vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip; - } - else if (p->numHashBytes == 3) - { - vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip; - } - else - { - vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip; - } -} diff --git a/desmume/src/windows/7z/C/LzFind.h b/desmume/src/windows/7z/C/LzFind.h deleted file mode 100644 index 423d67e0c..000000000 --- a/desmume/src/windows/7z/C/LzFind.h +++ /dev/null @@ -1,107 +0,0 @@ -/* LzFind.h -- Match finder for LZ algorithms -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __LZFIND_H -#define __LZFIND_H - -#include "Types.h" - -typedef UInt32 CLzRef; - -typedef struct _CMatchFinder -{ - Byte *buffer; - UInt32 pos; - UInt32 posLimit; - UInt32 streamPos; - UInt32 lenLimit; - - UInt32 cyclicBufferPos; - UInt32 cyclicBufferSize; /* it must be = (historySize + 1) */ - - UInt32 matchMaxLen; - CLzRef *hash; - CLzRef *son; - UInt32 hashMask; - UInt32 cutValue; - - Byte *bufferBase; - ISeqInStream *stream; - int streamEndWasReached; - - UInt32 blockSize; - UInt32 keepSizeBefore; - UInt32 keepSizeAfter; - - UInt32 numHashBytes; - int directInput; - int btMode; - /* int skipModeBits; */ - int bigHash; - UInt32 historySize; - UInt32 fixedHashSize; - UInt32 hashSizeSum; - UInt32 numSons; - SRes result; - UInt32 crc[256]; -} CMatchFinder; - -#define Inline_MatchFinder_GetPointerToCurrentPos(p) ((p)->buffer) -#define Inline_MatchFinder_GetIndexByte(p, index) ((p)->buffer[(Int32)(index)]) - -#define Inline_MatchFinder_GetNumAvailableBytes(p) ((p)->streamPos - (p)->pos) - -int MatchFinder_NeedMove(CMatchFinder *p); -Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p); -void MatchFinder_MoveBlock(CMatchFinder *p); -void MatchFinder_ReadIfRequired(CMatchFinder *p); - -void MatchFinder_Construct(CMatchFinder *p); - -/* Conditions: - historySize <= 3 GB - keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB -*/ -int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, - UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, - ISzAlloc *alloc); -void MatchFinder_Free(CMatchFinder *p, ISzAlloc *alloc); -void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems); -void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue); - -UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *buffer, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue, - UInt32 *distances, UInt32 maxLen); - -/* -Conditions: - Mf_GetNumAvailableBytes_Func must be called before each Mf_GetMatchLen_Func. - Mf_GetPointerToCurrentPos_Func's result must be used only before any other function -*/ - -typedef void (*Mf_Init_Func)(void *object); -typedef Byte (*Mf_GetIndexByte_Func)(void *object, Int32 index); -typedef UInt32 (*Mf_GetNumAvailableBytes_Func)(void *object); -typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object); -typedef UInt32 (*Mf_GetMatches_Func)(void *object, UInt32 *distances); -typedef void (*Mf_Skip_Func)(void *object, UInt32); - -typedef struct _IMatchFinder -{ - Mf_Init_Func Init; - Mf_GetIndexByte_Func GetIndexByte; - Mf_GetNumAvailableBytes_Func GetNumAvailableBytes; - Mf_GetPointerToCurrentPos_Func GetPointerToCurrentPos; - Mf_GetMatches_Func GetMatches; - Mf_Skip_Func Skip; -} IMatchFinder; - -void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable); - -void MatchFinder_Init(CMatchFinder *p); -UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances); -UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances); -void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num); -void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num); - -#endif diff --git a/desmume/src/windows/7z/C/LzFindMt.c b/desmume/src/windows/7z/C/LzFindMt.c deleted file mode 100644 index 0ef134735..000000000 --- a/desmume/src/windows/7z/C/LzFindMt.c +++ /dev/null @@ -1,793 +0,0 @@ -/* LzFindMt.c -- multithreaded Match finder for LZ algorithms -2008-10-04 : Igor Pavlov : Public domain */ - -#include "LzHash.h" - -#include "LzFindMt.h" - -void MtSync_Construct(CMtSync *p) -{ - p->wasCreated = False; - p->csWasInitialized = False; - p->csWasEntered = False; - Thread_Construct(&p->thread); - Event_Construct(&p->canStart); - Event_Construct(&p->wasStarted); - Event_Construct(&p->wasStopped); - Semaphore_Construct(&p->freeSemaphore); - Semaphore_Construct(&p->filledSemaphore); -} - -void MtSync_GetNextBlock(CMtSync *p) -{ - if (p->needStart) - { - p->numProcessedBlocks = 1; - p->needStart = False; - p->stopWriting = False; - p->exit = False; - Event_Reset(&p->wasStarted); - Event_Reset(&p->wasStopped); - - Event_Set(&p->canStart); - Event_Wait(&p->wasStarted); - } - else - { - CriticalSection_Leave(&p->cs); - p->csWasEntered = False; - p->numProcessedBlocks++; - Semaphore_Release1(&p->freeSemaphore); - } - Semaphore_Wait(&p->filledSemaphore); - CriticalSection_Enter(&p->cs); - p->csWasEntered = True; -} - -/* MtSync_StopWriting must be called if Writing was started */ - -void MtSync_StopWriting(CMtSync *p) -{ - UInt32 myNumBlocks = p->numProcessedBlocks; - if (!Thread_WasCreated(&p->thread) || p->needStart) - return; - p->stopWriting = True; - if (p->csWasEntered) - { - CriticalSection_Leave(&p->cs); - p->csWasEntered = False; - } - Semaphore_Release1(&p->freeSemaphore); - - Event_Wait(&p->wasStopped); - - while (myNumBlocks++ != p->numProcessedBlocks) - { - Semaphore_Wait(&p->filledSemaphore); - Semaphore_Release1(&p->freeSemaphore); - } - p->needStart = True; -} - -void MtSync_Destruct(CMtSync *p) -{ - if (Thread_WasCreated(&p->thread)) - { - MtSync_StopWriting(p); - p->exit = True; - if (p->needStart) - Event_Set(&p->canStart); - Thread_Wait(&p->thread); - Thread_Close(&p->thread); - } - if (p->csWasInitialized) - { - CriticalSection_Delete(&p->cs); - p->csWasInitialized = False; - } - - Event_Close(&p->canStart); - Event_Close(&p->wasStarted); - Event_Close(&p->wasStopped); - Semaphore_Close(&p->freeSemaphore); - Semaphore_Close(&p->filledSemaphore); - - p->wasCreated = False; -} - -#define RINOK_THREAD(x) { if ((x) != 0) return SZ_ERROR_THREAD; } - -static SRes MtSync_Create2(CMtSync *p, unsigned (MY_STD_CALL *startAddress)(void *), void *obj, UInt32 numBlocks) -{ - if (p->wasCreated) - return SZ_OK; - - RINOK_THREAD(CriticalSection_Init(&p->cs)); - p->csWasInitialized = True; - - RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->canStart)); - RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStarted)); - RINOK_THREAD(AutoResetEvent_CreateNotSignaled(&p->wasStopped)); - - RINOK_THREAD(Semaphore_Create(&p->freeSemaphore, numBlocks, numBlocks)); - RINOK_THREAD(Semaphore_Create(&p->filledSemaphore, 0, numBlocks)); - - p->needStart = True; - - RINOK_THREAD(Thread_Create(&p->thread, startAddress, obj)); - p->wasCreated = True; - return SZ_OK; -} - -static SRes MtSync_Create(CMtSync *p, unsigned (MY_STD_CALL *startAddress)(void *), void *obj, UInt32 numBlocks) -{ - SRes res = MtSync_Create2(p, startAddress, obj, numBlocks); - if (res != SZ_OK) - MtSync_Destruct(p); - return res; -} - -void MtSync_Init(CMtSync *p) { p->needStart = True; } - -#define kMtMaxValForNormalize 0xFFFFFFFF - -#define DEF_GetHeads2(name, v, action) \ -static void GetHeads ## name(const Byte *p, UInt32 pos, \ -UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc) \ -{ action; for (; numHeads != 0; numHeads--) { \ -const UInt32 value = (v); p++; *heads++ = pos - hash[value]; hash[value] = pos++; } } - -#define DEF_GetHeads(name, v) DEF_GetHeads2(name, v, ;) - -DEF_GetHeads2(2, (p[0] | ((UInt32)p[1] << 8)), hashMask = hashMask; crc = crc; ) -DEF_GetHeads(3, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8)) & hashMask) -DEF_GetHeads(4, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ (crc[p[3]] << 5)) & hashMask) -DEF_GetHeads(4b, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ ((UInt32)p[3] << 16)) & hashMask) -DEF_GetHeads(5, (crc[p[0]] ^ p[1] ^ ((UInt32)p[2] << 8) ^ (crc[p[3]] << 5) ^ (crc[p[4]] << 3)) & hashMask) - -void HashThreadFunc(CMatchFinderMt *mt) -{ - CMtSync *p = &mt->hashSync; - for (;;) - { - UInt32 numProcessedBlocks = 0; - Event_Wait(&p->canStart); - Event_Set(&p->wasStarted); - for (;;) - { - if (p->exit) - return; - if (p->stopWriting) - { - p->numProcessedBlocks = numProcessedBlocks; - Event_Set(&p->wasStopped); - break; - } - - { - CMatchFinder *mf = mt->MatchFinder; - if (MatchFinder_NeedMove(mf)) - { - CriticalSection_Enter(&mt->btSync.cs); - CriticalSection_Enter(&mt->hashSync.cs); - { - const Byte *beforePtr = MatchFinder_GetPointerToCurrentPos(mf); - const Byte *afterPtr; - MatchFinder_MoveBlock(mf); - afterPtr = MatchFinder_GetPointerToCurrentPos(mf); - mt->pointerToCurPos -= beforePtr - afterPtr; - mt->buffer -= beforePtr - afterPtr; - } - CriticalSection_Leave(&mt->btSync.cs); - CriticalSection_Leave(&mt->hashSync.cs); - continue; - } - - Semaphore_Wait(&p->freeSemaphore); - - MatchFinder_ReadIfRequired(mf); - if (mf->pos > (kMtMaxValForNormalize - kMtHashBlockSize)) - { - UInt32 subValue = (mf->pos - mf->historySize - 1); - MatchFinder_ReduceOffsets(mf, subValue); - MatchFinder_Normalize3(subValue, mf->hash + mf->fixedHashSize, mf->hashMask + 1); - } - { - UInt32 *heads = mt->hashBuf + ((numProcessedBlocks++) & kMtHashNumBlocksMask) * kMtHashBlockSize; - UInt32 num = mf->streamPos - mf->pos; - heads[0] = 2; - heads[1] = num; - if (num >= mf->numHashBytes) - { - num = num - mf->numHashBytes + 1; - if (num > kMtHashBlockSize - 2) - num = kMtHashBlockSize - 2; - mt->GetHeadsFunc(mf->buffer, mf->pos, mf->hash + mf->fixedHashSize, mf->hashMask, heads + 2, num, mf->crc); - heads[0] += num; - } - mf->pos += num; - mf->buffer += num; - } - } - - Semaphore_Release1(&p->filledSemaphore); - } - } -} - -void MatchFinderMt_GetNextBlock_Hash(CMatchFinderMt *p) -{ - MtSync_GetNextBlock(&p->hashSync); - p->hashBufPosLimit = p->hashBufPos = ((p->hashSync.numProcessedBlocks - 1) & kMtHashNumBlocksMask) * kMtHashBlockSize; - p->hashBufPosLimit += p->hashBuf[p->hashBufPos++]; - p->hashNumAvail = p->hashBuf[p->hashBufPos++]; -} - -#define kEmptyHashValue 0 - -/* #define MFMT_GM_INLINE */ - -#ifdef MFMT_GM_INLINE - -#define NO_INLINE MY_FAST_CALL - -Int32 NO_INLINE GetMatchesSpecN(UInt32 lenLimit, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue, - UInt32 *_distances, UInt32 _maxLen, const UInt32 *hash, Int32 limit, UInt32 size, UInt32 *posRes) -{ - do - { - UInt32 *distances = _distances + 1; - UInt32 curMatch = pos - *hash++; - - CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1; - CLzRef *ptr1 = son + (_cyclicBufferPos << 1); - UInt32 len0 = 0, len1 = 0; - UInt32 cutValue = _cutValue; - UInt32 maxLen = _maxLen; - for (;;) - { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - { - *ptr0 = *ptr1 = kEmptyHashValue; - break; - } - { - CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); - const Byte *pb = cur - delta; - UInt32 len = (len0 < len1 ? len0 : len1); - if (pb[len] == cur[len]) - { - if (++len != lenLimit && pb[len] == cur[len]) - while (++len != lenLimit) - if (pb[len] != cur[len]) - break; - if (maxLen < len) - { - *distances++ = maxLen = len; - *distances++ = delta - 1; - if (len == lenLimit) - { - *ptr1 = pair[0]; - *ptr0 = pair[1]; - break; - } - } - } - if (pb[len] < cur[len]) - { - *ptr1 = curMatch; - ptr1 = pair + 1; - curMatch = *ptr1; - len1 = len; - } - else - { - *ptr0 = curMatch; - ptr0 = pair; - curMatch = *ptr0; - len0 = len; - } - } - } - pos++; - _cyclicBufferPos++; - cur++; - { - UInt32 num = (UInt32)(distances - _distances); - *_distances = num - 1; - _distances += num; - limit -= num; - } - } - while (limit > 0 && --size != 0); - *posRes = pos; - return limit; -} - -#endif - -void BtGetMatches(CMatchFinderMt *p, UInt32 *distances) -{ - UInt32 numProcessed = 0; - UInt32 curPos = 2; - UInt32 limit = kMtBtBlockSize - (p->matchMaxLen * 2); - distances[1] = p->hashNumAvail; - while (curPos < limit) - { - if (p->hashBufPos == p->hashBufPosLimit) - { - MatchFinderMt_GetNextBlock_Hash(p); - distances[1] = numProcessed + p->hashNumAvail; - if (p->hashNumAvail >= p->numHashBytes) - continue; - for (; p->hashNumAvail != 0; p->hashNumAvail--) - distances[curPos++] = 0; - break; - } - { - UInt32 size = p->hashBufPosLimit - p->hashBufPos; - UInt32 lenLimit = p->matchMaxLen; - UInt32 pos = p->pos; - UInt32 cyclicBufferPos = p->cyclicBufferPos; - if (lenLimit >= p->hashNumAvail) - lenLimit = p->hashNumAvail; - { - UInt32 size2 = p->hashNumAvail - lenLimit + 1; - if (size2 < size) - size = size2; - size2 = p->cyclicBufferSize - cyclicBufferPos; - if (size2 < size) - size = size2; - } - #ifndef MFMT_GM_INLINE - while (curPos < limit && size-- != 0) - { - UInt32 *startDistances = distances + curPos; - UInt32 num = (UInt32)(GetMatchesSpec1(lenLimit, pos - p->hashBuf[p->hashBufPos++], - pos, p->buffer, p->son, cyclicBufferPos, p->cyclicBufferSize, p->cutValue, - startDistances + 1, p->numHashBytes - 1) - startDistances); - *startDistances = num - 1; - curPos += num; - cyclicBufferPos++; - pos++; - p->buffer++; - } - #else - { - UInt32 posRes; - curPos = limit - GetMatchesSpecN(lenLimit, pos, p->buffer, p->son, cyclicBufferPos, p->cyclicBufferSize, p->cutValue, - distances + curPos, p->numHashBytes - 1, p->hashBuf + p->hashBufPos, (Int32)(limit - curPos) , size, &posRes); - p->hashBufPos += posRes - pos; - cyclicBufferPos += posRes - pos; - p->buffer += posRes - pos; - pos = posRes; - } - #endif - - numProcessed += pos - p->pos; - p->hashNumAvail -= pos - p->pos; - p->pos = pos; - if (cyclicBufferPos == p->cyclicBufferSize) - cyclicBufferPos = 0; - p->cyclicBufferPos = cyclicBufferPos; - } - } - distances[0] = curPos; -} - -void BtFillBlock(CMatchFinderMt *p, UInt32 globalBlockIndex) -{ - CMtSync *sync = &p->hashSync; - if (!sync->needStart) - { - CriticalSection_Enter(&sync->cs); - sync->csWasEntered = True; - } - - BtGetMatches(p, p->btBuf + (globalBlockIndex & kMtBtNumBlocksMask) * kMtBtBlockSize); - - if (p->pos > kMtMaxValForNormalize - kMtBtBlockSize) - { - UInt32 subValue = p->pos - p->cyclicBufferSize; - MatchFinder_Normalize3(subValue, p->son, p->cyclicBufferSize * 2); - p->pos -= subValue; - } - - if (!sync->needStart) - { - CriticalSection_Leave(&sync->cs); - sync->csWasEntered = False; - } -} - -void BtThreadFunc(CMatchFinderMt *mt) -{ - CMtSync *p = &mt->btSync; - for (;;) - { - UInt32 blockIndex = 0; - Event_Wait(&p->canStart); - Event_Set(&p->wasStarted); - for (;;) - { - if (p->exit) - return; - if (p->stopWriting) - { - p->numProcessedBlocks = blockIndex; - MtSync_StopWriting(&mt->hashSync); - Event_Set(&p->wasStopped); - break; - } - Semaphore_Wait(&p->freeSemaphore); - BtFillBlock(mt, blockIndex++); - Semaphore_Release1(&p->filledSemaphore); - } - } -} - -void MatchFinderMt_Construct(CMatchFinderMt *p) -{ - p->hashBuf = 0; - MtSync_Construct(&p->hashSync); - MtSync_Construct(&p->btSync); -} - -void MatchFinderMt_FreeMem(CMatchFinderMt *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->hashBuf); - p->hashBuf = 0; -} - -void MatchFinderMt_Destruct(CMatchFinderMt *p, ISzAlloc *alloc) -{ - MtSync_Destruct(&p->hashSync); - MtSync_Destruct(&p->btSync); - MatchFinderMt_FreeMem(p, alloc); -} - -#define kHashBufferSize (kMtHashBlockSize * kMtHashNumBlocks) -#define kBtBufferSize (kMtBtBlockSize * kMtBtNumBlocks) - -static unsigned MY_STD_CALL HashThreadFunc2(void *p) { HashThreadFunc((CMatchFinderMt *)p); return 0; } -static unsigned MY_STD_CALL BtThreadFunc2(void *p) -{ - Byte allocaDummy[0x180]; - int i = 0; - for (i = 0; i < 16; i++) - allocaDummy[i] = (Byte)i; - BtThreadFunc((CMatchFinderMt *)p); - return 0; -} - -SRes MatchFinderMt_Create(CMatchFinderMt *p, UInt32 historySize, UInt32 keepAddBufferBefore, - UInt32 matchMaxLen, UInt32 keepAddBufferAfter, ISzAlloc *alloc) -{ - CMatchFinder *mf = p->MatchFinder; - p->historySize = historySize; - if (kMtBtBlockSize <= matchMaxLen * 4) - return SZ_ERROR_PARAM; - if (p->hashBuf == 0) - { - p->hashBuf = (UInt32 *)alloc->Alloc(alloc, (kHashBufferSize + kBtBufferSize) * sizeof(UInt32)); - if (p->hashBuf == 0) - return SZ_ERROR_MEM; - p->btBuf = p->hashBuf + kHashBufferSize; - } - keepAddBufferBefore += (kHashBufferSize + kBtBufferSize); - keepAddBufferAfter += kMtHashBlockSize; - if (!MatchFinder_Create(mf, historySize, keepAddBufferBefore, matchMaxLen, keepAddBufferAfter, alloc)) - return SZ_ERROR_MEM; - - RINOK(MtSync_Create(&p->hashSync, HashThreadFunc2, p, kMtHashNumBlocks)); - RINOK(MtSync_Create(&p->btSync, BtThreadFunc2, p, kMtBtNumBlocks)); - return SZ_OK; -} - -/* Call it after ReleaseStream / SetStream */ -void MatchFinderMt_Init(CMatchFinderMt *p) -{ - CMatchFinder *mf = p->MatchFinder; - p->btBufPos = p->btBufPosLimit = 0; - p->hashBufPos = p->hashBufPosLimit = 0; - MatchFinder_Init(mf); - p->pointerToCurPos = MatchFinder_GetPointerToCurrentPos(mf); - p->btNumAvailBytes = 0; - p->lzPos = p->historySize + 1; - - p->hash = mf->hash; - p->fixedHashSize = mf->fixedHashSize; - p->crc = mf->crc; - - p->son = mf->son; - p->matchMaxLen = mf->matchMaxLen; - p->numHashBytes = mf->numHashBytes; - p->pos = mf->pos; - p->buffer = mf->buffer; - p->cyclicBufferPos = mf->cyclicBufferPos; - p->cyclicBufferSize = mf->cyclicBufferSize; - p->cutValue = mf->cutValue; -} - -/* ReleaseStream is required to finish multithreading */ -void MatchFinderMt_ReleaseStream(CMatchFinderMt *p) -{ - MtSync_StopWriting(&p->btSync); - /* p->MatchFinder->ReleaseStream(); */ -} - -void MatchFinderMt_Normalize(CMatchFinderMt *p) -{ - MatchFinder_Normalize3(p->lzPos - p->historySize - 1, p->hash, p->fixedHashSize); - p->lzPos = p->historySize + 1; -} - -void MatchFinderMt_GetNextBlock_Bt(CMatchFinderMt *p) -{ - UInt32 blockIndex; - MtSync_GetNextBlock(&p->btSync); - blockIndex = ((p->btSync.numProcessedBlocks - 1) & kMtBtNumBlocksMask); - p->btBufPosLimit = p->btBufPos = blockIndex * kMtBtBlockSize; - p->btBufPosLimit += p->btBuf[p->btBufPos++]; - p->btNumAvailBytes = p->btBuf[p->btBufPos++]; - if (p->lzPos >= kMtMaxValForNormalize - kMtBtBlockSize) - MatchFinderMt_Normalize(p); -} - -const Byte * MatchFinderMt_GetPointerToCurrentPos(CMatchFinderMt *p) -{ - return p->pointerToCurPos; -} - -#define GET_NEXT_BLOCK_IF_REQUIRED if (p->btBufPos == p->btBufPosLimit) MatchFinderMt_GetNextBlock_Bt(p); - -UInt32 MatchFinderMt_GetNumAvailableBytes(CMatchFinderMt *p) -{ - GET_NEXT_BLOCK_IF_REQUIRED; - return p->btNumAvailBytes; -} - -Byte MatchFinderMt_GetIndexByte(CMatchFinderMt *p, Int32 index) -{ - return p->pointerToCurPos[index]; -} - -UInt32 * MixMatches2(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances) -{ - UInt32 hash2Value, curMatch2; - UInt32 *hash = p->hash; - const Byte *cur = p->pointerToCurPos; - UInt32 lzPos = p->lzPos; - MT_HASH2_CALC - - curMatch2 = hash[hash2Value]; - hash[hash2Value] = lzPos; - - if (curMatch2 >= matchMinPos) - if (cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0]) - { - *distances++ = 2; - *distances++ = lzPos - curMatch2 - 1; - } - return distances; -} - -UInt32 * MixMatches3(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances) -{ - UInt32 hash2Value, hash3Value, curMatch2, curMatch3; - UInt32 *hash = p->hash; - const Byte *cur = p->pointerToCurPos; - UInt32 lzPos = p->lzPos; - MT_HASH3_CALC - - curMatch2 = hash[ hash2Value]; - curMatch3 = hash[kFix3HashSize + hash3Value]; - - hash[ hash2Value] = - hash[kFix3HashSize + hash3Value] = - lzPos; - - if (curMatch2 >= matchMinPos && cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0]) - { - distances[1] = lzPos - curMatch2 - 1; - if (cur[(ptrdiff_t)curMatch2 - lzPos + 2] == cur[2]) - { - distances[0] = 3; - return distances + 2; - } - distances[0] = 2; - distances += 2; - } - if (curMatch3 >= matchMinPos && cur[(ptrdiff_t)curMatch3 - lzPos] == cur[0]) - { - *distances++ = 3; - *distances++ = lzPos - curMatch3 - 1; - } - return distances; -} - -/* -UInt32 *MixMatches4(CMatchFinderMt *p, UInt32 matchMinPos, UInt32 *distances) -{ - UInt32 hash2Value, hash3Value, hash4Value, curMatch2, curMatch3, curMatch4; - UInt32 *hash = p->hash; - const Byte *cur = p->pointerToCurPos; - UInt32 lzPos = p->lzPos; - MT_HASH4_CALC - - curMatch2 = hash[ hash2Value]; - curMatch3 = hash[kFix3HashSize + hash3Value]; - curMatch4 = hash[kFix4HashSize + hash4Value]; - - hash[ hash2Value] = - hash[kFix3HashSize + hash3Value] = - hash[kFix4HashSize + hash4Value] = - lzPos; - - if (curMatch2 >= matchMinPos && cur[(ptrdiff_t)curMatch2 - lzPos] == cur[0]) - { - distances[1] = lzPos - curMatch2 - 1; - if (cur[(ptrdiff_t)curMatch2 - lzPos + 2] == cur[2]) - { - distances[0] = (cur[(ptrdiff_t)curMatch2 - lzPos + 3] == cur[3]) ? 4 : 3; - return distances + 2; - } - distances[0] = 2; - distances += 2; - } - if (curMatch3 >= matchMinPos && cur[(ptrdiff_t)curMatch3 - lzPos] == cur[0]) - { - distances[1] = lzPos - curMatch3 - 1; - if (cur[(ptrdiff_t)curMatch3 - lzPos + 3] == cur[3]) - { - distances[0] = 4; - return distances + 2; - } - distances[0] = 3; - distances += 2; - } - - if (curMatch4 >= matchMinPos) - if ( - cur[(ptrdiff_t)curMatch4 - lzPos] == cur[0] && - cur[(ptrdiff_t)curMatch4 - lzPos + 3] == cur[3] - ) - { - *distances++ = 4; - *distances++ = lzPos - curMatch4 - 1; - } - return distances; -} -*/ - -#define INCREASE_LZ_POS p->lzPos++; p->pointerToCurPos++; - -UInt32 MatchFinderMt2_GetMatches(CMatchFinderMt *p, UInt32 *distances) -{ - const UInt32 *btBuf = p->btBuf + p->btBufPos; - UInt32 len = *btBuf++; - p->btBufPos += 1 + len; - p->btNumAvailBytes--; - { - UInt32 i; - for (i = 0; i < len; i += 2) - { - *distances++ = *btBuf++; - *distances++ = *btBuf++; - } - } - INCREASE_LZ_POS - return len; -} - -UInt32 MatchFinderMt_GetMatches(CMatchFinderMt *p, UInt32 *distances) -{ - const UInt32 *btBuf = p->btBuf + p->btBufPos; - UInt32 len = *btBuf++; - p->btBufPos += 1 + len; - - if (len == 0) - { - if (p->btNumAvailBytes-- >= 4) - len = (UInt32)(p->MixMatchesFunc(p, p->lzPos - p->historySize, distances) - (distances)); - } - else - { - /* Condition: there are matches in btBuf with length < p->numHashBytes */ - UInt32 *distances2; - p->btNumAvailBytes--; - distances2 = p->MixMatchesFunc(p, p->lzPos - btBuf[1], distances); - do - { - *distances2++ = *btBuf++; - *distances2++ = *btBuf++; - } - while ((len -= 2) != 0); - len = (UInt32)(distances2 - (distances)); - } - INCREASE_LZ_POS - return len; -} - -#define SKIP_HEADER2 do { GET_NEXT_BLOCK_IF_REQUIRED -#define SKIP_HEADER(n) SKIP_HEADER2 if (p->btNumAvailBytes-- >= (n)) { const Byte *cur = p->pointerToCurPos; UInt32 *hash = p->hash; -#define SKIP_FOOTER } INCREASE_LZ_POS p->btBufPos += p->btBuf[p->btBufPos] + 1; } while (--num != 0); - -void MatchFinderMt0_Skip(CMatchFinderMt *p, UInt32 num) -{ - SKIP_HEADER2 { p->btNumAvailBytes--; - SKIP_FOOTER -} - -void MatchFinderMt2_Skip(CMatchFinderMt *p, UInt32 num) -{ - SKIP_HEADER(2) - UInt32 hash2Value; - MT_HASH2_CALC - hash[hash2Value] = p->lzPos; - SKIP_FOOTER -} - -void MatchFinderMt3_Skip(CMatchFinderMt *p, UInt32 num) -{ - SKIP_HEADER(3) - UInt32 hash2Value, hash3Value; - MT_HASH3_CALC - hash[kFix3HashSize + hash3Value] = - hash[ hash2Value] = - p->lzPos; - SKIP_FOOTER -} - -/* -void MatchFinderMt4_Skip(CMatchFinderMt *p, UInt32 num) -{ - SKIP_HEADER(4) - UInt32 hash2Value, hash3Value, hash4Value; - MT_HASH4_CALC - hash[kFix4HashSize + hash4Value] = - hash[kFix3HashSize + hash3Value] = - hash[ hash2Value] = - p->lzPos; - SKIP_FOOTER -} -*/ - -void MatchFinderMt_CreateVTable(CMatchFinderMt *p, IMatchFinder *vTable) -{ - vTable->Init = (Mf_Init_Func)MatchFinderMt_Init; - vTable->GetIndexByte = (Mf_GetIndexByte_Func)MatchFinderMt_GetIndexByte; - vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinderMt_GetNumAvailableBytes; - vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinderMt_GetPointerToCurrentPos; - vTable->GetMatches = (Mf_GetMatches_Func)MatchFinderMt_GetMatches; - switch(p->MatchFinder->numHashBytes) - { - case 2: - p->GetHeadsFunc = GetHeads2; - p->MixMatchesFunc = (Mf_Mix_Matches)0; - vTable->Skip = (Mf_Skip_Func)MatchFinderMt0_Skip; - vTable->GetMatches = (Mf_GetMatches_Func)MatchFinderMt2_GetMatches; - break; - case 3: - p->GetHeadsFunc = GetHeads3; - p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches2; - vTable->Skip = (Mf_Skip_Func)MatchFinderMt2_Skip; - break; - default: - /* case 4: */ - p->GetHeadsFunc = p->MatchFinder->bigHash ? GetHeads4b : GetHeads4; - /* p->GetHeadsFunc = GetHeads4; */ - p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches3; - vTable->Skip = (Mf_Skip_Func)MatchFinderMt3_Skip; - break; - /* - default: - p->GetHeadsFunc = GetHeads5; - p->MixMatchesFunc = (Mf_Mix_Matches)MixMatches4; - vTable->Skip = (Mf_Skip_Func)MatchFinderMt4_Skip; - break; - */ - } -} diff --git a/desmume/src/windows/7z/C/LzFindMt.h b/desmume/src/windows/7z/C/LzFindMt.h deleted file mode 100644 index b7ead2d47..000000000 --- a/desmume/src/windows/7z/C/LzFindMt.h +++ /dev/null @@ -1,97 +0,0 @@ -/* LzFindMt.h -- multithreaded Match finder for LZ algorithms -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __LZFINDMT_H -#define __LZFINDMT_H - -#include "Threads.h" -#include "LzFind.h" - -#define kMtHashBlockSize (1 << 13) -#define kMtHashNumBlocks (1 << 3) -#define kMtHashNumBlocksMask (kMtHashNumBlocks - 1) - -#define kMtBtBlockSize (1 << 14) -#define kMtBtNumBlocks (1 << 6) -#define kMtBtNumBlocksMask (kMtBtNumBlocks - 1) - -typedef struct _CMtSync -{ - Bool wasCreated; - Bool needStart; - Bool exit; - Bool stopWriting; - - CThread thread; - CAutoResetEvent canStart; - CAutoResetEvent wasStarted; - CAutoResetEvent wasStopped; - CSemaphore freeSemaphore; - CSemaphore filledSemaphore; - Bool csWasInitialized; - Bool csWasEntered; - CCriticalSection cs; - UInt32 numProcessedBlocks; -} CMtSync; - -typedef UInt32 * (*Mf_Mix_Matches)(void *p, UInt32 matchMinPos, UInt32 *distances); - -/* kMtCacheLineDummy must be >= size_of_CPU_cache_line */ -#define kMtCacheLineDummy 128 - -typedef void (*Mf_GetHeads)(const Byte *buffer, UInt32 pos, - UInt32 *hash, UInt32 hashMask, UInt32 *heads, UInt32 numHeads, const UInt32 *crc); - -typedef struct _CMatchFinderMt -{ - /* LZ */ - const Byte *pointerToCurPos; - UInt32 *btBuf; - UInt32 btBufPos; - UInt32 btBufPosLimit; - UInt32 lzPos; - UInt32 btNumAvailBytes; - - UInt32 *hash; - UInt32 fixedHashSize; - UInt32 historySize; - const UInt32 *crc; - - Mf_Mix_Matches MixMatchesFunc; - - /* LZ + BT */ - CMtSync btSync; - Byte btDummy[kMtCacheLineDummy]; - - /* BT */ - UInt32 *hashBuf; - UInt32 hashBufPos; - UInt32 hashBufPosLimit; - UInt32 hashNumAvail; - - CLzRef *son; - UInt32 matchMaxLen; - UInt32 numHashBytes; - UInt32 pos; - Byte *buffer; - UInt32 cyclicBufferPos; - UInt32 cyclicBufferSize; /* it must be historySize + 1 */ - UInt32 cutValue; - - /* BT + Hash */ - CMtSync hashSync; - /* Byte hashDummy[kMtCacheLineDummy]; */ - - /* Hash */ - Mf_GetHeads GetHeadsFunc; - CMatchFinder *MatchFinder; -} CMatchFinderMt; - -void MatchFinderMt_Construct(CMatchFinderMt *p); -void MatchFinderMt_Destruct(CMatchFinderMt *p, ISzAlloc *alloc); -SRes MatchFinderMt_Create(CMatchFinderMt *p, UInt32 historySize, UInt32 keepAddBufferBefore, - UInt32 matchMaxLen, UInt32 keepAddBufferAfter, ISzAlloc *alloc); -void MatchFinderMt_CreateVTable(CMatchFinderMt *p, IMatchFinder *vTable); -void MatchFinderMt_ReleaseStream(CMatchFinderMt *p); - -#endif diff --git a/desmume/src/windows/7z/C/LzHash.h b/desmume/src/windows/7z/C/LzHash.h deleted file mode 100644 index c92341750..000000000 --- a/desmume/src/windows/7z/C/LzHash.h +++ /dev/null @@ -1,54 +0,0 @@ -/* LzHash.h -- HASH functions for LZ algorithms -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __LZHASH_H -#define __LZHASH_H - -#define kHash2Size (1 << 10) -#define kHash3Size (1 << 16) -#define kHash4Size (1 << 20) - -#define kFix3HashSize (kHash2Size) -#define kFix4HashSize (kHash2Size + kHash3Size) -#define kFix5HashSize (kHash2Size + kHash3Size + kHash4Size) - -#define HASH2_CALC hashValue = cur[0] | ((UInt32)cur[1] << 8); - -#define HASH3_CALC { \ - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - hash2Value = temp & (kHash2Size - 1); \ - hashValue = (temp ^ ((UInt32)cur[2] << 8)) & p->hashMask; } - -#define HASH4_CALC { \ - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - hash2Value = temp & (kHash2Size - 1); \ - hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \ - hashValue = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & p->hashMask; } - -#define HASH5_CALC { \ - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - hash2Value = temp & (kHash2Size - 1); \ - hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \ - hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)); \ - hashValue = (hash4Value ^ (p->crc[cur[4]] << 3)) & p->hashMask; \ - hash4Value &= (kHash4Size - 1); } - -/* #define HASH_ZIP_CALC hashValue = ((cur[0] | ((UInt32)cur[1] << 8)) ^ p->crc[cur[2]]) & 0xFFFF; */ -#define HASH_ZIP_CALC hashValue = ((cur[2] | ((UInt32)cur[0] << 8)) ^ p->crc[cur[1]]) & 0xFFFF; - - -#define MT_HASH2_CALC \ - hash2Value = (p->crc[cur[0]] ^ cur[1]) & (kHash2Size - 1); - -#define MT_HASH3_CALC { \ - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - hash2Value = temp & (kHash2Size - 1); \ - hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); } - -#define MT_HASH4_CALC { \ - UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ - hash2Value = temp & (kHash2Size - 1); \ - hash3Value = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); \ - hash4Value = (temp ^ ((UInt32)cur[2] << 8) ^ (p->crc[cur[3]] << 5)) & (kHash4Size - 1); } - -#endif diff --git a/desmume/src/windows/7z/C/LzmaDec.c b/desmume/src/windows/7z/C/LzmaDec.c deleted file mode 100644 index e40e4286e..000000000 --- a/desmume/src/windows/7z/C/LzmaDec.c +++ /dev/null @@ -1,1007 +0,0 @@ -/* LzmaDec.c -- LZMA Decoder -2008-11-06 : Igor Pavlov : Public domain */ - -#include "LzmaDec.h" - -#include - -#define kNumTopBits 24 -#define kTopValue ((UInt32)1 << kNumTopBits) - -#define kNumBitModelTotalBits 11 -#define kBitModelTotal (1 << kNumBitModelTotalBits) -#define kNumMoveBits 5 - -#define RC_INIT_SIZE 5 - -#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); } - -#define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound) -#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); -#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits)); -#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \ - { UPDATE_0(p); i = (i + i); A0; } else \ - { UPDATE_1(p); i = (i + i) + 1; A1; } -#define GET_BIT(p, i) GET_BIT2(p, i, ; , ;) - -#define TREE_GET_BIT(probs, i) { GET_BIT((probs + i), i); } -#define TREE_DECODE(probs, limit, i) \ - { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; } - -/* #define _LZMA_SIZE_OPT */ - -#ifdef _LZMA_SIZE_OPT -#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i) -#else -#define TREE_6_DECODE(probs, i) \ - { i = 1; \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - TREE_GET_BIT(probs, i); \ - i -= 0x40; } -#endif - -#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); } - -#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound) -#define UPDATE_0_CHECK range = bound; -#define UPDATE_1_CHECK range -= bound; code -= bound; -#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \ - { UPDATE_0_CHECK; i = (i + i); A0; } else \ - { UPDATE_1_CHECK; i = (i + i) + 1; A1; } -#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;) -#define TREE_DECODE_CHECK(probs, limit, i) \ - { i = 1; do { GET_BIT_CHECK(probs + i, i) } while (i < limit); i -= limit; } - - -#define kNumPosBitsMax 4 -#define kNumPosStatesMax (1 << kNumPosBitsMax) - -#define kLenNumLowBits 3 -#define kLenNumLowSymbols (1 << kLenNumLowBits) -#define kLenNumMidBits 3 -#define kLenNumMidSymbols (1 << kLenNumMidBits) -#define kLenNumHighBits 8 -#define kLenNumHighSymbols (1 << kLenNumHighBits) - -#define LenChoice 0 -#define LenChoice2 (LenChoice + 1) -#define LenLow (LenChoice2 + 1) -#define LenMid (LenLow + (kNumPosStatesMax << kLenNumLowBits)) -#define LenHigh (LenMid + (kNumPosStatesMax << kLenNumMidBits)) -#define kNumLenProbs (LenHigh + kLenNumHighSymbols) - - -#define kNumStates 12 -#define kNumLitStates 7 - -#define kStartPosModelIndex 4 -#define kEndPosModelIndex 14 -#define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) - -#define kNumPosSlotBits 6 -#define kNumLenToPosStates 4 - -#define kNumAlignBits 4 -#define kAlignTableSize (1 << kNumAlignBits) - -#define kMatchMinLen 2 -#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols) - -#define IsMatch 0 -#define IsRep (IsMatch + (kNumStates << kNumPosBitsMax)) -#define IsRepG0 (IsRep + kNumStates) -#define IsRepG1 (IsRepG0 + kNumStates) -#define IsRepG2 (IsRepG1 + kNumStates) -#define IsRep0Long (IsRepG2 + kNumStates) -#define PosSlot (IsRep0Long + (kNumStates << kNumPosBitsMax)) -#define SpecPos (PosSlot + (kNumLenToPosStates << kNumPosSlotBits)) -#define Align (SpecPos + kNumFullDistances - kEndPosModelIndex) -#define LenCoder (Align + kAlignTableSize) -#define RepLenCoder (LenCoder + kNumLenProbs) -#define Literal (RepLenCoder + kNumLenProbs) - -#define LZMA_BASE_SIZE 1846 -#define LZMA_LIT_SIZE 768 - -#define LzmaProps_GetNumProbs(p) ((UInt32)LZMA_BASE_SIZE + (LZMA_LIT_SIZE << ((p)->lc + (p)->lp))) - -#if Literal != LZMA_BASE_SIZE -StopCompilingDueBUG -#endif - -static const Byte kLiteralNextStates[kNumStates * 2] = -{ - 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5, - 7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10 -}; - -#define LZMA_DIC_MIN (1 << 12) - -/* First LZMA-symbol is always decoded. -And it decodes new LZMA-symbols while (buf < bufLimit), but "buf" is without last normalization -Out: - Result: - SZ_OK - OK - SZ_ERROR_DATA - Error - p->remainLen: - < kMatchSpecLenStart : normal remain - = kMatchSpecLenStart : finished - = kMatchSpecLenStart + 1 : Flush marker - = kMatchSpecLenStart + 2 : State Init Marker -*/ - -static int MY_FAST_CALL LzmaDec_DecodeReal(CLzmaDec *p, SizeT limit, const Byte *bufLimit) -{ - CLzmaProb *probs = p->probs; - - unsigned state = p->state; - UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3]; - unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1; - unsigned lpMask = ((unsigned)1 << (p->prop.lp)) - 1; - unsigned lc = p->prop.lc; - - Byte *dic = p->dic; - SizeT dicBufSize = p->dicBufSize; - SizeT dicPos = p->dicPos; - - UInt32 processedPos = p->processedPos; - UInt32 checkDicSize = p->checkDicSize; - unsigned len = 0; - - const Byte *buf = p->buf; - UInt32 range = p->range; - UInt32 code = p->code; - - do - { - CLzmaProb *prob; - UInt32 bound; - unsigned ttt; - unsigned posState = processedPos & pbMask; - - prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; - IF_BIT_0(prob) - { - unsigned symbol; - UPDATE_0(prob); - prob = probs + Literal; - if (checkDicSize != 0 || processedPos != 0) - prob += (LZMA_LIT_SIZE * (((processedPos & lpMask) << lc) + - (dic[(dicPos == 0 ? dicBufSize : dicPos) - 1] >> (8 - lc)))); - - if (state < kNumLitStates) - { - symbol = 1; - do { GET_BIT(prob + symbol, symbol) } while (symbol < 0x100); - } - else - { - unsigned matchByte = p->dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; - unsigned offs = 0x100; - symbol = 1; - do - { - unsigned bit; - CLzmaProb *probLit; - matchByte <<= 1; - bit = (matchByte & offs); - probLit = prob + offs + bit + symbol; - GET_BIT2(probLit, symbol, offs &= ~bit, offs &= bit) - } - while (symbol < 0x100); - } - dic[dicPos++] = (Byte)(symbol & 0xFF); - processedPos++; - - state = kLiteralNextStates[state]; - /* if (state < 4) state = 0; else if (state < 10) state -= 3; else state -= 6; */ - continue; - } - else - { - UPDATE_1(prob); - prob = probs + IsRep + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - state += kNumStates; - prob = probs + LenCoder; - } - else - { - UPDATE_1(prob); - if (checkDicSize == 0 && processedPos == 0) - return SZ_ERROR_DATA; - prob = probs + IsRepG0 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState; - IF_BIT_0(prob) - { - UPDATE_0(prob); - dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; - dicPos++; - processedPos++; - state = state < kNumLitStates ? 9 : 11; - continue; - } - UPDATE_1(prob); - } - else - { - UInt32 distance; - UPDATE_1(prob); - prob = probs + IsRepG1 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - distance = rep1; - } - else - { - UPDATE_1(prob); - prob = probs + IsRepG2 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - distance = rep2; - } - else - { - UPDATE_1(prob); - distance = rep3; - rep3 = rep2; - } - rep2 = rep1; - } - rep1 = rep0; - rep0 = distance; - } - state = state < kNumLitStates ? 8 : 11; - prob = probs + RepLenCoder; - } - { - unsigned limit, offset; - CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0(probLen) - { - UPDATE_0(probLen); - probLen = prob + LenLow + (posState << kLenNumLowBits); - offset = 0; - limit = (1 << kLenNumLowBits); - } - else - { - UPDATE_1(probLen); - probLen = prob + LenChoice2; - IF_BIT_0(probLen) - { - UPDATE_0(probLen); - probLen = prob + LenMid + (posState << kLenNumMidBits); - offset = kLenNumLowSymbols; - limit = (1 << kLenNumMidBits); - } - else - { - UPDATE_1(probLen); - probLen = prob + LenHigh; - offset = kLenNumLowSymbols + kLenNumMidSymbols; - limit = (1 << kLenNumHighBits); - } - } - TREE_DECODE(probLen, limit, len); - len += offset; - } - - if (state >= kNumStates) - { - UInt32 distance; - prob = probs + PosSlot + - ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); - TREE_6_DECODE(prob, distance); - if (distance >= kStartPosModelIndex) - { - unsigned posSlot = (unsigned)distance; - int numDirectBits = (int)(((distance >> 1) - 1)); - distance = (2 | (distance & 1)); - if (posSlot < kEndPosModelIndex) - { - distance <<= numDirectBits; - prob = probs + SpecPos + distance - posSlot - 1; - { - UInt32 mask = 1; - unsigned i = 1; - do - { - GET_BIT2(prob + i, i, ; , distance |= mask); - mask <<= 1; - } - while (--numDirectBits != 0); - } - } - else - { - numDirectBits -= kNumAlignBits; - do - { - NORMALIZE - range >>= 1; - - { - UInt32 t; - code -= range; - t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */ - distance = (distance << 1) + (t + 1); - code += range & t; - } - /* - distance <<= 1; - if (code >= range) - { - code -= range; - distance |= 1; - } - */ - } - while (--numDirectBits != 0); - prob = probs + Align; - distance <<= kNumAlignBits; - { - unsigned i = 1; - GET_BIT2(prob + i, i, ; , distance |= 1); - GET_BIT2(prob + i, i, ; , distance |= 2); - GET_BIT2(prob + i, i, ; , distance |= 4); - GET_BIT2(prob + i, i, ; , distance |= 8); - } - if (distance == (UInt32)0xFFFFFFFF) - { - len += kMatchSpecLenStart; - state -= kNumStates; - break; - } - } - } - rep3 = rep2; - rep2 = rep1; - rep1 = rep0; - rep0 = distance + 1; - if (checkDicSize == 0) - { - if (distance >= processedPos) - return SZ_ERROR_DATA; - } - else if (distance >= checkDicSize) - return SZ_ERROR_DATA; - state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3; - /* state = kLiteralNextStates[state]; */ - } - - len += kMatchMinLen; - - if (limit == dicPos) - return SZ_ERROR_DATA; - { - SizeT rem = limit - dicPos; - unsigned curLen = ((rem < len) ? (unsigned)rem : len); - SizeT pos = (dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0); - - processedPos += curLen; - - len -= curLen; - if (pos + curLen <= dicBufSize) - { - Byte *dest = dic + dicPos; - ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos; - const Byte *lim = dest + curLen; - dicPos += curLen; - do - *(dest) = (Byte)*(dest + src); - while (++dest != lim); - } - else - { - do - { - dic[dicPos++] = dic[pos]; - if (++pos == dicBufSize) - pos = 0; - } - while (--curLen != 0); - } - } - } - } - while (dicPos < limit && buf < bufLimit); - NORMALIZE; - p->buf = buf; - p->range = range; - p->code = code; - p->remainLen = len; - p->dicPos = dicPos; - p->processedPos = processedPos; - p->reps[0] = rep0; - p->reps[1] = rep1; - p->reps[2] = rep2; - p->reps[3] = rep3; - p->state = state; - - return SZ_OK; -} - -static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) -{ - if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart) - { - Byte *dic = p->dic; - SizeT dicPos = p->dicPos; - SizeT dicBufSize = p->dicBufSize; - unsigned len = p->remainLen; - UInt32 rep0 = p->reps[0]; - if (limit - dicPos < len) - len = (unsigned)(limit - dicPos); - - if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len) - p->checkDicSize = p->prop.dicSize; - - p->processedPos += len; - p->remainLen -= len; - while (len-- != 0) - { - dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; - dicPos++; - } - p->dicPos = dicPos; - } -} - -static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) -{ - do - { - SizeT limit2 = limit; - if (p->checkDicSize == 0) - { - UInt32 rem = p->prop.dicSize - p->processedPos; - if (limit - p->dicPos > rem) - limit2 = p->dicPos + rem; - } - RINOK(LzmaDec_DecodeReal(p, limit2, bufLimit)); - if (p->processedPos >= p->prop.dicSize) - p->checkDicSize = p->prop.dicSize; - LzmaDec_WriteRem(p, limit); - } - while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart); - - if (p->remainLen > kMatchSpecLenStart) - { - p->remainLen = kMatchSpecLenStart; - } - return 0; -} - -typedef enum -{ - DUMMY_ERROR, /* unexpected end of input stream */ - DUMMY_LIT, - DUMMY_MATCH, - DUMMY_REP -} ELzmaDummy; - -static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, SizeT inSize) -{ - UInt32 range = p->range; - UInt32 code = p->code; - const Byte *bufLimit = buf + inSize; - CLzmaProb *probs = p->probs; - unsigned state = p->state; - ELzmaDummy res; - - { - CLzmaProb *prob; - UInt32 bound; - unsigned ttt; - unsigned posState = (p->processedPos) & ((1 << p->prop.pb) - 1); - - prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK - - /* if (bufLimit - buf >= 7) return DUMMY_LIT; */ - - prob = probs + Literal; - if (p->checkDicSize != 0 || p->processedPos != 0) - prob += (LZMA_LIT_SIZE * - ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) + - (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc)))); - - if (state < kNumLitStates) - { - unsigned symbol = 1; - do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100); - } - else - { - unsigned matchByte = p->dic[p->dicPos - p->reps[0] + - ((p->dicPos < p->reps[0]) ? p->dicBufSize : 0)]; - unsigned offs = 0x100; - unsigned symbol = 1; - do - { - unsigned bit; - CLzmaProb *probLit; - matchByte <<= 1; - bit = (matchByte & offs); - probLit = prob + offs + bit + symbol; - GET_BIT2_CHECK(probLit, symbol, offs &= ~bit, offs &= bit) - } - while (symbol < 0x100); - } - res = DUMMY_LIT; - } - else - { - unsigned len; - UPDATE_1_CHECK; - - prob = probs + IsRep + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - state = 0; - prob = probs + LenCoder; - res = DUMMY_MATCH; - } - else - { - UPDATE_1_CHECK; - res = DUMMY_REP; - prob = probs + IsRepG0 + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - NORMALIZE_CHECK; - return DUMMY_REP; - } - else - { - UPDATE_1_CHECK; - } - } - else - { - UPDATE_1_CHECK; - prob = probs + IsRepG1 + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - } - else - { - UPDATE_1_CHECK; - prob = probs + IsRepG2 + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - } - else - { - UPDATE_1_CHECK; - } - } - } - state = kNumStates; - prob = probs + RepLenCoder; - } - { - unsigned limit, offset; - CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0_CHECK(probLen) - { - UPDATE_0_CHECK; - probLen = prob + LenLow + (posState << kLenNumLowBits); - offset = 0; - limit = 1 << kLenNumLowBits; - } - else - { - UPDATE_1_CHECK; - probLen = prob + LenChoice2; - IF_BIT_0_CHECK(probLen) - { - UPDATE_0_CHECK; - probLen = prob + LenMid + (posState << kLenNumMidBits); - offset = kLenNumLowSymbols; - limit = 1 << kLenNumMidBits; - } - else - { - UPDATE_1_CHECK; - probLen = prob + LenHigh; - offset = kLenNumLowSymbols + kLenNumMidSymbols; - limit = 1 << kLenNumHighBits; - } - } - TREE_DECODE_CHECK(probLen, limit, len); - len += offset; - } - - if (state < 4) - { - unsigned posSlot; - prob = probs + PosSlot + - ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << - kNumPosSlotBits); - TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot); - if (posSlot >= kStartPosModelIndex) - { - int numDirectBits = ((posSlot >> 1) - 1); - - /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */ - - if (posSlot < kEndPosModelIndex) - { - prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1; - } - else - { - numDirectBits -= kNumAlignBits; - do - { - NORMALIZE_CHECK - range >>= 1; - code -= range & (((code - range) >> 31) - 1); - /* if (code >= range) code -= range; */ - } - while (--numDirectBits != 0); - prob = probs + Align; - numDirectBits = kNumAlignBits; - } - { - unsigned i = 1; - do - { - GET_BIT_CHECK(prob + i, i); - } - while (--numDirectBits != 0); - } - } - } - } - } - NORMALIZE_CHECK; - return res; -} - - -static void LzmaDec_InitRc(CLzmaDec *p, const Byte *data) -{ - p->code = ((UInt32)data[1] << 24) | ((UInt32)data[2] << 16) | ((UInt32)data[3] << 8) | ((UInt32)data[4]); - p->range = 0xFFFFFFFF; - p->needFlush = 0; -} - -void LzmaDec_InitDicAndState(CLzmaDec *p, Bool initDic, Bool initState) -{ - p->needFlush = 1; - p->remainLen = 0; - p->tempBufSize = 0; - - if (initDic) - { - p->processedPos = 0; - p->checkDicSize = 0; - p->needInitState = 1; - } - if (initState) - p->needInitState = 1; -} - -void LzmaDec_Init(CLzmaDec *p) -{ - p->dicPos = 0; - LzmaDec_InitDicAndState(p, True, True); -} - -static void LzmaDec_InitStateReal(CLzmaDec *p) -{ - UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (p->prop.lc + p->prop.lp)); - UInt32 i; - CLzmaProb *probs = p->probs; - for (i = 0; i < numProbs; i++) - probs[i] = kBitModelTotal >> 1; - p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1; - p->state = 0; - p->needInitState = 0; -} - -SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *srcLen, - ELzmaFinishMode finishMode, ELzmaStatus *status) -{ - SizeT inSize = *srcLen; - (*srcLen) = 0; - LzmaDec_WriteRem(p, dicLimit); - - *status = LZMA_STATUS_NOT_SPECIFIED; - - while (p->remainLen != kMatchSpecLenStart) - { - int checkEndMarkNow; - - if (p->needFlush != 0) - { - for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--) - p->tempBuf[p->tempBufSize++] = *src++; - if (p->tempBufSize < RC_INIT_SIZE) - { - *status = LZMA_STATUS_NEEDS_MORE_INPUT; - return SZ_OK; - } - if (p->tempBuf[0] != 0) - return SZ_ERROR_DATA; - - LzmaDec_InitRc(p, p->tempBuf); - p->tempBufSize = 0; - } - - checkEndMarkNow = 0; - if (p->dicPos >= dicLimit) - { - if (p->remainLen == 0 && p->code == 0) - { - *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK; - return SZ_OK; - } - if (finishMode == LZMA_FINISH_ANY) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_OK; - } - if (p->remainLen != 0) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_ERROR_DATA; - } - checkEndMarkNow = 1; - } - - if (p->needInitState) - LzmaDec_InitStateReal(p); - - if (p->tempBufSize == 0) - { - SizeT processed; - const Byte *bufLimit; - if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) - { - int dummyRes = LzmaDec_TryDummy(p, src, inSize); - if (dummyRes == DUMMY_ERROR) - { - memcpy(p->tempBuf, src, inSize); - p->tempBufSize = (unsigned)inSize; - (*srcLen) += inSize; - *status = LZMA_STATUS_NEEDS_MORE_INPUT; - return SZ_OK; - } - if (checkEndMarkNow && dummyRes != DUMMY_MATCH) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_ERROR_DATA; - } - bufLimit = src; - } - else - bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX; - p->buf = src; - if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0) - return SZ_ERROR_DATA; - processed = (SizeT)(p->buf - src); - (*srcLen) += processed; - src += processed; - inSize -= processed; - } - else - { - unsigned rem = p->tempBufSize, lookAhead = 0; - while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize) - p->tempBuf[rem++] = src[lookAhead++]; - p->tempBufSize = rem; - if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) - { - int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem); - if (dummyRes == DUMMY_ERROR) - { - (*srcLen) += lookAhead; - *status = LZMA_STATUS_NEEDS_MORE_INPUT; - return SZ_OK; - } - if (checkEndMarkNow && dummyRes != DUMMY_MATCH) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_ERROR_DATA; - } - } - p->buf = p->tempBuf; - if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0) - return SZ_ERROR_DATA; - lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf)); - (*srcLen) += lookAhead; - src += lookAhead; - inSize -= lookAhead; - p->tempBufSize = 0; - } - } - if (p->code == 0) - *status = LZMA_STATUS_FINISHED_WITH_MARK; - return (p->code == 0) ? SZ_OK : SZ_ERROR_DATA; -} - -SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status) -{ - SizeT outSize = *destLen; - SizeT inSize = *srcLen; - *srcLen = *destLen = 0; - for (;;) - { - SizeT inSizeCur = inSize, outSizeCur, dicPos; - ELzmaFinishMode curFinishMode; - SRes res; - if (p->dicPos == p->dicBufSize) - p->dicPos = 0; - dicPos = p->dicPos; - if (outSize > p->dicBufSize - dicPos) - { - outSizeCur = p->dicBufSize; - curFinishMode = LZMA_FINISH_ANY; - } - else - { - outSizeCur = dicPos + outSize; - curFinishMode = finishMode; - } - - res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status); - src += inSizeCur; - inSize -= inSizeCur; - *srcLen += inSizeCur; - outSizeCur = p->dicPos - dicPos; - memcpy(dest, p->dic + dicPos, outSizeCur); - dest += outSizeCur; - outSize -= outSizeCur; - *destLen += outSizeCur; - if (res != 0) - return res; - if (outSizeCur == 0 || outSize == 0) - return SZ_OK; - } -} - -void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->probs); - p->probs = 0; -} - -static void LzmaDec_FreeDict(CLzmaDec *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->dic); - p->dic = 0; -} - -void LzmaDec_Free(CLzmaDec *p, ISzAlloc *alloc) -{ - LzmaDec_FreeProbs(p, alloc); - LzmaDec_FreeDict(p, alloc); -} - -SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size) -{ - UInt32 dicSize; - Byte d; - - if (size < LZMA_PROPS_SIZE) - return SZ_ERROR_UNSUPPORTED; - else - dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24); - - if (dicSize < LZMA_DIC_MIN) - dicSize = LZMA_DIC_MIN; - p->dicSize = dicSize; - - d = data[0]; - if (d >= (9 * 5 * 5)) - return SZ_ERROR_UNSUPPORTED; - - p->lc = d % 9; - d /= 9; - p->pb = d / 5; - p->lp = d % 5; - - return SZ_OK; -} - -static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAlloc *alloc) -{ - UInt32 numProbs = LzmaProps_GetNumProbs(propNew); - if (p->probs == 0 || numProbs != p->numProbs) - { - LzmaDec_FreeProbs(p, alloc); - p->probs = (CLzmaProb *)alloc->Alloc(alloc, numProbs * sizeof(CLzmaProb)); - p->numProbs = numProbs; - if (p->probs == 0) - return SZ_ERROR_MEM; - } - return SZ_OK; -} - -SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc) -{ - CLzmaProps propNew; - RINOK(LzmaProps_Decode(&propNew, props, propsSize)); - RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); - p->prop = propNew; - return SZ_OK; -} - -SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc) -{ - CLzmaProps propNew; - SizeT dicBufSize; - RINOK(LzmaProps_Decode(&propNew, props, propsSize)); - RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); - dicBufSize = propNew.dicSize; - if (p->dic == 0 || dicBufSize != p->dicBufSize) - { - LzmaDec_FreeDict(p, alloc); - p->dic = (Byte *)alloc->Alloc(alloc, dicBufSize); - if (p->dic == 0) - { - LzmaDec_FreeProbs(p, alloc); - return SZ_ERROR_MEM; - } - } - p->dicBufSize = dicBufSize; - p->prop = propNew; - return SZ_OK; -} - -SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, - const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode, - ELzmaStatus *status, ISzAlloc *alloc) -{ - CLzmaDec p; - SRes res; - SizeT inSize = *srcLen; - SizeT outSize = *destLen; - *srcLen = *destLen = 0; - if (inSize < RC_INIT_SIZE) - return SZ_ERROR_INPUT_EOF; - - LzmaDec_Construct(&p); - res = LzmaDec_AllocateProbs(&p, propData, propSize, alloc); - if (res != 0) - return res; - p.dic = dest; - p.dicBufSize = outSize; - - LzmaDec_Init(&p); - - *srcLen = inSize; - res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status); - - if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT) - res = SZ_ERROR_INPUT_EOF; - - (*destLen) = p.dicPos; - LzmaDec_FreeProbs(&p, alloc); - return res; -} diff --git a/desmume/src/windows/7z/C/LzmaDec.h b/desmume/src/windows/7z/C/LzmaDec.h deleted file mode 100644 index ad7d7057a..000000000 --- a/desmume/src/windows/7z/C/LzmaDec.h +++ /dev/null @@ -1,223 +0,0 @@ -/* LzmaDec.h -- LZMA Decoder -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __LZMADEC_H -#define __LZMADEC_H - -#include "Types.h" - -/* #define _LZMA_PROB32 */ -/* _LZMA_PROB32 can increase the speed on some CPUs, - but memory usage for CLzmaDec::probs will be doubled in that case */ - -#ifdef _LZMA_PROB32 -#define CLzmaProb UInt32 -#else -#define CLzmaProb UInt16 -#endif - - -/* ---------- LZMA Properties ---------- */ - -#define LZMA_PROPS_SIZE 5 - -typedef struct _CLzmaProps -{ - unsigned lc, lp, pb; - UInt32 dicSize; -} CLzmaProps; - -/* LzmaProps_Decode - decodes properties -Returns: - SZ_OK - SZ_ERROR_UNSUPPORTED - Unsupported properties -*/ - -SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size); - - -/* ---------- LZMA Decoder state ---------- */ - -/* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case. - Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */ - -#define LZMA_REQUIRED_INPUT_MAX 20 - -typedef struct -{ - CLzmaProps prop; - CLzmaProb *probs; - Byte *dic; - const Byte *buf; - UInt32 range, code; - SizeT dicPos; - SizeT dicBufSize; - UInt32 processedPos; - UInt32 checkDicSize; - unsigned state; - UInt32 reps[4]; - unsigned remainLen; - int needFlush; - int needInitState; - UInt32 numProbs; - unsigned tempBufSize; - Byte tempBuf[LZMA_REQUIRED_INPUT_MAX]; -} CLzmaDec; - -#define LzmaDec_Construct(p) { (p)->dic = 0; (p)->probs = 0; } - -void LzmaDec_Init(CLzmaDec *p); - -/* There are two types of LZMA streams: - 0) Stream with end mark. That end mark adds about 6 bytes to compressed size. - 1) Stream without end mark. You must know exact uncompressed size to decompress such stream. */ - -typedef enum -{ - LZMA_FINISH_ANY, /* finish at any point */ - LZMA_FINISH_END /* block must be finished at the end */ -} ELzmaFinishMode; - -/* ELzmaFinishMode has meaning only if the decoding reaches output limit !!! - - You must use LZMA_FINISH_END, when you know that current output buffer - covers last bytes of block. In other cases you must use LZMA_FINISH_ANY. - - If LZMA decoder sees end marker before reaching output limit, it returns SZ_OK, - and output value of destLen will be less than output buffer size limit. - You can check status result also. - - You can use multiple checks to test data integrity after full decompression: - 1) Check Result and "status" variable. - 2) Check that output(destLen) = uncompressedSize, if you know real uncompressedSize. - 3) Check that output(srcLen) = compressedSize, if you know real compressedSize. - You must use correct finish mode in that case. */ - -typedef enum -{ - LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */ - LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */ - LZMA_STATUS_NOT_FINISHED, /* stream was not finished */ - LZMA_STATUS_NEEDS_MORE_INPUT, /* you must provide more input bytes */ - LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK /* there is probability that stream was finished without end mark */ -} ELzmaStatus; - -/* ELzmaStatus is used only as output value for function call */ - - -/* ---------- Interfaces ---------- */ - -/* There are 3 levels of interfaces: - 1) Dictionary Interface - 2) Buffer Interface - 3) One Call Interface - You can select any of these interfaces, but don't mix functions from different - groups for same object. */ - - -/* There are two variants to allocate state for Dictionary Interface: - 1) LzmaDec_Allocate / LzmaDec_Free - 2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs - You can use variant 2, if you set dictionary buffer manually. - For Buffer Interface you must always use variant 1. - -LzmaDec_Allocate* can return: - SZ_OK - SZ_ERROR_MEM - Memory allocation error - SZ_ERROR_UNSUPPORTED - Unsupported properties -*/ - -SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAlloc *alloc); -void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc); - -SRes LzmaDec_Allocate(CLzmaDec *state, const Byte *prop, unsigned propsSize, ISzAlloc *alloc); -void LzmaDec_Free(CLzmaDec *state, ISzAlloc *alloc); - -/* ---------- Dictionary Interface ---------- */ - -/* You can use it, if you want to eliminate the overhead for data copying from - dictionary to some other external buffer. - You must work with CLzmaDec variables directly in this interface. - - STEPS: - LzmaDec_Constr() - LzmaDec_Allocate() - for (each new stream) - { - LzmaDec_Init() - while (it needs more decompression) - { - LzmaDec_DecodeToDic() - use data from CLzmaDec::dic and update CLzmaDec::dicPos - } - } - LzmaDec_Free() -*/ - -/* LzmaDec_DecodeToDic - - The decoding to internal dictionary buffer (CLzmaDec::dic). - You must manually update CLzmaDec::dicPos, if it reaches CLzmaDec::dicBufSize !!! - -finishMode: - It has meaning only if the decoding reaches output limit (dicLimit). - LZMA_FINISH_ANY - Decode just dicLimit bytes. - LZMA_FINISH_END - Stream must be finished after dicLimit. - -Returns: - SZ_OK - status: - LZMA_STATUS_FINISHED_WITH_MARK - LZMA_STATUS_NOT_FINISHED - LZMA_STATUS_NEEDS_MORE_INPUT - LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK - SZ_ERROR_DATA - Data error -*/ - -SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, - const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status); - - -/* ---------- Buffer Interface ---------- */ - -/* It's zlib-like interface. - See LzmaDec_DecodeToDic description for information about STEPS and return results, - but you must use LzmaDec_DecodeToBuf instead of LzmaDec_DecodeToDic and you don't need - to work with CLzmaDec variables manually. - -finishMode: - It has meaning only if the decoding reaches output limit (*destLen). - LZMA_FINISH_ANY - Decode just destLen bytes. - LZMA_FINISH_END - Stream must be finished after (*destLen). -*/ - -SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, - const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status); - - -/* ---------- One Call Interface ---------- */ - -/* LzmaDecode - -finishMode: - It has meaning only if the decoding reaches output limit (*destLen). - LZMA_FINISH_ANY - Decode just destLen bytes. - LZMA_FINISH_END - Stream must be finished after (*destLen). - -Returns: - SZ_OK - status: - LZMA_STATUS_FINISHED_WITH_MARK - LZMA_STATUS_NOT_FINISHED - LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK - SZ_ERROR_DATA - Data error - SZ_ERROR_MEM - Memory allocation error - SZ_ERROR_UNSUPPORTED - Unsupported properties - SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src). -*/ - -SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, - const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode, - ELzmaStatus *status, ISzAlloc *alloc); - -#endif diff --git a/desmume/src/windows/7z/C/LzmaEnc.c b/desmume/src/windows/7z/C/LzmaEnc.c deleted file mode 100644 index a5a82da91..000000000 --- a/desmume/src/windows/7z/C/LzmaEnc.c +++ /dev/null @@ -1,2275 +0,0 @@ -/* LzmaEnc.c -- LZMA Encoder -2008-10-04 : Igor Pavlov : Public domain */ - -#include - -/* #define SHOW_STAT */ -/* #define SHOW_STAT2 */ - -#if defined(SHOW_STAT) || defined(SHOW_STAT2) -#include -#endif - -#include "LzmaEnc.h" - -#include "LzFind.h" -#ifdef COMPRESS_MF_MT -#include "LzFindMt.h" -#endif - -#ifdef SHOW_STAT -static int ttt = 0; -#endif - -#define kBlockSizeMax ((1 << LZMA_NUM_BLOCK_SIZE_BITS) - 1) - -#define kBlockSize (9 << 10) -#define kUnpackBlockSize (1 << 18) -#define kMatchArraySize (1 << 21) -#define kMatchRecordMaxSize ((LZMA_MATCH_LEN_MAX * 2 + 3) * LZMA_MATCH_LEN_MAX) - -#define kNumMaxDirectBits (31) - -#define kNumTopBits 24 -#define kTopValue ((UInt32)1 << kNumTopBits) - -#define kNumBitModelTotalBits 11 -#define kBitModelTotal (1 << kNumBitModelTotalBits) -#define kNumMoveBits 5 -#define kProbInitValue (kBitModelTotal >> 1) - -#define kNumMoveReducingBits 4 -#define kNumBitPriceShiftBits 4 -#define kBitPrice (1 << kNumBitPriceShiftBits) - -void LzmaEncProps_Init(CLzmaEncProps *p) -{ - p->level = 5; - p->dictSize = p->mc = 0; - p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1; - p->writeEndMark = 0; -} - -void LzmaEncProps_Normalize(CLzmaEncProps *p) -{ - int level = p->level; - if (level < 0) level = 5; - p->level = level; - if (p->dictSize == 0) p->dictSize = (level <= 5 ? (1 << (level * 2 + 14)) : (level == 6 ? (1 << 25) : (1 << 26))); - if (p->lc < 0) p->lc = 3; - if (p->lp < 0) p->lp = 0; - if (p->pb < 0) p->pb = 2; - if (p->algo < 0) p->algo = (level < 5 ? 0 : 1); - if (p->fb < 0) p->fb = (level < 7 ? 32 : 64); - if (p->btMode < 0) p->btMode = (p->algo == 0 ? 0 : 1); - if (p->numHashBytes < 0) p->numHashBytes = 4; - if (p->mc == 0) p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1); - if (p->numThreads < 0) p->numThreads = ((p->btMode && p->algo) ? 2 : 1); -} - -UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2) -{ - CLzmaEncProps props = *props2; - LzmaEncProps_Normalize(&props); - return props.dictSize; -} - -/* #define LZMA_LOG_BSR */ -/* Define it for Intel's CPU */ - - -#ifdef LZMA_LOG_BSR - -#define kDicLogSizeMaxCompress 30 - -#define BSR2_RET(pos, res) { unsigned long i; _BitScanReverse(&i, (pos)); res = (i + i) + ((pos >> (i - 1)) & 1); } - -UInt32 GetPosSlot1(UInt32 pos) -{ - UInt32 res; - BSR2_RET(pos, res); - return res; -} -#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); } -#define GetPosSlot(pos, res) { if (pos < 2) res = pos; else BSR2_RET(pos, res); } - -#else - -#define kNumLogBits (9 + (int)sizeof(size_t) / 2) -#define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7) - -void LzmaEnc_FastPosInit(Byte *g_FastPos) -{ - int c = 2, slotFast; - g_FastPos[0] = 0; - g_FastPos[1] = 1; - - for (slotFast = 2; slotFast < kNumLogBits * 2; slotFast++) - { - UInt32 k = (1 << ((slotFast >> 1) - 1)); - UInt32 j; - for (j = 0; j < k; j++, c++) - g_FastPos[c] = (Byte)slotFast; - } -} - -#define BSR2_RET(pos, res) { UInt32 i = 6 + ((kNumLogBits - 1) & \ - (0 - (((((UInt32)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \ - res = p->g_FastPos[pos >> i] + (i * 2); } -/* -#define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \ - p->g_FastPos[pos >> 6] + 12 : \ - p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; } -*/ - -#define GetPosSlot1(pos) p->g_FastPos[pos] -#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); } -#define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos]; else BSR2_RET(pos, res); } - -#endif - - -#define LZMA_NUM_REPS 4 - -typedef unsigned CState; - -typedef struct _COptimal -{ - UInt32 price; - - CState state; - int prev1IsChar; - int prev2; - - UInt32 posPrev2; - UInt32 backPrev2; - - UInt32 posPrev; - UInt32 backPrev; - UInt32 backs[LZMA_NUM_REPS]; -} COptimal; - -#define kNumOpts (1 << 12) - -#define kNumLenToPosStates 4 -#define kNumPosSlotBits 6 -#define kDicLogSizeMin 0 -#define kDicLogSizeMax 32 -#define kDistTableSizeMax (kDicLogSizeMax * 2) - - -#define kNumAlignBits 4 -#define kAlignTableSize (1 << kNumAlignBits) -#define kAlignMask (kAlignTableSize - 1) - -#define kStartPosModelIndex 4 -#define kEndPosModelIndex 14 -#define kNumPosModels (kEndPosModelIndex - kStartPosModelIndex) - -#define kNumFullDistances (1 << (kEndPosModelIndex / 2)) - -#ifdef _LZMA_PROB32 -#define CLzmaProb UInt32 -#else -#define CLzmaProb UInt16 -#endif - -#define LZMA_PB_MAX 4 -#define LZMA_LC_MAX 8 -#define LZMA_LP_MAX 4 - -#define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX) - - -#define kLenNumLowBits 3 -#define kLenNumLowSymbols (1 << kLenNumLowBits) -#define kLenNumMidBits 3 -#define kLenNumMidSymbols (1 << kLenNumMidBits) -#define kLenNumHighBits 8 -#define kLenNumHighSymbols (1 << kLenNumHighBits) - -#define kLenNumSymbolsTotal (kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols) - -#define LZMA_MATCH_LEN_MIN 2 -#define LZMA_MATCH_LEN_MAX (LZMA_MATCH_LEN_MIN + kLenNumSymbolsTotal - 1) - -#define kNumStates 12 - -typedef struct -{ - CLzmaProb choice; - CLzmaProb choice2; - CLzmaProb low[LZMA_NUM_PB_STATES_MAX << kLenNumLowBits]; - CLzmaProb mid[LZMA_NUM_PB_STATES_MAX << kLenNumMidBits]; - CLzmaProb high[kLenNumHighSymbols]; -} CLenEnc; - -typedef struct -{ - CLenEnc p; - UInt32 prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal]; - UInt32 tableSize; - UInt32 counters[LZMA_NUM_PB_STATES_MAX]; -} CLenPriceEnc; - -typedef struct _CRangeEnc -{ - UInt32 range; - Byte cache; - UInt64 low; - UInt64 cacheSize; - Byte *buf; - Byte *bufLim; - Byte *bufBase; - ISeqOutStream *outStream; - UInt64 processed; - SRes res; -} CRangeEnc; - -typedef struct _CSeqInStreamBuf -{ - ISeqInStream funcTable; - const Byte *data; - SizeT rem; -} CSeqInStreamBuf; - -static SRes MyRead(void *pp, void *data, size_t *size) -{ - size_t curSize = *size; - CSeqInStreamBuf *p = (CSeqInStreamBuf *)pp; - if (p->rem < curSize) - curSize = p->rem; - memcpy(data, p->data, curSize); - p->rem -= curSize; - p->data += curSize; - *size = curSize; - return SZ_OK; -} - -typedef struct -{ - CLzmaProb *litProbs; - - CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX]; - CLzmaProb isRep[kNumStates]; - CLzmaProb isRepG0[kNumStates]; - CLzmaProb isRepG1[kNumStates]; - CLzmaProb isRepG2[kNumStates]; - CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX]; - - CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits]; - CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex]; - CLzmaProb posAlignEncoder[1 << kNumAlignBits]; - - CLenPriceEnc lenEnc; - CLenPriceEnc repLenEnc; - - UInt32 reps[LZMA_NUM_REPS]; - UInt32 state; -} CSaveState; - -typedef struct _CLzmaEnc -{ - IMatchFinder matchFinder; - void *matchFinderObj; - - #ifdef COMPRESS_MF_MT - Bool mtMode; - CMatchFinderMt matchFinderMt; - #endif - - CMatchFinder matchFinderBase; - - #ifdef COMPRESS_MF_MT - Byte pad[128]; - #endif - - UInt32 optimumEndIndex; - UInt32 optimumCurrentIndex; - - UInt32 longestMatchLength; - UInt32 numPairs; - UInt32 numAvail; - COptimal opt[kNumOpts]; - - #ifndef LZMA_LOG_BSR - Byte g_FastPos[1 << kNumLogBits]; - #endif - - UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits]; - UInt32 matches[LZMA_MATCH_LEN_MAX * 2 + 2 + 1]; - UInt32 numFastBytes; - UInt32 additionalOffset; - UInt32 reps[LZMA_NUM_REPS]; - UInt32 state; - - UInt32 posSlotPrices[kNumLenToPosStates][kDistTableSizeMax]; - UInt32 distancesPrices[kNumLenToPosStates][kNumFullDistances]; - UInt32 alignPrices[kAlignTableSize]; - UInt32 alignPriceCount; - - UInt32 distTableSize; - - unsigned lc, lp, pb; - unsigned lpMask, pbMask; - - CLzmaProb *litProbs; - - CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX]; - CLzmaProb isRep[kNumStates]; - CLzmaProb isRepG0[kNumStates]; - CLzmaProb isRepG1[kNumStates]; - CLzmaProb isRepG2[kNumStates]; - CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX]; - - CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits]; - CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex]; - CLzmaProb posAlignEncoder[1 << kNumAlignBits]; - - CLenPriceEnc lenEnc; - CLenPriceEnc repLenEnc; - - unsigned lclp; - - Bool fastMode; - - CRangeEnc rc; - - Bool writeEndMark; - UInt64 nowPos64; - UInt32 matchPriceCount; - Bool finished; - Bool multiThread; - - SRes result; - UInt32 dictSize; - UInt32 matchFinderCycles; - - ISeqInStream *inStream; - CSeqInStreamBuf seqBufInStream; - - CSaveState saveState; -} CLzmaEnc; - -void LzmaEnc_SaveState(CLzmaEncHandle pp) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - CSaveState *dest = &p->saveState; - int i; - dest->lenEnc = p->lenEnc; - dest->repLenEnc = p->repLenEnc; - dest->state = p->state; - - for (i = 0; i < kNumStates; i++) - { - memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i])); - memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i])); - } - for (i = 0; i < kNumLenToPosStates; i++) - memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i])); - memcpy(dest->isRep, p->isRep, sizeof(p->isRep)); - memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0)); - memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1)); - memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2)); - memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders)); - memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder)); - memcpy(dest->reps, p->reps, sizeof(p->reps)); - memcpy(dest->litProbs, p->litProbs, (0x300 << p->lclp) * sizeof(CLzmaProb)); -} - -void LzmaEnc_RestoreState(CLzmaEncHandle pp) -{ - CLzmaEnc *dest = (CLzmaEnc *)pp; - const CSaveState *p = &dest->saveState; - int i; - dest->lenEnc = p->lenEnc; - dest->repLenEnc = p->repLenEnc; - dest->state = p->state; - - for (i = 0; i < kNumStates; i++) - { - memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i])); - memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i])); - } - for (i = 0; i < kNumLenToPosStates; i++) - memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i])); - memcpy(dest->isRep, p->isRep, sizeof(p->isRep)); - memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0)); - memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1)); - memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2)); - memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders)); - memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder)); - memcpy(dest->reps, p->reps, sizeof(p->reps)); - memcpy(dest->litProbs, p->litProbs, (0x300 << dest->lclp) * sizeof(CLzmaProb)); -} - -SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - CLzmaEncProps props = *props2; - LzmaEncProps_Normalize(&props); - - if (props.lc > LZMA_LC_MAX || props.lp > LZMA_LP_MAX || props.pb > LZMA_PB_MAX || - props.dictSize > (1 << kDicLogSizeMaxCompress) || props.dictSize > (1 << 30)) - return SZ_ERROR_PARAM; - p->dictSize = props.dictSize; - p->matchFinderCycles = props.mc; - { - unsigned fb = props.fb; - if (fb < 5) - fb = 5; - if (fb > LZMA_MATCH_LEN_MAX) - fb = LZMA_MATCH_LEN_MAX; - p->numFastBytes = fb; - } - p->lc = props.lc; - p->lp = props.lp; - p->pb = props.pb; - p->fastMode = (props.algo == 0); - p->matchFinderBase.btMode = props.btMode; - { - UInt32 numHashBytes = 4; - if (props.btMode) - { - if (props.numHashBytes < 2) - numHashBytes = 2; - else if (props.numHashBytes < 4) - numHashBytes = props.numHashBytes; - } - p->matchFinderBase.numHashBytes = numHashBytes; - } - - p->matchFinderBase.cutValue = props.mc; - - p->writeEndMark = props.writeEndMark; - - #ifdef COMPRESS_MF_MT - /* - if (newMultiThread != _multiThread) - { - ReleaseMatchFinder(); - _multiThread = newMultiThread; - } - */ - p->multiThread = (props.numThreads > 1); - #endif - - return SZ_OK; -} - -static const int kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5}; -static const int kMatchNextStates[kNumStates] = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10}; -static const int kRepNextStates[kNumStates] = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11}; -static const int kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11}; - -#define IsCharState(s) ((s) < 7) - -#define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1) - -#define kInfinityPrice (1 << 30) - -static void RangeEnc_Construct(CRangeEnc *p) -{ - p->outStream = 0; - p->bufBase = 0; -} - -#define RangeEnc_GetProcessed(p) ((p)->processed + ((p)->buf - (p)->bufBase) + (p)->cacheSize) - -#define RC_BUF_SIZE (1 << 16) -static int RangeEnc_Alloc(CRangeEnc *p, ISzAlloc *alloc) -{ - if (p->bufBase == 0) - { - p->bufBase = (Byte *)alloc->Alloc(alloc, RC_BUF_SIZE); - if (p->bufBase == 0) - return 0; - p->bufLim = p->bufBase + RC_BUF_SIZE; - } - return 1; -} - -static void RangeEnc_Free(CRangeEnc *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->bufBase); - p->bufBase = 0; -} - -static void RangeEnc_Init(CRangeEnc *p) -{ - /* Stream.Init(); */ - p->low = 0; - p->range = 0xFFFFFFFF; - p->cacheSize = 1; - p->cache = 0; - - p->buf = p->bufBase; - - p->processed = 0; - p->res = SZ_OK; -} - -static void RangeEnc_FlushStream(CRangeEnc *p) -{ - size_t num; - if (p->res != SZ_OK) - return; - num = p->buf - p->bufBase; - if (num != p->outStream->Write(p->outStream, p->bufBase, num)) - p->res = SZ_ERROR_WRITE; - p->processed += num; - p->buf = p->bufBase; -} - -static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p) -{ - if ((UInt32)p->low < (UInt32)0xFF000000 || (int)(p->low >> 32) != 0) - { - Byte temp = p->cache; - do - { - Byte *buf = p->buf; - *buf++ = (Byte)(temp + (Byte)(p->low >> 32)); - p->buf = buf; - if (buf == p->bufLim) - RangeEnc_FlushStream(p); - temp = 0xFF; - } - while (--p->cacheSize != 0); - p->cache = (Byte)((UInt32)p->low >> 24); - } - p->cacheSize++; - p->low = (UInt32)p->low << 8; -} - -static void RangeEnc_FlushData(CRangeEnc *p) -{ - int i; - for (i = 0; i < 5; i++) - RangeEnc_ShiftLow(p); -} - -static void RangeEnc_EncodeDirectBits(CRangeEnc *p, UInt32 value, int numBits) -{ - do - { - p->range >>= 1; - p->low += p->range & (0 - ((value >> --numBits) & 1)); - if (p->range < kTopValue) - { - p->range <<= 8; - RangeEnc_ShiftLow(p); - } - } - while (numBits != 0); -} - -static void RangeEnc_EncodeBit(CRangeEnc *p, CLzmaProb *prob, UInt32 symbol) -{ - UInt32 ttt = *prob; - UInt32 newBound = (p->range >> kNumBitModelTotalBits) * ttt; - if (symbol == 0) - { - p->range = newBound; - ttt += (kBitModelTotal - ttt) >> kNumMoveBits; - } - else - { - p->low += newBound; - p->range -= newBound; - ttt -= ttt >> kNumMoveBits; - } - *prob = (CLzmaProb)ttt; - if (p->range < kTopValue) - { - p->range <<= 8; - RangeEnc_ShiftLow(p); - } -} - -static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol) -{ - symbol |= 0x100; - do - { - RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1); - symbol <<= 1; - } - while (symbol < 0x10000); -} - -static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol, UInt32 matchByte) -{ - UInt32 offs = 0x100; - symbol |= 0x100; - do - { - matchByte <<= 1; - RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1); - symbol <<= 1; - offs &= ~(matchByte ^ symbol); - } - while (symbol < 0x10000); -} - -void LzmaEnc_InitPriceTables(UInt32 *ProbPrices) -{ - UInt32 i; - for (i = (1 << kNumMoveReducingBits) / 2; i < kBitModelTotal; i += (1 << kNumMoveReducingBits)) - { - const int kCyclesBits = kNumBitPriceShiftBits; - UInt32 w = i; - UInt32 bitCount = 0; - int j; - for (j = 0; j < kCyclesBits; j++) - { - w = w * w; - bitCount <<= 1; - while (w >= ((UInt32)1 << 16)) - { - w >>= 1; - bitCount++; - } - } - ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount); - } -} - - -#define GET_PRICE(prob, symbol) \ - p->ProbPrices[((prob) ^ (((-(int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; - -#define GET_PRICEa(prob, symbol) \ - ProbPrices[((prob) ^ ((-((int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits]; - -#define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits] -#define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits] - -#define GET_PRICE_0a(prob) ProbPrices[(prob) >> kNumMoveReducingBits] -#define GET_PRICE_1a(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits] - -static UInt32 LitEnc_GetPrice(const CLzmaProb *probs, UInt32 symbol, UInt32 *ProbPrices) -{ - UInt32 price = 0; - symbol |= 0x100; - do - { - price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1); - symbol <<= 1; - } - while (symbol < 0x10000); - return price; -} - -static UInt32 LitEnc_GetPriceMatched(const CLzmaProb *probs, UInt32 symbol, UInt32 matchByte, UInt32 *ProbPrices) -{ - UInt32 price = 0; - UInt32 offs = 0x100; - symbol |= 0x100; - do - { - matchByte <<= 1; - price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1); - symbol <<= 1; - offs &= ~(matchByte ^ symbol); - } - while (symbol < 0x10000); - return price; -} - - -static void RcTree_Encode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol) -{ - UInt32 m = 1; - int i; - for (i = numBitLevels; i != 0;) - { - UInt32 bit; - i--; - bit = (symbol >> i) & 1; - RangeEnc_EncodeBit(rc, probs + m, bit); - m = (m << 1) | bit; - } -} - -static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UInt32 symbol) -{ - UInt32 m = 1; - int i; - for (i = 0; i < numBitLevels; i++) - { - UInt32 bit = symbol & 1; - RangeEnc_EncodeBit(rc, probs + m, bit); - m = (m << 1) | bit; - symbol >>= 1; - } -} - -static UInt32 RcTree_GetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices) -{ - UInt32 price = 0; - symbol |= (1 << numBitLevels); - while (symbol != 1) - { - price += GET_PRICEa(probs[symbol >> 1], symbol & 1); - symbol >>= 1; - } - return price; -} - -static UInt32 RcTree_ReverseGetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 symbol, UInt32 *ProbPrices) -{ - UInt32 price = 0; - UInt32 m = 1; - int i; - for (i = numBitLevels; i != 0; i--) - { - UInt32 bit = symbol & 1; - symbol >>= 1; - price += GET_PRICEa(probs[m], bit); - m = (m << 1) | bit; - } - return price; -} - - -static void LenEnc_Init(CLenEnc *p) -{ - unsigned i; - p->choice = p->choice2 = kProbInitValue; - for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumLowBits); i++) - p->low[i] = kProbInitValue; - for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumMidBits); i++) - p->mid[i] = kProbInitValue; - for (i = 0; i < kLenNumHighSymbols; i++) - p->high[i] = kProbInitValue; -} - -static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState) -{ - if (symbol < kLenNumLowSymbols) - { - RangeEnc_EncodeBit(rc, &p->choice, 0); - RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol); - } - else - { - RangeEnc_EncodeBit(rc, &p->choice, 1); - if (symbol < kLenNumLowSymbols + kLenNumMidSymbols) - { - RangeEnc_EncodeBit(rc, &p->choice2, 0); - RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols); - } - else - { - RangeEnc_EncodeBit(rc, &p->choice2, 1); - RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols); - } - } -} - -static void LenEnc_SetPrices(CLenEnc *p, UInt32 posState, UInt32 numSymbols, UInt32 *prices, UInt32 *ProbPrices) -{ - UInt32 a0 = GET_PRICE_0a(p->choice); - UInt32 a1 = GET_PRICE_1a(p->choice); - UInt32 b0 = a1 + GET_PRICE_0a(p->choice2); - UInt32 b1 = a1 + GET_PRICE_1a(p->choice2); - UInt32 i = 0; - for (i = 0; i < kLenNumLowSymbols; i++) - { - if (i >= numSymbols) - return; - prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices); - } - for (; i < kLenNumLowSymbols + kLenNumMidSymbols; i++) - { - if (i >= numSymbols) - return; - prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices); - } - for (; i < numSymbols; i++) - prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices); -} - -static void MY_FAST_CALL LenPriceEnc_UpdateTable(CLenPriceEnc *p, UInt32 posState, UInt32 *ProbPrices) -{ - LenEnc_SetPrices(&p->p, posState, p->tableSize, p->prices[posState], ProbPrices); - p->counters[posState] = p->tableSize; -} - -static void LenPriceEnc_UpdateTables(CLenPriceEnc *p, UInt32 numPosStates, UInt32 *ProbPrices) -{ - UInt32 posState; - for (posState = 0; posState < numPosStates; posState++) - LenPriceEnc_UpdateTable(p, posState, ProbPrices); -} - -static void LenEnc_Encode2(CLenPriceEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState, Bool updatePrice, UInt32 *ProbPrices) -{ - LenEnc_Encode(&p->p, rc, symbol, posState); - if (updatePrice) - if (--p->counters[posState] == 0) - LenPriceEnc_UpdateTable(p, posState, ProbPrices); -} - - - - -static void MovePos(CLzmaEnc *p, UInt32 num) -{ - #ifdef SHOW_STAT - ttt += num; - printf("\n MovePos %d", num); - #endif - if (num != 0) - { - p->additionalOffset += num; - p->matchFinder.Skip(p->matchFinderObj, num); - } -} - -static UInt32 ReadMatchDistances(CLzmaEnc *p, UInt32 *numDistancePairsRes) -{ - UInt32 lenRes = 0, numPairs; - p->numAvail = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj); - numPairs = p->matchFinder.GetMatches(p->matchFinderObj, p->matches); - #ifdef SHOW_STAT - printf("\n i = %d numPairs = %d ", ttt, numPairs / 2); - ttt++; - { - UInt32 i; - for (i = 0; i < numPairs; i += 2) - printf("%2d %6d | ", p->matches[i], p->matches[i + 1]); - } - #endif - if (numPairs > 0) - { - lenRes = p->matches[numPairs - 2]; - if (lenRes == p->numFastBytes) - { - const Byte *pby = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - UInt32 distance = p->matches[numPairs - 1] + 1; - UInt32 numAvail = p->numAvail; - if (numAvail > LZMA_MATCH_LEN_MAX) - numAvail = LZMA_MATCH_LEN_MAX; - { - const Byte *pby2 = pby - distance; - for (; lenRes < numAvail && pby[lenRes] == pby2[lenRes]; lenRes++); - } - } - } - p->additionalOffset++; - *numDistancePairsRes = numPairs; - return lenRes; -} - - -#define MakeAsChar(p) (p)->backPrev = (UInt32)(-1); (p)->prev1IsChar = False; -#define MakeAsShortRep(p) (p)->backPrev = 0; (p)->prev1IsChar = False; -#define IsShortRep(p) ((p)->backPrev == 0) - -static UInt32 GetRepLen1Price(CLzmaEnc *p, UInt32 state, UInt32 posState) -{ - return - GET_PRICE_0(p->isRepG0[state]) + - GET_PRICE_0(p->isRep0Long[state][posState]); -} - -static UInt32 GetPureRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 state, UInt32 posState) -{ - UInt32 price; - if (repIndex == 0) - { - price = GET_PRICE_0(p->isRepG0[state]); - price += GET_PRICE_1(p->isRep0Long[state][posState]); - } - else - { - price = GET_PRICE_1(p->isRepG0[state]); - if (repIndex == 1) - price += GET_PRICE_0(p->isRepG1[state]); - else - { - price += GET_PRICE_1(p->isRepG1[state]); - price += GET_PRICE(p->isRepG2[state], repIndex - 2); - } - } - return price; -} - -static UInt32 GetRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 len, UInt32 state, UInt32 posState) -{ - return p->repLenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN] + - GetPureRepPrice(p, repIndex, state, posState); -} - -static UInt32 Backward(CLzmaEnc *p, UInt32 *backRes, UInt32 cur) -{ - UInt32 posMem = p->opt[cur].posPrev; - UInt32 backMem = p->opt[cur].backPrev; - p->optimumEndIndex = cur; - do - { - if (p->opt[cur].prev1IsChar) - { - MakeAsChar(&p->opt[posMem]) - p->opt[posMem].posPrev = posMem - 1; - if (p->opt[cur].prev2) - { - p->opt[posMem - 1].prev1IsChar = False; - p->opt[posMem - 1].posPrev = p->opt[cur].posPrev2; - p->opt[posMem - 1].backPrev = p->opt[cur].backPrev2; - } - } - { - UInt32 posPrev = posMem; - UInt32 backCur = backMem; - - backMem = p->opt[posPrev].backPrev; - posMem = p->opt[posPrev].posPrev; - - p->opt[posPrev].backPrev = backCur; - p->opt[posPrev].posPrev = cur; - cur = posPrev; - } - } - while (cur != 0); - *backRes = p->opt[0].backPrev; - p->optimumCurrentIndex = p->opt[0].posPrev; - return p->optimumCurrentIndex; -} - -#define LIT_PROBS(pos, prevByte) (p->litProbs + ((((pos) & p->lpMask) << p->lc) + ((prevByte) >> (8 - p->lc))) * 0x300) - -static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes) -{ - UInt32 numAvail, mainLen, numPairs, repMaxIndex, i, posState, lenEnd, len, cur; - UInt32 matchPrice, repMatchPrice, normalMatchPrice; - UInt32 reps[LZMA_NUM_REPS], repLens[LZMA_NUM_REPS]; - UInt32 *matches; - const Byte *data; - Byte curByte, matchByte; - if (p->optimumEndIndex != p->optimumCurrentIndex) - { - const COptimal *opt = &p->opt[p->optimumCurrentIndex]; - UInt32 lenRes = opt->posPrev - p->optimumCurrentIndex; - *backRes = opt->backPrev; - p->optimumCurrentIndex = opt->posPrev; - return lenRes; - } - p->optimumCurrentIndex = p->optimumEndIndex = 0; - - if (p->additionalOffset == 0) - mainLen = ReadMatchDistances(p, &numPairs); - else - { - mainLen = p->longestMatchLength; - numPairs = p->numPairs; - } - - numAvail = p->numAvail; - if (numAvail < 2) - { - *backRes = (UInt32)(-1); - return 1; - } - if (numAvail > LZMA_MATCH_LEN_MAX) - numAvail = LZMA_MATCH_LEN_MAX; - - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - repMaxIndex = 0; - for (i = 0; i < LZMA_NUM_REPS; i++) - { - UInt32 lenTest; - const Byte *data2; - reps[i] = p->reps[i]; - data2 = data - (reps[i] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - { - repLens[i] = 0; - continue; - } - for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++); - repLens[i] = lenTest; - if (lenTest > repLens[repMaxIndex]) - repMaxIndex = i; - } - if (repLens[repMaxIndex] >= p->numFastBytes) - { - UInt32 lenRes; - *backRes = repMaxIndex; - lenRes = repLens[repMaxIndex]; - MovePos(p, lenRes - 1); - return lenRes; - } - - matches = p->matches; - if (mainLen >= p->numFastBytes) - { - *backRes = matches[numPairs - 1] + LZMA_NUM_REPS; - MovePos(p, mainLen - 1); - return mainLen; - } - curByte = *data; - matchByte = *(data - (reps[0] + 1)); - - if (mainLen < 2 && curByte != matchByte && repLens[repMaxIndex] < 2) - { - *backRes = (UInt32)-1; - return 1; - } - - p->opt[0].state = (CState)p->state; - - posState = (position & p->pbMask); - - { - const CLzmaProb *probs = LIT_PROBS(position, *(data - 1)); - p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) + - (!IsCharState(p->state) ? - LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) : - LitEnc_GetPrice(probs, curByte, p->ProbPrices)); - } - - MakeAsChar(&p->opt[1]); - - matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]); - repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]); - - if (matchByte == curByte) - { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState); - if (shortRepPrice < p->opt[1].price) - { - p->opt[1].price = shortRepPrice; - MakeAsShortRep(&p->opt[1]); - } - } - lenEnd = ((mainLen >= repLens[repMaxIndex]) ? mainLen : repLens[repMaxIndex]); - - if (lenEnd < 2) - { - *backRes = p->opt[1].backPrev; - return 1; - } - - p->opt[1].posPrev = 0; - for (i = 0; i < LZMA_NUM_REPS; i++) - p->opt[0].backs[i] = reps[i]; - - len = lenEnd; - do - p->opt[len--].price = kInfinityPrice; - while (len >= 2); - - for (i = 0; i < LZMA_NUM_REPS; i++) - { - UInt32 repLen = repLens[i]; - UInt32 price; - if (repLen < 2) - continue; - price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState); - do - { - UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][repLen - 2]; - COptimal *opt = &p->opt[repLen]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = 0; - opt->backPrev = i; - opt->prev1IsChar = False; - } - } - while (--repLen >= 2); - } - - normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]); - - len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); - if (len <= mainLen) - { - UInt32 offs = 0; - while (len > matches[offs]) - offs += 2; - for (; ; len++) - { - COptimal *opt; - UInt32 distance = matches[offs + 1]; - - UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN]; - UInt32 lenToPosState = GetLenToPosState(len); - if (distance < kNumFullDistances) - curAndLenPrice += p->distancesPrices[lenToPosState][distance]; - else - { - UInt32 slot; - GetPosSlot2(distance, slot); - curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot]; - } - opt = &p->opt[len]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = 0; - opt->backPrev = distance + LZMA_NUM_REPS; - opt->prev1IsChar = False; - } - if (len == matches[offs]) - { - offs += 2; - if (offs == numPairs) - break; - } - } - } - - cur = 0; - - #ifdef SHOW_STAT2 - if (position >= 0) - { - unsigned i; - printf("\n pos = %4X", position); - for (i = cur; i <= lenEnd; i++) - printf("\nprice[%4X] = %d", position - cur + i, p->opt[i].price); - } - #endif - - for (;;) - { - UInt32 numAvailFull, newLen, numPairs, posPrev, state, posState, startLen; - UInt32 curPrice, curAnd1Price, matchPrice, repMatchPrice; - Bool nextIsChar; - Byte curByte, matchByte; - const Byte *data; - COptimal *curOpt; - COptimal *nextOpt; - - cur++; - if (cur == lenEnd) - return Backward(p, backRes, cur); - - newLen = ReadMatchDistances(p, &numPairs); - if (newLen >= p->numFastBytes) - { - p->numPairs = numPairs; - p->longestMatchLength = newLen; - return Backward(p, backRes, cur); - } - position++; - curOpt = &p->opt[cur]; - posPrev = curOpt->posPrev; - if (curOpt->prev1IsChar) - { - posPrev--; - if (curOpt->prev2) - { - state = p->opt[curOpt->posPrev2].state; - if (curOpt->backPrev2 < LZMA_NUM_REPS) - state = kRepNextStates[state]; - else - state = kMatchNextStates[state]; - } - else - state = p->opt[posPrev].state; - state = kLiteralNextStates[state]; - } - else - state = p->opt[posPrev].state; - if (posPrev == cur - 1) - { - if (IsShortRep(curOpt)) - state = kShortRepNextStates[state]; - else - state = kLiteralNextStates[state]; - } - else - { - UInt32 pos; - const COptimal *prevOpt; - if (curOpt->prev1IsChar && curOpt->prev2) - { - posPrev = curOpt->posPrev2; - pos = curOpt->backPrev2; - state = kRepNextStates[state]; - } - else - { - pos = curOpt->backPrev; - if (pos < LZMA_NUM_REPS) - state = kRepNextStates[state]; - else - state = kMatchNextStates[state]; - } - prevOpt = &p->opt[posPrev]; - if (pos < LZMA_NUM_REPS) - { - UInt32 i; - reps[0] = prevOpt->backs[pos]; - for (i = 1; i <= pos; i++) - reps[i] = prevOpt->backs[i - 1]; - for (; i < LZMA_NUM_REPS; i++) - reps[i] = prevOpt->backs[i]; - } - else - { - UInt32 i; - reps[0] = (pos - LZMA_NUM_REPS); - for (i = 1; i < LZMA_NUM_REPS; i++) - reps[i] = prevOpt->backs[i - 1]; - } - } - curOpt->state = (CState)state; - - curOpt->backs[0] = reps[0]; - curOpt->backs[1] = reps[1]; - curOpt->backs[2] = reps[2]; - curOpt->backs[3] = reps[3]; - - curPrice = curOpt->price; - nextIsChar = False; - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - curByte = *data; - matchByte = *(data - (reps[0] + 1)); - - posState = (position & p->pbMask); - - curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]); - { - const CLzmaProb *probs = LIT_PROBS(position, *(data - 1)); - curAnd1Price += - (!IsCharState(state) ? - LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) : - LitEnc_GetPrice(probs, curByte, p->ProbPrices)); - } - - nextOpt = &p->opt[cur + 1]; - - if (curAnd1Price < nextOpt->price) - { - nextOpt->price = curAnd1Price; - nextOpt->posPrev = cur; - MakeAsChar(nextOpt); - nextIsChar = True; - } - - matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]); - repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]); - - if (matchByte == curByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0)) - { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState); - if (shortRepPrice <= nextOpt->price) - { - nextOpt->price = shortRepPrice; - nextOpt->posPrev = cur; - MakeAsShortRep(nextOpt); - nextIsChar = True; - } - } - numAvailFull = p->numAvail; - { - UInt32 temp = kNumOpts - 1 - cur; - if (temp < numAvailFull) - numAvailFull = temp; - } - - if (numAvailFull < 2) - continue; - numAvail = (numAvailFull <= p->numFastBytes ? numAvailFull : p->numFastBytes); - - if (!nextIsChar && matchByte != curByte) /* speed optimization */ - { - /* try Literal + rep0 */ - UInt32 temp; - UInt32 lenTest2; - const Byte *data2 = data - (reps[0] + 1); - UInt32 limit = p->numFastBytes + 1; - if (limit > numAvailFull) - limit = numAvailFull; - - for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++); - lenTest2 = temp - 1; - if (lenTest2 >= 2) - { - UInt32 state2 = kLiteralNextStates[state]; - UInt32 posStateNext = (position + 1) & p->pbMask; - UInt32 nextRepMatchPrice = curAnd1Price + - GET_PRICE_1(p->isMatch[state2][posStateNext]) + - GET_PRICE_1(p->isRep[state2]); - /* for (; lenTest2 >= 2; lenTest2--) */ - { - UInt32 curAndLenPrice; - COptimal *opt; - UInt32 offset = cur + 1 + lenTest2; - while (lenEnd < offset) - p->opt[++lenEnd].price = kInfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); - opt = &p->opt[offset]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur + 1; - opt->backPrev = 0; - opt->prev1IsChar = True; - opt->prev2 = False; - } - } - } - } - - startLen = 2; /* speed optimization */ - { - UInt32 repIndex; - for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++) - { - UInt32 lenTest; - UInt32 lenTestTemp; - UInt32 price; - const Byte *data2 = data - (reps[repIndex] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - continue; - for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++); - while (lenEnd < cur + lenTest) - p->opt[++lenEnd].price = kInfinityPrice; - lenTestTemp = lenTest; - price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState); - do - { - UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][lenTest - 2]; - COptimal *opt = &p->opt[cur + lenTest]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur; - opt->backPrev = repIndex; - opt->prev1IsChar = False; - } - } - while (--lenTest >= 2); - lenTest = lenTestTemp; - - if (repIndex == 0) - startLen = lenTest + 1; - - /* if (_maxMode) */ - { - UInt32 lenTest2 = lenTest + 1; - UInt32 limit = lenTest2 + p->numFastBytes; - UInt32 nextRepMatchPrice; - if (limit > numAvailFull) - limit = numAvailFull; - for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++); - lenTest2 -= lenTest + 1; - if (lenTest2 >= 2) - { - UInt32 state2 = kRepNextStates[state]; - UInt32 posStateNext = (position + lenTest) & p->pbMask; - UInt32 curAndLenCharPrice = - price + p->repLenEnc.prices[posState][lenTest - 2] + - GET_PRICE_0(p->isMatch[state2][posStateNext]) + - LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]), - data[lenTest], data2[lenTest], p->ProbPrices); - state2 = kLiteralNextStates[state2]; - posStateNext = (position + lenTest + 1) & p->pbMask; - nextRepMatchPrice = curAndLenCharPrice + - GET_PRICE_1(p->isMatch[state2][posStateNext]) + - GET_PRICE_1(p->isRep[state2]); - - /* for (; lenTest2 >= 2; lenTest2--) */ - { - UInt32 curAndLenPrice; - COptimal *opt; - UInt32 offset = cur + lenTest + 1 + lenTest2; - while (lenEnd < offset) - p->opt[++lenEnd].price = kInfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); - opt = &p->opt[offset]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur + lenTest + 1; - opt->backPrev = 0; - opt->prev1IsChar = True; - opt->prev2 = True; - opt->posPrev2 = cur; - opt->backPrev2 = repIndex; - } - } - } - } - } - } - /* for (UInt32 lenTest = 2; lenTest <= newLen; lenTest++) */ - if (newLen > numAvail) - { - newLen = numAvail; - for (numPairs = 0; newLen > matches[numPairs]; numPairs += 2); - matches[numPairs] = newLen; - numPairs += 2; - } - if (newLen >= startLen) - { - UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]); - UInt32 offs, curBack, posSlot; - UInt32 lenTest; - while (lenEnd < cur + newLen) - p->opt[++lenEnd].price = kInfinityPrice; - - offs = 0; - while (startLen > matches[offs]) - offs += 2; - curBack = matches[offs + 1]; - GetPosSlot2(curBack, posSlot); - for (lenTest = /*2*/ startLen; ; lenTest++) - { - UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][lenTest - LZMA_MATCH_LEN_MIN]; - UInt32 lenToPosState = GetLenToPosState(lenTest); - COptimal *opt; - if (curBack < kNumFullDistances) - curAndLenPrice += p->distancesPrices[lenToPosState][curBack]; - else - curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask]; - - opt = &p->opt[cur + lenTest]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur; - opt->backPrev = curBack + LZMA_NUM_REPS; - opt->prev1IsChar = False; - } - - if (/*_maxMode && */lenTest == matches[offs]) - { - /* Try Match + Literal + Rep0 */ - const Byte *data2 = data - (curBack + 1); - UInt32 lenTest2 = lenTest + 1; - UInt32 limit = lenTest2 + p->numFastBytes; - UInt32 nextRepMatchPrice; - if (limit > numAvailFull) - limit = numAvailFull; - for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++); - lenTest2 -= lenTest + 1; - if (lenTest2 >= 2) - { - UInt32 state2 = kMatchNextStates[state]; - UInt32 posStateNext = (position + lenTest) & p->pbMask; - UInt32 curAndLenCharPrice = curAndLenPrice + - GET_PRICE_0(p->isMatch[state2][posStateNext]) + - LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]), - data[lenTest], data2[lenTest], p->ProbPrices); - state2 = kLiteralNextStates[state2]; - posStateNext = (posStateNext + 1) & p->pbMask; - nextRepMatchPrice = curAndLenCharPrice + - GET_PRICE_1(p->isMatch[state2][posStateNext]) + - GET_PRICE_1(p->isRep[state2]); - - /* for (; lenTest2 >= 2; lenTest2--) */ - { - UInt32 offset = cur + lenTest + 1 + lenTest2; - UInt32 curAndLenPrice; - COptimal *opt; - while (lenEnd < offset) - p->opt[++lenEnd].price = kInfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); - opt = &p->opt[offset]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur + lenTest + 1; - opt->backPrev = 0; - opt->prev1IsChar = True; - opt->prev2 = True; - opt->posPrev2 = cur; - opt->backPrev2 = curBack + LZMA_NUM_REPS; - } - } - } - offs += 2; - if (offs == numPairs) - break; - curBack = matches[offs + 1]; - if (curBack >= kNumFullDistances) - GetPosSlot2(curBack, posSlot); - } - } - } - } -} - -#define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist)) - -static UInt32 GetOptimumFast(CLzmaEnc *p, UInt32 *backRes) -{ - UInt32 numAvail, mainLen, mainDist, numPairs, repIndex, repLen, i; - const Byte *data; - const UInt32 *matches; - - if (p->additionalOffset == 0) - mainLen = ReadMatchDistances(p, &numPairs); - else - { - mainLen = p->longestMatchLength; - numPairs = p->numPairs; - } - - numAvail = p->numAvail; - *backRes = (UInt32)-1; - if (numAvail < 2) - return 1; - if (numAvail > LZMA_MATCH_LEN_MAX) - numAvail = LZMA_MATCH_LEN_MAX; - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - - repLen = repIndex = 0; - for (i = 0; i < LZMA_NUM_REPS; i++) - { - UInt32 len; - const Byte *data2 = data - (p->reps[i] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - continue; - for (len = 2; len < numAvail && data[len] == data2[len]; len++); - if (len >= p->numFastBytes) - { - *backRes = i; - MovePos(p, len - 1); - return len; - } - if (len > repLen) - { - repIndex = i; - repLen = len; - } - } - - matches = p->matches; - if (mainLen >= p->numFastBytes) - { - *backRes = matches[numPairs - 1] + LZMA_NUM_REPS; - MovePos(p, mainLen - 1); - return mainLen; - } - - mainDist = 0; /* for GCC */ - if (mainLen >= 2) - { - mainDist = matches[numPairs - 1]; - while (numPairs > 2 && mainLen == matches[numPairs - 4] + 1) - { - if (!ChangePair(matches[numPairs - 3], mainDist)) - break; - numPairs -= 2; - mainLen = matches[numPairs - 2]; - mainDist = matches[numPairs - 1]; - } - if (mainLen == 2 && mainDist >= 0x80) - mainLen = 1; - } - - if (repLen >= 2 && ( - (repLen + 1 >= mainLen) || - (repLen + 2 >= mainLen && mainDist >= (1 << 9)) || - (repLen + 3 >= mainLen && mainDist >= (1 << 15)))) - { - *backRes = repIndex; - MovePos(p, repLen - 1); - return repLen; - } - - if (mainLen < 2 || numAvail <= 2) - return 1; - - p->longestMatchLength = ReadMatchDistances(p, &p->numPairs); - if (p->longestMatchLength >= 2) - { - UInt32 newDistance = matches[p->numPairs - 1]; - if ((p->longestMatchLength >= mainLen && newDistance < mainDist) || - (p->longestMatchLength == mainLen + 1 && !ChangePair(mainDist, newDistance)) || - (p->longestMatchLength > mainLen + 1) || - (p->longestMatchLength + 1 >= mainLen && mainLen >= 3 && ChangePair(newDistance, mainDist))) - return 1; - } - - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - for (i = 0; i < LZMA_NUM_REPS; i++) - { - UInt32 len, limit; - const Byte *data2 = data - (p->reps[i] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - continue; - limit = mainLen - 1; - for (len = 2; len < limit && data[len] == data2[len]; len++); - if (len >= limit) - return 1; - } - *backRes = mainDist + LZMA_NUM_REPS; - MovePos(p, mainLen - 2); - return mainLen; -} - -static void WriteEndMarker(CLzmaEnc *p, UInt32 posState) -{ - UInt32 len; - RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1); - RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0); - p->state = kMatchNextStates[p->state]; - len = LZMA_MATCH_LEN_MIN; - LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); - RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, (1 << kNumPosSlotBits) - 1); - RangeEnc_EncodeDirectBits(&p->rc, (((UInt32)1 << 30) - 1) >> kNumAlignBits, 30 - kNumAlignBits); - RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask); -} - -static SRes CheckErrors(CLzmaEnc *p) -{ - if (p->result != SZ_OK) - return p->result; - if (p->rc.res != SZ_OK) - p->result = SZ_ERROR_WRITE; - if (p->matchFinderBase.result != SZ_OK) - p->result = SZ_ERROR_READ; - if (p->result != SZ_OK) - p->finished = True; - return p->result; -} - -static SRes Flush(CLzmaEnc *p, UInt32 nowPos) -{ - /* ReleaseMFStream(); */ - p->finished = True; - if (p->writeEndMark) - WriteEndMarker(p, nowPos & p->pbMask); - RangeEnc_FlushData(&p->rc); - RangeEnc_FlushStream(&p->rc); - return CheckErrors(p); -} - -static void FillAlignPrices(CLzmaEnc *p) -{ - UInt32 i; - for (i = 0; i < kAlignTableSize; i++) - p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices); - p->alignPriceCount = 0; -} - -static void FillDistancesPrices(CLzmaEnc *p) -{ - UInt32 tempPrices[kNumFullDistances]; - UInt32 i, lenToPosState; - for (i = kStartPosModelIndex; i < kNumFullDistances; i++) - { - UInt32 posSlot = GetPosSlot1(i); - UInt32 footerBits = ((posSlot >> 1) - 1); - UInt32 base = ((2 | (posSlot & 1)) << footerBits); - tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices); - } - - for (lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++) - { - UInt32 posSlot; - const CLzmaProb *encoder = p->posSlotEncoder[lenToPosState]; - UInt32 *posSlotPrices = p->posSlotPrices[lenToPosState]; - for (posSlot = 0; posSlot < p->distTableSize; posSlot++) - posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices); - for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++) - posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits); - - { - UInt32 *distancesPrices = p->distancesPrices[lenToPosState]; - UInt32 i; - for (i = 0; i < kStartPosModelIndex; i++) - distancesPrices[i] = posSlotPrices[i]; - for (; i < kNumFullDistances; i++) - distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i]; - } - } - p->matchPriceCount = 0; -} - -void LzmaEnc_Construct(CLzmaEnc *p) -{ - RangeEnc_Construct(&p->rc); - MatchFinder_Construct(&p->matchFinderBase); - #ifdef COMPRESS_MF_MT - MatchFinderMt_Construct(&p->matchFinderMt); - p->matchFinderMt.MatchFinder = &p->matchFinderBase; - #endif - - { - CLzmaEncProps props; - LzmaEncProps_Init(&props); - LzmaEnc_SetProps(p, &props); - } - - #ifndef LZMA_LOG_BSR - LzmaEnc_FastPosInit(p->g_FastPos); - #endif - - LzmaEnc_InitPriceTables(p->ProbPrices); - p->litProbs = 0; - p->saveState.litProbs = 0; -} - -CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc) -{ - void *p; - p = alloc->Alloc(alloc, sizeof(CLzmaEnc)); - if (p != 0) - LzmaEnc_Construct((CLzmaEnc *)p); - return p; -} - -void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAlloc *alloc) -{ - alloc->Free(alloc, p->litProbs); - alloc->Free(alloc, p->saveState.litProbs); - p->litProbs = 0; - p->saveState.litProbs = 0; -} - -void LzmaEnc_Destruct(CLzmaEnc *p, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - #ifdef COMPRESS_MF_MT - MatchFinderMt_Destruct(&p->matchFinderMt, allocBig); - #endif - MatchFinder_Free(&p->matchFinderBase, allocBig); - LzmaEnc_FreeLits(p, alloc); - RangeEnc_Free(&p->rc, alloc); -} - -void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig); - alloc->Free(alloc, p); -} - -static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize, UInt32 maxUnpackSize) -{ - UInt32 nowPos32, startPos32; - if (p->inStream != 0) - { - p->matchFinderBase.stream = p->inStream; - p->matchFinder.Init(p->matchFinderObj); - p->inStream = 0; - } - - if (p->finished) - return p->result; - RINOK(CheckErrors(p)); - - nowPos32 = (UInt32)p->nowPos64; - startPos32 = nowPos32; - - if (p->nowPos64 == 0) - { - UInt32 numPairs; - Byte curByte; - if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0) - return Flush(p, nowPos32); - ReadMatchDistances(p, &numPairs); - RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0); - p->state = kLiteralNextStates[p->state]; - curByte = p->matchFinder.GetIndexByte(p->matchFinderObj, 0 - p->additionalOffset); - LitEnc_Encode(&p->rc, p->litProbs, curByte); - p->additionalOffset--; - nowPos32++; - } - - if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0) - for (;;) - { - UInt32 pos, len, posState; - - if (p->fastMode) - len = GetOptimumFast(p, &pos); - else - len = GetOptimum(p, nowPos32, &pos); - - #ifdef SHOW_STAT2 - printf("\n pos = %4X, len = %d pos = %d", nowPos32, len, pos); - #endif - - posState = nowPos32 & p->pbMask; - if (len == 1 && pos == (UInt32)-1) - { - Byte curByte; - CLzmaProb *probs; - const Byte *data; - - RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0); - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; - curByte = *data; - probs = LIT_PROBS(nowPos32, *(data - 1)); - if (IsCharState(p->state)) - LitEnc_Encode(&p->rc, probs, curByte); - else - LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1)); - p->state = kLiteralNextStates[p->state]; - } - else - { - RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1); - if (pos < LZMA_NUM_REPS) - { - RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1); - if (pos == 0) - { - RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0); - RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1)); - } - else - { - UInt32 distance = p->reps[pos]; - RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1); - if (pos == 1) - RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0); - else - { - RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1); - RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2); - if (pos == 3) - p->reps[3] = p->reps[2]; - p->reps[2] = p->reps[1]; - } - p->reps[1] = p->reps[0]; - p->reps[0] = distance; - } - if (len == 1) - p->state = kShortRepNextStates[p->state]; - else - { - LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); - p->state = kRepNextStates[p->state]; - } - } - else - { - UInt32 posSlot; - RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0); - p->state = kMatchNextStates[p->state]; - LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); - pos -= LZMA_NUM_REPS; - GetPosSlot(pos, posSlot); - RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot); - - if (posSlot >= kStartPosModelIndex) - { - UInt32 footerBits = ((posSlot >> 1) - 1); - UInt32 base = ((2 | (posSlot & 1)) << footerBits); - UInt32 posReduced = pos - base; - - if (posSlot < kEndPosModelIndex) - RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced); - else - { - RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits); - RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask); - p->alignPriceCount++; - } - } - p->reps[3] = p->reps[2]; - p->reps[2] = p->reps[1]; - p->reps[1] = p->reps[0]; - p->reps[0] = pos; - p->matchPriceCount++; - } - } - p->additionalOffset -= len; - nowPos32 += len; - if (p->additionalOffset == 0) - { - UInt32 processed; - if (!p->fastMode) - { - if (p->matchPriceCount >= (1 << 7)) - FillDistancesPrices(p); - if (p->alignPriceCount >= kAlignTableSize) - FillAlignPrices(p); - } - if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0) - break; - processed = nowPos32 - startPos32; - if (useLimits) - { - if (processed + kNumOpts + 300 >= maxUnpackSize || - RangeEnc_GetProcessed(&p->rc) + kNumOpts * 2 >= maxPackSize) - break; - } - else if (processed >= (1 << 15)) - { - p->nowPos64 += nowPos32 - startPos32; - return CheckErrors(p); - } - } - } - p->nowPos64 += nowPos32 - startPos32; - return Flush(p, nowPos32); -} - -#define kBigHashDicLimit ((UInt32)1 << 24) - -static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - UInt32 beforeSize = kNumOpts; - Bool btMode; - if (!RangeEnc_Alloc(&p->rc, alloc)) - return SZ_ERROR_MEM; - btMode = (p->matchFinderBase.btMode != 0); - #ifdef COMPRESS_MF_MT - p->mtMode = (p->multiThread && !p->fastMode && btMode); - #endif - - { - unsigned lclp = p->lc + p->lp; - if (p->litProbs == 0 || p->saveState.litProbs == 0 || p->lclp != lclp) - { - LzmaEnc_FreeLits(p, alloc); - p->litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb)); - p->saveState.litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb)); - if (p->litProbs == 0 || p->saveState.litProbs == 0) - { - LzmaEnc_FreeLits(p, alloc); - return SZ_ERROR_MEM; - } - p->lclp = lclp; - } - } - - p->matchFinderBase.bigHash = (p->dictSize > kBigHashDicLimit); - - if (beforeSize + p->dictSize < keepWindowSize) - beforeSize = keepWindowSize - p->dictSize; - - #ifdef COMPRESS_MF_MT - if (p->mtMode) - { - RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig)); - p->matchFinderObj = &p->matchFinderMt; - MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder); - } - else - #endif - { - if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig)) - return SZ_ERROR_MEM; - p->matchFinderObj = &p->matchFinderBase; - MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder); - } - return SZ_OK; -} - -void LzmaEnc_Init(CLzmaEnc *p) -{ - UInt32 i; - p->state = 0; - for (i = 0 ; i < LZMA_NUM_REPS; i++) - p->reps[i] = 0; - - RangeEnc_Init(&p->rc); - - - for (i = 0; i < kNumStates; i++) - { - UInt32 j; - for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++) - { - p->isMatch[i][j] = kProbInitValue; - p->isRep0Long[i][j] = kProbInitValue; - } - p->isRep[i] = kProbInitValue; - p->isRepG0[i] = kProbInitValue; - p->isRepG1[i] = kProbInitValue; - p->isRepG2[i] = kProbInitValue; - } - - { - UInt32 num = 0x300 << (p->lp + p->lc); - for (i = 0; i < num; i++) - p->litProbs[i] = kProbInitValue; - } - - { - for (i = 0; i < kNumLenToPosStates; i++) - { - CLzmaProb *probs = p->posSlotEncoder[i]; - UInt32 j; - for (j = 0; j < (1 << kNumPosSlotBits); j++) - probs[j] = kProbInitValue; - } - } - { - for (i = 0; i < kNumFullDistances - kEndPosModelIndex; i++) - p->posEncoders[i] = kProbInitValue; - } - - LenEnc_Init(&p->lenEnc.p); - LenEnc_Init(&p->repLenEnc.p); - - for (i = 0; i < (1 << kNumAlignBits); i++) - p->posAlignEncoder[i] = kProbInitValue; - - p->optimumEndIndex = 0; - p->optimumCurrentIndex = 0; - p->additionalOffset = 0; - - p->pbMask = (1 << p->pb) - 1; - p->lpMask = (1 << p->lp) - 1; -} - -void LzmaEnc_InitPrices(CLzmaEnc *p) -{ - if (!p->fastMode) - { - FillDistancesPrices(p); - FillAlignPrices(p); - } - - p->lenEnc.tableSize = - p->repLenEnc.tableSize = - p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN; - LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, p->ProbPrices); - LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, p->ProbPrices); -} - -static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - UInt32 i; - for (i = 0; i < (UInt32)kDicLogSizeMaxCompress; i++) - if (p->dictSize <= ((UInt32)1 << i)) - break; - p->distTableSize = i * 2; - - p->finished = False; - p->result = SZ_OK; - RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig)); - LzmaEnc_Init(p); - LzmaEnc_InitPrices(p); - p->nowPos64 = 0; - return SZ_OK; -} - -static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqInStream *inStream, ISeqOutStream *outStream, - ISzAlloc *alloc, ISzAlloc *allocBig) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - p->inStream = inStream; - p->rc.outStream = outStream; - return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig); -} - -SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, - ISeqInStream *inStream, UInt32 keepWindowSize, - ISzAlloc *alloc, ISzAlloc *allocBig) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - p->inStream = inStream; - return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig); -} - -static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen) -{ - p->seqBufInStream.funcTable.Read = MyRead; - p->seqBufInStream.data = src; - p->seqBufInStream.rem = srcLen; -} - -SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, - UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - LzmaEnc_SetInputBuf(p, src, srcLen); - p->inStream = &p->seqBufInStream.funcTable; - return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig); -} - -void LzmaEnc_Finish(CLzmaEncHandle pp) -{ - #ifdef COMPRESS_MF_MT - CLzmaEnc *p = (CLzmaEnc *)pp; - if (p->mtMode) - MatchFinderMt_ReleaseStream(&p->matchFinderMt); - #else - pp = pp; - #endif -} - -typedef struct _CSeqOutStreamBuf -{ - ISeqOutStream funcTable; - Byte *data; - SizeT rem; - Bool overflow; -} CSeqOutStreamBuf; - -static size_t MyWrite(void *pp, const void *data, size_t size) -{ - CSeqOutStreamBuf *p = (CSeqOutStreamBuf *)pp; - if (p->rem < size) - { - size = p->rem; - p->overflow = True; - } - memcpy(p->data, data, size); - p->rem -= size; - p->data += size; - return size; -} - - -UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp) -{ - const CLzmaEnc *p = (CLzmaEnc *)pp; - return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj); -} - -const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp) -{ - const CLzmaEnc *p = (CLzmaEnc *)pp; - return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; -} - -SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit, - Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - UInt64 nowPos64; - SRes res; - CSeqOutStreamBuf outStream; - - outStream.funcTable.Write = MyWrite; - outStream.data = dest; - outStream.rem = *destLen; - outStream.overflow = False; - - p->writeEndMark = False; - p->finished = False; - p->result = SZ_OK; - - if (reInit) - LzmaEnc_Init(p); - LzmaEnc_InitPrices(p); - nowPos64 = p->nowPos64; - RangeEnc_Init(&p->rc); - p->rc.outStream = &outStream.funcTable; - - res = LzmaEnc_CodeOneBlock(p, True, desiredPackSize, *unpackSize); - - *unpackSize = (UInt32)(p->nowPos64 - nowPos64); - *destLen -= outStream.rem; - if (outStream.overflow) - return SZ_ERROR_OUTPUT_EOF; - - return res; -} - -SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress, - ISzAlloc *alloc, ISzAlloc *allocBig) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - SRes res = SZ_OK; - - #ifdef COMPRESS_MF_MT - Byte allocaDummy[0x300]; - int i = 0; - for (i = 0; i < 16; i++) - allocaDummy[i] = (Byte)i; - #endif - - RINOK(LzmaEnc_Prepare(pp, inStream, outStream, alloc, allocBig)); - - for (;;) - { - res = LzmaEnc_CodeOneBlock(p, False, 0, 0); - if (res != SZ_OK || p->finished != 0) - break; - if (progress != 0) - { - res = progress->Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc)); - if (res != SZ_OK) - { - res = SZ_ERROR_PROGRESS; - break; - } - } - } - LzmaEnc_Finish(pp); - return res; -} - -SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size) -{ - CLzmaEnc *p = (CLzmaEnc *)pp; - int i; - UInt32 dictSize = p->dictSize; - if (*size < LZMA_PROPS_SIZE) - return SZ_ERROR_PARAM; - *size = LZMA_PROPS_SIZE; - props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc); - - for (i = 11; i <= 30; i++) - { - if (dictSize <= ((UInt32)2 << i)) - { - dictSize = (2 << i); - break; - } - if (dictSize <= ((UInt32)3 << i)) - { - dictSize = (3 << i); - break; - } - } - - for (i = 0; i < 4; i++) - props[1 + i] = (Byte)(dictSize >> (8 * i)); - return SZ_OK; -} - -SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - SRes res; - CLzmaEnc *p = (CLzmaEnc *)pp; - - CSeqOutStreamBuf outStream; - - LzmaEnc_SetInputBuf(p, src, srcLen); - - outStream.funcTable.Write = MyWrite; - outStream.data = dest; - outStream.rem = *destLen; - outStream.overflow = False; - - p->writeEndMark = writeEndMark; - res = LzmaEnc_Encode(pp, &outStream.funcTable, &p->seqBufInStream.funcTable, - progress, alloc, allocBig); - - *destLen -= outStream.rem; - if (outStream.overflow) - return SZ_ERROR_OUTPUT_EOF; - return res; -} - -SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, - ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig) -{ - CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc); - SRes res; - if (p == 0) - return SZ_ERROR_MEM; - - res = LzmaEnc_SetProps(p, props); - if (res == SZ_OK) - { - res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize); - if (res == SZ_OK) - res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen, - writeEndMark, progress, alloc, allocBig); - } - - LzmaEnc_Destroy(p, alloc, allocBig); - return res; -} diff --git a/desmume/src/windows/7z/C/LzmaEnc.h b/desmume/src/windows/7z/C/LzmaEnc.h deleted file mode 100644 index e3d84fa35..000000000 --- a/desmume/src/windows/7z/C/LzmaEnc.h +++ /dev/null @@ -1,72 +0,0 @@ -/* LzmaEnc.h -- LZMA Encoder -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __LZMAENC_H -#define __LZMAENC_H - -#include "Types.h" - -#define LZMA_PROPS_SIZE 5 - -typedef struct _CLzmaEncProps -{ - int level; /* 0 <= level <= 9 */ - UInt32 dictSize; /* (1 << 12) <= dictSize <= (1 << 27) for 32-bit version - (1 << 12) <= dictSize <= (1 << 30) for 64-bit version - default = (1 << 24) */ - int lc; /* 0 <= lc <= 8, default = 3 */ - int lp; /* 0 <= lp <= 4, default = 0 */ - int pb; /* 0 <= pb <= 4, default = 2 */ - int algo; /* 0 - fast, 1 - normal, default = 1 */ - int fb; /* 5 <= fb <= 273, default = 32 */ - int btMode; /* 0 - hashChain Mode, 1 - binTree mode - normal, default = 1 */ - int numHashBytes; /* 2, 3 or 4, default = 4 */ - UInt32 mc; /* 1 <= mc <= (1 << 30), default = 32 */ - unsigned writeEndMark; /* 0 - do not write EOPM, 1 - write EOPM, default = 0 */ - int numThreads; /* 1 or 2, default = 2 */ -} CLzmaEncProps; - -void LzmaEncProps_Init(CLzmaEncProps *p); -void LzmaEncProps_Normalize(CLzmaEncProps *p); -UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2); - - -/* ---------- CLzmaEncHandle Interface ---------- */ - -/* LzmaEnc_* functions can return the following exit codes: -Returns: - SZ_OK - OK - SZ_ERROR_MEM - Memory allocation error - SZ_ERROR_PARAM - Incorrect paramater in props - SZ_ERROR_WRITE - Write callback error. - SZ_ERROR_PROGRESS - some break from progress callback - SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version) -*/ - -typedef void * CLzmaEncHandle; - -CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc); -void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig); -SRes LzmaEnc_SetProps(CLzmaEncHandle p, const CLzmaEncProps *props); -SRes LzmaEnc_WriteProperties(CLzmaEncHandle p, Byte *properties, SizeT *size); -SRes LzmaEnc_Encode(CLzmaEncHandle p, ISeqOutStream *outStream, ISeqInStream *inStream, - ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig); -SRes LzmaEnc_MemEncode(CLzmaEncHandle p, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig); - -/* ---------- One Call Interface ---------- */ - -/* LzmaEncode -Return code: - SZ_OK - OK - SZ_ERROR_MEM - Memory allocation error - SZ_ERROR_PARAM - Incorrect paramater - SZ_ERROR_OUTPUT_EOF - output buffer overflow - SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version) -*/ - -SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, - ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig); - -#endif diff --git a/desmume/src/windows/7z/C/RotateDefs.h b/desmume/src/windows/7z/C/RotateDefs.h deleted file mode 100644 index 189350d7b..000000000 --- a/desmume/src/windows/7z/C/RotateDefs.h +++ /dev/null @@ -1,22 +0,0 @@ -/* RotateDefs.h -- Rotate functions -2008-08-05 -Igor Pavlov -Public domain */ - -#ifndef __ROTATEDEFS_H -#define __ROTATEDEFS_H - -#ifdef _MSC_VER - -#include -#define rotlFixed(x, n) _rotl((x), (n)) -#define rotrFixed(x, n) _rotr((x), (n)) - -#else - -#define rotlFixed(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) -#define rotrFixed(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) - -#endif - -#endif diff --git a/desmume/src/windows/7z/C/Sha256.c b/desmume/src/windows/7z/C/Sha256.c deleted file mode 100644 index 657c2ab92..000000000 --- a/desmume/src/windows/7z/C/Sha256.c +++ /dev/null @@ -1,204 +0,0 @@ -/* Crypto/Sha256.c -- SHA-256 Hash function -2008-11-06 : Igor Pavlov : Public domain -This code is based on public domain code from Wei Dai's Crypto++ library. */ - -#include "Sha256.h" -#include "RotateDefs.h" - -/* define it for speed optimization */ -/* #define _SHA256_UNROLL */ -/* #define _SHA256_UNROLL2 */ - -void Sha256_Init(CSha256 *p) -{ - p->state[0] = 0x6a09e667; - p->state[1] = 0xbb67ae85; - p->state[2] = 0x3c6ef372; - p->state[3] = 0xa54ff53a; - p->state[4] = 0x510e527f; - p->state[5] = 0x9b05688c; - p->state[6] = 0x1f83d9ab; - p->state[7] = 0x5be0cd19; - p->count = 0; -} - -#define S0(x) (rotrFixed(x, 2) ^ rotrFixed(x,13) ^ rotrFixed(x, 22)) -#define S1(x) (rotrFixed(x, 6) ^ rotrFixed(x,11) ^ rotrFixed(x, 25)) -#define s0(x) (rotrFixed(x, 7) ^ rotrFixed(x,18) ^ (x >> 3)) -#define s1(x) (rotrFixed(x,17) ^ rotrFixed(x,19) ^ (x >> 10)) - -#define blk0(i) (W[i] = data[i]) -#define blk2(i) (W[i&15] += s1(W[(i-2)&15]) + W[(i-7)&15] + s0(W[(i-15)&15])) - -#define Ch(x,y,z) (z^(x&(y^z))) -#define Maj(x,y,z) ((x&y)|(z&(x|y))) - -#define a(i) T[(0-(i))&7] -#define b(i) T[(1-(i))&7] -#define c(i) T[(2-(i))&7] -#define d(i) T[(3-(i))&7] -#define e(i) T[(4-(i))&7] -#define f(i) T[(5-(i))&7] -#define g(i) T[(6-(i))&7] -#define h(i) T[(7-(i))&7] - - -#ifdef _SHA256_UNROLL2 - -#define R(a,b,c,d,e,f,g,h, i) h += S1(e) + Ch(e,f,g) + K[i+j] + (j?blk2(i):blk0(i));\ - d += h; h += S0(a) + Maj(a, b, c) - -#define RX_8(i) \ - R(a,b,c,d,e,f,g,h, i); \ - R(h,a,b,c,d,e,f,g, i+1); \ - R(g,h,a,b,c,d,e,f, i+2); \ - R(f,g,h,a,b,c,d,e, i+3); \ - R(e,f,g,h,a,b,c,d, i+4); \ - R(d,e,f,g,h,a,b,c, i+5); \ - R(c,d,e,f,g,h,a,b, i+6); \ - R(b,c,d,e,f,g,h,a, i+7) - -#else - -#define R(i) h(i) += S1(e(i)) + Ch(e(i),f(i),g(i)) + K[i+j] + (j?blk2(i):blk0(i));\ - d(i) += h(i); h(i) += S0(a(i)) + Maj(a(i), b(i), c(i)) - -#ifdef _SHA256_UNROLL - -#define RX_8(i) R(i+0); R(i+1); R(i+2); R(i+3); R(i+4); R(i+5); R(i+6); R(i+7); - -#endif - -#endif - -const UInt32 K[64] = { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -}; - -static void Sha256_Transform(UInt32 *state, const UInt32 *data) -{ - UInt32 W[16]; - unsigned j; - #ifdef _SHA256_UNROLL2 - UInt32 a,b,c,d,e,f,g,h; - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - f = state[5]; - g = state[6]; - h = state[7]; - #else - UInt32 T[8]; - for (j = 0; j < 8; j++) - T[j] = state[j]; - #endif - - for (j = 0; j < 64; j += 16) - { - #if defined(_SHA256_UNROLL) || defined(_SHA256_UNROLL2) - RX_8(0); RX_8(8); - #else - unsigned i; - for (i = 0; i < 16; i++) { R(i); } - #endif - } - - #ifdef _SHA256_UNROLL2 - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - state[4] += e; - state[5] += f; - state[6] += g; - state[7] += h; - #else - for (j = 0; j < 8; j++) - state[j] += T[j]; - #endif - - /* Wipe variables */ - /* memset(W, 0, sizeof(W)); */ - /* memset(T, 0, sizeof(T)); */ -} - -#undef S0 -#undef S1 -#undef s0 -#undef s1 - -static void Sha256_WriteByteBlock(CSha256 *p) -{ - UInt32 data32[16]; - unsigned i; - for (i = 0; i < 16; i++) - data32[i] = - ((UInt32)(p->buffer[i * 4 ]) << 24) + - ((UInt32)(p->buffer[i * 4 + 1]) << 16) + - ((UInt32)(p->buffer[i * 4 + 2]) << 8) + - ((UInt32)(p->buffer[i * 4 + 3])); - Sha256_Transform(p->state, data32); -} - -void Sha256_Update(CSha256 *p, const Byte *data, size_t size) -{ - UInt32 curBufferPos = (UInt32)p->count & 0x3F; - while (size > 0) - { - p->buffer[curBufferPos++] = *data++; - p->count++; - size--; - if (curBufferPos == 64) - { - curBufferPos = 0; - Sha256_WriteByteBlock(p); - } - } -} - -void Sha256_Final(CSha256 *p, Byte *digest) -{ - UInt64 lenInBits = (p->count << 3); - UInt32 curBufferPos = (UInt32)p->count & 0x3F; - unsigned i; - p->buffer[curBufferPos++] = 0x80; - while (curBufferPos != (64 - 8)) - { - curBufferPos &= 0x3F; - if (curBufferPos == 0) - Sha256_WriteByteBlock(p); - p->buffer[curBufferPos++] = 0; - } - for (i = 0; i < 8; i++) - { - p->buffer[curBufferPos++] = (Byte)(lenInBits >> 56); - lenInBits <<= 8; - } - Sha256_WriteByteBlock(p); - - for (i = 0; i < 8; i++) - { - *digest++ = (Byte)((p->state[i] >> 24) & 0xFF); - *digest++ = (Byte)((p->state[i] >> 16) & 0xFF); - *digest++ = (Byte)((p->state[i] >> 8) & 0xFF); - *digest++ = (Byte)((p->state[i]) & 0xFF); - } - Sha256_Init(p); -} diff --git a/desmume/src/windows/7z/C/Sha256.h b/desmume/src/windows/7z/C/Sha256.h deleted file mode 100644 index 8703b4a63..000000000 --- a/desmume/src/windows/7z/C/Sha256.h +++ /dev/null @@ -1,22 +0,0 @@ -/* Crypto/Sha256.h -- SHA-256 Hash function -2008-10-04 : Igor Pavlov : Public domain */ - -#ifndef __CRYPTO_SHA256_H -#define __CRYPTO_SHA256_H - -#include "Types.h" - -#define SHA256_DIGEST_SIZE 32 - -typedef struct -{ - UInt32 state[8]; - UInt64 count; - Byte buffer[64]; -} CSha256; - -void Sha256_Init(CSha256 *p); -void Sha256_Update(CSha256 *p, const Byte *data, size_t size); -void Sha256_Final(CSha256 *p, Byte *digest); - -#endif diff --git a/desmume/src/windows/7z/C/Sort.c b/desmume/src/windows/7z/C/Sort.c deleted file mode 100644 index bb20dc348..000000000 --- a/desmume/src/windows/7z/C/Sort.c +++ /dev/null @@ -1,95 +0,0 @@ -/* Sort.c -- Sort functions -2008-08-17 -Igor Pavlov -Public domain */ - -#include "Sort.h" - -#define HeapSortDown(p, k, size, temp) \ - { for (;;) { \ - UInt32 s = (k << 1); \ - if (s > size) break; \ - if (s < size && p[s + 1] > p[s]) s++; \ - if (temp >= p[s]) break; \ - p[k] = p[s]; k = s; \ - } p[k] = temp; } - -void HeapSort(UInt32 *p, UInt32 size) -{ - if (size <= 1) - return; - p--; - { - UInt32 i = size / 2; - do - { - UInt32 temp = p[i]; - UInt32 k = i; - HeapSortDown(p, k, size, temp) - } - while (--i != 0); - } - /* - do - { - UInt32 k = 1; - UInt32 temp = p[size]; - p[size--] = p[1]; - HeapSortDown(p, k, size, temp) - } - while (size > 1); - */ - while (size > 3) - { - UInt32 temp = p[size]; - UInt32 k = (p[3] > p[2]) ? 3 : 2; - p[size--] = p[1]; - p[1] = p[k]; - HeapSortDown(p, k, size, temp) - } - { - UInt32 temp = p[size]; - p[size] = p[1]; - if (size > 2 && p[2] < temp) - { - p[1] = p[2]; - p[2] = temp; - } - else - p[1] = temp; - } -} - -/* -#define HeapSortRefDown(p, vals, n, size, temp) \ - { UInt32 k = n; UInt32 val = vals[temp]; for (;;) { \ - UInt32 s = (k << 1); \ - if (s > size) break; \ - if (s < size && vals[p[s + 1]] > vals[p[s]]) s++; \ - if (val >= vals[p[s]]) break; \ - p[k] = p[s]; k = s; \ - } p[k] = temp; } - -void HeapSortRef(UInt32 *p, UInt32 *vals, UInt32 size) -{ - if (size <= 1) - return; - p--; - { - UInt32 i = size / 2; - do - { - UInt32 temp = p[i]; - HeapSortRefDown(p, vals, i, size, temp); - } - while (--i != 0); - } - do - { - UInt32 temp = p[size]; - p[size--] = p[1]; - HeapSortRefDown(p, vals, 1, size, temp); - } - while (size > 1); -} -*/ \ No newline at end of file diff --git a/desmume/src/windows/7z/C/Sort.h b/desmume/src/windows/7z/C/Sort.h deleted file mode 100644 index cff6c4c32..000000000 --- a/desmume/src/windows/7z/C/Sort.h +++ /dev/null @@ -1,14 +0,0 @@ -/* Sort.h -- Sort functions -2008-03-19 -Igor Pavlov -Public domain */ - -#ifndef __7Z_SORT_H -#define __7Z_SORT_H - -#include "Types.h" - -void HeapSort(UInt32 *p, UInt32 size); -/* void HeapSortRef(UInt32 *p, UInt32 *vals, UInt32 size); */ - -#endif diff --git a/desmume/src/windows/7z/C/Threads.c b/desmume/src/windows/7z/C/Threads.c deleted file mode 100644 index c7d8b0a8a..000000000 --- a/desmume/src/windows/7z/C/Threads.c +++ /dev/null @@ -1,109 +0,0 @@ -/* Threads.c -- multithreading library -2008-08-05 -Igor Pavlov -Public domain */ - -#include "Threads.h" -#include - -static WRes GetError() -{ - DWORD res = GetLastError(); - return (res) ? (WRes)(res) : 1; -} - -WRes HandleToWRes(HANDLE h) { return (h != 0) ? 0 : GetError(); } -WRes BOOLToWRes(BOOL v) { return v ? 0 : GetError(); } - -static WRes MyCloseHandle(HANDLE *h) -{ - if (*h != NULL) - if (!CloseHandle(*h)) - return GetError(); - *h = NULL; - return 0; -} - -WRes Thread_Create(CThread *thread, THREAD_FUNC_RET_TYPE (THREAD_FUNC_CALL_TYPE *startAddress)(void *), LPVOID parameter) -{ - unsigned threadId; /* Windows Me/98/95: threadId parameter may not be NULL in _beginthreadex/CreateThread functions */ - thread->handle = - /* CreateThread(0, 0, startAddress, parameter, 0, &threadId); */ - (HANDLE)_beginthreadex(NULL, 0, startAddress, parameter, 0, &threadId); - /* maybe we must use errno here, but probably GetLastError() is also OK. */ - return HandleToWRes(thread->handle); -} - -WRes WaitObject(HANDLE h) -{ - return (WRes)WaitForSingleObject(h, INFINITE); -} - -WRes Thread_Wait(CThread *thread) -{ - if (thread->handle == NULL) - return 1; - return WaitObject(thread->handle); -} - -WRes Thread_Close(CThread *thread) -{ - return MyCloseHandle(&thread->handle); -} - -WRes Event_Create(CEvent *p, BOOL manualReset, int initialSignaled) -{ - p->handle = CreateEvent(NULL, manualReset, (initialSignaled ? TRUE : FALSE), NULL); - return HandleToWRes(p->handle); -} - -WRes ManualResetEvent_Create(CManualResetEvent *p, int initialSignaled) - { return Event_Create(p, TRUE, initialSignaled); } -WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *p) - { return ManualResetEvent_Create(p, 0); } - -WRes AutoResetEvent_Create(CAutoResetEvent *p, int initialSignaled) - { return Event_Create(p, FALSE, initialSignaled); } -WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p) - { return AutoResetEvent_Create(p, 0); } - -WRes Event_Set(CEvent *p) { return BOOLToWRes(SetEvent(p->handle)); } -WRes Event_Reset(CEvent *p) { return BOOLToWRes(ResetEvent(p->handle)); } -WRes Event_Wait(CEvent *p) { return WaitObject(p->handle); } -WRes Event_Close(CEvent *p) { return MyCloseHandle(&p->handle); } - - -WRes Semaphore_Create(CSemaphore *p, UInt32 initiallyCount, UInt32 maxCount) -{ - p->handle = CreateSemaphore(NULL, (LONG)initiallyCount, (LONG)maxCount, NULL); - return HandleToWRes(p->handle); -} - -WRes Semaphore_Release(CSemaphore *p, LONG releaseCount, LONG *previousCount) -{ - return BOOLToWRes(ReleaseSemaphore(p->handle, releaseCount, previousCount)); -} -WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 releaseCount) -{ - return Semaphore_Release(p, (LONG)releaseCount, NULL); -} -WRes Semaphore_Release1(CSemaphore *p) -{ - return Semaphore_ReleaseN(p, 1); -} - -WRes Semaphore_Wait(CSemaphore *p) { return WaitObject(p->handle); } -WRes Semaphore_Close(CSemaphore *p) { return MyCloseHandle(&p->handle); } - -WRes CriticalSection_Init(CCriticalSection *p) -{ - /* InitializeCriticalSection can raise only STATUS_NO_MEMORY exception */ - __try - { - InitializeCriticalSection(p); - /* InitializeCriticalSectionAndSpinCount(p, 0); */ - } - __except (EXCEPTION_EXECUTE_HANDLER) { return 1; } - return 0; -} - diff --git a/desmume/src/windows/7z/C/Threads.h b/desmume/src/windows/7z/C/Threads.h deleted file mode 100644 index 3d9072946..000000000 --- a/desmume/src/windows/7z/C/Threads.h +++ /dev/null @@ -1,68 +0,0 @@ -/* Threads.h -- multithreading library -2008-11-22 : Igor Pavlov : Public domain */ - -#ifndef __7Z_THRESDS_H -#define __7Z_THRESDS_H - -#include "Types.h" - -typedef struct _CThread -{ - HANDLE handle; -} CThread; - -#define Thread_Construct(thread) (thread)->handle = NULL -#define Thread_WasCreated(thread) ((thread)->handle != NULL) - -typedef unsigned THREAD_FUNC_RET_TYPE; -#define THREAD_FUNC_CALL_TYPE MY_STD_CALL -#define THREAD_FUNC_DECL THREAD_FUNC_RET_TYPE THREAD_FUNC_CALL_TYPE - -WRes Thread_Create(CThread *thread, THREAD_FUNC_RET_TYPE (THREAD_FUNC_CALL_TYPE *startAddress)(void *), LPVOID parameter); -WRes Thread_Wait(CThread *thread); -WRes Thread_Close(CThread *thread); - -typedef struct _CEvent -{ - HANDLE handle; -} CEvent; - -typedef CEvent CAutoResetEvent; -typedef CEvent CManualResetEvent; - -#define Event_Construct(event) (event)->handle = NULL -#define Event_IsCreated(event) ((event)->handle != NULL) - -WRes ManualResetEvent_Create(CManualResetEvent *event, int initialSignaled); -WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *event); -WRes AutoResetEvent_Create(CAutoResetEvent *event, int initialSignaled); -WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *event); -WRes Event_Set(CEvent *event); -WRes Event_Reset(CEvent *event); -WRes Event_Wait(CEvent *event); -WRes Event_Close(CEvent *event); - - -typedef struct _CSemaphore -{ - HANDLE handle; -} CSemaphore; - -#define Semaphore_Construct(p) (p)->handle = NULL - -WRes Semaphore_Create(CSemaphore *p, UInt32 initiallyCount, UInt32 maxCount); -WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 num); -WRes Semaphore_Release1(CSemaphore *p); -WRes Semaphore_Wait(CSemaphore *p); -WRes Semaphore_Close(CSemaphore *p); - - -typedef CRITICAL_SECTION CCriticalSection; - -WRes CriticalSection_Init(CCriticalSection *p); -#define CriticalSection_Delete(p) DeleteCriticalSection(p) -#define CriticalSection_Enter(p) EnterCriticalSection(p) -#define CriticalSection_Leave(p) LeaveCriticalSection(p) - -#endif - diff --git a/desmume/src/windows/7z/C/Types.h b/desmume/src/windows/7z/C/Types.h deleted file mode 100644 index 2638196aa..000000000 --- a/desmume/src/windows/7z/C/Types.h +++ /dev/null @@ -1,208 +0,0 @@ -/* Types.h -- Basic types -2008-11-23 : Igor Pavlov : Public domain */ - -#ifndef __7Z_TYPES_H -#define __7Z_TYPES_H - -#include - -#ifdef _WIN32 -#include -#endif - -#define SZ_OK 0 - -#define SZ_ERROR_DATA 1 -#define SZ_ERROR_MEM 2 -#define SZ_ERROR_CRC 3 -#define SZ_ERROR_UNSUPPORTED 4 -#define SZ_ERROR_PARAM 5 -#define SZ_ERROR_INPUT_EOF 6 -#define SZ_ERROR_OUTPUT_EOF 7 -#define SZ_ERROR_READ 8 -#define SZ_ERROR_WRITE 9 -#define SZ_ERROR_PROGRESS 10 -#define SZ_ERROR_FAIL 11 -#define SZ_ERROR_THREAD 12 - -#define SZ_ERROR_ARCHIVE 16 -#define SZ_ERROR_NO_ARCHIVE 17 - -typedef int SRes; - -#ifdef _WIN32 -typedef DWORD WRes; -#else -typedef int WRes; -#endif - -#ifndef RINOK -#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; } -#endif - -typedef unsigned char Byte; -typedef short Int16; -typedef unsigned short UInt16; - -#ifdef _LZMA_UINT32_IS_ULONG -typedef long Int32; -typedef unsigned long UInt32; -#else -typedef int Int32; -typedef unsigned int UInt32; -#endif - -#ifdef _SZ_NO_INT_64 - -/* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers. - NOTES: Some code will work incorrectly in that case! */ - -typedef long Int64; -typedef unsigned long UInt64; - -#else - -#if defined(_MSC_VER) || defined(__BORLANDC__) -typedef __int64 Int64; -typedef unsigned __int64 UInt64; -#else -typedef long long int Int64; -typedef unsigned long long int UInt64; -#endif - -#endif - -#ifdef _LZMA_NO_SYSTEM_SIZE_T -typedef UInt32 SizeT; -#else -typedef size_t SizeT; -#endif - -typedef int Bool; -#define True 1 -#define False 0 - - -#ifdef _MSC_VER - -#if _MSC_VER >= 1300 -#define MY_NO_INLINE __declspec(noinline) -#else -#define MY_NO_INLINE -#endif - -#define MY_CDECL __cdecl -#define MY_STD_CALL __stdcall -#define MY_FAST_CALL MY_NO_INLINE __fastcall - -#else - -#define MY_CDECL -#define MY_STD_CALL -#define MY_FAST_CALL - -#endif - - -/* The following interfaces use first parameter as pointer to structure */ - -typedef struct -{ - SRes (*Read)(void *p, void *buf, size_t *size); - /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. - (output(*size) < input(*size)) is allowed */ -} ISeqInStream; - -/* it can return SZ_ERROR_INPUT_EOF */ -SRes SeqInStream_Read(ISeqInStream *stream, void *buf, size_t size); -SRes SeqInStream_Read2(ISeqInStream *stream, void *buf, size_t size, SRes errorType); -SRes SeqInStream_ReadByte(ISeqInStream *stream, Byte *buf); - -typedef struct -{ - size_t (*Write)(void *p, const void *buf, size_t size); - /* Returns: result - the number of actually written bytes. - (result < size) means error */ -} ISeqOutStream; - -typedef enum -{ - SZ_SEEK_SET = 0, - SZ_SEEK_CUR = 1, - SZ_SEEK_END = 2 -} ESzSeek; - -typedef struct -{ - SRes (*Read)(void *p, void *buf, size_t *size); /* same as ISeqInStream::Read */ - SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin); -} ISeekInStream; - -typedef struct -{ - SRes (*Look)(void *p, void **buf, size_t *size); - /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. - (output(*size) > input(*size)) is not allowed - (output(*size) < input(*size)) is allowed */ - SRes (*Skip)(void *p, size_t offset); - /* offset must be <= output(*size) of Look */ - - SRes (*Read)(void *p, void *buf, size_t *size); - /* reads directly (without buffer). It's same as ISeqInStream::Read */ - SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin); -} ILookInStream; - -SRes LookInStream_LookRead(ILookInStream *stream, void *buf, size_t *size); -SRes LookInStream_SeekTo(ILookInStream *stream, UInt64 offset); - -/* reads via ILookInStream::Read */ -SRes LookInStream_Read2(ILookInStream *stream, void *buf, size_t size, SRes errorType); -SRes LookInStream_Read(ILookInStream *stream, void *buf, size_t size); - -#define LookToRead_BUF_SIZE (1 << 14) - -typedef struct -{ - ILookInStream s; - ISeekInStream *realStream; - size_t pos; - size_t size; - Byte buf[LookToRead_BUF_SIZE]; -} CLookToRead; - -void LookToRead_CreateVTable(CLookToRead *p, int lookahead); -void LookToRead_Init(CLookToRead *p); - -typedef struct -{ - ISeqInStream s; - ILookInStream *realStream; -} CSecToLook; - -void SecToLook_CreateVTable(CSecToLook *p); - -typedef struct -{ - ISeqInStream s; - ILookInStream *realStream; -} CSecToRead; - -void SecToRead_CreateVTable(CSecToRead *p); - -typedef struct -{ - SRes (*Progress)(void *p, UInt64 inSize, UInt64 outSize); - /* Returns: result. (result != SZ_OK) means break. - Value (UInt64)(Int64)-1 for size means unknown value. */ -} ICompressProgress; - -typedef struct -{ - void *(*Alloc)(void *p, size_t size); - void (*Free)(void *p, void *address); /* address can be 0 */ -} ISzAlloc; - -#define IAlloc_Alloc(p, size) (p)->Alloc((p), size) -#define IAlloc_Free(p, a) (p)->Free((p), a) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.cpp deleted file mode 100644 index 232c63820..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.cpp +++ /dev/null @@ -1,3 +0,0 @@ -// CompressionMethod.cpp - -#include "StdAfx.h" diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.h deleted file mode 100644 index 5e986355b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zCompressionMode.h +++ /dev/null @@ -1,50 +0,0 @@ -// 7zCompressionMode.h - -#ifndef __7Z_COMPRESSION_MODE_H -#define __7Z_COMPRESSION_MODE_H - -#include "../../../Common/MyString.h" - -#include "../../../Windows/PropVariant.h" - -#include "../../Common/MethodProps.h" - -namespace NArchive { -namespace N7z { - -struct CMethodFull: public CMethod -{ - UInt32 NumInStreams; - UInt32 NumOutStreams; - bool IsSimpleCoder() const { return (NumInStreams == 1) && (NumOutStreams == 1); } -}; - -struct CBind -{ - UInt32 InCoder; - UInt32 InStream; - UInt32 OutCoder; - UInt32 OutStream; -}; - -struct CCompressionMethodMode -{ - CObjectVector Methods; - CRecordVector Binds; - #ifdef COMPRESS_MT - UInt32 NumThreads; - #endif - bool PasswordIsDefined; - UString Password; - - bool IsEmpty() const { return (Methods.IsEmpty() && !PasswordIsDefined); } - CCompressionMethodMode(): PasswordIsDefined(false) - #ifdef COMPRESS_MT - , NumThreads(1) - #endif - {} -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.cpp deleted file mode 100644 index 02744c96a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.cpp +++ /dev/null @@ -1,332 +0,0 @@ -// 7zDecode.cpp - -#include "StdAfx.h" - -#include "../../Common/LimitedStreams.h" -#include "../../Common/LockedStream.h" -#include "../../Common/ProgressUtils.h" -#include "../../Common/StreamObjects.h" - -#include "7zDecode.h" - -namespace NArchive { -namespace N7z { - -static void ConvertFolderItemInfoToBindInfo(const CFolder &folder, - CBindInfoEx &bindInfo) -{ - bindInfo.Clear(); - int i; - for (i = 0; i < folder.BindPairs.Size(); i++) - { - NCoderMixer::CBindPair bindPair; - bindPair.InIndex = (UInt32)folder.BindPairs[i].InIndex; - bindPair.OutIndex = (UInt32)folder.BindPairs[i].OutIndex; - bindInfo.BindPairs.Add(bindPair); - } - UInt32 outStreamIndex = 0; - for (i = 0; i < folder.Coders.Size(); i++) - { - NCoderMixer::CCoderStreamsInfo coderStreamsInfo; - const CCoderInfo &coderInfo = folder.Coders[i]; - coderStreamsInfo.NumInStreams = (UInt32)coderInfo.NumInStreams; - coderStreamsInfo.NumOutStreams = (UInt32)coderInfo.NumOutStreams; - bindInfo.Coders.Add(coderStreamsInfo); - bindInfo.CoderMethodIDs.Add(coderInfo.MethodID); - for (UInt32 j = 0; j < coderStreamsInfo.NumOutStreams; j++, outStreamIndex++) - if (folder.FindBindPairForOutStream(outStreamIndex) < 0) - bindInfo.OutStreams.Add(outStreamIndex); - } - for (i = 0; i < folder.PackStreams.Size(); i++) - bindInfo.InStreams.Add((UInt32)folder.PackStreams[i]); -} - -static bool AreCodersEqual(const NCoderMixer::CCoderStreamsInfo &a1, - const NCoderMixer::CCoderStreamsInfo &a2) -{ - return (a1.NumInStreams == a2.NumInStreams) && - (a1.NumOutStreams == a2.NumOutStreams); -} - -static bool AreBindPairsEqual(const NCoderMixer::CBindPair &a1, const NCoderMixer::CBindPair &a2) -{ - return (a1.InIndex == a2.InIndex) && - (a1.OutIndex == a2.OutIndex); -} - -static bool AreBindInfoExEqual(const CBindInfoEx &a1, const CBindInfoEx &a2) -{ - if (a1.Coders.Size() != a2.Coders.Size()) - return false; - int i; - for (i = 0; i < a1.Coders.Size(); i++) - if (!AreCodersEqual(a1.Coders[i], a2.Coders[i])) - return false; - if (a1.BindPairs.Size() != a2.BindPairs.Size()) - return false; - for (i = 0; i < a1.BindPairs.Size(); i++) - if (!AreBindPairsEqual(a1.BindPairs[i], a2.BindPairs[i])) - return false; - for (i = 0; i < a1.CoderMethodIDs.Size(); i++) - if (a1.CoderMethodIDs[i] != a2.CoderMethodIDs[i]) - return false; - if (a1.InStreams.Size() != a2.InStreams.Size()) - return false; - if (a1.OutStreams.Size() != a2.OutStreams.Size()) - return false; - return true; -} - -CDecoder::CDecoder(bool multiThread) -{ - #ifndef _ST_MODE - multiThread = true; - #endif - _multiThread = multiThread; - _bindInfoExPrevIsDefined = false; -} - -HRESULT CDecoder::Decode( - DECL_EXTERNAL_CODECS_LOC_VARS - IInStream *inStream, - UInt64 startPos, - const UInt64 *packSizes, - const CFolder &folderInfo, - ISequentialOutStream *outStream, - ICompressProgressInfo *compressProgress - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - #ifdef COMPRESS_MT - , bool mtMode, UInt32 numThreads - #endif - ) -{ - if (!folderInfo.CheckStructure()) - return E_NOTIMPL; - #ifndef _NO_CRYPTO - passwordIsDefined = false; - #endif - CObjectVector< CMyComPtr > inStreams; - - CLockedInStream lockedInStream; - lockedInStream.Init(inStream); - - for (int j = 0; j < folderInfo.PackStreams.Size(); j++) - { - CLockedSequentialInStreamImp *lockedStreamImpSpec = new - CLockedSequentialInStreamImp; - CMyComPtr lockedStreamImp = lockedStreamImpSpec; - lockedStreamImpSpec->Init(&lockedInStream, startPos); - startPos += packSizes[j]; - - CLimitedSequentialInStream *streamSpec = new - CLimitedSequentialInStream; - CMyComPtr inStream = streamSpec; - streamSpec->SetStream(lockedStreamImp); - streamSpec->Init(packSizes[j]); - inStreams.Add(inStream); - } - - int numCoders = folderInfo.Coders.Size(); - - CBindInfoEx bindInfo; - ConvertFolderItemInfoToBindInfo(folderInfo, bindInfo); - bool createNewCoders; - if (!_bindInfoExPrevIsDefined) - createNewCoders = true; - else - createNewCoders = !AreBindInfoExEqual(bindInfo, _bindInfoExPrev); - if (createNewCoders) - { - int i; - _decoders.Clear(); - // _decoders2.Clear(); - - _mixerCoder.Release(); - - if (_multiThread) - { - _mixerCoderMTSpec = new NCoderMixer::CCoderMixer2MT; - _mixerCoder = _mixerCoderMTSpec; - _mixerCoderCommon = _mixerCoderMTSpec; - } - else - { - #ifdef _ST_MODE - _mixerCoderSTSpec = new NCoderMixer::CCoderMixer2ST; - _mixerCoder = _mixerCoderSTSpec; - _mixerCoderCommon = _mixerCoderSTSpec; - #endif - } - RINOK(_mixerCoderCommon->SetBindInfo(bindInfo)); - - for (i = 0; i < numCoders; i++) - { - const CCoderInfo &coderInfo = folderInfo.Coders[i]; - - - CMyComPtr decoder; - CMyComPtr decoder2; - RINOK(CreateCoder( - EXTERNAL_CODECS_LOC_VARS - coderInfo.MethodID, decoder, decoder2, false)); - CMyComPtr decoderUnknown; - if (coderInfo.IsSimpleCoder()) - { - if (decoder == 0) - return E_NOTIMPL; - - decoderUnknown = (IUnknown *)decoder; - - if (_multiThread) - _mixerCoderMTSpec->AddCoder(decoder); - #ifdef _ST_MODE - else - _mixerCoderSTSpec->AddCoder(decoder, false); - #endif - } - else - { - if (decoder2 == 0) - return E_NOTIMPL; - decoderUnknown = (IUnknown *)decoder2; - if (_multiThread) - _mixerCoderMTSpec->AddCoder2(decoder2); - #ifdef _ST_MODE - else - _mixerCoderSTSpec->AddCoder2(decoder2, false); - #endif - } - _decoders.Add(decoderUnknown); - #ifdef EXTERNAL_CODECS - CMyComPtr setCompressCodecsInfo; - decoderUnknown.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); - if (setCompressCodecsInfo) - { - RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(codecsInfo)); - } - #endif - } - _bindInfoExPrev = bindInfo; - _bindInfoExPrevIsDefined = true; - } - int i; - _mixerCoderCommon->ReInit(); - - UInt32 packStreamIndex = 0, unpackStreamIndex = 0; - UInt32 coderIndex = 0; - // UInt32 coder2Index = 0; - - for (i = 0; i < numCoders; i++) - { - const CCoderInfo &coderInfo = folderInfo.Coders[i]; - CMyComPtr &decoder = _decoders[coderIndex]; - - { - CMyComPtr setDecoderProperties; - decoder.QueryInterface(IID_ICompressSetDecoderProperties2, &setDecoderProperties); - if (setDecoderProperties) - { - const CByteBuffer &props = coderInfo.Props; - size_t size = props.GetCapacity(); - if (size > 0xFFFFFFFF) - return E_NOTIMPL; - if (size > 0) - { - RINOK(setDecoderProperties->SetDecoderProperties2((const Byte *)props, (UInt32)size)); - } - } - } - - #ifdef COMPRESS_MT - if (mtMode) - { - CMyComPtr setCoderMt; - decoder.QueryInterface(IID_ICompressSetCoderMt, &setCoderMt); - if (setCoderMt) - { - RINOK(setCoderMt->SetNumberOfThreads(numThreads)); - } - } - #endif - - #ifndef _NO_CRYPTO - { - CMyComPtr cryptoSetPassword; - decoder.QueryInterface(IID_ICryptoSetPassword, &cryptoSetPassword); - if (cryptoSetPassword) - { - if (getTextPassword == 0) - return E_FAIL; - CMyComBSTR passwordBSTR; - RINOK(getTextPassword->CryptoGetTextPassword(&passwordBSTR)); - CByteBuffer buffer; - passwordIsDefined = true; - const UString password(passwordBSTR); - const UInt32 sizeInBytes = password.Length() * 2; - buffer.SetCapacity(sizeInBytes); - for (int i = 0; i < password.Length(); i++) - { - wchar_t c = password[i]; - ((Byte *)buffer)[i * 2] = (Byte)c; - ((Byte *)buffer)[i * 2 + 1] = (Byte)(c >> 8); - } - RINOK(cryptoSetPassword->CryptoSetPassword((const Byte *)buffer, sizeInBytes)); - } - } - #endif - - coderIndex++; - - UInt32 numInStreams = (UInt32)coderInfo.NumInStreams; - UInt32 numOutStreams = (UInt32)coderInfo.NumOutStreams; - CRecordVector packSizesPointers; - CRecordVector unpackSizesPointers; - packSizesPointers.Reserve(numInStreams); - unpackSizesPointers.Reserve(numOutStreams); - UInt32 j; - for (j = 0; j < numOutStreams; j++, unpackStreamIndex++) - unpackSizesPointers.Add(&folderInfo.UnpackSizes[unpackStreamIndex]); - - for (j = 0; j < numInStreams; j++, packStreamIndex++) - { - int bindPairIndex = folderInfo.FindBindPairForInStream(packStreamIndex); - if (bindPairIndex >= 0) - packSizesPointers.Add( - &folderInfo.UnpackSizes[(UInt32)folderInfo.BindPairs[bindPairIndex].OutIndex]); - else - { - int index = folderInfo.FindPackStreamArrayIndex(packStreamIndex); - if (index < 0) - return E_FAIL; - packSizesPointers.Add(&packSizes[index]); - } - } - - _mixerCoderCommon->SetCoderInfo(i, - &packSizesPointers.Front(), - &unpackSizesPointers.Front()); - } - UInt32 mainCoder, temp; - bindInfo.FindOutStream(bindInfo.OutStreams[0], mainCoder, temp); - - if (_multiThread) - _mixerCoderMTSpec->SetProgressCoderIndex(mainCoder); - /* - else - _mixerCoderSTSpec->SetProgressCoderIndex(mainCoder);; - */ - - if (numCoders == 0) - return 0; - CRecordVector inStreamPointers; - inStreamPointers.Reserve(inStreams.Size()); - for (i = 0; i < inStreams.Size(); i++) - inStreamPointers.Add(inStreams[i]); - ISequentialOutStream *outStreamPointer = outStream; - return _mixerCoder->Code(&inStreamPointers.Front(), NULL, - inStreams.Size(), &outStreamPointer, NULL, 1, compressProgress); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.h deleted file mode 100644 index aa3904a7c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zDecode.h +++ /dev/null @@ -1,68 +0,0 @@ -// 7zDecode.h - -#ifndef __7Z_DECODE_H -#define __7Z_DECODE_H - -#include "../../IStream.h" -#include "../../IPassword.h" - -#include "../Common/CoderMixer2.h" -#include "../Common/CoderMixer2MT.h" -#ifdef _ST_MODE -#include "../Common/CoderMixer2ST.h" -#endif - -#include "../../Common/CreateCoder.h" - -#include "7zItem.h" - -namespace NArchive { -namespace N7z { - -struct CBindInfoEx: public NCoderMixer::CBindInfo -{ - CRecordVector CoderMethodIDs; - void Clear() - { - CBindInfo::Clear(); - CoderMethodIDs.Clear(); - } -}; - -class CDecoder -{ - bool _bindInfoExPrevIsDefined; - CBindInfoEx _bindInfoExPrev; - - bool _multiThread; - #ifdef _ST_MODE - NCoderMixer::CCoderMixer2ST *_mixerCoderSTSpec; - #endif - NCoderMixer::CCoderMixer2MT *_mixerCoderMTSpec; - NCoderMixer::CCoderMixer2 *_mixerCoderCommon; - - CMyComPtr _mixerCoder; - CObjectVector > _decoders; - // CObjectVector > _decoders2; -public: - CDecoder(bool multiThread); - HRESULT Decode( - DECL_EXTERNAL_CODECS_LOC_VARS - IInStream *inStream, - UInt64 startPos, - const UInt64 *packSizes, - const CFolder &folder, - ISequentialOutStream *outStream, - ICompressProgressInfo *compressProgress - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPasswordSpec, bool &passwordIsDefined - #endif - #ifdef COMPRESS_MT - , bool mtMode, UInt32 numThreads - #endif - ); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zExtract.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zExtract.cpp deleted file mode 100644 index dbc1aa522..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zExtract.cpp +++ /dev/null @@ -1,273 +0,0 @@ -// 7zExtract.cpp - -#include "StdAfx.h" - -#include "7zHandler.h" -#include "7zFolderOutStream.h" -#include "7zDecode.h" -// #include "7z1Decode.h" - -#include "../../../Common/ComTry.h" -#include "../../Common/StreamObjects.h" -#include "../../Common/ProgressUtils.h" -#include "../../Common/LimitedStreams.h" - -namespace NArchive { -namespace N7z { - -struct CExtractFolderInfo -{ - #ifdef _7Z_VOL - int VolumeIndex; - #endif - CNum FileIndex; - CNum FolderIndex; - CBoolVector ExtractStatuses; - UInt64 UnpackSize; - CExtractFolderInfo( - #ifdef _7Z_VOL - int volumeIndex, - #endif - CNum fileIndex, CNum folderIndex): - #ifdef _7Z_VOL - VolumeIndex(volumeIndex), - #endif - FileIndex(fileIndex), - FolderIndex(folderIndex), - UnpackSize(0) - { - if (fileIndex != kNumNoIndex) - { - ExtractStatuses.Reserve(1); - ExtractStatuses.Add(true); - } - }; -}; - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 testModeSpec, IArchiveExtractCallback *extractCallbackSpec) -{ - COM_TRY_BEGIN - bool testMode = (testModeSpec != 0); - CMyComPtr extractCallback = extractCallbackSpec; - UInt64 importantTotalUnpacked = 0; - - bool allFilesMode = (numItems == UInt32(-1)); - if (allFilesMode) - numItems = - #ifdef _7Z_VOL - _refs.Size(); - #else - _db.Files.Size(); - #endif - - if(numItems == 0) - return S_OK; - - /* - if(_volumes.Size() != 1) - return E_FAIL; - const CVolume &volume = _volumes.Front(); - const CArchiveDatabaseEx &_db = volume.Database; - IInStream *_inStream = volume.Stream; - */ - - CObjectVector extractFolderInfoVector; - for(UInt32 ii = 0; ii < numItems; ii++) - { - // UInt32 fileIndex = allFilesMode ? indexIndex : indices[indexIndex]; - UInt32 ref2Index = allFilesMode ? ii : indices[ii]; - // const CRef2 &ref2 = _refs[ref2Index]; - - // for(UInt32 ri = 0; ri < ref2.Refs.Size(); ri++) - { - #ifdef _7Z_VOL - // const CRef &ref = ref2.Refs[ri]; - const CRef &ref = _refs[ref2Index]; - - int volumeIndex = ref.VolumeIndex; - const CVolume &volume = _volumes[volumeIndex]; - const CArchiveDatabaseEx &db = volume.Database; - UInt32 fileIndex = ref.ItemIndex; - #else - const CArchiveDatabaseEx &db = _db; - UInt32 fileIndex = ref2Index; - #endif - - CNum folderIndex = db.FileIndexToFolderIndexMap[fileIndex]; - if (folderIndex == kNumNoIndex) - { - extractFolderInfoVector.Add(CExtractFolderInfo( - #ifdef _7Z_VOL - volumeIndex, - #endif - fileIndex, kNumNoIndex)); - continue; - } - if (extractFolderInfoVector.IsEmpty() || - folderIndex != extractFolderInfoVector.Back().FolderIndex - #ifdef _7Z_VOL - || volumeIndex != extractFolderInfoVector.Back().VolumeIndex - #endif - ) - { - extractFolderInfoVector.Add(CExtractFolderInfo( - #ifdef _7Z_VOL - volumeIndex, - #endif - kNumNoIndex, folderIndex)); - const CFolder &folderInfo = db.Folders[folderIndex]; - UInt64 unpackSize = folderInfo.GetUnpackSize(); - importantTotalUnpacked += unpackSize; - extractFolderInfoVector.Back().UnpackSize = unpackSize; - } - - CExtractFolderInfo &efi = extractFolderInfoVector.Back(); - - // const CFolderInfo &folderInfo = m_dam_Folders[folderIndex]; - CNum startIndex = db.FolderStartFileIndex[folderIndex]; - for (CNum index = efi.ExtractStatuses.Size(); - index <= fileIndex - startIndex; index++) - { - // UInt64 unpackSize = _db.Files[startIndex + index].UnpackSize; - // Count partial_folder_size - // efi.UnpackSize += unpackSize; - // importantTotalUnpacked += unpackSize; - efi.ExtractStatuses.Add(index == fileIndex - startIndex); - } - } - } - - extractCallback->SetTotal(importantTotalUnpacked); - - CDecoder decoder( - #ifdef _ST_MODE - false - #else - true - #endif - ); - // CDecoder1 decoder; - - UInt64 currentTotalPacked = 0; - UInt64 currentTotalUnpacked = 0; - UInt64 totalFolderUnpacked; - UInt64 totalFolderPacked; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - for(int i = 0; i < extractFolderInfoVector.Size(); i++, - currentTotalUnpacked += totalFolderUnpacked, - currentTotalPacked += totalFolderPacked) - { - lps->OutSize = currentTotalUnpacked; - lps->InSize = currentTotalPacked; - RINOK(lps->SetCur()); - - const CExtractFolderInfo &efi = extractFolderInfoVector[i]; - totalFolderUnpacked = efi.UnpackSize; - - totalFolderPacked = 0; - - CFolderOutStream *folderOutStream = new CFolderOutStream; - CMyComPtr outStream(folderOutStream); - - #ifdef _7Z_VOL - const CVolume &volume = _volumes[efi.VolumeIndex]; - const CArchiveDatabaseEx &db = volume.Database; - #else - const CArchiveDatabaseEx &db = _db; - #endif - - CNum startIndex; - if (efi.FileIndex != kNumNoIndex) - startIndex = efi.FileIndex; - else - startIndex = db.FolderStartFileIndex[efi.FolderIndex]; - - - HRESULT result = folderOutStream->Init(&db, - #ifdef _7Z_VOL - volume.StartRef2Index, - #else - 0, - #endif - startIndex, - &efi.ExtractStatuses, extractCallback, testMode, _crcSize != 0); - - RINOK(result); - - if (efi.FileIndex != kNumNoIndex) - continue; - - CNum folderIndex = efi.FolderIndex; - const CFolder &folderInfo = db.Folders[folderIndex]; - - totalFolderPacked = _db.GetFolderFullPackSize(folderIndex); - - CNum packStreamIndex = db.FolderStartPackStreamIndex[folderIndex]; - UInt64 folderStartPackPos = db.GetFolderStreamPos(folderIndex, 0); - - #ifndef _NO_CRYPTO - CMyComPtr getTextPassword; - if (extractCallback) - extractCallback.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword); - #endif - - try - { - #ifndef _NO_CRYPTO - bool passwordIsDefined; - #endif - - HRESULT result = decoder.Decode( - EXTERNAL_CODECS_VARS - #ifdef _7Z_VOL - volume.Stream, - #else - _inStream, - #endif - folderStartPackPos, - &db.PackSizes[packStreamIndex], - folderInfo, - outStream, - progress - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - #ifdef COMPRESS_MT - , true, _numThreads - #endif - ); - - if (result == S_FALSE) - { - RINOK(folderOutStream->FlushCorrupted(NArchive::NExtract::NOperationResult::kDataError)); - continue; - } - if (result == E_NOTIMPL) - { - RINOK(folderOutStream->FlushCorrupted(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - continue; - } - if (result != S_OK) - return result; - if (folderOutStream->WasWritingFinished() != S_OK) - { - RINOK(folderOutStream->FlushCorrupted(NArchive::NExtract::NOperationResult::kDataError)); - continue; - } - } - catch(...) - { - RINOK(folderOutStream->FlushCorrupted(NArchive::NExtract::NOperationResult::kDataError)); - continue; - } - } - return S_OK; - COM_TRY_END -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.cpp deleted file mode 100644 index 3b11f1686..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.cpp +++ /dev/null @@ -1,130 +0,0 @@ -// 7zFolderInStream.cpp - -#include "StdAfx.h" - -#include "7zFolderInStream.h" - -namespace NArchive { -namespace N7z { - -CFolderInStream::CFolderInStream() -{ - _inStreamWithHashSpec = new CSequentialInStreamWithCRC; - _inStreamWithHash = _inStreamWithHashSpec; -} - -void CFolderInStream::Init(IArchiveUpdateCallback *updateCallback, - const UInt32 *fileIndices, UInt32 numFiles) -{ - _updateCallback = updateCallback; - _numFiles = numFiles; - _fileIndex = 0; - _fileIndices = fileIndices; - Processed.Clear(); - CRCs.Clear(); - Sizes.Clear(); - _fileIsOpen = false; - _currentSizeIsDefined = false; -} - -HRESULT CFolderInStream::OpenStream() -{ - _filePos = 0; - while (_fileIndex < _numFiles) - { - _currentSizeIsDefined = false; - CMyComPtr stream; - HRESULT result = _updateCallback->GetStream(_fileIndices[_fileIndex], &stream); - if (result != S_OK && result != S_FALSE) - return result; - _fileIndex++; - _inStreamWithHashSpec->SetStream(stream); - _inStreamWithHashSpec->Init(); - if (!stream) - { - RINOK(_updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); - Sizes.Add(0); - Processed.Add(result == S_OK); - AddDigest(); - continue; - } - CMyComPtr streamGetSize; - if (stream.QueryInterface(IID_IStreamGetSize, &streamGetSize) == S_OK) - { - if(streamGetSize) - { - _currentSizeIsDefined = true; - RINOK(streamGetSize->GetSize(&_currentSize)); - } - } - - _fileIsOpen = true; - return S_OK; - } - return S_OK; -} - -void CFolderInStream::AddDigest() -{ - CRCs.Add(_inStreamWithHashSpec->GetCRC()); -} - -HRESULT CFolderInStream::CloseStream() -{ - RINOK(_updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK)); - _inStreamWithHashSpec->ReleaseStream(); - _fileIsOpen = false; - Processed.Add(true); - Sizes.Add(_filePos); - AddDigest(); - return S_OK; -} - -STDMETHODIMP CFolderInStream::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize = 0; - while ((_fileIndex < _numFiles || _fileIsOpen) && size > 0) - { - if (_fileIsOpen) - { - UInt32 localProcessedSize; - RINOK(_inStreamWithHash->Read( - ((Byte *)data) + realProcessedSize, size, &localProcessedSize)); - if (localProcessedSize == 0) - { - RINOK(CloseStream()); - continue; - } - realProcessedSize += localProcessedSize; - _filePos += localProcessedSize; - size -= localProcessedSize; - break; - } - else - { - RINOK(OpenStream()); - } - } - if (processedSize != 0) - *processedSize = realProcessedSize; - return S_OK; -} - -STDMETHODIMP CFolderInStream::GetSubStreamSize(UInt64 subStream, UInt64 *value) -{ - *value = 0; - int subStreamIndex = (int)subStream; - if (subStreamIndex < 0 || subStream > Sizes.Size()) - return E_FAIL; - if (subStreamIndex < Sizes.Size()) - { - *value= Sizes[subStreamIndex]; - return S_OK; - } - if (!_currentSizeIsDefined) - return S_FALSE; - *value = _currentSize; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.h deleted file mode 100644 index b4df6d62a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderInStream.h +++ /dev/null @@ -1,66 +0,0 @@ -// 7z/FolderInStream.h - -#ifndef __7Z_FOLDERINSTREAM_H -#define __7Z_FOLDERINSTREAM_H - -#include "7zItem.h" -#include "7zHeader.h" - -#include "../IArchive.h" -#include "../Common/InStreamWithCRC.h" -#include "../../IStream.h" -#include "../../ICoder.h" - -namespace NArchive { -namespace N7z { - -class CFolderInStream: - public ISequentialInStream, - public ICompressGetSubStreamSize, - public CMyUnknownImp -{ -public: - - MY_UNKNOWN_IMP1(ICompressGetSubStreamSize) - - CFolderInStream(); - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - - STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value); -private: - CSequentialInStreamWithCRC *_inStreamWithHashSpec; - CMyComPtr _inStreamWithHash; - CMyComPtr _updateCallback; - - bool _currentSizeIsDefined; - UInt64 _currentSize; - - bool _fileIsOpen; - UInt64 _filePos; - - const UInt32 *_fileIndices; - UInt32 _numFiles; - UInt32 _fileIndex; - - HRESULT OpenStream(); - HRESULT CloseStream(); - void AddDigest(); -public: - void Init(IArchiveUpdateCallback *updateCallback, - const UInt32 *fileIndices, UInt32 numFiles); - CRecordVector Processed; - CRecordVector CRCs; - CRecordVector Sizes; - UInt64 GetFullSize() const - { - UInt64 size = 0; - for (int i = 0; i < Sizes.Size(); i++) - size += Sizes[i]; - return size; - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.cpp deleted file mode 100644 index d3a79ee13..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.cpp +++ /dev/null @@ -1,164 +0,0 @@ -// 7zFolderOutStream.cpp - -#include "StdAfx.h" - -#include "7zFolderOutStream.h" - -namespace NArchive { -namespace N7z { - -CFolderOutStream::CFolderOutStream() -{ - _outStreamWithHashSpec = new COutStreamWithCRC; - _outStreamWithHash = _outStreamWithHashSpec; -} - -HRESULT CFolderOutStream::Init( - const CArchiveDatabaseEx *archiveDatabase, - UInt32 ref2Offset, - UInt32 startIndex, - const CBoolVector *extractStatuses, - IArchiveExtractCallback *extractCallback, - bool testMode, - bool checkCrc) -{ - _archiveDatabase = archiveDatabase; - _ref2Offset = ref2Offset; - _startIndex = startIndex; - - _extractStatuses = extractStatuses; - _extractCallback = extractCallback; - _testMode = testMode; - - _checkCrc = checkCrc; - - _currentIndex = 0; - _fileIsOpen = false; - return WriteEmptyFiles(); -} - -HRESULT CFolderOutStream::OpenFile() -{ - Int32 askMode; - if((*_extractStatuses)[_currentIndex]) - askMode = _testMode ? - NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - else - askMode = NArchive::NExtract::NAskMode::kSkip; - CMyComPtr realOutStream; - - UInt32 index = _startIndex + _currentIndex; - RINOK(_extractCallback->GetStream(_ref2Offset + index, &realOutStream, askMode)); - - _outStreamWithHashSpec->SetStream(realOutStream); - _outStreamWithHashSpec->Init(_checkCrc); - if (askMode == NArchive::NExtract::NAskMode::kExtract && - (!realOutStream)) - { - const CFileItem &fi = _archiveDatabase->Files[index]; - if (!_archiveDatabase->IsItemAnti(index) && !fi.IsDir) - askMode = NArchive::NExtract::NAskMode::kSkip; - } - return _extractCallback->PrepareOperation(askMode); -} - -HRESULT CFolderOutStream::WriteEmptyFiles() -{ - for(;_currentIndex < _extractStatuses->Size(); _currentIndex++) - { - UInt32 index = _startIndex + _currentIndex; - const CFileItem &fi = _archiveDatabase->Files[index]; - if (!_archiveDatabase->IsItemAnti(index) && !fi.IsDir && fi.Size != 0) - return S_OK; - RINOK(OpenFile()); - RINOK(_extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK)); - _outStreamWithHashSpec->ReleaseStream(); - } - return S_OK; -} - -STDMETHODIMP CFolderOutStream::Write(const void *data, - UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize = 0; - while(_currentIndex < _extractStatuses->Size()) - { - if (_fileIsOpen) - { - UInt32 index = _startIndex + _currentIndex; - const CFileItem &fi = _archiveDatabase->Files[index]; - UInt64 fileSize = fi.Size; - - UInt32 numBytesToWrite = (UInt32)MyMin(fileSize - _filePos, - UInt64(size - realProcessedSize)); - - UInt32 processedSizeLocal; - RINOK(_outStreamWithHash->Write((const Byte *)data + realProcessedSize, - numBytesToWrite, &processedSizeLocal)); - - _filePos += processedSizeLocal; - realProcessedSize += processedSizeLocal; - if (_filePos == fileSize) - { - bool digestsAreEqual; - if (fi.CrcDefined && _checkCrc) - digestsAreEqual = fi.Crc == _outStreamWithHashSpec->GetCRC(); - else - digestsAreEqual = true; - - RINOK(_extractCallback->SetOperationResult( - digestsAreEqual ? - NArchive::NExtract::NOperationResult::kOK : - NArchive::NExtract::NOperationResult::kCRCError)); - _outStreamWithHashSpec->ReleaseStream(); - _fileIsOpen = false; - _currentIndex++; - } - if (realProcessedSize == size) - { - if (processedSize != NULL) - *processedSize = realProcessedSize; - return WriteEmptyFiles(); - } - } - else - { - RINOK(OpenFile()); - _fileIsOpen = true; - _filePos = 0; - } - } - if (processedSize != NULL) - *processedSize = size; - return S_OK; -} - -HRESULT CFolderOutStream::FlushCorrupted(Int32 resultEOperationResult) -{ - while(_currentIndex < _extractStatuses->Size()) - { - if (_fileIsOpen) - { - RINOK(_extractCallback->SetOperationResult(resultEOperationResult)); - _outStreamWithHashSpec->ReleaseStream(); - _fileIsOpen = false; - _currentIndex++; - } - else - { - RINOK(OpenFile()); - _fileIsOpen = true; - } - } - return S_OK; -} - -HRESULT CFolderOutStream::WasWritingFinished() -{ - if (_currentIndex == _extractStatuses->Size()) - return S_OK; - return E_FAIL; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.h deleted file mode 100644 index d88cde985..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zFolderOutStream.h +++ /dev/null @@ -1,60 +0,0 @@ -// 7zFolderOutStream.h - -#ifndef __7Z_FOLDEROUTSTREAM_H -#define __7Z_FOLDEROUTSTREAM_H - -#include "7zIn.h" - -#include "../../IStream.h" -#include "../IArchive.h" -#include "../Common/OutStreamWithCRC.h" - -namespace NArchive { -namespace N7z { - -class CFolderOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - CFolderOutStream(); - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -private: - - COutStreamWithCRC *_outStreamWithHashSpec; - CMyComPtr _outStreamWithHash; - const CArchiveDatabaseEx *_archiveDatabase; - const CBoolVector *_extractStatuses; - UInt32 _startIndex; - UInt32 _ref2Offset; - int _currentIndex; - // UInt64 _currentDataPos; - CMyComPtr _extractCallback; - bool _testMode; - - bool _fileIsOpen; - - bool _checkCrc; - UInt64 _filePos; - - HRESULT OpenFile(); - HRESULT WriteEmptyFiles(); -public: - HRESULT Init( - const CArchiveDatabaseEx *archiveDatabase, - UInt32 ref2Offset, - UInt32 startIndex, - const CBoolVector *extractStatuses, - IArchiveExtractCallback *extractCallback, - bool testMode, - bool checkCrc); - HRESULT FlushCorrupted(Int32 resultEOperationResult); - HRESULT WasWritingFinished(); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.cpp deleted file mode 100644 index c76a106f8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.cpp +++ /dev/null @@ -1,503 +0,0 @@ -// 7zHandler.cpp - -#include "StdAfx.h" - -extern "C" -{ - #include "../../../../C/CpuArch.h" -} - -#include "../../../Common/ComTry.h" -#include "../../../Common/IntToString.h" - -#ifdef COMPRESS_MT -#include "../../../Windows/System.h" -#endif - -#include "../Common/ItemNameUtils.h" - -#include "7zHandler.h" -#include "7zProperties.h" - -#ifdef __7Z_SET_PROPERTIES -#ifdef EXTRACT_ONLY -#include "../Common/ParseProperties.h" -#endif -#endif - -using namespace NWindows; - -extern UString ConvertMethodIdToString(UInt64 id); - -namespace NArchive { -namespace N7z { - -CHandler::CHandler() -{ - _crcSize = 4; - - #ifndef _NO_CRYPTO - _passwordIsDefined = false; - #endif - - #ifdef EXTRACT_ONLY - #ifdef COMPRESS_MT - _numThreads = NSystem::GetNumberOfProcessors(); - #endif - #else - Init(); - #endif -} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = _db.Files.Size(); - return S_OK; -} - -#ifdef _SFX - -IMP_IInArchive_ArcProps_NO - -STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 * /* numProperties */) -{ - return E_NOTIMPL; -} - -STDMETHODIMP CHandler::GetPropertyInfo(UInt32 /* index */, - BSTR * /* name */, PROPID * /* propID */, VARTYPE * /* varType */) -{ - return E_NOTIMPL; -} - - -#else - -STATPROPSTG kArcProps[] = -{ - { NULL, kpidMethod, VT_BSTR}, - { NULL, kpidSolid, VT_BOOL}, - { NULL, kpidNumBlocks, VT_UI4}, - { NULL, kpidPhySize, VT_UI8}, - { NULL, kpidHeadersSize, VT_UI8}, - { NULL, kpidOffset, VT_UI8} -}; - -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NCOM::CPropVariant prop; - switch(propID) - { - case kpidMethod: - { - UString resString; - CRecordVector ids; - int i; - for (i = 0; i < _db.Folders.Size(); i++) - { - const CFolder &f = _db.Folders[i]; - for (int j = f.Coders.Size() - 1; j >= 0; j--) - ids.AddToUniqueSorted(f.Coders[j].MethodID); - } - - for (i = 0; i < ids.Size(); i++) - { - UInt64 id = ids[i]; - UString methodName; - /* bool methodIsKnown = */ FindMethod(EXTERNAL_CODECS_VARS id, methodName); - if (methodName.IsEmpty()) - methodName = ConvertMethodIdToString(id); - if (!resString.IsEmpty()) - resString += L' '; - resString += methodName; - } - prop = resString; - break; - } - case kpidSolid: prop = _db.IsSolid(); break; - case kpidNumBlocks: prop = (UInt32)_db.Folders.Size(); break; - case kpidHeadersSize: prop = _db.HeadersSize; break; - case kpidPhySize: prop = _db.PhySize; break; - case kpidOffset: if (_db.ArchiveInfo.StartPosition != 0) prop = _db.ArchiveInfo.StartPosition; break; - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -IMP_IInArchive_ArcProps - -#endif - -static void SetPropFromUInt64Def(CUInt64DefVector &v, int index, NCOM::CPropVariant &prop) -{ - UInt64 value; - if (v.GetItem(index, value)) - { - FILETIME ft; - ft.dwLowDateTime = (DWORD)value; - ft.dwHighDateTime = (DWORD)(value >> 32); - prop = ft; - } -} - -#ifndef _SFX - -static UString ConvertUInt32ToString(UInt32 value) -{ - wchar_t buffer[32]; - ConvertUInt64ToString(value, buffer); - return buffer; -} - -static UString GetStringForSizeValue(UInt32 value) -{ - for (int i = 31; i >= 0; i--) - if ((UInt32(1) << i) == value) - return ConvertUInt32ToString(i); - UString result; - if (value % (1 << 20) == 0) - { - result += ConvertUInt32ToString(value >> 20); - result += L"m"; - } - else if (value % (1 << 10) == 0) - { - result += ConvertUInt32ToString(value >> 10); - result += L"k"; - } - else - { - result += ConvertUInt32ToString(value); - result += L"b"; - } - return result; -} - -static const UInt64 k_Copy = 0x0; -static const UInt64 k_LZMA = 0x030101; -static const UInt64 k_PPMD = 0x030401; - -static wchar_t GetHex(Byte value) -{ - return (wchar_t)((value < 10) ? (L'0' + value) : (L'A' + (value - 10))); -} -static inline UString GetHex2(Byte value) -{ - UString result; - result += GetHex((Byte)(value >> 4)); - result += GetHex((Byte)(value & 0xF)); - return result; -} - -#endif - -static const UInt64 k_AES = 0x06F10701; - -bool CHandler::IsEncrypted(UInt32 index2) const -{ - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; - if (folderIndex != kNumNoIndex) - { - const CFolder &folderInfo = _db.Folders[folderIndex]; - for (int i = folderInfo.Coders.Size() - 1; i >= 0; i--) - if (folderInfo.Coders[i].MethodID == k_AES) - return true; - } - return false; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NCOM::CPropVariant prop; - - /* - const CRef2 &ref2 = _refs[index]; - if (ref2.Refs.IsEmpty()) - return E_FAIL; - const CRef &ref = ref2.Refs.Front(); - */ - - const CFileItem &item = _db.Files[index]; - UInt32 index2 = index; - - switch(propID) - { - case kpidPath: - if (!item.Name.IsEmpty()) - prop = NItemName::GetOSName(item.Name); - break; - case kpidIsDir: prop = item.IsDir; break; - case kpidSize: - { - prop = item.Size; - // prop = ref2.Size; - break; - } - case kpidPackSize: - { - // prop = ref2.PackSize; - { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; - if (folderIndex != kNumNoIndex) - { - if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2) - prop = _db.GetFolderFullPackSize(folderIndex); - /* - else - prop = (UInt64)0; - */ - } - else - prop = (UInt64)0; - } - break; - } - case kpidPosition: { UInt64 v; if (_db.StartPos.GetItem(index2, v)) prop = v; break; } - case kpidCTime: SetPropFromUInt64Def(_db.CTime, index2, prop); break; - case kpidATime: SetPropFromUInt64Def(_db.ATime, index2, prop); break; - case kpidMTime: SetPropFromUInt64Def(_db.MTime, index2, prop); break; - case kpidAttrib: if (item.AttribDefined) prop = item.Attrib; break; - case kpidCRC: if (item.CrcDefined) prop = item.Crc; break; - case kpidEncrypted: prop = IsEncrypted(index2); break; - case kpidIsAnti: prop = _db.IsItemAnti(index2); break; - #ifndef _SFX - case kpidMethod: - { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; - if (folderIndex != kNumNoIndex) - { - const CFolder &folderInfo = _db.Folders[folderIndex]; - UString methodsString; - for (int i = folderInfo.Coders.Size() - 1; i >= 0; i--) - { - const CCoderInfo &coderInfo = folderInfo.Coders[i]; - if (!methodsString.IsEmpty()) - methodsString += L' '; - - { - UString methodName; - bool methodIsKnown = FindMethod( - EXTERNAL_CODECS_VARS - coderInfo.MethodID, methodName); - - if (methodIsKnown) - { - methodsString += methodName; - if (coderInfo.MethodID == k_LZMA) - { - if (coderInfo.Props.GetCapacity() >= 5) - { - methodsString += L":"; - UInt32 dicSize = GetUi32((const Byte *)coderInfo.Props + 1); - methodsString += GetStringForSizeValue(dicSize); - } - } - else if (coderInfo.MethodID == k_PPMD) - { - if (coderInfo.Props.GetCapacity() >= 5) - { - Byte order = *(const Byte *)coderInfo.Props; - methodsString += L":o"; - methodsString += ConvertUInt32ToString(order); - methodsString += L":mem"; - UInt32 dicSize = GetUi32((const Byte *)coderInfo.Props + 1); - methodsString += GetStringForSizeValue(dicSize); - } - } - else if (coderInfo.MethodID == k_AES) - { - if (coderInfo.Props.GetCapacity() >= 1) - { - methodsString += L":"; - const Byte *data = (const Byte *)coderInfo.Props; - Byte firstByte = *data++; - UInt32 numCyclesPower = firstByte & 0x3F; - methodsString += ConvertUInt32ToString(numCyclesPower); - /* - if ((firstByte & 0xC0) != 0) - { - methodsString += L":"; - return S_OK; - UInt32 saltSize = (firstByte >> 7) & 1; - UInt32 ivSize = (firstByte >> 6) & 1; - if (coderInfo.Props.GetCapacity() >= 2) - { - Byte secondByte = *data++; - saltSize += (secondByte >> 4); - ivSize += (secondByte & 0x0F); - } - } - */ - } - } - else - { - if (coderInfo.Props.GetCapacity() > 0) - { - methodsString += L":["; - for (size_t bi = 0; bi < coderInfo.Props.GetCapacity(); bi++) - { - if (bi > 5 && bi + 1 < coderInfo.Props.GetCapacity()) - { - methodsString += L".."; - break; - } - else - methodsString += GetHex2(coderInfo.Props[bi]); - } - methodsString += L"]"; - } - } - } - else - { - methodsString += ConvertMethodIdToString(coderInfo.MethodID); - } - } - } - prop = methodsString; - } - } - break; - case kpidBlock: - { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; - if (folderIndex != kNumNoIndex) - prop = (UInt32)folderIndex; - } - break; - case kpidPackedSize0: - case kpidPackedSize1: - case kpidPackedSize2: - case kpidPackedSize3: - case kpidPackedSize4: - { - CNum folderIndex = _db.FileIndexToFolderIndexMap[index2]; - if (folderIndex != kNumNoIndex) - { - const CFolder &folderInfo = _db.Folders[folderIndex]; - if (_db.FolderStartFileIndex[folderIndex] == (CNum)index2 && - folderInfo.PackStreams.Size() > (int)(propID - kpidPackedSize0)) - { - prop = _db.GetFolderPackStreamSize(folderIndex, propID - kpidPackedSize0); - } - else - prop = (UInt64)0; - } - else - prop = (UInt64)0; - } - break; - #endif - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openArchiveCallback) -{ - COM_TRY_BEGIN - Close(); - #ifndef _SFX - _fileInfoPopIDs.Clear(); - #endif - try - { - CMyComPtr openArchiveCallbackTemp = openArchiveCallback; - - #ifndef _NO_CRYPTO - CMyComPtr getTextPassword; - if (openArchiveCallback) - { - openArchiveCallbackTemp.QueryInterface( - IID_ICryptoGetTextPassword, &getTextPassword); - } - #endif - CInArchive archive; - RINOK(archive.Open(stream, maxCheckStartPosition)); - #ifndef _NO_CRYPTO - _passwordIsDefined = false; - UString password; - #endif - HRESULT result = archive.ReadDatabase( - EXTERNAL_CODECS_VARS - _db - #ifndef _NO_CRYPTO - , getTextPassword, _passwordIsDefined - #endif - ); - RINOK(result); - _db.Fill(); - _inStream = stream; - } - catch(...) - { - Close(); - return S_FALSE; - } - // _inStream = stream; - #ifndef _SFX - FillPopIDs(); - #endif - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - COM_TRY_BEGIN - _inStream.Release(); - _db.Clear(); - return S_OK; - COM_TRY_END -} - -#ifdef __7Z_SET_PROPERTIES -#ifdef EXTRACT_ONLY - -STDMETHODIMP CHandler::SetProperties(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties) -{ - COM_TRY_BEGIN - #ifdef COMPRESS_MT - const UInt32 numProcessors = NSystem::GetNumberOfProcessors(); - _numThreads = numProcessors; - #endif - - for (int i = 0; i < numProperties; i++) - { - UString name = names[i]; - name.MakeUpper(); - if (name.IsEmpty()) - return E_INVALIDARG; - const PROPVARIANT &value = values[i]; - UInt32 number; - int index = ParseStringToUInt32(name, number); - if (index == 0) - { - if(name.Left(2).CompareNoCase(L"MT") == 0) - { - #ifdef COMPRESS_MT - RINOK(ParseMtProp(name.Mid(2), value, numProcessors, _numThreads)); - #endif - continue; - } - else - return E_INVALIDARG; - } - } - return S_OK; - COM_TRY_END -} - -#endif -#endif - -IMPL_ISetCompressCodecsInfo - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.h deleted file mode 100644 index c04a0f931..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHandler.h +++ /dev/null @@ -1,121 +0,0 @@ -// 7z/Handler.h - -#ifndef __7Z_HANDLER_H -#define __7Z_HANDLER_H - -#include "../../ICoder.h" -#include "../IArchive.h" -#include "7zIn.h" - -#include "7zCompressionMode.h" - -#include "../../Common/CreateCoder.h" - -#ifndef EXTRACT_ONLY -#include "../Common/HandlerOut.h" -#endif - -namespace NArchive { -namespace N7z { - -#ifndef __7Z_SET_PROPERTIES - -#ifdef EXTRACT_ONLY -#ifdef COMPRESS_MT -#define __7Z_SET_PROPERTIES -#endif -#else -#define __7Z_SET_PROPERTIES -#endif - -#endif - - -class CHandler: - #ifndef EXTRACT_ONLY - public NArchive::COutHandler, - #endif - public IInArchive, - #ifdef __7Z_SET_PROPERTIES - public ISetProperties, - #endif - #ifndef EXTRACT_ONLY - public IOutArchive, - #endif - PUBLIC_ISetCompressCodecsInfo - public CMyUnknownImp -{ -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - #ifdef __7Z_SET_PROPERTIES - MY_QUERYINTERFACE_ENTRY(ISetProperties) - #endif - #ifndef EXTRACT_ONLY - MY_QUERYINTERFACE_ENTRY(IOutArchive) - #endif - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) - - #ifdef __7Z_SET_PROPERTIES - STDMETHOD(SetProperties)(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties); - #endif - - #ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(;) - #endif - - DECL_ISetCompressCodecsInfo - - CHandler(); - -private: - CMyComPtr _inStream; - NArchive::N7z::CArchiveDatabaseEx _db; - #ifndef _NO_CRYPTO - bool _passwordIsDefined; - #endif - - #ifdef EXTRACT_ONLY - - #ifdef COMPRESS_MT - UInt32 _numThreads; - #endif - - UInt32 _crcSize; - - #else - - CRecordVector _binds; - - HRESULT SetPassword(CCompressionMethodMode &methodMode, IArchiveUpdateCallback *updateCallback); - - HRESULT SetCompressionMethod(CCompressionMethodMode &method, - CObjectVector &methodsInfo - #ifdef COMPRESS_MT - , UInt32 numThreads - #endif - ); - - HRESULT SetCompressionMethod( - CCompressionMethodMode &method, - CCompressionMethodMode &headerMethod); - - #endif - - bool IsEncrypted(UInt32 index2) const; - #ifndef _SFX - - CRecordVector _fileInfoPopIDs; - void FillPopIDs(); - - #endif - - DECL_EXTERNAL_CODECS_VARS -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.cpp deleted file mode 100644 index c010f3671..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// 7z/Header.cpp - -#include "StdAfx.h" -#include "7zHeader.h" - -namespace NArchive { -namespace N7z { - -Byte kSignature[kSignatureSize] = {'7' + 1, 'z', 0xBC, 0xAF, 0x27, 0x1C}; -#ifdef _7Z_VOL -Byte kFinishSignature[kSignatureSize] = {'7' + 1, 'z', 0xBC, 0xAF, 0x27, 0x1C + 1}; -#endif - -class SignatureInitializer -{ -public: - SignatureInitializer() - { - kSignature[0]--; - #ifdef _7Z_VOL - kFinishSignature[0]--; - #endif - }; -} g_SignatureInitializer; - -}} - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.h deleted file mode 100644 index 57f455b81..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zHeader.h +++ /dev/null @@ -1,97 +0,0 @@ -// 7z/7zHeader.h - -#ifndef __7Z_HEADER_H -#define __7Z_HEADER_H - -#include "../../../Common/Types.h" - -namespace NArchive { -namespace N7z { - -const int kSignatureSize = 6; -extern Byte kSignature[kSignatureSize]; - -// #define _7Z_VOL -// 7z-MultiVolume is not finished yet. -// It can work already, but I still do not like some -// things of that new multivolume format. -// So please keep it commented. - -#ifdef _7Z_VOL -extern Byte kFinishSignature[kSignatureSize]; -#endif - -struct CArchiveVersion -{ - Byte Major; - Byte Minor; -}; - -const Byte kMajorVersion = 0; - -struct CStartHeader -{ - UInt64 NextHeaderOffset; - UInt64 NextHeaderSize; - UInt32 NextHeaderCRC; -}; - -const UInt32 kStartHeaderSize = 20; - -#ifdef _7Z_VOL -struct CFinishHeader: public CStartHeader -{ - UInt64 ArchiveStartOffset; // data offset from end if that struct - UInt64 AdditionalStartBlockSize; // start signature & start header size -}; - -const UInt32 kFinishHeaderSize = kStartHeaderSize + 16; -#endif - -namespace NID -{ - enum EEnum - { - kEnd, - - kHeader, - - kArchiveProperties, - - kAdditionalStreamsInfo, - kMainStreamsInfo, - kFilesInfo, - - kPackInfo, - kUnpackInfo, - kSubStreamsInfo, - - kSize, - kCRC, - - kFolder, - - kCodersUnpackSize, - kNumUnpackStream, - - kEmptyStream, - kEmptyFile, - kAnti, - - kName, - kCTime, - kATime, - kMTime, - kWinAttributes, - kComment, - - kEncodedHeader, - - kStartPos, - kDummy - }; -} - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.cpp deleted file mode 100644 index a9fecf8e1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.cpp +++ /dev/null @@ -1,1260 +0,0 @@ -// 7zIn.cpp - -#include "StdAfx.h" - -extern "C" -{ - #include "../../../../C/7zCrc.h" - #include "../../../../C/CpuArch.h" -} - -#include "../../Common/StreamObjects.h" -#include "../../Common/StreamUtils.h" - -#include "7zDecode.h" -#include "7zIn.h" - -#define Get16(p) GetUi16(p) -#define Get32(p) GetUi32(p) -#define Get64(p) GetUi64(p) - -// define FORMAT_7Z_RECOVERY if you want to recover multivolume archives with empty StartHeader -#ifndef _SFX -#define FORMAT_7Z_RECOVERY -#endif - -namespace NArchive { -namespace N7z { - -static void BoolVector_Fill_False(CBoolVector &v, int size) -{ - v.Clear(); - v.Reserve(size); - for (int i = 0; i < size; i++) - v.Add(false); -} - -static bool BoolVector_GetAndSet(CBoolVector &v, UInt32 index) -{ - if (index >= (UInt32)v.Size()) - return true; - bool res = v[index]; - v[index] = true; - return res; -} - -bool CFolder::CheckStructure() const -{ - const int kNumCodersMax = sizeof(UInt32) * 8; // don't change it - const int kMaskSize = sizeof(UInt32) * 8; // it must be >= kNumCodersMax - const int kNumBindsMax = 32; - - if (Coders.Size() > kNumCodersMax || BindPairs.Size() > kNumBindsMax) - return false; - - { - CBoolVector v; - BoolVector_Fill_False(v, BindPairs.Size() + PackStreams.Size()); - - int i; - for (i = 0; i < BindPairs.Size(); i++) - if (BoolVector_GetAndSet(v, BindPairs[i].InIndex)) - return false; - for (i = 0; i < PackStreams.Size(); i++) - if (BoolVector_GetAndSet(v, PackStreams[i])) - return false; - - BoolVector_Fill_False(v, UnpackSizes.Size()); - for (i = 0; i < BindPairs.Size(); i++) - if (BoolVector_GetAndSet(v, BindPairs[i].OutIndex)) - return false; - } - - UInt32 mask[kMaskSize]; - int i; - for (i = 0; i < kMaskSize; i++) - mask[i] = 0; - - { - CIntVector inStreamToCoder, outStreamToCoder; - for (i = 0; i < Coders.Size(); i++) - { - CNum j; - const CCoderInfo &coder = Coders[i]; - for (j = 0; j < coder.NumInStreams; j++) - inStreamToCoder.Add(i); - for (j = 0; j < coder.NumOutStreams; j++) - outStreamToCoder.Add(i); - } - - for (i = 0; i < BindPairs.Size(); i++) - { - const CBindPair &bp = BindPairs[i]; - mask[inStreamToCoder[bp.InIndex]] |= (1 << outStreamToCoder[bp.OutIndex]); - } - } - - for (i = 0; i < kMaskSize; i++) - for (int j = 0; j < kMaskSize; j++) - if (((1 << j) & mask[i]) != 0) - mask[i] |= mask[j]; - - for (i = 0; i < kMaskSize; i++) - if (((1 << i) & mask[i]) != 0) - return false; - - return true; -} - -class CInArchiveException {}; - -static void ThrowException() { throw CInArchiveException(); } -static inline void ThrowEndOfData() { ThrowException(); } -static inline void ThrowUnsupported() { ThrowException(); } -static inline void ThrowIncorrect() { ThrowException(); } -static inline void ThrowUnsupportedVersion() { ThrowException(); } - -/* -class CInArchiveException -{ -public: - enum CCauseType - { - kUnsupportedVersion = 0, - kUnsupported, - kIncorrect, - kEndOfData, - } Cause; - CInArchiveException(CCauseType cause): Cause(cause) {}; -}; - -static void ThrowException(CInArchiveException::CCauseType c) { throw CInArchiveException(c); } -static void ThrowEndOfData() { ThrowException(CInArchiveException::kEndOfData); } -static void ThrowUnsupported() { ThrowException(CInArchiveException::kUnsupported); } -static void ThrowIncorrect() { ThrowException(CInArchiveException::kIncorrect); } -static void ThrowUnsupportedVersion() { ThrowException(CInArchiveException::kUnsupportedVersion); } -*/ - -class CStreamSwitch -{ - CInArchive *_archive; - bool _needRemove; -public: - CStreamSwitch(): _needRemove(false) {} - ~CStreamSwitch() { Remove(); } - void Remove(); - void Set(CInArchive *archive, const Byte *data, size_t size); - void Set(CInArchive *archive, const CByteBuffer &byteBuffer); - void Set(CInArchive *archive, const CObjectVector *dataVector); -}; - -void CStreamSwitch::Remove() -{ - if (_needRemove) - { - _archive->DeleteByteStream(); - _needRemove = false; - } -} - -void CStreamSwitch::Set(CInArchive *archive, const Byte *data, size_t size) -{ - Remove(); - _archive = archive; - _archive->AddByteStream(data, size); - _needRemove = true; -} - -void CStreamSwitch::Set(CInArchive *archive, const CByteBuffer &byteBuffer) -{ - Set(archive, byteBuffer, byteBuffer.GetCapacity()); -} - -void CStreamSwitch::Set(CInArchive *archive, const CObjectVector *dataVector) -{ - Remove(); - Byte external = archive->ReadByte(); - if (external != 0) - { - int dataIndex = (int)archive->ReadNum(); - if (dataIndex < 0 || dataIndex >= dataVector->Size()) - ThrowIncorrect(); - Set(archive, (*dataVector)[dataIndex]); - } -} - -Byte CInByte2::ReadByte() -{ - if (_pos >= _size) - ThrowEndOfData(); - return _buffer[_pos++]; -} - -void CInByte2::ReadBytes(Byte *data, size_t size) -{ - if (size > _size - _pos) - ThrowEndOfData(); - for (size_t i = 0; i < size; i++) - data[i] = _buffer[_pos++]; -} - -void CInByte2::SkeepData(UInt64 size) -{ - if (size > _size - _pos) - ThrowEndOfData(); - _pos += (size_t)size; -} - -void CInByte2::SkeepData() -{ - SkeepData(ReadNumber()); -} - -UInt64 CInByte2::ReadNumber() -{ - if (_pos >= _size) - ThrowEndOfData(); - Byte firstByte = _buffer[_pos++]; - Byte mask = 0x80; - UInt64 value = 0; - for (int i = 0; i < 8; i++) - { - if ((firstByte & mask) == 0) - { - UInt64 highPart = firstByte & (mask - 1); - value += (highPart << (i * 8)); - return value; - } - if (_pos >= _size) - ThrowEndOfData(); - value |= ((UInt64)_buffer[_pos++] << (8 * i)); - mask >>= 1; - } - return value; -} - -CNum CInByte2::ReadNum() -{ - UInt64 value = ReadNumber(); - if (value > kNumMax) - ThrowUnsupported(); - return (CNum)value; -} - -UInt32 CInByte2::ReadUInt32() -{ - if (_pos + 4 > _size) - ThrowEndOfData(); - UInt32 res = Get32(_buffer + _pos); - _pos += 4; - return res; -} - -UInt64 CInByte2::ReadUInt64() -{ - if (_pos + 8 > _size) - ThrowEndOfData(); - UInt64 res = Get64(_buffer + _pos); - _pos += 8; - return res; -} - -void CInByte2::ReadString(UString &s) -{ - const Byte *buf = _buffer + _pos; - size_t rem = (_size - _pos) / 2 * 2; - { - size_t i; - for (i = 0; i < rem; i += 2) - if (buf[i] == 0 && buf[i + 1] == 0) - break; - if (i == rem) - ThrowEndOfData(); - rem = i; - } - int len = (int)(rem / 2); - if (len < 0 || (size_t)len * 2 != rem) - ThrowUnsupported(); - wchar_t *p = s.GetBuffer(len); - int i; - for (i = 0; i < len; i++, buf += 2) - p[i] = (wchar_t)Get16(buf); - s.ReleaseBuffer(len); - _pos += rem + 2; -} - -static inline bool TestSignatureCandidate(const Byte *p) -{ - for (int i = 0; i < kSignatureSize; i++) - if (p[i] != kSignature[i]) - return false; - return (p[0x1A] == 0 && p[0x1B] == 0); -} - -HRESULT CInArchive::FindAndReadSignature(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - RINOK(ReadStream_FALSE(stream, _header, kHeaderSize)); - - if (TestSignatureCandidate(_header)) - return S_OK; - - CByteBuffer byteBuffer; - const UInt32 kBufferSize = (1 << 16); - byteBuffer.SetCapacity(kBufferSize); - Byte *buffer = byteBuffer; - UInt32 numPrevBytes = kHeaderSize - 1; - memcpy(buffer, _header + 1, numPrevBytes); - UInt64 curTestPos = _arhiveBeginStreamPosition + 1; - for (;;) - { - if (searchHeaderSizeLimit != NULL) - if (curTestPos - _arhiveBeginStreamPosition > *searchHeaderSizeLimit) - break; - do - { - UInt32 numReadBytes = kBufferSize - numPrevBytes; - UInt32 processedSize; - RINOK(stream->Read(buffer + numPrevBytes, numReadBytes, &processedSize)); - numPrevBytes += processedSize; - if (processedSize == 0) - return S_FALSE; - } - while (numPrevBytes < kHeaderSize); - UInt32 numTests = numPrevBytes - kHeaderSize + 1; - for (UInt32 pos = 0; pos < numTests; pos++) - { - for (; buffer[pos] != '7' && pos < numTests; pos++); - if (pos == numTests) - break; - if (TestSignatureCandidate(buffer + pos)) - { - memcpy(_header, buffer + pos, kHeaderSize); - curTestPos += pos; - _arhiveBeginStreamPosition = curTestPos; - return stream->Seek(curTestPos + kHeaderSize, STREAM_SEEK_SET, NULL); - } - } - curTestPos += numTests; - numPrevBytes -= numTests; - memmove(buffer, buffer + numTests, numPrevBytes); - } - return S_FALSE; -} - -// S_FALSE means that file is not archive -HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - HeadersSize = 0; - Close(); - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_arhiveBeginStreamPosition)) - RINOK(FindAndReadSignature(stream, searchHeaderSizeLimit)); - _stream = stream; - return S_OK; -} - -void CInArchive::Close() -{ - _stream.Release(); -} - -void CInArchive::ReadArchiveProperties(CInArchiveInfo & /* archiveInfo */) -{ - for (;;) - { - if (ReadID() == NID::kEnd) - break; - SkeepData(); - } -} - -void CInArchive::GetNextFolderItem(CFolder &folder) -{ - CNum numCoders = ReadNum(); - - folder.Coders.Clear(); - folder.Coders.Reserve((int)numCoders); - CNum numInStreams = 0; - CNum numOutStreams = 0; - CNum i; - for (i = 0; i < numCoders; i++) - { - folder.Coders.Add(CCoderInfo()); - CCoderInfo &coder = folder.Coders.Back(); - - { - Byte mainByte = ReadByte(); - int idSize = (mainByte & 0xF); - Byte longID[15]; - ReadBytes(longID, idSize); - if (idSize > 8) - ThrowUnsupported(); - UInt64 id = 0; - for (int j = 0; j < idSize; j++) - id |= (UInt64)longID[idSize - 1 - j] << (8 * j); - coder.MethodID = id; - - if ((mainByte & 0x10) != 0) - { - coder.NumInStreams = ReadNum(); - coder.NumOutStreams = ReadNum(); - } - else - { - coder.NumInStreams = 1; - coder.NumOutStreams = 1; - } - if ((mainByte & 0x20) != 0) - { - CNum propsSize = ReadNum(); - coder.Props.SetCapacity((size_t)propsSize); - ReadBytes((Byte *)coder.Props, (size_t)propsSize); - } - if ((mainByte & 0x80) != 0) - ThrowUnsupported(); - } - numInStreams += coder.NumInStreams; - numOutStreams += coder.NumOutStreams; - } - - CNum numBindPairs = numOutStreams - 1; - folder.BindPairs.Clear(); - folder.BindPairs.Reserve(numBindPairs); - for (i = 0; i < numBindPairs; i++) - { - CBindPair bp; - bp.InIndex = ReadNum(); - bp.OutIndex = ReadNum(); - folder.BindPairs.Add(bp); - } - - if (numInStreams < numBindPairs) - ThrowUnsupported(); - CNum numPackStreams = numInStreams - numBindPairs; - folder.PackStreams.Reserve(numPackStreams); - if (numPackStreams == 1) - { - for (i = 0; i < numInStreams; i++) - if (folder.FindBindPairForInStream(i) < 0) - { - folder.PackStreams.Add(i); - break; - } - if (folder.PackStreams.Size() != 1) - ThrowUnsupported(); - } - else - for (i = 0; i < numPackStreams; i++) - folder.PackStreams.Add(ReadNum()); -} - -void CInArchive::WaitAttribute(UInt64 attribute) -{ - for (;;) - { - UInt64 type = ReadID(); - if (type == attribute) - return; - if (type == NID::kEnd) - ThrowIncorrect(); - SkeepData(); - } -} - -void CInArchive::ReadHashDigests(int numItems, - CBoolVector &digestsDefined, - CRecordVector &digests) -{ - ReadBoolVector2(numItems, digestsDefined); - digests.Clear(); - digests.Reserve(numItems); - for (int i = 0; i < numItems; i++) - { - UInt32 crc = 0; - if (digestsDefined[i]) - crc = ReadUInt32(); - digests.Add(crc); - } -} - -void CInArchive::ReadPackInfo( - UInt64 &dataOffset, - CRecordVector &packSizes, - CBoolVector &packCRCsDefined, - CRecordVector &packCRCs) -{ - dataOffset = ReadNumber(); - CNum numPackStreams = ReadNum(); - - WaitAttribute(NID::kSize); - packSizes.Clear(); - packSizes.Reserve(numPackStreams); - for (CNum i = 0; i < numPackStreams; i++) - packSizes.Add(ReadNumber()); - - UInt64 type; - for (;;) - { - type = ReadID(); - if (type == NID::kEnd) - break; - if (type == NID::kCRC) - { - ReadHashDigests(numPackStreams, packCRCsDefined, packCRCs); - continue; - } - SkeepData(); - } - if (packCRCsDefined.IsEmpty()) - { - BoolVector_Fill_False(packCRCsDefined, numPackStreams); - packCRCs.Reserve(numPackStreams); - packCRCs.Clear(); - for (CNum i = 0; i < numPackStreams; i++) - packCRCs.Add(0); - } -} - -void CInArchive::ReadUnpackInfo( - const CObjectVector *dataVector, - CObjectVector &folders) -{ - WaitAttribute(NID::kFolder); - CNum numFolders = ReadNum(); - - { - CStreamSwitch streamSwitch; - streamSwitch.Set(this, dataVector); - folders.Clear(); - folders.Reserve(numFolders); - for (CNum i = 0; i < numFolders; i++) - { - folders.Add(CFolder()); - GetNextFolderItem(folders.Back()); - } - } - - WaitAttribute(NID::kCodersUnpackSize); - - CNum i; - for (i = 0; i < numFolders; i++) - { - CFolder &folder = folders[i]; - CNum numOutStreams = folder.GetNumOutStreams(); - folder.UnpackSizes.Reserve(numOutStreams); - for (CNum j = 0; j < numOutStreams; j++) - folder.UnpackSizes.Add(ReadNumber()); - } - - for (;;) - { - UInt64 type = ReadID(); - if (type == NID::kEnd) - return; - if (type == NID::kCRC) - { - CBoolVector crcsDefined; - CRecordVector crcs; - ReadHashDigests(numFolders, crcsDefined, crcs); - for (i = 0; i < numFolders; i++) - { - CFolder &folder = folders[i]; - folder.UnpackCRCDefined = crcsDefined[i]; - folder.UnpackCRC = crcs[i]; - } - continue; - } - SkeepData(); - } -} - -void CInArchive::ReadSubStreamsInfo( - const CObjectVector &folders, - CRecordVector &numUnpackStreamsInFolders, - CRecordVector &unpackSizes, - CBoolVector &digestsDefined, - CRecordVector &digests) -{ - numUnpackStreamsInFolders.Clear(); - numUnpackStreamsInFolders.Reserve(folders.Size()); - UInt64 type; - for (;;) - { - type = ReadID(); - if (type == NID::kNumUnpackStream) - { - for (int i = 0; i < folders.Size(); i++) - numUnpackStreamsInFolders.Add(ReadNum()); - continue; - } - if (type == NID::kCRC || type == NID::kSize) - break; - if (type == NID::kEnd) - break; - SkeepData(); - } - - if (numUnpackStreamsInFolders.IsEmpty()) - for (int i = 0; i < folders.Size(); i++) - numUnpackStreamsInFolders.Add(1); - - int i; - for (i = 0; i < numUnpackStreamsInFolders.Size(); i++) - { - // v3.13 incorrectly worked with empty folders - // v4.07: we check that folder is empty - CNum numSubstreams = numUnpackStreamsInFolders[i]; - if (numSubstreams == 0) - continue; - UInt64 sum = 0; - for (CNum j = 1; j < numSubstreams; j++) - if (type == NID::kSize) - { - UInt64 size = ReadNumber(); - unpackSizes.Add(size); - sum += size; - } - unpackSizes.Add(folders[i].GetUnpackSize() - sum); - } - if (type == NID::kSize) - type = ReadID(); - - int numDigests = 0; - int numDigestsTotal = 0; - for (i = 0; i < folders.Size(); i++) - { - CNum numSubstreams = numUnpackStreamsInFolders[i]; - if (numSubstreams != 1 || !folders[i].UnpackCRCDefined) - numDigests += numSubstreams; - numDigestsTotal += numSubstreams; - } - - for (;;) - { - if (type == NID::kCRC) - { - CBoolVector digestsDefined2; - CRecordVector digests2; - ReadHashDigests(numDigests, digestsDefined2, digests2); - int digestIndex = 0; - for (i = 0; i < folders.Size(); i++) - { - CNum numSubstreams = numUnpackStreamsInFolders[i]; - const CFolder &folder = folders[i]; - if (numSubstreams == 1 && folder.UnpackCRCDefined) - { - digestsDefined.Add(true); - digests.Add(folder.UnpackCRC); - } - else - for (CNum j = 0; j < numSubstreams; j++, digestIndex++) - { - digestsDefined.Add(digestsDefined2[digestIndex]); - digests.Add(digests2[digestIndex]); - } - } - } - else if (type == NID::kEnd) - { - if (digestsDefined.IsEmpty()) - { - BoolVector_Fill_False(digestsDefined, numDigestsTotal); - digests.Clear(); - for (int i = 0; i < numDigestsTotal; i++) - digests.Add(0); - } - return; - } - else - SkeepData(); - type = ReadID(); - } -} - -void CInArchive::ReadStreamsInfo( - const CObjectVector *dataVector, - UInt64 &dataOffset, - CRecordVector &packSizes, - CBoolVector &packCRCsDefined, - CRecordVector &packCRCs, - CObjectVector &folders, - CRecordVector &numUnpackStreamsInFolders, - CRecordVector &unpackSizes, - CBoolVector &digestsDefined, - CRecordVector &digests) -{ - for (;;) - { - UInt64 type = ReadID(); - if (type > ((UInt32)1 << 30)) - ThrowIncorrect(); - switch((UInt32)type) - { - case NID::kEnd: - return; - case NID::kPackInfo: - { - ReadPackInfo(dataOffset, packSizes, packCRCsDefined, packCRCs); - break; - } - case NID::kUnpackInfo: - { - ReadUnpackInfo(dataVector, folders); - break; - } - case NID::kSubStreamsInfo: - { - ReadSubStreamsInfo(folders, numUnpackStreamsInFolders, - unpackSizes, digestsDefined, digests); - break; - } - default: - ThrowIncorrect(); - } - } -} - -void CInArchive::ReadBoolVector(int numItems, CBoolVector &v) -{ - v.Clear(); - v.Reserve(numItems); - Byte b = 0; - Byte mask = 0; - for (int i = 0; i < numItems; i++) - { - if (mask == 0) - { - b = ReadByte(); - mask = 0x80; - } - v.Add((b & mask) != 0); - mask >>= 1; - } -} - -void CInArchive::ReadBoolVector2(int numItems, CBoolVector &v) -{ - Byte allAreDefined = ReadByte(); - if (allAreDefined == 0) - { - ReadBoolVector(numItems, v); - return; - } - v.Clear(); - v.Reserve(numItems); - for (int i = 0; i < numItems; i++) - v.Add(true); -} - -void CInArchive::ReadUInt64DefVector(const CObjectVector &dataVector, - CUInt64DefVector &v, int numFiles) -{ - ReadBoolVector2(numFiles, v.Defined); - - CStreamSwitch streamSwitch; - streamSwitch.Set(this, &dataVector); - v.Values.Reserve(numFiles); - - for (int i = 0; i < numFiles; i++) - { - UInt64 t = 0; - if (v.Defined[i]) - t = ReadUInt64(); - v.Values.Add(t); - } -} - -HRESULT CInArchive::ReadAndDecodePackedStreams( - DECL_EXTERNAL_CODECS_LOC_VARS - UInt64 baseOffset, - UInt64 &dataOffset, CObjectVector &dataVector - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ) -{ - CRecordVector packSizes; - CBoolVector packCRCsDefined; - CRecordVector packCRCs; - CObjectVector folders; - - CRecordVector numUnpackStreamsInFolders; - CRecordVector unpackSizes; - CBoolVector digestsDefined; - CRecordVector digests; - - ReadStreamsInfo(NULL, - dataOffset, - packSizes, - packCRCsDefined, - packCRCs, - folders, - numUnpackStreamsInFolders, - unpackSizes, - digestsDefined, - digests); - - // db.ArchiveInfo.DataStartPosition2 += db.ArchiveInfo.StartPositionAfterHeader; - - CNum packIndex = 0; - CDecoder decoder( - #ifdef _ST_MODE - false - #else - true - #endif - ); - UInt64 dataStartPos = baseOffset + dataOffset; - for (int i = 0; i < folders.Size(); i++) - { - const CFolder &folder = folders[i]; - dataVector.Add(CByteBuffer()); - CByteBuffer &data = dataVector.Back(); - UInt64 unpackSize64 = folder.GetUnpackSize(); - size_t unpackSize = (size_t)unpackSize64; - if (unpackSize != unpackSize64) - ThrowUnsupported(); - data.SetCapacity(unpackSize); - - CSequentialOutStreamImp2 *outStreamSpec = new CSequentialOutStreamImp2; - CMyComPtr outStream = outStreamSpec; - outStreamSpec->Init(data, unpackSize); - - HRESULT result = decoder.Decode( - EXTERNAL_CODECS_LOC_VARS - _stream, dataStartPos, - &packSizes[packIndex], folder, outStream, NULL - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - #ifdef COMPRESS_MT - , false, 1 - #endif - ); - RINOK(result); - - if (folder.UnpackCRCDefined) - if (CrcCalc(data, unpackSize) != folder.UnpackCRC) - ThrowIncorrect(); - for (int j = 0; j < folder.PackStreams.Size(); j++) - { - UInt64 packSize = packSizes[packIndex++]; - dataStartPos += packSize; - HeadersSize += packSize; - } - } - return S_OK; -} - -HRESULT CInArchive::ReadHeader( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ) -{ - UInt64 type = ReadID(); - - if (type == NID::kArchiveProperties) - { - ReadArchiveProperties(db.ArchiveInfo); - type = ReadID(); - } - - CObjectVector dataVector; - - if (type == NID::kAdditionalStreamsInfo) - { - HRESULT result = ReadAndDecodePackedStreams( - EXTERNAL_CODECS_LOC_VARS - db.ArchiveInfo.StartPositionAfterHeader, - db.ArchiveInfo.DataStartPosition2, - dataVector - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - ); - RINOK(result); - db.ArchiveInfo.DataStartPosition2 += db.ArchiveInfo.StartPositionAfterHeader; - type = ReadID(); - } - - CRecordVector unpackSizes; - CBoolVector digestsDefined; - CRecordVector digests; - - if (type == NID::kMainStreamsInfo) - { - ReadStreamsInfo(&dataVector, - db.ArchiveInfo.DataStartPosition, - db.PackSizes, - db.PackCRCsDefined, - db.PackCRCs, - db.Folders, - db.NumUnpackStreamsVector, - unpackSizes, - digestsDefined, - digests); - db.ArchiveInfo.DataStartPosition += db.ArchiveInfo.StartPositionAfterHeader; - type = ReadID(); - } - else - { - for (int i = 0; i < db.Folders.Size(); i++) - { - db.NumUnpackStreamsVector.Add(1); - CFolder &folder = db.Folders[i]; - unpackSizes.Add(folder.GetUnpackSize()); - digestsDefined.Add(folder.UnpackCRCDefined); - digests.Add(folder.UnpackCRC); - } - } - - db.Files.Clear(); - - if (type == NID::kEnd) - return S_OK; - if (type != NID::kFilesInfo) - ThrowIncorrect(); - - CNum numFiles = ReadNum(); - db.Files.Reserve(numFiles); - CNum i; - for (i = 0; i < numFiles; i++) - db.Files.Add(CFileItem()); - - db.ArchiveInfo.FileInfoPopIDs.Add(NID::kSize); - if (!db.PackSizes.IsEmpty()) - db.ArchiveInfo.FileInfoPopIDs.Add(NID::kPackInfo); - if (numFiles > 0 && !digests.IsEmpty()) - db.ArchiveInfo.FileInfoPopIDs.Add(NID::kCRC); - - CBoolVector emptyStreamVector; - BoolVector_Fill_False(emptyStreamVector, (int)numFiles); - CBoolVector emptyFileVector; - CBoolVector antiFileVector; - CNum numEmptyStreams = 0; - - for (;;) - { - UInt64 type = ReadID(); - if (type == NID::kEnd) - break; - UInt64 size = ReadNumber(); - size_t ppp = _inByteBack->_pos; - bool addPropIdToList = true; - bool isKnownType = true; - if (type > ((UInt32)1 << 30)) - isKnownType = false; - else switch((UInt32)type) - { - case NID::kName: - { - CStreamSwitch streamSwitch; - streamSwitch.Set(this, &dataVector); - for (int i = 0; i < db.Files.Size(); i++) - _inByteBack->ReadString(db.Files[i].Name); - break; - } - case NID::kWinAttributes: - { - CBoolVector boolVector; - ReadBoolVector2(db.Files.Size(), boolVector); - CStreamSwitch streamSwitch; - streamSwitch.Set(this, &dataVector); - for (i = 0; i < numFiles; i++) - { - CFileItem &file = db.Files[i]; - file.AttribDefined = boolVector[i]; - if (file.AttribDefined) - file.Attrib = ReadUInt32(); - } - break; - } - case NID::kEmptyStream: - { - ReadBoolVector(numFiles, emptyStreamVector); - for (i = 0; i < (CNum)emptyStreamVector.Size(); i++) - if (emptyStreamVector[i]) - numEmptyStreams++; - - BoolVector_Fill_False(emptyFileVector, numEmptyStreams); - BoolVector_Fill_False(antiFileVector, numEmptyStreams); - - break; - } - case NID::kEmptyFile: ReadBoolVector(numEmptyStreams, emptyFileVector); break; - case NID::kAnti: ReadBoolVector(numEmptyStreams, antiFileVector); break; - case NID::kStartPos: ReadUInt64DefVector(dataVector, db.StartPos, (int)numFiles); break; - case NID::kCTime: ReadUInt64DefVector(dataVector, db.CTime, (int)numFiles); break; - case NID::kATime: ReadUInt64DefVector(dataVector, db.ATime, (int)numFiles); break; - case NID::kMTime: ReadUInt64DefVector(dataVector, db.MTime, (int)numFiles); break; - case NID::kDummy: - { - for (UInt64 j = 0; j < size; j++) - if (ReadByte() != 0) - ThrowIncorrect(); - addPropIdToList = false; - break; - } - default: - addPropIdToList = isKnownType = false; - } - if (isKnownType) - { - if(addPropIdToList) - db.ArchiveInfo.FileInfoPopIDs.Add(type); - } - else - SkeepData(size); - bool checkRecordsSize = (db.ArchiveInfo.Version.Major > 0 || - db.ArchiveInfo.Version.Minor > 2); - if (checkRecordsSize && _inByteBack->_pos - ppp != size) - ThrowIncorrect(); - } - - CNum emptyFileIndex = 0; - CNum sizeIndex = 0; - - CNum numAntiItems = 0; - for (i = 0; i < numEmptyStreams; i++) - if (antiFileVector[i]) - numAntiItems++; - - for (i = 0; i < numFiles; i++) - { - CFileItem &file = db.Files[i]; - bool isAnti; - file.HasStream = !emptyStreamVector[i]; - if (file.HasStream) - { - file.IsDir = false; - isAnti = false; - file.Size = unpackSizes[sizeIndex]; - file.Crc = digests[sizeIndex]; - file.CrcDefined = digestsDefined[sizeIndex]; - sizeIndex++; - } - else - { - file.IsDir = !emptyFileVector[emptyFileIndex]; - isAnti = antiFileVector[emptyFileIndex]; - emptyFileIndex++; - file.Size = 0; - file.CrcDefined = false; - } - if (numAntiItems != 0) - db.IsAnti.Add(isAnti); - } - return S_OK; -} - - -void CArchiveDatabaseEx::FillFolderStartPackStream() -{ - FolderStartPackStreamIndex.Clear(); - FolderStartPackStreamIndex.Reserve(Folders.Size()); - CNum startPos = 0; - for (int i = 0; i < Folders.Size(); i++) - { - FolderStartPackStreamIndex.Add(startPos); - startPos += (CNum)Folders[i].PackStreams.Size(); - } -} - -void CArchiveDatabaseEx::FillStartPos() -{ - PackStreamStartPositions.Clear(); - PackStreamStartPositions.Reserve(PackSizes.Size()); - UInt64 startPos = 0; - for (int i = 0; i < PackSizes.Size(); i++) - { - PackStreamStartPositions.Add(startPos); - startPos += PackSizes[i]; - } -} - -void CArchiveDatabaseEx::FillFolderStartFileIndex() -{ - FolderStartFileIndex.Clear(); - FolderStartFileIndex.Reserve(Folders.Size()); - FileIndexToFolderIndexMap.Clear(); - FileIndexToFolderIndexMap.Reserve(Files.Size()); - - int folderIndex = 0; - CNum indexInFolder = 0; - for (int i = 0; i < Files.Size(); i++) - { - const CFileItem &file = Files[i]; - bool emptyStream = !file.HasStream; - if (emptyStream && indexInFolder == 0) - { - FileIndexToFolderIndexMap.Add(kNumNoIndex); - continue; - } - if (indexInFolder == 0) - { - // v3.13 incorrectly worked with empty folders - // v4.07: Loop for skipping empty folders - for (;;) - { - if (folderIndex >= Folders.Size()) - ThrowIncorrect(); - FolderStartFileIndex.Add(i); // check it - if (NumUnpackStreamsVector[folderIndex] != 0) - break; - folderIndex++; - } - } - FileIndexToFolderIndexMap.Add(folderIndex); - if (emptyStream) - continue; - indexInFolder++; - if (indexInFolder >= NumUnpackStreamsVector[folderIndex]) - { - folderIndex++; - indexInFolder = 0; - } - } -} - -HRESULT CInArchive::ReadDatabase2( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ) -{ - db.Clear(); - db.ArchiveInfo.StartPosition = _arhiveBeginStreamPosition; - - db.ArchiveInfo.Version.Major = _header[6]; - db.ArchiveInfo.Version.Minor = _header[7]; - - if (db.ArchiveInfo.Version.Major != kMajorVersion) - ThrowUnsupportedVersion(); - - UInt32 crcFromArchive = Get32(_header + 8); - UInt64 nextHeaderOffset = Get64(_header + 0xC); - UInt64 nextHeaderSize = Get64(_header + 0x14); - UInt32 nextHeaderCRC = Get32(_header + 0x1C); - UInt32 crc = CrcCalc(_header + 0xC, 20); - - #ifdef FORMAT_7Z_RECOVERY - if (crcFromArchive == 0 && nextHeaderOffset == 0 && nextHeaderSize == 0 && nextHeaderCRC == 0) - { - UInt64 cur, cur2; - RINOK(_stream->Seek(0, STREAM_SEEK_CUR, &cur)); - const int kCheckSize = 500; - Byte buf[kCheckSize]; - RINOK(_stream->Seek(0, STREAM_SEEK_END, &cur2)); - int checkSize = kCheckSize; - if (cur2 - cur < kCheckSize) - checkSize = (int)(cur2 - cur); - RINOK(_stream->Seek(-checkSize, STREAM_SEEK_END, &cur2)); - - RINOK(ReadStream_FALSE(_stream, buf, (size_t)checkSize)); - - int i; - for (i = (int)checkSize - 2; i >= 0; i--) - if (buf[i] == 0x17 && buf[i + 1] == 0x6 || buf[i] == 0x01 && buf[i + 1] == 0x04) - break; - if (i < 0) - return S_FALSE; - nextHeaderSize = checkSize - i; - nextHeaderOffset = cur2 - cur + i; - nextHeaderCRC = CrcCalc(buf + i, (size_t)nextHeaderSize); - RINOK(_stream->Seek(cur, STREAM_SEEK_SET, NULL)); - } - #endif - - #ifdef FORMAT_7Z_RECOVERY - crcFromArchive = crc; - #endif - - db.ArchiveInfo.StartPositionAfterHeader = _arhiveBeginStreamPosition + kHeaderSize; - - if (crc != crcFromArchive) - ThrowIncorrect(); - - if (nextHeaderSize == 0) - return S_OK; - - if (nextHeaderSize > (UInt64)0xFFFFFFFF) - return S_FALSE; - - RINOK(_stream->Seek(nextHeaderOffset, STREAM_SEEK_CUR, NULL)); - - CByteBuffer buffer2; - buffer2.SetCapacity((size_t)nextHeaderSize); - - RINOK(ReadStream_FALSE(_stream, buffer2, (size_t)nextHeaderSize)); - HeadersSize += kHeaderSize + nextHeaderSize; - db.PhySize = kHeaderSize + nextHeaderOffset + nextHeaderSize; - - if (CrcCalc(buffer2, (UInt32)nextHeaderSize) != nextHeaderCRC) - ThrowIncorrect(); - - CStreamSwitch streamSwitch; - streamSwitch.Set(this, buffer2); - - CObjectVector dataVector; - - UInt64 type = ReadID(); - if (type != NID::kHeader) - { - if (type != NID::kEncodedHeader) - ThrowIncorrect(); - HRESULT result = ReadAndDecodePackedStreams( - EXTERNAL_CODECS_LOC_VARS - db.ArchiveInfo.StartPositionAfterHeader, - db.ArchiveInfo.DataStartPosition2, - dataVector - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - ); - RINOK(result); - if (dataVector.Size() == 0) - return S_OK; - if (dataVector.Size() > 1) - ThrowIncorrect(); - streamSwitch.Remove(); - streamSwitch.Set(this, dataVector.Front()); - if (ReadID() != NID::kHeader) - ThrowIncorrect(); - } - - db.HeadersSize = HeadersSize; - - return ReadHeader( - EXTERNAL_CODECS_LOC_VARS - db - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - ); -} - -HRESULT CInArchive::ReadDatabase( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ) -{ - try - { - return ReadDatabase2( - EXTERNAL_CODECS_LOC_VARS db - #ifndef _NO_CRYPTO - , getTextPassword, passwordIsDefined - #endif - ); - } - catch(CInArchiveException &) { return S_FALSE; } -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.h deleted file mode 100644 index bfec78564..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zIn.h +++ /dev/null @@ -1,245 +0,0 @@ -// 7zIn.h - -#ifndef __7Z_IN_H -#define __7Z_IN_H - -#include "../../../Common/MyCom.h" - -#include "../../IPassword.h" -#include "../../IStream.h" - -#include "../../Common/CreateCoder.h" -#include "../../Common/InBuffer.h" - -#include "7zItem.h" - -namespace NArchive { -namespace N7z { - -struct CInArchiveInfo -{ - CArchiveVersion Version; - UInt64 StartPosition; - UInt64 StartPositionAfterHeader; - UInt64 DataStartPosition; - UInt64 DataStartPosition2; - CRecordVector FileInfoPopIDs; - void Clear() - { - FileInfoPopIDs.Clear(); - } -}; - -struct CArchiveDatabaseEx: public CArchiveDatabase -{ - CInArchiveInfo ArchiveInfo; - CRecordVector PackStreamStartPositions; - CRecordVector FolderStartPackStreamIndex; - CRecordVector FolderStartFileIndex; - CRecordVector FileIndexToFolderIndexMap; - - UInt64 HeadersSize; - UInt64 PhySize; - - void Clear() - { - CArchiveDatabase::Clear(); - ArchiveInfo.Clear(); - PackStreamStartPositions.Clear(); - FolderStartPackStreamIndex.Clear(); - FolderStartFileIndex.Clear(); - FileIndexToFolderIndexMap.Clear(); - - HeadersSize = 0; - PhySize = 0; - } - - void FillFolderStartPackStream(); - void FillStartPos(); - void FillFolderStartFileIndex(); - - void Fill() - { - FillFolderStartPackStream(); - FillStartPos(); - FillFolderStartFileIndex(); - } - - UInt64 GetFolderStreamPos(int folderIndex, int indexInFolder) const - { - return ArchiveInfo.DataStartPosition + - PackStreamStartPositions[FolderStartPackStreamIndex[folderIndex] + indexInFolder]; - } - - UInt64 GetFolderFullPackSize(int folderIndex) const - { - CNum packStreamIndex = FolderStartPackStreamIndex[folderIndex]; - const CFolder &folder = Folders[folderIndex]; - UInt64 size = 0; - for (int i = 0; i < folder.PackStreams.Size(); i++) - size += PackSizes[packStreamIndex + i]; - return size; - } - - UInt64 GetFolderPackStreamSize(int folderIndex, int streamIndex) const - { - return PackSizes[FolderStartPackStreamIndex[folderIndex] + streamIndex]; - } - - UInt64 GetFilePackSize(CNum fileIndex) const - { - CNum folderIndex = FileIndexToFolderIndexMap[fileIndex]; - if (folderIndex != kNumNoIndex) - if (FolderStartFileIndex[folderIndex] == fileIndex) - return GetFolderFullPackSize(folderIndex); - return 0; - } -}; - -class CInByte2 -{ - const Byte *_buffer; - size_t _size; -public: - size_t _pos; - void Init(const Byte *buffer, size_t size) - { - _buffer = buffer; - _size = size; - _pos = 0; - } - Byte ReadByte(); - void ReadBytes(Byte *data, size_t size); - void SkeepData(UInt64 size); - void SkeepData(); - UInt64 ReadNumber(); - CNum ReadNum(); - UInt32 ReadUInt32(); - UInt64 ReadUInt64(); - void ReadString(UString &s); -}; - -class CStreamSwitch; - -const UInt32 kHeaderSize = 32; - -class CInArchive -{ - friend class CStreamSwitch; - - CMyComPtr _stream; - - CObjectVector _inByteVector; - CInByte2 *_inByteBack; - - UInt64 _arhiveBeginStreamPosition; - - Byte _header[kHeaderSize]; - - UInt64 HeadersSize; - - void AddByteStream(const Byte *buffer, size_t size) - { - _inByteVector.Add(CInByte2()); - _inByteBack = &_inByteVector.Back(); - _inByteBack->Init(buffer, size); - } - - void DeleteByteStream() - { - _inByteVector.DeleteBack(); - if (!_inByteVector.IsEmpty()) - _inByteBack = &_inByteVector.Back(); - } - -private: - HRESULT FindAndReadSignature(IInStream *stream, const UInt64 *searchHeaderSizeLimit); - - void ReadBytes(Byte *data, size_t size) { _inByteBack->ReadBytes(data, size); } - Byte ReadByte() { return _inByteBack->ReadByte(); } - UInt64 ReadNumber() { return _inByteBack->ReadNumber(); } - CNum ReadNum() { return _inByteBack->ReadNum(); } - UInt64 ReadID() { return _inByteBack->ReadNumber(); } - UInt32 ReadUInt32() { return _inByteBack->ReadUInt32(); } - UInt64 ReadUInt64() { return _inByteBack->ReadUInt64(); } - void SkeepData(UInt64 size) { _inByteBack->SkeepData(size); } - void SkeepData() { _inByteBack->SkeepData(); } - void WaitAttribute(UInt64 attribute); - - void ReadArchiveProperties(CInArchiveInfo &archiveInfo); - void GetNextFolderItem(CFolder &itemInfo); - void ReadHashDigests(int numItems, - CBoolVector &digestsDefined, CRecordVector &digests); - - void ReadPackInfo( - UInt64 &dataOffset, - CRecordVector &packSizes, - CBoolVector &packCRCsDefined, - CRecordVector &packCRCs); - - void ReadUnpackInfo( - const CObjectVector *dataVector, - CObjectVector &folders); - - void ReadSubStreamsInfo( - const CObjectVector &folders, - CRecordVector &numUnpackStreamsInFolders, - CRecordVector &unpackSizes, - CBoolVector &digestsDefined, - CRecordVector &digests); - - void ReadStreamsInfo( - const CObjectVector *dataVector, - UInt64 &dataOffset, - CRecordVector &packSizes, - CBoolVector &packCRCsDefined, - CRecordVector &packCRCs, - CObjectVector &folders, - CRecordVector &numUnpackStreamsInFolders, - CRecordVector &unpackSizes, - CBoolVector &digestsDefined, - CRecordVector &digests); - - - void ReadBoolVector(int numItems, CBoolVector &v); - void ReadBoolVector2(int numItems, CBoolVector &v); - void ReadUInt64DefVector(const CObjectVector &dataVector, - CUInt64DefVector &v, int numFiles); - HRESULT ReadAndDecodePackedStreams( - DECL_EXTERNAL_CODECS_LOC_VARS - UInt64 baseOffset, UInt64 &dataOffset, - CObjectVector &dataVector - #ifndef _NO_CRYPTO - , ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ); - HRESULT ReadHeader( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - ,ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ); - HRESULT ReadDatabase2( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - ,ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ); -public: - HRESULT Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit); // S_FALSE means is not archive - void Close(); - - HRESULT ReadDatabase( - DECL_EXTERNAL_CODECS_LOC_VARS - CArchiveDatabaseEx &db - #ifndef _NO_CRYPTO - ,ICryptoGetTextPassword *getTextPassword, bool &passwordIsDefined - #endif - ); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zItem.h deleted file mode 100644 index 6cc9ccc55..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zItem.h +++ /dev/null @@ -1,258 +0,0 @@ -// 7zItem.h - -#ifndef __7Z_ITEM_H -#define __7Z_ITEM_H - -#include "../../../Common/Buffer.h" -#include "../../../Common/MyString.h" - -#include "../../Common/MethodId.h" - -#include "7zHeader.h" - -namespace NArchive { -namespace N7z { - -typedef UInt32 CNum; -const CNum kNumMax = 0x7FFFFFFF; -const CNum kNumNoIndex = 0xFFFFFFFF; - -struct CCoderInfo -{ - CMethodId MethodID; - CByteBuffer Props; - CNum NumInStreams; - CNum NumOutStreams; - bool IsSimpleCoder() const { return (NumInStreams == 1) && (NumOutStreams == 1); } -}; - -struct CBindPair -{ - CNum InIndex; - CNum OutIndex; -}; - -struct CFolder -{ - CObjectVector Coders; - CRecordVector BindPairs; - CRecordVector PackStreams; - CRecordVector UnpackSizes; - UInt32 UnpackCRC; - bool UnpackCRCDefined; - - CFolder(): UnpackCRCDefined(false) {} - - UInt64 GetUnpackSize() const // test it - { - if (UnpackSizes.IsEmpty()) - return 0; - for (int i = UnpackSizes.Size() - 1; i >= 0; i--) - if (FindBindPairForOutStream(i) < 0) - return UnpackSizes[i]; - throw 1; - } - - CNum GetNumOutStreams() const - { - CNum result = 0; - for (int i = 0; i < Coders.Size(); i++) - result += Coders[i].NumOutStreams; - return result; - } - - int FindBindPairForInStream(CNum inStreamIndex) const - { - for(int i = 0; i < BindPairs.Size(); i++) - if (BindPairs[i].InIndex == inStreamIndex) - return i; - return -1; - } - int FindBindPairForOutStream(CNum outStreamIndex) const - { - for(int i = 0; i < BindPairs.Size(); i++) - if (BindPairs[i].OutIndex == outStreamIndex) - return i; - return -1; - } - int FindPackStreamArrayIndex(CNum inStreamIndex) const - { - for(int i = 0; i < PackStreams.Size(); i++) - if (PackStreams[i] == inStreamIndex) - return i; - return -1; - } - - bool CheckStructure() const; -}; - -struct CUInt64DefVector -{ - CRecordVector Values; - CRecordVector Defined; - - void Clear() - { - Values.Clear(); - Defined.Clear(); - } - - void ReserveDown() - { - Values.ReserveDown(); - Values.ReserveDown(); - } - - bool GetItem(int index, UInt64 &value) const - { - if (index < Defined.Size() && Defined[index]) - { - value = Values[index]; - return true; - } - value = 0; - return false; - } - - void SetItem(int index, bool defined, UInt64 value) - { - while (index >= Defined.Size()) - Defined.Add(false); - Defined[index] = defined; - if (!defined) - return; - while (index >= Values.Size()) - Values.Add(0); - Values[index] = value; - } - - bool CheckSize(int size) const { return Defined.Size() == size || Defined.Size() == 0; } -}; - -struct CFileItem -{ - UInt64 Size; - UInt32 Attrib; - UInt32 Crc; - UString Name; - - bool HasStream; // Test it !!! it means that there is - // stream in some folder. It can be empty stream - bool IsDir; - bool CrcDefined; - bool AttribDefined; - - CFileItem(): - HasStream(true), - IsDir(false), - CrcDefined(false), - AttribDefined(false) - {} - void SetAttrib(UInt32 attrib) - { - AttribDefined = true; - Attrib = attrib; - } -}; - -struct CFileItem2 -{ - UInt64 CTime; - UInt64 ATime; - UInt64 MTime; - UInt64 StartPos; - bool CTimeDefined; - bool ATimeDefined; - bool MTimeDefined; - bool StartPosDefined; - bool IsAnti; -}; - -struct CArchiveDatabase -{ - CRecordVector PackSizes; - CRecordVector PackCRCsDefined; - CRecordVector PackCRCs; - CObjectVector Folders; - CRecordVector NumUnpackStreamsVector; - CObjectVector Files; - - CUInt64DefVector CTime; - CUInt64DefVector ATime; - CUInt64DefVector MTime; - CUInt64DefVector StartPos; - CRecordVector IsAnti; - - void Clear() - { - PackSizes.Clear(); - PackCRCsDefined.Clear(); - PackCRCs.Clear(); - Folders.Clear(); - NumUnpackStreamsVector.Clear(); - Files.Clear(); - CTime.Clear(); - ATime.Clear(); - MTime.Clear(); - StartPos.Clear(); - IsAnti.Clear(); - } - - void ReserveDown() - { - PackSizes.ReserveDown(); - PackCRCsDefined.ReserveDown(); - PackCRCs.ReserveDown(); - Folders.ReserveDown(); - NumUnpackStreamsVector.ReserveDown(); - Files.ReserveDown(); - CTime.ReserveDown(); - ATime.ReserveDown(); - MTime.ReserveDown(); - StartPos.ReserveDown(); - IsAnti.ReserveDown(); - } - - bool IsEmpty() const - { - return (PackSizes.IsEmpty() && - PackCRCsDefined.IsEmpty() && - PackCRCs.IsEmpty() && - Folders.IsEmpty() && - NumUnpackStreamsVector.IsEmpty() && - Files.IsEmpty()); - } - - bool CheckNumFiles() const - { - int size = Files.Size(); - return ( - CTime.CheckSize(size) && - ATime.CheckSize(size) && - MTime.CheckSize(size) && - StartPos.CheckSize(size) && - (size == IsAnti.Size() || IsAnti.Size() == 0)); - } - - bool IsSolid() const - { - for (int i = 0; i < NumUnpackStreamsVector.Size(); i++) - if (NumUnpackStreamsVector[i] > 1) - return true; - return false; - } - bool IsItemAnti(int index) const { return (index < IsAnti.Size() && IsAnti[index]); } - void SetItemAnti(int index, bool isAnti) - { - while (index >= IsAnti.Size()) - IsAnti.Add(false); - IsAnti[index] = isAnti; - } - - void GetFile(int index, CFileItem &file, CFileItem2 &file2) const; - void AddFile(const CFileItem &file, const CFileItem2 &file2); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.cpp deleted file mode 100644 index f5ac3b9bf..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.cpp +++ /dev/null @@ -1,163 +0,0 @@ -// 7zProperties.cpp - -#include "StdAfx.h" - -#include "7zProperties.h" -#include "7zHeader.h" -#include "7zHandler.h" - -// #define _MULTI_PACK - -namespace NArchive { -namespace N7z { - -struct CPropMap -{ - UInt64 FilePropID; - STATPROPSTG StatPROPSTG; -}; - -CPropMap kPropMap[] = -{ - { NID::kName, NULL, kpidPath, VT_BSTR}, - { NID::kSize, NULL, kpidSize, VT_UI8}, - { NID::kPackInfo, NULL, kpidPackSize, VT_UI8}, - - #ifdef _MULTI_PACK - { 100, L"Pack0", kpidPackedSize0, VT_UI8}, - { 101, L"Pack1", kpidPackedSize1, VT_UI8}, - { 102, L"Pack2", kpidPackedSize2, VT_UI8}, - { 103, L"Pack3", kpidPackedSize3, VT_UI8}, - { 104, L"Pack4", kpidPackedSize4, VT_UI8}, - #endif - - { NID::kCTime, NULL, kpidCTime, VT_FILETIME}, - { NID::kMTime, NULL, kpidMTime, VT_FILETIME}, - { NID::kATime, NULL, kpidATime, VT_FILETIME}, - { NID::kWinAttributes, NULL, kpidAttrib, VT_UI4}, - { NID::kStartPos, NULL, kpidPosition, VT_UI4}, - - { NID::kCRC, NULL, kpidCRC, VT_UI4}, - - { NID::kAnti, NULL, kpidIsAnti, VT_BOOL}, - - #ifndef _SFX - { 97, NULL, kpidEncrypted, VT_BOOL}, - { 98, NULL, kpidMethod, VT_BSTR}, - { 99, NULL, kpidBlock, VT_UI4} - #endif -}; - -static const int kPropMapSize = sizeof(kPropMap) / sizeof(kPropMap[0]); - -static int FindPropInMap(UInt64 filePropID) -{ - for (int i = 0; i < kPropMapSize; i++) - if (kPropMap[i].FilePropID == filePropID) - return i; - return -1; -} - -static void CopyOneItem(CRecordVector &src, - CRecordVector &dest, UInt32 item) -{ - for (int i = 0; i < src.Size(); i++) - if (src[i] == item) - { - dest.Add(item); - src.Delete(i); - return; - } -} - -static void RemoveOneItem(CRecordVector &src, UInt32 item) -{ - for (int i = 0; i < src.Size(); i++) - if (src[i] == item) - { - src.Delete(i); - return; - } -} - -static void InsertToHead(CRecordVector &dest, UInt32 item) -{ - for (int i = 0; i < dest.Size(); i++) - if (dest[i] == item) - { - dest.Delete(i); - break; - } - dest.Insert(0, item); -} - -void CHandler::FillPopIDs() -{ - _fileInfoPopIDs.Clear(); - - #ifdef _7Z_VOL - if(_volumes.Size() < 1) - return; - const CVolume &volume = _volumes.Front(); - const CArchiveDatabaseEx &_db = volume.Database; - #endif - - CRecordVector fileInfoPopIDs = _db.ArchiveInfo.FileInfoPopIDs; - - RemoveOneItem(fileInfoPopIDs, NID::kEmptyStream); - RemoveOneItem(fileInfoPopIDs, NID::kEmptyFile); - - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kName); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kAnti); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kSize); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kPackInfo); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kCTime); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kMTime); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kATime); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kWinAttributes); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kCRC); - CopyOneItem(fileInfoPopIDs, _fileInfoPopIDs, NID::kComment); - _fileInfoPopIDs += fileInfoPopIDs; - - #ifndef _SFX - _fileInfoPopIDs.Add(97); - _fileInfoPopIDs.Add(98); - _fileInfoPopIDs.Add(99); - #endif - #ifdef _MULTI_PACK - _fileInfoPopIDs.Add(100); - _fileInfoPopIDs.Add(101); - _fileInfoPopIDs.Add(102); - _fileInfoPopIDs.Add(103); - _fileInfoPopIDs.Add(104); - #endif - - #ifndef _SFX - InsertToHead(_fileInfoPopIDs, NID::kMTime); - InsertToHead(_fileInfoPopIDs, NID::kPackInfo); - InsertToHead(_fileInfoPopIDs, NID::kSize); - InsertToHead(_fileInfoPopIDs, NID::kName); - #endif -} - -STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProperties) -{ - *numProperties = _fileInfoPopIDs.Size(); - return S_OK; -} - -STDMETHODIMP CHandler::GetPropertyInfo(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) -{ - if ((int)index >= _fileInfoPopIDs.Size()) - return E_INVALIDARG; - int indexInMap = FindPropInMap(_fileInfoPopIDs[index]); - if (indexInMap == -1) - return E_INVALIDARG; - const STATPROPSTG &srcItem = kPropMap[indexInMap].StatPROPSTG; - *propID = srcItem.propid; - *varType = srcItem.vt; - *name = 0; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.h deleted file mode 100644 index 7b78130ef..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zProperties.h +++ /dev/null @@ -1,22 +0,0 @@ -// 7zProperties.h - -#ifndef __7Z_PROPERTIES_H -#define __7Z_PROPERTIES_H - -#include "../../PropID.h" - -namespace NArchive { -namespace N7z { - -enum -{ - kpidPackedSize0 = kpidUserDefined, - kpidPackedSize1, - kpidPackedSize2, - kpidPackedSize3, - kpidPackedSize4 -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zRegister.cpp deleted file mode 100644 index 4450498f0..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zRegister.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// 7zRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "7zHandler.h" -static IInArchive *CreateArc() { return new NArchive::N7z::CHandler; } -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::N7z::CHandler; } -#else -#define CreateArcOut 0 -#endif - -static CArcInfo g_ArcInfo = - { L"7z", L"7z", 0, 7, {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C}, 6, false, CreateArc, CreateArcOut }; - -REGISTER_ARC(7z) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.cpp deleted file mode 100644 index 58f2ec459..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// 7zSpecStream.cpp - -#include "StdAfx.h" - -#include "7zSpecStream.h" - -STDMETHODIMP CSequentialInStreamSizeCount2::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result = _stream->Read(data, size, &realProcessedSize); - _size += realProcessedSize; - if (processedSize != 0) - *processedSize = realProcessedSize; - return result; -} - -STDMETHODIMP CSequentialInStreamSizeCount2::GetSubStreamSize( - UInt64 subStream, UInt64 *value) -{ - if (_getSubStreamSize == NULL) - return E_NOTIMPL; - return _getSubStreamSize->GetSubStreamSize(subStream, value); -} - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.h deleted file mode 100644 index 0058ac27c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/7zSpecStream.h +++ /dev/null @@ -1,35 +0,0 @@ -// 7zSpecStream.h - -#ifndef __7Z_SPEC_STREAM_H -#define __7Z_SPEC_STREAM_H - -#include "../../IStream.h" -#include "../../ICoder.h" -#include "../../../Common/MyCom.h" - -class CSequentialInStreamSizeCount2: - public ISequentialInStream, - public ICompressGetSubStreamSize, - public CMyUnknownImp -{ - CMyComPtr _stream; - CMyComPtr _getSubStreamSize; - UInt64 _size; -public: - void Init(ISequentialInStream *stream) - { - _stream = stream; - _getSubStreamSize = 0; - _stream.QueryInterface(IID_ICompressGetSubStreamSize, &_getSubStreamSize); - _size = 0; - } - UInt64 GetSize() const { return _size; } - - MY_UNKNOWN_IMP1(ICompressGetSubStreamSize) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - - STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/7z/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/7z/StdAfx.h deleted file mode 100644 index a4e617312..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/7z/StdAfx.h +++ /dev/null @@ -1,9 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" -#include "../../../Common/NewHandler.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/ArchiveExports.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/ArchiveExports.cpp deleted file mode 100644 index 054f1b081..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/ArchiveExports.cpp +++ /dev/null @@ -1,130 +0,0 @@ -// ArchiveExports.cpp - -#include "StdAfx.h" - -#include "../../Common/ComTry.h" -#include "../../Common/Types.h" -#include "../../Windows/PropVariant.h" -#include "../Common/RegisterArc.h" - -#include "IArchive.h" -#include "../ICoder.h" -#include "../IPassword.h" - -static const unsigned int kNumArcsMax = 32; -static unsigned int g_NumArcs = 0; -static const CArcInfo *g_Arcs[kNumArcsMax]; -void RegisterArc(const CArcInfo *arcInfo) -{ - if (g_NumArcs < kNumArcsMax) - g_Arcs[g_NumArcs++] = arcInfo; -} - -DEFINE_GUID(CLSID_CArchiveHandler, -0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x00, 0x00, 0x00); - -#define CLS_ARC_ID_ITEM(cls) ((cls).Data4[5]) - -static inline HRESULT SetPropString(const char *s, unsigned int size, PROPVARIANT *value) -{ - if ((value->bstrVal = ::SysAllocStringByteLen(s, size)) != 0) - value->vt = VT_BSTR; - return S_OK; -} - -static inline HRESULT SetPropGUID(const GUID &guid, PROPVARIANT *value) -{ - return SetPropString((const char *)&guid, sizeof(GUID), value); -} - -int FindFormatCalssId(const GUID *clsID) -{ - GUID cls = *clsID; - CLS_ARC_ID_ITEM(cls) = 0; - if (cls != CLSID_CArchiveHandler) - return -1; - Byte id = CLS_ARC_ID_ITEM(*clsID); - for (unsigned i = 0; i < g_NumArcs; i++) - if (g_Arcs[i]->ClassId == id) - return (int)i; - return -1; -} - -STDAPI CreateArchiver(const GUID *clsid, const GUID *iid, void **outObject) -{ - COM_TRY_BEGIN - { - int needIn = (*iid == IID_IInArchive); - int needOut = (*iid == IID_IOutArchive); - if (!needIn && !needOut) - return E_NOINTERFACE; - int formatIndex = FindFormatCalssId(clsid); - if (formatIndex < 0) - return CLASS_E_CLASSNOTAVAILABLE; - - const CArcInfo &arc = *g_Arcs[formatIndex]; - if (needIn) - { - *outObject = arc.CreateInArchive(); - ((IInArchive *)*outObject)->AddRef(); - } - else - { - if (!arc.CreateOutArchive) - return CLASS_E_CLASSNOTAVAILABLE; - *outObject = arc.CreateOutArchive(); - ((IOutArchive *)*outObject)->AddRef(); - } - } - COM_TRY_END - return S_OK; -} - -STDAPI GetHandlerProperty2(UInt32 formatIndex, PROPID propID, PROPVARIANT *value) -{ - if (formatIndex >= g_NumArcs) - return E_INVALIDARG; - const CArcInfo &arc = *g_Arcs[formatIndex]; - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case NArchive::kName: - prop = arc.Name; - break; - case NArchive::kClassID: - { - GUID clsId = CLSID_CArchiveHandler; - CLS_ARC_ID_ITEM(clsId) = arc.ClassId; - return SetPropGUID(clsId, value); - } - case NArchive::kExtension: - if (arc.Ext != 0) - prop = arc.Ext; - break; - case NArchive::kAddExtension: - if (arc.AddExt != 0) - prop = arc.AddExt; - break; - case NArchive::kUpdate: - prop = (bool)(arc.CreateOutArchive != 0); - break; - case NArchive::kKeepName: - prop = arc.KeepName; - break; - case NArchive::kStartSignature: - return SetPropString((const char *)arc.Signature, arc.SignatureSize, value); - } - prop.Detach(value); - return S_OK; -} - -STDAPI GetHandlerProperty(PROPID propID, PROPVARIANT *value) -{ - return GetHandlerProperty2(0, propID, value); -} - -STDAPI GetNumberOfFormats(UINT32 *numFormats) -{ - *numFormats = g_NumArcs; - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.cpp deleted file mode 100644 index a797b6ddd..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.cpp +++ /dev/null @@ -1,216 +0,0 @@ -// BZip2Handler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" - -#include "Windows/PropVariant.h" - -#include "../../Common/CreateCoder.h" -#include "../../Common/ProgressUtils.h" -#include "../../Common/StreamUtils.h" - -#include "../Common/DummyOutStream.h" - -#include "BZip2Handler.h" - -using namespace NWindows; - -namespace NArchive { -namespace NBZip2 { - -static const CMethodId kMethodId_BZip2 = 0x040202; - -STATPROPSTG kProps[] = -{ - { NULL, kpidPackSize, VT_UI8} -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = 1; - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) -{ - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case kpidPackSize: prop = _item.PackSize; break; - } - prop.Detach(value); - return S_OK; -} - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) -{ - COM_TRY_BEGIN - try - { - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_streamStartPosition)); - const int kSignatureSize = 3; - Byte buffer[kSignatureSize]; - RINOK(ReadStream_FALSE(stream, buffer, kSignatureSize)); - if (buffer[0] != 'B' || buffer[1] != 'Z' || buffer[2] != 'h') - return S_FALSE; - - UInt64 endPosition; - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPosition)); - _item.PackSize = endPosition - _streamStartPosition; - - _stream = stream; - } - catch(...) - { - return S_FALSE; - } - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - _stream.Release(); - return S_OK; -} - - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 testModeSpec, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - bool allFilesMode = (numItems == UInt32(-1)); - if (!allFilesMode) - { - if (numItems == 0) - return S_OK; - if (numItems != 1) - return E_INVALIDARG; - if (indices[0] != 0) - return E_INVALIDARG; - } - - bool testMode = (testModeSpec != 0); - - extractCallback->SetTotal(_item.PackSize); - - UInt64 currentTotalPacked = 0; - - RINOK(extractCallback->SetCompleted(¤tTotalPacked)); - - CMyComPtr realOutStream; - Int32 askMode; - askMode = testMode ? NExtract::NAskMode::kTest : - NExtract::NAskMode::kExtract; - - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); - - if(!testMode && !realOutStream) - return S_OK; - - - extractCallback->PrepareOperation(askMode); - - CMyComPtr decoder; - HRESULT loadResult = CreateCoder( - EXTERNAL_CODECS_VARS - kMethodId_BZip2, decoder, false); - if (loadResult != S_OK || !decoder) - { - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnSupportedMethod)); - return S_OK; - } - - #ifdef COMPRESS_MT - { - CMyComPtr setCoderMt; - decoder.QueryInterface(IID_ICompressSetCoderMt, &setCoderMt); - if (setCoderMt) - { - RINOK(setCoderMt->SetNumberOfThreads(_numThreads)); - } - } - #endif - - CDummyOutStream *outStreamSpec = new CDummyOutStream; - CMyComPtr outStream(outStreamSpec); - outStreamSpec->SetStream(realOutStream); - outStreamSpec->Init(); - - realOutStream.Release(); - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, true); - - RINOK(_stream->Seek(_streamStartPosition, STREAM_SEEK_SET, NULL)); - - HRESULT result = S_OK; - - bool firstItem = true; - for (;;) - { - lps->InSize = currentTotalPacked; - lps->OutSize = outStreamSpec->GetSize(); - - RINOK(lps->SetCur()); - - const int kSignatureSize = 3; - Byte buffer[kSignatureSize]; - size_t processedSize = kSignatureSize; - RINOK(ReadStream(_stream, buffer, &processedSize)); - if (processedSize != kSignatureSize) - { - if (firstItem) - return E_FAIL; - break; - } - if (buffer[0] != 'B' || buffer[1] != 'Z' || buffer[2] != 'h') - { - if (firstItem) - return E_FAIL; - break; - } - firstItem = false; - - UInt64 dataStartPos; - RINOK(_stream->Seek((UInt64)(Int64)(-3), STREAM_SEEK_CUR, &dataStartPos)); - - result = decoder->Code(_stream, outStream, NULL, NULL, progress); - - if (result != S_OK) - break; - - CMyComPtr getInStreamProcessedSize; - decoder.QueryInterface(IID_ICompressGetInStreamProcessedSize, &getInStreamProcessedSize); - if (!getInStreamProcessedSize) - break; - UInt64 packSize; - RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&packSize)); - UInt64 pos; - RINOK(_stream->Seek(dataStartPos + packSize, STREAM_SEEK_SET, &pos)); - currentTotalPacked = pos - _streamStartPosition; - } - outStream.Release(); - - Int32 retResult; - if (result == S_OK) - retResult = NExtract::NOperationResult::kOK; - else if (result == S_FALSE) - retResult = NExtract::NOperationResult::kDataError; - else - return result; - return extractCallback->SetOperationResult(retResult); - - COM_TRY_END -} - -IMPL_ISetCompressCodecsInfo - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.h b/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.h deleted file mode 100644 index 5d9fb1430..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Handler.h +++ /dev/null @@ -1,70 +0,0 @@ -// BZip2/Handler.h - -#ifndef __BZIP2_HANDLER_H -#define __BZIP2_HANDLER_H - -#include "Common/MyCom.h" -#include "../IArchive.h" -#include "../../Common/CreateCoder.h" -#include "BZip2Item.h" - -#ifdef COMPRESS_MT -#include "../../../Windows/System.h" -#endif - -namespace NArchive { -namespace NBZip2 { - -class CHandler: - public IInArchive, - public IOutArchive, - public ISetProperties, - PUBLIC_ISetCompressCodecsInfo - public CMyUnknownImp -{ - CMyComPtr _stream; - NArchive::NBZip2::CItem _item; - UInt64 _streamStartPosition; - - UInt32 _level; - UInt32 _dicSize; - UInt32 _numPasses; - #ifdef COMPRESS_MT - UInt32 _numThreads; - #endif - - DECL_EXTERNAL_CODECS_VARS - - void InitMethodProperties() - { - _level = 5; - _dicSize = - _numPasses = 0xFFFFFFFF; - #ifdef COMPRESS_MT - _numThreads = NWindows::NSystem::GetNumberOfProcessors();; - #endif - } - -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - MY_QUERYINTERFACE_ENTRY(IOutArchive) - MY_QUERYINTERFACE_ENTRY(ISetProperties) - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) -#ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(;) - - STDMETHOD(SetProperties)(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties); -#endif - - DECL_ISetCompressCodecsInfo - - CHandler() { InitMethodProperties(); } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Item.h b/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Item.h deleted file mode 100644 index f3fce499a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/BZip2Item.h +++ /dev/null @@ -1,20 +0,0 @@ -// Archive/BZip2Item.h - -#ifndef __ARCHIVE_BZIP2_ITEM_H -#define __ARCHIVE_BZIP2_ITEM_H - -namespace NArchive { -namespace NBZip2 { - -struct CItem -{ - UInt64 PackSize; - UInt64 UnPackSize; -}; - -}} - -#endif - - - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/bz2Register.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/bz2Register.cpp deleted file mode 100644 index f4a706ed1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/BZip2/bz2Register.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// BZip2Register.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "BZip2Handler.h" -static IInArchive *CreateArc() { return new NArchive::NBZip2::CHandler; } -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::NBZip2::CHandler; } -#else -#define CreateArcOut 0 -#endif - -static CArcInfo g_ArcInfo = - { L"BZip2", L"bz2 bzip2 tbz2 tbz", L"* * .tar .tar", 2, { 'B', 'Z', 'h' }, 3, true, CreateArc, CreateArcOut }; - -REGISTER_ARC(BZip2) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.cpp deleted file mode 100644 index c4333f234..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.cpp +++ /dev/null @@ -1,121 +0,0 @@ -// CoderMixer2.cpp - -#include "StdAfx.h" - -#include "CoderMixer2.h" - -namespace NCoderMixer { - -CBindReverseConverter::CBindReverseConverter(const CBindInfo &srcBindInfo): - _srcBindInfo(srcBindInfo) -{ - srcBindInfo.GetNumStreams(NumSrcInStreams, _numSrcOutStreams); - - UInt32 j; - for (j = 0; j < NumSrcInStreams; j++) - { - _srcInToDestOutMap.Add(0); - DestOutToSrcInMap.Add(0); - } - for (j = 0; j < _numSrcOutStreams; j++) - { - _srcOutToDestInMap.Add(0); - _destInToSrcOutMap.Add(0); - } - - UInt32 destInOffset = 0; - UInt32 destOutOffset = 0; - UInt32 srcInOffset = NumSrcInStreams; - UInt32 srcOutOffset = _numSrcOutStreams; - - for (int i = srcBindInfo.Coders.Size() - 1; i >= 0; i--) - { - const CCoderStreamsInfo &srcCoderInfo = srcBindInfo.Coders[i]; - - srcInOffset -= srcCoderInfo.NumInStreams; - srcOutOffset -= srcCoderInfo.NumOutStreams; - - UInt32 j; - for (j = 0; j < srcCoderInfo.NumInStreams; j++, destOutOffset++) - { - UInt32 index = srcInOffset + j; - _srcInToDestOutMap[index] = destOutOffset; - DestOutToSrcInMap[destOutOffset] = index; - } - for (j = 0; j < srcCoderInfo.NumOutStreams; j++, destInOffset++) - { - UInt32 index = srcOutOffset + j; - _srcOutToDestInMap[index] = destInOffset; - _destInToSrcOutMap[destInOffset] = index; - } - } -} - -void CBindReverseConverter::CreateReverseBindInfo(CBindInfo &destBindInfo) -{ - destBindInfo.Coders.Clear(); - destBindInfo.BindPairs.Clear(); - destBindInfo.InStreams.Clear(); - destBindInfo.OutStreams.Clear(); - - int i; - for (i = _srcBindInfo.Coders.Size() - 1; i >= 0; i--) - { - const CCoderStreamsInfo &srcCoderInfo = _srcBindInfo.Coders[i]; - CCoderStreamsInfo destCoderInfo; - destCoderInfo.NumInStreams = srcCoderInfo.NumOutStreams; - destCoderInfo.NumOutStreams = srcCoderInfo.NumInStreams; - destBindInfo.Coders.Add(destCoderInfo); - } - for (i = _srcBindInfo.BindPairs.Size() - 1; i >= 0; i--) - { - const CBindPair &srcBindPair = _srcBindInfo.BindPairs[i]; - CBindPair destBindPair; - destBindPair.InIndex = _srcOutToDestInMap[srcBindPair.OutIndex]; - destBindPair.OutIndex = _srcInToDestOutMap[srcBindPair.InIndex]; - destBindInfo.BindPairs.Add(destBindPair); - } - for (i = 0; i < _srcBindInfo.InStreams.Size(); i++) - destBindInfo.OutStreams.Add(_srcInToDestOutMap[_srcBindInfo.InStreams[i]]); - for (i = 0; i < _srcBindInfo.OutStreams.Size(); i++) - destBindInfo.InStreams.Add(_srcOutToDestInMap[_srcBindInfo.OutStreams[i]]); -} - -CCoderInfo2::CCoderInfo2(UInt32 numInStreams, UInt32 numOutStreams): - NumInStreams(numInStreams), - NumOutStreams(numOutStreams) -{ - InSizes.Reserve(NumInStreams); - InSizePointers.Reserve(NumInStreams); - OutSizePointers.Reserve(NumOutStreams); - OutSizePointers.Reserve(NumOutStreams); -} - -static void SetSizes(const UInt64 **srcSizes, CRecordVector &sizes, - CRecordVector &sizePointers, UInt32 numItems) -{ - sizes.Clear(); - sizePointers.Clear(); - for(UInt32 i = 0; i < numItems; i++) - { - if (srcSizes == 0 || srcSizes[i] == NULL) - { - sizes.Add(0); - sizePointers.Add(NULL); - } - else - { - sizes.Add(*srcSizes[i]); - sizePointers.Add(&sizes.Back()); - } - } -} - -void CCoderInfo2::SetCoderInfo(const UInt64 **inSizes, - const UInt64 **outSizes) -{ - SetSizes(inSizes, InSizes, InSizePointers, NumInStreams); - SetSizes(outSizes, OutSizes, OutSizePointers, NumOutStreams); -} - -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.h deleted file mode 100644 index b1893b217..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2.h +++ /dev/null @@ -1,174 +0,0 @@ -// CoderMixer2.h - -#ifndef __CODER_MIXER2_H -#define __CODER_MIXER2_H - -#include "../../../Common/MyVector.h" -#include "../../../Common/Types.h" -#include "../../../Common/MyCom.h" -#include "../../ICoder.h" - -namespace NCoderMixer { - -struct CBindPair -{ - UInt32 InIndex; - UInt32 OutIndex; -}; - -struct CCoderStreamsInfo -{ - UInt32 NumInStreams; - UInt32 NumOutStreams; -}; - -struct CBindInfo -{ - CRecordVector Coders; - CRecordVector BindPairs; - CRecordVector InStreams; - CRecordVector OutStreams; - - void Clear() - { - Coders.Clear(); - BindPairs.Clear(); - InStreams.Clear(); - OutStreams.Clear(); - } - - /* - UInt32 GetCoderStartOutStream(UInt32 coderIndex) const - { - UInt32 numOutStreams = 0; - for (UInt32 i = 0; i < coderIndex; i++) - numOutStreams += Coders[i].NumOutStreams; - return numOutStreams; - } - */ - - - void GetNumStreams(UInt32 &numInStreams, UInt32 &numOutStreams) const - { - numInStreams = 0; - numOutStreams = 0; - for (int i = 0; i < Coders.Size(); i++) - { - const CCoderStreamsInfo &coderStreamsInfo = Coders[i]; - numInStreams += coderStreamsInfo.NumInStreams; - numOutStreams += coderStreamsInfo.NumOutStreams; - } - } - - int FindBinderForInStream(UInt32 inStream) const - { - for (int i = 0; i < BindPairs.Size(); i++) - if (BindPairs[i].InIndex == inStream) - return i; - return -1; - } - int FindBinderForOutStream(UInt32 outStream) const - { - for (int i = 0; i < BindPairs.Size(); i++) - if (BindPairs[i].OutIndex == outStream) - return i; - return -1; - } - - UInt32 GetCoderInStreamIndex(UInt32 coderIndex) const - { - UInt32 streamIndex = 0; - for (UInt32 i = 0; i < coderIndex; i++) - streamIndex += Coders[i].NumInStreams; - return streamIndex; - } - - UInt32 GetCoderOutStreamIndex(UInt32 coderIndex) const - { - UInt32 streamIndex = 0; - for (UInt32 i = 0; i < coderIndex; i++) - streamIndex += Coders[i].NumOutStreams; - return streamIndex; - } - - - void FindInStream(UInt32 streamIndex, UInt32 &coderIndex, - UInt32 &coderStreamIndex) const - { - for (coderIndex = 0; coderIndex < (UInt32)Coders.Size(); coderIndex++) - { - UInt32 curSize = Coders[coderIndex].NumInStreams; - if (streamIndex < curSize) - { - coderStreamIndex = streamIndex; - return; - } - streamIndex -= curSize; - } - throw 1; - } - void FindOutStream(UInt32 streamIndex, UInt32 &coderIndex, - UInt32 &coderStreamIndex) const - { - for (coderIndex = 0; coderIndex < (UInt32)Coders.Size(); coderIndex++) - { - UInt32 curSize = Coders[coderIndex].NumOutStreams; - if (streamIndex < curSize) - { - coderStreamIndex = streamIndex; - return; - } - streamIndex -= curSize; - } - throw 1; - } -}; - -class CBindReverseConverter -{ - UInt32 _numSrcOutStreams; - NCoderMixer::CBindInfo _srcBindInfo; - CRecordVector _srcInToDestOutMap; - CRecordVector _srcOutToDestInMap; - CRecordVector _destInToSrcOutMap; -public: - UInt32 NumSrcInStreams; - CRecordVector DestOutToSrcInMap; - - CBindReverseConverter(const NCoderMixer::CBindInfo &srcBindInfo); - void CreateReverseBindInfo(NCoderMixer::CBindInfo &destBindInfo); -}; - -struct CCoderInfo2 -{ - CMyComPtr Coder; - CMyComPtr Coder2; - UInt32 NumInStreams; - UInt32 NumOutStreams; - - CRecordVector InSizes; - CRecordVector OutSizes; - CRecordVector InSizePointers; - CRecordVector OutSizePointers; - - CCoderInfo2(UInt32 numInStreams, UInt32 numOutStreams); - void SetCoderInfo(const UInt64 **inSizes, const UInt64 **outSizes); - - HRESULT QueryInterface(REFGUID iid, void** pp) const - { - IUnknown *p = Coder ? (IUnknown *)Coder : (IUnknown *)Coder2; - return p->QueryInterface(iid, pp); - } -}; - -class CCoderMixer2 -{ -public: - virtual HRESULT SetBindInfo(const CBindInfo &bindInfo) = 0; - virtual void ReInit() = 0; - virtual void SetCoderInfo(UInt32 coderIndex, const UInt64 **inSizes, const UInt64 **outSizes) = 0; -}; - -} -#endif - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.cpp deleted file mode 100644 index f3bea728d..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.cpp +++ /dev/null @@ -1,230 +0,0 @@ -// CoderMixer2MT.cpp - -#include "StdAfx.h" - -#include "CoderMixer2MT.h" - -namespace NCoderMixer { - -CCoder2::CCoder2(UInt32 numInStreams, UInt32 numOutStreams): - CCoderInfo2(numInStreams, numOutStreams) -{ - InStreams.Reserve(NumInStreams); - InStreamPointers.Reserve(NumInStreams); - OutStreams.Reserve(NumOutStreams); - OutStreamPointers.Reserve(NumOutStreams); -} - -void CCoder2::Execute() { Code(NULL); } - -void CCoder2::Code(ICompressProgressInfo *progress) -{ - InStreamPointers.Clear(); - OutStreamPointers.Clear(); - UInt32 i; - for (i = 0; i < NumInStreams; i++) - { - if (InSizePointers[i] != NULL) - InSizePointers[i] = &InSizes[i]; - InStreamPointers.Add((ISequentialInStream *)InStreams[i]); - } - for (i = 0; i < NumOutStreams; i++) - { - if (OutSizePointers[i] != NULL) - OutSizePointers[i] = &OutSizes[i]; - OutStreamPointers.Add((ISequentialOutStream *)OutStreams[i]); - } - if (Coder) - Result = Coder->Code(InStreamPointers[0], OutStreamPointers[0], - InSizePointers[0], OutSizePointers[0], progress); - else - Result = Coder2->Code(&InStreamPointers.Front(), &InSizePointers.Front(), NumInStreams, - &OutStreamPointers.Front(), &OutSizePointers.Front(), NumOutStreams, progress); - { - int i; - for (i = 0; i < InStreams.Size(); i++) - InStreams[i].Release(); - for (i = 0; i < OutStreams.Size(); i++) - OutStreams[i].Release(); - } -} - -static void SetSizes(const UInt64 **srcSizes, CRecordVector &sizes, - CRecordVector &sizePointers, UInt32 numItems) -{ - sizes.Clear(); - sizePointers.Clear(); - for(UInt32 i = 0; i < numItems; i++) - { - if (srcSizes == 0 || srcSizes[i] == NULL) - { - sizes.Add(0); - sizePointers.Add(NULL); - } - else - { - sizes.Add(*srcSizes[i]); - sizePointers.Add(&sizes.Back()); - } - } -} - - -void CCoder2::SetCoderInfo(const UInt64 **inSizes, const UInt64 **outSizes) -{ - SetSizes(inSizes, InSizes, InSizePointers, NumInStreams); - SetSizes(outSizes, OutSizes, OutSizePointers, NumOutStreams); -} - -////////////////////////////////////// -// CCoderMixer2MT - -HRESULT CCoderMixer2MT::SetBindInfo(const CBindInfo &bindInfo) -{ - _bindInfo = bindInfo; - _streamBinders.Clear(); - for(int i = 0; i < _bindInfo.BindPairs.Size(); i++) - { - _streamBinders.Add(CStreamBinder()); - RINOK(_streamBinders.Back().CreateEvents()); - } - return S_OK; -} - -void CCoderMixer2MT::AddCoderCommon() -{ - const CCoderStreamsInfo &c = _bindInfo.Coders[_coders.Size()]; - CCoder2 threadCoderInfo(c.NumInStreams, c.NumOutStreams); - _coders.Add(threadCoderInfo); -} - -void CCoderMixer2MT::AddCoder(ICompressCoder *coder) -{ - AddCoderCommon(); - _coders.Back().Coder = coder; -} - -void CCoderMixer2MT::AddCoder2(ICompressCoder2 *coder) -{ - AddCoderCommon(); - _coders.Back().Coder2 = coder; -} - - -void CCoderMixer2MT::ReInit() -{ - for(int i = 0; i < _streamBinders.Size(); i++) - _streamBinders[i].ReInit(); -} - - -HRESULT CCoderMixer2MT::Init(ISequentialInStream **inStreams, ISequentialOutStream **outStreams) -{ - /* - if (_coders.Size() != _bindInfo.Coders.Size()) - throw 0; - */ - int i; - for(i = 0; i < _coders.Size(); i++) - { - CCoder2 &coderInfo = _coders[i]; - const CCoderStreamsInfo &coderStreamsInfo = _bindInfo.Coders[i]; - coderInfo.InStreams.Clear(); - UInt32 j; - for(j = 0; j < coderStreamsInfo.NumInStreams; j++) - coderInfo.InStreams.Add(NULL); - coderInfo.OutStreams.Clear(); - for(j = 0; j < coderStreamsInfo.NumOutStreams; j++) - coderInfo.OutStreams.Add(NULL); - } - - for(i = 0; i < _bindInfo.BindPairs.Size(); i++) - { - const CBindPair &bindPair = _bindInfo.BindPairs[i]; - UInt32 inCoderIndex, inCoderStreamIndex; - UInt32 outCoderIndex, outCoderStreamIndex; - _bindInfo.FindInStream(bindPair.InIndex, inCoderIndex, inCoderStreamIndex); - _bindInfo.FindOutStream(bindPair.OutIndex, outCoderIndex, outCoderStreamIndex); - - _streamBinders[i].CreateStreams( - &_coders[inCoderIndex].InStreams[inCoderStreamIndex], - &_coders[outCoderIndex].OutStreams[outCoderStreamIndex]); - } - - for(i = 0; i < _bindInfo.InStreams.Size(); i++) - { - UInt32 inCoderIndex, inCoderStreamIndex; - _bindInfo.FindInStream(_bindInfo.InStreams[i], inCoderIndex, inCoderStreamIndex); - _coders[inCoderIndex].InStreams[inCoderStreamIndex] = inStreams[i]; - } - - for(i = 0; i < _bindInfo.OutStreams.Size(); i++) - { - UInt32 outCoderIndex, outCoderStreamIndex; - _bindInfo.FindOutStream(_bindInfo.OutStreams[i], outCoderIndex, outCoderStreamIndex); - _coders[outCoderIndex].OutStreams[outCoderStreamIndex] = outStreams[i]; - } - return S_OK; -} - -HRESULT CCoderMixer2MT::ReturnIfError(HRESULT code) -{ - for (int i = 0; i < _coders.Size(); i++) - if (_coders[i].Result == code) - return code; - return S_OK; -} - -STDMETHODIMP CCoderMixer2MT::Code(ISequentialInStream **inStreams, - const UInt64 ** /* inSizes */, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 ** /* outSizes */, - UInt32 numOutStreams, - ICompressProgressInfo *progress) -{ - if (numInStreams != (UInt32)_bindInfo.InStreams.Size() || - numOutStreams != (UInt32)_bindInfo.OutStreams.Size()) - return E_INVALIDARG; - - Init(inStreams, outStreams); - - int i; - for (i = 0; i < _coders.Size(); i++) - if (i != _progressCoderIndex) - { - RINOK(_coders[i].Create()); - } - - for (i = 0; i < _coders.Size(); i++) - if (i != _progressCoderIndex) - _coders[i].Start(); - - _coders[_progressCoderIndex].Code(progress); - - for (i = 0; i < _coders.Size(); i++) - if (i != _progressCoderIndex) - _coders[i].WaitFinish(); - - RINOK(ReturnIfError(E_ABORT)); - RINOK(ReturnIfError(E_OUTOFMEMORY)); - - for (i = 0; i < _coders.Size(); i++) - { - HRESULT result = _coders[i].Result; - if (result != S_OK && result != E_FAIL && result != S_FALSE) - return result; - } - - RINOK(ReturnIfError(S_FALSE)); - - for (i = 0; i < _coders.Size(); i++) - { - HRESULT result = _coders[i].Result; - if (result != S_OK) - return result; - } - return S_OK; -} - -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.h deleted file mode 100644 index acecc390f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/CoderMixer2MT.h +++ /dev/null @@ -1,80 +0,0 @@ -// CoderMixer2MT.h - -#ifndef __CODER_MIXER2_MT_H -#define __CODER_MIXER2_MT_H - -#include "CoderMixer2.h" -#include "../../../Common/MyCom.h" -#include "../../Common/StreamBinder.h" -#include "../../Common/VirtThread.h" - -namespace NCoderMixer { - -struct CCoder2: public CCoderInfo2, public CVirtThread -{ - HRESULT Result; - CObjectVector< CMyComPtr > InStreams; - CObjectVector< CMyComPtr > OutStreams; - CRecordVector InStreamPointers; - CRecordVector OutStreamPointers; - - CCoder2(UInt32 numInStreams, UInt32 numOutStreams); - void SetCoderInfo(const UInt64 **inSizes, const UInt64 **outSizes); - virtual void Execute(); - void Code(ICompressProgressInfo *progress); -}; - - -/* - SetBindInfo() - for each coder - AddCoder[2]() - SetProgressIndex(UInt32 coderIndex); - - for each file - { - ReInit() - for each coder - SetCoderInfo - Code - } -*/ - -class CCoderMixer2MT: - public ICompressCoder2, - public CCoderMixer2, - public CMyUnknownImp -{ - CBindInfo _bindInfo; - CObjectVector _streamBinders; - int _progressCoderIndex; - - void AddCoderCommon(); - HRESULT Init(ISequentialInStream **inStreams, ISequentialOutStream **outStreams); - HRESULT ReturnIfError(HRESULT code); -public: - CObjectVector _coders; - MY_UNKNOWN_IMP - - STDMETHOD(Code)(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress); - - HRESULT SetBindInfo(const CBindInfo &bindInfo); - void AddCoder(ICompressCoder *coder); - void AddCoder2(ICompressCoder2 *coder); - void SetProgressCoderIndex(int coderIndex) { _progressCoderIndex = coderIndex; } - - void ReInit(); - void SetCoderInfo(UInt32 coderIndex, const UInt64 **inSizes, const UInt64 **outSizes) - { _coders[coderIndex].SetCoderInfo(inSizes, outSizes); } - UInt64 GetWriteProcessedSize(UInt32 binderIndex) const - { return _streamBinders[binderIndex].ProcessedSize; } -}; - -} -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.cpp deleted file mode 100644 index 237e01e59..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// DummyOutStream.cpp - -#include "StdAfx.h" - -#include "DummyOutStream.h" - -STDMETHODIMP CDummyOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result; - if(!_stream) - { - realProcessedSize = size; - result = S_OK; - } - else - result = _stream->Write(data, size, &realProcessedSize); - _size += realProcessedSize; - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.h deleted file mode 100644 index c993bb3dd..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/DummyOutStream.h +++ /dev/null @@ -1,24 +0,0 @@ -// DummyOutStream.h - -#ifndef __DUMMYOUTSTREAM_H -#define __DUMMYOUTSTREAM_H - -#include "../../IStream.h" -#include "Common/MyCom.h" - -class CDummyOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; -public: - void SetStream(ISequentialOutStream *outStream) { _stream = outStream; } - void ReleaseStream() { _stream.Release(); } - void Init() { _size = 0; } - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - UInt64 GetSize() const { return _size; } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.cpp deleted file mode 100644 index ad04bfcb7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// FindSignature.cpp - -#include "StdAfx.h" - -#include "Common/Buffer.h" - -#include "FindSignature.h" - -#include "../../Common/StreamUtils.h" - -HRESULT FindSignatureInStream(ISequentialInStream *stream, - const Byte *signature, unsigned signatureSize, - const UInt64 *limit, UInt64 &resPos) -{ - resPos = 0; - CByteBuffer byteBuffer2; - byteBuffer2.SetCapacity(signatureSize); - RINOK(ReadStream_FALSE(stream, byteBuffer2, signatureSize)); - - if (memcmp(byteBuffer2, signature, signatureSize) == 0) - return S_OK; - - const UInt32 kBufferSize = (1 << 16); - CByteBuffer byteBuffer; - byteBuffer.SetCapacity(kBufferSize); - Byte *buffer = byteBuffer; - UInt32 numPrevBytes = signatureSize - 1; - memcpy(buffer, (const Byte *)byteBuffer2 + 1, numPrevBytes); - resPos = 1; - for (;;) - { - if (limit != NULL) - if (resPos > *limit) - return S_FALSE; - do - { - UInt32 numReadBytes = kBufferSize - numPrevBytes; - UInt32 processedSize; - RINOK(stream->Read(buffer + numPrevBytes, numReadBytes, &processedSize)); - numPrevBytes += processedSize; - if (processedSize == 0) - return S_FALSE; - } - while (numPrevBytes < signatureSize); - UInt32 numTests = numPrevBytes - signatureSize + 1; - for (UInt32 pos = 0; pos < numTests; pos++) - { - Byte b = signature[0]; - for (; buffer[pos] != b && pos < numTests; pos++); - if (pos == numTests) - break; - if (memcmp(buffer + pos, signature, signatureSize) == 0) - { - resPos += pos; - return S_OK; - } - } - resPos += numTests; - numPrevBytes -= numTests; - memmove(buffer, buffer + numTests, numPrevBytes); - } -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.h deleted file mode 100644 index f801d9860..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/FindSignature.h +++ /dev/null @@ -1,12 +0,0 @@ -// FindSignature.h - -#ifndef __FINDSIGNATURE_H -#define __FINDSIGNATURE_H - -#include "../../IStream.h" - -HRESULT FindSignatureInStream(ISequentialInStream *stream, - const Byte *signature, unsigned signatureSize, - const UInt64 *limit, UInt64 &resPos); - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.cpp deleted file mode 100644 index 4b87a43c0..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// InStreamWithCRC.cpp - -#include "StdAfx.h" - -#include "InStreamWithCRC.h" - -STDMETHODIMP CSequentialInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result = _stream->Read(data, size, &realProcessedSize); - _size += realProcessedSize; - if (size > 0 && realProcessedSize == 0) - _wasFinished = true; - _crc = CrcUpdate(_crc, data, realProcessedSize); - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} - -STDMETHODIMP CInStreamWithCRC::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result = _stream->Read(data, size, &realProcessedSize); - if (size > 0 && realProcessedSize == 0) - _wasFinished = true; - _size += realProcessedSize; - _crc = CrcUpdate(_crc, data, realProcessedSize); - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} - -STDMETHODIMP CInStreamWithCRC::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) -{ - if (seekOrigin != STREAM_SEEK_SET || offset != 0) - return E_FAIL; - _size = 0; - _crc = CRC_INIT_VAL; - return _stream->Seek(offset, seekOrigin, newPosition); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.h deleted file mode 100644 index d73f658e3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/InStreamWithCRC.h +++ /dev/null @@ -1,69 +0,0 @@ -// InStreamWithCRC.h - -#ifndef __INSTREAMWITHCRC_H -#define __INSTREAMWITHCRC_H - -#include "../../../Common/MyCom.h" -#include "../../IStream.h" - -extern "C" -{ -#include "../../../../C/7zCrc.h" -} - -class CSequentialInStreamWithCRC: - public ISequentialInStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); -private: - CMyComPtr _stream; - UInt64 _size; - UInt32 _crc; - bool _wasFinished; -public: - void SetStream(ISequentialInStream *stream) { _stream = stream; } - void Init() - { - _size = 0; - _wasFinished = false; - _crc = CRC_INIT_VAL; - } - void ReleaseStream() { _stream.Release(); } - UInt32 GetCRC() const { return CRC_GET_DIGEST(_crc); } - UInt64 GetSize() const { return _size; } - bool WasFinished() const { return _wasFinished; } -}; - -class CInStreamWithCRC: - public IInStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP1(IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); -private: - CMyComPtr _stream; - UInt64 _size; - UInt32 _crc; - bool _wasFinished; -public: - void SetStream(IInStream *stream) { _stream = stream; } - void Init() - { - _size = 0; - _wasFinished = false; - _crc = CRC_INIT_VAL; - } - void ReleaseStream() { _stream.Release(); } - UInt32 GetCRC() const { return CRC_GET_DIGEST(_crc); } - UInt64 GetSize() const { return _size; } - bool WasFinished() const { return _wasFinished; } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.cpp deleted file mode 100644 index b4fee7c06..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// Archive/Common/ItemNameUtils.cpp - -#include "StdAfx.h" - -#include "ItemNameUtils.h" - -namespace NArchive { -namespace NItemName { - -static const wchar_t kOSDirDelimiter = WCHAR_PATH_SEPARATOR; -static const wchar_t kDirDelimiter = L'/'; - -UString MakeLegalName(const UString &name) -{ - UString zipName = name; - zipName.Replace(kOSDirDelimiter, kDirDelimiter); - return zipName; -} - -UString GetOSName(const UString &name) -{ - UString newName = name; - newName.Replace(kDirDelimiter, kOSDirDelimiter); - return newName; -} - -UString GetOSName2(const UString &name) -{ - if (name.IsEmpty()) - return UString(); - UString newName = GetOSName(name); - if (newName[newName.Length() - 1] == kOSDirDelimiter) - newName.Delete(newName.Length() - 1); - return newName; -} - -bool HasTailSlash(const AString &name, UINT codePage) -{ - if (name.IsEmpty()) - return false; - LPCSTR prev = - #ifdef _WIN32 - CharPrevExA((WORD)codePage, name, &name[name.Length()], 0); - #else - (LPCSTR)(name) + (name.Length() - 1); - #endif - return (*prev == '/'); -} - -#ifndef _WIN32 -UString WinNameToOSName(const UString &name) -{ - UString newName = name; - newName.Replace(L'\\', kOSDirDelimiter); - return newName; -} -#endif - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.h deleted file mode 100644 index 8b91d1c68..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ItemNameUtils.h +++ /dev/null @@ -1,24 +0,0 @@ -// Archive/Common/ItemNameUtils.h - -#ifndef __ARCHIVE_ITEMNAMEUTILS_H -#define __ARCHIVE_ITEMNAMEUTILS_H - -#include "../../../Common/MyString.h" - -namespace NArchive { -namespace NItemName { - - UString MakeLegalName(const UString &name); - UString GetOSName(const UString &name); - UString GetOSName2(const UString &name); - bool HasTailSlash(const AString &name, UINT codePage); - - #ifdef _WIN32 - inline UString WinNameToOSName(const UString &name) { return name; } - #else - UString WinNameToOSName(const UString &name); - #endif - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.cpp deleted file mode 100644 index 33bb91ed8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.cpp +++ /dev/null @@ -1,201 +0,0 @@ -// MultiStream.cpp - -#include "StdAfx.h" - -#include "MultiStream.h" - -STDMETHODIMP CMultiStream::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - if(processedSize != NULL) - *processedSize = 0; - while(_streamIndex < Streams.Size() && size > 0) - { - CSubStreamInfo &s = Streams[_streamIndex]; - if (_pos == s.Size) - { - _streamIndex++; - _pos = 0; - continue; - } - RINOK(s.Stream->Seek(s.Pos + _pos, STREAM_SEEK_SET, 0)); - UInt32 sizeToRead = UInt32(MyMin((UInt64)size, s.Size - _pos)); - UInt32 realProcessed; - HRESULT result = s.Stream->Read(data, sizeToRead, &realProcessed); - data = (void *)((Byte *)data + realProcessed); - size -= realProcessed; - if(processedSize != NULL) - *processedSize += realProcessed; - _pos += realProcessed; - _seekPos += realProcessed; - RINOK(result); - break; - } - return S_OK; -} - -STDMETHODIMP CMultiStream::Seek(Int64 offset, UInt32 seekOrigin, - UInt64 *newPosition) -{ - UInt64 newPos; - switch(seekOrigin) - { - case STREAM_SEEK_SET: - newPos = offset; - break; - case STREAM_SEEK_CUR: - newPos = _seekPos + offset; - break; - case STREAM_SEEK_END: - newPos = _totalLength + offset; - break; - default: - return STG_E_INVALIDFUNCTION; - } - _seekPos = 0; - for (_streamIndex = 0; _streamIndex < Streams.Size(); _streamIndex++) - { - UInt64 size = Streams[_streamIndex].Size; - if (newPos < _seekPos + size) - { - _pos = newPos - _seekPos; - _seekPos += _pos; - if (newPosition != 0) - *newPosition = newPos; - return S_OK; - } - _seekPos += size; - } - if (newPos == _seekPos) - { - if (newPosition != 0) - *newPosition = newPos; - return S_OK; - } - return E_FAIL; -} - - -/* -class COutVolumeStream: - public ISequentialOutStream, - public CMyUnknownImp -{ - int _volIndex; - UInt64 _volSize; - UInt64 _curPos; - CMyComPtr _volumeStream; - COutArchive _archive; - CCRC _crc; - -public: - MY_UNKNOWN_IMP - - CFileItem _file; - CUpdateOptions _options; - CMyComPtr VolumeCallback; - void Init(IArchiveUpdateCallback2 *volumeCallback, - const UString &name) - { - _file.Name = name; - _file.IsStartPosDefined = true; - _file.StartPos = 0; - - VolumeCallback = volumeCallback; - _volIndex = 0; - _volSize = 0; - } - - HRESULT Flush(); - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -}; - -HRESULT COutVolumeStream::Flush() -{ - if (_volumeStream) - { - _file.UnPackSize = _curPos; - _file.FileCRC = _crc.GetDigest(); - RINOK(WriteVolumeHeader(_archive, _file, _options)); - _archive.Close(); - _volumeStream.Release(); - _file.StartPos += _file.UnPackSize; - } - return S_OK; -} -*/ - -/* -STDMETHODIMP COutMultiStream::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - if(processedSize != NULL) - *processedSize = 0; - while(size > 0) - { - if (_streamIndex >= Streams.Size()) - { - CSubStreamInfo subStream; - RINOK(VolumeCallback->GetVolumeSize(Streams.Size(), &subStream.Size)); - RINOK(VolumeCallback->GetVolumeStream(Streams.Size(), &subStream.Stream)); - subStream.Pos = 0; - Streams.Add(subStream); - continue; - } - CSubStreamInfo &subStream = Streams[_streamIndex]; - if (_offsetPos >= subStream.Size) - { - _offsetPos -= subStream.Size; - _streamIndex++; - continue; - } - if (_offsetPos != subStream.Pos) - { - CMyComPtr outStream; - RINOK(subStream.Stream.QueryInterface(IID_IOutStream, &outStream)); - RINOK(outStream->Seek(_offsetPos, STREAM_SEEK_SET, NULL)); - subStream.Pos = _offsetPos; - } - - UInt32 curSize = (UInt32)MyMin((UInt64)size, subStream.Size - subStream.Pos); - UInt32 realProcessed; - RINOK(subStream.Stream->Write(data, curSize, &realProcessed)); - data = (void *)((Byte *)data + realProcessed); - size -= realProcessed; - subStream.Pos += realProcessed; - _offsetPos += realProcessed; - _absPos += realProcessed; - if (_absPos > _length) - _length = _absPos; - if(processedSize != NULL) - *processedSize += realProcessed; - if (subStream.Pos == subStream.Size) - { - _streamIndex++; - _offsetPos = 0; - } - if (realProcessed != curSize && realProcessed == 0) - return E_FAIL; - } - return S_OK; -} - -STDMETHODIMP COutMultiStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) -{ - if(seekOrigin >= 3) - return STG_E_INVALIDFUNCTION; - switch(seekOrigin) - { - case STREAM_SEEK_SET: - _absPos = offset; - break; - case STREAM_SEEK_CUR: - _absPos += offset; - break; - case STREAM_SEEK_END: - _absPos = _length + offset; - break; - } - _offsetPos = _absPos; - _streamIndex = 0; - return S_OK; -} -*/ diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.h deleted file mode 100644 index 133a06f9f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/MultiStream.h +++ /dev/null @@ -1,76 +0,0 @@ -// MultiStream.h - -#ifndef __MULTISTREAM_H -#define __MULTISTREAM_H - -#include "../../../Common/MyCom.h" -#include "../../../Common/MyVector.h" -#include "../../Archive/IArchive.h" - -class CMultiStream: - public IInStream, - public CMyUnknownImp -{ - int _streamIndex; - UInt64 _pos; - UInt64 _seekPos; - UInt64 _totalLength; -public: - struct CSubStreamInfo - { - CMyComPtr Stream; - UInt64 Pos; - UInt64 Size; - }; - CObjectVector Streams; - void Init() - { - _streamIndex = 0; - _pos = 0; - _seekPos = 0; - _totalLength = 0; - for (int i = 0; i < Streams.Size(); i++) - _totalLength += Streams[i].Size; - } - - MY_UNKNOWN_IMP1(IInStream) - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); -}; - -/* -class COutMultiStream: - public IOutStream, - public CMyUnknownImp -{ - int _streamIndex; // required stream - UInt64 _offsetPos; // offset from start of _streamIndex index - UInt64 _absPos; - UInt64 _length; - - struct CSubStreamInfo - { - CMyComPtr Stream; - UInt64 Size; - UInt64 Pos; - }; - CObjectVector Streams; -public: - CMyComPtr VolumeCallback; - void Init() - { - _streamIndex = 0; - _offsetPos = 0; - _absPos = 0; - _length = 0; - } - - MY_UNKNOWN_IMP1(IOutStream) - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); -}; -*/ - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp deleted file mode 100644 index 37b157d1e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// OutStreamWithCRC.cpp - -#include "StdAfx.h" - -#include "OutStreamWithCRC.h" - -STDMETHODIMP COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result; - if(!_stream) - { - realProcessedSize = size; - result = S_OK; - } - else - result = _stream->Write(data, size, &realProcessedSize); - if (_calculate) - _crc = CrcUpdate(_crc, data, realProcessedSize); - _size += realProcessedSize; - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.h deleted file mode 100644 index 44e5eb24b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/OutStreamWithCRC.h +++ /dev/null @@ -1,38 +0,0 @@ -// OutStreamWithCRC.h - -#ifndef __OUT_STREAM_WITH_CRC_H -#define __OUT_STREAM_WITH_CRC_H - -#include "../../../Common/MyCom.h" -#include "../../IStream.h" - -extern "C" -{ -#include "../../../../C/7zCrc.h" -} - -class COutStreamWithCRC: - public ISequentialOutStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; - UInt32 _crc; - bool _calculate; -public: - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - void SetStream(ISequentialOutStream *stream) { _stream = stream; } - void ReleaseStream() { _stream.Release(); } - void Init(bool calculate = true) - { - _size = 0; - _calculate = calculate; - _crc = CRC_INIT_VAL; - } - void InitCRC() { _crc = CRC_INIT_VAL; } - UInt64 GetSize() const { return _size; } - UInt32 GetCRC() const { return CRC_GET_DIGEST(_crc); } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.cpp deleted file mode 100644 index 5550a23bc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.cpp +++ /dev/null @@ -1,177 +0,0 @@ -// ParseProperties.cpp - -#include "StdAfx.h" - -#include "ParseProperties.h" - -#include "Common/StringToInt.h" -#include "Common/MyCom.h" - -HRESULT ParsePropValue(const UString &name, const PROPVARIANT &prop, UInt32 &resValue) -{ - if (prop.vt == VT_UI4) - { - if (!name.IsEmpty()) - return E_INVALIDARG; - resValue = prop.ulVal; - } - else if (prop.vt == VT_EMPTY) - { - if(!name.IsEmpty()) - { - const wchar_t *start = name; - const wchar_t *end; - UInt64 v = ConvertStringToUInt64(start, &end); - if (end - start != name.Length()) - return E_INVALIDARG; - resValue = (UInt32)v; - } - } - else - return E_INVALIDARG; - return S_OK; -} - -static const int kLogarithmicSizeLimit = 32; -static const wchar_t kByteSymbol = L'B'; -static const wchar_t kKiloByteSymbol = L'K'; -static const wchar_t kMegaByteSymbol = L'M'; - -HRESULT ParsePropDictionaryValue(const UString &srcStringSpec, UInt32 &dicSize) -{ - UString srcString = srcStringSpec; - srcString.MakeUpper(); - - const wchar_t *start = srcString; - const wchar_t *end; - UInt64 number = ConvertStringToUInt64(start, &end); - int numDigits = (int)(end - start); - if (numDigits == 0 || srcString.Length() > numDigits + 1) - return E_INVALIDARG; - if (srcString.Length() == numDigits) - { - if (number >= kLogarithmicSizeLimit) - return E_INVALIDARG; - dicSize = (UInt32)1 << (int)number; - return S_OK; - } - switch (srcString[numDigits]) - { - case kByteSymbol: - if (number >= ((UInt64)1 << kLogarithmicSizeLimit)) - return E_INVALIDARG; - dicSize = (UInt32)number; - break; - case kKiloByteSymbol: - if (number >= ((UInt64)1 << (kLogarithmicSizeLimit - 10))) - return E_INVALIDARG; - dicSize = (UInt32)(number << 10); - break; - case kMegaByteSymbol: - if (number >= ((UInt64)1 << (kLogarithmicSizeLimit - 20))) - return E_INVALIDARG; - dicSize = (UInt32)(number << 20); - break; - default: - return E_INVALIDARG; - } - return S_OK; -} - -HRESULT ParsePropDictionaryValue(const UString &name, const PROPVARIANT &prop, UInt32 &resValue) -{ - if (name.IsEmpty()) - { - if (prop.vt == VT_UI4) - { - UInt32 logDicSize = prop.ulVal; - if (logDicSize >= 32) - return E_INVALIDARG; - resValue = (UInt32)1 << logDicSize; - return S_OK; - } - if (prop.vt == VT_BSTR) - return ParsePropDictionaryValue(prop.bstrVal, resValue); - return E_INVALIDARG; - } - return ParsePropDictionaryValue(name, resValue); -} - -bool StringToBool(const UString &s, bool &res) -{ - if (s.IsEmpty() || s.CompareNoCase(L"ON") == 0 || s.Compare(L"+") == 0) - { - res = true; - return true; - } - if (s.CompareNoCase(L"OFF") == 0 || s.Compare(L"-") == 0) - { - res = false; - return true; - } - return false; -} - -HRESULT SetBoolProperty(bool &dest, const PROPVARIANT &value) -{ - switch(value.vt) - { - case VT_EMPTY: - dest = true; - return S_OK; - case VT_BOOL: - dest = (value.boolVal != VARIANT_FALSE); - return S_OK; - /* - case VT_UI4: - dest = (value.ulVal != 0); - break; - */ - case VT_BSTR: - return StringToBool(value.bstrVal, dest) ? S_OK : E_INVALIDARG; - } - return E_INVALIDARG; -} - -int ParseStringToUInt32(const UString &srcString, UInt32 &number) -{ - const wchar_t *start = srcString; - const wchar_t *end; - UInt64 number64 = ConvertStringToUInt64(start, &end); - if (number64 > 0xFFFFFFFF) - { - number = 0; - return 0; - } - number = (UInt32)number64; - return (int)(end - start); -} - -HRESULT ParseMtProp(const UString &name, const PROPVARIANT &prop, UInt32 defaultNumThreads, UInt32 &numThreads) -{ - if (name.IsEmpty()) - { - switch(prop.vt) - { - case VT_UI4: - numThreads = prop.ulVal; - break; - default: - { - bool val; - RINOK(SetBoolProperty(val, prop)); - numThreads = (val ? defaultNumThreads : 1); - break; - } - } - } - else - { - UInt32 number; - int index = ParseStringToUInt32(name, number); - if (index != name.Length()) - return E_INVALIDARG; - numThreads = number; - } - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.h deleted file mode 100644 index c64fc1ea1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/ParseProperties.h +++ /dev/null @@ -1,18 +0,0 @@ -// ParseProperties.h - -#ifndef __PARSEPROPERTIES_H -#define __PARSEPROPERTIES_H - -#include "Common/MyString.h" -#include "Common/Types.h" - -HRESULT ParsePropValue(const UString &name, const PROPVARIANT &prop, UInt32 &resValue); -HRESULT ParsePropDictionaryValue(const UString &srcStringSpec, UInt32 &dicSize); -HRESULT ParsePropDictionaryValue(const UString &name, const PROPVARIANT &prop, UInt32 &resValue); - -bool StringToBool(const UString &s, bool &res); -HRESULT SetBoolProperty(bool &dest, const PROPVARIANT &value); -int ParseStringToUInt32(const UString &srcString, UInt32 &number); -HRESULT ParseMtProp(const UString &name, const PROPVARIANT &prop, UInt32 defaultNumThreads, UInt32 &numThreads); - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Common/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Common/StdAfx.h deleted file mode 100644 index a4e617312..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Common/StdAfx.h +++ /dev/null @@ -1,9 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" -#include "../../../Common/NewHandler.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/DllExports2.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/DllExports2.cpp deleted file mode 100644 index 7f4764654..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/DllExports2.cpp +++ /dev/null @@ -1,83 +0,0 @@ -// DLLExports.cpp - -#include "StdAfx.h" - -#include "../../Common/MyInitGuid.h" -#include "../../Common/ComTry.h" -#include "../../Common/Types.h" -#include "../../Windows/PropVariant.h" -#if defined(_WIN32) && defined(_7ZIP_LARGE_PAGES) -extern "C" -{ -#include "../../../C/Alloc.h" -} -#endif - -#include "IArchive.h" -#include "../ICoder.h" -#include "../IPassword.h" - -HINSTANCE g_hInstance; -#ifndef _UNICODE -#ifdef _WIN32 -bool g_IsNT = false; -static bool IsItWindowsNT() -{ - OSVERSIONINFO versionInfo; - versionInfo.dwOSVersionInfoSize = sizeof(versionInfo); - if (!::GetVersionEx(&versionInfo)) - return false; - return (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT); -} -#endif -#endif - -//desmume 27-jun-09 - dont want this in a static library -//extern "C" -//BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) -//{ -// if (dwReason == DLL_PROCESS_ATTACH) -// { -// g_hInstance = hInstance; -// #ifndef _UNICODE -// #ifdef _WIN32 -// g_IsNT = IsItWindowsNT(); -// #endif -// #endif -// } -// return TRUE; -//} - -DEFINE_GUID(CLSID_CArchiveHandler, -0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x10, 0x00, 0x00, 0x00); - -static const UInt16 kDecodeId = 0x2790; - -DEFINE_GUID(CLSID_CCodec, -0x23170F69, 0x40C1, kDecodeId, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); - -STDAPI CreateCoder(const GUID *clsid, const GUID *iid, void **outObject); -STDAPI CreateArchiver(const GUID *classID, const GUID *iid, void **outObject); - -STDAPI CreateObject(const GUID *clsid, const GUID *iid, void **outObject) -{ - // COM_TRY_BEGIN - *outObject = 0; - if (*iid == IID_ICompressCoder || *iid == IID_ICompressCoder2 || *iid == IID_ICompressFilter) - { - return CreateCoder(clsid, iid, outObject); - } - else - { - return CreateArchiver(clsid, iid, outObject); - } - // COM_TRY_END -} - -STDAPI SetLargePageMode() -{ - #if defined(_WIN32) && defined(_7ZIP_LARGE_PAGES) - SetLargePageSize(); - #endif - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.cpp deleted file mode 100644 index 01a5c9f99..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.cpp +++ /dev/null @@ -1,284 +0,0 @@ -// GZipHandler.cpp - -#include "StdAfx.h" - -#include "GZipHandler.h" - -#include "Common/Defs.h" -#include "Common/StringConvert.h" -#include "Common/ComTry.h" -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "../../ICoder.h" -#include "../../Common/ProgressUtils.h" -#include "../../Common/CreateCoder.h" -#include "../Common/OutStreamWithCRC.h" - -using namespace NWindows; - -namespace NArchive { -namespace NGZip { - -static const CMethodId kMethodId_Deflate = 0x040108; - -const wchar_t *kHostOS[] = -{ - L"FAT", - L"AMIGA", - L"VMS", - L"Unix", - L"VM_CMS", - L"Atari", // what if it's a minix filesystem? [cjh] - L"HPFS", // filesystem used by OS/2 (and NT 3.x) - L"Mac", - L"Z_System", - L"CPM", - L"TOPS20", // pkzip 2.50 NTFS - L"NTFS", // filesystem used by Windows NT - L"QDOS ", // SMS/QDOS - L"Acorn", // Archimedes Acorn RISC OS - L"VFAT", // filesystem used by Windows 95, NT - L"MVS", - L"BeOS", // hybrid POSIX/database filesystem - // BeBOX or PowerMac - L"Tandem", - L"THEOS" -}; - -static const int kNumHostOSes = sizeof(kHostOS) / sizeof(kHostOS[0]); - -static const wchar_t *kUnknownOS = L"Unknown"; - -/* -enum // PropID -{ - kpidExtraIsPresent = kpidUserDefined, - kpidExtraFlags, - kpidIsText -}; -*/ - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMTime, VT_FILETIME}, - // { NULL, kpidMethod, VT_UI1}, - { NULL, kpidHostOS, VT_BSTR}, - { NULL, kpidCRC, VT_UI4} - // { L"Extra", kpidExtraIsPresent, VT_BOOL} - // { L"Extra flags", kpidExtraFlags, VT_UI1}, - // { L"Is Text", kpidIsText, VT_BOOL}, -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = 1; - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case kpidPath: - if (m_Item.NameIsPresent()) - prop = MultiByteToUnicodeString(m_Item.Name, CP_ACP); - break; - case kpidMTime: - { - FILETIME utcTime; - if (m_Item.Time != 0) - { - NTime::UnixTimeToFileTime((UInt32)m_Item.Time, utcTime); - prop = utcTime; - } - else - { - // utcTime.dwLowDateTime = utcTime.dwHighDateTime = 0; - // prop = utcTime; - } - break; - } - case kpidSize: prop = UInt64(m_Item.UnPackSize32); break; - case kpidPackSize: prop = m_PackSize; break; - case kpidCommented: prop = m_Item.CommentIsPresent(); break; - case kpidHostOS: - prop = (m_Item.HostOS < kNumHostOSes) ? - kHostOS[m_Item.HostOS] : kUnknownOS; - break; - case kpidMethod: prop = m_Item.CompressionMethod; break; - case kpidCRC: prop = m_Item.FileCRC; break; - /* - case kpidExtraFlags: prop = m_Item.ExtraFlags; break; - case kpidIsText: prop = m_Item.IsText(); break; - case kpidExtraIsPresent: prop = m_Item.ExtraFieldIsPresent(); break; - */ - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Open(IInStream *inStream, - const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) -{ - COM_TRY_BEGIN - try - { - CInArchive archive; - RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &m_StreamStartPosition)); - RINOK(archive.ReadHeader(inStream, m_Item)); - m_DataOffset = archive.GetOffset(); - UInt64 newPosition; - RINOK(inStream->Seek(-8, STREAM_SEEK_END, &newPosition)); - m_PackSize = newPosition - (m_StreamStartPosition + m_DataOffset); - if (archive.ReadPostHeader(inStream, m_Item) != S_OK) - return S_FALSE; - m_Stream = inStream; - } - catch(...) - { - return S_FALSE; - } - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - m_Stream.Release(); - return S_OK; -} - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - bool allFilesMode = (numItems == UInt32(-1)); - if (!allFilesMode) - { - if (numItems == 0) - return S_OK; - if (numItems != 1) - return E_INVALIDARG; - if (indices[0] != 0) - return E_INVALIDARG; - } - - bool testMode = (_aTestMode != 0); - - extractCallback->SetTotal(m_PackSize); - - UInt64 currentTotalPacked = 0; - - RINOK(extractCallback->SetCompleted(¤tTotalPacked)); - CMyComPtr realOutStream; - Int32 askMode; - askMode = testMode ? NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); - - if(!testMode && !realOutStream) - return S_OK; - - extractCallback->PrepareOperation(askMode); - - COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC; - CMyComPtr outStream(outStreamSpec); - outStreamSpec->SetStream(realOutStream); - outStreamSpec->Init(); - realOutStream.Release(); - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, true); - - CMyComPtr deflateDecoder; - bool firstItem = true; - RINOK(m_Stream->Seek(m_StreamStartPosition, STREAM_SEEK_SET, NULL)); - Int32 opRes; - for (;;) - { - lps->InSize = currentTotalPacked; - lps->OutSize = outStreamSpec->GetSize(); - - CInArchive archive; - CItem item; - HRESULT result = archive.ReadHeader(m_Stream, item); - if (result != S_OK) - { - if (firstItem) - return E_FAIL; - opRes = NArchive::NExtract::NOperationResult::kOK; - break; - } - firstItem = false; - - UInt64 dataStartPos; - RINOK(m_Stream->Seek(0, STREAM_SEEK_CUR, &dataStartPos)); - - outStreamSpec->InitCRC(); - - if (item.CompressionMethod != NFileHeader::NCompressionMethod::kDeflate) - { - opRes = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - break; - } - - if (!deflateDecoder) - { - RINOK(CreateCoder( - EXTERNAL_CODECS_VARS - kMethodId_Deflate, deflateDecoder, false)); - if (!deflateDecoder) - { - opRes = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - break; - } - } - result = deflateDecoder->Code(m_Stream, outStream, NULL, NULL, progress); - if (result != S_OK) - { - if (result != S_FALSE) - return result; - opRes = NArchive::NExtract::NOperationResult::kDataError; - break; - } - - CMyComPtr getInStreamProcessedSize; - RINOK(deflateDecoder.QueryInterface(IID_ICompressGetInStreamProcessedSize, - &getInStreamProcessedSize)); - UInt64 packSize; - RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(&packSize)); - UInt64 pos; - RINOK(m_Stream->Seek(dataStartPos + packSize, STREAM_SEEK_SET, &pos)); - - currentTotalPacked = pos - m_StreamStartPosition; - - CItem postItem; - if (archive.ReadPostHeader(m_Stream, postItem) != S_OK) - return E_FAIL; - if((outStreamSpec->GetCRC() != postItem.FileCRC)) - { - opRes = NArchive::NExtract::NOperationResult::kCRCError; - break; - } - } - outStream.Release(); - return extractCallback->SetOperationResult(opRes); - COM_TRY_END -} - -IMPL_ISetCompressCodecsInfo - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.h deleted file mode 100644 index 31f5a430f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHandler.h +++ /dev/null @@ -1,65 +0,0 @@ -// GZip/Handler.h - -#ifndef __GZIP_HANDLER_H -#define __GZIP_HANDLER_H - -#include "Common/MyCom.h" - -#include "../IArchive.h" - -#include "../../Common/CreateCoder.h" - -#include "GZipIn.h" -#include "GZipUpdate.h" - -namespace NArchive { -namespace NGZip { - -class CHandler: - public IInArchive, - public IOutArchive, - public ISetProperties, - PUBLIC_ISetCompressCodecsInfo - public CMyUnknownImp -{ -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - MY_QUERYINTERFACE_ENTRY(IOutArchive) - MY_QUERYINTERFACE_ENTRY(ISetProperties) - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) -#ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(;) - - STDMETHOD(SetProperties)(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties); -#endif - - DECL_ISetCompressCodecsInfo - - CHandler() { InitMethodProperties(); } - -private: - NArchive::NGZip::CItem m_Item; - UInt64 m_StreamStartPosition; - UInt64 m_DataOffset; - UInt64 m_PackSize; - CMyComPtr m_Stream; - CCompressionMethodMode m_Method; - UInt32 m_Level; - - DECL_EXTERNAL_CODECS_VARS - - void InitMethodProperties() - { - m_Method.NumMatchFinderCyclesDefined = false; - m_Level = m_Method.NumPasses = m_Method.NumFastBytes = - m_Method.NumMatchFinderCycles = m_Method.Algo = 0xFFFFFFFF; - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.cpp deleted file mode 100644 index 508d6bd5b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// Archive/GZip/Header.h - -#include "StdAfx.h" - -#include "GZipHeader.h" - -namespace NArchive { -namespace NGZip { - -extern UInt16 kSignature = 0x8B1F + 1; - -class CMarkersInitializer -{ -public: - CMarkersInitializer() - { kSignature--; } -} g_MarkerInitializer; - -}} - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.h deleted file mode 100644 index 3e76ad6d2..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipHeader.h +++ /dev/null @@ -1,85 +0,0 @@ -// Archive/GZip/Header.h - -#ifndef __ARCHIVE_GZIP_HEADER_H -#define __ARCHIVE_GZIP_HEADER_H - -#include "Common/Types.h" - -namespace NArchive { -namespace NGZip { - -extern UInt16 kSignature; -static const UInt32 kSignatureSize = 2; - -namespace NFileHeader -{ - /* - struct CBlock - { - UInt16 Id; - Byte CompressionMethod; - Byte Flags; - UInt32 Time; - Byte ExtraFlags; - Byte HostOS; - }; - */ - - namespace NFlags - { - const int kDataIsText = 1 << 0; - const int kHeaderCRCIsPresent = 1 << 1; - const int kExtraIsPresent = 1 << 2; - const int kNameIsPresent = 1 << 3; - const int kComentIsPresent = 1 << 4; - } - - namespace NExtraFlags - { - enum EEnum - { - kMaximum = 2, - kFastest = 4 - }; - } - - namespace NCompressionMethod - { - const Byte kDeflate = 8; - } - - namespace NHostOS - { - enum EEnum - { - kFAT = 0, // filesystem used by MS-DOS, OS/2, Win32 - // pkzip 2.50 (FAT / VFAT / FAT32 file systems) - kAMIGA = 1, - kVMS = 2, // VAX/VMS - kUnix = 3, - kVM_CMS = 4, - kAtari = 5, // what if it's a minix filesystem? [cjh] - kHPFS = 6, // filesystem used by OS/2 (and NT 3.x) - kMac = 7, - kZ_System = 8, - kCPM = 9, - kTOPS20 = 10, // pkzip 2.50 NTFS - kNTFS = 11, // filesystem used by Windows NT - kQDOS = 12, // SMS/QDOS - kAcorn = 13, // Archimedes Acorn RISC OS - kVFAT = 14, // filesystem used by Windows 95, NT - kMVS = 15, - kBeOS = 16, // hybrid POSIX/database filesystem - // BeBOX or PowerMac - kTandem = 17, - kTHEOS = 18, - - kUnknown = 255 - }; - const int kNumHostSystems = 19; - } -} - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.cpp deleted file mode 100644 index b29f10e08..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.cpp +++ /dev/null @@ -1,119 +0,0 @@ -// Archive/GZipIn.cpp - -#include "StdAfx.h" - -#include "GZipIn.h" - -#include "Common/Defs.h" -#include "Common/MyCom.h" -#include "Windows/Defs.h" - -#include "../../Common/StreamUtils.h" - -extern "C" -{ - #include "../../../../C/7zCrc.h" -} - -namespace NArchive { -namespace NGZip { - -HRESULT CInArchive::ReadBytes(ISequentialInStream *inStream, void *data, UInt32 size) -{ - RINOK(ReadStream_FALSE(inStream, data, size)); - m_Position += size; - return S_OK; -} - -HRESULT CInArchive::ReadByte(ISequentialInStream *inStream, Byte &value, UInt32 &crc) -{ - RINOK(ReadBytes(inStream, &value, 1)); - crc = CRC_UPDATE_BYTE(crc, value); - return S_OK; -} - -HRESULT CInArchive::ReadUInt16(ISequentialInStream *inStream, UInt16 &value, UInt32 &crc) -{ - value = 0; - for (int i = 0; i < 2; i++) - { - Byte b; - RINOK(ReadByte(inStream, b, crc)); - value |= (UInt16(b) << (8 * i)); - } - return S_OK; -} - -HRESULT CInArchive::ReadUInt32(ISequentialInStream *inStream, UInt32 &value, UInt32 &crc) -{ - value = 0; - for (int i = 0; i < 4; i++) - { - Byte b; - RINOK(ReadByte(inStream, b, crc)); - value |= (UInt32(b) << (8 * i)); - } - return S_OK; -} - -HRESULT CInArchive::ReadZeroTerminatedString(ISequentialInStream *inStream, AString &resString, UInt32 &crc) -{ - resString.Empty(); - for (;;) - { - Byte c; - RINOK(ReadByte(inStream, c, crc)); - if (c == 0) - return S_OK; - resString += char(c); - } -} - -HRESULT CInArchive::ReadHeader(ISequentialInStream *inStream, CItem &item) -{ - item.Clear(); - m_Position = 0; - - UInt16 signature; - UInt32 crc = CRC_INIT_VAL;; - RINOK(ReadUInt16(inStream, signature, crc)); - if (signature != kSignature) - return S_FALSE; - - RINOK(ReadByte(inStream, item.CompressionMethod, crc)); - RINOK(ReadByte(inStream, item.Flags, crc)); - RINOK(ReadUInt32(inStream, item.Time, crc)); - RINOK(ReadByte(inStream, item.ExtraFlags, crc)); - RINOK(ReadByte(inStream, item.HostOS, crc)); - - if (item.ExtraFieldIsPresent()) - { - UInt16 extraSize; - RINOK(ReadUInt16(inStream, extraSize, crc)); - item.Extra.SetCapacity(extraSize); - RINOK(ReadBytes(inStream, item.Extra, extraSize)); - crc = CrcUpdate(crc, item.Extra, extraSize); - } - if (item.NameIsPresent()) - RINOK(ReadZeroTerminatedString(inStream, item.Name, crc)); - if (item.CommentIsPresent()) - RINOK(ReadZeroTerminatedString(inStream, item.Comment, crc)); - if (item.HeaderCRCIsPresent()) - { - UInt16 headerCRC; - UInt32 dummy = 0; - RINOK(ReadUInt16(inStream, headerCRC, dummy)); - if ((UInt16)CRC_GET_DIGEST(crc) != headerCRC) - return S_FALSE; - } - return S_OK; -} - -HRESULT CInArchive::ReadPostHeader(ISequentialInStream *inStream, CItem &item) -{ - UInt32 dummy = 0; - RINOK(ReadUInt32(inStream, item.FileCRC, dummy)); - return ReadUInt32(inStream, item.UnPackSize32, dummy); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.h deleted file mode 100644 index 1204d667c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipIn.h +++ /dev/null @@ -1,30 +0,0 @@ -// Archive/GZipIn.h - -#ifndef __ARCHIVE_GZIP_IN_H -#define __ARCHIVE_GZIP_IN_H - -#include "GZipHeader.h" -#include "GZipItem.h" -#include "../../IStream.h" - -namespace NArchive { -namespace NGZip { - -class CInArchive -{ - UInt64 m_Position; - - HRESULT ReadBytes(ISequentialInStream *inStream, void *data, UInt32 size); - HRESULT ReadZeroTerminatedString(ISequentialInStream *inStream, AString &resString, UInt32 &crc); - HRESULT ReadByte(ISequentialInStream *inStream, Byte &value, UInt32 &crc); - HRESULT ReadUInt16(ISequentialInStream *inStream, UInt16 &value, UInt32 &crc); - HRESULT ReadUInt32(ISequentialInStream *inStream, UInt32 &value, UInt32 &crc); -public: - HRESULT ReadHeader(ISequentialInStream *inStream, CItem &item); - HRESULT ReadPostHeader(ISequentialInStream *inStream, CItem &item); - UInt64 GetOffset() const { return m_Position; } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipItem.h deleted file mode 100644 index 50eaef8a8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipItem.h +++ /dev/null @@ -1,59 +0,0 @@ -// Archive/GZipItem.h - -#ifndef __ARCHIVE_GZIP_ITEM_H -#define __ARCHIVE_GZIP_ITEM_H - -#include "Common/Types.h" -#include "Common/MyString.h" -#include "Common/Buffer.h" - -namespace NArchive { -namespace NGZip { - -class CItem -{ -private: - bool TestFlag(Byte flag) const { return ((Flags & flag) != 0); } -public: - Byte CompressionMethod; - Byte Flags; - UInt32 Time; - Byte ExtraFlags; - Byte HostOS; - UInt32 FileCRC; - UInt32 UnPackSize32; - - AString Name; - AString Comment; - CByteBuffer Extra; - - bool IsText() const - { return TestFlag(NFileHeader::NFlags::kDataIsText); } - bool HeaderCRCIsPresent() const - { return TestFlag(NFileHeader::NFlags::kHeaderCRCIsPresent); } - bool ExtraFieldIsPresent() const - { return TestFlag(NFileHeader::NFlags::kExtraIsPresent); } - bool NameIsPresent() const - { return TestFlag(NFileHeader::NFlags::kNameIsPresent); } - bool CommentIsPresent() const - { return TestFlag(NFileHeader::NFlags::kComentIsPresent); } - - void SetNameIsPresentFlag(bool nameIsPresent) - { - if (nameIsPresent) - Flags |= NFileHeader::NFlags::kNameIsPresent; - else - Flags &= (~NFileHeader::NFlags::kNameIsPresent); - } - - void Clear() - { - Name.Empty(); - Comment.Empty();; - Extra.SetCapacity(0); - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipRegister.cpp deleted file mode 100644 index 0c1065088..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipRegister.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// GZipRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "GZipHandler.h" -static IInArchive *CreateArc() { return new NArchive::NGZip::CHandler; } -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::NGZip::CHandler; } -#else -#define CreateArcOut 0 -#endif - -static CArcInfo g_ArcInfo = - { L"GZip", L"gz gzip tgz tpz", L"* * .tar .tar", 0xEF, { 0x1F, 0x8B, 8 }, 3, true, CreateArc, CreateArcOut }; - -REGISTER_ARC(GZip) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipUpdate.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipUpdate.h deleted file mode 100644 index 59115ba2d..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/GZipUpdate.h +++ /dev/null @@ -1,39 +0,0 @@ -// GZip/Update.h - -#ifndef __GZIP_UPDATE_H -#define __GZIP_UPDATE_H - -#include "../IArchive.h" - -#include "../../Common/CreateCoder.h" - -#ifndef EXTRACT_ONLY -#include "GZipOut.h" -#endif -#include "GZipItem.h" - -namespace NArchive { -namespace NGZip { - -struct CCompressionMethodMode -{ - UInt32 NumPasses; - UInt32 NumFastBytes; - UInt32 Algo; - bool NumMatchFinderCyclesDefined; - UInt32 NumMatchFinderCycles; -}; - -HRESULT UpdateArchive( - DECL_EXTERNAL_CODECS_LOC_VARS - IInStream *inStream, - UInt64 unpackSize, - ISequentialOutStream *outStream, - const CItem &newItem, - const CCompressionMethodMode &compressionMethod, - int indexInClient, - IArchiveUpdateCallback *updateCallback); - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/GZip/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/GZip/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/IArchive.h b/desmume/src/windows/7z/CPP/7zip/Archive/IArchive.h deleted file mode 100644 index 2ab476324..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/IArchive.h +++ /dev/null @@ -1,237 +0,0 @@ -// IArchive.h - -#ifndef __IARCHIVE_H -#define __IARCHIVE_H - -#include "../IStream.h" -#include "../IProgress.h" -#include "../PropID.h" - -#define ARCHIVE_INTERFACE_SUB(i, base, x) DECL_INTERFACE_SUB(i, base, 6, x) -#define ARCHIVE_INTERFACE(i, x) ARCHIVE_INTERFACE_SUB(i, IUnknown, x) - -namespace NFileTimeType -{ - enum EEnum - { - kWindows, - kUnix, - kDOS - }; -} - -namespace NArchive -{ - enum - { - kName = 0, - kClassID, - kExtension, - kAddExtension, - kUpdate, - kKeepName, - kStartSignature, - kFinishSignature, - kAssociate - }; - - namespace NExtract - { - namespace NAskMode - { - enum - { - kExtract = 0, - kTest, - kSkip - }; - } - namespace NOperationResult - { - enum - { - kOK = 0, - kUnSupportedMethod, - kDataError, - kCRCError - }; - } - } - namespace NUpdate - { - namespace NOperationResult - { - enum - { - kOK = 0, - kError - }; - } - } -} - -#define INTERFACE_IArchiveOpenCallback(x) \ - STDMETHOD(SetTotal)(const UInt64 *files, const UInt64 *bytes) x; \ - STDMETHOD(SetCompleted)(const UInt64 *files, const UInt64 *bytes) x; \ - -ARCHIVE_INTERFACE(IArchiveOpenCallback, 0x10) -{ - INTERFACE_IArchiveOpenCallback(PURE); -}; - - -#define INTERFACE_IArchiveExtractCallback(x) \ - INTERFACE_IProgress(x) \ - /* GetStream OUT: S_OK - OK, S_FALSE - skeep this file */ \ - STDMETHOD(GetStream)(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode) x; \ - STDMETHOD(PrepareOperation)(Int32 askExtractMode) x; \ - STDMETHOD(SetOperationResult)(Int32 resultEOperationResult) x; \ - -ARCHIVE_INTERFACE_SUB(IArchiveExtractCallback, IProgress, 0x20) -{ - INTERFACE_IArchiveExtractCallback(PURE) -}; - - -#define INTERFACE_IArchiveOpenVolumeCallback(x) \ - STDMETHOD(GetProperty)(PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(GetStream)(const wchar_t *name, IInStream **inStream) x; \ - -ARCHIVE_INTERFACE(IArchiveOpenVolumeCallback, 0x30) -{ - INTERFACE_IArchiveOpenVolumeCallback(PURE); -}; - - -ARCHIVE_INTERFACE(IInArchiveGetStream, 0x40) -{ - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream) PURE; -}; - - -ARCHIVE_INTERFACE(IArchiveOpenSetSubArchiveName, 0x50) -{ - STDMETHOD(SetSubArchiveName)(const wchar_t *name) PURE; -}; - - -/* -IInArchive::Extract: - indices must be sorted - numItems = 0xFFFFFFFF means "all files" - testMode != 0 means "test files without writing to outStream" -*/ - -#define INTERFACE_IInArchive(x) \ - STDMETHOD(Open)(IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openArchiveCallback) x; \ - STDMETHOD(Close)() x; \ - STDMETHOD(GetNumberOfItems)(UInt32 *numItems) x; \ - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback) x; \ - STDMETHOD(GetArchiveProperty)(PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(GetNumberOfProperties)(UInt32 *numProperties) x; \ - STDMETHOD(GetPropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; \ - STDMETHOD(GetNumberOfArchiveProperties)(UInt32 *numProperties) x; \ - STDMETHOD(GetArchivePropertyInfo)(UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) x; - -ARCHIVE_INTERFACE(IInArchive, 0x60) -{ - INTERFACE_IInArchive(PURE) - virtual ~IInArchive() {} -}; - - -#define INTERFACE_IArchiveUpdateCallback(x) \ - INTERFACE_IProgress(x); \ - STDMETHOD(GetUpdateItemInfo)(UInt32 index, \ - Int32 *newData, /*1 - new data, 0 - old data */ \ - Int32 *newProperties, /* 1 - new properties, 0 - old properties */ \ - UInt32 *indexInArchive /* -1 if there is no in archive, or if doesn't matter */ \ - ) x; \ - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) x; \ - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **inStream) x; \ - STDMETHOD(SetOperationResult)(Int32 operationResult) x; \ - -ARCHIVE_INTERFACE_SUB(IArchiveUpdateCallback, IProgress, 0x80) -{ - INTERFACE_IArchiveUpdateCallback(PURE); -}; - -#define INTERFACE_IArchiveUpdateCallback2(x) \ - INTERFACE_IArchiveUpdateCallback(x) \ - STDMETHOD(GetVolumeSize)(UInt32 index, UInt64 *size) x; \ - STDMETHOD(GetVolumeStream)(UInt32 index, ISequentialOutStream **volumeStream) x; \ - -ARCHIVE_INTERFACE_SUB(IArchiveUpdateCallback2, IArchiveUpdateCallback, 0x82) -{ - INTERFACE_IArchiveUpdateCallback2(PURE); -}; - - -#ifndef EXTRACT_ONLY -#define INTERFACE_IOutArchive(x) \ - STDMETHOD(UpdateItems)(ISequentialOutStream *outStream, UInt32 numItems, IArchiveUpdateCallback *updateCallback) x; \ - STDMETHOD(GetFileTimeType)(UInt32 *type) x; -#else -#define INTERFACE_IOutArchive(x) -#endif - -ARCHIVE_INTERFACE(IOutArchive, 0xA0) -{ -#ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(PURE) -#endif -}; - - -ARCHIVE_INTERFACE(ISetProperties, 0x03) -{ -#ifndef EXTRACT_ONLY - STDMETHOD(SetProperties)(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties) PURE; -#endif -}; - - -#define IMP_IInArchive_GetProp(k) \ - (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \ - { if(index >= sizeof(k) / sizeof(k[0])) return E_INVALIDARG; \ - const STATPROPSTG &srcItem = k[index]; \ - *propID = srcItem.propid; *varType = srcItem.vt; *name = 0; return S_OK; } \ - -#define IMP_IInArchive_GetProp_WITH_NAME(k) \ - (UInt32 index, BSTR *name, PROPID *propID, VARTYPE *varType) \ - { if(index >= sizeof(k) / sizeof(k[0])) return E_INVALIDARG; \ - const STATPROPSTG &srcItem = k[index]; \ - *propID = srcItem.propid; *varType = srcItem.vt; \ - if (srcItem.lpwstrName == 0) *name = 0; else *name = ::SysAllocString(srcItem.lpwstrName); return S_OK; } \ - -#define IMP_IInArchive_Props \ - STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProperties) \ - { *numProperties = sizeof(kProps) / sizeof(kProps[0]); return S_OK; } \ - STDMETHODIMP CHandler::GetPropertyInfo IMP_IInArchive_GetProp(kProps) - -#define IMP_IInArchive_Props_WITH_NAME \ - STDMETHODIMP CHandler::GetNumberOfProperties(UInt32 *numProperties) \ - { *numProperties = sizeof(kProps) / sizeof(kProps[0]); return S_OK; } \ - STDMETHODIMP CHandler::GetPropertyInfo IMP_IInArchive_GetProp_WITH_NAME(kProps) - - -#define IMP_IInArchive_ArcProps \ - STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProperties) \ - { *numProperties = sizeof(kArcProps) / sizeof(kArcProps[0]); return S_OK; } \ - STDMETHODIMP CHandler::GetArchivePropertyInfo IMP_IInArchive_GetProp(kArcProps) - -#define IMP_IInArchive_ArcProps_WITH_NAME \ - STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProperties) \ - { *numProperties = sizeof(kArcProps) / sizeof(kArcProps[0]); return S_OK; } \ - STDMETHODIMP CHandler::GetArchivePropertyInfo IMP_IInArchive_GetProp_WITH_NAME(kArcProps) - -#define IMP_IInArchive_ArcProps_NO \ - STDMETHODIMP CHandler::GetNumberOfArchiveProperties(UInt32 *numProperties) \ - { *numProperties = 0; return S_OK; } \ - STDMETHODIMP CHandler::GetArchivePropertyInfo(UInt32, BSTR *, PROPID *, VARTYPE *) \ - { return E_NOTIMPL; } \ - STDMETHODIMP CHandler::GetArchiveProperty(PROPID, PROPVARIANT *value) \ - { value->vt = VT_EMPTY; return S_OK; } - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.cpp deleted file mode 100644 index 0afeb7102..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// LzhCRC.cpp - -#include "StdAfx.h" - -#include "LzhCRC.h" - -namespace NArchive { -namespace NLzh { - -static const UInt16 kCRCPoly = 0xA001; - -UInt16 CCRC::Table[256]; - -void CCRC::InitTable() -{ - for (UInt32 i = 0; i < 256; i++) - { - UInt32 r = i; - for (int j = 0; j < 8; j++) - if (r & 1) - r = (r >> 1) ^ kCRCPoly; - else - r >>= 1; - CCRC::Table[i] = (UInt16)r; - } -} - -class CCRCTableInit -{ -public: - CCRCTableInit() { CCRC::InitTable(); } -} g_CRCTableInit; - -void CCRC::Update(const void *data, size_t size) -{ - UInt16 v = _value; - const Byte *p = (const Byte *)data; - for (; size > 0; size--, p++) - v = (UInt16)(Table[((Byte)(v)) ^ *p] ^ (v >> 8)); - _value = v; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.h deleted file mode 100644 index aaa647baf..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhCRC.h +++ /dev/null @@ -1,27 +0,0 @@ -// LzhCRC.h - -#ifndef __LZH_CRC_H -#define __LZH_CRC_H - -#include -#include "Common/Types.h" - -namespace NArchive { -namespace NLzh { - -class CCRC -{ - UInt16 _value; -public: - static UInt16 Table[256]; - static void InitTable(); - - CCRC(): _value(0){}; - void Init() { _value = 0; } - void Update(const void *data, size_t size); - UInt16 GetDigest() const { return _value; } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.cpp deleted file mode 100644 index b15ffd1bc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.cpp +++ /dev/null @@ -1,387 +0,0 @@ -// LzhHandler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" -#include "Common/Defs.h" -#include "Common/StringConvert.h" - -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "LzhHandler.h" -#include "LzhOutStreamWithCRC.h" - -#include "../../ICoder.h" - -#include "../../Common/LimitedStreams.h" -#include "../../Common/ProgressUtils.h" - -#include "../../Compress/CopyCoder.h" -#include "../../Compress/LzhDecoder.h" - -#include "../Common/ItemNameUtils.h" - -using namespace NWindows; -using namespace NTime; - -namespace NArchive { -namespace NLzh{ - -struct COsPair -{ - Byte Id; - const wchar_t *Name; -}; - -COsPair g_OsPairs[] = -{ - { 'M', L"MS-DOS" }, - { '2', L"OS/2" }, - { '9', L"OS9" }, - { 'K', L"OS/68K" }, - { '3', L"OS/386" }, - { 'H', L"HUMAN" }, - { 'U', L"UNIX" }, - { 'C', L"CP/M" }, - { 'F', L"FLEX" }, - { 'm', L"Mac" }, - { 'R', L"Runser" }, - { 'T', L"TownsOS" }, - { 'X', L"XOSK" }, - { 'w', L"Windows95" }, - { 'W', L"WindowsNT" }, - { 0, L"MS-DOS" }, - { 'J', L"Java VM" } -}; - -const wchar_t *kUnknownOS = L"Unknown"; - -const int kNumHostOSes = sizeof(g_OsPairs) / sizeof(g_OsPairs[0]); - -static const wchar_t *GetOS(Byte osId) -{ - for (int i = 0; i < kNumHostOSes; i++) - if (g_OsPairs[i].Id == osId) - return g_OsPairs[i].Name; - return kUnknownOS; -}; - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidIsDir, VT_BOOL}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMTime, VT_FILETIME}, - { NULL, kpidAttrib, VT_UI4}, - - // { NULL, kpidCommented, VT_BOOL}, - - { NULL, kpidCRC, VT_UI4}, - - { NULL, kpidMethod, VT_UI1}, - { NULL, kpidHostOS, VT_BSTR} - -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -CHandler::CHandler() {} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = _items.Size(); - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - const CItemEx &item = _items[index]; - switch(propID) - { - case kpidPath: - { - UString s = NItemName::WinNameToOSName(MultiByteToUnicodeString(item.GetName(), CP_OEMCP)); - if (!s.IsEmpty()) - { - if (s[s.Length() - 1] == WCHAR_PATH_SEPARATOR) - s.Delete(s.Length() - 1); - prop = s; - } - break; - } - case kpidIsDir: prop = item.IsDir(); break; - case kpidSize: prop = item.Size; break; - case kpidPackSize: prop = item.PackSize; break; - case kpidCRC: prop = (UInt32)item.CRC; break; - case kpidHostOS: prop = GetOS(item.OsId); break; - case kpidMTime: - { - FILETIME utcFileTime; - UInt32 unixTime; - if (item.GetUnixTime(unixTime)) - NTime::UnixTimeToFileTime(unixTime, utcFileTime); - else - { - FILETIME localFileTime; - if (DosTimeToFileTime(item.ModifiedTime, localFileTime)) - { - if (!LocalFileTimeToFileTime(&localFileTime, &utcFileTime)) - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - } - else - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - } - prop = utcFileTime; - break; - } - /* - case kpidAttrib: prop = (UInt32)item.Attributes; break; - case kpidCommented: prop = item.IsCommented(); break; - */ - case kpidMethod: - { - wchar_t method2[kMethodIdSize + 1]; - method2[kMethodIdSize] = 0; - for (int i = 0; i < kMethodIdSize; i++) - method2[i] = item.Method[i]; - prop = method2; - break; - } - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -/* -class CProgressImp: public CProgressVirt -{ -public: - CMyComPtr Callback; - STDMETHOD(SetCompleted)(const UInt64 *numFiles); -}; - -STDMETHODIMP CProgressImp::SetCompleted(const UInt64 *numFiles) -{ - if (Callback) - return Callback->SetCompleted(numFiles, NULL); - return S_OK; -} -*/ - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 * /* maxCheckStartPosition */, IArchiveOpenCallback *callback) -{ - COM_TRY_BEGIN - try - { - _items.Clear(); - CInArchive archive; - - UInt64 endPos = 0; - bool needSetTotal = true; - - if (callback != NULL) - { - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); - } - - RINOK(archive.Open(stream)); - for (;;) - { - CItemEx item; - bool filled; - HRESULT result = archive.GetNextItem(filled, item); - if (result == S_FALSE) - return S_FALSE; - if (result != S_OK) - return S_FALSE; - if (!filled) - break; - _items.Add(item); - archive.Skeep(item.PackSize); - if (callback != NULL) - { - if (needSetTotal) - { - RINOK(callback->SetTotal(NULL, &endPos)); - needSetTotal = false; - } - if (_items.Size() % 100 == 0) - { - UInt64 numFiles = _items.Size(); - UInt64 numBytes = item.DataPosition; - RINOK(callback->SetCompleted(&numFiles, &numBytes)); - } - } - } - if (_items.IsEmpty()) - return S_FALSE; - - _stream = stream; - } - catch(...) - { - return S_FALSE; - } - COM_TRY_END - return S_OK; -} - -STDMETHODIMP CHandler::Close() -{ - _items.Clear(); - _stream.Release(); - return S_OK; -} - - - -////////////////////////////////////// -// CHandler::DecompressItems - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 testModeSpec, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - bool testMode = (testModeSpec != 0); - UInt64 totalUnPacked = 0, totalPacked = 0; - bool allFilesMode = (numItems == UInt32(-1)); - if (allFilesMode) - numItems = _items.Size(); - if(numItems == 0) - return S_OK; - UInt32 i; - for(i = 0; i < numItems; i++) - { - const CItemEx &item = _items[allFilesMode ? i : indices[i]]; - totalUnPacked += item.Size; - totalPacked += item.PackSize; - } - extractCallback->SetTotal(totalUnPacked); - - UInt64 currentTotalUnPacked = 0, currentTotalPacked = 0; - UInt64 currentItemUnPacked, currentItemPacked; - - NCompress::NLzh::NDecoder::CCoder *lzhDecoderSpec = 0; - CMyComPtr lzhDecoder; - CMyComPtr lzh1Decoder; - CMyComPtr arj2Decoder; - - NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder(); - CMyComPtr copyCoder = copyCoderSpec; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; - CMyComPtr inStream(streamSpec); - streamSpec->SetStream(_stream); - - for(i = 0; i < numItems; i++, currentTotalUnPacked += currentItemUnPacked, - currentTotalPacked += currentItemPacked) - { - currentItemUnPacked = 0; - currentItemPacked = 0; - - lps->InSize = currentTotalPacked; - lps->OutSize = currentTotalUnPacked; - RINOK(lps->SetCur()); - - CMyComPtr realOutStream; - Int32 askMode; - askMode = testMode ? NExtract::NAskMode::kTest : - NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; - const CItemEx &item = _items[index]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - - if (item.IsDir()) - { - // if (!testMode) - { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK)); - } - continue; - } - - if (!testMode && (!realOutStream)) - continue; - - RINOK(extractCallback->PrepareOperation(askMode)); - currentItemUnPacked = item.Size; - currentItemPacked = item.PackSize; - - { - COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC; - CMyComPtr outStream(outStreamSpec); - outStreamSpec->Init(realOutStream); - realOutStream.Release(); - - UInt64 pos; - _stream->Seek(item.DataPosition, STREAM_SEEK_SET, &pos); - - streamSpec->Init(item.PackSize); - - HRESULT result = S_OK; - Int32 opRes = NExtract::NOperationResult::kOK; - - if (item.IsCopyMethod()) - { - result = copyCoder->Code(inStream, outStream, NULL, NULL, progress); - if (result == S_OK && copyCoderSpec->TotalSize != item.PackSize) - result = S_FALSE; - } - else if (item.IsLh4GroupMethod()) - { - if (!lzhDecoder) - { - lzhDecoderSpec = new NCompress::NLzh::NDecoder::CCoder; - lzhDecoder = lzhDecoderSpec; - } - lzhDecoderSpec->SetDictionary(item.GetNumDictBits()); - result = lzhDecoder->Code(inStream, outStream, NULL, ¤tItemUnPacked, progress); - } - /* - else if (item.IsLh1GroupMethod()) - { - if (!lzh1Decoder) - { - lzh1DecoderSpec = new NCompress::NLzh1::NDecoder::CCoder; - lzh1Decoder = lzh1DecoderSpec; - } - lzh1DecoderSpec->SetDictionary(item.GetNumDictBits()); - result = lzh1Decoder->Code(inStream, outStream, NULL, ¤tItemUnPacked, progress); - } - */ - else - opRes = NExtract::NOperationResult::kUnSupportedMethod; - - if (opRes == NExtract::NOperationResult::kOK) - { - if (result == S_FALSE) - opRes = NExtract::NOperationResult::kDataError; - else - { - RINOK(result); - if (outStreamSpec->GetCRC() != item.CRC) - opRes = NExtract::NOperationResult::kCRCError; - } - } - outStream.Release(); - RINOK(extractCallback->SetOperationResult(opRes)); - } - } - return S_OK; - COM_TRY_END -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.h deleted file mode 100644 index 6d31df534..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHandler.h +++ /dev/null @@ -1,30 +0,0 @@ -// LzhHandler.h - -#ifndef __LZH_HANDLER_H -#define __LZH_HANDLER_H - -#include "Common/MyCom.h" -#include "../IArchive.h" -#include "LzhIn.h" - -namespace NArchive { -namespace NLzh { - -class CHandler: - public IInArchive, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP1(IInArchive) - - INTERFACE_IInArchive(;) - - CHandler(); -private: - CObjectVector _items; - CMyComPtr _stream; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHeader.h deleted file mode 100644 index 1c758a14b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhHeader.h +++ /dev/null @@ -1,19 +0,0 @@ -// Archive/Lzh/Header.h - -#ifndef __ARCHIVE_LZH_HEADER_H -#define __ARCHIVE_LZH_HEADER_H - -#include "Common/Types.h" - -namespace NArchive { -namespace NLzh { - -const int kMethodIdSize = 5; - -const Byte kExtIdFileName = 0x01; -const Byte kExtIdDirName = 0x02; -const Byte kExtIdUnixTime = 0x54; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.cpp deleted file mode 100644 index 56b62a943..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.cpp +++ /dev/null @@ -1,172 +0,0 @@ -// Archive/LzhIn.cpp - -#include "StdAfx.h" - -#include "Common/StringConvert.h" -#include "Common/Buffer.h" - -#include "../../Common/StreamUtils.h" - -#include "LzhIn.h" - -namespace NArchive { -namespace NLzh { - -HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 &processedSize) -{ - size_t realProcessedSize = size; - RINOK(ReadStream(m_Stream, data, &realProcessedSize)); - processedSize = (UInt32)realProcessedSize; - m_Position += processedSize; - return S_OK; -} - -HRESULT CInArchive::CheckReadBytes(void *data, UInt32 size) -{ - UInt32 processedSize; - RINOK(ReadBytes(data, size, processedSize)); - return (processedSize == size) ? S_OK: S_FALSE; -} - -HRESULT CInArchive::Open(IInStream *inStream) -{ - RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &m_Position)); - m_Stream = inStream; - return S_OK; -} - -static const Byte *ReadUInt32(const Byte *p, UInt32 &v) -{ - v = 0; - for (int i = 0; i < 4; i++) - v |= ((UInt32)(*p++) << (i * 8)); - return p; -} - -static const Byte *ReadUInt16(const Byte *p, UInt16 &v) -{ - v = 0; - for (int i = 0; i < 2; i++) - v |= ((UInt16)(*p++) << (i * 8)); - return p; -} - -static const Byte *ReadString(const Byte *p, size_t size, AString &s) -{ - s.Empty(); - for (size_t i = 0; i < size; i++) - { - char c = p[i]; - if (c == 0) - break; - s += c; - } - return p + size; -} - -static Byte CalcSum(const Byte *data, size_t size) -{ - Byte sum = 0; - for (size_t i = 0; i < size; i++) - sum = (Byte)(sum + data[i]); - return sum; -} - -HRESULT CInArchive::GetNextItem(bool &filled, CItemEx &item) -{ - filled = false; - - UInt32 processedSize; - Byte startHeader[2]; - RINOK(ReadBytes(startHeader, 2, processedSize)) - if (processedSize == 0) - return S_OK; - if (processedSize == 1) - return (startHeader[0] == 0) ? S_OK: S_FALSE; - if (startHeader[0] == 0 && startHeader[1] == 0) - return S_OK; - - Byte header[256]; - const UInt32 kBasicPartSize = 22; - RINOK(ReadBytes(header, kBasicPartSize, processedSize)); - if (processedSize != kBasicPartSize) - return (startHeader[0] == 0) ? S_OK: S_FALSE; - - const Byte *p = header; - memmove(item.Method, p, kMethodIdSize); - if (!item.IsValidMethod()) - return S_OK; - p += kMethodIdSize; - p = ReadUInt32(p, item.PackSize); - p = ReadUInt32(p, item.Size); - p = ReadUInt32(p, item.ModifiedTime); - item.Attributes = *p++; - item.Level = *p++; - if (item.Level > 2) - return S_FALSE; - UInt32 headerSize; - if (item.Level < 2) - { - headerSize = startHeader[0]; - if (headerSize < kBasicPartSize) - return S_FALSE; - UInt32 remain = headerSize - kBasicPartSize; - RINOK(CheckReadBytes(header + kBasicPartSize, remain)); - if (startHeader[1] != CalcSum(header, headerSize)) - return S_FALSE; - size_t nameLength = *p++; - if ((p - header) + nameLength + 2 > headerSize) - return S_FALSE; - p = ReadString(p, nameLength, item.Name); - } - else - headerSize = startHeader[0] | ((UInt32)startHeader[1] << 8); - p = ReadUInt16(p, item.CRC); - if (item.Level != 0) - { - if (item.Level == 2) - { - RINOK(CheckReadBytes(header + kBasicPartSize, 2)); - } - if ((size_t)(p - header) + 3 > headerSize) - return S_FALSE; - item.OsId = *p++; - UInt16 nextSize; - p = ReadUInt16(p, nextSize); - while (nextSize != 0) - { - if (nextSize < 3) - return S_FALSE; - if (item.Level == 1) - { - if (item.PackSize < nextSize) - return S_FALSE; - item.PackSize -= nextSize; - } - CExtension ext; - RINOK(CheckReadBytes(&ext.Type, 1)) - nextSize -= 3; - ext.Data.SetCapacity(nextSize); - RINOK(CheckReadBytes((Byte *)ext.Data, nextSize)) - item.Extensions.Add(ext); - Byte hdr2[2]; - RINOK(CheckReadBytes(hdr2, 2)); - ReadUInt16(hdr2, nextSize); - } - } - item.DataPosition = m_Position; - filled = true; - return S_OK; -} - -HRESULT CInArchive::Skeep(UInt64 numBytes) -{ - UInt64 newPostion; - RINOK(m_Stream->Seek(numBytes, STREAM_SEEK_CUR, &newPostion)); - m_Position += numBytes; - if (m_Position != newPostion) - return E_FAIL; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.h deleted file mode 100644 index a8c639801..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhIn.h +++ /dev/null @@ -1,29 +0,0 @@ -// Archive/LzhIn.h - -#ifndef __ARCHIVE_LZHIN_H -#define __ARCHIVE_LZHIN_H - -#include "Common/MyCom.h" -#include "../../IStream.h" - -#include "LzhItem.h" - -namespace NArchive { -namespace NLzh { - -class CInArchive -{ - CMyComPtr m_Stream; - UInt64 m_Position; - - HRESULT ReadBytes(void *data, UInt32 size, UInt32 &processedSize); - HRESULT CheckReadBytes(void *data, UInt32 size); -public: - HRESULT Open(IInStream *inStream); - HRESULT GetNextItem(bool &filled, CItemEx &itemInfo); - HRESULT Skeep(UInt64 numBytes); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhItem.h deleted file mode 100644 index ca85a5153..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhItem.h +++ /dev/null @@ -1,172 +0,0 @@ -// Archive/LzhItem.h - -#ifndef __ARCHIVE_LZH_ITEM_H -#define __ARCHIVE_LZH_ITEM_H - -#include "Common/Types.h" -#include "Common/MyString.h" -#include "Common/Buffer.h" -#include "LzhHeader.h" - -namespace NArchive { -namespace NLzh { - -struct CExtension -{ - Byte Type; - CByteBuffer Data; - AString GetString() const - { - AString s; - for (size_t i = 0; i < Data.GetCapacity(); i++) - { - char c = (char)Data[i]; - if (c == 0) - break; - s += c; - } - return s; - } -}; - -struct CItem -{ -public: - AString Name; - Byte Method[kMethodIdSize]; - UInt32 PackSize; - UInt32 Size; - UInt32 ModifiedTime; - Byte Attributes; - Byte Level; - UInt16 CRC; - Byte OsId; - CObjectVector Extensions; - - bool IsValidMethod() const { return (Method[0] == '-' && Method[1] == 'l' && Method[4] == '-'); } - bool IsLhMethod() const {return (IsValidMethod() && Method[2] == 'h'); } - bool IsDir() const {return (IsLhMethod() && Method[3] == 'd'); } - - bool IsCopyMethod() const - { - return (IsLhMethod() && Method[3] == '0') || - (IsValidMethod() && Method[2] == 'z' && Method[3] == '4'); - } - - bool IsLh1GroupMethod() const - { - if (!IsLhMethod()) - return false; - switch(Method[3]) - { - case '1': - return true; - } - return false; - } - - bool IsLh4GroupMethod() const - { - if (!IsLhMethod()) - return false; - switch(Method[3]) - { - case '4': - case '5': - case '6': - case '7': - return true; - } - return false; - } - - int GetNumDictBits() const - { - if (!IsLhMethod()) - return 0; - switch(Method[3]) - { - case '1': - return 12; - case '2': - return 13; - case '3': - return 13; - case '4': - return 12; - case '5': - return 13; - case '6': - return 15; - case '7': - return 16; - } - return 0; - } - - int FindExt(Byte type) const - { - for (int i = 0; i < Extensions.Size(); i++) - if (Extensions[i].Type == type) - return i; - return -1; - } - bool GetUnixTime(UInt32 &value) const - { - int index = FindExt(kExtIdUnixTime); - if (index < 0) - { - if (Level == 2) - { - value = ModifiedTime; - return true; - } - return false; - } - const Byte *data = (const Byte *)(Extensions[index].Data); - value = data[0] | - ((UInt32)data[1] << 8) | - ((UInt32)data[2] << 16) | - ((UInt32)data[3] << 24); - return true; - } - - AString GetDirName() const - { - int index = FindExt(kExtIdDirName); - if (index < 0) - return AString(); - return Extensions[index].GetString(); - } - - AString GetFileName() const - { - int index = FindExt(kExtIdFileName); - if (index < 0) - return Name; - return Extensions[index].GetString(); - } - - AString GetName() const - { - AString dirName = GetDirName(); - dirName.Replace((char)(unsigned char)0xFF, '\\'); - if (!dirName.IsEmpty()) - { - char c = dirName[dirName.Length() - 1]; - if (c != '\\') - dirName += '\\'; - } - return dirName + GetFileName(); - } -}; - -class CItemEx: public CItem -{ -public: - UInt64 DataPosition; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.cpp deleted file mode 100644 index 3cd632aa7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// LzhOutStreamWithCRC.cpp - -#include "StdAfx.h" - -#include "LzhOutStreamWithCRC.h" - -namespace NArchive { -namespace NLzh { - -STDMETHODIMP COutStreamWithCRC::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result; - if(!_stream) - { - realProcessedSize = size; - result = S_OK; - } - else - result = _stream->Write(data, size, &realProcessedSize); - _crc.Update(data, realProcessedSize); - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.h deleted file mode 100644 index eee15d0e2..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhOutStreamWithCRC.h +++ /dev/null @@ -1,38 +0,0 @@ -// LzhOutStreamWithCRC.h - -#ifndef __LZHOUTSTREAMWITHCRC_H -#define __LZHOUTSTREAMWITHCRC_H - -#include "LzhCRC.h" -#include "../../../Common/MyCom.h" -#include "../../IStream.h" - -namespace NArchive { -namespace NLzh { - -class COutStreamWithCRC: - public ISequentialOutStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -private: - CCRC _crc; - CMyComPtr _stream; -public: - void Init(ISequentialOutStream *stream) - { - _stream = stream; - _crc.Init(); - } - void ReleaseStream() { _stream.Release(); } - UInt32 GetCRC() const { return _crc.GetDigest(); } - void InitCRC() { _crc.Init(); } - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhRegister.cpp deleted file mode 100644 index b83d2ee6c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/LzhRegister.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// LzhRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "LzhHandler.h" -static IInArchive *CreateArc() { return new NArchive::NLzh::CHandler; } - -static CArcInfo g_ArcInfo = - { L"Lzh", L"lzh lha", 0, 6, { '-', 'l' }, 2, false, CreateArc, 0 }; - -REGISTER_ARC(Lzh) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzh/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaArcRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaArcRegister.cpp deleted file mode 100644 index 867bc78ff..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaArcRegister.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// LzmaArcRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "LzmaHandler.h" - -static IInArchive *CreateArc() { return new NArchive::NLzma::CHandler; } - -static CArcInfo g_ArcInfo = - { L"Lzma", L"lzma lzma86", 0, 0xA, {0 }, 0, true, CreateArc, NULL }; - -REGISTER_ARC(Lzma) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.cpp deleted file mode 100644 index 2ab3dbf4b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.cpp +++ /dev/null @@ -1,86 +0,0 @@ -// LzmaFiltersDecode.cpp - -#include "StdAfx.h" - -#include "LzmaFiltersDecode.h" - -namespace NArchive { -namespace NLzma { - -static const UInt64 k_LZMA = 0x030101; -static const UInt64 k_BCJ = 0x03030103; - -HRESULT CDecoder::Code( - DECL_EXTERNAL_CODECS_LOC_VARS - const CHeader &block, - ISequentialInStream *inStream, ISequentialOutStream *outStream, - UInt64 *inProcessedSize, ICompressProgressInfo *progress) -{ - *inProcessedSize = (UInt64)(Int64)-1; - - if (block.FilterMethod > 1) - return E_NOTIMPL; - - if (!_lzmaDecoder) - { - RINOK(CreateCoder(EXTERNAL_CODECS_LOC_VARS k_LZMA, _lzmaDecoder, false)); - if (_lzmaDecoder == 0) - return E_NOTIMPL; - } - - { - CMyComPtr setDecoderProperties; - _lzmaDecoder.QueryInterface(IID_ICompressSetDecoderProperties2, &setDecoderProperties); - if (!setDecoderProperties) - return E_NOTIMPL; - RINOK(setDecoderProperties->SetDecoderProperties2(block.LzmaProps, 5)); - } - - bool filteredMode = (block.FilterMethod == 1); - - CMyComPtr setOutStream; - - if (filteredMode) - { - if (!_bcjStream) - { - CMyComPtr coder; - RINOK(CreateCoder(EXTERNAL_CODECS_LOC_VARS k_BCJ, coder, false)); - if (!coder) - return E_NOTIMPL; - coder.QueryInterface(IID_ISequentialOutStream, &_bcjStream); - if (!_bcjStream) - return E_NOTIMPL; - } - - _bcjStream.QueryInterface(IID_ICompressSetOutStream, &setOutStream); - if (!setOutStream) - return E_NOTIMPL; - RINOK(setOutStream->SetOutStream(outStream)); - outStream = _bcjStream; - } - - const UInt64 *unpackSize = block.HasUnpackSize() ? &block.UnpackSize : NULL; - RINOK(_lzmaDecoder->Code(inStream, outStream, NULL, unpackSize, progress)); - - if (filteredMode) - { - CMyComPtr flush; - _bcjStream.QueryInterface(IID_IOutStreamFlush, &flush); - if (flush) - { - RINOK(flush->Flush()); - } - RINOK(setOutStream->ReleaseOutStream()); - } - - CMyComPtr getInStreamProcessedSize; - _lzmaDecoder.QueryInterface(IID_ICompressGetInStreamProcessedSize, &getInStreamProcessedSize); - if (getInStreamProcessedSize) - { - RINOK(getInStreamProcessedSize->GetInStreamProcessedSize(inProcessedSize)); - } - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.h deleted file mode 100644 index b966b422a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaFiltersDecode.h +++ /dev/null @@ -1,26 +0,0 @@ -// LzmaFiltersDecode.h - -#ifndef __LZMA_FILTERS_DECODE_H -#define __LZMA_FILTERS_DECODE_H - -#include "../../Common/CreateCoder.h" - -#include "LzmaItem.h" - -namespace NArchive { -namespace NLzma { - -class CDecoder -{ - CMyComPtr _lzmaDecoder; - CMyComPtr _bcjStream; -public: - HRESULT Code(DECL_EXTERNAL_CODECS_LOC_VARS - const CHeader &block, - ISequentialInStream *inStream, ISequentialOutStream *outStream, - UInt64 *inProcessedSize, ICompressProgressInfo *progress); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.cpp deleted file mode 100644 index 249fd90fa..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.cpp +++ /dev/null @@ -1,243 +0,0 @@ -// LzmaHandler.cpp - -#include "StdAfx.h" - -#include "LzmaHandler.h" - -#include "Common/Defs.h" -#include "Common/StringConvert.h" -#include "Common/ComTry.h" -#include "Common/IntToString.h" - -#include "Windows/PropVariant.h" - -#include "../../Common/ProgressUtils.h" -#include "../../Common/StreamUtils.h" -#include "../Common/DummyOutStream.h" - -#include "LzmaFiltersDecode.h" - -namespace NArchive { -namespace NLzma { - -STATPROPSTG kProps[] = -{ - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMethod, VT_UI1} -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = 1; - return S_OK; -} - -static void ConvertUInt32ToString(UInt32 value, wchar_t *s) -{ - ConvertUInt64ToString(value, s + MyStringLen(s)); -} - -static void DictSizeToString(UInt32 value, wchar_t *s) -{ - for (int i = 0; i <= 31; i++) - if ((UInt32(1) << i) == value) - { - ConvertUInt32ToString(i, s); - return; - } - wchar_t c = L'b'; - if ((value & ((1 << 20) - 1)) == 0) - { - value >>= 20; - c = L'm'; - } - else if ((value & ((1 << 10) - 1)) == 0) - { - value >>= 10; - c = L'k'; - } - ConvertUInt32ToString(value, s); - int p = MyStringLen(s); - s[p++] = c; - s[p++] = L'\0'; -} - -static void MyStrCat(wchar_t *d, const wchar_t *s) -{ - MyStringCopy(d + MyStringLen(d), s); -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - if (index != 0) - return E_INVALIDARG; - NWindows::NCOM::CPropVariant propVariant; - switch(propID) - { - case kpidSize: - if (m_StreamInfo.HasUnpackSize()) - propVariant = (UInt64)m_StreamInfo.UnpackSize; - break; - case kpidPackSize: - propVariant = (UInt64)m_PackSize; - break; - case kpidMethod: - { - wchar_t s[64]; - s[0] = '\0'; - if (m_StreamInfo.IsThereFilter) - { - const wchar_t *f; - if (m_StreamInfo.FilterMethod == 0) - f = L"Copy"; - else if (m_StreamInfo.FilterMethod == 1) - f = L"BCJ"; - else - f = L"Unknown"; - MyStrCat(s, f); - MyStrCat(s, L" "); - } - MyStrCat(s, L"LZMA:"); - DictSizeToString(m_StreamInfo.GetDicSize(), s); - propVariant = s; - break; - } - } - propVariant.Detach(value); - return S_OK; -} - -STDMETHODIMP CHandler::Open(IInStream *inStream, - const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback * /* openArchiveCallback */) -{ - { - RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &m_StreamStartPosition)); - - HRESULT res = ReadStreamHeader(inStream, m_StreamInfo); - if (res != S_OK) - return S_FALSE; - - Byte b; - RINOK(ReadStream_FALSE(inStream, &b, 1)); - if (b != 0) - return S_FALSE; - - UInt64 endPos; - RINOK(inStream->Seek(0, STREAM_SEEK_END, &endPos)); - m_PackSize = endPos - m_StreamStartPosition - m_StreamInfo.GetHeaderSize(); - - m_Stream = inStream; - } - return S_OK; -} - -STDMETHODIMP CHandler::Close() -{ - m_Stream.Release(); - return S_OK; -} - - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - bool allFilesMode = (numItems == UInt32(-1)); - if (!allFilesMode) - { - if (numItems == 0) - return S_OK; - if (numItems != 1) - return E_INVALIDARG; - if (indices[0] != 0) - return E_INVALIDARG; - } - - bool testMode = (_aTestMode != 0); - - RINOK(extractCallback->SetTotal(m_PackSize)); - - UInt64 currentTotalPacked = 0; - - CDummyOutStream *outStreamSpec = new CDummyOutStream; - CMyComPtr outStream(outStreamSpec); - - { - CMyComPtr realOutStream; - Int32 askMode = testMode ? - NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - - RINOK(extractCallback->GetStream(0, &realOutStream, askMode)); - - outStreamSpec->SetStream(realOutStream); - outStreamSpec->Init(); - if(!testMode && !realOutStream) - return S_OK; - extractCallback->PrepareOperation(askMode); - } - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, true); - - CDecoder decoder; - RINOK(m_Stream->Seek(m_StreamStartPosition, STREAM_SEEK_SET, NULL)); - UInt64 streamPos = m_StreamStartPosition; - Int32 opRes = NArchive::NExtract::NOperationResult::kOK; - bool firstItem = true; - for (;;) - { - CHeader st; - HRESULT result = ReadStreamHeader(m_Stream, st); - if (result != S_OK) - { - if (firstItem) - return E_FAIL; - break; - } - firstItem = false; - - lps->OutSize = outStreamSpec->GetSize(); - lps->InSize = currentTotalPacked; - RINOK(lps->SetCur()); - - streamPos += st.GetHeaderSize(); - UInt64 packProcessed; - - { - result = decoder.Code( - EXTERNAL_CODECS_VARS - st, m_Stream, outStream, &packProcessed, progress); - if (result == E_NOTIMPL) - { - opRes = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - break; - } - if (result == S_FALSE) - { - opRes = NArchive::NExtract::NOperationResult::kDataError; - break; - } - RINOK(result); - } - - if (packProcessed == (UInt64)(Int64)-1) - break; - RINOK(m_Stream->Seek(streamPos + packProcessed, STREAM_SEEK_SET, NULL)); - currentTotalPacked += packProcessed; - streamPos += packProcessed; - } - outStream.Release(); - return extractCallback->SetOperationResult(opRes); - COM_TRY_END -} - -IMPL_ISetCompressCodecsInfo - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.h deleted file mode 100644 index bbf11a46b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaHandler.h +++ /dev/null @@ -1,69 +0,0 @@ -// Lzma/Handler.h - -#ifndef __GZIP_HANDLER_H -#define __GZIP_HANDLER_H - -#include "Common/MyCom.h" - -#include "../IArchive.h" -#include "../../Common/CreateCoder.h" - -#include "LzmaIn.h" - -namespace NArchive { -namespace NLzma { - -// const UInt64 k_LZMA = 0x030101; - -class CHandler: - public IInArchive, - PUBLIC_ISetCompressCodecsInfo - public CMyUnknownImp -{ -public: - MY_QUERYINTERFACE_BEGIN - MY_QUERYINTERFACE_ENTRY(IInArchive) - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - STDMETHOD(Open)(IInStream *inStream, - const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openArchiveCallback); - STDMETHOD(Close)(); - - STDMETHOD(GetNumberOfItems)(UInt32 *numItems); - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value); - STDMETHOD(Extract)(const UInt32* indices, UInt32 numItems, - Int32 testMode, IArchiveExtractCallback *extractCallback); - - STDMETHOD(GetArchiveProperty)(PROPID propID, PROPVARIANT *value); - - STDMETHOD(GetNumberOfProperties)(UInt32 *numProperties); - STDMETHOD(GetPropertyInfo)(UInt32 index, - BSTR *name, PROPID *propID, VARTYPE *varType); - - STDMETHOD(GetNumberOfArchiveProperties)(UInt32 *numProperties); - STDMETHOD(GetArchivePropertyInfo)(UInt32 index, - BSTR *name, PROPID *propID, VARTYPE *varType); - - UString GetMethodString(); -public: - CHandler() { } - -private: - CHeader m_StreamInfo; - UInt64 m_StreamStartPosition; - UInt64 m_PackSize; - - CMyComPtr m_Stream; - - DECL_EXTERNAL_CODECS_VARS - - DECL_ISetCompressCodecsInfo - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.cpp deleted file mode 100644 index 7d2475c75..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.cpp +++ /dev/null @@ -1,56 +0,0 @@ -// Archive/LzmaIn.cpp - -#include "StdAfx.h" - -#include "LzmaIn.h" - -#include "../../Common/StreamUtils.h" - -namespace NArchive { -namespace NLzma { - -static bool CheckDictSize(const Byte *p) -{ - UInt32 dicSize = GetUi32(p); - int i; - for (i = 1; i <= 30; i++) - if (dicSize == ((UInt32)2 << i) || dicSize == ((UInt32)3 << i)) - return true; - return false; -} - -HRESULT ReadStreamHeader(ISequentialInStream *inStream, CHeader &block) -{ - Byte sig[5 + 9]; - RINOK(ReadStream_FALSE(inStream, sig, 5 + 8)); - - const Byte kMaxProp0Val = 5 * 5 * 9 - 1; - if (sig[0] > kMaxProp0Val) - return S_FALSE; - - for (int i = 0; i < 5; i++) - block.LzmaProps[i] = sig[i]; - - block.IsThereFilter = false; - block.FilterMethod = 0; - - if (!CheckDictSize(sig + 1)) - { - if (sig[0] > 1 || sig[1] > kMaxProp0Val) - return S_FALSE; - block.IsThereFilter = true; - block.FilterMethod = sig[0]; - for (int i = 0; i < 5; i++) - block.LzmaProps[i] = sig[i + 1]; - if (!CheckDictSize(block.LzmaProps + 1)) - return S_FALSE; - RINOK(ReadStream_FALSE(inStream, sig + 5 + 8, 1)); - } - UInt32 unpOffset = 5 + (block.IsThereFilter ? 1 : 0); - block.UnpackSize = GetUi64(sig + unpOffset); - if (block.HasUnpackSize() && block.UnpackSize >= ((UInt64)1 << 56)) - return S_FALSE; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.h deleted file mode 100644 index 6f5c24c0e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaIn.h +++ /dev/null @@ -1,16 +0,0 @@ -// Archive/LzmaIn.h - -#ifndef __ARCHIVE_LZMA_IN_H -#define __ARCHIVE_LZMA_IN_H - -#include "LzmaItem.h" -#include "../../IStream.h" - -namespace NArchive { -namespace NLzma { - -HRESULT ReadStreamHeader(ISequentialInStream *inStream, CHeader &st); - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaItem.h deleted file mode 100644 index 1bfadf727..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/LzmaItem.h +++ /dev/null @@ -1,27 +0,0 @@ -// Archive/LzmaItem.h - -#ifndef __ARCHIVE_LZMA_ITEM_H -#define __ARCHIVE_LZMA_ITEM_H - -#include "Common/Types.h" - -#include "../../../../C/CpuArch.h" - -namespace NArchive { -namespace NLzma { - -struct CHeader -{ - UInt64 UnpackSize; - bool IsThereFilter; - Byte FilterMethod; - Byte LzmaProps[5]; - - UInt32 GetDicSize() const { return GetUi32(LzmaProps + 1); } - bool HasUnpackSize() const { return (UnpackSize != (UInt64)(Int64)-1); } - unsigned GetHeaderSize() const { return 5 + 8 + (IsThereFilter ? 1 : 0); } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Lzma/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.cpp deleted file mode 100644 index 3bd17b6db..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.cpp +++ /dev/null @@ -1,835 +0,0 @@ -// RarHandler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" -#include "Common/IntToString.h" -#include "Common/StringConvert.h" - -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "../../IPassword.h" - -#include "../../Common/CreateCoder.h" -#include "../../Common/FilterCoder.h" -#include "../../Common/MethodId.h" -#include "../../Common/ProgressUtils.h" - -#include "../../Compress/CopyCoder.h" - -#include "../../Crypto/Rar20Crypto.h" -#include "../../Crypto/RarAes.h" - -#include "../Common/ItemNameUtils.h" -#include "../Common/OutStreamWithCRC.h" - -#include "RarHandler.h" - -using namespace NWindows; -using namespace NTime; - -namespace NArchive { -namespace NRar { - -static const wchar_t *kHostOS[] = -{ - L"MS DOS", - L"OS/2", - L"Win32", - L"Unix", - L"Mac OS", - L"BeOS" -}; - -static const int kNumHostOSes = sizeof(kHostOS) / sizeof(kHostOS[0]); - -static const wchar_t *kUnknownOS = L"Unknown"; - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidIsDir, VT_BOOL}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMTime, VT_FILETIME}, - { NULL, kpidCTime, VT_FILETIME}, - { NULL, kpidATime, VT_FILETIME}, - { NULL, kpidAttrib, VT_UI4}, - - { NULL, kpidEncrypted, VT_BOOL}, - { NULL, kpidSolid, VT_BOOL}, - { NULL, kpidCommented, VT_BOOL}, - { NULL, kpidSplitBefore, VT_BOOL}, - { NULL, kpidSplitAfter, VT_BOOL}, - { NULL, kpidCRC, VT_UI4}, - { NULL, kpidHostOS, VT_BSTR}, - { NULL, kpidMethod, VT_BSTR}, - { NULL, kpidUnpackVer, VT_UI1} -}; - -STATPROPSTG kArcProps[] = -{ - { NULL, kpidSolid, VT_BOOL}, - { NULL, kpidNumBlocks, VT_UI4}, - // { NULL, kpidEncrypted, VT_BOOL}, - { NULL, kpidIsVolume, VT_BOOL}, - { NULL, kpidNumVolumes, VT_UI4}, - { NULL, kpidPhySize, VT_UI8} - // { NULL, kpidCommented, VT_BOOL} -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps - -UInt64 CHandler::GetPackSize(int refIndex) const -{ - const CRefItem &refItem = _refItems[refIndex]; - UInt64 totalPackSize = 0; - for (int i = 0; i < refItem.NumItems; i++) - totalPackSize += _items[refItem.ItemIndex + i].PackSize; - return totalPackSize; -} - -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) -{ - // COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case kpidSolid: prop = _archiveInfo.IsSolid(); break; - // case kpidEncrypted: prop = _archiveInfo.IsEncrypted(); break; // it's for encrypted names. - case kpidIsVolume: prop = _archiveInfo.IsVolume(); break; - case kpidNumVolumes: prop = (UInt32)_archives.Size(); break; - case kpidOffset: if (_archiveInfo.StartPosition != 0) prop = _archiveInfo.StartPosition; break; - // case kpidCommented: prop = _archiveInfo.IsCommented(); break; - case kpidNumBlocks: - { - UInt32 numBlocks = 0; - for (int i = 0; i < _refItems.Size(); i++) - if (!IsSolid(i)) - numBlocks++; - prop = (UInt32)numBlocks; - break; - } - } - prop.Detach(value); - return S_OK; - // COM_TRY_END -} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = _refItems.Size(); - return S_OK; -} - -static bool RarTimeToFileTime(const CRarTime &rarTime, FILETIME &result) -{ - if (!DosTimeToFileTime(rarTime.DosTime, result)) - return false; - UInt64 value = (((UInt64)result.dwHighDateTime) << 32) + result.dwLowDateTime; - value += (UInt64)rarTime.LowSecond * 10000000; - value += ((UInt64)rarTime.SubTime[2] << 16) + - ((UInt64)rarTime.SubTime[1] << 8) + - ((UInt64)rarTime.SubTime[0]); - result.dwLowDateTime = (DWORD)value; - result.dwHighDateTime = DWORD(value >> 32); - return true; -} - -static void RarTimeToProp(const CRarTime &rarTime, NWindows::NCOM::CPropVariant &prop) -{ - FILETIME localFileTime, utcFileTime; - if (RarTimeToFileTime(rarTime, localFileTime)) - { - if (!LocalFileTimeToFileTime(&localFileTime, &utcFileTime)) - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - } - else - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - prop = utcFileTime; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - const CRefItem &refItem = _refItems[index]; - const CItemEx &item = _items[refItem.ItemIndex]; - switch(propID) - { - case kpidPath: - { - UString u; - if (item.HasUnicodeName() && !item.UnicodeName.IsEmpty()) - u = item.UnicodeName; - else - u = MultiByteToUnicodeString(item.Name, CP_OEMCP); - prop = (const wchar_t *)NItemName::WinNameToOSName(u); - break; - } - case kpidIsDir: prop = item.IsDir(); break; - case kpidSize: prop = item.Size; break; - case kpidPackSize: prop = GetPackSize(index); break; - case kpidMTime: RarTimeToProp(item.MTime, prop); break; - case kpidCTime: if (item.CTimeDefined) RarTimeToProp(item.CTime, prop); break; - case kpidATime: if (item.ATimeDefined) RarTimeToProp(item.ATime, prop); break; - case kpidAttrib: prop = item.GetWinAttributes(); break; - case kpidEncrypted: prop = item.IsEncrypted(); break; - case kpidSolid: prop = IsSolid(index); break; - case kpidCommented: prop = item.IsCommented(); break; - case kpidSplitBefore: prop = item.IsSplitBefore(); break; - case kpidSplitAfter: prop = _items[refItem.ItemIndex + refItem.NumItems - 1].IsSplitAfter(); break; - case kpidCRC: - { - const CItemEx &lastItem = _items[refItem.ItemIndex + refItem.NumItems - 1]; - prop = ((lastItem.IsSplitAfter()) ? item.FileCRC : lastItem.FileCRC); - break; - } - case kpidUnpackVer: prop = item.UnPackVersion; break; - case kpidMethod: - { - UString method; - if (item.Method >= Byte('0') && item.Method <= Byte('5')) - { - method = L"m"; - wchar_t temp[32]; - ConvertUInt64ToString(item.Method - Byte('0'), temp); - method += temp; - if (!item.IsDir()) - { - method += L":"; - ConvertUInt64ToString(16 + item.GetDictSize(), temp); - method += temp; - } - } - else - { - wchar_t temp[32]; - ConvertUInt64ToString(item.Method, temp); - method += temp; - } - prop = method; - break; - } - case kpidHostOS: prop = (item.HostOS < kNumHostOSes) ? (kHostOS[item.HostOS]) : kUnknownOS; break; - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -class CVolumeName -{ - bool _first; - bool _newStyle; - UString _unchangedPart; - UString _changedPart; - UString _afterPart; -public: - CVolumeName(): _newStyle(true) {}; - - bool InitName(const UString &name, bool newStyle) - { - _first = true; - _newStyle = newStyle; - int dotPos = name.ReverseFind('.'); - UString basePart = name; - if (dotPos >= 0) - { - UString ext = name.Mid(dotPos + 1); - if (ext.CompareNoCase(L"rar") == 0) - { - _afterPart = name.Mid(dotPos); - basePart = name.Left(dotPos); - } - else if (ext.CompareNoCase(L"exe") == 0) - { - _afterPart = L".rar"; - basePart = name.Left(dotPos); - } - else if (!_newStyle) - { - if (ext.CompareNoCase(L"000") == 0 || ext.CompareNoCase(L"001") == 0) - { - _afterPart.Empty(); - _first = false; - _changedPart = ext; - _unchangedPart = name.Left(dotPos + 1); - return true; - } - } - } - - if (!_newStyle) - { - _afterPart.Empty(); - _unchangedPart = basePart + UString(L"."); - _changedPart = L"r00"; - return true; - } - - int numLetters = 1; - if (basePart.Right(numLetters) == L"1" || basePart.Right(numLetters) == L"0") - { - while (numLetters < basePart.Length()) - { - if (basePart[basePart.Length() - numLetters - 1] != '0') - break; - numLetters++; - } - } - else - return false; - _unchangedPart = basePart.Left(basePart.Length() - numLetters); - _changedPart = basePart.Right(numLetters); - return true; - } - - UString GetNextName() - { - UString newName; - if (_newStyle || !_first) - { - int i; - int numLetters = _changedPart.Length(); - for (i = numLetters - 1; i >= 0; i--) - { - wchar_t c = _changedPart[i]; - if (c == L'9') - { - c = L'0'; - newName = c + newName; - if (i == 0) - newName = UString(L'1') + newName; - continue; - } - c++; - newName = UString(c) + newName; - i--; - for (; i >= 0; i--) - newName = _changedPart[i] + newName; - break; - } - _changedPart = newName; - } - _first = false; - return _unchangedPart + _changedPart + _afterPart; - } -}; - -HRESULT CHandler::Open2(IInStream *stream, - const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openArchiveCallback) -{ - { - CMyComPtr openVolumeCallback; - CMyComPtr getTextPassword; - CMyComPtr openArchiveCallbackWrap = openArchiveCallback; - - CVolumeName seqName; - - UInt64 totalBytes = 0; - UInt64 curBytes = 0; - - if (openArchiveCallback != NULL) - { - openArchiveCallbackWrap.QueryInterface(IID_IArchiveOpenVolumeCallback, &openVolumeCallback); - openArchiveCallbackWrap.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword); - } - - for (;;) - { - CMyComPtr inStream; - if (!_archives.IsEmpty()) - { - if (!openVolumeCallback) - break; - - if(_archives.Size() == 1) - { - if (!_archiveInfo.IsVolume()) - break; - UString baseName; - { - NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); - if (prop.vt != VT_BSTR) - break; - baseName = prop.bstrVal; - } - seqName.InitName(baseName, _archiveInfo.HaveNewVolumeName()); - } - - UString fullName = seqName.GetNextName(); - HRESULT result = openVolumeCallback->GetStream(fullName, &inStream); - if (result == S_FALSE) - break; - if (result != S_OK) - return result; - if (!stream) - break; - } - else - inStream = stream; - - UInt64 endPos = 0; - if (openArchiveCallback != NULL) - { - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); - totalBytes += endPos; - RINOK(openArchiveCallback->SetTotal(NULL, &totalBytes)); - } - - NArchive::NRar::CInArchive archive; - RINOK(archive.Open(inStream, maxCheckStartPosition)); - - if (_archives.IsEmpty()) - archive.GetArchiveInfo(_archiveInfo); - - CItemEx item; - for (;;) - { - HRESULT result = archive.GetNextItem(item, getTextPassword); - if (result == S_FALSE) - break; - RINOK(result); - if (item.IgnoreItem()) - continue; - - bool needAdd = true; - if (item.IsSplitBefore()) - { - if (!_refItems.IsEmpty()) - { - CRefItem &refItem = _refItems.Back(); - refItem.NumItems++; - needAdd = false; - } - } - if (needAdd) - { - CRefItem refItem; - refItem.ItemIndex = _items.Size(); - refItem.NumItems = 1; - refItem.VolumeIndex = _archives.Size(); - _refItems.Add(refItem); - } - _items.Add(item); - if (openArchiveCallback != NULL && _items.Size() % 100 == 0) - { - UInt64 numFiles = _items.Size(); - UInt64 numBytes = curBytes + item.Position; - RINOK(openArchiveCallback->SetCompleted(&numFiles, &numBytes)); - } - } - curBytes += endPos; - _archives.Add(archive); - } - } - return S_OK; -} - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openArchiveCallback) -{ - COM_TRY_BEGIN - Close(); - try - { - HRESULT res = Open2(stream, maxCheckStartPosition, openArchiveCallback); - if (res != S_OK) - Close(); - return res; - } - catch(const CInArchiveException &) { Close(); return S_FALSE; } - catch(...) { Close(); throw; } - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - COM_TRY_BEGIN - _refItems.Clear(); - _items.Clear(); - _archives.Clear(); - return S_OK; - COM_TRY_END -} - -struct CMethodItem -{ - Byte RarUnPackVersion; - CMyComPtr Coder; -}; - - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *_anExtractCallback) -{ - COM_TRY_BEGIN - CMyComPtr getTextPassword; - bool testMode = (_aTestMode != 0); - CMyComPtr extractCallback = _anExtractCallback; - UInt64 censoredTotalUnPacked = 0, - // censoredTotalPacked = 0, - importantTotalUnPacked = 0; - // importantTotalPacked = 0; - bool allFilesMode = (numItems == UInt32(-1)); - if (allFilesMode) - numItems = _refItems.Size(); - if(numItems == 0) - return S_OK; - int lastIndex = 0; - CRecordVector importantIndexes; - CRecordVector extractStatuses; - - for(UInt32 t = 0; t < numItems; t++) - { - int index = allFilesMode ? t : indices[t]; - const CRefItem &refItem = _refItems[index]; - const CItemEx &item = _items[refItem.ItemIndex]; - censoredTotalUnPacked += item.Size; - // censoredTotalPacked += item.PackSize; - int j; - for(j = lastIndex; j <= index; j++) - // if(!_items[_refItems[j].ItemIndex].IsSolid()) - if(!IsSolid(j)) - lastIndex = j; - for(j = lastIndex; j <= index; j++) - { - const CRefItem &refItem = _refItems[j]; - const CItemEx &item = _items[refItem.ItemIndex]; - - // const CItemEx &item = _items[j]; - - importantTotalUnPacked += item.Size; - // importantTotalPacked += item.PackSize; - importantIndexes.Add(j); - extractStatuses.Add(j == index); - } - lastIndex = index + 1; - } - - extractCallback->SetTotal(importantTotalUnPacked); - UInt64 currentImportantTotalUnPacked = 0; - UInt64 currentImportantTotalPacked = 0; - UInt64 currentUnPackSize, currentPackSize; - - CObjectVector methodItems; - - NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; - CMyComPtr copyCoder = copyCoderSpec; - - CFilterCoder *filterStreamSpec = new CFilterCoder; - CMyComPtr filterStream = filterStreamSpec; - - NCrypto::NRar20::CDecoder *rar20CryptoDecoderSpec = NULL; - CMyComPtr rar20CryptoDecoder; - NCrypto::NRar29::CDecoder *rar29CryptoDecoderSpec = NULL; - CMyComPtr rar29CryptoDecoder; - - CFolderInStream *folderInStreamSpec = NULL; - CMyComPtr folderInStream; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - bool solidStart = true; - for(int i = 0; i < importantIndexes.Size(); i++, - currentImportantTotalUnPacked += currentUnPackSize, - currentImportantTotalPacked += currentPackSize) - { - lps->InSize = currentImportantTotalPacked; - lps->OutSize = currentImportantTotalUnPacked; - RINOK(lps->SetCur()); - CMyComPtr realOutStream; - - Int32 askMode; - if(extractStatuses[i]) - askMode = testMode ? - NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - else - askMode = NArchive::NExtract::NAskMode::kSkip; - - UInt32 index = importantIndexes[i]; - - const CRefItem &refItem = _refItems[index]; - const CItemEx &item = _items[refItem.ItemIndex]; - - currentUnPackSize = item.Size; - - currentPackSize = GetPackSize(index); - - if(item.IgnoreItem()) - continue; - - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - - if (!IsSolid(index)) - solidStart = true; - if(item.IsDir()) - { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK)); - continue; - } - - bool mustBeProcessedAnywhere = false; - if(i < importantIndexes.Size() - 1) - { - // const CRefItem &nextRefItem = _refItems[importantIndexes[i + 1]]; - // const CItemEx &nextItemInfo = _items[nextRefItem.ItemIndex]; - // mustBeProcessedAnywhere = nextItemInfo.IsSolid(); - mustBeProcessedAnywhere = IsSolid(importantIndexes[i + 1]); - } - - if (!mustBeProcessedAnywhere && !testMode && !realOutStream) - continue; - - if (!realOutStream && !testMode) - askMode = NArchive::NExtract::NAskMode::kSkip; - - RINOK(extractCallback->PrepareOperation(askMode)); - - COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC; - CMyComPtr outStream(outStreamSpec); - outStreamSpec->SetStream(realOutStream); - outStreamSpec->Init(); - realOutStream.Release(); - - /* - for (int partIndex = 0; partIndex < 1; partIndex++) - { - CMyComPtr inStream; - - // item redefinition - const CItemEx &item = _items[refItem.ItemIndex + partIndex]; - - NArchive::NRar::CInArchive &archive = _archives[refItem.VolumeIndex + partIndex]; - - inStream.Attach(archive.CreateLimitedStream(item.GetDataPosition(), - item.PackSize)); - */ - if (!folderInStream) - { - folderInStreamSpec = new CFolderInStream; - folderInStream = folderInStreamSpec; - } - - folderInStreamSpec->Init(&_archives, &_items, refItem); - - UInt64 packSize = currentPackSize; - - // packedPos += item.PackSize; - // unpackedPos += 0; - - CMyComPtr inStream; - if (item.IsEncrypted()) - { - CMyComPtr cryptoSetPassword; - if (item.UnPackVersion >= 29) - { - if (!rar29CryptoDecoder) - { - rar29CryptoDecoderSpec = new NCrypto::NRar29::CDecoder; - rar29CryptoDecoder = rar29CryptoDecoderSpec; - // RINOK(rar29CryptoDecoder.CoCreateInstance(CLSID_CCryptoRar29Decoder)); - } - rar29CryptoDecoderSpec->SetRar350Mode(item.UnPackVersion < 36); - CMyComPtr cryptoProperties; - RINOK(rar29CryptoDecoder.QueryInterface(IID_ICompressSetDecoderProperties2, - &cryptoProperties)); - RINOK(cryptoProperties->SetDecoderProperties2(item.Salt, item.HasSalt() ? sizeof(item.Salt) : 0)); - filterStreamSpec->Filter = rar29CryptoDecoder; - } - else if (item.UnPackVersion >= 20) - { - if (!rar20CryptoDecoder) - { - rar20CryptoDecoderSpec = new NCrypto::NRar20::CDecoder; - rar20CryptoDecoder = rar20CryptoDecoderSpec; - // RINOK(rar20CryptoDecoder.CoCreateInstance(CLSID_CCryptoRar20Decoder)); - } - filterStreamSpec->Filter = rar20CryptoDecoder; - } - else - { - outStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - continue; - } - RINOK(filterStreamSpec->Filter.QueryInterface(IID_ICryptoSetPassword, - &cryptoSetPassword)); - - if (!getTextPassword) - extractCallback.QueryInterface(IID_ICryptoGetTextPassword, - &getTextPassword); - if (getTextPassword) - { - CMyComBSTR password; - RINOK(getTextPassword->CryptoGetTextPassword(&password)); - if (item.UnPackVersion >= 29) - { - CByteBuffer buffer; - UString unicodePassword(password); - const UInt32 sizeInBytes = unicodePassword.Length() * 2; - buffer.SetCapacity(sizeInBytes); - for (int i = 0; i < unicodePassword.Length(); i++) - { - wchar_t c = unicodePassword[i]; - ((Byte *)buffer)[i * 2] = (Byte)c; - ((Byte *)buffer)[i * 2 + 1] = (Byte)(c >> 8); - } - RINOK(cryptoSetPassword->CryptoSetPassword( - (const Byte *)buffer, sizeInBytes)); - } - else - { - AString oemPassword = UnicodeStringToMultiByte( - (const wchar_t *)password, CP_OEMCP); - RINOK(cryptoSetPassword->CryptoSetPassword( - (const Byte *)(const char *)oemPassword, oemPassword.Length())); - } - } - else - { - RINOK(cryptoSetPassword->CryptoSetPassword(0, 0)); - } - filterStreamSpec->SetInStream(folderInStream); - inStream = filterStream; - } - else - { - inStream = folderInStream; - } - CMyComPtr commonCoder; - switch(item.Method) - { - case '0': - { - commonCoder = copyCoder; - break; - } - case '1': - case '2': - case '3': - case '4': - case '5': - { - /* - if (item.UnPackVersion >= 29) - { - outStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - continue; - } - */ - int m; - for (m = 0; m < methodItems.Size(); m++) - if (methodItems[m].RarUnPackVersion == item.UnPackVersion) - break; - if (m == methodItems.Size()) - { - CMethodItem mi; - mi.RarUnPackVersion = item.UnPackVersion; - - mi.Coder.Release(); - if (item.UnPackVersion <= 30) - { - UInt32 methodID = 0x040300; - if (item.UnPackVersion < 20) - methodID += 1; - else if (item.UnPackVersion < 29) - methodID += 2; - else - methodID += 3; - RINOK(CreateCoder(EXTERNAL_CODECS_VARS methodID, mi.Coder, false)); - } - - if (mi.Coder == 0) - { - outStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - continue; - } - - m = methodItems.Add(mi); - } - CMyComPtr decoder = methodItems[m].Coder; - - CMyComPtr compressSetDecoderProperties; - RINOK(decoder.QueryInterface(IID_ICompressSetDecoderProperties2, - &compressSetDecoderProperties)); - - Byte isSolid = (Byte)((IsSolid(index) || item.IsSplitBefore()) ? 1: 0); - if (solidStart) - { - isSolid = false; - solidStart = false; - } - - - RINOK(compressSetDecoderProperties->SetDecoderProperties2(&isSolid, 1)); - - commonCoder = decoder; - break; - } - default: - outStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - continue; - } - HRESULT result = commonCoder->Code(inStream, outStream, &packSize, &item.Size, progress); - if (item.IsEncrypted()) - filterStreamSpec->ReleaseInStream(); - if (result == S_FALSE) - { - outStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kDataError)); - continue; - } - if (result != S_OK) - return result; - - /* - if (refItem.NumItems == 1 && - !item.IsSplitBefore() && !item.IsSplitAfter()) - */ - { - const CItemEx &lastItem = _items[refItem.ItemIndex + refItem.NumItems - 1]; - bool crcOK = outStreamSpec->GetCRC() == lastItem.FileCRC; - outStream.Release(); - RINOK(extractCallback->SetOperationResult(crcOK ? NArchive::NExtract::NOperationResult::kOK: - NArchive::NExtract::NOperationResult::kCRCError)); - } - /* - else - { - bool crcOK = true; - for (int partIndex = 0; partIndex < refItem.NumItems; partIndex++) - { - const CItemEx &item = _items[refItem.ItemIndex + partIndex]; - if (item.FileCRC != folderInStreamSpec->CRCs[partIndex]) - { - crcOK = false; - break; - } - } - RINOK(extractCallback->SetOperationResult(crcOK ? NArchive::NExtract::NOperationResult::kOK: - NArchive::NExtract::NOperationResult::kCRCError)); - } - */ - } - return S_OK; - COM_TRY_END -} - -IMPL_ISetCompressCodecsInfo - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.h deleted file mode 100644 index dff8ed322..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHandler.h +++ /dev/null @@ -1,60 +0,0 @@ -// Rar/Handler.h - -#ifndef __RAR_HANDLER_H -#define __RAR_HANDLER_H - -#include "../IArchive.h" -#include "RarIn.h" -#include "RarVolumeInStream.h" - -#include "../../Common/CreateCoder.h" - -namespace NArchive { -namespace NRar { - -class CHandler: - public IInArchive, - PUBLIC_ISetCompressCodecsInfo - public CMyUnknownImp -{ -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) - QUERY_ENTRY_ISetCompressCodecsInfo - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) - - DECL_ISetCompressCodecsInfo - -private: - CRecordVector _refItems; - CObjectVector _items; - CObjectVector _archives; - NArchive::NRar::CInArchiveInfo _archiveInfo; - - DECL_EXTERNAL_CODECS_VARS - - UInt64 GetPackSize(int refIndex) const; - // NArchive::NRar::CInArchive _archive; - - bool IsSolid(int refIndex) - { - const CItemEx &item = _items[_refItems[refIndex].ItemIndex]; - if (item.UnPackVersion < 20) - { - if (_archiveInfo.IsSolid()) - return (refIndex > 0); - return false; - } - return item.IsSolid(); - } - - HRESULT Open2(IInStream *stream, - const UInt64 *maxCheckStartPosition, - IArchiveOpenCallback *openArchiveCallback); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.cpp deleted file mode 100644 index 90dc8366f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// Archive/Rar/Headers.cpp - -#include "StdAfx.h" - -#include "RarHeader.h" - -namespace NArchive{ -namespace NRar{ -namespace NHeader{ - -Byte kMarker[kMarkerSize] = {0x52 + 1, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00}; - -class CMarkerInitializer -{ -public: - CMarkerInitializer() { kMarker[0]--; }; -} g_MarkerInitializer; - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.h deleted file mode 100644 index e5a3e1deb..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarHeader.h +++ /dev/null @@ -1,224 +0,0 @@ -// Archive/RarHeader.h - -#ifndef __ARCHIVE_RAR_HEADER_H -#define __ARCHIVE_RAR_HEADER_H - -#include "Common/Types.h" - -namespace NArchive{ -namespace NRar{ -namespace NHeader{ - -const int kMarkerSize = 7; -extern Byte kMarker[kMarkerSize]; - -const int kArchiveSolid = 0x1; - -namespace NBlockType -{ - enum EBlockType - { - kMarker = 0x72, - kArchiveHeader = 0x73, - kFileHeader = 0x74, - kCommentHeader = 0x75, - kOldAuthenticity = 0x76, - kSubBlock = 0x77, - kRecoveryRecord = 0x78, - kAuthenticity = 0x79, - - kEndOfArchive = 0x7B // Is not safe - }; -} - -namespace NArchive -{ - const UInt16 kVolume = 1; - const UInt16 kComment = 2; - const UInt16 kLock = 4; - const UInt16 kSolid = 8; - const UInt16 kNewVolName = 0x10; // ('volname.partN.rar') - const UInt16 kAuthenticity = 0x20; - const UInt16 kRecovery = 0x40; - const UInt16 kBlockEncryption = 0x80; - const UInt16 kFirstVolume = 0x100; // (set only by RAR 3.0 and later) - const UInt16 kEncryptVer = 0x200; // RAR 3.6 there is EncryptVer Byte in End of MainHeader - - const int kHeaderSizeMin = 7; - - struct CBlock - { - UInt16 CRC; - Byte Type; - UInt16 Flags; - UInt16 Size; - UInt16 Reserved1; - UInt32 Reserved2; - // UInt16 GetRealCRC() const; - }; - - const int kArchiveHeaderSize = 13; - - const int kBlockHeadersAreEncrypted = 0x80; - - struct CHeader360: public CBlock - { - Byte EncryptVersion; - bool IsEncrypted() const { return (Flags & NHeader::NArchive::kBlockEncryption) != 0; } - bool IsThereEncryptVer() const { return (Flags & NHeader::NArchive::kEncryptVer) != 0; } - bool IsEncryptOld() const { return (!IsThereEncryptVer() || EncryptVersion < 36); } - UInt32 GetBaseSize() const { return kArchiveHeaderSize + (IsEncryptOld() ? 0 : 1); } - }; -} - -namespace NFile -{ - const int kSplitBefore = 1 << 0; - const int kSplitAfter = 1 << 1; - const int kEncrypted = 1 << 2; - const int kComment = 1 << 3; - const int kSolid = 1 << 4; - - const int kDictBitStart = 5; - const int kNumDictBits = 3; - const int kDictMask = (1 << kNumDictBits) - 1; - const int kDictDirectoryValue = 0x7; - - const int kSize64Bits = 1 << 8; - const int kUnicodeName = 1 << 9; - const int kSalt = 1 << 10; - const int kOldVersion = 1 << 11; - const int kExtTime = 1 << 12; - // const int kExtFlags = 1 << 13; - // const int kSkipIfUnknown = 1 << 14; - - const int kLongBlock = 1 << 15; - - /* - struct CBlock - { - // UInt16 HeadCRC; - // Byte Type; - // UInt16 Flags; - // UInt16 HeadSize; - UInt32 PackSize; - UInt32 UnPackSize; - Byte HostOS; - UInt32 FileCRC; - UInt32 Time; - Byte UnPackVersion; - Byte Method; - UInt16 NameSize; - UInt32 Attributes; - }; - */ - - /* - struct CBlock32 - { - UInt16 HeadCRC; - Byte Type; - UInt16 Flags; - UInt16 HeadSize; - UInt32 PackSize; - UInt32 UnPackSize; - Byte HostOS; - UInt32 FileCRC; - UInt32 Time; - Byte UnPackVersion; - Byte Method; - UInt16 NameSize; - UInt32 Attributes; - UInt16 GetRealCRC(const void *aName, UInt32 aNameSize, - bool anExtraDataDefined = false, Byte *anExtraData = 0) const; - }; - struct CBlock64 - { - UInt16 HeadCRC; - Byte Type; - UInt16 Flags; - UInt16 HeadSize; - UInt32 PackSizeLow; - UInt32 UnPackSizeLow; - Byte HostOS; - UInt32 FileCRC; - UInt32 Time; - Byte UnPackVersion; - Byte Method; - UInt16 NameSize; - UInt32 Attributes; - UInt32 PackSizeHigh; - UInt32 UnPackSizeHigh; - UInt16 GetRealCRC(const void *aName, UInt32 aNameSize) const; - }; - */ - - const int kLabelFileAttribute = 0x08; - const int kWinFileDirectoryAttributeMask = 0x10; - - enum CHostOS - { - kHostMSDOS = 0, - kHostOS2 = 1, - kHostWin32 = 2, - kHostUnix = 3, - kHostMacOS = 4, - kHostBeOS = 5 - }; -} - -namespace NBlock -{ - const UInt16 kLongBlock = 1 << 15; - struct CBlock - { - UInt16 CRC; - Byte Type; - UInt16 Flags; - UInt16 HeadSize; - // UInt32 DataSize; - }; -} - -/* -struct CSubBlock -{ - UInt16 HeadCRC; - Byte HeadType; - UInt16 Flags; - UInt16 HeadSize; - UInt32 DataSize; - UInt16 SubType; - Byte Level; // Reserved : Must be 0 -}; - -struct CCommentBlock -{ - UInt16 HeadCRC; - Byte HeadType; - UInt16 Flags; - UInt16 HeadSize; - UInt16 UnpSize; - Byte UnpVer; - Byte Method; - UInt16 CommCRC; -}; - - -struct CProtectHeader -{ - UInt16 HeadCRC; - Byte HeadType; - UInt16 Flags; - UInt16 HeadSize; - UInt32 DataSize; - Byte Version; - UInt16 RecSectors; - UInt32 TotalBlocks; - Byte Mark[8]; -}; -*/ - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.cpp deleted file mode 100644 index f434bce63..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.cpp +++ /dev/null @@ -1,513 +0,0 @@ -// Archive/RarIn.cpp - -#include "StdAfx.h" - -#include "Common/StringConvert.h" -#include "Common/UTFConvert.h" - -#include "RarIn.h" -#include "../../Common/LimitedStreams.h" -#include "../../Common/StreamUtils.h" - -#include "../Common/FindSignature.h" - -extern "C" -{ - #include "../../../../C/7zCrc.h" -} - -namespace NArchive { -namespace NRar { - -void CInArchive::ThrowExceptionWithCode( - CInArchiveException::CCauseType cause) -{ - throw CInArchiveException(cause); -} - -HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *searchHeaderSizeLimit) -{ - try - { - Close(); - HRESULT res = Open2(inStream, searchHeaderSizeLimit); - if (res == S_OK) - return res; - Close(); - return res; - } - catch(...) { Close(); throw; } -} - -void CInArchive::Close() -{ - m_Stream.Release(); -} - - -static inline bool TestMarkerCandidate(const void *aTestBytes) -{ - for (UInt32 i = 0; i < NHeader::kMarkerSize; i++) - if (((const Byte *)aTestBytes)[i] != NHeader::kMarker[i]) - return false; - return true; -} - -HRESULT CInArchive::FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - RINOK(FindSignatureInStream(stream, - NHeader::kMarker, NHeader::kMarkerSize, - searchHeaderSizeLimit, m_ArchiveStartPosition)); - m_Stream = stream; - m_Position = m_ArchiveStartPosition + NHeader::kMarkerSize; - return m_Stream->Seek(m_Position, STREAM_SEEK_SET, NULL); -} - -void CInArchive::ThrowUnexpectedEndOfArchiveException() -{ - ThrowExceptionWithCode(CInArchiveException::kUnexpectedEndOfArchive); -} - -bool CInArchive::ReadBytesAndTestSize(void *data, UInt32 size) -{ - if (m_CryptoMode) - { - const Byte *bufData = (const Byte *)m_DecryptedData; - UInt32 bufSize = m_DecryptedDataSize; - UInt32 i; - for (i = 0; i < size && m_CryptoPos < bufSize; i++) - ((Byte *)data)[i] = bufData[m_CryptoPos++]; - return (i == size); - } - return (ReadStream_FALSE(m_Stream, data, size) == S_OK); -} - -void CInArchive::ReadBytesAndTestResult(void *data, UInt32 size) -{ - if(!ReadBytesAndTestSize(data,size)) - ThrowUnexpectedEndOfArchiveException(); -} - -HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 *processedSize) -{ - size_t realProcessedSize = size; - HRESULT result = ReadStream(m_Stream, data, &realProcessedSize); - if (processedSize != NULL) - *processedSize = (UInt32)realProcessedSize; - AddToSeekValue(realProcessedSize); - return result; -} - -static UInt32 CrcUpdateUInt16(UInt32 crc, UInt16 v) -{ - crc = CRC_UPDATE_BYTE(crc, (Byte)(v & 0xFF)); - crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 8) & 0xFF)); - return crc; -} - -static UInt32 CrcUpdateUInt32(UInt32 crc, UInt32 v) -{ - crc = CRC_UPDATE_BYTE(crc, (Byte)(v & 0xFF)); - crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 8) & 0xFF)); - crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 16) & 0xFF)); - crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 24) & 0xFF)); - return crc; -} - - -HRESULT CInArchive::Open2(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - m_CryptoMode = false; - RINOK(stream->Seek(0, STREAM_SEEK_SET, &m_StreamStartPosition)); - m_Position = m_StreamStartPosition; - - RINOK(FindAndReadMarker(stream, searchHeaderSizeLimit)); - - Byte buf[NHeader::NArchive::kArchiveHeaderSize]; - UInt32 processedSize; - ReadBytes(buf, sizeof(buf), &processedSize); - if (processedSize != sizeof(buf)) - return S_FALSE; - m_CurData = buf; - m_CurPos = 0; - m_PosLimit = sizeof(buf); - - m_ArchiveHeader.CRC = ReadUInt16(); - m_ArchiveHeader.Type = ReadByte(); - m_ArchiveHeader.Flags = ReadUInt16(); - m_ArchiveHeader.Size = ReadUInt16(); - m_ArchiveHeader.Reserved1 = ReadUInt16(); - m_ArchiveHeader.Reserved2 = ReadUInt32(); - m_ArchiveHeader.EncryptVersion = 0; - - UInt32 crc = CRC_INIT_VAL; - crc = CRC_UPDATE_BYTE(crc, m_ArchiveHeader.Type); - crc = CrcUpdateUInt16(crc, m_ArchiveHeader.Flags); - crc = CrcUpdateUInt16(crc, m_ArchiveHeader.Size); - crc = CrcUpdateUInt16(crc, m_ArchiveHeader.Reserved1); - crc = CrcUpdateUInt32(crc, m_ArchiveHeader.Reserved2); - - if (m_ArchiveHeader.IsThereEncryptVer() && m_ArchiveHeader.Size > NHeader::NArchive::kArchiveHeaderSize) - { - ReadBytes(&m_ArchiveHeader.EncryptVersion, 1, &processedSize); - if (processedSize != 1) - return S_FALSE; - crc = CRC_UPDATE_BYTE(crc, m_ArchiveHeader.EncryptVersion); - } - - if(m_ArchiveHeader.CRC != (CRC_GET_DIGEST(crc) & 0xFFFF)) - ThrowExceptionWithCode(CInArchiveException::kArchiveHeaderCRCError); - if (m_ArchiveHeader.Type != NHeader::NBlockType::kArchiveHeader) - return S_FALSE; - m_ArchiveCommentPosition = m_Position; - m_SeekOnArchiveComment = true; - return S_OK; -} - -void CInArchive::SkipArchiveComment() -{ - if (!m_SeekOnArchiveComment) - return; - AddToSeekValue(m_ArchiveHeader.Size - m_ArchiveHeader.GetBaseSize()); - m_SeekOnArchiveComment = false; -} - -void CInArchive::GetArchiveInfo(CInArchiveInfo &archiveInfo) const -{ - archiveInfo.StartPosition = m_ArchiveStartPosition; - archiveInfo.Flags = m_ArchiveHeader.Flags; - archiveInfo.CommentPosition = m_ArchiveCommentPosition; - archiveInfo.CommentSize = (UInt16)(m_ArchiveHeader.Size - NHeader::NArchive::kArchiveHeaderSize); -} - -static void DecodeUnicodeFileName(const char *name, const Byte *encName, - int encSize, wchar_t *unicodeName, int maxDecSize) -{ - int encPos = 0; - int decPos = 0; - int flagBits = 0; - Byte flags = 0; - Byte highByte = encName[encPos++]; - while (encPos < encSize && decPos < maxDecSize) - { - if (flagBits == 0) - { - flags = encName[encPos++]; - flagBits = 8; - } - switch(flags >> 6) - { - case 0: - unicodeName[decPos++] = encName[encPos++]; - break; - case 1: - unicodeName[decPos++] = (wchar_t)(encName[encPos++] + (highByte << 8)); - break; - case 2: - unicodeName[decPos++] = (wchar_t)(encName[encPos] + (encName[encPos + 1] << 8)); - encPos += 2; - break; - case 3: - { - int length = encName[encPos++]; - if (length & 0x80) - { - Byte correction = encName[encPos++]; - for (length = (length & 0x7f) + 2; - length > 0 && decPos < maxDecSize; length--, decPos++) - unicodeName[decPos] = (wchar_t)(((name[decPos] + correction) & 0xff) + (highByte << 8)); - } - else - for (length += 2; length > 0 && decPos < maxDecSize; length--, decPos++) - unicodeName[decPos] = name[decPos]; - } - break; - } - flags <<= 2; - flagBits -= 2; - } - unicodeName[decPos < maxDecSize ? decPos : maxDecSize - 1] = 0; -} - -void CInArchive::ReadName(CItemEx &item, int nameSize) -{ - item.UnicodeName.Empty(); - if (nameSize > 0) - { - m_NameBuffer.EnsureCapacity(nameSize + 1); - char *buffer = (char *)m_NameBuffer; - - for (int i = 0; i < nameSize; i++) - buffer[i] = ReadByte(); - - int mainLen; - for (mainLen = 0; mainLen < nameSize; mainLen++) - if (buffer[mainLen] == '\0') - break; - buffer[mainLen] = '\0'; - item.Name = buffer; - - if(item.HasUnicodeName()) - { - if(mainLen < nameSize) - { - int unicodeNameSizeMax = MyMin(nameSize, (0x400)); - _unicodeNameBuffer.EnsureCapacity(unicodeNameSizeMax + 1); - DecodeUnicodeFileName(buffer, (const Byte *)buffer + mainLen + 1, - nameSize - (mainLen + 1), _unicodeNameBuffer, unicodeNameSizeMax); - item.UnicodeName = _unicodeNameBuffer; - } - else if (!ConvertUTF8ToUnicode(item.Name, item.UnicodeName)) - item.UnicodeName.Empty(); - } - } - else - item.Name.Empty(); -} - -Byte CInArchive::ReadByte() -{ - if (m_CurPos >= m_PosLimit) - throw CInArchiveException(CInArchiveException::kIncorrectArchive); - return m_CurData[m_CurPos++]; -} - -UInt16 CInArchive::ReadUInt16() -{ - UInt16 value = 0; - for (int i = 0; i < 2; i++) - { - Byte b = ReadByte(); - value |= (UInt16(b) << (8 * i)); - } - return value; -} - -UInt32 CInArchive::ReadUInt32() -{ - UInt32 value = 0; - for (int i = 0; i < 4; i++) - { - Byte b = ReadByte(); - value |= (UInt32(b) << (8 * i)); - } - return value; -} - -void CInArchive::ReadTime(Byte mask, CRarTime &rarTime) -{ - rarTime.LowSecond = (Byte)(((mask & 4) != 0) ? 1 : 0); - int numDigits = (mask & 3); - rarTime.SubTime[0] = rarTime.SubTime[1] = rarTime.SubTime[2] = 0; - for (int i = 0; i < numDigits; i++) - rarTime.SubTime[3 - numDigits + i] = ReadByte(); -} - -void CInArchive::ReadHeaderReal(CItemEx &item) -{ - item.Flags = m_BlockHeader.Flags; - item.PackSize = ReadUInt32(); - item.Size = ReadUInt32(); - item.HostOS = ReadByte(); - item.FileCRC = ReadUInt32(); - item.MTime.DosTime = ReadUInt32(); - item.UnPackVersion = ReadByte(); - item.Method = ReadByte(); - int nameSize = ReadUInt16(); - item.Attrib = ReadUInt32(); - - item.MTime.LowSecond = 0; - item.MTime.SubTime[0] = - item.MTime.SubTime[1] = - item.MTime.SubTime[2] = 0; - - if((item.Flags & NHeader::NFile::kSize64Bits) != 0) - { - item.PackSize |= ((UInt64)ReadUInt32() << 32); - item.Size |= ((UInt64)ReadUInt32() << 32); - } - - ReadName(item, nameSize); - - if (item.HasSalt()) - for (int i = 0; i < sizeof(item.Salt); i++) - item.Salt[i] = ReadByte(); - - // some rar archives have HasExtTime flag without field. - if (m_CurPos < m_PosLimit && item.HasExtTime()) - { - Byte accessMask = (Byte)(ReadByte() >> 4); - Byte b = ReadByte(); - Byte modifMask = (Byte)(b >> 4); - Byte createMask = (Byte)(b & 0xF); - if ((modifMask & 8) != 0) - ReadTime(modifMask, item.MTime); - item.CTimeDefined = ((createMask & 8) != 0); - if (item.CTimeDefined) - { - item.CTime.DosTime = ReadUInt32(); - ReadTime(createMask, item.CTime); - } - item.ATimeDefined = ((accessMask & 8) != 0); - if (item.ATimeDefined) - { - item.ATime.DosTime = ReadUInt32(); - ReadTime(accessMask, item.ATime); - } - } - - UInt16 fileHeaderWithNameSize = (UInt16)m_CurPos; - - item.Position = m_Position; - item.MainPartSize = fileHeaderWithNameSize; - item.CommentSize = (UInt16)(m_BlockHeader.HeadSize - fileHeaderWithNameSize); - - if (m_CryptoMode) - item.AlignSize = (UInt16)((16 - ((m_BlockHeader.HeadSize) & 0xF)) & 0xF); - else - item.AlignSize = 0; - AddToSeekValue(m_BlockHeader.HeadSize); -} - -void CInArchive::AddToSeekValue(UInt64 addValue) -{ - m_Position += addValue; -} - -HRESULT CInArchive::GetNextItem(CItemEx &item, ICryptoGetTextPassword *getTextPassword) -{ - if (m_SeekOnArchiveComment) - SkipArchiveComment(); - for (;;) - { - if(!SeekInArchive(m_Position)) - return S_FALSE; - if (!m_CryptoMode && (m_ArchiveHeader.Flags & - NHeader::NArchive::kBlockHeadersAreEncrypted) != 0) - { - m_CryptoMode = false; - if (getTextPassword == 0) - return S_FALSE; - if(!SeekInArchive(m_Position)) - return S_FALSE; - if (!m_RarAES) - { - m_RarAESSpec = new NCrypto::NRar29::CDecoder; - m_RarAES = m_RarAESSpec; - } - m_RarAESSpec->SetRar350Mode(m_ArchiveHeader.IsEncryptOld()); - - // Salt - const UInt32 kSaltSize = 8; - Byte salt[kSaltSize]; - if(!ReadBytesAndTestSize(salt, kSaltSize)) - return S_FALSE; - m_Position += kSaltSize; - RINOK(m_RarAESSpec->SetDecoderProperties2(salt, kSaltSize)) - // Password - CMyComBSTR password; - RINOK(getTextPassword->CryptoGetTextPassword(&password)) - UString unicodePassword(password); - - CByteBuffer buffer; - const UInt32 sizeInBytes = unicodePassword.Length() * 2; - buffer.SetCapacity(sizeInBytes); - for (int i = 0; i < unicodePassword.Length(); i++) - { - wchar_t c = unicodePassword[i]; - ((Byte *)buffer)[i * 2] = (Byte)c; - ((Byte *)buffer)[i * 2 + 1] = (Byte)(c >> 8); - } - - RINOK(m_RarAESSpec->CryptoSetPassword((const Byte *)buffer, sizeInBytes)); - - const UInt32 kDecryptedBufferSize = (1 << 12); - if (m_DecryptedData.GetCapacity() == 0) - { - m_DecryptedData.SetCapacity(kDecryptedBufferSize); - } - RINOK(m_RarAES->Init()); - size_t decryptedDataSizeT = kDecryptedBufferSize; - RINOK(ReadStream(m_Stream, (Byte *)m_DecryptedData, &decryptedDataSizeT)); - m_DecryptedDataSize = (UInt32)decryptedDataSizeT; - m_DecryptedDataSize = m_RarAES->Filter((Byte *)m_DecryptedData, m_DecryptedDataSize); - - m_CryptoMode = true; - m_CryptoPos = 0; - } - - m_FileHeaderData.EnsureCapacity(7); - if(!ReadBytesAndTestSize((Byte *)m_FileHeaderData, 7)) - return S_FALSE; - - m_CurData = (Byte *)m_FileHeaderData; - m_CurPos = 0; - m_PosLimit = 7; - m_BlockHeader.CRC = ReadUInt16(); - m_BlockHeader.Type = ReadByte(); - m_BlockHeader.Flags = ReadUInt16(); - m_BlockHeader.HeadSize = ReadUInt16(); - - if (m_BlockHeader.HeadSize < 7) - ThrowExceptionWithCode(CInArchiveException::kIncorrectArchive); - - if (m_BlockHeader.Type == NHeader::NBlockType::kEndOfArchive) - return S_FALSE; - - if (m_BlockHeader.Type == NHeader::NBlockType::kFileHeader) - { - m_FileHeaderData.EnsureCapacity(m_BlockHeader.HeadSize); - m_CurData = (Byte *)m_FileHeaderData; - m_PosLimit = m_BlockHeader.HeadSize; - ReadBytesAndTestResult(m_CurData + m_CurPos, m_BlockHeader.HeadSize - 7); - ReadHeaderReal(item); - if ((CrcCalc(m_CurData + 2, - m_BlockHeader.HeadSize - item.CommentSize - 2) & 0xFFFF) != m_BlockHeader.CRC) - ThrowExceptionWithCode(CInArchiveException::kFileHeaderCRCError); - - FinishCryptoBlock(); - m_CryptoMode = false; - SeekInArchive(m_Position); // Move Position to compressed Data; - AddToSeekValue(item.PackSize); // m_Position points to next header; - return S_OK; - } - if (m_CryptoMode && m_BlockHeader.HeadSize > (1 << 12)) - return E_FAIL; // it's for bad passwords - if ((m_BlockHeader.Flags & NHeader::NBlock::kLongBlock) != 0) - { - m_FileHeaderData.EnsureCapacity(7 + 4); - m_CurData = (Byte *)m_FileHeaderData; - ReadBytesAndTestResult(m_CurData + m_CurPos, 4); // test it - m_PosLimit = 7 + 4; - UInt32 dataSize = ReadUInt32(); - AddToSeekValue(dataSize); - if (m_CryptoMode && dataSize > (1 << 27)) - return E_FAIL; // it's for bad passwords - m_CryptoPos = m_BlockHeader.HeadSize; - } - else - m_CryptoPos = 0; - AddToSeekValue(m_BlockHeader.HeadSize); - FinishCryptoBlock(); - m_CryptoMode = false; - } -} - -bool CInArchive::SeekInArchive(UInt64 position) -{ - UInt64 newPosition; - m_Stream->Seek(position, STREAM_SEEK_SET, &newPosition); - return newPosition == position; -} - -ISequentialInStream* CInArchive::CreateLimitedStream(UInt64 position, UInt64 size) -{ - CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; - CMyComPtr inStream(streamSpec); - SeekInArchive(position); - streamSpec->SetStream(m_Stream); - streamSpec->Init(size); - return inStream.Detach(); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.h deleted file mode 100644 index 500f1134e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarIn.h +++ /dev/null @@ -1,126 +0,0 @@ -// RarIn.h - -#ifndef __ARCHIVE_RAR_IN_H -#define __ARCHIVE_RAR_IN_H - -#include "Common/DynamicBuffer.h" -#include "Common/MyCom.h" - -#include "../../ICoder.h" -#include "../../IStream.h" - -#include "../../Common/StreamObjects.h" - -#include "../../Crypto/RarAes.h" - -#include "RarHeader.h" -#include "RarItem.h" - -namespace NArchive { -namespace NRar { - -class CInArchiveException -{ -public: - enum CCauseType - { - kUnexpectedEndOfArchive = 0, - kArchiveHeaderCRCError, - kFileHeaderCRCError, - kIncorrectArchive - } - Cause; - CInArchiveException(CCauseType cause) : Cause(cause) {} -}; - -class CInArchiveInfo -{ -public: - UInt64 StartPosition; - UInt16 Flags; - UInt64 CommentPosition; - UInt16 CommentSize; - bool IsSolid() const { return (Flags & NHeader::NArchive::kSolid) != 0; } - bool IsCommented() const { return (Flags & NHeader::NArchive::kComment) != 0; } - bool IsVolume() const { return (Flags & NHeader::NArchive::kVolume) != 0; } - bool HaveNewVolumeName() const { return (Flags & NHeader::NArchive::kNewVolName) != 0; } - bool IsEncrypted() const { return (Flags & NHeader::NArchive::kBlockEncryption) != 0; } -}; - -class CInArchive -{ - CMyComPtr m_Stream; - - UInt64 m_StreamStartPosition; - UInt64 m_Position; - UInt64 m_ArchiveStartPosition; - - NHeader::NArchive::CHeader360 m_ArchiveHeader; - CDynamicBuffer m_NameBuffer; - CDynamicBuffer _unicodeNameBuffer; - bool m_SeekOnArchiveComment; - UInt64 m_ArchiveCommentPosition; - - void ReadName(CItemEx &item, int nameSize); - void ReadHeaderReal(CItemEx &item); - - HRESULT ReadBytes(void *data, UInt32 size, UInt32 *aProcessedSize); - bool ReadBytesAndTestSize(void *data, UInt32 size); - void ReadBytesAndTestResult(void *data, UInt32 size); - - HRESULT FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit); - HRESULT Open2(IInStream *stream, const UInt64 *searchHeaderSizeLimit); - - void ThrowExceptionWithCode(CInArchiveException::CCauseType cause); - void ThrowUnexpectedEndOfArchiveException(); - - void AddToSeekValue(UInt64 addValue); - -protected: - - CDynamicBuffer m_FileHeaderData; - - NHeader::NBlock::CBlock m_BlockHeader; - - NCrypto::NRar29::CDecoder *m_RarAESSpec; - CMyComPtr m_RarAES; - - Byte *m_CurData; // it must point to start of Rar::Block - UInt32 m_CurPos; - UInt32 m_PosLimit; - Byte ReadByte(); - UInt16 ReadUInt16(); - UInt32 ReadUInt32(); - void ReadTime(Byte mask, CRarTime &rarTime); - - CBuffer m_DecryptedData; - UInt32 m_DecryptedDataSize; - - bool m_CryptoMode; - UInt32 m_CryptoPos; - void FinishCryptoBlock() - { - if (m_CryptoMode) - while ((m_CryptoPos & 0xF) != 0) - { - m_CryptoPos++; - m_Position++; - } - } - -public: - HRESULT Open(IInStream *inStream, const UInt64 *searchHeaderSizeLimit); - void Close(); - HRESULT GetNextItem(CItemEx &item, ICryptoGetTextPassword *getTextPassword); - - void SkipArchiveComment(); - - void GetArchiveInfo(CInArchiveInfo &archiveInfo) const; - - bool SeekInArchive(UInt64 position); - ISequentialInStream *CreateLimitedStream(UInt64 position, UInt64 size); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.cpp deleted file mode 100644 index b0963778b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.cpp +++ /dev/null @@ -1,55 +0,0 @@ -// RarItem.cpp - -#include "StdAfx.h" - -#include "RarItem.h" - -namespace NArchive{ -namespace NRar{ - -bool CItem::IgnoreItem() const -{ - switch(HostOS) - { - case NHeader::NFile::kHostMSDOS: - case NHeader::NFile::kHostOS2: - case NHeader::NFile::kHostWin32: - return ((Attrib & NHeader::NFile::kLabelFileAttribute) != 0); - } - return false; -} - -bool CItem::IsDir() const -{ - if (GetDictSize() == NHeader::NFile::kDictDirectoryValue) - return true; - switch(HostOS) - { - case NHeader::NFile::kHostMSDOS: - case NHeader::NFile::kHostOS2: - case NHeader::NFile::kHostWin32: - if ((Attrib & FILE_ATTRIBUTE_DIRECTORY) != 0) - return true; - } - return false; -} - -UInt32 CItem::GetWinAttributes() const -{ - UInt32 winAttributes; - switch(HostOS) - { - case NHeader::NFile::kHostMSDOS: - case NHeader::NFile::kHostOS2: - case NHeader::NFile::kHostWin32: - winAttributes = Attrib; - break; - default: - winAttributes = 0; // must be converted from unix value; - } - if (IsDir()) - winAttributes |= NHeader::NFile::kWinFileDirectoryAttributeMask; - return winAttributes; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.h deleted file mode 100644 index 515ecd4be..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarItem.h +++ /dev/null @@ -1,79 +0,0 @@ -// RarItem.h - -#ifndef __ARCHIVE_RAR_ITEM_H -#define __ARCHIVE_RAR_ITEM_H - -#include "Common/Types.h" -#include "Common/MyString.h" - -#include "RarHeader.h" - -namespace NArchive{ -namespace NRar{ - -struct CRarTime -{ - UInt32 DosTime; - Byte LowSecond; - Byte SubTime[3]; -}; - -struct CItem -{ - UInt64 Size; - UInt64 PackSize; - - CRarTime CTime; - CRarTime ATime; - CRarTime MTime; - - UInt32 FileCRC; - UInt32 Attrib; - - UInt16 Flags; - Byte HostOS; - Byte UnPackVersion; - Byte Method; - - bool CTimeDefined; - bool ATimeDefined; - - AString Name; - UString UnicodeName; - - Byte Salt[8]; - - bool IsEncrypted() const { return (Flags & NHeader::NFile::kEncrypted) != 0; } - bool IsSolid() const { return (Flags & NHeader::NFile::kSolid) != 0; } - bool IsCommented() const { return (Flags & NHeader::NFile::kComment) != 0; } - bool IsSplitBefore() const { return (Flags & NHeader::NFile::kSplitBefore) != 0; } - bool IsSplitAfter() const { return (Flags & NHeader::NFile::kSplitAfter) != 0; } - bool HasSalt() const { return (Flags & NHeader::NFile::kSalt) != 0; } - bool HasExtTime() const { return (Flags & NHeader::NFile::kExtTime) != 0; } - bool HasUnicodeName()const { return (Flags & NHeader::NFile::kUnicodeName) != 0; } - bool IsOldVersion() const { return (Flags & NHeader::NFile::kOldVersion) != 0; } - - UInt32 GetDictSize() const { return (Flags >> NHeader::NFile::kDictBitStart) & NHeader::NFile::kDictMask; } - bool IsDir() const; - bool IgnoreItem() const; - UInt32 GetWinAttributes() const; - - CItem(): CTimeDefined(false), ATimeDefined(false) {} -}; - -class CItemEx: public CItem -{ -public: - UInt64 Position; - UInt16 MainPartSize; - UInt16 CommentSize; - UInt16 AlignSize; - UInt64 GetFullSize() const { return MainPartSize + CommentSize + AlignSize + PackSize; }; - // DWORD GetHeaderWithCommentSize() const { return MainPartSize + CommentSize; }; - UInt64 GetCommentPosition() const { return Position + MainPartSize; }; - UInt64 GetDataPosition() const { return GetCommentPosition() + CommentSize + AlignSize; }; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarRegister.cpp deleted file mode 100644 index f7897a607..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarRegister.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// RarRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "RarHandler.h" -static IInArchive *CreateArc() { return new NArchive::NRar::CHandler; } - -static CArcInfo g_ArcInfo = - { L"Rar", L"rar r00", 0, 3, {0x52 , 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00}, 7, false, CreateArc, 0, }; - -REGISTER_ARC(Rar) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.cpp deleted file mode 100644 index 8b62d9fd9..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// RarVolumeInStream.cpp - -#include "StdAfx.h" - -#include "RarVolumeInStream.h" - -#include "Windows/Defs.h" -#include "Common/Defs.h" - -extern "C" -{ - #include "../../../../C/7zCrc.h" -} - -namespace NArchive { -namespace NRar { - -void CFolderInStream::Init( - CObjectVector *archives, - const CObjectVector *items, - const CRefItem &refItem) -{ - _archives = archives; - _items = items; - _refItem = refItem; - _curIndex = 0; - CRCs.Clear(); - _fileIsOpen = false; -} - -HRESULT CFolderInStream::OpenStream() -{ - while (_curIndex < _refItem.NumItems) - { - const CItemEx &item = (*_items)[_refItem.ItemIndex + _curIndex]; - _stream.Attach((*_archives)[_refItem.VolumeIndex + _curIndex]. - CreateLimitedStream(item.GetDataPosition(), item.PackSize)); - _curIndex++; - _fileIsOpen = true; - _crc = CRC_INIT_VAL; - return S_OK; - } - return S_OK; -} - -HRESULT CFolderInStream::CloseStream() -{ - CRCs.Add(CRC_GET_DIGEST(_crc)); - _stream.Release(); - _fileIsOpen = false; - return S_OK; -} - -STDMETHODIMP CFolderInStream::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize = 0; - while ((_curIndex < _refItem.NumItems || _fileIsOpen) && size > 0) - { - if (_fileIsOpen) - { - UInt32 localProcessedSize; - RINOK(_stream->Read( - ((Byte *)data) + realProcessedSize, size, &localProcessedSize)); - _crc = CrcUpdate(_crc, ((Byte *)data) + realProcessedSize, localProcessedSize); - if (localProcessedSize == 0) - { - RINOK(CloseStream()); - continue; - } - realProcessedSize += localProcessedSize; - size -= localProcessedSize; - break; - } - else - { - RINOK(OpenStream()); - } - } - if (processedSize != 0) - *processedSize = realProcessedSize; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.h deleted file mode 100644 index d175a2c0c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/RarVolumeInStream.h +++ /dev/null @@ -1,49 +0,0 @@ -// RarVolumeInStream.h - -#ifndef __RAR_VOLUME_IN_STREAM_H -#define __RAR_VOLUME_IN_STREAM_H - -#include "../../IStream.h" -#include "RarIn.h" - -namespace NArchive { -namespace NRar { - -struct CRefItem -{ - int VolumeIndex; - int ItemIndex; - int NumItems; -}; - -class CFolderInStream: - public ISequentialInStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - -private: - CObjectVector *_archives; - const CObjectVector *_items; - CRefItem _refItem; - int _curIndex; - UInt32 _crc; - bool _fileIsOpen; - CMyComPtr _stream; - - HRESULT OpenStream(); - HRESULT CloseStream(); -public: - void Init(CObjectVector *archives, - const CObjectVector *items, - const CRefItem &refItem); - - CRecordVector CRCs; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Rar/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Rar/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.cpp deleted file mode 100644 index 36be6cc3b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.cpp +++ /dev/null @@ -1,357 +0,0 @@ -// SplitHandler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" -#include "Common/Defs.h" -#include "Common/NewHandler.h" -#include "Common/StringConvert.h" - -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "../../Common/ProgressUtils.h" - -#include "../../Compress/CopyCoder.h" - -#include "../Common/ItemNameUtils.h" -#include "../Common/MultiStream.h" - -#include "SplitHandler.h" - -using namespace NWindows; -using namespace NTime; - -namespace NArchive { -namespace NSplit { - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -class CSeqName -{ -public: - UString _unchangedPart; - UString _changedPart; - bool _splitStyle; - UString GetNextName() - { - UString newName; - if (_splitStyle) - { - int i; - int numLetters = _changedPart.Length(); - for (i = numLetters - 1; i >= 0; i--) - { - wchar_t c = _changedPart[i]; - if (c == 'z') - { - c = 'a'; - newName = c + newName; - continue; - } - else if (c == 'Z') - { - c = 'A'; - newName = c + newName; - continue; - } - c++; - if ((c == 'z' || c == 'Z') && i == 0) - { - _unchangedPart += c; - wchar_t newChar = (c == 'z') ? L'a' : L'A'; - newName.Empty(); - numLetters++; - for (int k = 0; k < numLetters; k++) - newName += newChar; - break; - } - newName = c + newName; - i--; - for (; i >= 0; i--) - newName = _changedPart[i] + newName; - break; - } - } - else - { - int i; - int numLetters = _changedPart.Length(); - for (i = numLetters - 1; i >= 0; i--) - { - wchar_t c = _changedPart[i]; - if (c == L'9') - { - c = L'0'; - newName = c + newName; - if (i == 0) - newName = UString(L'1') + newName; - continue; - } - c++; - newName = c + newName; - i--; - for (; i >= 0; i--) - newName = _changedPart[i] + newName; - break; - } - } - _changedPart = newName; - return _unchangedPart + _changedPart; - } -}; - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback *openArchiveCallback) -{ - COM_TRY_BEGIN - Close(); - if (openArchiveCallback == 0) - return S_FALSE; - // try - { - CMyComPtr openVolumeCallback; - CMyComPtr openArchiveCallbackWrap = openArchiveCallback; - if (openArchiveCallbackWrap.QueryInterface(IID_IArchiveOpenVolumeCallback, - &openVolumeCallback) != S_OK) - return S_FALSE; - - { - NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidName, &prop)); - if (prop.vt != VT_BSTR) - return S_FALSE; - _name = prop.bstrVal; - } - - int dotPos = _name.ReverseFind('.'); - UString prefix, ext; - if (dotPos >= 0) - { - prefix = _name.Left(dotPos + 1); - ext = _name.Mid(dotPos + 1); - } - else - ext = _name; - UString extBig = ext; - extBig.MakeUpper(); - - CSeqName seqName; - - int numLetters = 2; - bool splitStyle = false; - if (extBig.Right(2) == L"AA") - { - splitStyle = true; - while (numLetters < extBig.Length()) - { - if (extBig[extBig.Length() - numLetters - 1] != 'A') - break; - numLetters++; - } - } - else if (ext.Right(2) == L"01") - { - while (numLetters < extBig.Length()) - { - if (extBig[extBig.Length() - numLetters - 1] != '0') - break; - numLetters++; - } - if (numLetters != ext.Length()) - return S_FALSE; - } - else - return S_FALSE; - - _streams.Add(stream); - - seqName._unchangedPart = prefix + ext.Left(extBig.Length() - numLetters); - seqName._changedPart = ext.Right(numLetters); - seqName._splitStyle = splitStyle; - - if (prefix.Length() < 1) - _subName = L"file"; - else - _subName = prefix.Left(prefix.Length() - 1); - - _totalSize = 0; - UInt64 size; - { - NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidSize, &prop)); - if (prop.vt != VT_UI8) - return E_INVALIDARG; - size = prop.uhVal.QuadPart; - } - _totalSize += size; - _sizes.Add(size); - - if (openArchiveCallback != NULL) - { - UInt64 numFiles = _streams.Size(); - RINOK(openArchiveCallback->SetCompleted(&numFiles, NULL)); - } - - for (;;) - { - UString fullName = seqName.GetNextName(); - CMyComPtr nextStream; - HRESULT result = openVolumeCallback->GetStream(fullName, &nextStream); - if (result == S_FALSE) - break; - if (result != S_OK) - return result; - if (!stream) - break; - { - NCOM::CPropVariant prop; - RINOK(openVolumeCallback->GetProperty(kpidSize, &prop)); - if (prop.vt != VT_UI8) - return E_INVALIDARG; - size = prop.uhVal.QuadPart; - } - _totalSize += size; - _sizes.Add(size); - _streams.Add(nextStream); - if (openArchiveCallback != NULL) - { - UInt64 numFiles = _streams.Size(); - RINOK(openArchiveCallback->SetCompleted(&numFiles, NULL)); - } - } - } - /* - catch(...) - { - return S_FALSE; - } - */ - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - _sizes.Clear(); - _streams.Clear(); - return S_OK; -} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = _streams.IsEmpty() ? 0 : 1; - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value) -{ - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case kpidPath: - prop = _subName; - break; - case kpidSize: - case kpidPackSize: - prop = _totalSize; - break; - } - prop.Detach(value); - return S_OK; -} - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *_anExtractCallback) -{ - COM_TRY_BEGIN - - if (numItems != UInt32(-1)) - { - if (numItems != 1) - return E_INVALIDARG; - if (indices[0] != 0) - return E_INVALIDARG; - } - bool testMode = (_aTestMode != 0); - CMyComPtr extractCallback = _anExtractCallback; - extractCallback->SetTotal(_totalSize); - - /* - CMyComPtr volumeExtractCallback; - if (extractCallback.QueryInterface(&volumeExtractCallback) != S_OK) - return E_FAIL; - */ - - UInt64 currentTotalSize = 0; - UInt64 currentItemSize; - - RINOK(extractCallback->SetCompleted(¤tTotalSize)); - CMyComPtr realOutStream; - Int32 askMode; - askMode = testMode ? NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - Int32 index = 0; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - - RINOK(extractCallback->PrepareOperation(askMode)); - if (testMode) - { - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK)); - return S_OK; - } - - if (!testMode && (!realOutStream)) - return S_OK; - - NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder; - CMyComPtr copyCoder = copyCoderSpec; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - for (int i = 0; i < _streams.Size(); i++, currentTotalSize += currentItemSize) - { - lps->InSize = lps->OutSize = currentTotalSize; - RINOK(lps->SetCur()); - IInStream *inStream = _streams[i]; - RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL)); - RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); - currentItemSize = copyCoderSpec->TotalSize; - } - realOutStream.Release(); - return extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK); - COM_TRY_END -} - -STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) -{ - if (index != 0) - return E_INVALIDARG; - *stream = 0; - CMultiStream *streamSpec = new CMultiStream; - CMyComPtr streamTemp = streamSpec; - for (int i = 0; i < _streams.Size(); i++) - { - CMultiStream::CSubStreamInfo subStreamInfo; - subStreamInfo.Stream = _streams[i]; - subStreamInfo.Pos = 0; - subStreamInfo.Size = _sizes[i]; - streamSpec->Streams.Add(subStreamInfo); - } - streamSpec->Init(); - *stream = streamTemp.Detach(); - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.h deleted file mode 100644 index c323490ae..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitHandler.h +++ /dev/null @@ -1,37 +0,0 @@ -// Split/Handler.h - -#ifndef __SPLIT_HANDLER_H -#define __SPLIT_HANDLER_H - -#include "Common/MyCom.h" -#include "Common/MyString.h" -#include "../IArchive.h" - -namespace NArchive { -namespace NSplit { - -class CHandler: - public IInArchive, - public IInArchiveGetStream, - // public IOutArchive, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream) - - INTERFACE_IInArchive(;) - - STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); - -private: - UString _subName; - UString _name; - CObjectVector > _streams; - CRecordVector _sizes; - - UInt64 _totalSize; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitRegister.cpp deleted file mode 100644 index 691a3829c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Split/SplitRegister.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// SplitRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "SplitHandler.h" -static IInArchive *CreateArc() { return new NArchive::NSplit::CHandler; } -/* -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::NSplit::CHandler; } -#else -#define CreateArcOut 0 -#endif -*/ - -static CArcInfo g_ArcInfo = -{ L"Split", L"001", 0, 0xEA, { 0 }, 0, false, CreateArc, 0 }; - -REGISTER_ARC(Split) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Split/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Split/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Split/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/StdAfx.h deleted file mode 100644 index f56e92fd8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/StdAfx.h +++ /dev/null @@ -1,9 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../Common/MyWindows.h" -#include "../../Common/NewHandler.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/StdAfx.h deleted file mode 100644 index a4e617312..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/StdAfx.h +++ /dev/null @@ -1,9 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" -#include "../../../Common/NewHandler.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.cpp deleted file mode 100644 index b1e34fff7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.cpp +++ /dev/null @@ -1,229 +0,0 @@ -// TarHandler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" -#include "Common/Defs.h" -#include "Common/NewHandler.h" -#include "Common/StringConvert.h" - -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "../../Common/LimitedStreams.h" -#include "../../Common/ProgressUtils.h" - -#include "../../Compress/CopyCoder.h" - -#include "../Common/DummyOutStream.h" -#include "../Common/ItemNameUtils.h" - -#include "TarHandler.h" -#include "TarIn.h" - -using namespace NWindows; - -namespace NArchive { -namespace NTar { - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidIsDir, VT_BOOL}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMTime, VT_FILETIME}, - { NULL, kpidUser, VT_BSTR}, - { NULL, kpidGroup, VT_BSTR} -}; - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps_NO - -HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback) -{ - UInt64 endPos = 0; - if (callback != NULL) - { - RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos)); - RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL)); - } - - UInt64 pos = 0; - for (;;) - { - CItemEx item; - bool filled; - item.HeaderPosition = pos; - RINOK(ReadItem(stream, filled, item)); - if (!filled) - break; - _items.Add(item); - - RINOK(stream->Seek(item.GetPackSize(), STREAM_SEEK_CUR, &pos)); - if (pos >= endPos) - return S_FALSE; - if (callback != NULL) - { - if (_items.Size() == 1) - { - RINOK(callback->SetTotal(NULL, &endPos)); - } - if (_items.Size() % 100 == 0) - { - UInt64 numFiles = _items.Size(); - RINOK(callback->SetCompleted(&numFiles, &pos)); - } - } - } - - if (_items.Size() == 0) - { - CMyComPtr openVolumeCallback; - if (!callback) - return S_FALSE; - callback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback); - if (!openVolumeCallback) - return S_FALSE; - NCOM::CPropVariant prop; - if (openVolumeCallback->GetProperty(kpidName, &prop) != S_OK) - return S_FALSE; - if (prop.vt != VT_BSTR) - return S_FALSE; - UString baseName = prop.bstrVal; - baseName = baseName.Right(4); - if (baseName.CompareNoCase(L".tar") != 0) - return S_FALSE; - } - return S_OK; -} - -STDMETHODIMP CHandler::Open(IInStream *stream, - const UInt64 * /* maxCheckStartPosition */, - IArchiveOpenCallback *openArchiveCallback) -{ - COM_TRY_BEGIN - { - Close(); - RINOK(Open2(stream, openArchiveCallback)); - _inStream = stream; - } - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - _items.Clear(); - _inStream.Release(); - return S_OK; -} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = _items.Size(); - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - const CItemEx &item = _items[index]; - - switch(propID) - { - case kpidPath: prop = NItemName::GetOSName2(MultiByteToUnicodeString(item.Name, CP_OEMCP)); break; - case kpidIsDir: prop = item.IsDir(); break; - case kpidSize: prop = item.Size; break; - case kpidPackSize: prop = item.GetPackSize(); break; - case kpidMTime: - if (item.MTime != 0) - { - FILETIME ft; - NTime::UnixTimeToFileTime(item.MTime, ft); - prop = ft; - } - break; - case kpidUser: prop = MultiByteToUnicodeString(item.UserName, CP_OEMCP); break; - case kpidGroup: prop = MultiByteToUnicodeString(item.GroupName, CP_OEMCP); break; - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - bool testMode = (_aTestMode != 0); - bool allFilesMode = (numItems == UInt32(-1)); - if (allFilesMode) - numItems = _items.Size(); - if (numItems == 0) - return S_OK; - UInt64 totalSize = 0; - UInt32 i; - for (i = 0; i < numItems; i++) - totalSize += _items[allFilesMode ? i : indices[i]].Size; - extractCallback->SetTotal(totalSize); - - UInt64 totalPackSize, curPackSize, curSize; - totalSize = totalPackSize = 0; - - NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder(); - CMyComPtr copyCoder = copyCoderSpec; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; - CMyComPtr inStream(streamSpec); - streamSpec->SetStream(_inStream); - - CDummyOutStream *outStreamSpec = new CDummyOutStream; - CMyComPtr outStream(outStreamSpec); - - for (i = 0; i < numItems; i++, totalSize += curSize, totalPackSize += curPackSize) - { - lps->InSize = totalPackSize; - lps->OutSize = totalSize; - RINOK(lps->SetCur()); - CMyComPtr realOutStream; - Int32 askMode = testMode ? - NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; - const CItemEx &item = _items[index]; - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - curSize = item.Size; - curPackSize = item.GetPackSize(); - if (item.IsDir()) - { - RINOK(extractCallback->PrepareOperation(askMode)); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK)); - continue; - } - if (!testMode && (!realOutStream)) - continue; - RINOK(extractCallback->PrepareOperation(askMode)); - - outStreamSpec->SetStream(realOutStream); - realOutStream.Release(); - outStreamSpec->Init(); - - RINOK(_inStream->Seek(item.GetDataPosition(), STREAM_SEEK_SET, NULL)); - streamSpec->Init(item.Size); - RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); - outStreamSpec->ReleaseStream(); - RINOK(extractCallback->SetOperationResult(copyCoderSpec->TotalSize == item.Size ? - NArchive::NExtract::NOperationResult::kOK: - NArchive::NExtract::NOperationResult::kDataError)); - } - return S_OK; - COM_TRY_END -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.h deleted file mode 100644 index 38792b25a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHandler.h +++ /dev/null @@ -1,37 +0,0 @@ -// Tar/Handler.h - -#ifndef __TAR_HANDLER_H -#define __TAR_HANDLER_H - -#include "Common/MyCom.h" -#include "../IArchive.h" - -#include "TarItem.h" - -namespace NArchive { -namespace NTar { - -class CHandler: - public IInArchive, - public IOutArchive, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP2( - IInArchive, - IOutArchive - ) - - INTERFACE_IInArchive(;) - INTERFACE_IOutArchive(;) - - HRESULT Open2(IInStream *stream, IArchiveOpenCallback *callback); - -private: - CObjectVector _items; - CMyComPtr _inStream; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.cpp deleted file mode 100644 index 9304388bc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// Archive/Tar/Header.h - -#include "StdAfx.h" - -#include "TarHeader.h" - -namespace NArchive { -namespace NTar { -namespace NFileHeader { - - // The checksum field is filled with this while the checksum is computed. - const char *kCheckSumBlanks = " "; // 8 blanks, no null - - const char *kLongLink = "././@LongLink"; - const char *kLongLink2 = "@LongLink"; - - // The magic field is filled with this if uname and gname are valid. - namespace NMagic - { - const char *kUsTar = "ustar"; // 5 chars - const char *kGNUTar = "GNUtar "; // 7 chars and a null - const char *kEmpty = "\0\0\0\0\0\0\0\0"; // 7 chars and a null - } - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.h deleted file mode 100644 index dece1f7f4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarHeader.h +++ /dev/null @@ -1,108 +0,0 @@ -// Archive/Tar/Header.h - -#ifndef __ARCHIVE_TAR_HEADER_H -#define __ARCHIVE_TAR_HEADER_H - -#include "Common/Types.h" - -namespace NArchive { -namespace NTar { - -namespace NFileHeader -{ - const int kRecordSize = 512; - const int kNameSize = 100; - const int kUserNameSize = 32; - const int kGroupNameSize = 32; - const int kPrefixSize = 155; - - /* - struct CHeader - { - char Name[kNameSize]; - char Mode[8]; - char UID[8]; - char GID[8]; - char Size[12]; - char ModificationTime[12]; - char CheckSum[8]; - char LinkFlag; - char LinkName[kNameSize]; - char Magic[8]; - char UserName[kUserNameSize]; - char GroupName[kGroupNameSize]; - char DeviceMajor[8]; - char DeviceMinor[8]; - char Prefix[155]; - }; - union CRecord - { - CHeader Header; - Byte Padding[kRecordSize]; - }; - */ - - namespace NMode - { - const int kSetUID = 04000; // Set UID on execution - const int kSetGID = 02000; // Set GID on execution - const int kSaveText = 01000; // Save text (sticky bit) - } - - namespace NFilePermissions - { - const int kUserRead = 00400; // read by owner - const int kUserWrite = 00200; // write by owner - const int kUserExecute = 00100; // execute/search by owner - const int kGroupRead = 00040; // read by group - const int kGroupWrite = 00020; // write by group - const int kGroupExecute = 00010; // execute/search by group - const int kOtherRead = 00004; // read by other - const int kOtherWrite = 00002; // write by other - const int kOtherExecute = 00001; // execute/search by other - } - - - // The linkflag defines the type of file - namespace NLinkFlag - { - const char kOldNormal = '\0'; // Normal disk file, Unix compatible - const char kNormal = '0'; // Normal disk file - const char kLink = '1'; // Link to previously dumped file - const char kSymbolicLink = '2'; // Symbolic link - const char kCharacter = '3'; // Character special file - const char kBlock = '4'; // Block special file - const char kDirectory = '5'; // Directory - const char kFIFO = '6'; // FIFO special file - const char kContiguous = '7'; // Contiguous file - - const char kDumpDir = 'D'; /* GNUTYPE_DUMPDIR. - data: list of files created by the --incremental (-G) option - Each file name is preceded by either - - 'Y' (file should be in this archive) - - 'N' (file is a directory, or is not stored in the archive.) - Each file name is terminated by a null + an additional null after - the last file name. */ - - } - // Further link types may be defined later. - - // The checksum field is filled with this while the checksum is computed. - extern const char *kCheckSumBlanks;// = " "; // 8 blanks, no null - - extern const char *kLongLink; // = "././@LongLink"; - extern const char *kLongLink2; // = "@LongLink"; - - // The magic field is filled with this if uname and gname are valid. - namespace NMagic - { - extern const char *kUsTar; // = "ustar"; // 5 chars - extern const char *kGNUTar; // = "GNUtar "; // 7 chars and a null - extern const char *kEmpty; // = "GNUtar "; // 7 chars and a null - } - -} - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.cpp deleted file mode 100644 index 85702eb2b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.cpp +++ /dev/null @@ -1,176 +0,0 @@ -// Archive/TarIn.cpp - -#include "StdAfx.h" - -#include "TarIn.h" -#include "TarHeader.h" - -#include "Common/StringToInt.h" -#include "Windows/Defs.h" - -#include "../../Common/StreamUtils.h" - -namespace NArchive { -namespace NTar { - -static void MyStrNCpy(char *dest, const char *src, int size) -{ - for (int i = 0; i < size; i++) - { - char c = src[i]; - dest[i] = c; - if (c == 0) - break; - } -} - -static bool OctalToNumber(const char *srcString, int size, UInt64 &res) -{ - char sz[32]; - MyStrNCpy(sz, srcString, size); - sz[size] = 0; - const char *end; - int i; - for (i = 0; sz[i] == ' '; i++); - res = ConvertOctStringToUInt64(sz + i, &end); - return (*end == ' ' || *end == 0); -} - -static bool OctalToNumber32(const char *srcString, int size, UInt32 &res) -{ - UInt64 res64; - if (!OctalToNumber(srcString, size, res64)) - return false; - res = (UInt32)res64; - return (res64 <= 0xFFFFFFFF); -} - -#define RIF(x) { if (!(x)) return S_FALSE; } - -static bool IsRecordLast(const char *buf) -{ - for (int i = 0; i < NFileHeader::kRecordSize; i++) - if (buf[i] != 0) - return false; - return true; -} - -static void ReadString(const char *s, int size, AString &result) -{ - char temp[NFileHeader::kRecordSize + 1]; - MyStrNCpy(temp, s, size); - temp[size] = '\0'; - result = temp; -} - -static HRESULT GetNextItemReal(ISequentialInStream *stream, bool &filled, CItemEx &item, size_t &processedSize) -{ - item.LongLinkSize = 0; - char buf[NFileHeader::kRecordSize]; - char *p = buf; - - filled = false; - - processedSize = NFileHeader::kRecordSize; - RINOK(ReadStream(stream, buf, &processedSize)); - if (processedSize == 0 || (processedSize == NFileHeader::kRecordSize && IsRecordLast(buf))) - return S_OK; - if (processedSize < NFileHeader::kRecordSize) - return S_FALSE; - - ReadString(p, NFileHeader::kNameSize, item.Name); p += NFileHeader::kNameSize; - - RIF(OctalToNumber32(p, 8, item.Mode)); p += 8; - - if (!OctalToNumber32(p, 8, item.UID)) item.UID = 0; p += 8; - if (!OctalToNumber32(p, 8, item.GID)) item.GID = 0; p += 8; - - RIF(OctalToNumber(p, 12, item.Size)); p += 12; - RIF(OctalToNumber32(p, 12, item.MTime)); p += 12; - - UInt32 checkSum; - RIF(OctalToNumber32(p, 8, checkSum)); - memcpy(p, NFileHeader::kCheckSumBlanks, 8); p += 8; - - item.LinkFlag = *p++; - - ReadString(p, NFileHeader::kNameSize, item.LinkName); p += NFileHeader::kNameSize; - - memcpy(item.Magic, p, 8); p += 8; - - ReadString(p, NFileHeader::kUserNameSize, item.UserName); p += NFileHeader::kUserNameSize; - ReadString(p, NFileHeader::kUserNameSize, item.GroupName); p += NFileHeader::kUserNameSize; - - item.DeviceMajorDefined = (p[0] != 0); RIF(OctalToNumber32(p, 8, item.DeviceMajor)); p += 8; - item.DeviceMinorDefined = (p[0] != 0); RIF(OctalToNumber32(p, 8, item.DeviceMinor)); p += 8; - - AString prefix; - ReadString(p, NFileHeader::kPrefixSize, prefix); - p += NFileHeader::kPrefixSize; - if (!prefix.IsEmpty() && item.IsMagic() && - (item.LinkFlag != 'L' /* || prefix != "00000000000" */ )) - item.Name = prefix + AString('/') + item.Name; - - if (item.LinkFlag == NFileHeader::NLinkFlag::kLink) - item.Size = 0; - - UInt32 checkSumReal = 0; - for (int i = 0; i < NFileHeader::kRecordSize; i++) - checkSumReal += (Byte)buf[i]; - - if (checkSumReal != checkSum) - return S_FALSE; - - filled = true; - return S_OK; -} - -HRESULT ReadItem(ISequentialInStream *stream, bool &filled, CItemEx &item) -{ - size_t processedSize; - RINOK(GetNextItemReal(stream, filled, item, processedSize)); - if (!filled) - return S_OK; - // GNUtar extension - if (item.LinkFlag == 'L') - { - if (item.Name.Compare(NFileHeader::kLongLink) != 0) - if (item.Name.Compare(NFileHeader::kLongLink2) != 0) - return S_FALSE; - - AString fullName; - if (item.Size > (1 << 15)) - return S_FALSE; - int packSize = (int)item.GetPackSize(); - char *buffer = fullName.GetBuffer(packSize + 1); - - RINOK(ReadStream_FALSE(stream, buffer, packSize)); - processedSize += packSize; - buffer[item.Size] = '\0'; - fullName.ReleaseBuffer(); - - UInt64 headerPosition = item.HeaderPosition; - { - size_t processedSize2; - RINOK(GetNextItemReal(stream, filled, item, processedSize2)); - } - item.LongLinkSize = (unsigned)processedSize; - item.Name = fullName; - item.HeaderPosition = headerPosition; - } - else if (item.LinkFlag == 'g' || item.LinkFlag == 'x' || item.LinkFlag == 'X') - { - // pax Extended Header - return S_OK; - } - else if (item.LinkFlag == NFileHeader::NLinkFlag::kDumpDir) - { - // GNU Extensions to the Archive Format - return S_OK; - } - else if (item.LinkFlag > '7' || (item.LinkFlag < '0' && item.LinkFlag != 0)) - return S_FALSE; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.h deleted file mode 100644 index 546ad1966..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarIn.h +++ /dev/null @@ -1,18 +0,0 @@ -// Archive/TarIn.h - -#ifndef __ARCHIVE_TAR_IN_H -#define __ARCHIVE_TAR_IN_H - -#include "Common/MyCom.h" -#include "../../IStream.h" - -#include "TarItem.h" - -namespace NArchive { -namespace NTar { - -HRESULT ReadItem(ISequentialInStream *stream, bool &filled, CItemEx &itemInfo); - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarItem.h deleted file mode 100644 index 54beefcc4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarItem.h +++ /dev/null @@ -1,71 +0,0 @@ -// Archive/Tar/Item.h - -#ifndef __ARCHIVE_TAR_ITEM_H -#define __ARCHIVE_TAR_ITEM_H - -#include "Common/Types.h" -#include "Common/MyString.h" - -#include "../Common/ItemNameUtils.h" -#include "TarHeader.h" - -namespace NArchive { -namespace NTar { - -struct CItem -{ - AString Name; - UInt64 Size; - - UInt32 Mode; - UInt32 UID; - UInt32 GID; - UInt32 MTime; - UInt32 DeviceMajor; - UInt32 DeviceMinor; - - AString LinkName; - AString UserName; - AString GroupName; - - char Magic[8]; - char LinkFlag; - bool DeviceMajorDefined; - bool DeviceMinorDefined; - - bool IsDir() const - { - switch(LinkFlag) - { - case NFileHeader::NLinkFlag::kDirectory: - case NFileHeader::NLinkFlag::kDumpDir: - return true; - case NFileHeader::NLinkFlag::kOldNormal: - case NFileHeader::NLinkFlag::kNormal: - return NItemName::HasTailSlash(Name, CP_OEMCP); - } - return false; - } - - bool IsMagic() const - { - for (int i = 0; i < 5; i++) - if (Magic[i] != NFileHeader::NMagic::kUsTar[i]) - return false; - return true; - } - - UInt64 GetPackSize() const { return (Size + 0x1FF) & (~((UInt64)0x1FF)); } -}; - -struct CItemEx: public CItem -{ - UInt64 HeaderPosition; - unsigned LongLinkSize; - UInt64 GetDataPosition() const { return HeaderPosition + LongLinkSize + NFileHeader::kRecordSize; } - UInt64 GetFullSize() const { return LongLinkSize + NFileHeader::kRecordSize + Size; } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarRegister.cpp deleted file mode 100644 index 17eccb7b3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Tar/TarRegister.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// TarRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "TarHandler.h" -static IInArchive *CreateArc() { return new NArchive::NTar::CHandler; } -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::NTar::CHandler; } -#else -#define CreateArcOut 0 -#endif - -static CArcInfo g_ArcInfo = -{ L"Tar", L"tar", 0, 0xEE, { 'u', 's', 't', 'a', 'r' }, 5, false, CreateArc, CreateArcOut }; - -REGISTER_ARC(Tar) diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/StdAfx.h deleted file mode 100644 index 83fdd22d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipCompressionMode.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipCompressionMode.h deleted file mode 100644 index f3c105e81..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipCompressionMode.h +++ /dev/null @@ -1,39 +0,0 @@ -// CompressionMode.h - -#ifndef __ZIP_COMPRESSIONMETHOD_H -#define __ZIP_COMPRESSIONMETHOD_H - -#include "../../../Common/MyString.h" - -namespace NArchive { -namespace NZip { - -struct CCompressionMethodMode -{ - CRecordVector MethodSequence; - UString MatchFinder; - UInt32 Algo; - UInt32 NumPasses; - UInt32 NumFastBytes; - bool NumMatchFinderCyclesDefined; - UInt32 NumMatchFinderCycles; - UInt32 DicSize; - #ifdef COMPRESS_MT - UInt32 NumThreads; - #endif - bool PasswordIsDefined; - AString Password; - bool IsAesMode; - Byte AesKeyMode; - - CCompressionMethodMode(): - NumMatchFinderCyclesDefined(false), - PasswordIsDefined(false), - IsAesMode(false), - AesKeyMode(3) - {} -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.cpp deleted file mode 100644 index 43f1cf996..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.cpp +++ /dev/null @@ -1,831 +0,0 @@ -// ZipHandler.cpp - -#include "StdAfx.h" - -#include "Common/ComTry.h" -#include "Common/Defs.h" -#include "Common/IntToString.h" -#include "Common/StringConvert.h" - -#include "Windows/PropVariant.h" -#include "Windows/Time.h" - -#include "../../IPassword.h" - -#include "../../Common/CreateCoder.h" -#include "../../Common/FilterCoder.h" -#include "../../Common/ProgressUtils.h" -#include "../../Common/StreamObjects.h" -#include "../../Common/StreamUtils.h" - -#include "../../Compress/CopyCoder.h" -#include "../../Compress/LzmaDecoder.h" -#include "../../Compress/ImplodeDecoder.h" -#include "../../Compress/ShrinkDecoder.h" - -#include "../../Crypto/WzAes.h" -#include "../../Crypto/ZipCrypto.h" -#include "../../Crypto/ZipStrong.h" - -#include "../Common/ItemNameUtils.h" -#include "../Common/OutStreamWithCRC.h" - -#include "ZipHandler.h" - -using namespace NWindows; - -namespace NArchive { -namespace NZip { - -// static const CMethodId kMethodId_Store = 0; -static const CMethodId kMethodId_ZipBase = 0x040100; -static const CMethodId kMethodId_BZip2 = 0x040202; - -const wchar_t *kHostOS[] = -{ - L"FAT", - L"AMIGA", - L"VMS", - L"Unix", - L"VM/CMS", - L"Atari", - L"HPFS", - L"Macintosh", - L"Z-System", - L"CP/M", - L"TOPS-20", - L"NTFS", - L"SMS/QDOS", - L"Acorn", - L"VFAT", - L"MVS", - L"BeOS", - L"Tandem", - L"OS/400", - L"OS/X" -}; - - -static const int kNumHostOSes = sizeof(kHostOS) / sizeof(kHostOS[0]); - -static const wchar_t *kUnknownOS = L"Unknown"; - -STATPROPSTG kProps[] = -{ - { NULL, kpidPath, VT_BSTR}, - { NULL, kpidIsDir, VT_BOOL}, - { NULL, kpidSize, VT_UI8}, - { NULL, kpidPackSize, VT_UI8}, - { NULL, kpidMTime, VT_FILETIME}, - { NULL, kpidCTime, VT_FILETIME}, - { NULL, kpidATime, VT_FILETIME}, - - { NULL, kpidAttrib, VT_UI4}, - - { NULL, kpidEncrypted, VT_BOOL}, - { NULL, kpidComment, VT_BSTR}, - - { NULL, kpidCRC, VT_UI4}, - - { NULL, kpidMethod, VT_BSTR}, - { NULL, kpidHostOS, VT_BSTR} - - // { NULL, kpidUnpackVer, VT_UI1}, -}; - -const wchar_t *kMethods[] = -{ - L"Store", - L"Shrink", - L"Reduced1", - L"Reduced2", - L"Reduced2", - L"Reduced3", - L"Implode", - L"Tokenizing", - L"Deflate", - L"Deflate64", - L"PKImploding" -}; - -const int kNumMethods = sizeof(kMethods) / sizeof(kMethods[0]); -const wchar_t *kBZip2Method = L"BZip2"; -const wchar_t *kLZMAMethod = L"LZMA"; -const wchar_t *kJpegMethod = L"Jpeg"; -const wchar_t *kWavPackMethod = L"WavPack"; -const wchar_t *kPPMdMethod = L"PPMd"; -const wchar_t *kAESMethod = L"AES"; -const wchar_t *kZipCryptoMethod = L"ZipCrypto"; -const wchar_t *kStrongCryptoMethod = L"StrongCrypto"; - -struct CStrongCryptoPair -{ - UInt16 Id; - const wchar_t *Name; -}; - -CStrongCryptoPair g_StrongCryptoPairs[] = -{ - { NStrongCryptoFlags::kDES, L"DES" }, - { NStrongCryptoFlags::kRC2old, L"RC2a" }, - { NStrongCryptoFlags::k3DES168, L"3DES-168" }, - { NStrongCryptoFlags::k3DES112, L"3DES-112" }, - { NStrongCryptoFlags::kAES128, L"pkAES-128" }, - { NStrongCryptoFlags::kAES192, L"pkAES-192" }, - { NStrongCryptoFlags::kAES256, L"pkAES-256" }, - { NStrongCryptoFlags::kRC2, L"RC2" }, - { NStrongCryptoFlags::kBlowfish, L"Blowfish" }, - { NStrongCryptoFlags::kTwofish, L"Twofish" }, - { NStrongCryptoFlags::kRC4, L"RC4" } -}; - -STATPROPSTG kArcProps[] = -{ - { NULL, kpidBit64, VT_BOOL}, - { NULL, kpidComment, VT_BSTR} -}; - -CHandler::CHandler() -{ - InitMethodProperties(); -} - -static AString BytesToString(const CByteBuffer &data) -{ - AString s; - int size = (int)data.GetCapacity(); - if (size > 0) - { - char *p = s.GetBuffer(size + 1); - memcpy(p, (const Byte *)data, size); - p[size] = '\0'; - s.ReleaseBuffer(); - } - return s; -} - -IMP_IInArchive_Props -IMP_IInArchive_ArcProps - -STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - switch(propID) - { - case kpidBit64: if (m_Archive.IsZip64) prop = m_Archive.IsZip64; break; - case kpidComment: - prop = MultiByteToUnicodeString(BytesToString(m_Archive.m_ArchiveInfo.Comment), CP_ACP); - break; - } - prop.Detach(value); - COM_TRY_END - return S_OK; -} - -STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) -{ - *numItems = m_Items.Size(); - return S_OK; -} - -STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) -{ - COM_TRY_BEGIN - NWindows::NCOM::CPropVariant prop; - const CItemEx &item = m_Items[index]; - switch(propID) - { - case kpidPath: prop = NItemName::GetOSName2(item.GetUnicodeString(item.Name)); break; - case kpidIsDir: prop = item.IsDir(); break; - case kpidSize: prop = item.UnPackSize; break; - case kpidPackSize: prop = item.PackSize; break; - case kpidTimeType: - { - FILETIME utcFileTime; - if (item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kTagTime, utcFileTime)) - prop = (UInt32)NFileTimeType::kWindows; - break; - } - case kpidCTime: - { - FILETIME ft; - if (item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kCTime, ft)) - prop = ft; - break; - } - case kpidATime: - { - FILETIME ft; - if (item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kATime, ft)) - prop = ft; - break; - } - case kpidMTime: - { - FILETIME utcFileTime; - if (!item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kMTime, utcFileTime)) - { - FILETIME localFileTime; - if (NTime::DosTimeToFileTime(item.Time, localFileTime)) - { - if (!LocalFileTimeToFileTime(&localFileTime, &utcFileTime)) - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - } - else - utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0; - } - prop = utcFileTime; - break; - } - case kpidAttrib: prop = item.GetWinAttributes(); break; - case kpidEncrypted: prop = item.IsEncrypted(); break; - case kpidComment: prop = item.GetUnicodeString(BytesToString(item.Comment)); break; - case kpidCRC: if (item.IsThereCrc()) prop = item.FileCRC; break; - case kpidMethod: - { - UInt16 methodId = item.CompressionMethod; - UString method; - if (item.IsEncrypted()) - { - if (methodId == NFileHeader::NCompressionMethod::kWzAES) - { - method = kAESMethod; - CWzAesExtraField aesField; - if (item.CentralExtra.GetWzAesField(aesField)) - { - method += L"-"; - wchar_t s[32]; - ConvertUInt64ToString((aesField.Strength + 1) * 64 , s); - method += s; - method += L" "; - methodId = aesField.Method; - } - } - else - { - if (item.IsStrongEncrypted()) - { - CStrongCryptoField f; - bool finded = false; - if (item.CentralExtra.GetStrongCryptoField(f)) - { - for (int i = 0; i < sizeof(g_StrongCryptoPairs) / sizeof(g_StrongCryptoPairs[0]); i++) - { - const CStrongCryptoPair &pair = g_StrongCryptoPairs[i]; - if (f.AlgId == pair.Id) - { - method += pair.Name; - finded = true; - break; - } - } - } - if (!finded) - method += kStrongCryptoMethod; - } - else - method += kZipCryptoMethod; - method += L" "; - } - } - if (methodId < kNumMethods) - method += kMethods[methodId]; - else switch (methodId) - { - case NFileHeader::NCompressionMethod::kLZMA: - method += kLZMAMethod; - if (item.IsLzmaEOS()) - method += L":EOS"; - break; - case NFileHeader::NCompressionMethod::kBZip2: method += kBZip2Method; break; - case NFileHeader::NCompressionMethod::kJpeg: method += kJpegMethod; break; - case NFileHeader::NCompressionMethod::kWavPack: method += kWavPackMethod; break; - case NFileHeader::NCompressionMethod::kPPMd: method += kPPMdMethod; break; - default: - { - wchar_t s[32]; - ConvertUInt64ToString(methodId, s); - method += s; - } - } - prop = method; - break; - } - case kpidHostOS: - prop = (item.MadeByVersion.HostOS < kNumHostOSes) ? - (kHostOS[item.MadeByVersion.HostOS]) : kUnknownOS; - break; - } - prop.Detach(value); - return S_OK; - COM_TRY_END -} - -class CProgressImp: public CProgressVirt -{ - CMyComPtr _callback; -public: - STDMETHOD(SetTotal)(UInt64 numFiles); - STDMETHOD(SetCompleted)(UInt64 numFiles); - CProgressImp(IArchiveOpenCallback *callback): _callback(callback) {} -}; - -STDMETHODIMP CProgressImp::SetTotal(UInt64 numFiles) -{ - if (_callback) - return _callback->SetTotal(&numFiles, NULL); - return S_OK; -} - -STDMETHODIMP CProgressImp::SetCompleted(UInt64 numFiles) -{ - if (_callback) - return _callback->SetCompleted(&numFiles, NULL); - return S_OK; -} - -STDMETHODIMP CHandler::Open(IInStream *inStream, - const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *callback) -{ - COM_TRY_BEGIN - try - { - Close(); - RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL)); - RINOK(m_Archive.Open(inStream, maxCheckStartPosition)); - CProgressImp progressImp(callback); - return m_Archive.ReadHeaders(m_Items, &progressImp); - } - catch(const CInArchiveException &) { Close(); return S_FALSE; } - catch(...) { Close(); throw; } - COM_TRY_END -} - -STDMETHODIMP CHandler::Close() -{ - m_Items.Clear(); - m_Archive.Close(); - return S_OK; -} - -////////////////////////////////////// -// CHandler::DecompressItems - -class CLzmaDecoder: - public ICompressCoder, - public CMyUnknownImp -{ - NCompress::NLzma::CDecoder *DecoderSpec; - CMyComPtr Decoder; -public: - CLzmaDecoder(); - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - MY_UNKNOWN_IMP -}; - -CLzmaDecoder::CLzmaDecoder() -{ - DecoderSpec = new NCompress::NLzma::CDecoder; - Decoder = DecoderSpec; -} - -HRESULT CLzmaDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - Byte buf[9]; - RINOK(ReadStream_FALSE(inStream, buf, 9)); - if (buf[2] != 5 || buf[3] != 0) - return E_NOTIMPL; - RINOK(DecoderSpec->SetDecoderProperties2(buf + 4, 5)); - return Decoder->Code(inStream, outStream, NULL, outSize, progress); -} - -struct CMethodItem -{ - UInt16 ZipMethod; - CMyComPtr Coder; -}; - -class CZipDecoder -{ - NCrypto::NZip::CDecoder *_zipCryptoDecoderSpec; - NCrypto::NZipStrong::CDecoder *_pkAesDecoderSpec; - NCrypto::NWzAes::CDecoder *_wzAesDecoderSpec; - - CMyComPtr _zipCryptoDecoder; - CMyComPtr _pkAesDecoder; - CMyComPtr _wzAesDecoder; - - CFilterCoder *filterStreamSpec; - CMyComPtr filterStream; - CMyComPtr getTextPassword; - CObjectVector methodItems; - -public: - CZipDecoder(): - _zipCryptoDecoderSpec(0), - _pkAesDecoderSpec(0), - _wzAesDecoderSpec(0), - filterStreamSpec(0) {} - - HRESULT Decode( - DECL_EXTERNAL_CODECS_LOC_VARS - CInArchive &archive, const CItemEx &item, - ISequentialOutStream *realOutStream, - IArchiveExtractCallback *extractCallback, - ICompressProgressInfo *compressProgress, - UInt32 numThreads, Int32 &res); -}; - -HRESULT CZipDecoder::Decode( - DECL_EXTERNAL_CODECS_LOC_VARS - CInArchive &archive, const CItemEx &item, - ISequentialOutStream *realOutStream, - IArchiveExtractCallback *extractCallback, - ICompressProgressInfo *compressProgress, - UInt32 numThreads, Int32 &res) -{ - res = NArchive::NExtract::NOperationResult::kDataError; - CInStreamReleaser inStreamReleaser; - - bool needCRC = true; - bool wzAesMode = false; - bool pkAesMode = false; - UInt16 methodId = item.CompressionMethod; - if (item.IsEncrypted()) - { - if (item.IsStrongEncrypted()) - { - CStrongCryptoField f; - if (item.CentralExtra.GetStrongCryptoField(f)) - { - pkAesMode = true; - } - if (!pkAesMode) - { - res = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - return S_OK; - } - } - if (methodId == NFileHeader::NCompressionMethod::kWzAES) - { - CWzAesExtraField aesField; - if (item.CentralExtra.GetWzAesField(aesField)) - { - wzAesMode = true; - needCRC = aesField.NeedCrc(); - } - } - } - - COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC; - CMyComPtr outStream = outStreamSpec; - outStreamSpec->SetStream(realOutStream); - outStreamSpec->Init(needCRC); - - UInt64 authenticationPos; - - CMyComPtr inStream; - { - UInt64 packSize = item.PackSize; - if (wzAesMode) - { - if (packSize < NCrypto::NWzAes::kMacSize) - return S_OK; - packSize -= NCrypto::NWzAes::kMacSize; - } - UInt64 dataPos = item.GetDataPosition(); - inStream.Attach(archive.CreateLimitedStream(dataPos, packSize)); - authenticationPos = dataPos + packSize; - } - - CMyComPtr cryptoFilter; - if (item.IsEncrypted()) - { - if (wzAesMode) - { - CWzAesExtraField aesField; - if (!item.CentralExtra.GetWzAesField(aesField)) - return S_OK; - methodId = aesField.Method; - if (!_wzAesDecoder) - { - _wzAesDecoderSpec = new NCrypto::NWzAes::CDecoder; - _wzAesDecoder = _wzAesDecoderSpec; - } - cryptoFilter = _wzAesDecoder; - Byte properties = aesField.Strength; - RINOK(_wzAesDecoderSpec->SetDecoderProperties2(&properties, 1)); - } - else if (pkAesMode) - { - if (!_pkAesDecoder) - { - _pkAesDecoderSpec = new NCrypto::NZipStrong::CDecoder; - _pkAesDecoder = _pkAesDecoderSpec; - } - cryptoFilter = _pkAesDecoder; - } - else - { - if (!_zipCryptoDecoder) - { - _zipCryptoDecoderSpec = new NCrypto::NZip::CDecoder; - _zipCryptoDecoder = _zipCryptoDecoderSpec; - } - cryptoFilter = _zipCryptoDecoder; - } - CMyComPtr cryptoSetPassword; - RINOK(cryptoFilter.QueryInterface(IID_ICryptoSetPassword, &cryptoSetPassword)); - - if (!getTextPassword) - extractCallback->QueryInterface(IID_ICryptoGetTextPassword, (void **)&getTextPassword); - - if (getTextPassword) - { - CMyComBSTR password; - RINOK(getTextPassword->CryptoGetTextPassword(&password)); - AString charPassword; - if (wzAesMode || pkAesMode) - { - charPassword = UnicodeStringToMultiByte((const wchar_t *)password, CP_ACP); - /* - for (int i = 0;; i++) - { - wchar_t c = password[i]; - if (c == 0) - break; - if (c >= 0x80) - { - res = NArchive::NExtract::NOperationResult::kDataError; - return S_OK; - } - charPassword += (char)c; - } - */ - } - else - { - // we use OEM. WinZip/Windows probably use ANSI for some files - charPassword = UnicodeStringToMultiByte((const wchar_t *)password, CP_OEMCP); - } - HRESULT result = cryptoSetPassword->CryptoSetPassword( - (const Byte *)(const char *)charPassword, charPassword.Length()); - if (result != S_OK) - return S_OK; - } - else - { - RINOK(cryptoSetPassword->CryptoSetPassword(0, 0)); - } - } - - int m; - for (m = 0; m < methodItems.Size(); m++) - if (methodItems[m].ZipMethod == methodId) - break; - - if (m == methodItems.Size()) - { - CMethodItem mi; - mi.ZipMethod = methodId; - if (methodId == NFileHeader::NCompressionMethod::kStored) - mi.Coder = new NCompress::CCopyCoder; - else if (methodId == NFileHeader::NCompressionMethod::kShrunk) - mi.Coder = new NCompress::NShrink::CDecoder; - else if (methodId == NFileHeader::NCompressionMethod::kImploded) - mi.Coder = new NCompress::NImplode::NDecoder::CCoder; - else if (methodId == NFileHeader::NCompressionMethod::kLZMA) - mi.Coder = new CLzmaDecoder; - else - { - CMethodId szMethodID; - if (methodId == NFileHeader::NCompressionMethod::kBZip2) - szMethodID = kMethodId_BZip2; - else - { - if (methodId > 0xFF) - { - res = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - return S_OK; - } - szMethodID = kMethodId_ZipBase + (Byte)methodId; - } - - RINOK(CreateCoder(EXTERNAL_CODECS_LOC_VARS szMethodID, mi.Coder, false)); - - if (mi.Coder == 0) - { - res = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - return S_OK; - } - } - m = methodItems.Add(mi); - } - ICompressCoder *coder = methodItems[m].Coder; - - { - CMyComPtr setDecoderProperties; - coder->QueryInterface(IID_ICompressSetDecoderProperties2, (void **)&setDecoderProperties); - if (setDecoderProperties) - { - Byte properties = (Byte)item.Flags; - RINOK(setDecoderProperties->SetDecoderProperties2(&properties, 1)); - } - } - - #ifdef COMPRESS_MT - { - CMyComPtr setCoderMt; - coder->QueryInterface(IID_ICompressSetCoderMt, (void **)&setCoderMt); - if (setCoderMt) - { - RINOK(setCoderMt->SetNumberOfThreads(numThreads)); - } - } - #endif - - { - HRESULT result = S_OK; - CMyComPtr inStreamNew; - if (item.IsEncrypted()) - { - if (!filterStream) - { - filterStreamSpec = new CFilterCoder; - filterStream = filterStreamSpec; - } - filterStreamSpec->Filter = cryptoFilter; - if (wzAesMode) - { - result = _wzAesDecoderSpec->ReadHeader(inStream); - } - else if (pkAesMode) - { - result =_pkAesDecoderSpec->ReadHeader(inStream, item.FileCRC, item.UnPackSize); - if (result == S_OK) - { - bool passwOK; - result = _pkAesDecoderSpec->CheckPassword(passwOK); - if (result == S_OK && !passwOK) - result = S_FALSE; - } - } - else - { - result = _zipCryptoDecoderSpec->ReadHeader(inStream); - } - - if (result == S_OK) - { - RINOK(filterStreamSpec->SetInStream(inStream)); - inStreamReleaser.FilterCoder = filterStreamSpec; - inStreamNew = filterStream; - if (wzAesMode) - { - if (!_wzAesDecoderSpec->CheckPasswordVerifyCode()) - result = S_FALSE; - } - } - } - else - inStreamNew = inStream; - if (result == S_OK) - result = coder->Code(inStreamNew, outStream, NULL, &item.UnPackSize, compressProgress); - if (result == S_FALSE) - return S_OK; - if (result == E_NOTIMPL) - { - res = NArchive::NExtract::NOperationResult::kUnSupportedMethod; - return S_OK; - } - - RINOK(result); - } - bool crcOK = true; - bool authOk = true; - if (needCRC) - crcOK = (outStreamSpec->GetCRC() == item.FileCRC); - if (wzAesMode) - { - inStream.Attach(archive.CreateLimitedStream(authenticationPos, NCrypto::NWzAes::kMacSize)); - if (_wzAesDecoderSpec->CheckMac(inStream, authOk) != S_OK) - authOk = false; - } - - res = ((crcOK && authOk) ? - NArchive::NExtract::NOperationResult::kOK : - NArchive::NExtract::NOperationResult::kCRCError); - return S_OK; -} - - -STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, - Int32 _aTestMode, IArchiveExtractCallback *extractCallback) -{ - COM_TRY_BEGIN - CZipDecoder myDecoder; - bool testMode = (_aTestMode != 0); - UInt64 totalUnPacked = 0, totalPacked = 0; - bool allFilesMode = (numItems == UInt32(-1)); - if (allFilesMode) - numItems = m_Items.Size(); - if(numItems == 0) - return S_OK; - UInt32 i; - for(i = 0; i < numItems; i++) - { - const CItemEx &item = m_Items[allFilesMode ? i : indices[i]]; - totalUnPacked += item.UnPackSize; - totalPacked += item.PackSize; - } - RINOK(extractCallback->SetTotal(totalUnPacked)); - - UInt64 currentTotalUnPacked = 0, currentTotalPacked = 0; - UInt64 currentItemUnPacked, currentItemPacked; - - CLocalProgress *lps = new CLocalProgress; - CMyComPtr progress = lps; - lps->Init(extractCallback, false); - - for (i = 0; i < numItems; i++, currentTotalUnPacked += currentItemUnPacked, - currentTotalPacked += currentItemPacked) - { - currentItemUnPacked = 0; - currentItemPacked = 0; - - lps->InSize = currentTotalPacked; - lps->OutSize = currentTotalUnPacked; - RINOK(lps->SetCur()); - - CMyComPtr realOutStream; - Int32 askMode = testMode ? - NArchive::NExtract::NAskMode::kTest : - NArchive::NExtract::NAskMode::kExtract; - Int32 index = allFilesMode ? i : indices[i]; - - RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); - - CItemEx item = m_Items[index]; - if (!item.FromLocal) - { - HRESULT res = m_Archive.ReadLocalItemAfterCdItem(item); - if (res == S_FALSE) - { - if (item.IsDir() || realOutStream || testMode) - { - RINOK(extractCallback->PrepareOperation(askMode)); - realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kUnSupportedMethod)); - } - continue; - } - RINOK(res); - } - - if (item.IsDir() || item.IgnoreItem()) - { - // if (!testMode) - { - RINOK(extractCallback->PrepareOperation(askMode)); - realOutStream.Release(); - RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK)); - } - continue; - } - - currentItemUnPacked = item.UnPackSize; - currentItemPacked = item.PackSize; - - if (!testMode && (!realOutStream)) - continue; - - RINOK(extractCallback->PrepareOperation(askMode)); - -#ifndef COMPRESS_MT -#define _numThreads 1 -#endif - - Int32 res; - RINOK(myDecoder.Decode( - EXTERNAL_CODECS_VARS - m_Archive, item, realOutStream, extractCallback, - progress, - _numThreads, - res)); - realOutStream.Release(); - - RINOK(extractCallback->SetOperationResult(res)) - } - return S_OK; - COM_TRY_END -} - -#ifndef EXTRACT_ONLY -IMPL_ISetCompressCodecsInfo -#endif - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.h deleted file mode 100644 index fc0cfa250..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHandler.h +++ /dev/null @@ -1,100 +0,0 @@ -// Zip/Handler.h - -#ifndef __ZIP_HANDLER_H -#define __ZIP_HANDLER_H - -#include "../../../Common/DynamicBuffer.h" -#include "../../ICoder.h" -#include "../IArchive.h" - -#include "../../Common/CreateCoder.h" - -#include "ZipIn.h" -#include "ZipCompressionMode.h" - -#ifdef COMPRESS_MT -#include "../../../Windows/System.h" -#endif - -namespace NArchive { -namespace NZip { - -class CHandler: - public IInArchive, -#ifndef EXTRACT_ONLY - public IOutArchive, - public ISetProperties, - PUBLIC_ISetCompressCodecsInfo -#endif - public CMyUnknownImp -{ -public: - MY_QUERYINTERFACE_BEGIN2(IInArchive) -#ifndef EXTRACT_ONLY - MY_QUERYINTERFACE_ENTRY(IOutArchive) - MY_QUERYINTERFACE_ENTRY(ISetProperties) - QUERY_ENTRY_ISetCompressCodecsInfo -#endif - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - - INTERFACE_IInArchive(;) -#ifndef EXTRACT_ONLY - INTERFACE_IOutArchive(;) - - STDMETHOD(SetProperties)(const wchar_t **names, const PROPVARIANT *values, Int32 numProperties); - - DECL_ISetCompressCodecsInfo -#endif - - CHandler(); -private: - CObjectVector m_Items; - CInArchive m_Archive; - - int m_Level; - int m_MainMethod; - UInt32 m_DicSize; - UInt32 m_Algo; - UInt32 m_NumPasses; - UInt32 m_NumFastBytes; - UInt32 m_NumMatchFinderCycles; - bool m_NumMatchFinderCyclesDefined; - - bool m_IsAesMode; - Byte m_AesKeyMode; - - bool m_WriteNtfsTimeExtra; - bool m_ForseLocal; - bool m_ForseUtf8; - - #ifdef COMPRESS_MT - UInt32 _numThreads; - #endif - - DECL_EXTERNAL_CODECS_VARS - - void InitMethodProperties() - { - m_Level = -1; - m_MainMethod = -1; - m_Algo = - m_DicSize = - m_NumPasses = - m_NumFastBytes = - m_NumMatchFinderCycles = 0xFFFFFFFF; - m_NumMatchFinderCyclesDefined = false; - m_IsAesMode = false; - m_AesKeyMode = 3; // aes-256 - m_WriteNtfsTimeExtra = false; - m_ForseLocal = false; - m_ForseUtf8 = false; - #ifdef COMPRESS_MT - _numThreads = NWindows::NSystem::GetNumberOfProcessors();; - #endif - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.cpp deleted file mode 100644 index 331aed2be..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// Archive/Zip/Header.h - -#include "StdAfx.h" - -#include "ZipHeader.h" - -namespace NArchive { -namespace NZip { - -namespace NSignature -{ - UInt32 kLocalFileHeader = 0x04034B50 + 1; - UInt32 kDataDescriptor = 0x08074B50 + 1; - UInt32 kCentralFileHeader = 0x02014B50 + 1; - UInt32 kEndOfCentralDir = 0x06054B50 + 1; - UInt32 kZip64EndOfCentralDir = 0x06064B50 + 1; - UInt32 kZip64EndOfCentralDirLocator = 0x07064B50 + 1; - - class CMarkersInitializer - { - public: - CMarkersInitializer() - { - kLocalFileHeader--; - kDataDescriptor--; - kCentralFileHeader--; - kEndOfCentralDir--; - kZip64EndOfCentralDir--; - kZip64EndOfCentralDirLocator--; - } - } g_MarkerInitializer; -} - -}} - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.h deleted file mode 100644 index b595e65e8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipHeader.h +++ /dev/null @@ -1,265 +0,0 @@ -// Archive/Zip/Header.h - -#ifndef __ARCHIVE_ZIP_HEADER_H -#define __ARCHIVE_ZIP_HEADER_H - -#include "../../../Common/Types.h" - -namespace NArchive { -namespace NZip { - -namespace NSignature -{ - extern UInt32 kLocalFileHeader; - extern UInt32 kDataDescriptor; - extern UInt32 kCentralFileHeader; - extern UInt32 kEndOfCentralDir; - extern UInt32 kZip64EndOfCentralDir; - extern UInt32 kZip64EndOfCentralDirLocator; - - static const UInt32 kMarkerSize = 4; -} - -const UInt32 kEcdSize = 22; -const UInt32 kZip64EcdSize = 44; -const UInt32 kZip64EcdLocatorSize = 20; -/* -struct CEndOfCentralDirectoryRecord -{ - UInt16 ThisDiskNumber; - UInt16 StartCentralDirectoryDiskNumber; - UInt16 NumEntriesInCentaralDirectoryOnThisDisk; - UInt16 NumEntriesInCentaralDirectory; - UInt32 CentralDirectorySize; - UInt32 CentralDirectoryStartOffset; - UInt16 CommentSize; -}; - -struct CEndOfCentralDirectoryRecordFull -{ - UInt32 Signature; - CEndOfCentralDirectoryRecord Header; -}; -*/ - -namespace NFileHeader -{ - /* - struct CVersion - { - Byte Version; - Byte HostOS; - }; - */ - - namespace NCompressionMethod - { - enum EType - { - kStored = 0, - kShrunk = 1, - kReduced1 = 2, - kReduced2 = 3, - kReduced3 = 4, - kReduced4 = 5, - kImploded = 6, - kReservedTokenizing = 7, // reserved for tokenizing - kDeflated = 8, - kDeflated64 = 9, - kPKImploding = 10, - - kBZip2 = 12, - kLZMA = 14, - kTerse = 18, - kLz77 = 19, - kJpeg = 0x60, - kWavPack = 0x61, - kPPMd = 0x62, - kWzAES = 0x63 - }; - const int kNumCompressionMethods = 11; - const Byte kMadeByProgramVersion = 20; - - const Byte kDeflateExtractVersion = 20; - const Byte kStoreExtractVersion = 10; - - const Byte kSupportedVersion = 20; - } - - namespace NExtraID - { - enum - { - kZip64 = 0x01, - kNTFS = 0x0A, - kStrongEncrypt = 0x17, - kWzAES = 0x9901 - }; - } - - namespace NNtfsExtra - { - const UInt16 kTagTime = 1; - enum - { - kMTime = 0, - kATime = 1, - kCTime = 2 - }; - } - - const UInt32 kLocalBlockSize = 26; - /* - struct CLocalBlock - { - CVersion ExtractVersion; - - UInt16 Flags; - UInt16 CompressionMethod; - UInt32 Time; - UInt32 FileCRC; - UInt32 PackSize; - UInt32 UnPackSize; - UInt16 NameSize; - UInt16 ExtraSize; - }; - */ - - const UInt32 kDataDescriptorSize = 16; - // const UInt32 kDataDescriptor64Size = 16 + 8; - /* - struct CDataDescriptor - { - UInt32 Signature; - UInt32 FileCRC; - UInt32 PackSize; - UInt32 UnPackSize; - }; - - struct CLocalBlockFull - { - UInt32 Signature; - CLocalBlock Header; - }; - */ - - const UInt32 kCentralBlockSize = 42; - /* - struct CBlock - { - CVersion MadeByVersion; - CVersion ExtractVersion; - UInt16 Flags; - UInt16 CompressionMethod; - UInt32 Time; - UInt32 FileCRC; - UInt32 PackSize; - UInt32 UnPackSize; - UInt16 NameSize; - UInt16 ExtraSize; - UInt16 CommentSize; - UInt16 DiskNumberStart; - UInt16 InternalAttributes; - UInt32 ExternalAttributes; - UInt32 LocalHeaderOffset; - }; - - struct CBlockFull - { - UInt32 Signature; - CBlock Header; - }; - */ - - namespace NFlags - { - const int kEncrypted = 1 << 0; - const int kLzmaEOS = 1 << 1; - const int kDescriptorUsedMask = 1 << 3; - const int kStrongEncrypted = 1 << 6; - const int kUtf8 = 1 << 11; - - const int kImplodeDictionarySizeMask = 1 << 1; - const int kImplodeLiteralsOnMask = 1 << 2; - - const int kDeflateTypeBitStart = 1; - const int kNumDeflateTypeBits = 2; - const int kNumDeflateTypes = (1 << kNumDeflateTypeBits); - const int kDeflateTypeMask = (1 << kNumDeflateTypeBits) - 1; - } - - namespace NHostOS - { - enum EEnum - { - kFAT = 0, - kAMIGA = 1, - kVMS = 2, // VAX/VMS - kUnix = 3, - kVM_CMS = 4, - kAtari = 5, // what if it's a minix filesystem? [cjh] - kHPFS = 6, // filesystem used by OS/2 (and NT 3.x) - kMac = 7, - kZ_System = 8, - kCPM = 9, - kTOPS20 = 10, // pkzip 2.50 NTFS - kNTFS = 11, // filesystem used by Windows NT - kQDOS = 12, // SMS/QDOS - kAcorn = 13, // Archimedes Acorn RISC OS - kVFAT = 14, // filesystem used by Windows 95, NT - kMVS = 15, - kBeOS = 16, // hybrid POSIX/database filesystem - kTandem = 17, - kOS400 = 18, - kOSX = 19 - }; - } - namespace NUnixAttribute - { - const UInt32 kIFMT = 0170000; /* Unix file type mask */ - - const UInt32 kIFDIR = 0040000; /* Unix directory */ - const UInt32 kIFREG = 0100000; /* Unix regular file */ - const UInt32 kIFSOCK = 0140000; /* Unix socket (BSD, not SysV or Amiga) */ - const UInt32 kIFLNK = 0120000; /* Unix symbolic link (not SysV, Amiga) */ - const UInt32 kIFBLK = 0060000; /* Unix block special (not Amiga) */ - const UInt32 kIFCHR = 0020000; /* Unix character special (not Amiga) */ - const UInt32 kIFIFO = 0010000; /* Unix fifo (BCC, not MSC or Amiga) */ - - const UInt32 kISUID = 04000; /* Unix set user id on execution */ - const UInt32 kISGID = 02000; /* Unix set group id on execution */ - const UInt32 kISVTX = 01000; /* Unix directory permissions control */ - const UInt32 kENFMT = kISGID; /* Unix record locking enforcement flag */ - const UInt32 kIRWXU = 00700; /* Unix read, write, execute: owner */ - const UInt32 kIRUSR = 00400; /* Unix read permission: owner */ - const UInt32 kIWUSR = 00200; /* Unix write permission: owner */ - const UInt32 kIXUSR = 00100; /* Unix execute permission: owner */ - const UInt32 kIRWXG = 00070; /* Unix read, write, execute: group */ - const UInt32 kIRGRP = 00040; /* Unix read permission: group */ - const UInt32 kIWGRP = 00020; /* Unix write permission: group */ - const UInt32 kIXGRP = 00010; /* Unix execute permission: group */ - const UInt32 kIRWXO = 00007; /* Unix read, write, execute: other */ - const UInt32 kIROTH = 00004; /* Unix read permission: other */ - const UInt32 kIWOTH = 00002; /* Unix write permission: other */ - const UInt32 kIXOTH = 00001; /* Unix execute permission: other */ - } - - namespace NAmigaAttribute - { - const UInt32 kIFMT = 06000; /* Amiga file type mask */ - const UInt32 kIFDIR = 04000; /* Amiga directory */ - const UInt32 kIFREG = 02000; /* Amiga regular file */ - const UInt32 kIHIDDEN = 00200; /* to be supported in AmigaDOS 3.x */ - const UInt32 kISCRIPT = 00100; /* executable script (text command file) */ - const UInt32 kIPURE = 00040; /* allow loading into resident memory */ - const UInt32 kIARCHIVE = 00020; /* not modified since bit was last set */ - const UInt32 kIREAD = 00010; /* can be opened for reading */ - const UInt32 kIWRITE = 00004; /* can be opened for writing */ - const UInt32 kIEXECUTE = 00002; /* executable image, a loadable runfile */ - const UInt32 kIDELETE = 00001; /* can be deleted */ - } -} - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.cpp deleted file mode 100644 index 7c43bd911..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.cpp +++ /dev/null @@ -1,868 +0,0 @@ -// Archive/ZipIn.cpp - -#include "StdAfx.h" - -#include "ZipIn.h" -#include "Windows/Defs.h" -#include "Common/StringConvert.h" -#include "Common/DynamicBuffer.h" -#include "../../Common/LimitedStreams.h" -#include "../../Common/StreamUtils.h" - -extern "C" -{ - #include "../../../../C/CpuArch.h" -} - -#define Get16(p) GetUi16(p) -#define Get32(p) GetUi32(p) -#define Get64(p) GetUi64(p) - -namespace NArchive { -namespace NZip { - -// static const char kEndOfString = '\0'; - -HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - Close(); - RINOK(stream->Seek(0, STREAM_SEEK_CUR, &m_StreamStartPosition)); - m_Position = m_StreamStartPosition; - RINOK(FindAndReadMarker(stream, searchHeaderSizeLimit)); - RINOK(stream->Seek(m_Position, STREAM_SEEK_SET, NULL)); - m_Stream = stream; - return S_OK; -} - -void CInArchive::Close() -{ - m_Stream.Release(); -} - -HRESULT CInArchive::Seek(UInt64 offset) -{ - return m_Stream->Seek(offset, STREAM_SEEK_SET, NULL); -} - -////////////////////////////////////// -// Markers - -static inline bool TestMarkerCandidate(const Byte *p, UInt32 &value) -{ - value = Get32(p); - return - (value == NSignature::kLocalFileHeader) || - (value == NSignature::kEndOfCentralDir); -} - -static const UInt32 kNumMarkerAddtionalBytes = 2; -static inline bool TestMarkerCandidate2(const Byte *p, UInt32 &value) -{ - value = Get32(p); - if (value == NSignature::kEndOfCentralDir) - return (Get16(p + 4) == 0); - return (value == NSignature::kLocalFileHeader && p[4] < 128); -} - -HRESULT CInArchive::FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit) -{ - m_ArchiveInfo.Clear(); - m_Position = m_StreamStartPosition; - - Byte marker[NSignature::kMarkerSize]; - RINOK(ReadStream_FALSE(stream, marker, NSignature::kMarkerSize)); - m_Position += NSignature::kMarkerSize; - if (TestMarkerCandidate(marker, m_Signature)) - return S_OK; - - CByteDynamicBuffer dynamicBuffer; - const UInt32 kSearchMarkerBufferSize = 0x10000; - dynamicBuffer.EnsureCapacity(kSearchMarkerBufferSize); - Byte *buffer = dynamicBuffer; - UInt32 numBytesPrev = NSignature::kMarkerSize - 1; - memcpy(buffer, marker + 1, numBytesPrev); - UInt64 curTestPos = m_StreamStartPosition + 1; - for (;;) - { - if (searchHeaderSizeLimit != NULL) - if (curTestPos - m_StreamStartPosition > *searchHeaderSizeLimit) - break; - size_t numReadBytes = kSearchMarkerBufferSize - numBytesPrev; - RINOK(ReadStream(stream, buffer + numBytesPrev, &numReadBytes)); - m_Position += numReadBytes; - UInt32 numBytesInBuffer = numBytesPrev + (UInt32)numReadBytes; - const UInt32 kMarker2Size = NSignature::kMarkerSize + kNumMarkerAddtionalBytes; - if (numBytesInBuffer < kMarker2Size) - break; - UInt32 numTests = numBytesInBuffer - kMarker2Size + 1; - for (UInt32 pos = 0; pos < numTests; pos++) - { - if (buffer[pos] != 0x50) - continue; - if (TestMarkerCandidate2(buffer + pos, m_Signature)) - { - curTestPos += pos; - m_ArchiveInfo.StartPosition = curTestPos; - m_Position = curTestPos + NSignature::kMarkerSize; - return S_OK; - } - } - curTestPos += numTests; - numBytesPrev = numBytesInBuffer - numTests; - memmove(buffer, buffer + numTests, numBytesPrev); - } - return S_FALSE; -} - -HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 *processedSize) -{ - size_t realProcessedSize = size; - HRESULT result = ReadStream(m_Stream, data, &realProcessedSize); - if (processedSize != NULL) - *processedSize = (UInt32)realProcessedSize; - m_Position += realProcessedSize; - return result; -} - -void CInArchive::IncreaseRealPosition(UInt64 addValue) -{ - if (m_Stream->Seek(addValue, STREAM_SEEK_CUR, &m_Position) != S_OK) - throw CInArchiveException(CInArchiveException::kSeekStreamError); -} - -bool CInArchive::ReadBytesAndTestSize(void *data, UInt32 size) -{ - UInt32 realProcessedSize; - if (ReadBytes(data, size, &realProcessedSize) != S_OK) - throw CInArchiveException(CInArchiveException::kReadStreamError); - return (realProcessedSize == size); -} - -void CInArchive::SafeReadBytes(void *data, UInt32 size) -{ - if (!ReadBytesAndTestSize(data, size)) - throw CInArchiveException(CInArchiveException::kUnexpectedEndOfArchive); -} - -void CInArchive::ReadBuffer(CByteBuffer &buffer, UInt32 size) -{ - buffer.SetCapacity(size); - if (size > 0) - SafeReadBytes(buffer, size); -} - -Byte CInArchive::ReadByte() -{ - Byte b; - SafeReadBytes(&b, 1); - return b; -} - -UInt16 CInArchive::ReadUInt16() -{ - UInt16 value = 0; - for (int i = 0; i < 2; i++) - value |= (((UInt16)ReadByte()) << (8 * i)); - return value; -} - -UInt32 CInArchive::ReadUInt32() -{ - UInt32 value = 0; - for (int i = 0; i < 4; i++) - value |= (((UInt32)ReadByte()) << (8 * i)); - return value; -} - -UInt64 CInArchive::ReadUInt64() -{ - UInt64 value = 0; - for (int i = 0; i < 8; i++) - value |= (((UInt64)ReadByte()) << (8 * i)); - return value; -} - -bool CInArchive::ReadUInt32(UInt32 &value) -{ - value = 0; - for (int i = 0; i < 4; i++) - { - Byte b; - if (!ReadBytesAndTestSize(&b, 1)) - return false; - value |= (UInt32(b) << (8 * i)); - } - return true; -} - - -AString CInArchive::ReadFileName(UInt32 nameSize) -{ - if (nameSize == 0) - return AString(); - char *p = m_NameBuffer.GetBuffer(nameSize); - SafeReadBytes(p, nameSize); - p[nameSize] = 0; - m_NameBuffer.ReleaseBuffer(); - return m_NameBuffer; -} - -void CInArchive::GetArchiveInfo(CInArchiveInfo &archiveInfo) const -{ - archiveInfo = m_ArchiveInfo; -} - -/* -void CInArchive::ThrowIncorrectArchiveException() -{ - throw CInArchiveException(CInArchiveException::kIncorrectArchive); -} -*/ - -static UInt32 GetUInt32(const Byte *data) -{ - return - ((UInt32)(Byte)data[0]) | - (((UInt32)(Byte)data[1]) << 8) | - (((UInt32)(Byte)data[2]) << 16) | - (((UInt32)(Byte)data[3]) << 24); -} - -/* -static UInt16 GetUInt16(const Byte *data) -{ - return - ((UInt16)(Byte)data[0]) | - (((UInt16)(Byte)data[1]) << 8); -} -*/ - -static UInt64 GetUInt64(const Byte *data) -{ - return GetUInt32(data) | ((UInt64)GetUInt32(data + 4) << 32); -} - - - -void CInArchive::ReadExtra(UInt32 extraSize, CExtraBlock &extraBlock, - UInt64 &unpackSize, UInt64 &packSize, UInt64 &localHeaderOffset, UInt32 &diskStartNumber) -{ - extraBlock.Clear(); - UInt32 remain = extraSize; - while(remain >= 4) - { - CExtraSubBlock subBlock; - subBlock.ID = ReadUInt16(); - UInt32 dataSize = ReadUInt16(); - remain -= 4; - if (dataSize > remain) // it's bug - dataSize = remain; - if (subBlock.ID == NFileHeader::NExtraID::kZip64) - { - if (unpackSize == 0xFFFFFFFF) - { - if (dataSize < 8) - break; - unpackSize = ReadUInt64(); - remain -= 8; - dataSize -= 8; - } - if (packSize == 0xFFFFFFFF) - { - if (dataSize < 8) - break; - packSize = ReadUInt64(); - remain -= 8; - dataSize -= 8; - } - if (localHeaderOffset == 0xFFFFFFFF) - { - if (dataSize < 8) - break; - localHeaderOffset = ReadUInt64(); - remain -= 8; - dataSize -= 8; - } - if (diskStartNumber == 0xFFFF) - { - if (dataSize < 4) - break; - diskStartNumber = ReadUInt32(); - remain -= 4; - dataSize -= 4; - } - for (UInt32 i = 0; i < dataSize; i++) - ReadByte(); - } - else - { - ReadBuffer(subBlock.Data, dataSize); - extraBlock.SubBlocks.Add(subBlock); - } - remain -= dataSize; - } - IncreaseRealPosition(remain); -} - -HRESULT CInArchive::ReadLocalItem(CItemEx &item) -{ - item.ExtractVersion.Version = ReadByte(); - item.ExtractVersion.HostOS = ReadByte(); - item.Flags = ReadUInt16(); - item.CompressionMethod = ReadUInt16(); - item.Time = ReadUInt32(); - item.FileCRC = ReadUInt32(); - item.PackSize = ReadUInt32(); - item.UnPackSize = ReadUInt32(); - UInt32 fileNameSize = ReadUInt16(); - item.LocalExtraSize = ReadUInt16(); - item.Name = ReadFileName(fileNameSize); - item.FileHeaderWithNameSize = 4 + NFileHeader::kLocalBlockSize + fileNameSize; - if (item.LocalExtraSize > 0) - { - UInt64 localHeaderOffset = 0; - UInt32 diskStartNumber = 0; - ReadExtra(item.LocalExtraSize, item.LocalExtra, item.UnPackSize, item.PackSize, - localHeaderOffset, diskStartNumber); - } - /* - if (item.IsDir()) - item.UnPackSize = 0; // check It - */ - return S_OK; -} - -HRESULT CInArchive::ReadLocalItemAfterCdItem(CItemEx &item) -{ - if (item.FromLocal) - return S_OK; - try - { - RINOK(Seek(m_ArchiveInfo.Base + item.LocalHeaderPosition)); - CItemEx localItem; - if (ReadUInt32() != NSignature::kLocalFileHeader) - return S_FALSE; - RINOK(ReadLocalItem(localItem)); - if (item.Flags != localItem.Flags) - { - if ( - (item.CompressionMethod != NFileHeader::NCompressionMethod::kDeflated || - (item.Flags & 0x7FF9) != (localItem.Flags & 0x7FF9)) && - (item.CompressionMethod != NFileHeader::NCompressionMethod::kStored || - (item.Flags & 0x7FFF) != (localItem.Flags & 0x7FFF)) && - (item.CompressionMethod != NFileHeader::NCompressionMethod::kImploded || - (item.Flags & 0x7FFF) != (localItem.Flags & 0x7FFF)) - ) - return S_FALSE; - } - - if (item.CompressionMethod != localItem.CompressionMethod || - // item.Time != localItem.Time || - (!localItem.HasDescriptor() && - ( - item.FileCRC != localItem.FileCRC || - item.PackSize != localItem.PackSize || - item.UnPackSize != localItem.UnPackSize - ) - ) || - item.Name.Length() != localItem.Name.Length() - ) - return S_FALSE; - item.FileHeaderWithNameSize = localItem.FileHeaderWithNameSize; - item.LocalExtraSize = localItem.LocalExtraSize; - item.LocalExtra = localItem.LocalExtra; - item.FromLocal = true; - } - catch(...) { return S_FALSE; } - return S_OK; -} - -HRESULT CInArchive::ReadLocalItemDescriptor(CItemEx &item) -{ - if (item.HasDescriptor()) - { - const int kBufferSize = (1 << 12); - Byte buffer[kBufferSize]; - - UInt32 numBytesInBuffer = 0; - UInt32 packedSize = 0; - - bool descriptorWasFound = false; - for (;;) - { - UInt32 processedSize; - RINOK(ReadBytes(buffer + numBytesInBuffer, kBufferSize - numBytesInBuffer, &processedSize)); - numBytesInBuffer += processedSize; - if (numBytesInBuffer < NFileHeader::kDataDescriptorSize) - return S_FALSE; - UInt32 i; - for (i = 0; i <= numBytesInBuffer - NFileHeader::kDataDescriptorSize; i++) - { - // descriptorSignature field is Info-ZIP's extension - // to Zip specification. - UInt32 descriptorSignature = GetUInt32(buffer + i); - - // !!!! It must be fixed for Zip64 archives - UInt32 descriptorPackSize = GetUInt32(buffer + i + 8); - if (descriptorSignature== NSignature::kDataDescriptor && descriptorPackSize == packedSize + i) - { - descriptorWasFound = true; - item.FileCRC = GetUInt32(buffer + i + 4); - item.PackSize = descriptorPackSize; - item.UnPackSize = GetUInt32(buffer + i + 12); - IncreaseRealPosition(Int64(Int32(0 - (numBytesInBuffer - i - NFileHeader::kDataDescriptorSize)))); - break; - } - } - if (descriptorWasFound) - break; - packedSize += i; - int j; - for (j = 0; i < numBytesInBuffer; i++, j++) - buffer[j] = buffer[i]; - numBytesInBuffer = j; - } - } - else - IncreaseRealPosition(item.PackSize); - return S_OK; -} - -HRESULT CInArchive::ReadLocalItemAfterCdItemFull(CItemEx &item) -{ - if (item.FromLocal) - return S_OK; - try - { - RINOK(ReadLocalItemAfterCdItem(item)); - if (item.HasDescriptor()) - { - RINOK(Seek(m_ArchiveInfo.Base + item.GetDataPosition() + item.PackSize)); - if (ReadUInt32() != NSignature::kDataDescriptor) - return S_FALSE; - UInt32 crc = ReadUInt32(); - UInt64 packSize, unpackSize; - - /* - if (IsZip64) - { - packSize = ReadUInt64(); - unpackSize = ReadUInt64(); - } - else - */ - { - packSize = ReadUInt32(); - unpackSize = ReadUInt32(); - } - - if (crc != item.FileCRC || item.PackSize != packSize || item.UnPackSize != unpackSize) - return S_FALSE; - } - } - catch(...) { return S_FALSE; } - return S_OK; -} - -HRESULT CInArchive::ReadCdItem(CItemEx &item) -{ - item.FromCentral = true; - const int kBufSize = 42; - Byte p[kBufSize]; - SafeReadBytes(p, kBufSize); - item.MadeByVersion.Version = p[0]; - item.MadeByVersion.HostOS = p[1]; - item.ExtractVersion.Version = p[2]; - item.ExtractVersion.HostOS = p[3]; - item.Flags = Get16(p + 4); - item.CompressionMethod = Get16(p + 6); - item.Time = Get32(p + 8); - item.FileCRC = Get32(p + 12); - item.PackSize = Get32(p + 16); - item.UnPackSize = Get32(p + 20); - UInt16 headerNameSize = Get16(p + 24); - UInt16 headerExtraSize = Get16(p + 26); - UInt16 headerCommentSize = Get16(p + 28); - UInt32 headerDiskNumberStart = Get16(p + 30); - item.InternalAttributes = Get16(p + 32); - item.ExternalAttributes = Get32(p + 34); - item.LocalHeaderPosition = Get32(p + 38); - item.Name = ReadFileName(headerNameSize); - - if (headerExtraSize > 0) - { - ReadExtra(headerExtraSize, item.CentralExtra, item.UnPackSize, item.PackSize, - item.LocalHeaderPosition, headerDiskNumberStart); - } - - if (headerDiskNumberStart != 0) - throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported); - - // May be these strings must be deleted - /* - if (item.IsDir()) - item.UnPackSize = 0; - */ - - ReadBuffer(item.Comment, headerCommentSize); - return S_OK; -} - -HRESULT CInArchive::TryEcd64(UInt64 offset, CCdInfo &cdInfo) -{ - RINOK(Seek(offset)); - const UInt32 kEcd64Size = 56; - Byte buf[kEcd64Size]; - if (!ReadBytesAndTestSize(buf, kEcd64Size)) - return S_FALSE; - if (GetUInt32(buf) != NSignature::kZip64EndOfCentralDir) - return S_FALSE; - // cdInfo.NumEntries = GetUInt64(buf + 24); - cdInfo.Size = GetUInt64(buf + 40); - cdInfo.Offset = GetUInt64(buf + 48); - return S_OK; -} - -HRESULT CInArchive::FindCd(CCdInfo &cdInfo) -{ - UInt64 endPosition; - RINOK(m_Stream->Seek(0, STREAM_SEEK_END, &endPosition)); - const UInt32 kBufSizeMax = (1 << 16) + kEcdSize + kZip64EcdLocatorSize; - Byte buf[kBufSizeMax]; - UInt32 bufSize = (endPosition < kBufSizeMax) ? (UInt32)endPosition : kBufSizeMax; - if (bufSize < kEcdSize) - return S_FALSE; - UInt64 startPosition = endPosition - bufSize; - RINOK(m_Stream->Seek(startPosition, STREAM_SEEK_SET, &m_Position)); - if (m_Position != startPosition) - return S_FALSE; - if (!ReadBytesAndTestSize(buf, bufSize)) - return S_FALSE; - for (int i = (int)(bufSize - kEcdSize); i >= 0; i--) - { - if (GetUInt32(buf + i) == NSignature::kEndOfCentralDir) - { - if (i >= kZip64EcdLocatorSize) - { - const Byte *locator = buf + i - kZip64EcdLocatorSize; - if (GetUInt32(locator) == NSignature::kZip64EndOfCentralDirLocator) - { - UInt64 ecd64Offset = GetUInt64(locator + 8); - if (TryEcd64(ecd64Offset, cdInfo) == S_OK) - return S_OK; - if (TryEcd64(m_ArchiveInfo.StartPosition + ecd64Offset, cdInfo) == S_OK) - { - m_ArchiveInfo.Base = m_ArchiveInfo.StartPosition; - return S_OK; - } - } - } - if (GetUInt32(buf + i + 4) == 0) - { - // cdInfo.NumEntries = GetUInt16(buf + i + 10); - cdInfo.Size = GetUInt32(buf + i + 12); - cdInfo.Offset = GetUInt32(buf + i + 16); - UInt64 curPos = endPosition - bufSize + i; - UInt64 cdEnd = cdInfo.Size + cdInfo.Offset; - if (curPos > cdEnd) - m_ArchiveInfo.Base = curPos - cdEnd; - return S_OK; - } - } - } - return S_FALSE; -} - -HRESULT CInArchive::TryReadCd(CObjectVector &items, UInt64 cdOffset, UInt64 cdSize, CProgressVirt *progress) -{ - items.Clear(); - RINOK(m_Stream->Seek(cdOffset, STREAM_SEEK_SET, &m_Position)); - if (m_Position != cdOffset) - return S_FALSE; - while(m_Position - cdOffset < cdSize) - { - if (ReadUInt32() != NSignature::kCentralFileHeader) - return S_FALSE; - CItemEx cdItem; - RINOK(ReadCdItem(cdItem)); - items.Add(cdItem); - if (progress && items.Size() % 1000 == 0) - RINOK(progress->SetCompleted(items.Size())); - } - return (m_Position - cdOffset == cdSize) ? S_OK : S_FALSE; -} - -HRESULT CInArchive::ReadCd(CObjectVector &items, UInt64 &cdOffset, UInt64 &cdSize, CProgressVirt *progress) -{ - m_ArchiveInfo.Base = 0; - CCdInfo cdInfo; - RINOK(FindCd(cdInfo)); - HRESULT res = S_FALSE; - cdSize = cdInfo.Size; - cdOffset = cdInfo.Offset; - res = TryReadCd(items, m_ArchiveInfo.Base + cdOffset, cdSize, progress); - if (res == S_FALSE && m_ArchiveInfo.Base == 0) - { - res = TryReadCd(items, cdInfo.Offset + m_ArchiveInfo.StartPosition, cdSize, progress); - if (res == S_OK) - m_ArchiveInfo.Base = m_ArchiveInfo.StartPosition; - } - if (!ReadUInt32(m_Signature)) - return S_FALSE; - return res; -} - -HRESULT CInArchive::ReadLocalsAndCd(CObjectVector &items, CProgressVirt *progress, UInt64 &cdOffset) -{ - items.Clear(); - while (m_Signature == NSignature::kLocalFileHeader) - { - // FSeek points to next byte after signature - // NFileHeader::CLocalBlock localHeader; - CItemEx item; - item.LocalHeaderPosition = m_Position - m_StreamStartPosition - 4; // points to signature; - RINOK(ReadLocalItem(item)); - item.FromLocal = true; - ReadLocalItemDescriptor(item); - items.Add(item); - if (progress && items.Size() % 100 == 0) - RINOK(progress->SetCompleted(items.Size())); - if (!ReadUInt32(m_Signature)) - break; - } - cdOffset = m_Position - 4; - for (int i = 0; i < items.Size(); i++) - { - if (progress && i % 1000 == 0) - RINOK(progress->SetCompleted(items.Size())); - if (m_Signature != NSignature::kCentralFileHeader) - return S_FALSE; - - CItemEx cdItem; - RINOK(ReadCdItem(cdItem)); - - if (i == 0) - { - if (cdItem.LocalHeaderPosition == 0) - m_ArchiveInfo.Base = m_ArchiveInfo.StartPosition; - } - - int index; - int left = 0, right = items.Size(); - for (;;) - { - if (left >= right) - return S_FALSE; - index = (left + right) / 2; - UInt64 position = items[index].LocalHeaderPosition - m_ArchiveInfo.Base; - if (cdItem.LocalHeaderPosition == position) - break; - if (cdItem.LocalHeaderPosition < position) - right = index; - else - left = index + 1; - } - CItemEx &item = items[index]; - item.LocalHeaderPosition = cdItem.LocalHeaderPosition; - item.MadeByVersion = cdItem.MadeByVersion; - item.CentralExtra = cdItem.CentralExtra; - - if ( - // item.ExtractVersion != cdItem.ExtractVersion || - item.Flags != cdItem.Flags || - item.CompressionMethod != cdItem.CompressionMethod || - // item.Time != cdItem.Time || - item.FileCRC != cdItem.FileCRC) - return S_FALSE; - - if (item.Name.Length() != cdItem.Name.Length() || - item.PackSize != cdItem.PackSize || - item.UnPackSize != cdItem.UnPackSize - ) - return S_FALSE; - item.Name = cdItem.Name; - item.InternalAttributes = cdItem.InternalAttributes; - item.ExternalAttributes = cdItem.ExternalAttributes; - item.Comment = cdItem.Comment; - item.FromCentral = cdItem.FromCentral; - if (!ReadUInt32(m_Signature)) - return S_FALSE; - } - return S_OK; -} - -struct CEcd -{ - UInt16 thisDiskNumber; - UInt16 startCDDiskNumber; - UInt16 numEntriesInCDOnThisDisk; - UInt16 numEntriesInCD; - UInt32 cdSize; - UInt32 cdStartOffset; - UInt16 commentSize; - void Parse(const Byte *p); -}; - -void CEcd::Parse(const Byte *p) -{ - thisDiskNumber = Get16(p); - startCDDiskNumber = Get16(p + 2); - numEntriesInCDOnThisDisk = Get16(p + 4); - numEntriesInCD = Get16(p + 6); - cdSize = Get32(p + 8); - cdStartOffset = Get32(p + 12); - commentSize = Get16(p + 16); -} - -struct CEcd64 -{ - UInt16 versionMade; - UInt16 versionNeedExtract; - UInt32 thisDiskNumber; - UInt32 startCDDiskNumber; - UInt64 numEntriesInCDOnThisDisk; - UInt64 numEntriesInCD; - UInt64 cdSize; - UInt64 cdStartOffset; - void Parse(const Byte *p); - CEcd64() { memset(this, 0, sizeof(*this)); } -}; - -void CEcd64::Parse(const Byte *p) -{ - versionMade = Get16(p); - versionNeedExtract = Get16(p + 2); - thisDiskNumber = Get32(p + 4); - startCDDiskNumber = Get32(p + 8); - numEntriesInCDOnThisDisk = Get64(p + 12); - numEntriesInCD = Get64(p + 20); - cdSize = Get64(p + 28); - cdStartOffset = Get64(p + 36); -} - -#define COPY_ECD_ITEM_16(n) if (!isZip64 || ecd. n != 0xFFFF) ecd64. n = ecd. n; -#define COPY_ECD_ITEM_32(n) if (!isZip64 || ecd. n != 0xFFFFFFFF) ecd64. n = ecd. n; - -HRESULT CInArchive::ReadHeaders(CObjectVector &items, CProgressVirt *progress) -{ - // m_Signature must be kLocalFileHeaderSignature or - // kEndOfCentralDirSignature - // m_Position points to next byte after signature - - IsZip64 = false; - items.Clear(); - - UInt64 cdSize, cdStartOffset; - HRESULT res = ReadCd(items, cdStartOffset, cdSize, progress); - if (res != S_FALSE && res != S_OK) - return res; - - /* - if (res != S_OK) - return res; - res = S_FALSE; - */ - - if (res == S_FALSE) - { - m_ArchiveInfo.Base = 0; - RINOK(m_Stream->Seek(m_ArchiveInfo.StartPosition, STREAM_SEEK_SET, &m_Position)); - if (m_Position != m_ArchiveInfo.StartPosition) - return S_FALSE; - if (!ReadUInt32(m_Signature)) - return S_FALSE; - RINOK(ReadLocalsAndCd(items, progress, cdStartOffset)); - cdSize = (m_Position - 4) - cdStartOffset; - cdStartOffset -= m_ArchiveInfo.Base; - } - - CEcd64 ecd64; - bool isZip64 = false; - UInt64 zip64EcdStartOffset = m_Position - 4 - m_ArchiveInfo.Base; - if (m_Signature == NSignature::kZip64EndOfCentralDir) - { - IsZip64 = isZip64 = true; - UInt64 recordSize = ReadUInt64(); - - const int kBufSize = kZip64EcdSize; - Byte buf[kBufSize]; - SafeReadBytes(buf, kBufSize); - ecd64.Parse(buf); - - IncreaseRealPosition(recordSize - kZip64EcdSize); - if (!ReadUInt32(m_Signature)) - return S_FALSE; - if (ecd64.thisDiskNumber != 0 || ecd64.startCDDiskNumber != 0) - throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported); - if (ecd64.numEntriesInCDOnThisDisk != items.Size() || - ecd64.numEntriesInCD != items.Size() || - ecd64.cdSize != cdSize || - (ecd64.cdStartOffset != cdStartOffset && - (!items.IsEmpty()))) - return S_FALSE; - } - if (m_Signature == NSignature::kZip64EndOfCentralDirLocator) - { - /* UInt32 startEndCDDiskNumber = */ ReadUInt32(); - UInt64 endCDStartOffset = ReadUInt64(); - /* UInt32 numberOfDisks = */ ReadUInt32(); - if (zip64EcdStartOffset != endCDStartOffset) - return S_FALSE; - if (!ReadUInt32(m_Signature)) - return S_FALSE; - } - if (m_Signature != NSignature::kEndOfCentralDir) - return S_FALSE; - - const int kBufSize = kEcdSize - 4; - Byte buf[kBufSize]; - SafeReadBytes(buf, kBufSize); - CEcd ecd; - ecd.Parse(buf); - - COPY_ECD_ITEM_16(thisDiskNumber); - COPY_ECD_ITEM_16(startCDDiskNumber); - COPY_ECD_ITEM_16(numEntriesInCDOnThisDisk); - COPY_ECD_ITEM_16(numEntriesInCD); - COPY_ECD_ITEM_32(cdSize); - COPY_ECD_ITEM_32(cdStartOffset); - - ReadBuffer(m_ArchiveInfo.Comment, ecd.commentSize); - - if (ecd64.thisDiskNumber != 0 || ecd64.startCDDiskNumber != 0) - throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported); - if ((UInt16)ecd64.numEntriesInCDOnThisDisk != ((UInt16)items.Size()) || - (UInt16)ecd64.numEntriesInCD != ((UInt16)items.Size()) || - (UInt32)ecd64.cdSize != (UInt32)cdSize || - ((UInt32)(ecd64.cdStartOffset) != (UInt32)cdStartOffset && - (!items.IsEmpty()))) - return S_FALSE; - - return S_OK; -} - -ISequentialInStream* CInArchive::CreateLimitedStream(UInt64 position, UInt64 size) -{ - CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; - CMyComPtr stream(streamSpec); - SeekInArchive(m_ArchiveInfo.Base + position); - streamSpec->SetStream(m_Stream); - streamSpec->Init(size); - return stream.Detach(); -} - -IInStream* CInArchive::CreateStream() -{ - CMyComPtr stream = m_Stream; - return stream.Detach(); -} - -bool CInArchive::SeekInArchive(UInt64 position) -{ - UInt64 newPosition; - if (m_Stream->Seek(position, STREAM_SEEK_SET, &newPosition) != S_OK) - return false; - return (newPosition == position); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.h deleted file mode 100644 index dd8114c3d..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipIn.h +++ /dev/null @@ -1,116 +0,0 @@ -// Archive/ZipIn.h - -#ifndef __ZIP_IN_H -#define __ZIP_IN_H - -#include "../../../Common/MyCom.h" -#include "../../IStream.h" - -#include "ZipHeader.h" -#include "ZipItemEx.h" - -namespace NArchive { -namespace NZip { - -class CInArchiveException -{ -public: - enum ECauseType - { - kUnexpectedEndOfArchive = 0, - kArchiceHeaderCRCError, - kFileHeaderCRCError, - kIncorrectArchive, - kDataDescroptorsAreNotSupported, - kMultiVolumeArchiveAreNotSupported, - kReadStreamError, - kSeekStreamError - } - Cause; - CInArchiveException(ECauseType cause): Cause(cause) {} -}; - -class CInArchiveInfo -{ -public: - UInt64 Base; - UInt64 StartPosition; - CByteBuffer Comment; - CInArchiveInfo(): Base(0), StartPosition(0) {} - void Clear() - { - Base = 0; - StartPosition = 0; - Comment.SetCapacity(0); - } -}; - -class CProgressVirt -{ -public: - STDMETHOD(SetTotal)(UInt64 numFiles) PURE; - STDMETHOD(SetCompleted)(UInt64 numFiles) PURE; -}; - -struct CCdInfo -{ - // UInt64 NumEntries; - UInt64 Size; - UInt64 Offset; -}; - -class CInArchive -{ - CMyComPtr m_Stream; - UInt32 m_Signature; - UInt64 m_StreamStartPosition; - UInt64 m_Position; - AString m_NameBuffer; - - HRESULT Seek(UInt64 offset); - - HRESULT FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit); - bool ReadUInt32(UInt32 &signature); - AString ReadFileName(UInt32 nameSize); - - HRESULT ReadBytes(void *data, UInt32 size, UInt32 *processedSize); - bool ReadBytesAndTestSize(void *data, UInt32 size); - void SafeReadBytes(void *data, UInt32 size); - void ReadBuffer(CByteBuffer &buffer, UInt32 size); - Byte ReadByte(); - UInt16 ReadUInt16(); - UInt32 ReadUInt32(); - UInt64 ReadUInt64(); - - void IncreaseRealPosition(UInt64 addValue); - - void ReadExtra(UInt32 extraSize, CExtraBlock &extraBlock, - UInt64 &unpackSize, UInt64 &packSize, UInt64 &localHeaderOffset, UInt32 &diskStartNumber); - HRESULT ReadLocalItem(CItemEx &item); - HRESULT ReadLocalItemDescriptor(CItemEx &item); - HRESULT ReadCdItem(CItemEx &item); - HRESULT TryEcd64(UInt64 offset, CCdInfo &cdInfo); - HRESULT FindCd(CCdInfo &cdInfo); - HRESULT TryReadCd(CObjectVector &items, UInt64 cdOffset, UInt64 cdSize, CProgressVirt *progress); - HRESULT ReadCd(CObjectVector &items, UInt64 &cdOffset, UInt64 &cdSize, CProgressVirt *progress); - HRESULT ReadLocalsAndCd(CObjectVector &items, CProgressVirt *progress, UInt64 &cdOffset); -public: - CInArchiveInfo m_ArchiveInfo; - bool IsZip64; - - HRESULT ReadHeaders(CObjectVector &items, CProgressVirt *progress); - HRESULT ReadLocalItemAfterCdItem(CItemEx &item); - HRESULT ReadLocalItemAfterCdItemFull(CItemEx &item); - HRESULT Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit); - void Close(); - void GetArchiveInfo(CInArchiveInfo &archiveInfo) const; - bool SeekInArchive(UInt64 position); - ISequentialInStream *CreateLimitedStream(UInt64 position, UInt64 size); - IInStream* CreateStream(); - - bool IsOpen() const { return m_Stream != NULL; } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.cpp deleted file mode 100644 index 6756e4b44..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.cpp +++ /dev/null @@ -1,147 +0,0 @@ -// Archive/ZipItem.cpp - -#include "StdAfx.h" - -#include "ZipHeader.h" -#include "ZipItem.h" -#include "../Common/ItemNameUtils.h" -#include "../../../../C/CpuArch.h" - -namespace NArchive { -namespace NZip { - -bool operator==(const CVersion &v1, const CVersion &v2) -{ - return (v1.Version == v2.Version) && (v1.HostOS == v2.HostOS); -} - -bool operator!=(const CVersion &v1, const CVersion &v2) -{ - return !(v1 == v2); -} - -bool CExtraSubBlock::ExtractNtfsTime(int index, FILETIME &ft) const -{ - ft.dwHighDateTime = ft.dwLowDateTime = 0; - UInt32 size = (UInt32)Data.GetCapacity(); - if (ID != NFileHeader::NExtraID::kNTFS || size < 32) - return false; - const Byte *p = (const Byte *)Data; - p += 4; // for reserved - size -= 4; - while (size > 4) - { - UInt16 tag = GetUi16(p); - UInt32 attrSize = GetUi16(p + 2); - p += 4; - size -= 4; - if (attrSize > size) - attrSize = size; - - if (tag == NFileHeader::NNtfsExtra::kTagTime && attrSize >= 24) - { - p += 8 * index; - ft.dwLowDateTime = GetUi32(p); - ft.dwHighDateTime = GetUi32(p + 4); - return true; - } - p += attrSize; - size -= attrSize; - } - return false; -} - -bool CLocalItem::IsDir() const -{ - return NItemName::HasTailSlash(Name, GetCodePage()); -} - -bool CItem::IsDir() const -{ - if (NItemName::HasTailSlash(Name, GetCodePage())) - return true; - if (!FromCentral) - return false; - WORD highAttributes = WORD((ExternalAttributes >> 16 ) & 0xFFFF); - switch(MadeByVersion.HostOS) - { - case NFileHeader::NHostOS::kAMIGA: - switch (highAttributes & NFileHeader::NAmigaAttribute::kIFMT) - { - case NFileHeader::NAmigaAttribute::kIFDIR: return true; - case NFileHeader::NAmigaAttribute::kIFREG: return false; - default: return false; // change it throw kUnknownAttributes; - } - case NFileHeader::NHostOS::kFAT: - case NFileHeader::NHostOS::kNTFS: - case NFileHeader::NHostOS::kHPFS: - case NFileHeader::NHostOS::kVFAT: - return ((ExternalAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0); - case NFileHeader::NHostOS::kAtari: - case NFileHeader::NHostOS::kMac: - case NFileHeader::NHostOS::kVMS: - case NFileHeader::NHostOS::kVM_CMS: - case NFileHeader::NHostOS::kAcorn: - case NFileHeader::NHostOS::kMVS: - return false; // change it throw kUnknownAttributes; - default: - /* - switch (highAttributes & NFileHeader::NUnixAttribute::kIFMT) - { - case NFileHeader::NUnixAttribute::kIFDIR: - return true; - default: - return false; - } - */ - return false; - } -} - -UInt32 CLocalItem::GetWinAttributes() const -{ - DWORD winAttributes = 0; - if (IsDir()) - winAttributes |= FILE_ATTRIBUTE_DIRECTORY; - return winAttributes; -} - -UInt32 CItem::GetWinAttributes() const -{ - DWORD winAttributes = 0; - switch(MadeByVersion.HostOS) - { - case NFileHeader::NHostOS::kFAT: - case NFileHeader::NHostOS::kNTFS: - if (FromCentral) - winAttributes = ExternalAttributes; - break; - default: - winAttributes = 0; // must be converted from unix value; - } - if (IsDir()) // test it; - winAttributes |= FILE_ATTRIBUTE_DIRECTORY; - return winAttributes; -} - -void CLocalItem::SetFlagBits(int startBitNumber, int numBits, int value) -{ - UInt16 mask = (UInt16)(((1 << numBits) - 1) << startBitNumber); - Flags &= ~mask; - Flags |= value << startBitNumber; -} - -void CLocalItem::SetBitMask(int bitMask, bool enable) -{ - if(enable) - Flags |= bitMask; - else - Flags &= ~bitMask; -} - -void CLocalItem::SetEncrypted(bool encrypted) - { SetBitMask(NFileHeader::NFlags::kEncrypted, encrypted); } -void CLocalItem::SetUtf8(bool isUtf8) - { SetBitMask(NFileHeader::NFlags::kUtf8, isUtf8); } - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.h deleted file mode 100644 index e7e0c47bf..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItem.h +++ /dev/null @@ -1,268 +0,0 @@ -// Archive/ZipItem.h - -#ifndef __ARCHIVE_ZIP_ITEM_H -#define __ARCHIVE_ZIP_ITEM_H - -#include "../../../Common/Types.h" -#include "../../../Common/MyString.h" -#include "../../../Common/Buffer.h" -#include "../../../Common/UTFConvert.h" -#include "../../../Common/StringConvert.h" - -#include "ZipHeader.h" - -namespace NArchive { -namespace NZip { - -struct CVersion -{ - Byte Version; - Byte HostOS; -}; - -bool operator==(const CVersion &v1, const CVersion &v2); -bool operator!=(const CVersion &v1, const CVersion &v2); - -struct CExtraSubBlock -{ - UInt16 ID; - CByteBuffer Data; - bool ExtractNtfsTime(int index, FILETIME &ft) const; -}; - -struct CWzAesExtraField -{ - UInt16 VendorVersion; // 0x0001 - AE-1, 0x0002 - AE-2, - // UInt16 VendorId; // "AE" - Byte Strength; // 1 - 128-bit , 2 - 192-bit , 3 - 256-bit - UInt16 Method; - - CWzAesExtraField(): VendorVersion(2), Strength(3), Method(0) {} - - bool NeedCrc() const { return (VendorVersion == 1); } - - bool ParseFromSubBlock(const CExtraSubBlock &sb) - { - if (sb.ID != NFileHeader::NExtraID::kWzAES) - return false; - if (sb.Data.GetCapacity() < 7) - return false; - const Byte *p = (const Byte *)sb.Data; - VendorVersion = (((UInt16)p[1]) << 8) | p[0]; - if (p[2] != 'A' || p[3] != 'E') - return false; - Strength = p[4]; - Method = (((UInt16)p[6]) << 16) | p[5]; - return true; - } - void SetSubBlock(CExtraSubBlock &sb) const - { - sb.Data.SetCapacity(7); - sb.ID = NFileHeader::NExtraID::kWzAES; - Byte *p = (Byte *)sb.Data; - p[0] = (Byte)VendorVersion; - p[1] = (Byte)(VendorVersion >> 8); - p[2] = 'A'; - p[3] = 'E'; - p[4] = Strength; - p[5] = (Byte)Method; - p[6] = (Byte)(Method >> 8); - } -}; - -namespace NStrongCryptoFlags -{ - const UInt16 kDES = 0x6601; - const UInt16 kRC2old = 0x6602; - const UInt16 k3DES168 = 0x6603; - const UInt16 k3DES112 = 0x6609; - const UInt16 kAES128 = 0x660E; - const UInt16 kAES192 = 0x660F; - const UInt16 kAES256 = 0x6610; - const UInt16 kRC2 = 0x6702; - const UInt16 kBlowfish = 0x6720; - const UInt16 kTwofish = 0x6721; - const UInt16 kRC4 = 0x6801; -} - -struct CStrongCryptoField -{ - UInt16 Format; - UInt16 AlgId; - UInt16 BitLen; - UInt16 Flags; - - bool ParseFromSubBlock(const CExtraSubBlock &sb) - { - if (sb.ID != NFileHeader::NExtraID::kStrongEncrypt) - return false; - const Byte *p = (const Byte *)sb.Data; - if (sb.Data.GetCapacity() < 8) - return false; - Format = (((UInt16)p[1]) << 8) | p[0]; - AlgId = (((UInt16)p[3]) << 8) | p[2]; - BitLen = (((UInt16)p[5]) << 8) | p[4]; - Flags = (((UInt16)p[7]) << 8) | p[6]; - return (Format == 2); - } -}; - -struct CExtraBlock -{ - CObjectVector SubBlocks; - void Clear() { SubBlocks.Clear(); } - size_t GetSize() const - { - size_t res = 0; - for (int i = 0; i < SubBlocks.Size(); i++) - res += SubBlocks[i].Data.GetCapacity() + 2 + 2; - return res; - } - bool GetWzAesField(CWzAesExtraField &aesField) const - { - for (int i = 0; i < SubBlocks.Size(); i++) - if (aesField.ParseFromSubBlock(SubBlocks[i])) - return true; - return false; - } - - bool GetStrongCryptoField(CStrongCryptoField &f) const - { - for (int i = 0; i < SubBlocks.Size(); i++) - if (f.ParseFromSubBlock(SubBlocks[i])) - return true; - return false; - } - - bool HasWzAesField() const - { - CWzAesExtraField aesField; - return GetWzAesField(aesField); - } - - bool GetNtfsTime(int index, FILETIME &ft) const - { - for (int i = 0; i < SubBlocks.Size(); i++) - { - const CExtraSubBlock &sb = SubBlocks[i]; - if (sb.ID == NFileHeader::NExtraID::kNTFS) - return sb.ExtractNtfsTime(index, ft); - } - return false; - } - - /* - bool HasStrongCryptoField() const - { - CStrongCryptoField f; - return GetStrongCryptoField(f); - } - */ - - void RemoveUnknownSubBlocks() - { - for (int i = SubBlocks.Size() - 1; i >= 0; i--) - if (SubBlocks[i].ID != NFileHeader::NExtraID::kWzAES) - SubBlocks.Delete(i); - } -}; - - -class CLocalItem -{ -public: - CVersion ExtractVersion; - UInt16 Flags; - UInt16 CompressionMethod; - UInt32 Time; - UInt32 FileCRC; - UInt64 PackSize; - UInt64 UnPackSize; - - AString Name; - - CExtraBlock LocalExtra; - - bool IsUtf8() const { return (Flags & NFileHeader::NFlags::kUtf8) != 0; } - - bool IsEncrypted() const { return (Flags & NFileHeader::NFlags::kEncrypted) != 0; } - bool IsStrongEncrypted() const { return IsEncrypted() && (Flags & NFileHeader::NFlags::kStrongEncrypted) != 0; }; - - bool IsLzmaEOS() const { return (Flags & NFileHeader::NFlags::kLzmaEOS) != 0; } - - bool IsDir() const; - bool IgnoreItem() const { return false; } - UInt32 GetWinAttributes() const; - - bool HasDescriptor() const { return (Flags & NFileHeader::NFlags::kDescriptorUsedMask) != 0; } - - UString GetUnicodeString(const AString &s) const - { - UString res; - if (IsUtf8()) - if (!ConvertUTF8ToUnicode(s, res)) - res.Empty(); - if (res.IsEmpty()) - res = MultiByteToUnicodeString(s, GetCodePage()); - return res; - } - -private: - void SetFlagBits(int startBitNumber, int numBits, int value); - void SetBitMask(int bitMask, bool enable); -public: - void ClearFlags() { Flags = 0; } - void SetEncrypted(bool encrypted); - void SetUtf8(bool isUtf8); - - WORD GetCodePage() const { return CP_OEMCP; } -}; - -class CItem: public CLocalItem -{ -public: - CVersion MadeByVersion; - UInt16 InternalAttributes; - UInt32 ExternalAttributes; - - UInt64 LocalHeaderPosition; - - FILETIME NtfsMTime; - FILETIME NtfsATime; - FILETIME NtfsCTime; - - CExtraBlock CentralExtra; - CByteBuffer Comment; - - bool FromLocal; - bool FromCentral; - bool NtfsTimeIsDefined; - - bool IsDir() const; - UInt32 GetWinAttributes() const; - - bool IsThereCrc() const - { - if (CompressionMethod == NFileHeader::NCompressionMethod::kWzAES) - { - CWzAesExtraField aesField; - if (CentralExtra.GetWzAesField(aesField)) - return aesField.NeedCrc(); - } - return (FileCRC != 0 || !IsDir()); - } - - WORD GetCodePage() const - { - return (WORD)((MadeByVersion.HostOS == NFileHeader::NHostOS::kFAT - || MadeByVersion.HostOS == NFileHeader::NHostOS::kNTFS - ) ? CP_OEMCP : CP_ACP); - } - CItem() : FromLocal(false), FromCentral(false), NtfsTimeIsDefined(false) {} -}; - -}} - -#endif - - diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItemEx.h b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItemEx.h deleted file mode 100644 index 0d74edd80..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipItemEx.h +++ /dev/null @@ -1,34 +0,0 @@ -// Archive/ZipItemEx.h - -#ifndef __ARCHIVE_ZIP_ITEMEX_H -#define __ARCHIVE_ZIP_ITEMEX_H - -#include "ZipHeader.h" -#include "ZipItem.h" - -namespace NArchive { -namespace NZip { - -class CItemEx: public CItem -{ -public: - UInt32 FileHeaderWithNameSize; - UInt16 LocalExtraSize; - - UInt64 GetLocalFullSize() const - { return FileHeaderWithNameSize + LocalExtraSize + PackSize + - (HasDescriptor() ? NFileHeader::kDataDescriptorSize : 0); }; - /* - UInt64 GetLocalFullSize(bool isZip64) const - { return FileHeaderWithNameSize + LocalExtraSize + PackSize + - (HasDescriptor() ? (isZip64 ? NFileHeader::kDataDescriptor64Size : NFileHeader::kDataDescriptorSize) : 0); }; - */ - UInt64 GetLocalExtraPosition() const - { return LocalHeaderPosition + FileHeaderWithNameSize; }; - UInt64 GetDataPosition() const - { return GetLocalExtraPosition() + LocalExtraSize; }; -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipRegister.cpp deleted file mode 100644 index 0e90e4ec3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Archive/Zip/ZipRegister.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// ZipRegister.cpp - -#include "StdAfx.h" - -#include "../../Common/RegisterArc.h" - -#include "ZipHandler.h" -static IInArchive *CreateArc() { return new NArchive::NZip::CHandler; } -#ifndef EXTRACT_ONLY -static IOutArchive *CreateArcOut() { return new NArchive::NZip::CHandler; } -#else -#define CreateArcOut 0 -#endif - -static CArcInfo g_ArcInfo = { L"Zip", L"zip jar xpi zsg", 0, 1, { 0x50, 0x4B, 0x03, 0x04 }, 4, false, CreateArc, CreateArcOut }; -static CArcInfo g_ArcInfo2 = { L"Zip", L"zip jar xpi zsg", 0, 1, { 0x50, 0x4B, 0x01, 0x02 }, 4, false, CreateArc, CreateArcOut }; -static CArcInfo g_ArcInfo3 = { L"Zip", L"zip jar xpi zsg", 0, 1, { 0x50, 0x4B, 0x05, 0x06 }, 4, false, CreateArc, CreateArcOut }; - -REGISTER_ARC(Zip) -REGISTER_ARCN(Zip,2) -REGISTER_ARCN(Zip,3) diff --git a/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.cpp b/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.cpp deleted file mode 100644 index 10c9f9600..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.cpp +++ /dev/null @@ -1,292 +0,0 @@ -// CreateCoder.cpp - -#include "StdAfx.h" - -#include "CreateCoder.h" - -#include "../../Windows/PropVariant.h" -#include "../../Windows/Defs.h" -#include "FilterCoder.h" -#include "RegisterCodec.h" - -static const unsigned int kNumCodecsMax = 64; -unsigned int g_NumCodecs = 0; -const CCodecInfo *g_Codecs[kNumCodecsMax]; -void RegisterCodec(const CCodecInfo *codecInfo) -{ - if (g_NumCodecs < kNumCodecsMax) - g_Codecs[g_NumCodecs++] = codecInfo; -} - -#ifdef EXTERNAL_CODECS -static HRESULT ReadNumberOfStreams(ICompressCodecsInfo *codecsInfo, UInt32 index, PROPID propID, UInt32 &res) -{ - NWindows::NCOM::CPropVariant prop; - RINOK(codecsInfo->GetProperty(index, propID, &prop)); - if (prop.vt == VT_EMPTY) - res = 1; - else if (prop.vt == VT_UI4) - res = prop.ulVal; - else - return E_INVALIDARG; - return S_OK; -} - -static HRESULT ReadIsAssignedProp(ICompressCodecsInfo *codecsInfo, UInt32 index, PROPID propID, bool &res) -{ - NWindows::NCOM::CPropVariant prop; - RINOK(codecsInfo->GetProperty(index, propID, &prop)); - if (prop.vt == VT_EMPTY) - res = true; - else if (prop.vt == VT_BOOL) - res = VARIANT_BOOLToBool(prop.boolVal); - else - return E_INVALIDARG; - return S_OK; -} - -HRESULT LoadExternalCodecs(ICompressCodecsInfo *codecsInfo, CObjectVector &externalCodecs) -{ - UInt32 num; - RINOK(codecsInfo->GetNumberOfMethods(&num)); - for (UInt32 i = 0; i < num; i++) - { - CCodecInfoEx info; - NWindows::NCOM::CPropVariant prop; - RINOK(codecsInfo->GetProperty(i, NMethodPropID::kID, &prop)); - // if (prop.vt != VT_BSTR) - // info.Id.IDSize = (Byte)SysStringByteLen(prop.bstrVal); - // memmove(info.Id.ID, prop.bstrVal, info.Id.IDSize); - if (prop.vt != VT_UI8) - { - continue; // old Interface - // return E_INVALIDARG; - } - info.Id = prop.uhVal.QuadPart; - prop.Clear(); - - RINOK(codecsInfo->GetProperty(i, NMethodPropID::kName, &prop)); - if (prop.vt == VT_BSTR) - info.Name = prop.bstrVal; - else if (prop.vt != VT_EMPTY) - return E_INVALIDARG;; - - RINOK(ReadNumberOfStreams(codecsInfo, i, NMethodPropID::kInStreams, info.NumInStreams)); - RINOK(ReadNumberOfStreams(codecsInfo, i, NMethodPropID::kOutStreams, info.NumOutStreams)); - RINOK(ReadIsAssignedProp(codecsInfo, i, NMethodPropID::kEncoderIsAssigned, info.EncoderIsAssigned)); - RINOK(ReadIsAssignedProp(codecsInfo, i, NMethodPropID::kDecoderIsAssigned, info.DecoderIsAssigned)); - - externalCodecs.Add(info); - } - return S_OK; -} - -#endif - -bool FindMethod( - #ifdef EXTERNAL_CODECS - ICompressCodecsInfo * /* codecsInfo */, const CObjectVector *externalCodecs, - #endif - const UString &name, - CMethodId &methodId, UInt32 &numInStreams, UInt32 &numOutStreams) -{ - UInt32 i; - for (i = 0; i < g_NumCodecs; i++) - { - const CCodecInfo &codec = *g_Codecs[i]; - if (name.CompareNoCase(codec.Name) == 0) - { - methodId = codec.Id; - numInStreams = codec.NumInStreams; - numOutStreams = 1; - return true; - } - } - #ifdef EXTERNAL_CODECS - if (externalCodecs) - for (i = 0; i < (UInt32)externalCodecs->Size(); i++) - { - const CCodecInfoEx &codec = (*externalCodecs)[i]; - if (codec.Name.CompareNoCase(name) == 0) - { - methodId = codec.Id; - numInStreams = codec.NumInStreams; - numOutStreams = codec.NumOutStreams; - return true; - } - } - #endif - return false; -} - -bool FindMethod( - #ifdef EXTERNAL_CODECS - ICompressCodecsInfo * /* codecsInfo */, const CObjectVector *externalCodecs, - #endif - CMethodId methodId, UString &name) -{ - UInt32 i; - for (i = 0; i < g_NumCodecs; i++) - { - const CCodecInfo &codec = *g_Codecs[i]; - if (methodId == codec.Id) - { - name = codec.Name; - return true; - } - } - #ifdef EXTERNAL_CODECS - if (externalCodecs) - for (i = 0; i < (UInt32)externalCodecs->Size(); i++) - { - const CCodecInfoEx &codec = (*externalCodecs)[i]; - if (methodId == codec.Id) - { - name = codec.Name; - return true; - } - } - #endif - return false; -} - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &filter, - CMyComPtr &coder, - CMyComPtr &coder2, - bool encode, bool onlyCoder) -{ - bool created = false; - UInt32 i; - for (i = 0; i < g_NumCodecs; i++) - { - const CCodecInfo &codec = *g_Codecs[i]; - if (codec.Id == methodId) - { - if (encode) - { - if (codec.CreateEncoder) - { - void *p = codec.CreateEncoder(); - if (codec.IsFilter) filter = (ICompressFilter *)p; - else if (codec.NumInStreams == 1) coder = (ICompressCoder *)p; - else coder2 = (ICompressCoder2 *)p; - created = (p != 0); - break; - } - } - else - if (codec.CreateDecoder) - { - void *p = codec.CreateDecoder(); - if (codec.IsFilter) filter = (ICompressFilter *)p; - else if (codec.NumInStreams == 1) coder = (ICompressCoder *)p; - else coder2 = (ICompressCoder2 *)p; - created = (p != 0); - break; - } - } - } - - #ifdef EXTERNAL_CODECS - if (!created && externalCodecs) - for (i = 0; i < (UInt32)externalCodecs->Size(); i++) - { - const CCodecInfoEx &codec = (*externalCodecs)[i]; - if (codec.Id == methodId) - { - if (encode) - { - if (codec.EncoderIsAssigned) - { - if (codec.IsSimpleCodec()) - { - HRESULT result = codecsInfo->CreateEncoder(i, &IID_ICompressCoder, (void **)&coder); - if (result != S_OK && result != E_NOINTERFACE && result != CLASS_E_CLASSNOTAVAILABLE) - return result; - if (!coder) - { - RINOK(codecsInfo->CreateEncoder(i, &IID_ICompressFilter, (void **)&filter)); - } - } - else - { - RINOK(codecsInfo->CreateEncoder(i, &IID_ICompressCoder2, (void **)&coder2)); - } - break; - } - } - else - if (codec.DecoderIsAssigned) - { - if (codec.IsSimpleCodec()) - { - HRESULT result = codecsInfo->CreateDecoder(i, &IID_ICompressCoder, (void **)&coder); - if (result != S_OK && result != E_NOINTERFACE && result != CLASS_E_CLASSNOTAVAILABLE) - return result; - if (!coder) - { - RINOK(codecsInfo->CreateDecoder(i, &IID_ICompressFilter, (void **)&filter)); - } - } - else - { - RINOK(codecsInfo->CreateDecoder(i, &IID_ICompressCoder2, (void **)&coder2)); - } - break; - } - } - } - #endif - - if (onlyCoder && filter) - { - CFilterCoder *coderSpec = new CFilterCoder; - coder = coderSpec; - coderSpec->Filter = filter; - } - return S_OK; -} - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &coder, - CMyComPtr &coder2, - bool encode) -{ - CMyComPtr filter; - return CreateCoder( - EXTERNAL_CODECS_LOC_VARS - methodId, - filter, coder, coder2, encode, true); -} - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &coder, bool encode) -{ - CMyComPtr filter; - CMyComPtr coder2; - return CreateCoder( - EXTERNAL_CODECS_LOC_VARS - methodId, - coder, coder2, encode); -} - -HRESULT CreateFilter( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &filter, - bool encode) -{ - CMyComPtr coder; - CMyComPtr coder2; - return CreateCoder( - EXTERNAL_CODECS_LOC_VARS - methodId, - filter, coder, coder2, encode, false); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.h b/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.h deleted file mode 100644 index 2f83f5ec5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/CreateCoder.h +++ /dev/null @@ -1,98 +0,0 @@ -// CreateCoder.h - -#ifndef __CREATECODER_H -#define __CREATECODER_H - -#include "../../Common/MyCom.h" -#include "../../Common/MyString.h" -#include "../ICoder.h" - -#include "MethodId.h" - -#ifdef EXTERNAL_CODECS - -struct CCodecInfoEx -{ - UString Name; - CMethodId Id; - UInt32 NumInStreams; - UInt32 NumOutStreams; - bool EncoderIsAssigned; - bool DecoderIsAssigned; - bool IsSimpleCodec() const { return NumOutStreams == 1 && NumInStreams == 1; } - CCodecInfoEx(): EncoderIsAssigned(false), DecoderIsAssigned(false) {} -}; - -HRESULT LoadExternalCodecs(ICompressCodecsInfo *codecsInfo, CObjectVector &externalCodecs); - -#define PUBLIC_ISetCompressCodecsInfo public ISetCompressCodecsInfo, -#define QUERY_ENTRY_ISetCompressCodecsInfo MY_QUERYINTERFACE_ENTRY(ISetCompressCodecsInfo) -#define DECL_ISetCompressCodecsInfo STDMETHOD(SetCompressCodecsInfo)(ICompressCodecsInfo *compressCodecsInfo); -#define IMPL_ISetCompressCodecsInfo2(x) \ -STDMETHODIMP x::SetCompressCodecsInfo(ICompressCodecsInfo *compressCodecsInfo) { \ - COM_TRY_BEGIN _codecsInfo = compressCodecsInfo; return LoadExternalCodecs(_codecsInfo, _externalCodecs); COM_TRY_END } -#define IMPL_ISetCompressCodecsInfo IMPL_ISetCompressCodecsInfo2(CHandler) - -#define EXTERNAL_CODECS_VARS2 _codecsInfo, &_externalCodecs - -#define DECL_EXTERNAL_CODECS_VARS CMyComPtr _codecsInfo; CObjectVector _externalCodecs; -#define EXTERNAL_CODECS_VARS EXTERNAL_CODECS_VARS2, - -#define DECL_EXTERNAL_CODECS_LOC_VARS2 ICompressCodecsInfo *codecsInfo, const CObjectVector *externalCodecs -#define EXTERNAL_CODECS_LOC_VARS2 codecsInfo, externalCodecs - -#define DECL_EXTERNAL_CODECS_LOC_VARS DECL_EXTERNAL_CODECS_LOC_VARS2, -#define EXTERNAL_CODECS_LOC_VARS EXTERNAL_CODECS_LOC_VARS2, - -#else - -#define PUBLIC_ISetCompressCodecsInfo -#define QUERY_ENTRY_ISetCompressCodecsInfo -#define DECL_ISetCompressCodecsInfo -#define IMPL_ISetCompressCodecsInfo -#define EXTERNAL_CODECS_VARS2 -#define DECL_EXTERNAL_CODECS_VARS -#define EXTERNAL_CODECS_VARS EXTERNAL_CODECS_VARS2 -#define DECL_EXTERNAL_CODECS_LOC_VARS2 -#define EXTERNAL_CODECS_LOC_VARS2 -#define DECL_EXTERNAL_CODECS_LOC_VARS -#define EXTERNAL_CODECS_LOC_VARS - -#endif - -bool FindMethod( - DECL_EXTERNAL_CODECS_LOC_VARS - const UString &name, CMethodId &methodId, UInt32 &numInStreams, UInt32 &numOutStreams); - -bool FindMethod( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, UString &name); - - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &filter, - CMyComPtr &coder, - CMyComPtr &coder2, - bool encode, bool onlyCoder); - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &coder, - CMyComPtr &coder2, - bool encode); - -HRESULT CreateCoder( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &coder, bool encode); - -HRESULT CreateFilter( - DECL_EXTERNAL_CODECS_LOC_VARS - CMethodId methodId, - CMyComPtr &filter, - bool encode); - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/DeclareArcs.h b/desmume/src/windows/7z/CPP/7zip/Common/DeclareArcs.h deleted file mode 100644 index 22443a779..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/DeclareArcs.h +++ /dev/null @@ -1,28 +0,0 @@ -// DeclareArcs.h - -#ifndef __DECLAREARCS_H -#define __DECLAREARCS_H - -#define DECLARE_ARC(x) struct CRegister##x { CRegister##x(); }; \ - FORCE_REF(CRegister##x, g_RegisterArc##x) - -#define DECLARE_ARCN(x,n) struct CRegister##x##n { CRegister##x##n(); }; \ - FORCE_REF(CRegister##x##n, g_RegisterArc##n##x) - -#ifndef FORCE_REF - #define FORCE_REF(...) -#endif - -DECLARE_ARC(7z) -DECLARE_ARC(BZip2) -DECLARE_ARC(GZip) -DECLARE_ARC(Lzh) -DECLARE_ARC(Lzma) -DECLARE_ARC(Rar) -DECLARE_ARC(Split) -DECLARE_ARC(Tar) -DECLARE_ARC(Zip) -DECLARE_ARCN(Zip,2) -DECLARE_ARCN(Zip,3) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/DeclareCodecs.h b/desmume/src/windows/7z/CPP/7zip/Common/DeclareCodecs.h deleted file mode 100644 index 6b933cac6..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/DeclareCodecs.h +++ /dev/null @@ -1,31 +0,0 @@ -// DeclareCodecs.h - -#ifndef __DECLARECODECS_H -#define __DECLARECODECS_H - -#define DECLARE_CODEC(x) struct CRegisterCodec##x { CRegisterCodec##x(); }; \ - FORCE_REF(CRegisterCodec##x, g_RegisterCodec##x) - -#define DECLARE_CODECS(x) struct CRegisterCodecs##x { CRegisterCodecs##x(); }; \ - FORCE_REF(CRegisterCodecs##x, g_RegisterCodecs##x) - -#ifndef FORCE_REF - #define FORCE_REF(...) -#endif - -DECLARE_CODEC(7zAES) -DECLARE_CODEC(BCJ2) -DECLARE_CODEC(BCJ) -DECLARE_CODEC(BZip2) -DECLARE_CODEC(Copy) -DECLARE_CODEC(Deflate64) -DECLARE_CODEC(DeflateNsis) -DECLARE_CODEC(Deflate) -DECLARE_CODEC(LZMA) -DECLARE_CODEC(PPMD) - -DECLARE_CODECS(Branch) -DECLARE_CODECS(ByteSwap) -DECLARE_CODECS(Rar) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.cpp b/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.cpp deleted file mode 100644 index 1985d383a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.cpp +++ /dev/null @@ -1,262 +0,0 @@ -// FilterCoder.cpp - -#include "StdAfx.h" - -#include "FilterCoder.h" -extern "C" -{ -#include "../../../C/Alloc.h" -} -#include "../../Common/Defs.h" -#include "StreamUtils.h" - -static const UInt32 kBufferSize = 1 << 17; - -CFilterCoder::CFilterCoder() -{ - _buffer = (Byte *)::MidAlloc(kBufferSize); -} - -CFilterCoder::~CFilterCoder() -{ - ::MidFree(_buffer); -} - -HRESULT CFilterCoder::WriteWithLimit(ISequentialOutStream *outStream, UInt32 size) -{ - if (_outSizeIsDefined) - { - UInt64 remSize = _outSize - _nowPos64; - if (size > remSize) - size = (UInt32)remSize; - } - RINOK(WriteStream(outStream, _buffer, size)); - _nowPos64 += size; - return S_OK; -} - - -STDMETHODIMP CFilterCoder::Code(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 * /* inSize */, const UInt64 *outSize, - ICompressProgressInfo *progress) -{ - RINOK(Init()); - UInt32 bufferPos = 0; - _outSizeIsDefined = (outSize != 0); - if (_outSizeIsDefined) - _outSize = *outSize; - - while(NeedMore()) - { - size_t processedSize = kBufferSize - bufferPos; - - // Change it: It can be optimized using ReadPart - RINOK(ReadStream(inStream, _buffer + bufferPos, &processedSize)); - - UInt32 endPos = bufferPos + (UInt32)processedSize; - - bufferPos = Filter->Filter(_buffer, endPos); - if (bufferPos > endPos) - { - for (; endPos< bufferPos; endPos++) - _buffer[endPos] = 0; - bufferPos = Filter->Filter(_buffer, endPos); - } - - if (bufferPos == 0) - { - if (endPos > 0) - return WriteWithLimit(outStream, endPos); - return S_OK; - } - RINOK(WriteWithLimit(outStream, bufferPos)); - if (progress != NULL) - { - RINOK(progress->SetRatioInfo(&_nowPos64, &_nowPos64)); - } - UInt32 i = 0; - while(bufferPos < endPos) - _buffer[i++] = _buffer[bufferPos++]; - bufferPos = i; - } - return S_OK; -} - -// #ifdef _ST_MODE -STDMETHODIMP CFilterCoder::SetOutStream(ISequentialOutStream *outStream) -{ - _bufferPos = 0; - _outStream = outStream; - return Init(); -} - -STDMETHODIMP CFilterCoder::ReleaseOutStream() -{ - _outStream.Release(); - return S_OK; -}; - - -STDMETHODIMP CFilterCoder::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 processedSizeTotal = 0; - while(size > 0) - { - UInt32 sizeMax = kBufferSize - _bufferPos; - UInt32 sizeTemp = size; - if (sizeTemp > sizeMax) - sizeTemp = sizeMax; - memmove(_buffer + _bufferPos, data, sizeTemp); - size -= sizeTemp; - processedSizeTotal += sizeTemp; - data = (const Byte *)data + sizeTemp; - UInt32 endPos = _bufferPos + sizeTemp; - _bufferPos = Filter->Filter(_buffer, endPos); - if (_bufferPos == 0) - { - _bufferPos = endPos; - break; - } - if (_bufferPos > endPos) - { - if (size != 0) - return E_FAIL; - break; - } - RINOK(WriteWithLimit(_outStream, _bufferPos)); - UInt32 i = 0; - while(_bufferPos < endPos) - _buffer[i++] = _buffer[_bufferPos++]; - _bufferPos = i; - } - if (processedSize != NULL) - *processedSize = processedSizeTotal; - return S_OK; -} - -STDMETHODIMP CFilterCoder::Flush() -{ - if (_bufferPos != 0) - { - UInt32 endPos = Filter->Filter(_buffer, _bufferPos); - if (endPos > _bufferPos) - { - for (; _bufferPos < endPos; _bufferPos++) - _buffer[_bufferPos] = 0; - if (Filter->Filter(_buffer, endPos) != endPos) - return E_FAIL; - } - RINOK(WriteStream(_outStream, _buffer, _bufferPos)); - _bufferPos = 0; - } - CMyComPtr flush; - _outStream.QueryInterface(IID_IOutStreamFlush, &flush); - if (flush) - return flush->Flush(); - return S_OK; -} - - -STDMETHODIMP CFilterCoder::SetInStream(ISequentialInStream *inStream) -{ - _convertedPosBegin = _convertedPosEnd = _bufferPos = 0; - _inStream = inStream; - return Init(); -} - -STDMETHODIMP CFilterCoder::ReleaseInStream() -{ - _inStream.Release(); - return S_OK; -}; - -STDMETHODIMP CFilterCoder::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 processedSizeTotal = 0; - while(size > 0) - { - if (_convertedPosBegin != _convertedPosEnd) - { - UInt32 sizeTemp = MyMin(size, _convertedPosEnd - _convertedPosBegin); - memmove(data, _buffer + _convertedPosBegin, sizeTemp); - _convertedPosBegin += sizeTemp; - data = (void *)((Byte *)data + sizeTemp); - size -= sizeTemp; - processedSizeTotal += sizeTemp; - break; - } - int i; - for (i = 0; _convertedPosEnd + i < _bufferPos; i++) - _buffer[i] = _buffer[i + _convertedPosEnd]; - _bufferPos = i; - _convertedPosBegin = _convertedPosEnd = 0; - size_t processedSizeTemp = kBufferSize - _bufferPos; - RINOK(ReadStream(_inStream, _buffer + _bufferPos, &processedSizeTemp)); - _bufferPos = _bufferPos + (UInt32)processedSizeTemp; - _convertedPosEnd = Filter->Filter(_buffer, _bufferPos); - if (_convertedPosEnd == 0) - { - if (_bufferPos == 0) - break; - else - { - _convertedPosEnd = _bufferPos; // check it - continue; - } - } - if (_convertedPosEnd > _bufferPos) - { - for (; _bufferPos < _convertedPosEnd; _bufferPos++) - _buffer[_bufferPos] = 0; - _convertedPosEnd = Filter->Filter(_buffer, _bufferPos); - } - } - if (processedSize != NULL) - *processedSize = processedSizeTotal; - return S_OK; -} - -// #endif // _ST_MODE - -#ifndef _NO_CRYPTO -STDMETHODIMP CFilterCoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - return _setPassword->CryptoSetPassword(data, size); -} -#endif - -#ifndef EXTRACT_ONLY -STDMETHODIMP CFilterCoder::SetCoderProperties(const PROPID *propIDs, - const PROPVARIANT *properties, UInt32 numProperties) -{ - return _SetCoderProperties->SetCoderProperties(propIDs, properties, numProperties); -} - -STDMETHODIMP CFilterCoder::WriteCoderProperties(ISequentialOutStream *outStream) -{ - return _writeCoderProperties->WriteCoderProperties(outStream); -} - -/* -STDMETHODIMP CFilterCoder::ResetSalt() -{ - return _CryptoResetSalt->ResetSalt(); -} -*/ - -STDMETHODIMP CFilterCoder::ResetInitVector() -{ - return _CryptoResetInitVector->ResetInitVector(); -} -#endif - -STDMETHODIMP CFilterCoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - return _setDecoderProperties->SetDecoderProperties2(data, size); -} - - - -void foo() -{ -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.h b/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.h deleted file mode 100644 index 496eb5e04..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/FilterCoder.h +++ /dev/null @@ -1,143 +0,0 @@ -// FilterCoder.h - -#ifndef __FILTERCODER_H -#define __FILTERCODER_H - -#include "../../Common/MyCom.h" -#include "../ICoder.h" -#include "../IPassword.h" - -#define MY_QUERYINTERFACE_ENTRY_AG(i, sub0, sub) if (iid == IID_ ## i) \ -{ if (!sub) RINOK(sub0->QueryInterface(IID_ ## i, (void **)&sub)) \ -*outObject = (void *)(i *)this; AddRef(); return S_OK; } - -class CFilterCoder: - public ICompressCoder, - // #ifdef _ST_MODE - public ICompressSetInStream, - public ISequentialInStream, - public ICompressSetOutStream, - public ISequentialOutStream, - public IOutStreamFlush, - // #endif - - #ifndef _NO_CRYPTO - public ICryptoSetPassword, - #endif - #ifndef EXTRACT_ONLY - public ICompressSetCoderProperties, - public ICompressWriteCoderProperties, - // public ICryptoResetSalt, - public ICryptoResetInitVector, - #endif - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ -protected: - Byte *_buffer; - // #ifdef _ST_MODE - CMyComPtr _inStream; - CMyComPtr _outStream; - UInt32 _bufferPos; - UInt32 _convertedPosBegin; - UInt32 _convertedPosEnd; - // #endif - bool _outSizeIsDefined; - UInt64 _outSize; - UInt64 _nowPos64; - - HRESULT Init() - { - _nowPos64 = 0; - _outSizeIsDefined = false; - return Filter->Init(); - } - - CMyComPtr _setPassword; - #ifndef EXTRACT_ONLY - CMyComPtr _SetCoderProperties; - CMyComPtr _writeCoderProperties; - // CMyComPtr _CryptoResetSalt; - CMyComPtr _CryptoResetInitVector; - #endif - CMyComPtr _setDecoderProperties; -public: - CMyComPtr Filter; - - CFilterCoder(); - ~CFilterCoder(); - HRESULT WriteWithLimit(ISequentialOutStream *outStream, UInt32 size); - bool NeedMore() const - { return (!_outSizeIsDefined || (_nowPos64 < _outSize)); } - -public: - MY_QUERYINTERFACE_BEGIN - MY_QUERYINTERFACE_ENTRY(ICompressCoder) - // #ifdef _ST_MODE - MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) - MY_QUERYINTERFACE_ENTRY(ISequentialInStream) - - MY_QUERYINTERFACE_ENTRY(ICompressSetOutStream) - MY_QUERYINTERFACE_ENTRY(ISequentialOutStream) - MY_QUERYINTERFACE_ENTRY(IOutStreamFlush) - // #endif - - #ifndef _NO_CRYPTO - MY_QUERYINTERFACE_ENTRY_AG(ICryptoSetPassword, Filter, _setPassword) - #endif - - #ifndef EXTRACT_ONLY - MY_QUERYINTERFACE_ENTRY_AG(ICompressSetCoderProperties, Filter, _SetCoderProperties) - MY_QUERYINTERFACE_ENTRY_AG(ICompressWriteCoderProperties, Filter, _writeCoderProperties) - // MY_QUERYINTERFACE_ENTRY_AG(ICryptoResetSalt, Filter, _CryptoResetSalt) - MY_QUERYINTERFACE_ENTRY_AG(ICryptoResetInitVector, Filter, _CryptoResetInitVector) - #endif - - MY_QUERYINTERFACE_ENTRY_AG(ICompressSetDecoderProperties2, Filter, _setDecoderProperties) - MY_QUERYINTERFACE_END - MY_ADDREF_RELEASE - STDMETHOD(Code)(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, - ICompressProgressInfo *progress); - // #ifdef _ST_MODE - STDMETHOD(ReleaseInStream)(); - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); \ - STDMETHOD(SetOutStream)(ISequentialOutStream *outStream); - STDMETHOD(ReleaseOutStream)(); - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Flush)(); - // #endif - - #ifndef _NO_CRYPTO - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - #endif - #ifndef EXTRACT_ONLY - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, - const PROPVARIANT *properties, UInt32 numProperties); - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); - // STDMETHOD(ResetSalt)(); - STDMETHOD(ResetInitVector)(); - #endif - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); -}; - -// #ifdef _ST_MODE -class CInStreamReleaser -{ -public: - CFilterCoder *FilterCoder; - CInStreamReleaser(): FilterCoder(0) {} - ~CInStreamReleaser() { if (FilterCoder) FilterCoder->ReleaseInStream(); } -}; - -class COutStreamReleaser -{ -public: - CFilterCoder *FilterCoder; - COutStreamReleaser(): FilterCoder(0) {} - ~COutStreamReleaser() { if (FilterCoder) FilterCoder->ReleaseOutStream(); } -}; -// #endif - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.cpp b/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.cpp deleted file mode 100644 index 7e061156a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.cpp +++ /dev/null @@ -1,83 +0,0 @@ -// InBuffer.cpp - -#include "StdAfx.h" - -#include "InBuffer.h" - -extern "C" -{ - #include "../../../C/Alloc.h" -} - -CInBuffer::CInBuffer(): - _buffer(0), - _bufferLimit(0), - _bufferBase(0), - _stream(0), - _bufferSize(0) -{} - -bool CInBuffer::Create(UInt32 bufferSize) -{ - const UInt32 kMinBlockSize = 1; - if (bufferSize < kMinBlockSize) - bufferSize = kMinBlockSize; - if (_bufferBase != 0 && _bufferSize == bufferSize) - return true; - Free(); - _bufferSize = bufferSize; - _bufferBase = (Byte *)::MidAlloc(bufferSize); - return (_bufferBase != 0); -} - -void CInBuffer::Free() -{ - ::MidFree(_bufferBase); - _bufferBase = 0; -} - -void CInBuffer::SetStream(ISequentialInStream *stream) -{ - _stream = stream; -} - -void CInBuffer::Init() -{ - _processedSize = 0; - _buffer = _bufferBase; - _bufferLimit = _buffer; - _wasFinished = false; - #ifdef _NO_EXCEPTIONS - ErrorCode = S_OK; - #endif -} - -bool CInBuffer::ReadBlock() -{ - #ifdef _NO_EXCEPTIONS - if (ErrorCode != S_OK) - return false; - #endif - if (_wasFinished) - return false; - _processedSize += (_buffer - _bufferBase); - UInt32 numProcessedBytes; - HRESULT result = _stream->Read(_bufferBase, _bufferSize, &numProcessedBytes); - #ifdef _NO_EXCEPTIONS - ErrorCode = result; - #else - if (result != S_OK) - throw CInBufferException(result); - #endif - _buffer = _bufferBase; - _bufferLimit = _buffer + numProcessedBytes; - _wasFinished = (numProcessedBytes == 0); - return (!_wasFinished); -} - -Byte CInBuffer::ReadBlock2() -{ - if(!ReadBlock()) - return 0xFF; - return *_buffer++; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.h b/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.h deleted file mode 100644 index cdd50f1b2..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/InBuffer.h +++ /dev/null @@ -1,81 +0,0 @@ -// InBuffer.h - -#ifndef __INBUFFER_H -#define __INBUFFER_H - -#include "../IStream.h" -#include "../../Common/MyCom.h" -#include "../../Common/MyException.h" - -#ifndef _NO_EXCEPTIONS -struct CInBufferException: public CSystemException -{ - CInBufferException(HRESULT errorCode): CSystemException(errorCode) {} -}; -#endif - -class CInBuffer -{ - Byte *_buffer; - Byte *_bufferLimit; - Byte *_bufferBase; - CMyComPtr _stream; - UInt64 _processedSize; - UInt32 _bufferSize; - bool _wasFinished; - - bool ReadBlock(); - Byte ReadBlock2(); - -public: - #ifdef _NO_EXCEPTIONS - HRESULT ErrorCode; - #endif - - CInBuffer(); - ~CInBuffer() { Free(); } - - bool Create(UInt32 bufferSize); - void Free(); - - void SetStream(ISequentialInStream *stream); - void Init(); - void ReleaseStream() { _stream.Release(); } - - bool ReadByte(Byte &b) - { - if (_buffer >= _bufferLimit) - if (!ReadBlock()) - return false; - b = *_buffer++; - return true; - } - Byte ReadByte() - { - if (_buffer >= _bufferLimit) - return ReadBlock2(); - return *_buffer++; - } - UInt32 ReadBytes(Byte *buf, UInt32 size) - { - if ((UInt32)(_bufferLimit - _buffer) >= size) - { - for (UInt32 i = 0; i < size; i++) - buf[i] = _buffer[i]; - _buffer += size; - return size; - } - for (UInt32 i = 0; i < size; i++) - { - if (_buffer >= _bufferLimit) - if (!ReadBlock()) - return i; - buf[i] = *_buffer++; - } - return size; - } - UInt64 GetProcessedSize() const { return _processedSize + (_buffer - _bufferBase); } - bool WasFinished() const { return _wasFinished; } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.cpp b/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.cpp deleted file mode 100644 index 79c04c109..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.cpp +++ /dev/null @@ -1,122 +0,0 @@ -// InOutTempBuffer.cpp - -#include "StdAfx.h" - -#include "InOutTempBuffer.h" -#include "../../Common/Defs.h" -// #include "Windows/Defs.h" - -#include "StreamUtils.h" - -using namespace NWindows; -using namespace NFile; -using namespace NDirectory; - -static UInt32 kTmpBufferMemorySize = (1 << 20); - -static LPCTSTR kTempFilePrefixString = TEXT("iot"); - -CInOutTempBuffer::CInOutTempBuffer(): - _buffer(NULL) -{ -} - -void CInOutTempBuffer::Create() -{ - _buffer = new Byte[kTmpBufferMemorySize]; -} - -CInOutTempBuffer::~CInOutTempBuffer() -{ - delete []_buffer; -} -void CInOutTempBuffer::InitWriting() -{ - _bufferPosition = 0; - _tmpFileCreated = false; - _fileSize = 0; -} - -bool CInOutTempBuffer::WriteToFile(const void *data, UInt32 size) -{ - if (size == 0) - return true; - if(!_tmpFileCreated) - { - CSysString tempDirPath; - if(!MyGetTempPath(tempDirPath)) - return false; - if (_tempFile.Create(tempDirPath, kTempFilePrefixString, _tmpFileName) == 0) - return false; - // _outFile.SetOpenCreationDispositionCreateAlways(); - if(!_outFile.Create(_tmpFileName, true)) - return false; - _tmpFileCreated = true; - } - UInt32 processedSize; - if(!_outFile.Write(data, size, processedSize)) - return false; - _fileSize += processedSize; - return (processedSize == size); -} - -bool CInOutTempBuffer::FlushWrite() -{ - return _outFile.Close(); -} - -bool CInOutTempBuffer::Write(const void *data, UInt32 size) -{ - if(_bufferPosition < kTmpBufferMemorySize) - { - UInt32 curSize = MyMin(kTmpBufferMemorySize - _bufferPosition, size); - memmove(_buffer + _bufferPosition, (const Byte *)data, curSize); - _bufferPosition += curSize; - size -= curSize; - data = ((const Byte *)data) + curSize; - _fileSize += curSize; - } - return WriteToFile(data, size); -} - -bool CInOutTempBuffer::InitReading() -{ - _currentPositionInBuffer = 0; - if(_tmpFileCreated) - return _inFile.Open(_tmpFileName); - return true; -} - -HRESULT CInOutTempBuffer::WriteToStream(ISequentialOutStream *stream) -{ - if (_currentPositionInBuffer < _bufferPosition) - { - UInt32 sizeToWrite = _bufferPosition - _currentPositionInBuffer; - RINOK(WriteStream(stream, _buffer + _currentPositionInBuffer, sizeToWrite)); - _currentPositionInBuffer += sizeToWrite; - } - if (!_tmpFileCreated) - return true; - for (;;) - { - UInt32 localProcessedSize; - if (!_inFile.ReadPart(_buffer, kTmpBufferMemorySize, localProcessedSize)) - return E_FAIL; - if (localProcessedSize == 0) - return S_OK; - RINOK(WriteStream(stream, _buffer, localProcessedSize)); - } -} - -STDMETHODIMP CSequentialOutTempBufferImp::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - if (!_buffer->Write(data, size)) - { - if (processedSize != NULL) - *processedSize = 0; - return E_FAIL; - } - if (processedSize != NULL) - *processedSize = size; - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.h b/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.h deleted file mode 100644 index 1ccf1153f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/InOutTempBuffer.h +++ /dev/null @@ -1,55 +0,0 @@ -// Util/InOutTempBuffer.h - -#ifndef __IN_OUT_TEMP_BUFFER_H -#define __IN_OUT_TEMP_BUFFER_H - -#include "../../Windows/FileIO.h" -#include "../../Windows/FileDir.h" -#include "../../Common/MyCom.h" - -#include "../IStream.h" - -class CInOutTempBuffer -{ - NWindows::NFile::NDirectory::CTempFile _tempFile; - NWindows::NFile::NIO::COutFile _outFile; - NWindows::NFile::NIO::CInFile _inFile; - Byte *_buffer; - UInt32 _bufferPosition; - UInt32 _currentPositionInBuffer; - CSysString _tmpFileName; - bool _tmpFileCreated; - - UInt64 _fileSize; - - bool WriteToFile(const void *data, UInt32 size); -public: - CInOutTempBuffer(); - ~CInOutTempBuffer(); - void Create(); - - void InitWriting(); - bool Write(const void *data, UInt32 size); - UInt64 GetDataSize() const { return _fileSize; } - bool FlushWrite(); - bool InitReading(); - HRESULT WriteToStream(ISequentialOutStream *stream); -}; - -class CSequentialOutTempBufferImp: - public ISequentialOutStream, - public CMyUnknownImp -{ - CInOutTempBuffer *_buffer; -public: - // CSequentialOutStreamImp(): _size(0) {} - // UInt32 _size; - void Init(CInOutTempBuffer *buffer) { _buffer = buffer; } - // UInt32 GetSize() const { return _size; } - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.cpp b/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.cpp deleted file mode 100644 index 0a1bfa38e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.cpp +++ /dev/null @@ -1,45 +0,0 @@ -// LimitedStreams.cpp - -#include "StdAfx.h" - -#include "LimitedStreams.h" -#include "../../Common/Defs.h" - -STDMETHODIMP CLimitedSequentialInStream::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize = 0; - UInt32 sizeToRead = (UInt32)MyMin((_size - _pos), (UInt64)size); - HRESULT result = S_OK; - if (sizeToRead > 0) - { - result = _stream->Read(data, sizeToRead, &realProcessedSize); - _pos += realProcessedSize; - if (realProcessedSize == 0) - _wasFinished = true; - } - if(processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} - -STDMETHODIMP CLimitedSequentialOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - HRESULT result = S_OK; - if (processedSize != NULL) - *processedSize = 0; - if (size > _size) - { - size = (UInt32)_size; - if (size == 0) - { - _overflow = true; - return E_FAIL; - } - } - if (_stream) - result = _stream->Write(data, size, &size); - _size -= size; - if (processedSize != NULL) - *processedSize = size; - return result; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.h b/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.h deleted file mode 100644 index 7e0e1c126..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/LimitedStreams.h +++ /dev/null @@ -1,54 +0,0 @@ -// LimitedStreams.h - -#ifndef __LIMITEDSTREAMS_H -#define __LIMITEDSTREAMS_H - -#include "../../Common/MyCom.h" -#include "../IStream.h" - -class CLimitedSequentialInStream: - public ISequentialInStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; - UInt64 _pos; - bool _wasFinished; -public: - void SetStream(ISequentialInStream *stream) { _stream = stream; } - void Init(UInt64 streamSize) - { - _size = streamSize; - _pos = 0; - _wasFinished = false; - } - - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - UInt64 GetSize() const { return _pos; } - bool WasFinished() const { return _wasFinished; } -}; - -class CLimitedSequentialOutStream: - public ISequentialOutStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; - bool _overflow; -public: - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - void SetStream(ISequentialOutStream *stream) { _stream = stream; } - void ReleaseStream() { _stream.Release(); } - void Init(UInt64 size) - { - _size = size; - _overflow = false; - } - bool IsFinishedOK() const { return (_size == 0 && !_overflow); } - UInt64 GetRem() const { return _size; } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.cpp b/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.cpp deleted file mode 100644 index d1bbf6dba..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// LockedStream.cpp - -#include "StdAfx.h" - -#include "LockedStream.h" - -HRESULT CLockedInStream::Read(UInt64 startPos, void *data, UInt32 size, - UInt32 *processedSize) -{ - NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection); - RINOK(_stream->Seek(startPos, STREAM_SEEK_SET, NULL)); - return _stream->Read(data, size, processedSize); -} - -STDMETHODIMP CLockedSequentialInStreamImp::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize = 0; - HRESULT result = _lockedInStream->Read(_pos, data, size, &realProcessedSize); - _pos += realProcessedSize; - if (processedSize != NULL) - *processedSize = realProcessedSize; - return result; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.h b/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.h deleted file mode 100644 index e12e22a4a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/LockedStream.h +++ /dev/null @@ -1,38 +0,0 @@ -// LockedStream.h - -#ifndef __LOCKEDSTREAM_H -#define __LOCKEDSTREAM_H - -#include "../../Windows/Synchronization.h" -#include "../../Common/MyCom.h" -#include "../IStream.h" - -class CLockedInStream -{ - CMyComPtr _stream; - NWindows::NSynchronization::CCriticalSection _criticalSection; -public: - void Init(IInStream *stream) - { _stream = stream; } - HRESULT Read(UInt64 startPos, void *data, UInt32 size, UInt32 *processedSize); -}; - -class CLockedSequentialInStreamImp: - public ISequentialInStream, - public CMyUnknownImp -{ - CLockedInStream *_lockedInStream; - UInt64 _pos; -public: - void Init(CLockedInStream *lockedInStream, UInt64 startPos) - { - _lockedInStream = lockedInStream; - _pos = startPos; - } - - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.cpp b/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.cpp deleted file mode 100644 index 923c2e775..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.cpp +++ /dev/null @@ -1,183 +0,0 @@ -// MemBlocks.cpp - -#include "StdAfx.h" - -#include "Common/MyCom.h" - -#include "StreamUtils.h" -#include "MemBlocks.h" - -bool CMemBlockManager::AllocateSpace(size_t numBlocks) -{ - FreeSpace(); - if (_blockSize < sizeof(void *) || numBlocks < 1) - return false; - size_t totalSize = numBlocks * _blockSize; - if (totalSize / _blockSize != numBlocks) - return false; - _data = ::MidAlloc(totalSize); - if (_data == 0) - return false; - Byte *p = (Byte *)_data; - for (size_t i = 0; i + 1 < numBlocks; i++, p += _blockSize) - *(Byte **)p = (p + _blockSize); - *(Byte **)p = 0; - _headFree = _data; - return true; -} - -void CMemBlockManager::FreeSpace() -{ - ::MidFree(_data); - _data = 0; - _headFree= 0; -} - -void *CMemBlockManager::AllocateBlock() -{ - if (_headFree == 0) - return 0; - void *p = _headFree; - _headFree = *(void **)_headFree; - return p; -} - -void CMemBlockManager::FreeBlock(void *p) -{ - if (p == 0) - return; - *(void **)p = _headFree; - _headFree = p; -} - - -HRes CMemBlockManagerMt::AllocateSpace(size_t numBlocks, size_t numNoLockBlocks) -{ - if (numNoLockBlocks > numBlocks) - return E_INVALIDARG; - if (!CMemBlockManager::AllocateSpace(numBlocks)) - return E_OUTOFMEMORY; - size_t numLockBlocks = numBlocks - numNoLockBlocks; - Semaphore.Close(); - return Semaphore.Create((LONG)numLockBlocks, (LONG)numLockBlocks); -} - -HRes CMemBlockManagerMt::AllocateSpaceAlways(size_t desiredNumberOfBlocks, size_t numNoLockBlocks) -{ - if (numNoLockBlocks > desiredNumberOfBlocks) - return E_INVALIDARG; - for (;;) - { - if (AllocateSpace(desiredNumberOfBlocks, numNoLockBlocks) == 0) - return 0; - if (desiredNumberOfBlocks == numNoLockBlocks) - return E_OUTOFMEMORY; - desiredNumberOfBlocks = numNoLockBlocks + ((desiredNumberOfBlocks - numNoLockBlocks) >> 1); - } -} - -void CMemBlockManagerMt::FreeSpace() -{ - Semaphore.Close(); - CMemBlockManager::FreeSpace(); -} - -void *CMemBlockManagerMt::AllocateBlock() -{ - // Semaphore.Lock(); - NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection); - return CMemBlockManager::AllocateBlock(); -} - -void CMemBlockManagerMt::FreeBlock(void *p, bool lockMode) -{ - if (p == 0) - return; - { - NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection); - CMemBlockManager::FreeBlock(p); - } - if (lockMode) - Semaphore.Release(); -} - -void CMemBlocks::Free(CMemBlockManagerMt *manager) -{ - while(Blocks.Size() > 0) - { - manager->FreeBlock(Blocks.Back()); - Blocks.DeleteBack(); - } - TotalSize = 0; -} - -void CMemBlocks::FreeOpt(CMemBlockManagerMt *manager) -{ - Free(manager); - Blocks.ClearAndFree(); -} - -HRESULT CMemBlocks::WriteToStream(size_t blockSize, ISequentialOutStream *outStream) const -{ - UInt64 totalSize = TotalSize; - for (int blockIndex = 0; totalSize > 0; blockIndex++) - { - UInt32 curSize = (UInt32)blockSize; - if (totalSize < curSize) - curSize = (UInt32)totalSize; - if (blockIndex >= Blocks.Size()) - return E_FAIL; - RINOK(WriteStream(outStream, Blocks[blockIndex], curSize)); - totalSize -= curSize; - } - return S_OK; -} - - -void CMemLockBlocks::FreeBlock(int index, CMemBlockManagerMt *memManager) -{ - memManager->FreeBlock(Blocks[index], LockMode); - Blocks[index] = 0; -} - -void CMemLockBlocks::Free(CMemBlockManagerMt *memManager) -{ - while (Blocks.Size() > 0) - { - FreeBlock(Blocks.Size() - 1, memManager); - Blocks.DeleteBack(); - } - TotalSize = 0; -} - -HRes CMemLockBlocks::SwitchToNoLockMode(CMemBlockManagerMt *memManager) -{ - if (LockMode) - { - if (Blocks.Size() > 0) - { - RINOK(memManager->ReleaseLockedBlocks(Blocks.Size())); - } - LockMode = false; - } - return 0; -} - -void CMemLockBlocks::Detach(CMemLockBlocks &blocks, CMemBlockManagerMt *memManager) -{ - blocks.Free(memManager); - blocks.LockMode = LockMode; - UInt64 totalSize = 0; - size_t blockSize = memManager->GetBlockSize(); - for (int i = 0; i < Blocks.Size(); i++) - { - if (totalSize < TotalSize) - blocks.Blocks.Add(Blocks[i]); - else - FreeBlock(i, memManager); - Blocks[i] = 0; - totalSize += blockSize; - } - blocks.TotalSize = TotalSize; - Free(memManager); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.h b/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.h deleted file mode 100644 index 4b20a1c4a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MemBlocks.h +++ /dev/null @@ -1,77 +0,0 @@ -// MemBlocks.h - -#ifndef __MEMBLOCKS_H -#define __MEMBLOCKS_H - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "Common/Types.h" -#include "Common/MyVector.h" - -#include "Windows/Synchronization.h" - -#include "../IStream.h" - -class CMemBlockManager -{ - void *_data; - size_t _blockSize; - void *_headFree; -public: - CMemBlockManager(size_t blockSize = (1 << 20)): _data(0), _blockSize(blockSize), _headFree(0) {} - ~CMemBlockManager() { FreeSpace(); } - - bool AllocateSpace(size_t numBlocks); - void FreeSpace(); - size_t GetBlockSize() const { return _blockSize; } - void *AllocateBlock(); - void FreeBlock(void *p); -}; - - -class CMemBlockManagerMt: public CMemBlockManager -{ - NWindows::NSynchronization::CCriticalSection _criticalSection; -public: - NWindows::NSynchronization::CSemaphore Semaphore; - - CMemBlockManagerMt(size_t blockSize = (1 << 20)): CMemBlockManager(blockSize) {} - ~CMemBlockManagerMt() { FreeSpace(); } - - HRes AllocateSpace(size_t numBlocks, size_t numNoLockBlocks = 0); - HRes AllocateSpaceAlways(size_t desiredNumberOfBlocks, size_t numNoLockBlocks = 0); - void FreeSpace(); - void *AllocateBlock(); - void FreeBlock(void *p, bool lockMode = true); - HRes ReleaseLockedBlocks(int number) { return Semaphore.Release(number); } -}; - - -class CMemBlocks -{ - void Free(CMemBlockManagerMt *manager); -public: - CRecordVector Blocks; - UInt64 TotalSize; - - CMemBlocks(): TotalSize(0) {} - - void FreeOpt(CMemBlockManagerMt *manager); - HRESULT WriteToStream(size_t blockSize, ISequentialOutStream *outStream) const; -}; - -struct CMemLockBlocks: public CMemBlocks -{ - bool LockMode; - - CMemLockBlocks(): LockMode(true) {}; - void Free(CMemBlockManagerMt *memManager); - void FreeBlock(int index, CMemBlockManagerMt *memManager); - HRes SwitchToNoLockMode(CMemBlockManagerMt *memManager); - void Detach(CMemLockBlocks &blocks, CMemBlockManagerMt *memManager); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MethodId.cpp b/desmume/src/windows/7z/CPP/7zip/Common/MethodId.cpp deleted file mode 100644 index 705cc4d9b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MethodId.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// MethodId.cpp - -#include "StdAfx.h" - -#include "MethodId.h" -#include "../../Common/MyString.h" - -static inline wchar_t GetHex(Byte value) -{ - return (wchar_t)((value < 10) ? ('0' + value) : ('A' + (value - 10))); -} - -UString ConvertMethodIdToString(UInt64 id) -{ - wchar_t s[32]; - int len = 32; - s[--len] = 0; - do - { - s[--len] = GetHex((Byte)id & 0xF); - id >>= 4; - s[--len] = GetHex((Byte)id & 0xF); - id >>= 4; - } - while (id != 0); - return s + len; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MethodId.h b/desmume/src/windows/7z/CPP/7zip/Common/MethodId.h deleted file mode 100644 index 955172354..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MethodId.h +++ /dev/null @@ -1,10 +0,0 @@ -// MethodId.h - -#ifndef __7Z_METHOD_ID_H -#define __7Z_METHOD_ID_H - -#include "../../Common/Types.h" - -typedef UInt64 CMethodId; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.cpp b/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.cpp deleted file mode 100644 index d917a2c23..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.cpp +++ /dev/null @@ -1,99 +0,0 @@ -// MethodProps.cpp - -#include "StdAfx.h" - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "MethodProps.h" - -static UInt64 k_LZMA = 0x030101; -// static UInt64 k_LZMA2 = 0x030102; - -HRESULT SetMethodProperties(const CMethod &method, const UInt64 *inSizeForReduce, IUnknown *coder) -{ - bool tryReduce = false; - UInt32 reducedDictionarySize = 1 << 10; - if (inSizeForReduce != 0 && (method.Id == k_LZMA /* || methodFull.MethodID == k_LZMA2 */)) - { - for (;;) - { - const UInt32 step = (reducedDictionarySize >> 1); - if (reducedDictionarySize >= *inSizeForReduce) - { - tryReduce = true; - break; - } - reducedDictionarySize += step; - if (reducedDictionarySize >= *inSizeForReduce) - { - tryReduce = true; - break; - } - if (reducedDictionarySize >= ((UInt32)3 << 30)) - break; - reducedDictionarySize += step; - } - } - - { - int numProps = method.Props.Size(); - CMyComPtr setCoderProperties; - coder->QueryInterface(IID_ICompressSetCoderProperties, (void **)&setCoderProperties); - if (setCoderProperties == NULL) - { - if (numProps != 0) - return E_INVALIDARG; - } - else - { - CRecordVector propIDs; - NWindows::NCOM::CPropVariant *values = new NWindows::NCOM::CPropVariant[numProps]; - HRESULT res = S_OK; - try - { - for (int i = 0; i < numProps; i++) - { - const CProp &prop = method.Props[i]; - propIDs.Add(prop.Id); - NWindows::NCOM::CPropVariant &value = values[i]; - value = prop.Value; - // if (tryReduce && prop.Id == NCoderPropID::kDictionarySize && value.vt == VT_UI4 && reducedDictionarySize < value.ulVal) - if (tryReduce) - if (prop.Id == NCoderPropID::kDictionarySize) - if (value.vt == VT_UI4) - if (reducedDictionarySize < value.ulVal) - value.ulVal = reducedDictionarySize; - } - CMyComPtr setCoderProperties; - coder->QueryInterface(IID_ICompressSetCoderProperties, (void **)&setCoderProperties); - res = setCoderProperties->SetCoderProperties(&propIDs.Front(), values, numProps); - } - catch(...) - { - delete []values; - throw; - } - delete []values; - RINOK(res); - } - } - - /* - CMyComPtr writeCoderProperties; - coder->QueryInterface(IID_ICompressWriteCoderProperties, (void **)&writeCoderProperties); - if (writeCoderProperties != NULL) - { - CSequentialOutStreamImp *outStreamSpec = new CSequentialOutStreamImp; - CMyComPtr outStream(outStreamSpec); - outStreamSpec->Init(); - RINOK(writeCoderProperties->WriteCoderProperties(outStream)); - size_t size = outStreamSpec->GetSize(); - filterProps.SetCapacity(size); - memmove(filterProps, outStreamSpec->GetBuffer(), size); - } - */ - return S_OK; -} - diff --git a/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.h b/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.h deleted file mode 100644 index e27f09574..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/MethodProps.h +++ /dev/null @@ -1,41 +0,0 @@ -// MethodProps.h - -#ifndef __7Z_METHOD_PROPS_H -#define __7Z_METHOD_PROPS_H - -#include "../../Common/MyVector.h" - -#include "../../Windows/PropVariant.h" - -#include "MethodId.h" - -struct CProp -{ - PROPID Id; - NWindows::NCOM::CPropVariant Value; -}; - -struct CMethod -{ - CMethodId Id; - CObjectVector Props; -}; - -struct CMethodsMode -{ - CObjectVector Methods; - #ifdef COMPRESS_MT - UInt32 NumThreads; - #endif - - CMethodsMode() - #ifdef COMPRESS_MT - : NumThreads(1) - #endif - {} - bool IsEmpty() const { return Methods.IsEmpty() ; } -}; - -HRESULT SetMethodProperties(const CMethod &method, const UInt64 *inSizeForReduce, IUnknown *coder); - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.cpp b/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.cpp deleted file mode 100644 index d37657949..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// OffsetStream.cpp - -#include "StdAfx.h" - -#include "Common/Defs.h" -#include "OffsetStream.h" - -HRESULT COffsetOutStream::Init(IOutStream *stream, UInt64 offset) -{ - _offset = offset; - _stream = stream; - return _stream->Seek(offset, STREAM_SEEK_SET, NULL); -} - -STDMETHODIMP COffsetOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - return _stream->Write(data, size, processedSize); -} - -STDMETHODIMP COffsetOutStream::Seek(Int64 offset, UInt32 seekOrigin, - UInt64 *newPosition) -{ - UInt64 absoluteNewPosition; - if (seekOrigin == STREAM_SEEK_SET) - offset += _offset; - HRESULT result = _stream->Seek(offset, seekOrigin, &absoluteNewPosition); - if (newPosition != NULL) - *newPosition = absoluteNewPosition - _offset; - return result; -} - -STDMETHODIMP COffsetOutStream::SetSize(Int64 newSize) -{ - return _stream->SetSize(_offset + newSize); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.h b/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.h deleted file mode 100644 index 15846b24a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OffsetStream.h +++ /dev/null @@ -1,25 +0,0 @@ -// OffsetStream.h - -#ifndef __OFFSETSTREAM_H -#define __OFFSETSTREAM_H - -#include "Common/MyCom.h" -#include "../IStream.h" - -class COffsetOutStream: - public IOutStream, - public CMyUnknownImp -{ - UInt64 _offset; - CMyComPtr _stream; -public: - HRESULT Init(IOutStream *stream, UInt64 offset); - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - STDMETHOD(SetSize)(Int64 newSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.cpp b/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.cpp deleted file mode 100644 index 238320fe4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.cpp +++ /dev/null @@ -1,119 +0,0 @@ -// OutByte.cpp - -#include "StdAfx.h" - -#include "OutBuffer.h" - -extern "C" -{ - #include "../../../C/Alloc.h" -} - -bool COutBuffer::Create(UInt32 bufferSize) -{ - const UInt32 kMinBlockSize = 1; - if (bufferSize < kMinBlockSize) - bufferSize = kMinBlockSize; - if (_buffer != 0 && _bufferSize == bufferSize) - return true; - Free(); - _bufferSize = bufferSize; - _buffer = (Byte *)::MidAlloc(bufferSize); - return (_buffer != 0); -} - -void COutBuffer::Free() -{ - ::MidFree(_buffer); - _buffer = 0; -} - -void COutBuffer::SetStream(ISequentialOutStream *stream) -{ - _stream = stream; -} - -void COutBuffer::Init() -{ - _streamPos = 0; - _limitPos = _bufferSize; - _pos = 0; - _processedSize = 0; - _overDict = false; - #ifdef _NO_EXCEPTIONS - ErrorCode = S_OK; - #endif -} - -UInt64 COutBuffer::GetProcessedSize() const -{ - UInt64 res = _processedSize + _pos - _streamPos; - if (_streamPos > _pos) - res += _bufferSize; - return res; -} - - -HRESULT COutBuffer::FlushPart() -{ - // _streamPos < _bufferSize - UInt32 size = (_streamPos >= _pos) ? (_bufferSize - _streamPos) : (_pos - _streamPos); - HRESULT result = S_OK; - #ifdef _NO_EXCEPTIONS - result = ErrorCode; - #endif - if (_buffer2 != 0) - { - memmove(_buffer2, _buffer + _streamPos, size); - _buffer2 += size; - } - - if (_stream != 0 - #ifdef _NO_EXCEPTIONS - && (ErrorCode == S_OK) - #endif - ) - { - UInt32 processedSize = 0; - result = _stream->Write(_buffer + _streamPos, size, &processedSize); - size = processedSize; - } - _streamPos += size; - if (_streamPos == _bufferSize) - _streamPos = 0; - if (_pos == _bufferSize) - { - _overDict = true; - _pos = 0; - } - _limitPos = (_streamPos > _pos) ? _streamPos : _bufferSize; - _processedSize += size; - return result; -} - -HRESULT COutBuffer::Flush() -{ - #ifdef _NO_EXCEPTIONS - if (ErrorCode != S_OK) - return ErrorCode; - #endif - - while(_streamPos != _pos) - { - HRESULT result = FlushPart(); - if (result != S_OK) - return result; - } - return S_OK; -} - -void COutBuffer::FlushWithCheck() -{ - HRESULT result = Flush(); - #ifdef _NO_EXCEPTIONS - ErrorCode = result; - #else - if (result != S_OK) - throw COutBufferException(result); - #endif -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.h b/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.h deleted file mode 100644 index e2e76ad58..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OutBuffer.h +++ /dev/null @@ -1,64 +0,0 @@ -// OutBuffer.h - -#ifndef __OUTBUFFER_H -#define __OUTBUFFER_H - -#include "../IStream.h" -#include "../../Common/MyCom.h" -#include "../../Common/MyException.h" - -#ifndef _NO_EXCEPTIONS -struct COutBufferException: public CSystemException -{ - COutBufferException(HRESULT errorCode): CSystemException(errorCode) {} -}; -#endif - -class COutBuffer -{ -protected: - Byte *_buffer; - UInt32 _pos; - UInt32 _limitPos; - UInt32 _streamPos; - UInt32 _bufferSize; - CMyComPtr _stream; - UInt64 _processedSize; - Byte *_buffer2; - bool _overDict; - - HRESULT FlushPart(); -public: - #ifdef _NO_EXCEPTIONS - HRESULT ErrorCode; - #endif - - COutBuffer(): _buffer(0), _pos(0), _stream(0), _buffer2(0) {} - ~COutBuffer() { Free(); } - - bool Create(UInt32 bufferSize); - void Free(); - - void SetMemStream(Byte *buffer) { _buffer2 = buffer; } - void SetStream(ISequentialOutStream *stream); - void Init(); - HRESULT Flush(); - void FlushWithCheck(); - void ReleaseStream() { _stream.Release(); } - - void WriteByte(Byte b) - { - _buffer[_pos++] = b; - if(_pos == _limitPos) - FlushWithCheck(); - } - void WriteBytes(const void *data, size_t size) - { - for (size_t i = 0; i < size; i++) - WriteByte(((const Byte *)data)[i]); - } - - UInt64 GetProcessedSize() const; -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.cpp b/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.cpp deleted file mode 100644 index f0208eaaf..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.cpp +++ /dev/null @@ -1,142 +0,0 @@ -// OutMemStream.cpp - -#include "StdAfx.h" - -#include "OutMemStream.h" - -void COutMemStream::Free() -{ - Blocks.Free(_memManager); - Blocks.LockMode = true; -} - -void COutMemStream::Init() -{ - WriteToRealStreamEvent.Reset(); - _unlockEventWasSent = false; - _realStreamMode = false; - Free(); - _curBlockPos = 0; - _curBlockIndex = 0; -} - -void COutMemStream::DetachData(CMemLockBlocks &blocks) -{ - Blocks.Detach(blocks, _memManager); - Free(); -} - - -HRESULT COutMemStream::WriteToRealStream() -{ - RINOK(Blocks.WriteToStream(_memManager->GetBlockSize(), OutSeqStream)); - Blocks.Free(_memManager); - return S_OK; -} - -STDMETHODIMP COutMemStream::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - if (_realStreamMode) - return OutSeqStream->Write(data, size, processedSize); - if (processedSize != 0) - *processedSize = 0; - while(size != 0) - { - if ((int)_curBlockIndex < Blocks.Blocks.Size()) - { - Byte *p = (Byte *)Blocks.Blocks[(int)_curBlockIndex] + _curBlockPos; - size_t curSize = _memManager->GetBlockSize() - _curBlockPos; - if (size < curSize) - curSize = size; - memmove(p, data, curSize); - if (processedSize != 0) - *processedSize += (UInt32)curSize; - data = (const void *)((const Byte *)data + curSize); - size -= (UInt32)curSize; - _curBlockPos += curSize; - - UInt64 pos64 = GetPos(); - if (pos64 > Blocks.TotalSize) - Blocks.TotalSize = pos64; - if (_curBlockPos == _memManager->GetBlockSize()) - { - _curBlockIndex++; - _curBlockPos = 0; - } - continue; - } - HANDLE events[3] = { StopWritingEvent, WriteToRealStreamEvent, /* NoLockEvent, */ _memManager->Semaphore }; - DWORD waitResult = ::WaitForMultipleObjects((Blocks.LockMode ? 3 : 2), events, FALSE, INFINITE); - switch (waitResult) - { - case (WAIT_OBJECT_0 + 0): - return StopWriteResult; - case (WAIT_OBJECT_0 + 1): - { - _realStreamMode = true; - RINOK(WriteToRealStream()); - UInt32 processedSize2; - HRESULT res = OutSeqStream->Write(data, size, &processedSize2); - if (processedSize != 0) - *processedSize += processedSize2; - return res; - } - /* - case (WAIT_OBJECT_0 + 2): - { - // it has bug: no write. - if (!Blocks.SwitchToNoLockMode(_memManager)) - return E_FAIL; - break; - } - */ - case (WAIT_OBJECT_0 + 2): - break; - default: - return E_FAIL; - } - Blocks.Blocks.Add(_memManager->AllocateBlock()); - if (Blocks.Blocks.Back() == 0) - return E_FAIL; - } - return S_OK; -} - -STDMETHODIMP COutMemStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) -{ - if (_realStreamMode) - { - if (!OutStream) - return E_FAIL; - return OutStream->Seek(offset, seekOrigin, newPosition); - } - if (seekOrigin == STREAM_SEEK_CUR) - { - if (offset != 0) - return E_NOTIMPL; - } - else if (seekOrigin == STREAM_SEEK_SET) - { - if (offset != 0) - return E_NOTIMPL; - _curBlockIndex = 0; - _curBlockPos = 0; - } - else - return E_NOTIMPL; - if (newPosition != 0) - *newPosition = GetPos(); - return S_OK; -} - -STDMETHODIMP COutMemStream::SetSize(Int64 newSize) -{ - if (_realStreamMode) - { - if (!OutStream) - return E_FAIL; - return OutStream->SetSize(newSize); - } - Blocks.TotalSize = newSize; - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.h b/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.h deleted file mode 100644 index 9a8cac431..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/OutMemStream.h +++ /dev/null @@ -1,96 +0,0 @@ -// OutMemStream.h - -#ifndef __OUTMEMSTREAM_H -#define __OUTMEMSTREAM_H - -#include "Common/MyCom.h" -#include "MemBlocks.h" - -class COutMemStream: - public IOutStream, - public CMyUnknownImp -{ - CMemBlockManagerMt *_memManager; - size_t _curBlockIndex; - size_t _curBlockPos; - bool _realStreamMode; - - bool _unlockEventWasSent; - NWindows::NSynchronization::CAutoResetEvent StopWritingEvent; - NWindows::NSynchronization::CAutoResetEvent WriteToRealStreamEvent; - // NWindows::NSynchronization::CAutoResetEvent NoLockEvent; - - HRESULT StopWriteResult; - CMemLockBlocks Blocks; - - UInt64 GetPos() const { return (UInt64)_curBlockIndex * _memManager->GetBlockSize() + _curBlockPos; } - - CMyComPtr OutSeqStream; - CMyComPtr OutStream; - -public: - - HRes CreateEvents() - { - RINOK(StopWritingEvent.CreateIfNotCreated()); - return WriteToRealStreamEvent.CreateIfNotCreated(); - } - - void SetOutStream(IOutStream *outStream) - { - OutStream = outStream; - OutSeqStream = outStream; - } - - void SetSeqOutStream(ISequentialOutStream *outStream) - { - OutStream = NULL; - OutSeqStream = outStream; - } - - void ReleaseOutStream() - { - OutStream.Release(); - OutSeqStream.Release(); - } - - COutMemStream(CMemBlockManagerMt *memManager): _memManager(memManager) { } - - ~COutMemStream() { Free(); } - void Free(); - - void Init(); - HRESULT WriteToRealStream(); - - void DetachData(CMemLockBlocks &blocks); - - bool WasUnlockEventSent() const { return _unlockEventWasSent; } - - void SetRealStreamMode() - { - _unlockEventWasSent = true; - WriteToRealStreamEvent.Set(); - } - - /* - void SetNoLockMode() - { - _unlockEventWasSent = true; - NoLockEvent.Set(); - } - */ - - void StopWriting(HRESULT res) - { - StopWriteResult = res; - StopWritingEvent.Set(); - } - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition); - STDMETHOD(SetSize)(Int64 newSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.cpp b/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.cpp deleted file mode 100644 index e1e7f38e0..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.cpp +++ /dev/null @@ -1,53 +0,0 @@ -// ProgressMt.h - -#include "StdAfx.h" - -#include "ProgressMt.h" - -void CMtCompressProgressMixer::Init(int numItems, ICompressProgressInfo *progress) -{ - NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); - InSizes.Clear(); - OutSizes.Clear(); - for (int i = 0; i < numItems; i++) - { - InSizes.Add(0); - OutSizes.Add(0); - } - TotalInSize = 0; - TotalOutSize = 0; - _progress = progress; -} - -void CMtCompressProgressMixer::Reinit(int index) -{ - NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); - InSizes[index] = 0; - OutSizes[index] = 0; -} - -HRESULT CMtCompressProgressMixer::SetRatioInfo(int index, const UInt64 *inSize, const UInt64 *outSize) -{ - NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection); - if (inSize != 0) - { - UInt64 diff = *inSize - InSizes[index]; - InSizes[index] = *inSize; - TotalInSize += diff; - } - if (outSize != 0) - { - UInt64 diff = *outSize - OutSizes[index]; - OutSizes[index] = *outSize; - TotalOutSize += diff; - } - if (_progress) - return _progress->SetRatioInfo(&TotalInSize, &TotalOutSize); - return S_OK; -} - - -STDMETHODIMP CMtCompressProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) -{ - return _progress->SetRatioInfo(_index, inSize, outSize); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.h b/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.h deleted file mode 100644 index 4eeb02aa0..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/ProgressMt.h +++ /dev/null @@ -1,46 +0,0 @@ -// ProgressMt.h - -#ifndef __PROGRESSMT_H -#define __PROGRESSMT_H - -#include "../../Common/MyCom.h" -#include "../../Common/MyVector.h" -#include "../../Windows/Synchronization.h" - -#include "../ICoder.h" -#include "../IProgress.h" - -class CMtCompressProgressMixer -{ - CMyComPtr _progress; - CRecordVector InSizes; - CRecordVector OutSizes; - UInt64 TotalInSize; - UInt64 TotalOutSize; -public: - NWindows::NSynchronization::CCriticalSection CriticalSection; - void Init(int numItems, ICompressProgressInfo *progress); - void Reinit(int index); - HRESULT SetRatioInfo(int index, const UInt64 *inSize, const UInt64 *outSize); -}; - -class CMtCompressProgress: - public ICompressProgressInfo, - public CMyUnknownImp -{ - CMtCompressProgressMixer *_progress; - int _index; -public: - void Init(CMtCompressProgressMixer *progress, int index) - { - _progress = progress; - _index = index; - } - void Reinit() { _progress->Reinit(_index); } - - MY_UNKNOWN_IMP - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.cpp b/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.cpp deleted file mode 100644 index 84a3eaf65..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// ProgressUtils.h - -#include "StdAfx.h" - -#include "ProgressUtils.h" - -CLocalProgress::CLocalProgress() -{ - ProgressOffset = InSize = OutSize = 0; - SendRatio = SendProgress = true; -} - -void CLocalProgress::Init(IProgress *progress, bool inSizeIsMain) -{ - _ratioProgress.Release(); - _progress = progress; - _progress.QueryInterface(IID_ICompressProgressInfo, &_ratioProgress); - _inSizeIsMain = inSizeIsMain; -} - -STDMETHODIMP CLocalProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize) -{ - UInt64 inSizeNew = InSize, outSizeNew = OutSize; - if (inSize) - inSizeNew += (*inSize); - if (outSize) - outSizeNew += (*outSize); - if (SendRatio && _ratioProgress) - { - RINOK(_ratioProgress->SetRatioInfo(&inSizeNew, &outSizeNew)); - } - inSizeNew += ProgressOffset; - outSizeNew += ProgressOffset; - if (SendProgress) - return _progress->SetCompleted(_inSizeIsMain ? &inSizeNew : &outSizeNew); - return S_OK; -} - -HRESULT CLocalProgress::SetCur() -{ - return SetRatioInfo(NULL, NULL); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.h b/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.h deleted file mode 100644 index c6204844a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/ProgressUtils.h +++ /dev/null @@ -1,34 +0,0 @@ -// ProgressUtils.h - -#ifndef __PROGRESSUTILS_H -#define __PROGRESSUTILS_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" -#include "../IProgress.h" - -class CLocalProgress: - public ICompressProgressInfo, - public CMyUnknownImp -{ - CMyComPtr _progress; - CMyComPtr _ratioProgress; - bool _inSizeIsMain; -public: - UInt64 ProgressOffset; - UInt64 InSize; - UInt64 OutSize; - bool SendRatio; - bool SendProgress; - - CLocalProgress(); - void Init(IProgress *progress, bool inSizeIsMain); - HRESULT SetCur(); - - MY_UNKNOWN_IMP - - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/RegisterArc.h b/desmume/src/windows/7z/CPP/7zip/Common/RegisterArc.h deleted file mode 100644 index e377c4095..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/RegisterArc.h +++ /dev/null @@ -1,33 +0,0 @@ -// RegisterArc.h - -#ifndef __REGISTERARC_H -#define __REGISTERARC_H - -#include "../Archive/IArchive.h" -#include "DeclareArcs.h" - -typedef IInArchive * (*CreateInArchiveP)(); -typedef IOutArchive * (*CreateOutArchiveP)(); - -struct CArcInfo -{ - const wchar_t *Name; - const wchar_t *Ext; - const wchar_t *AddExt; - Byte ClassId; - Byte Signature[16]; - int SignatureSize; - bool KeepName; - CreateInArchiveP CreateInArchive; - CreateOutArchiveP CreateOutArchive; -}; - -void RegisterArc(const CArcInfo *arcInfo); - -#define REGISTER_ARC(x) CRegister##x::CRegister##x() { RegisterArc(&g_ArcInfo); } \ - CRegister##x g_RegisterArc##x; - -#define REGISTER_ARCN(x,n) CRegister##x##n::CRegister##x##n() { RegisterArc(&g_ArcInfo##n); } \ - CRegister##x##n g_RegisterArc##n##x; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/RegisterCodec.h b/desmume/src/windows/7z/CPP/7zip/Common/RegisterCodec.h deleted file mode 100644 index f51e6317e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/RegisterCodec.h +++ /dev/null @@ -1,30 +0,0 @@ -// RegisterCodec.h - -#ifndef __REGISTERCODEC_H -#define __REGISTERCODEC_H - -#include "../Common/MethodId.h" -#include "DeclareCodecs.h" - -typedef void * (*CreateCodecP)(); -struct CCodecInfo -{ - CreateCodecP CreateDecoder; - CreateCodecP CreateEncoder; - CMethodId Id; - const wchar_t *Name; - UInt32 NumInStreams; - bool IsFilter; -}; - -void RegisterCodec(const CCodecInfo *codecInfo); - -#define REGISTER_CODEC(x) CRegisterCodec##x::CRegisterCodec##x() { RegisterCodec(&g_CodecInfo); } \ - CRegisterCodec##x g_RegisterCodec##x; - -#define REGISTER_CODECS(x) CRegisterCodecs##x::CRegisterCodecs##x() { \ - for(int i=0;iCloseRead(); } - void SetBinder(CStreamBinder *streamBinder) { m_StreamBinder = streamBinder; } -}; - -STDMETHODIMP CSequentialInStreamForBinder::Read(void *data, UInt32 size, UInt32 *processedSize) - { return m_StreamBinder->Read(data, size, processedSize); } - -class CSequentialOutStreamForBinder: - public ISequentialOutStream, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - -private: - CStreamBinder *m_StreamBinder; -public: - ~CSequentialOutStreamForBinder() { m_StreamBinder->CloseWrite(); } - void SetBinder(CStreamBinder *streamBinder) { m_StreamBinder = streamBinder; } -}; - -STDMETHODIMP CSequentialOutStreamForBinder::Write(const void *data, UInt32 size, UInt32 *processedSize) - { return m_StreamBinder->Write(data, size, processedSize); } - - -////////////////////////// -// CStreamBinder -// (_thereAreBytesToReadEvent && _bufferSize == 0) means that stream is finished. - -HRes CStreamBinder::CreateEvents() -{ - RINOK(_allBytesAreWritenEvent.Create(true)); - RINOK(_thereAreBytesToReadEvent.Create()); - return _readStreamIsClosedEvent.Create(); -} - -void CStreamBinder::ReInit() -{ - _thereAreBytesToReadEvent.Reset(); - _readStreamIsClosedEvent.Reset(); - ProcessedSize = 0; -} - - - -void CStreamBinder::CreateStreams(ISequentialInStream **inStream, - ISequentialOutStream **outStream) -{ - CSequentialInStreamForBinder *inStreamSpec = new - CSequentialInStreamForBinder; - CMyComPtr inStreamLoc(inStreamSpec); - inStreamSpec->SetBinder(this); - *inStream = inStreamLoc.Detach(); - - CSequentialOutStreamForBinder *outStreamSpec = new - CSequentialOutStreamForBinder; - CMyComPtr outStreamLoc(outStreamSpec); - outStreamSpec->SetBinder(this); - *outStream = outStreamLoc.Detach(); - - _buffer = NULL; - _bufferSize= 0; - ProcessedSize = 0; -} - -HRESULT CStreamBinder::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 sizeToRead = size; - if (size > 0) - { - RINOK(_thereAreBytesToReadEvent.Lock()); - sizeToRead = MyMin(_bufferSize, size); - if (_bufferSize > 0) - { - memcpy(data, _buffer, sizeToRead); - _buffer = ((const Byte *)_buffer) + sizeToRead; - _bufferSize -= sizeToRead; - if (_bufferSize == 0) - { - _thereAreBytesToReadEvent.Reset(); - _allBytesAreWritenEvent.Set(); - } - } - } - if (processedSize != NULL) - *processedSize = sizeToRead; - ProcessedSize += sizeToRead; - return S_OK; -} - -void CStreamBinder::CloseRead() -{ - _readStreamIsClosedEvent.Set(); -} - -HRESULT CStreamBinder::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - if (size > 0) - { - _buffer = data; - _bufferSize = size; - _allBytesAreWritenEvent.Reset(); - _thereAreBytesToReadEvent.Set(); - - HANDLE events[2]; - events[0] = _allBytesAreWritenEvent; - events[1] = _readStreamIsClosedEvent; - DWORD waitResult = ::WaitForMultipleObjects(2, events, FALSE, INFINITE); - if (waitResult != WAIT_OBJECT_0 + 0) - { - // ReadingWasClosed = true; - return S_FALSE; - } - // if(!_allBytesAreWritenEvent.Lock()) - // return E_FAIL; - } - if (processedSize != NULL) - *processedSize = size; - return S_OK; -} - -void CStreamBinder::CloseWrite() -{ - // _bufferSize must be = 0 - _thereAreBytesToReadEvent.Set(); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/StreamBinder.h b/desmume/src/windows/7z/CPP/7zip/Common/StreamBinder.h deleted file mode 100644 index b5d6c0d1c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/StreamBinder.h +++ /dev/null @@ -1,32 +0,0 @@ -// StreamBinder.h - -#ifndef __STREAMBINDER_H -#define __STREAMBINDER_H - -#include "../IStream.h" -#include "../../Windows/Synchronization.h" - -class CStreamBinder -{ - NWindows::NSynchronization::CManualResetEvent _allBytesAreWritenEvent; - NWindows::NSynchronization::CManualResetEvent _thereAreBytesToReadEvent; - NWindows::NSynchronization::CManualResetEvent _readStreamIsClosedEvent; - UInt32 _bufferSize; - const void *_buffer; -public: - // bool ReadingWasClosed; - UInt64 ProcessedSize; - CStreamBinder() {} - HRes CreateEvents(); - - void CreateStreams(ISequentialInStream **inStream, - ISequentialOutStream **outStream); - HRESULT Read(void *data, UInt32 size, UInt32 *processedSize); - void CloseRead(); - - HRESULT Write(const void *data, UInt32 size, UInt32 *processedSize); - void CloseWrite(); - void ReInit(); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.cpp b/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.cpp deleted file mode 100644 index f42b56bfa..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.cpp +++ /dev/null @@ -1,68 +0,0 @@ -// StreamObjects.cpp - -#include "StdAfx.h" - -#include "StreamObjects.h" -#include "../../Common/Defs.h" - - -STDMETHODIMP CSequentialInStreamImp::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - size_t rem = _size - _pos; - if (size < rem) - rem = (size_t)size; - memcpy(data, _dataPointer + _pos, rem); - _pos += rem; - if (processedSize != NULL) - *processedSize = (UInt32)rem; - return S_OK; -} - - -void CWriteBuffer::Write(const void *data, size_t size) -{ - size_t newCapacity = _size + size; - _buffer.EnsureCapacity(newCapacity); - memcpy(_buffer + _size, data, size); - _size += size; -} - -STDMETHODIMP CSequentialOutStreamImp::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - _writeBuffer.Write(data, (size_t)size); - if(processedSize != NULL) - *processedSize = size; - return S_OK; -} - -STDMETHODIMP CSequentialOutStreamImp2::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - size_t rem = _size - _pos; - if (size < rem) - rem = (size_t)size; - memcpy(_buffer + _pos, data, rem); - _pos += rem; - if (processedSize != NULL) - *processedSize = (UInt32)rem; - return (rem == size ? S_OK : E_FAIL); -} - -STDMETHODIMP CSequentialInStreamSizeCount::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result = _stream->Read(data, size, &realProcessedSize); - _size += realProcessedSize; - if (processedSize != 0) - *processedSize = realProcessedSize; - return result; -} - -STDMETHODIMP CSequentialOutStreamSizeCount::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - UInt32 realProcessedSize; - HRESULT result = _stream->Write(data, size, &realProcessedSize); - _size += realProcessedSize; - if (processedSize != 0) - *processedSize = realProcessedSize; - return result; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.h b/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.h deleted file mode 100644 index 7f19fd479..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/StreamObjects.h +++ /dev/null @@ -1,117 +0,0 @@ -// StreamObjects.h - -#ifndef __STREAMOBJECTS_H -#define __STREAMOBJECTS_H - -#include "../../Common/DynamicBuffer.h" -#include "../../Common/MyCom.h" -#include "../IStream.h" - -class CSequentialInStreamImp: - public ISequentialInStream, - public CMyUnknownImp -{ - const Byte *_dataPointer; - size_t _size; - size_t _pos; - -public: - void Init(const Byte *dataPointer, size_t size) - { - _dataPointer = dataPointer; - _size = size; - _pos = 0; - } - - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); -}; - - -class CWriteBuffer -{ - CByteDynamicBuffer _buffer; - size_t _size; -public: - CWriteBuffer(): _size(0) {} - void Init() { _size = 0; } - void Write(const void *data, size_t size); - size_t GetSize() const { return _size; } - const CByteDynamicBuffer& GetBuffer() const { return _buffer; } -}; - -class CSequentialOutStreamImp: - public ISequentialOutStream, - public CMyUnknownImp -{ - CWriteBuffer _writeBuffer; -public: - void Init() { _writeBuffer.Init(); } - size_t GetSize() const { return _writeBuffer.GetSize(); } - const CByteDynamicBuffer& GetBuffer() const { return _writeBuffer.GetBuffer(); } - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -}; - -class CSequentialOutStreamImp2: - public ISequentialOutStream, - public CMyUnknownImp -{ - Byte *_buffer; - size_t _size; - size_t _pos; -public: - - void Init(Byte *buffer, size_t size) - { - _buffer = buffer; - _pos = 0; - _size = size; - } - - size_t GetPos() const { return _pos; } - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -}; - -class CSequentialInStreamSizeCount: - public ISequentialInStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; -public: - void Init(ISequentialInStream *stream) - { - _stream = stream; - _size = 0; - } - UInt64 GetSize() const { return _size; } - - MY_UNKNOWN_IMP - - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); -}; - -class CSequentialOutStreamSizeCount: - public ISequentialOutStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt64 _size; -public: - void SetStream(ISequentialOutStream *stream) { _stream = stream; } - void Init() { _size = 0; } - UInt64 GetSize() const { return _size; } - - MY_UNKNOWN_IMP - - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.cpp b/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.cpp deleted file mode 100644 index 57ff4ee38..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.cpp +++ /dev/null @@ -1,56 +0,0 @@ -// StreamUtils.cpp - -#include "StdAfx.h" - -#include "StreamUtils.h" - -static const UInt32 kBlockSize = ((UInt32)1 << 31); - -HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *processedSize) -{ - size_t size = *processedSize; - *processedSize = 0; - while (size != 0) - { - UInt32 curSize = (size < kBlockSize) ? (UInt32)size : kBlockSize; - UInt32 processedSizeLoc; - HRESULT res = stream->Read(data, curSize, &processedSizeLoc); - *processedSize += processedSizeLoc; - data = (void *)((Byte *)data + processedSizeLoc); - size -= processedSizeLoc; - RINOK(res); - if (processedSizeLoc == 0) - return S_OK; - } - return S_OK; -} - -HRESULT ReadStream_FALSE(ISequentialInStream *stream, void *data, size_t size) -{ - size_t processedSize = size; - RINOK(ReadStream(stream, data, &processedSize)); - return (size == processedSize) ? S_OK : S_FALSE; -} - -HRESULT ReadStream_FAIL(ISequentialInStream *stream, void *data, size_t size) -{ - size_t processedSize = size; - RINOK(ReadStream(stream, data, &processedSize)); - return (size == processedSize) ? S_OK : E_FAIL; -} - -HRESULT WriteStream(ISequentialOutStream *stream, const void *data, size_t size) -{ - while (size != 0) - { - UInt32 curSize = (size < kBlockSize) ? (UInt32)size : kBlockSize; - UInt32 processedSizeLoc; - HRESULT res = stream->Write(data, curSize, &processedSizeLoc); - data = (const void *)((const Byte *)data + processedSizeLoc); - size -= processedSizeLoc; - RINOK(res); - if (processedSizeLoc == 0) - return E_FAIL; - } - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.h b/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.h deleted file mode 100644 index 30535ab1b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/StreamUtils.h +++ /dev/null @@ -1,13 +0,0 @@ -// StreamUtils.h - -#ifndef __STREAMUTILS_H -#define __STREAMUTILS_H - -#include "../IStream.h" - -HRESULT ReadStream(ISequentialInStream *stream, void *data, size_t *size); -HRESULT ReadStream_FALSE(ISequentialInStream *stream, void *data, size_t size); -HRESULT ReadStream_FAIL(ISequentialInStream *stream, void *data, size_t size); -HRESULT WriteStream(ISequentialOutStream *stream, const void *data, size_t size); - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.cpp b/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.cpp deleted file mode 100644 index 75dc24c35..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.cpp +++ /dev/null @@ -1,45 +0,0 @@ -// VirtThread.cpp - -#include "StdAfx.h" - -#include "VirtThread.h" - -static THREAD_FUNC_DECL CoderThread(void *p) -{ - for (;;) - { - CVirtThread *t = (CVirtThread *)p; - t->StartEvent.Lock(); - if (t->ExitEvent) - return 0; - t->Execute(); - t->FinishedEvent.Set(); - } -} - -WRes CVirtThread::Create() -{ - RINOK(StartEvent.CreateIfNotCreated()); - RINOK(FinishedEvent.CreateIfNotCreated()); - StartEvent.Reset(); - FinishedEvent.Reset(); - ExitEvent = false; - if (Thread.IsCreated()) - return S_OK; - return Thread.Create(CoderThread, this); -} - -void CVirtThread::Start() -{ - ExitEvent = false; - StartEvent.Set(); -} - -CVirtThread::~CVirtThread() -{ - ExitEvent = true; - if (StartEvent.IsCreated()) - StartEvent.Set(); - Thread.Wait(); -} - diff --git a/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.h b/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.h deleted file mode 100644 index bfc10dc4a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Common/VirtThread.h +++ /dev/null @@ -1,23 +0,0 @@ -// VirtThread.h - -#ifndef __VIRTTHREAD_H -#define __VIRTTHREAD_H - -#include "../../Windows/Synchronization.h" -#include "../../Windows/Thread.h" - -struct CVirtThread -{ - NWindows::NSynchronization::CAutoResetEvent StartEvent; - NWindows::NSynchronization::CAutoResetEvent FinishedEvent; - NWindows::CThread Thread; - bool ExitEvent; - - ~CVirtThread(); - WRes Create(); - void Start(); - void WaitFinish() { FinishedEvent.Lock(); } - virtual void Execute() = 0; -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Const.h b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Const.h deleted file mode 100644 index fe0c53ff2..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Const.h +++ /dev/null @@ -1,54 +0,0 @@ -// Compress/BZip2Const.h - -#ifndef __COMPRESS_BZIP2_CONST_H -#define __COMPRESS_BZIP2_CONST_H - -namespace NCompress { -namespace NBZip2 { - -const Byte kArSig0 = 'B'; -const Byte kArSig1 = 'Z'; -const Byte kArSig2 = 'h'; -const Byte kArSig3 = '0'; - -const Byte kFinSig0 = 0x17; -const Byte kFinSig1 = 0x72; -const Byte kFinSig2 = 0x45; -const Byte kFinSig3 = 0x38; -const Byte kFinSig4 = 0x50; -const Byte kFinSig5 = 0x90; - -const Byte kBlockSig0 = 0x31; -const Byte kBlockSig1 = 0x41; -const Byte kBlockSig2 = 0x59; -const Byte kBlockSig3 = 0x26; -const Byte kBlockSig4 = 0x53; -const Byte kBlockSig5 = 0x59; - -const int kNumOrigBits = 24; - -const int kNumTablesBits = 3; -const int kNumTablesMin = 2; -const int kNumTablesMax = 6; - -const int kNumLevelsBits = 5; - -const int kMaxHuffmanLen = 20; // Check it - -const int kMaxAlphaSize = 258; - -const int kGroupSize = 50; - -const int kBlockSizeMultMin = 1; -const int kBlockSizeMultMax = 9; -const UInt32 kBlockSizeStep = 100000; -const UInt32 kBlockSizeMax = kBlockSizeMultMax * kBlockSizeStep; - -const int kNumSelectorsBits = 15; -const UInt32 kNumSelectorsMax = (2 + (kBlockSizeMax / kGroupSize)); - -const int kRleModeRepSize = 4; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.cpp deleted file mode 100644 index 2a8277ca4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.cpp +++ /dev/null @@ -1,26 +0,0 @@ -// BZip2Crc.cpp - -#include "StdAfx.h" - -#include "BZip2Crc.h" - -UInt32 CBZip2Crc::Table[256]; - -static const UInt32 kBZip2CrcPoly = 0x04c11db7; /* AUTODIN II, Ethernet, & FDDI */ - -void CBZip2Crc::InitTable() -{ - for (UInt32 i = 0; i < 256; i++) - { - UInt32 r = (i << 24); - for (int j = 8; j > 0; j--) - r = (r & 0x80000000) ? ((r << 1) ^ kBZip2CrcPoly) : (r << 1); - Table[i] = r; - } -} - -class CBZip2CrcTableInit -{ -public: - CBZip2CrcTableInit() { CBZip2Crc::InitTable(); } -} g_BZip2CrcTableInit; diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.h b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.h deleted file mode 100644 index ad1322fdd..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Crc.h +++ /dev/null @@ -1,31 +0,0 @@ -// BZip2Crc.h - -#ifndef __BZIP2_CRC_H -#define __BZIP2_CRC_H - -#include "Common/Types.h" - -class CBZip2Crc -{ - UInt32 _value; - static UInt32 Table[256]; -public: - static void InitTable(); - CBZip2Crc(): _value(0xFFFFFFFF) {}; - void Init() { _value = 0xFFFFFFFF; } - void UpdateByte(Byte b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); } - void UpdateByte(unsigned int b) { _value = Table[(_value >> 24) ^ b] ^ (_value << 8); } - UInt32 GetDigest() const { return _value ^ 0xFFFFFFFF; } -}; - -class CBZip2CombinedCrc -{ - UInt32 _value; -public: - CBZip2CombinedCrc(): _value(0){}; - void Init() { _value = 0; } - void Update(UInt32 v) { _value = ((_value << 1) | (_value >> 31)) ^ v; } - UInt32 GetDigest() const { return _value ; } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.cpp deleted file mode 100644 index b291be6f1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.cpp +++ /dev/null @@ -1,791 +0,0 @@ -// BZip2Decoder.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "../../Common/Defs.h" - -#include "BZip2Crc.h" -#include "BZip2Decoder.h" -#include "Mtf8.h" - -namespace NCompress { -namespace NBZip2 { - -#define NO_INLINE MY_FAST_CALL - -const UInt32 kNumThreadsMax = 4; - -static const UInt32 kBufferSize = (1 << 17); - -static Int16 kRandNums[512] = { - 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, - 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, - 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, - 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, - 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, - 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, - 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, - 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, - 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, - 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, - 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, - 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, - 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, - 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, - 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, - 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, - 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, - 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, - 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, - 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, - 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, - 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, - 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, - 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, - 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, - 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, - 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, - 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, - 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, - 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, - 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, - 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, - 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, - 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, - 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, - 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, - 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, - 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, - 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, - 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, - 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, - 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, - 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, - 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, - 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, - 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, - 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, - 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, - 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, - 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, - 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, - 936, 638 -}; - -bool CState::Alloc() -{ - if (Counters == 0) - Counters = (UInt32 *)BigAlloc((256 + kBlockSizeMax) * sizeof(UInt32)); - return (Counters != 0); -} - -void CState::Free() -{ - ::BigFree(Counters); - Counters = 0; -} - -UInt32 CDecoder::ReadBits(int numBits) { return m_InStream.ReadBits(numBits); } -Byte CDecoder::ReadByte() {return (Byte)ReadBits(8); } -bool CDecoder::ReadBit() { return ReadBits(1) != 0; } - -UInt32 CDecoder::ReadCrc() -{ - UInt32 crc = 0; - for (int i = 0; i < 4; i++) - { - crc <<= 8; - crc |= ReadByte(); - } - return crc; -} - -UInt32 NO_INLINE ReadBits(NBitm::CDecoder *m_InStream, int num) -{ - return m_InStream->ReadBits(num); -} - -UInt32 NO_INLINE ReadBit(NBitm::CDecoder *m_InStream) -{ - return m_InStream->ReadBits(1); -} - -static HRESULT NO_INLINE ReadBlock(NBitm::CDecoder *m_InStream, - UInt32 *CharCounters, UInt32 blockSizeMax, Byte *m_Selectors, CHuffmanDecoder *m_HuffmanDecoders, - UInt32 *blockSizeRes, UInt32 *origPtrRes, bool *randRes) -{ - *randRes = ReadBit(m_InStream) ? true : false; - *origPtrRes = ReadBits(m_InStream, kNumOrigBits); - - // in original code it compares OrigPtr to (UInt32)(10 + blockSizeMax)) : why ? - if (*origPtrRes >= blockSizeMax) - return S_FALSE; - - CMtf8Decoder mtf; - mtf.StartInit(); - - int numInUse = 0; - { - Byte inUse16[16]; - int i; - for (i = 0; i < 16; i++) - inUse16[i] = (Byte)ReadBit(m_InStream); - for (i = 0; i < 256; i++) - if (inUse16[i >> 4]) - { - if (ReadBit(m_InStream)) - mtf.Add(numInUse++, (Byte)i); - } - if (numInUse == 0) - return S_FALSE; - // mtf.Init(numInUse); - } - int alphaSize = numInUse + 2; - - int numTables = ReadBits(m_InStream, kNumTablesBits); - if (numTables < kNumTablesMin || numTables > kNumTablesMax) - return S_FALSE; - - UInt32 numSelectors = ReadBits(m_InStream, kNumSelectorsBits); - if (numSelectors < 1 || numSelectors > kNumSelectorsMax) - return S_FALSE; - - { - Byte mtfPos[kNumTablesMax]; - int t = 0; - do - mtfPos[t] = (Byte)t; - while(++t < numTables); - UInt32 i = 0; - do - { - int j = 0; - while (ReadBit(m_InStream)) - if (++j >= numTables) - return S_FALSE; - Byte tmp = mtfPos[j]; - for (;j > 0; j--) - mtfPos[j] = mtfPos[j - 1]; - m_Selectors[i] = mtfPos[0] = tmp; - } - while(++i < numSelectors); - } - - int t = 0; - do - { - Byte lens[kMaxAlphaSize]; - int len = (int)ReadBits(m_InStream, kNumLevelsBits); - int i; - for (i = 0; i < alphaSize; i++) - { - for (;;) - { - if (len < 1 || len > kMaxHuffmanLen) - return S_FALSE; - if (!ReadBit(m_InStream)) - break; - len += 1 - (int)(ReadBit(m_InStream) << 1); - } - lens[i] = (Byte)len; - } - for (; i < kMaxAlphaSize; i++) - lens[i] = 0; - if(!m_HuffmanDecoders[t].SetCodeLengths(lens)) - return S_FALSE; - } - while(++t < numTables); - - { - for (int i = 0; i < 256; i++) - CharCounters[i] = 0; - } - - UInt32 blockSize = 0; - { - UInt32 groupIndex = 0; - UInt32 groupSize = 0; - CHuffmanDecoder *huffmanDecoder = 0; - int runPower = 0; - UInt32 runCounter = 0; - - for (;;) - { - if (groupSize == 0) - { - if (groupIndex >= numSelectors) - return S_FALSE; - groupSize = kGroupSize; - huffmanDecoder = &m_HuffmanDecoders[m_Selectors[groupIndex++]]; - } - groupSize--; - - UInt32 nextSym = huffmanDecoder->DecodeSymbol(m_InStream); - - if (nextSym < 2) - { - runCounter += ((UInt32)(nextSym + 1) << runPower++); - if (blockSizeMax - blockSize < runCounter) - return S_FALSE; - continue; - } - if (runCounter != 0) - { - UInt32 b = (UInt32)mtf.GetHead(); - CharCounters[b] += runCounter; - do - CharCounters[256 + blockSize++] = b; - while(--runCounter != 0); - runPower = 0; - } - if (nextSym <= (UInt32)numInUse) - { - UInt32 b = (UInt32)mtf.GetAndMove((int)nextSym - 1); - if (blockSize >= blockSizeMax) - return S_FALSE; - CharCounters[b]++; - CharCounters[256 + blockSize++] = b; - } - else if (nextSym == (UInt32)numInUse + 1) - break; - else - return S_FALSE; - } - } - *blockSizeRes = blockSize; - return (*origPtrRes < blockSize) ? S_OK : S_FALSE; -} - -void NO_INLINE DecodeBlock1(UInt32 *charCounters, UInt32 blockSize) -{ - { - UInt32 sum = 0; - for (UInt32 i = 0; i < 256; i++) - { - sum += charCounters[i]; - charCounters[i] = sum - charCounters[i]; - } - } - - UInt32 *tt = charCounters + 256; - // Compute the T^(-1) vector - UInt32 i = 0; - do - tt[charCounters[tt[i] & 0xFF]++] |= (i << 8); - while(++i < blockSize); -} - -static UInt32 NO_INLINE DecodeBlock2(const UInt32 *tt, UInt32 blockSize, UInt32 OrigPtr, COutBuffer &m_OutStream) -{ - CBZip2Crc crc; - - // it's for speed optimization: prefetch & prevByte_init; - UInt32 tPos = tt[tt[OrigPtr] >> 8]; - unsigned int prevByte = (unsigned int)(tPos & 0xFF); - - int numReps = 0; - - do - { - unsigned int b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - - if (numReps == kRleModeRepSize) - { - for (; b > 0; b--) - { - crc.UpdateByte(prevByte); - m_OutStream.WriteByte((Byte)prevByte); - } - numReps = 0; - continue; - } - if (b != prevByte) - numReps = 0; - numReps++; - prevByte = b; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - - /* - prevByte = b; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - for (; --blockSize != 0;) - { - b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - if (b != prevByte) - { - prevByte = b; - continue; - } - if (--blockSize == 0) - break; - - b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - if (b != prevByte) - { - prevByte = b; - continue; - } - if (--blockSize == 0) - break; - - b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - if (b != prevByte) - { - prevByte = b; - continue; - } - --blockSize; - break; - } - if (blockSize == 0) - break; - - b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - - for (; b > 0; b--) - { - crc.UpdateByte(prevByte); - m_OutStream.WriteByte((Byte)prevByte); - } - */ - } - while(--blockSize != 0); - return crc.GetDigest(); -} - -static UInt32 NO_INLINE DecodeBlock2Rand(const UInt32 *tt, UInt32 blockSize, UInt32 OrigPtr, COutBuffer &m_OutStream) -{ - CBZip2Crc crc; - - UInt32 randIndex = 1; - UInt32 randToGo = kRandNums[0] - 2; - - int numReps = 0; - - // it's for speed optimization: prefetch & prevByte_init; - UInt32 tPos = tt[tt[OrigPtr] >> 8]; - unsigned int prevByte = (unsigned int)(tPos & 0xFF); - - do - { - unsigned int b = (unsigned int)(tPos & 0xFF); - tPos = tt[tPos >> 8]; - - { - if (randToGo == 0) - { - b ^= 1; - randToGo = kRandNums[randIndex++]; - randIndex &= 0x1FF; - } - randToGo--; - } - - if (numReps == kRleModeRepSize) - { - for (; b > 0; b--) - { - crc.UpdateByte(prevByte); - m_OutStream.WriteByte((Byte)prevByte); - } - numReps = 0; - continue; - } - if (b != prevByte) - numReps = 0; - numReps++; - prevByte = b; - crc.UpdateByte(b); - m_OutStream.WriteByte((Byte)b); - } - while(--blockSize != 0); - return crc.GetDigest(); -} - -#ifdef COMPRESS_BZIP2_MT - -CDecoder::CDecoder(): - m_States(0) -{ - m_NumThreadsPrev = 0; - NumThreads = 1; -} - -CDecoder::~CDecoder() -{ - Free(); -} - -#define RINOK_THREAD(x) { WRes __result_ = (x); if(__result_ != 0) return __result_; } - -HRESULT CDecoder::Create() -{ - RINOK_THREAD(CanProcessEvent.CreateIfNotCreated()); - RINOK_THREAD(CanStartWaitingEvent.CreateIfNotCreated()); - if (m_States != 0 && m_NumThreadsPrev == NumThreads) - return S_OK; - Free(); - MtMode = (NumThreads > 1); - m_NumThreadsPrev = NumThreads; - try - { - m_States = new CState[NumThreads]; - if (m_States == 0) - return E_OUTOFMEMORY; - } - catch(...) { return E_OUTOFMEMORY; } - for (UInt32 t = 0; t < NumThreads; t++) - { - CState &ti = m_States[t]; - ti.Decoder = this; - if (MtMode) - { - HRESULT res = ti.Create(); - if (res != S_OK) - { - NumThreads = t; - Free(); - return res; - } - } - } - return S_OK; -} - -void CDecoder::Free() -{ - if (!m_States) - return; - CloseThreads = true; - CanProcessEvent.Set(); - for (UInt32 t = 0; t < NumThreads; t++) - { - CState &s = m_States[t]; - if (MtMode) - s.Thread.Wait(); - s.Free(); - } - delete []m_States; - m_States = 0; -} -#endif - -HRESULT CDecoder::ReadSignatures(bool &wasFinished, UInt32 &crc) -{ - wasFinished = false; - Byte s[6]; - for (int i = 0; i < 6; i++) - s[i] = ReadByte(); - crc = ReadCrc(); - if (s[0] == kFinSig0) - { - if (s[1] != kFinSig1 || - s[2] != kFinSig2 || - s[3] != kFinSig3 || - s[4] != kFinSig4 || - s[5] != kFinSig5) - return S_FALSE; - - wasFinished = true; - return (crc == CombinedCrc.GetDigest()) ? S_OK : S_FALSE; - } - if (s[0] != kBlockSig0 || - s[1] != kBlockSig1 || - s[2] != kBlockSig2 || - s[3] != kBlockSig3 || - s[4] != kBlockSig4 || - s[5] != kBlockSig5) - return S_FALSE; - CombinedCrc.Update(crc); - return S_OK; -} - -HRESULT CDecoder::DecodeFile(bool &isBZ, ICompressProgressInfo *progress) -{ - #ifdef COMPRESS_BZIP2_MT - Progress = progress; - RINOK(Create()); - for (UInt32 t = 0; t < NumThreads; t++) - { - CState &s = m_States[t]; - if (!s.Alloc()) - return E_OUTOFMEMORY; - if (MtMode) - { - RINOK(s.StreamWasFinishedEvent.Reset()); - RINOK(s.WaitingWasStartedEvent.Reset()); - RINOK(s.CanWriteEvent.Reset()); - } - } - #else - if (!m_States[0].Alloc()) - return E_OUTOFMEMORY; - #endif - - isBZ = false; - Byte s[6]; - int i; - for (i = 0; i < 4; i++) - s[i] = ReadByte(); - if (s[0] != kArSig0 || - s[1] != kArSig1 || - s[2] != kArSig2 || - s[3] <= kArSig3 || - s[3] > kArSig3 + kBlockSizeMultMax) - return S_OK; - isBZ = true; - UInt32 dicSize = (UInt32)(s[3] - kArSig3) * kBlockSizeStep; - - CombinedCrc.Init(); - #ifdef COMPRESS_BZIP2_MT - if (MtMode) - { - NextBlockIndex = 0; - StreamWasFinished1 = StreamWasFinished2 = false; - CloseThreads = false; - CanStartWaitingEvent.Reset(); - m_States[0].CanWriteEvent.Set(); - BlockSizeMax = dicSize; - Result1 = Result2 = S_OK; - CanProcessEvent.Set(); - UInt32 t; - for (t = 0; t < NumThreads; t++) - m_States[t].StreamWasFinishedEvent.Lock(); - CanProcessEvent.Reset(); - CanStartWaitingEvent.Set(); - for (t = 0; t < NumThreads; t++) - m_States[t].WaitingWasStartedEvent.Lock(); - CanStartWaitingEvent.Reset(); - RINOK(Result2); - RINOK(Result1); - } - else - #endif - { - CState &state = m_States[0]; - for (;;) - { - if (progress) - { - UInt64 packSize = m_InStream.GetProcessedSize(); - UInt64 unpackSize = m_OutStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &unpackSize)); - } - bool wasFinished; - UInt32 crc; - RINOK(ReadSignatures(wasFinished, crc)); - if (wasFinished) - return S_OK; - - UInt32 blockSize, origPtr; - bool randMode; - RINOK(ReadBlock(&m_InStream, state.Counters, dicSize, - m_Selectors, m_HuffmanDecoders, - &blockSize, &origPtr, &randMode)); - DecodeBlock1(state.Counters, blockSize); - if ((randMode ? - DecodeBlock2Rand(state.Counters + 256, blockSize, origPtr, m_OutStream) : - DecodeBlock2(state.Counters + 256, blockSize, origPtr, m_OutStream)) != crc) - return S_FALSE; - } - } - return S_OK; -} - -HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) -{ - if (!m_InStream.Create(kBufferSize)) - return E_OUTOFMEMORY; - if (!m_OutStream.Create(kBufferSize)) - return E_OUTOFMEMORY; - - m_InStream.SetStream(inStream); - m_InStream.Init(); - - m_OutStream.SetStream(outStream); - m_OutStream.Init(); - - CDecoderFlusher flusher(this); - - bool isBZ; - RINOK(DecodeFile(isBZ, progress)); - return isBZ ? S_OK: S_FALSE; -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress); } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const COutBufferException &e) { return e.ErrorCode; } - catch(...) { return E_FAIL; } -} - -STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) -{ - if (value == NULL) - return E_INVALIDARG; - *value = m_InStream.GetProcessedSize(); - return S_OK; -} - -#ifdef COMPRESS_BZIP2_MT - -static THREAD_FUNC_DECL MFThread(void *p) { ((CState *)p)->ThreadFunc(); return 0; } - -HRESULT CState::Create() -{ - RINOK_THREAD(StreamWasFinishedEvent.CreateIfNotCreated()); - RINOK_THREAD(WaitingWasStartedEvent.CreateIfNotCreated()); - RINOK_THREAD(CanWriteEvent.CreateIfNotCreated()); - RINOK_THREAD(Thread.Create(MFThread, this)); - return S_OK; -} - -void CState::FinishStream() -{ - Decoder->StreamWasFinished1 = true; - StreamWasFinishedEvent.Set(); - Decoder->CS.Leave(); - Decoder->CanStartWaitingEvent.Lock(); - WaitingWasStartedEvent.Set(); -} - -void CState::ThreadFunc() -{ - for (;;) - { - Decoder->CanProcessEvent.Lock(); - Decoder->CS.Enter(); - if (Decoder->CloseThreads) - { - Decoder->CS.Leave(); - return; - } - if (Decoder->StreamWasFinished1) - { - FinishStream(); - continue; - } - HRESULT res = S_OK; - - UInt32 blockIndex = Decoder->NextBlockIndex; - UInt32 nextBlockIndex = blockIndex + 1; - if (nextBlockIndex == Decoder->NumThreads) - nextBlockIndex = 0; - Decoder->NextBlockIndex = nextBlockIndex; - UInt32 crc; - UInt64 packSize; - UInt32 blockSize = 0, origPtr = 0; - bool randMode = false; - - try - { - bool wasFinished; - res = Decoder->ReadSignatures(wasFinished, crc); - if (res != S_OK) - { - Decoder->Result1 = res; - FinishStream(); - continue; - } - if (wasFinished) - { - Decoder->Result1 = res; - FinishStream(); - continue; - } - - res = ReadBlock(&Decoder->m_InStream, Counters, Decoder->BlockSizeMax, - Decoder->m_Selectors, Decoder->m_HuffmanDecoders, - &blockSize, &origPtr, &randMode); - if (res != S_OK) - { - Decoder->Result1 = res; - FinishStream(); - continue; - } - packSize = Decoder->m_InStream.GetProcessedSize(); - } - catch(const CInBufferException &e) { res = e.ErrorCode; if (res != S_OK) res = E_FAIL; } - catch(...) { res = E_FAIL; } - if (res != S_OK) - { - Decoder->Result1 = res; - FinishStream(); - continue; - } - - Decoder->CS.Leave(); - - DecodeBlock1(Counters, blockSize); - - bool needFinish = true; - try - { - Decoder->m_States[blockIndex].CanWriteEvent.Lock(); - needFinish = Decoder->StreamWasFinished2; - if (!needFinish) - { - if ((randMode ? - DecodeBlock2Rand(Counters + 256, blockSize, origPtr, Decoder->m_OutStream) : - DecodeBlock2(Counters + 256, blockSize, origPtr, Decoder->m_OutStream)) == crc) - { - if (Decoder->Progress) - { - UInt64 unpackSize = Decoder->m_OutStream.GetProcessedSize(); - res = Decoder->Progress->SetRatioInfo(&packSize, &unpackSize); - } - } - else - res = S_FALSE; - } - } - catch(const COutBufferException &e) { res = e.ErrorCode; if (res != S_OK) res = E_FAIL; } - catch(...) { res = E_FAIL; } - if (res != S_OK) - { - Decoder->Result2 = res; - Decoder->StreamWasFinished2 = true; - } - Decoder->m_States[nextBlockIndex].CanWriteEvent.Set(); - if (res != S_OK || needFinish) - { - StreamWasFinishedEvent.Set(); - Decoder->CanStartWaitingEvent.Lock(); - WaitingWasStartedEvent.Set(); - } - } -} - -STDMETHODIMP CDecoder::SetNumberOfThreads(UInt32 numThreads) -{ - NumThreads = numThreads; - if (NumThreads < 1) - NumThreads = 1; - if (NumThreads > kNumThreadsMax) - NumThreads = kNumThreadsMax; - return S_OK; -} -#endif - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.h deleted file mode 100644 index 394860071..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Decoder.h +++ /dev/null @@ -1,159 +0,0 @@ -// Compress/BZip2Decoder.h - -#ifndef __COMPRESS_BZIP2_DECODER_H -#define __COMPRESS_BZIP2_DECODER_H - -#include "../../Common/MyCom.h" - -#ifdef COMPRESS_BZIP2_MT -#include "../../Windows/Synchronization.h" -#include "../../Windows/Thread.h" -#endif - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" -#include "../Common/OutBuffer.h" - -#include "BitmDecoder.h" -#include "BZip2Const.h" -#include "BZip2Crc.h" -#include "HuffmanDecoder.h" - -namespace NCompress { -namespace NBZip2 { - -typedef NCompress::NHuffman::CDecoder CHuffmanDecoder; - -class CDecoder; - -struct CState -{ - UInt32 *Counters; - - #ifdef COMPRESS_BZIP2_MT - - CDecoder *Decoder; - NWindows::CThread Thread; - bool m_OptimizeNumTables; - - NWindows::NSynchronization::CAutoResetEvent StreamWasFinishedEvent; - NWindows::NSynchronization::CAutoResetEvent WaitingWasStartedEvent; - - // it's not member of this thread. We just need one event per thread - NWindows::NSynchronization::CAutoResetEvent CanWriteEvent; - - Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size. - - HRESULT Create(); - void FinishStream(); - void ThreadFunc(); - - #endif - - CState(): Counters(0) {} - ~CState() { Free(); } - bool Alloc(); - void Free(); -}; - -class CDecoder : - public ICompressCoder, - #ifdef COMPRESS_BZIP2_MT - public ICompressSetCoderMt, - #endif - public ICompressGetInStreamProcessedSize, - public CMyUnknownImp -{ -public: - COutBuffer m_OutStream; - Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size. - NBitm::CDecoder m_InStream; - Byte m_Selectors[kNumSelectorsMax]; - CHuffmanDecoder m_HuffmanDecoders[kNumTablesMax]; -private: - - UInt32 m_NumThreadsPrev; - - UInt32 ReadBits(int numBits); - Byte ReadByte(); - bool ReadBit(); - UInt32 ReadCrc(); - HRESULT PrepareBlock(CState &state); - HRESULT DecodeFile(bool &isBZ, ICompressProgressInfo *progress); - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - class CDecoderFlusher - { - CDecoder *_decoder; - public: - bool NeedFlush; - CDecoderFlusher(CDecoder *decoder): _decoder(decoder), NeedFlush(true) {} - ~CDecoderFlusher() - { - if (NeedFlush) - _decoder->Flush(); - _decoder->ReleaseStreams(); - } - }; - -public: - CBZip2CombinedCrc CombinedCrc; - - #ifdef COMPRESS_BZIP2_MT - ICompressProgressInfo *Progress; - CState *m_States; - - NWindows::NSynchronization::CManualResetEvent CanProcessEvent; - NWindows::NSynchronization::CCriticalSection CS; - UInt32 NumThreads; - bool MtMode; - UInt32 NextBlockIndex; - bool CloseThreads; - bool StreamWasFinished1; - bool StreamWasFinished2; - NWindows::NSynchronization::CManualResetEvent CanStartWaitingEvent; - - HRESULT Result1; - HRESULT Result2; - - UInt32 BlockSizeMax; - CDecoder(); - ~CDecoder(); - HRESULT Create(); - void Free(); - - #else - CState m_States[1]; - #endif - - HRESULT ReadSignatures(bool &wasFinished, UInt32 &crc); - - - HRESULT Flush() { return m_OutStream.Flush(); } - void ReleaseStreams() - { - m_InStream.ReleaseStream(); - m_OutStream.ReleaseStream(); - } - - #ifdef COMPRESS_BZIP2_MT - MY_UNKNOWN_IMP2(ICompressSetCoderMt, ICompressGetInStreamProcessedSize) - #else - MY_UNKNOWN_IMP1(ICompressGetInStreamProcessedSize) - #endif - - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - - #ifdef COMPRESS_BZIP2_MT - STDMETHOD(SetNumberOfThreads)(UInt32 numThreads); - #endif -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Register.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Register.cpp deleted file mode 100644 index f10e594c6..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BZip2Register.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// BZip2Register.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "BZip2Decoder.h" - -static void *CreateCodec() { return (void *)(ICompressCoder *)(new NCompress::NBZip2::CDecoder); } -#if !defined(EXTRACT_ONLY) && !defined(BZIP2_EXTRACT_ONLY) -#include "BZip2Encoder.h" -static void *CreateCodecOut() { return (void *)(ICompressCoder *)(new NCompress::NBZip2::CEncoder); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x040202, L"BZip2", 1, false }; - -REGISTER_CODEC(BZip2) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.cpp deleted file mode 100644 index e52095a77..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.cpp +++ /dev/null @@ -1,393 +0,0 @@ -// Bcj2Coder.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "Bcj2Coder.h" - -namespace NCompress { -namespace NBcj2 { - -inline bool IsJcc(Byte b0, Byte b1) { return (b0 == 0x0F && (b1 & 0xF0) == 0x80); } -inline bool IsJ(Byte b0, Byte b1) { return ((b1 & 0xFE) == 0xE8 || IsJcc(b0, b1)); } -inline unsigned GetIndex(Byte b0, Byte b1) { return ((b1 == 0xE8) ? b0 : ((b1 == 0xE9) ? 256 : 257)); } - -#ifndef EXTRACT_ONLY - -static const int kBufferSize = 1 << 17; - -static bool inline Test86MSByte(Byte b) -{ - return (b == 0 || b == 0xFF); -} - -bool CEncoder::Create() -{ - if (!_mainStream.Create(1 << 16)) - return false; - if (!_callStream.Create(1 << 20)) - return false; - if (!_jumpStream.Create(1 << 20)) - return false; - if (!_rangeEncoder.Create(1 << 20)) - return false; - if (_buffer == 0) - { - _buffer = (Byte *)MidAlloc(kBufferSize); - if (_buffer == 0) - return false; - } - return true; -} - -CEncoder::~CEncoder() -{ - ::MidFree(_buffer); -} - -HRESULT CEncoder::Flush() -{ - RINOK(_mainStream.Flush()); - RINOK(_callStream.Flush()); - RINOK(_jumpStream.Flush()); - _rangeEncoder.FlushData(); - return _rangeEncoder.FlushStream(); -} - -const UInt32 kDefaultLimit = (1 << 24); - -HRESULT CEncoder::CodeReal(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 ** /* outSizes */, - UInt32 numOutStreams, - ICompressProgressInfo *progress) -{ - if (numInStreams != 1 || numOutStreams != 4) - return E_INVALIDARG; - - if (!Create()) - return E_OUTOFMEMORY; - - bool sizeIsDefined = false; - UInt64 inSize = 0; - if (inSizes != NULL) - if (inSizes[0] != NULL) - { - inSize = *inSizes[0]; - if (inSize <= kDefaultLimit) - sizeIsDefined = true; - } - - ISequentialInStream *inStream = inStreams[0]; - - _mainStream.SetStream(outStreams[0]); - _mainStream.Init(); - _callStream.SetStream(outStreams[1]); - _callStream.Init(); - _jumpStream.SetStream(outStreams[2]); - _jumpStream.Init(); - _rangeEncoder.SetStream(outStreams[3]); - _rangeEncoder.Init(); - for (int i = 0; i < 256 + 2; i++) - _statusEncoder[i].Init(); - CCoderReleaser releaser(this); - - CMyComPtr getSubStreamSize; - { - inStream->QueryInterface(IID_ICompressGetSubStreamSize, (void **)&getSubStreamSize); - } - - UInt32 nowPos = 0; - UInt64 nowPos64 = 0; - UInt32 bufferPos = 0; - - Byte prevByte = 0; - - UInt64 subStreamIndex = 0; - UInt64 subStreamStartPos = 0; - UInt64 subStreamEndPos = 0; - - for (;;) - { - UInt32 processedSize = 0; - for (;;) - { - UInt32 size = kBufferSize - (bufferPos + processedSize); - UInt32 processedSizeLoc; - if (size == 0) - break; - RINOK(inStream->Read(_buffer + bufferPos + processedSize, size, &processedSizeLoc)); - if (processedSizeLoc == 0) - break; - processedSize += processedSizeLoc; - } - UInt32 endPos = bufferPos + processedSize; - - if (endPos < 5) - { - // change it - for (bufferPos = 0; bufferPos < endPos; bufferPos++) - { - Byte b = _buffer[bufferPos]; - _mainStream.WriteByte(b); - UInt32 index; - if (b == 0xE8) - index = prevByte; - else if (b == 0xE9) - index = 256; - else if (IsJcc(prevByte, b)) - index = 257; - else - { - prevByte = b; - continue; - } - _statusEncoder[index].Encode(&_rangeEncoder, 0); - prevByte = b; - } - return Flush(); - } - - bufferPos = 0; - - UInt32 limit = endPos - 5; - while(bufferPos <= limit) - { - Byte b = _buffer[bufferPos]; - _mainStream.WriteByte(b); - if (!IsJ(prevByte, b)) - { - bufferPos++; - prevByte = b; - continue; - } - Byte nextByte = _buffer[bufferPos + 4]; - UInt32 src = - (UInt32(nextByte) << 24) | - (UInt32(_buffer[bufferPos + 3]) << 16) | - (UInt32(_buffer[bufferPos + 2]) << 8) | - (_buffer[bufferPos + 1]); - UInt32 dest = (nowPos + bufferPos + 5) + src; - // if (Test86MSByte(nextByte)) - bool convert; - if (getSubStreamSize != NULL) - { - UInt64 currentPos = (nowPos64 + bufferPos); - while (subStreamEndPos < currentPos) - { - UInt64 subStreamSize; - HRESULT result = getSubStreamSize->GetSubStreamSize(subStreamIndex, &subStreamSize); - if (result == S_OK) - { - subStreamStartPos = subStreamEndPos; - subStreamEndPos += subStreamSize; - subStreamIndex++; - } - else if (result == S_FALSE || result == E_NOTIMPL) - { - getSubStreamSize.Release(); - subStreamStartPos = 0; - subStreamEndPos = subStreamStartPos - 1; - } - else - return result; - } - if (getSubStreamSize == NULL) - { - if (sizeIsDefined) - convert = (dest < inSize); - else - convert = Test86MSByte(nextByte); - } - else if (subStreamEndPos - subStreamStartPos > kDefaultLimit) - convert = Test86MSByte(nextByte); - else - { - UInt64 dest64 = (currentPos + 5) + Int64(Int32(src)); - convert = (dest64 >= subStreamStartPos && dest64 < subStreamEndPos); - } - } - else if (sizeIsDefined) - convert = (dest < inSize); - else - convert = Test86MSByte(nextByte); - unsigned index = GetIndex(prevByte, b); - if (convert) - { - _statusEncoder[index].Encode(&_rangeEncoder, 1); - bufferPos += 5; - COutBuffer &s = (b == 0xE8) ? _callStream : _jumpStream; - for (int i = 24; i >= 0; i -= 8) - s.WriteByte((Byte)(dest >> i)); - prevByte = nextByte; - } - else - { - _statusEncoder[index].Encode(&_rangeEncoder, 0); - bufferPos++; - prevByte = b; - } - } - nowPos += bufferPos; - nowPos64 += bufferPos; - - if (progress != NULL) - { - /* - const UInt64 compressedSize = - _mainStream.GetProcessedSize() + - _callStream.GetProcessedSize() + - _jumpStream.GetProcessedSize() + - _rangeEncoder.GetProcessedSize(); - */ - RINOK(progress->SetRatioInfo(&nowPos64, NULL)); - } - - UInt32 i = 0; - while(bufferPos < endPos) - _buffer[i++] = _buffer[bufferPos++]; - bufferPos = i; - } -} - -STDMETHODIMP CEncoder::Code(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress) -{ - try - { - return CodeReal(inStreams, inSizes, numInStreams, - outStreams, outSizes,numOutStreams, progress); - } - catch(const COutBufferException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -#endif - -HRESULT CDecoder::CodeReal(ISequentialInStream **inStreams, - const UInt64 ** /* inSizes */, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 ** /* outSizes */, - UInt32 numOutStreams, - ICompressProgressInfo *progress) -{ - if (numInStreams != 4 || numOutStreams != 1) - return E_INVALIDARG; - - if (!_mainInStream.Create(1 << 16)) - return E_OUTOFMEMORY; - if (!_callStream.Create(1 << 20)) - return E_OUTOFMEMORY; - if (!_jumpStream.Create(1 << 16)) - return E_OUTOFMEMORY; - if (!_rangeDecoder.Create(1 << 20)) - return E_OUTOFMEMORY; - if (!_outStream.Create(1 << 16)) - return E_OUTOFMEMORY; - - _mainInStream.SetStream(inStreams[0]); - _callStream.SetStream(inStreams[1]); - _jumpStream.SetStream(inStreams[2]); - _rangeDecoder.SetStream(inStreams[3]); - _outStream.SetStream(outStreams[0]); - - _mainInStream.Init(); - _callStream.Init(); - _jumpStream.Init(); - _rangeDecoder.Init(); - _outStream.Init(); - - for (int i = 0; i < 256 + 2; i++) - _statusDecoder[i].Init(); - - CCoderReleaser releaser(this); - - Byte prevByte = 0; - UInt32 processedBytes = 0; - for (;;) - { - if (processedBytes >= (1 << 20) && progress != NULL) - { - /* - const UInt64 compressedSize = - _mainInStream.GetProcessedSize() + - _callStream.GetProcessedSize() + - _jumpStream.GetProcessedSize() + - _rangeDecoder.GetProcessedSize(); - */ - const UInt64 nowPos64 = _outStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(NULL, &nowPos64)); - processedBytes = 0; - } - UInt32 i; - Byte b = 0; - const UInt32 kBurstSize = (1 << 18); - for (i = 0; i < kBurstSize; i++) - { - if (!_mainInStream.ReadByte(b)) - return Flush(); - _outStream.WriteByte(b); - if (IsJ(prevByte, b)) - break; - prevByte = b; - } - processedBytes += i; - if (i == kBurstSize) - continue; - unsigned index = GetIndex(prevByte, b); - if (_statusDecoder[index].Decode(&_rangeDecoder) == 1) - { - UInt32 src = 0; - CInBuffer &s = (b == 0xE8) ? _callStream : _jumpStream; - for (int i = 0; i < 4; i++) - { - Byte b0; - if(!s.ReadByte(b0)) - return S_FALSE; - src <<= 8; - src |= ((UInt32)b0); - } - UInt32 dest = src - (UInt32(_outStream.GetProcessedSize()) + 4) ; - _outStream.WriteByte((Byte)(dest)); - _outStream.WriteByte((Byte)(dest >> 8)); - _outStream.WriteByte((Byte)(dest >> 16)); - _outStream.WriteByte((Byte)(dest >> 24)); - prevByte = (Byte)(dest >> 24); - processedBytes += 4; - } - else - prevByte = b; - } -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress) -{ - try - { - return CodeReal(inStreams, inSizes, numInStreams, - outStreams, outSizes,numOutStreams, progress); - } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const COutBufferException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.h b/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.h deleted file mode 100644 index fcbc2a411..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Coder.h +++ /dev/null @@ -1,125 +0,0 @@ -// Bcj2Coder.h - -#ifndef __COMPRESS_BCJ2_CODER_H -#define __COMPRESS_BCJ2_CODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "RangeCoderBit.h" - -namespace NCompress { -namespace NBcj2 { - -const int kNumMoveBits = 5; - -#ifndef EXTRACT_ONLY - -class CEncoder: - public ICompressCoder2, - public CMyUnknownImp -{ - Byte *_buffer; -public: - CEncoder(): _buffer(0) {}; - ~CEncoder(); - bool Create(); - - COutBuffer _mainStream; - COutBuffer _callStream; - COutBuffer _jumpStream; - NCompress::NRangeCoder::CEncoder _rangeEncoder; - NCompress::NRangeCoder::CBitEncoder _statusEncoder[256 + 2]; - - HRESULT Flush(); - void ReleaseStreams() - { - _mainStream.ReleaseStream(); - _callStream.ReleaseStream(); - _jumpStream.ReleaseStream(); - _rangeEncoder.ReleaseStream(); - } - - class CCoderReleaser - { - CEncoder *_coder; - public: - CCoderReleaser(CEncoder *coder): _coder(coder) {} - ~CCoderReleaser() { _coder->ReleaseStreams(); } - }; - -public: - - MY_UNKNOWN_IMP - - HRESULT CodeReal(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress); - STDMETHOD(Code)(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress); -}; - -#endif - -class CDecoder: - public ICompressCoder2, - public CMyUnknownImp -{ -public: - CInBuffer _mainInStream; - CInBuffer _callStream; - CInBuffer _jumpStream; - NCompress::NRangeCoder::CDecoder _rangeDecoder; - NCompress::NRangeCoder::CBitDecoder _statusDecoder[256 + 2]; - - COutBuffer _outStream; - - void ReleaseStreams() - { - _mainInStream.ReleaseStream(); - _callStream.ReleaseStream(); - _jumpStream.ReleaseStream(); - _rangeDecoder.ReleaseStream(); - _outStream.ReleaseStream(); - } - - HRESULT Flush() { return _outStream.Flush(); } - class CCoderReleaser - { - CDecoder *_coder; - public: - CCoderReleaser(CDecoder *coder): _coder(coder) {} - ~CCoderReleaser() { _coder->ReleaseStreams(); } - }; - -public: - MY_UNKNOWN_IMP - HRESULT CodeReal(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress); - STDMETHOD(Code)(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Register.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Register.cpp deleted file mode 100644 index b063f3f69..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Bcj2Register.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// Bcj2Register.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "Bcj2Coder.h" - -static void *CreateCodec() { return (void *)(ICompressCoder2 *)(new NCompress::NBcj2::CDecoder()); } -#ifndef EXTRACT_ONLY -static void *CreateCodecOut() { return (void *)(ICompressCoder2 *)(new NCompress::NBcj2::CEncoder()); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x0303011B, L"BCJ2", 4, false }; - -REGISTER_CODEC(BCJ2) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.cpp deleted file mode 100644 index 108c573d5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.cpp +++ /dev/null @@ -1,15 +0,0 @@ -// BcjCoder.cpp - -#include "StdAfx.h" - -#include "BcjCoder.h" - -UInt32 CBCJ_x86_Encoder::SubFilter(Byte *data, UInt32 size) -{ - return (UInt32)::x86_Convert(data, size, _bufferPos, &_prevMask, 1); -} - -UInt32 CBCJ_x86_Decoder::SubFilter(Byte *data, UInt32 size) -{ - return (UInt32)::x86_Convert(data, size, _bufferPos, &_prevMask, 0); -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.h deleted file mode 100644 index 3389b2092..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BcjCoder.h +++ /dev/null @@ -1,22 +0,0 @@ -// BcjCoder.h - -#ifndef __COMPRESS_BCJ_CODER_H -#define __COMPRESS_BCJ_CODER_H - -extern "C" -{ -#include "../../../C/Bra.h" -} - -#include "BranchCoder.h" - -struct CBranch86 -{ - UInt32 _prevMask; - void x86Init() { x86_Convert_Init(_prevMask); } -}; - -MyClassB(BCJ_x86, 0x01, 3, CBranch86 , - virtual void SubInit() { x86Init(); }) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BcjRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BcjRegister.cpp deleted file mode 100644 index 09e53c655..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BcjRegister.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// BcjRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "BcjCoder.h" - -static void *CreateCodec() { return (void *)(ICompressFilter *)(new CBCJ_x86_Decoder()); } -#ifndef EXTRACT_ONLY -static void *CreateCodecOut() { return (void *)(ICompressFilter *)(new CBCJ_x86_Encoder()); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x03030103, L"BCJ", 1, true }; - -REGISTER_CODEC(BCJ) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.cpp deleted file mode 100644 index 6022e8bf5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// BitlDecoder.cpp - -#include "StdAfx.h" - -#include "BitlDecoder.h" - -namespace NBitl { - -Byte kInvertTable[256]; - -struct CInverterTableInitializer -{ - CInverterTableInitializer() - { - for (int i = 0; i < 256; i++) - { - int x = ((i & 0x55) << 1) | ((i & 0xAA) >> 1); - x = ((x & 0x33) << 2) | ((x & 0xCC) >> 2); - kInvertTable[i] = (Byte)(((x & 0x0F) << 4) | ((x & 0xF0) >> 4)); - } - } -} g_InverterTableInitializer; - -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.h deleted file mode 100644 index f2e115d48..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BitlDecoder.h +++ /dev/null @@ -1,125 +0,0 @@ -// BitlDecoder.h -- the Least Significant Bit of byte is First - -#ifndef __BITL_DECODER_H -#define __BITL_DECODER_H - -#include "../IStream.h" - -namespace NBitl { - -const int kNumBigValueBits = 8 * 4; - -const int kNumValueBytes = 3; -const int kNumValueBits = 8 * kNumValueBytes; - -const UInt32 kMask = (1 << kNumValueBits) - 1; - -extern Byte kInvertTable[256]; - -template -class CBaseDecoder -{ -protected: - int m_BitPos; - UInt32 m_Value; - TInByte m_Stream; -public: - UInt32 NumExtraBytes; - bool Create(UInt32 bufferSize) { return m_Stream.Create(bufferSize); } - void SetStream(ISequentialInStream *inStream) { m_Stream.SetStream(inStream); } - void ReleaseStream() { m_Stream.ReleaseStream(); } - void Init() - { - m_Stream.Init(); - m_BitPos = kNumBigValueBits; - m_Value = 0; - NumExtraBytes = 0; - } - UInt64 GetProcessedSize() const - { return m_Stream.GetProcessedSize() - (kNumBigValueBits - m_BitPos) / 8; } - UInt64 GetProcessedBitsSize() const - { return (m_Stream.GetProcessedSize() << 3) - (kNumBigValueBits - m_BitPos); } - int GetBitPosition() const { return (m_BitPos & 7); } - - void Normalize() - { - for (;m_BitPos >= 8; m_BitPos -= 8) - { - Byte b = 0; - if (!m_Stream.ReadByte(b)) - { - b = 0xFF; // check it - NumExtraBytes++; - } - m_Value = (b << (kNumBigValueBits - m_BitPos)) | m_Value; - } - } - - UInt32 ReadBits(int numBits) - { - Normalize(); - UInt32 res = m_Value & ((1 << numBits) - 1); - m_BitPos += numBits; - m_Value >>= numBits; - return res; - } - - bool ExtraBitsWereRead() const - { - if (NumExtraBytes == 0) - return false; - return ((UInt32)(kNumBigValueBits - m_BitPos) < (NumExtraBytes << 3)); - } -}; - -template -class CDecoder: public CBaseDecoder -{ - UInt32 m_NormalValue; - -public: - void Init() - { - CBaseDecoder::Init(); - m_NormalValue = 0; - } - - void Normalize() - { - for (; this->m_BitPos >= 8; this->m_BitPos -= 8) - { - Byte b = 0; - if (!this->m_Stream.ReadByte(b)) - { - b = 0xFF; // check it - this->NumExtraBytes++; - } - m_NormalValue = (b << (kNumBigValueBits - this->m_BitPos)) | m_NormalValue; - this->m_Value = (this->m_Value << 8) | kInvertTable[b]; - } - } - - UInt32 GetValue(int numBits) - { - Normalize(); - return ((this->m_Value >> (8 - this->m_BitPos)) & kMask) >> (kNumValueBits - numBits); - } - - void MovePos(int numBits) - { - this->m_BitPos += numBits; - m_NormalValue >>= numBits; - } - - UInt32 ReadBits(int numBits) - { - Normalize(); - UInt32 res = m_NormalValue & ( (1 << numBits) - 1); - MovePos(numBits); - return res; - } -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BitmDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/BitmDecoder.h deleted file mode 100644 index f58ec29e5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BitmDecoder.h +++ /dev/null @@ -1,66 +0,0 @@ -// BitmDecoder.h -- the Most Significant Bit of byte is First - -#ifndef __BITM_DECODER_H -#define __BITM_DECODER_H - -#include "../IStream.h" - -namespace NBitm { - -const int kNumBigValueBits = 8 * 4; -const int kNumValueBytes = 3; -const int kNumValueBits = 8 * kNumValueBytes; - -const UInt32 kMask = (1 << kNumValueBits) - 1; - -template -class CDecoder -{ - UInt32 m_BitPos; - UInt32 m_Value; -public: - TInByte m_Stream; - bool Create(UInt32 bufferSize) { return m_Stream.Create(bufferSize); } - void SetStream(ISequentialInStream *inStream) { m_Stream.SetStream(inStream);} - void ReleaseStream() { m_Stream.ReleaseStream();} - - void Init() - { - m_Stream.Init(); - m_BitPos = kNumBigValueBits; - Normalize(); - } - - UInt64 GetProcessedSize() const - { return m_Stream.GetProcessedSize() - (kNumBigValueBits - m_BitPos) / 8; } - UInt32 GetBitPosition() const { return (m_BitPos & 7); } - - void Normalize() - { - for (;m_BitPos >= 8; m_BitPos -= 8) - m_Value = (m_Value << 8) | m_Stream.ReadByte(); - } - - UInt32 GetValue(UInt32 numBits) const - { - // return (m_Value << m_BitPos) >> (kNumBigValueBits - numBits); - return ((m_Value >> (8 - m_BitPos)) & kMask) >> (kNumValueBits - numBits); - } - - void MovePos(UInt32 numBits) - { - m_BitPos += numBits; - Normalize(); - } - - UInt32 ReadBits(UInt32 numBits) - { - UInt32 res = GetValue(numBits); - MovePos(numBits); - return res; - } -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.cpp deleted file mode 100644 index 6cacc66ac..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// BranchCoder.cpp - -#include "StdAfx.h" - -#include "BranchCoder.h" - -STDMETHODIMP CBranchConverter::Init() -{ - _bufferPos = 0; - SubInit(); - return S_OK; -} - -STDMETHODIMP_(UInt32) CBranchConverter::Filter(Byte *data, UInt32 size) -{ - UInt32 processedSize = SubFilter(data, size); - _bufferPos += processedSize; - return processedSize; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.h deleted file mode 100644 index 473286af3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BranchCoder.h +++ /dev/null @@ -1,44 +0,0 @@ -// BranchCoder.h - -#ifndef __COMPRESS_BRANCH_CODER_H -#define __COMPRESS_BRANCH_CODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -class CBranchConverter: - public ICompressFilter, - public CMyUnknownImp -{ -protected: - UInt32 _bufferPos; - virtual void SubInit() {} - virtual UInt32 SubFilter(Byte *data, UInt32 size) = 0; -public: - MY_UNKNOWN_IMP; - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); -}; - -#define MyClassEncoderA(Name) class C ## Name: public CBranchConverter \ - { public: UInt32 SubFilter(Byte *data, UInt32 size); }; - -#define MyClassDecoderA(Name) class C ## Name: public CBranchConverter \ - { public: UInt32 SubFilter(Byte *data, UInt32 size); }; - -#define MyClassEncoderB(Name, ADD_ITEMS, ADD_INIT) class C ## Name: public CBranchConverter, public ADD_ITEMS \ - { public: UInt32 SubFilter(Byte *data, UInt32 size); ADD_INIT}; - -#define MyClassDecoderB(Name, ADD_ITEMS, ADD_INIT) class C ## Name: public CBranchConverter, public ADD_ITEMS \ - { public: UInt32 SubFilter(Byte *data, UInt32 size); ADD_INIT}; - -#define MyClassA(Name, id, subId) \ -MyClassEncoderA(Name ## _Encoder) \ -MyClassDecoderA(Name ## _Decoder) - -#define MyClassB(Name, id, subId, ADD_ITEMS, ADD_INIT) \ -MyClassEncoderB(Name ## _Encoder, ADD_ITEMS, ADD_INIT) \ -MyClassDecoderB(Name ## _Decoder, ADD_ITEMS, ADD_INIT) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.cpp deleted file mode 100644 index 238dbe311..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// BranchMisc.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Bra.h" -} - -#include "BranchMisc.h" - -UInt32 CBC_ARM_Encoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::ARM_Convert(data, size, _bufferPos, 1); } - -UInt32 CBC_ARM_Decoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::ARM_Convert(data, size, _bufferPos, 0); } - -UInt32 CBC_ARMT_Encoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::ARMT_Convert(data, size, _bufferPos, 1); } - -UInt32 CBC_ARMT_Decoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::ARMT_Convert(data, size, _bufferPos, 0); } - -UInt32 CBC_PPC_Encoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::PPC_Convert(data, size, _bufferPos, 1); } - -UInt32 CBC_PPC_Decoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::PPC_Convert(data, size, _bufferPos, 0); } - -UInt32 CBC_SPARC_Encoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::SPARC_Convert(data, size, _bufferPos, 1); } - -UInt32 CBC_SPARC_Decoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::SPARC_Convert(data, size, _bufferPos, 0); } - -UInt32 CBC_IA64_Encoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::IA64_Convert(data, size, _bufferPos, 1); } - -UInt32 CBC_IA64_Decoder::SubFilter(Byte *data, UInt32 size) - { return (UInt32)::IA64_Convert(data, size, _bufferPos, 0); } diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.h b/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.h deleted file mode 100644 index 053e923a9..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BranchMisc.h +++ /dev/null @@ -1,14 +0,0 @@ -// BranchMisc.h - -#ifndef __COMPRESS_BRANCH_MISC_H -#define __COMPRESS_BRANCH_MISC_H - -#include "BranchCoder.h" - -MyClassA(BC_ARM, 0x05, 1) -MyClassA(BC_ARMT, 0x07, 1) -MyClassA(BC_PPC, 0x02, 5) -MyClassA(BC_SPARC, 0x08, 5) -MyClassA(BC_IA64, 0x04, 1) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/BranchRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/BranchRegister.cpp deleted file mode 100644 index bc55dd668..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/BranchRegister.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// BranchRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "BranchMisc.h" - -#define CREATE_CODEC(x) \ - static void *CreateCodec ## x() { return (void *)(ICompressFilter *)(new C ## x ## _Decoder); } \ - static void *CreateCodec ## x ## Out() { return (void *)(ICompressFilter *)(new C ## x ## _Encoder); } - -CREATE_CODEC(BC_PPC) -CREATE_CODEC(BC_IA64) -CREATE_CODEC(BC_ARM) -CREATE_CODEC(BC_ARMT) -CREATE_CODEC(BC_SPARC) - -#define METHOD_ITEM(x, id1, id2, name) { CreateCodec ## x, CreateCodec ## x ## Out, 0x03030000 + (id1 * 256) + id2, name, 1, true } - -static CCodecInfo g_CodecsInfo[] = -{ - METHOD_ITEM(BC_PPC, 0x02, 0x05, L"PPC"), - METHOD_ITEM(BC_IA64, 0x04, 1, L"IA64"), - METHOD_ITEM(BC_ARM, 0x05, 1, L"ARM"), - METHOD_ITEM(BC_ARMT, 0x07, 1, L"ARMT"), - METHOD_ITEM(BC_SPARC, 0x08, 0x05, L"SPARC") -}; - -REGISTER_CODECS(Branch) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.cpp deleted file mode 100644 index f21a7acfe..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// ByteSwap.cpp - -#include "StdAfx.h" - -#include "ByteSwap.h" - -STDMETHODIMP CByteSwap2::Init() { return S_OK; } - -STDMETHODIMP_(UInt32) CByteSwap2::Filter(Byte *data, UInt32 size) -{ - const UInt32 kStep = 2; - UInt32 i; - for (i = 0; i + kStep <= size; i += kStep) - { - Byte b = data[i]; - data[i] = data[i + 1]; - data[i + 1] = b; - } - return i; -} - -STDMETHODIMP CByteSwap4::Init() { return S_OK; } - -STDMETHODIMP_(UInt32) CByteSwap4::Filter(Byte *data, UInt32 size) -{ - const UInt32 kStep = 4; - UInt32 i; - for (i = 0; i + kStep <= size; i += kStep) - { - Byte b0 = data[i]; - Byte b1 = data[i + 1]; - data[i] = data[i + 3]; - data[i + 1] = data[i + 2]; - data[i + 2] = b1; - data[i + 3] = b0; - } - return i; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.h b/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.h deleted file mode 100644 index ecf983db4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwap.h +++ /dev/null @@ -1,30 +0,0 @@ -// ByteSwap.h - -#ifndef __COMPRESS_BYTE_SWAP_H -#define __COMPRESS_BYTE_SWAP_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -class CByteSwap2: - public ICompressFilter, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); -}; - -class CByteSwap4: - public ICompressFilter, - public CMyUnknownImp -{ -public: - MY_UNKNOWN_IMP - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwapRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwapRegister.cpp deleted file mode 100644 index c3413f67b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ByteSwapRegister.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// ByteSwapRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "ByteSwap.h" - -static void *CreateCodec2() { return (void *)(ICompressFilter *)(new CByteSwap2); } -static void *CreateCodec4() { return (void *)(ICompressFilter *)(new CByteSwap4); } - -static CCodecInfo g_CodecsInfo[] = -{ - { CreateCodec2, CreateCodec4, 0x020302, L"Swap2", 1, true }, - { CreateCodec4, CreateCodec4, 0x020304, L"Swap4", 1, true } -}; - -REGISTER_CODECS(ByteSwap) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Codec.def b/desmume/src/windows/7z/CPP/7zip/Compress/Codec.def deleted file mode 100644 index aab87ef8e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Codec.def +++ /dev/null @@ -1,4 +0,0 @@ -EXPORTS - CreateObject PRIVATE - GetNumberOfMethods PRIVATE - GetMethodProperty PRIVATE diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/CodecExports.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/CodecExports.cpp deleted file mode 100644 index 0cf84e73f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/CodecExports.cpp +++ /dev/null @@ -1,157 +0,0 @@ -// CodecExports.cpp - -#include "StdAfx.h" - -#include "../../Common/ComTry.h" -#include "../../Windows/PropVariant.h" -#include "../Common/RegisterCodec.h" -#include "../ICoder.h" - -extern unsigned int g_NumCodecs; -extern const CCodecInfo *g_Codecs[]; - -static const UInt16 kDecodeId = 0x2790; - -DEFINE_GUID(CLSID_CCodec, -0x23170F69, 0x40C1, kDecodeId, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); - -static inline HRESULT SetPropString(const char *s, unsigned int size, PROPVARIANT *value) -{ - if ((value->bstrVal = ::SysAllocStringByteLen(s, size)) != 0) - value->vt = VT_BSTR; - return S_OK; -} - -static inline HRESULT SetPropGUID(const GUID &guid, PROPVARIANT *value) -{ - return SetPropString((const char *)&guid, sizeof(GUID), value); -} - -static HRESULT SetClassID(CMethodId id, bool encode, PROPVARIANT *value) -{ - GUID clsId = CLSID_CCodec; - for (int i = 0; i < sizeof(id); i++, id >>= 8) - clsId.Data4[i] = (Byte)(id & 0xFF); - if (encode) - clsId.Data3++; - return SetPropGUID(clsId, value); -} - -static HRESULT FindCodecClassId(const GUID *clsID, UInt32 isCoder2, bool isFilter, bool &encode, int &index) -{ - index = -1; - if (clsID->Data1 != CLSID_CCodec.Data1 || - clsID->Data2 != CLSID_CCodec.Data2 || - (clsID->Data3 & ~1) != kDecodeId) - return S_OK; - encode = (clsID->Data3 != kDecodeId); - UInt64 id = 0; - for (int j = 0; j < 8; j++) - id |= ((UInt64)clsID->Data4[j]) << (8 * j); - for (unsigned i = 0; i < g_NumCodecs; i++) - { - const CCodecInfo &codec = *g_Codecs[i]; - if (id != codec.Id || encode && !codec.CreateEncoder || !encode && !codec.CreateDecoder) - continue; - if (!isFilter && codec.IsFilter || isFilter && !codec.IsFilter || - codec.NumInStreams != 1 && !isCoder2 || codec.NumInStreams == 1 && isCoder2) - return E_NOINTERFACE; - index = i; - return S_OK; - } - return S_OK; -} - -STDAPI CreateCoder2(bool encode, UInt32 index, const GUID *iid, void **outObject) -{ - COM_TRY_BEGIN - *outObject = 0; - bool isCoder = (*iid == IID_ICompressCoder) != 0; - bool isCoder2 = (*iid == IID_ICompressCoder2) != 0; - bool isFilter = (*iid == IID_ICompressFilter) != 0; - const CCodecInfo &codec = *g_Codecs[index]; - if (!isFilter && codec.IsFilter || isFilter && !codec.IsFilter || - codec.NumInStreams != 1 && !isCoder2 || codec.NumInStreams == 1 && isCoder2) - return E_NOINTERFACE; - if (encode) - { - if (!codec.CreateEncoder) - return CLASS_E_CLASSNOTAVAILABLE; - *outObject = codec.CreateEncoder(); - } - else - { - if (!codec.CreateDecoder) - return CLASS_E_CLASSNOTAVAILABLE; - *outObject = codec.CreateDecoder(); - } - if (isCoder) - ((ICompressCoder *)*outObject)->AddRef(); - else if (isCoder2) - ((ICompressCoder2 *)*outObject)->AddRef(); - else - ((ICompressFilter *)*outObject)->AddRef(); - return S_OK; - COM_TRY_END -} - -STDAPI CreateCoder(const GUID *clsid, const GUID *iid, void **outObject) -{ - *outObject = 0; - bool isCoder = (*iid == IID_ICompressCoder) != 0; - bool isCoder2 = (*iid == IID_ICompressCoder2) != 0; - bool isFilter = (*iid == IID_ICompressFilter) != 0; - if (!isCoder && !isCoder2 && !isFilter) - return E_NOINTERFACE; - bool encode; - int codecIndex; - HRESULT res = FindCodecClassId(clsid, isCoder2, isFilter, encode, codecIndex); - if (res != S_OK) - return res; - if (codecIndex < 0) - return CLASS_E_CLASSNOTAVAILABLE; - return CreateCoder2(encode, codecIndex, iid, outObject); -} - -STDAPI GetMethodProperty(UInt32 codecIndex, PROPID propID, PROPVARIANT *value) -{ - ::VariantClear((VARIANTARG *)value); - const CCodecInfo &codec = *g_Codecs[codecIndex]; - switch(propID) - { - case NMethodPropID::kID: - { - value->uhVal.QuadPart = (UInt64)codec.Id; - value->vt = VT_UI8; - break; - } - case NMethodPropID::kName: - if ((value->bstrVal = ::SysAllocString(codec.Name)) != 0) - value->vt = VT_BSTR; - break; - case NMethodPropID::kDecoder: - if (codec.CreateDecoder) - return SetClassID(codec.Id, false, value); - break; - case NMethodPropID::kEncoder: - if (codec.CreateEncoder) - return SetClassID(codec.Id, true, value); - break; - case NMethodPropID::kInStreams: - { - if (codec.NumInStreams != 1) - { - value->vt = VT_UI4; - value->ulVal = (ULONG)codec.NumInStreams; - } - break; - } - } - return S_OK; -} - -STDAPI GetNumberOfMethods(UINT32 *numCodecs) -{ - *numCodecs = g_NumCodecs; - return S_OK; -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.cpp deleted file mode 100644 index 4c2f5e0fc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// Compress/CopyCoder.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "../Common/StreamUtils.h" - -#include "CopyCoder.h" - -namespace NCompress { - -static const UInt32 kBufferSize = 1 << 17; - -CCopyCoder::~CCopyCoder() -{ - ::MidFree(_buffer); -} - -STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream, - ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, - ICompressProgressInfo *progress) -{ - if (_buffer == 0) - { - _buffer = (Byte *)::MidAlloc(kBufferSize); - if (_buffer == 0) - return E_OUTOFMEMORY; - } - - TotalSize = 0; - for (;;) - { - UInt32 realProcessedSize; - UInt32 size = kBufferSize; - if (outSize != 0) - if (size > *outSize - TotalSize) - size = (UInt32)(*outSize - TotalSize); - RINOK(inStream->Read(_buffer, size, &realProcessedSize)); - if (realProcessedSize == 0) - break; - RINOK(WriteStream(outStream, _buffer, realProcessedSize)); - TotalSize += realProcessedSize; - if (progress != NULL) - { - RINOK(progress->SetRatioInfo(&TotalSize, &TotalSize)); - } - } - return S_OK; -} - -STDMETHODIMP CCopyCoder::GetInStreamProcessedSize(UInt64 *value) -{ - *value = TotalSize; - return S_OK; -} - -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.h deleted file mode 100644 index 7c9d3d355..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/CopyCoder.h +++ /dev/null @@ -1,32 +0,0 @@ -// Compress/CopyCoder.h - -#ifndef __COMPRESS_COPY_CODER_H -#define __COMPRESS_COPY_CODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -namespace NCompress { - -class CCopyCoder: - public ICompressCoder, - public ICompressGetInStreamProcessedSize, - public CMyUnknownImp -{ - Byte *_buffer; -public: - UInt64 TotalSize; - CCopyCoder(): TotalSize(0) , _buffer(0) {}; - ~CCopyCoder(); - - MY_UNKNOWN_IMP1(ICompressGetInStreamProcessedSize) - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/CopyRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/CopyRegister.cpp deleted file mode 100644 index 3ef245978..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/CopyRegister.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// CopyRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "CopyCoder.h" - -static void *CreateCodec() { return (void *)(ICompressCoder *)(new NCompress::CCopyCoder); } - -static CCodecInfo g_CodecInfo = -{ CreateCodec, CreateCodec, 0x00, L"Copy", 1, false }; - -REGISTER_CODEC(Copy) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Deflate64Register.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Deflate64Register.cpp deleted file mode 100644 index 6d6a904d1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Deflate64Register.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// Deflate64Register.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "DeflateDecoder.h" - -static void *CreateCodecDeflate64() { return (void *)(ICompressCoder *)(new NCompress::NDeflate::NDecoder::CCOMCoder64); } -#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY) -#include "DeflateEncoder.h" -static void *CreateCodecOutDeflate64() { return (void *)(ICompressCoder *)(new NCompress::NDeflate::NEncoder::CCOMCoder64); } -#else -#define CreateCodecOutDeflate64 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodecDeflate64, CreateCodecOutDeflate64, 0x040109, L"Deflate64", 1, false }; - -REGISTER_CODEC(Deflate64) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateConst.h b/desmume/src/windows/7z/CPP/7zip/Compress/DeflateConst.h deleted file mode 100644 index b5c28d79e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateConst.h +++ /dev/null @@ -1,134 +0,0 @@ -// DeflateConst.h - -#ifndef __DEFLATE_CONST_H -#define __DEFLATE_CONST_H - -namespace NCompress { -namespace NDeflate { - -const int kNumHuffmanBits = 15; - -const UInt32 kHistorySize32 = (1 << 15); -const UInt32 kHistorySize64 = (1 << 16); - -const UInt32 kDistTableSize32 = 30; -const UInt32 kDistTableSize64 = 32; - -const UInt32 kNumLenSymbols32 = 256; -const UInt32 kNumLenSymbols64 = 255; // don't change it. It must be <= 255. -const UInt32 kNumLenSymbolsMax = kNumLenSymbols32; - -const UInt32 kNumLenSlots = 29; - -const UInt32 kFixedDistTableSize = 32; -const UInt32 kFixedLenTableSize = 31; - -const UInt32 kSymbolEndOfBlock = 0x100; -const UInt32 kSymbolMatch = kSymbolEndOfBlock + 1; - -const UInt32 kMainTableSize = kSymbolMatch + kNumLenSlots; -const UInt32 kFixedMainTableSize = kSymbolMatch + kFixedLenTableSize; - -const UInt32 kLevelTableSize = 19; - -const UInt32 kTableDirectLevels = 16; -const UInt32 kTableLevelRepNumber = kTableDirectLevels; -const UInt32 kTableLevel0Number = kTableLevelRepNumber + 1; -const UInt32 kTableLevel0Number2 = kTableLevel0Number + 1; - -const UInt32 kLevelMask = 0xF; - -const Byte kLenStart32[kFixedLenTableSize] = - {0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224, 255, 0, 0}; -const Byte kLenStart64[kFixedLenTableSize] = - {0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224, 0, 0, 0}; - -const Byte kLenDirectBits32[kFixedLenTableSize] = - {0,0,0,0,0,0,0,0,1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0}; -const Byte kLenDirectBits64[kFixedLenTableSize] = - {0,0,0,0,0,0,0,0,1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 16, 0, 0}; - -const UInt32 kDistStart[kDistTableSize64] = - {0,1,2,3,4,6,8,12,16,24,32,48,64,96,128,192,256,384,512,768, - 1024,1536,2048,3072,4096,6144,8192,12288,16384,24576,32768,49152}; -const Byte kDistDirectBits[kDistTableSize64] = - {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14}; - -const Byte kLevelDirectBits[3] = {2, 3, 7}; - -const Byte kCodeLengthAlphabetOrder[kLevelTableSize] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - -const UInt32 kMatchMinLen = 3; -const UInt32 kMatchMaxLen32 = kNumLenSymbols32 + kMatchMinLen - 1; //256 + 2 -const UInt32 kMatchMaxLen64 = kNumLenSymbols64 + kMatchMinLen - 1; //255 + 2 -const UInt32 kMatchMaxLen = kMatchMaxLen32; - -const int kFinalBlockFieldSize = 1; - -namespace NFinalBlockField -{ - enum - { - kNotFinalBlock = 0, - kFinalBlock = 1 - }; -} - -const int kBlockTypeFieldSize = 2; - -namespace NBlockType -{ - enum - { - kStored = 0, - kFixedHuffman = 1, - kDynamicHuffman = 2 - }; -} - -const int kNumLenCodesFieldSize = 5; -const int kNumDistCodesFieldSize = 5; -const int kNumLevelCodesFieldSize = 4; - -const UInt32 kNumLitLenCodesMin = 257; -const UInt32 kNumDistCodesMin = 1; -const UInt32 kNumLevelCodesMin = 4; - -const int kLevelFieldSize = 3; - -const int kStoredBlockLengthFieldSize = 16; - -struct CLevels -{ - Byte litLenLevels[kFixedMainTableSize]; - Byte distLevels[kFixedDistTableSize]; - - void SubClear() - { - UInt32 i; - for(i = kNumLitLenCodesMin; i < kFixedMainTableSize; i++) - litLenLevels[i] = 0; - for(i = 0; i < kFixedDistTableSize; i++) - distLevels[i] = 0; - } - - void SetFixedLevels() - { - int i; - - for (i = 0; i < 144; i++) - litLenLevels[i] = 8; - for (; i < 256; i++) - litLenLevels[i] = 9; - for (; i < 280; i++) - litLenLevels[i] = 7; - for (; i < 288; i++) - litLenLevels[i] = 8; - for (i = 0; i < kFixedDistTableSize; i++) // test it: InfoZip only uses kDistTableSize - distLevels[i] = 5; - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.cpp deleted file mode 100644 index 31a61371b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.cpp +++ /dev/null @@ -1,345 +0,0 @@ -// DeflateDecoder.cpp - -#include "StdAfx.h" - -#include "DeflateDecoder.h" - -namespace NCompress { -namespace NDeflate { -namespace NDecoder { - -static const int kLenIdFinished = -1; -static const int kLenIdNeedInit = -2; - -CCoder::CCoder(bool deflate64Mode, bool deflateNSIS): - _deflate64Mode(deflate64Mode), - _deflateNSIS(deflateNSIS), - _keepHistory(false), - ZlibMode(false) {} - -UInt32 CCoder::ReadBits(int numBits) -{ - return m_InBitStream.ReadBits(numBits); -} - -bool CCoder::DeCodeLevelTable(Byte *values, int numSymbols) -{ - int i = 0; - do - { - UInt32 number = m_LevelDecoder.DecodeSymbol(&m_InBitStream); - if (number < kTableDirectLevels) - values[i++] = (Byte)number; - else if (number < kLevelTableSize) - { - if (number == kTableLevelRepNumber) - { - if (i == 0) - return false; - int num = ReadBits(2) + 3; - for (; num > 0 && i < numSymbols; num--, i++) - values[i] = values[i - 1]; - } - else - { - int num; - if (number == kTableLevel0Number) - num = ReadBits(3) + 3; - else - num = ReadBits(7) + 11; - for (;num > 0 && i < numSymbols; num--) - values[i++] = 0; - } - } - else - return false; - } - while(i < numSymbols); - return true; -} - -#define RIF(x) { if (!(x)) return false; } - -bool CCoder::ReadTables(void) -{ - m_FinalBlock = (ReadBits(kFinalBlockFieldSize) == NFinalBlockField::kFinalBlock); - UInt32 blockType = ReadBits(kBlockTypeFieldSize); - if (blockType > NBlockType::kDynamicHuffman) - return false; - - if (blockType == NBlockType::kStored) - { - m_StoredMode = true; - UInt32 currentBitPosition = m_InBitStream.GetBitPosition(); - int numBitsForAlign = (int)(currentBitPosition > 0 ? (8 - currentBitPosition): 0); - ReadBits(numBitsForAlign); - m_StoredBlockSize = ReadBits(kStoredBlockLengthFieldSize); - if (_deflateNSIS) - return true; - return (m_StoredBlockSize == (UInt16)~ReadBits(kStoredBlockLengthFieldSize)); - } - - m_StoredMode = false; - - CLevels levels; - if (blockType == NBlockType::kFixedHuffman) - { - levels.SetFixedLevels(); - _numDistLevels = _deflate64Mode ? kDistTableSize64 : kDistTableSize32; - } - else - { - int numLitLenLevels = ReadBits(kNumLenCodesFieldSize) + kNumLitLenCodesMin; - _numDistLevels = ReadBits(kNumDistCodesFieldSize) + kNumDistCodesMin; - int numLevelCodes = ReadBits(kNumLevelCodesFieldSize) + kNumLevelCodesMin; - - if (!_deflate64Mode) - if (_numDistLevels > kDistTableSize32) - return false; - - Byte levelLevels[kLevelTableSize]; - for (int i = 0; i < kLevelTableSize; i++) - { - int position = kCodeLengthAlphabetOrder[i]; - if(i < numLevelCodes) - levelLevels[position] = (Byte)ReadBits(kLevelFieldSize); - else - levelLevels[position] = 0; - } - - RIF(m_LevelDecoder.SetCodeLengths(levelLevels)); - - Byte tmpLevels[kFixedMainTableSize + kFixedDistTableSize]; - if (!DeCodeLevelTable(tmpLevels, numLitLenLevels + _numDistLevels)) - return false; - - levels.SubClear(); - memcpy(levels.litLenLevels, tmpLevels, numLitLenLevels); - memcpy(levels.distLevels, tmpLevels + numLitLenLevels, _numDistLevels); - } - RIF(m_MainDecoder.SetCodeLengths(levels.litLenLevels)); - return m_DistDecoder.SetCodeLengths(levels.distLevels); -} - -HRESULT CCoder::CodeSpec(UInt32 curSize) -{ - if (_remainLen == kLenIdFinished) - return S_OK; - if (_remainLen == kLenIdNeedInit) - { - if (!_keepHistory) - if (!m_OutWindowStream.Create(_deflate64Mode ? kHistorySize64: kHistorySize32)) - return E_OUTOFMEMORY; - if (!m_InBitStream.Create(1 << 17)) - return E_OUTOFMEMORY; - m_OutWindowStream.Init(_keepHistory); - m_InBitStream.Init(); - m_FinalBlock = false; - _remainLen = 0; - _needReadTable = true; - } - - if (curSize == 0) - return S_OK; - - while(_remainLen > 0 && curSize > 0) - { - _remainLen--; - Byte b = m_OutWindowStream.GetByte(_rep0); - m_OutWindowStream.PutByte(b); - curSize--; - } - - while(curSize > 0) - { - if (_needReadTable) - { - if (m_FinalBlock) - { - _remainLen = kLenIdFinished; - break; - } - if (!ReadTables()) - return S_FALSE; - _needReadTable = false; - } - - if(m_StoredMode) - { - for (; m_StoredBlockSize > 0 && curSize > 0; m_StoredBlockSize--, curSize--) - m_OutWindowStream.PutByte((Byte)m_InBitStream.ReadBits(8)); - _needReadTable = (m_StoredBlockSize == 0); - continue; - } - while(curSize > 0) - { - if (m_InBitStream.NumExtraBytes > 4) - return S_FALSE; - - UInt32 number = m_MainDecoder.DecodeSymbol(&m_InBitStream); - if (number < 0x100) - { - m_OutWindowStream.PutByte((Byte)number); - curSize--; - continue; - } - else if (number == kSymbolEndOfBlock) - { - _needReadTable = true; - break; - } - else if (number < kMainTableSize) - { - number -= kSymbolMatch; - UInt32 len; - { - int numBits; - if (_deflate64Mode) - { - len = kLenStart64[number]; - numBits = kLenDirectBits64[number]; - } - else - { - len = kLenStart32[number]; - numBits = kLenDirectBits32[number]; - } - len += kMatchMinLen + m_InBitStream.ReadBits(numBits); - } - UInt32 locLen = len; - if (locLen > curSize) - locLen = (UInt32)curSize; - number = m_DistDecoder.DecodeSymbol(&m_InBitStream); - if (number >= _numDistLevels) - return S_FALSE; - UInt32 distance = kDistStart[number] + m_InBitStream.ReadBits(kDistDirectBits[number]); - if (!m_OutWindowStream.CopyBlock(distance, locLen)) - return S_FALSE; - curSize -= locLen; - len -= locLen; - if (len != 0) - { - _remainLen = (Int32)len; - _rep0 = distance; - break; - } - } - else - return S_FALSE; - } - } - return S_OK; -} - -HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - SetInStream(inStream); - m_OutWindowStream.SetStream(outStream); - SetOutStreamSize(outSize); - CCoderReleaser flusher(this); - - const UInt64 start = m_OutWindowStream.GetProcessedSize(); - for (;;) - { - UInt32 curSize = 1 << 18; - if (outSize != 0) - { - const UInt64 rem = *outSize - (m_OutWindowStream.GetProcessedSize() - start); - if (curSize > rem) - curSize = (UInt32)rem; - } - if (curSize == 0) - break; - RINOK(CodeSpec(curSize)); - if (_remainLen == kLenIdFinished) - break; - if (progress != NULL) - { - const UInt64 inSize = m_InBitStream.GetProcessedSize(); - const UInt64 nowPos64 = m_OutWindowStream.GetProcessedSize() - start; - RINOK(progress->SetRatioInfo(&inSize, &nowPos64)); - } - } - if (_remainLen == kLenIdFinished && ZlibMode) - { - UInt32 currentBitPosition = m_InBitStream.GetBitPosition(); - int numBitsForAlign = (int)(currentBitPosition > 0 ? (8 - currentBitPosition): 0); - ReadBits(numBitsForAlign); - for (int i = 0; i < 4; i++) - ZlibFooter[i] = (Byte)m_InBitStream.ReadBits(8); - } - flusher.NeedFlush = false; - return Flush(); -} - - -#ifdef _NO_EXCEPTIONS - -#define DEFLATE_TRY_BEGIN -#define DEFLATE_TRY_END - -#else - -#define DEFLATE_TRY_BEGIN try { -#define DEFLATE_TRY_END } \ - catch(const CInBufferException &e) { return e.ErrorCode; } \ - catch(const CLzOutWindowException &e) { return e.ErrorCode; } \ - catch(...) { return S_FALSE; } - -#endif - -HRESULT CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - DEFLATE_TRY_BEGIN - return CodeReal(inStream, outStream, inSize, outSize, progress); - DEFLATE_TRY_END -} - -STDMETHODIMP CCoder::GetInStreamProcessedSize(UInt64 *value) -{ - if (value == NULL) - return E_INVALIDARG; - *value = m_InBitStream.GetProcessedSize(); - return S_OK; -} - -STDMETHODIMP CCoder::SetInStream(ISequentialInStream *inStream) -{ - m_InBitStream.SetStream(inStream); - return S_OK; -} - -STDMETHODIMP CCoder::ReleaseInStream() -{ - m_InBitStream.ReleaseStream(); - return S_OK; -} - -STDMETHODIMP CCoder::SetOutStreamSize(const UInt64 * /* outSize */) -{ - _remainLen = kLenIdNeedInit; - m_OutWindowStream.Init(_keepHistory); - return S_OK; -} - -#ifndef NO_READ_FROM_CODER - -STDMETHODIMP CCoder::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - DEFLATE_TRY_BEGIN - if (processedSize) - *processedSize = 0; - const UInt64 startPos = m_OutWindowStream.GetProcessedSize(); - m_OutWindowStream.SetMemStream((Byte *)data); - RINOK(CodeSpec(size)); - if (processedSize) - *processedSize = (UInt32)(m_OutWindowStream.GetProcessedSize() - startPos); - return Flush(); - DEFLATE_TRY_END -} - -#endif - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.h deleted file mode 100644 index 3a81e1657..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateDecoder.h +++ /dev/null @@ -1,136 +0,0 @@ -// DeflateDecoder.h - -#ifndef __DEFLATE_DECODER_H -#define __DEFLATE_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" - -#include "BitlDecoder.h" -#include "DeflateConst.h" -#include "HuffmanDecoder.h" -#include "LzOutWindow.h" - -namespace NCompress { -namespace NDeflate { -namespace NDecoder { - -class CCoder: - public ICompressCoder, - public ICompressGetInStreamProcessedSize, - #ifndef NO_READ_FROM_CODER - public ICompressSetInStream, - public ICompressSetOutStreamSize, - public ISequentialInStream, - #endif - public CMyUnknownImp -{ - CLzOutWindow m_OutWindowStream; - NBitl::CDecoder m_InBitStream; - NCompress::NHuffman::CDecoder m_MainDecoder; - NCompress::NHuffman::CDecoder m_DistDecoder; - NCompress::NHuffman::CDecoder m_LevelDecoder; - - UInt32 m_StoredBlockSize; - - bool m_FinalBlock; - bool m_StoredMode; - UInt32 _numDistLevels; - - - bool _deflateNSIS; - bool _deflate64Mode; - bool _keepHistory; - Int32 _remainLen; - UInt32 _rep0; - bool _needReadTable; - - UInt32 ReadBits(int numBits); - - bool DeCodeLevelTable(Byte *values, int numSymbols); - bool ReadTables(); - - void ReleaseStreams() - { - m_OutWindowStream.ReleaseStream(); - ReleaseInStream(); - } - - HRESULT Flush() { return m_OutWindowStream.Flush(); } - class CCoderReleaser - { - CCoder *m_Coder; - public: - bool NeedFlush; - CCoderReleaser(CCoder *coder): m_Coder(coder), NeedFlush(true) {} - ~CCoderReleaser() - { - if (NeedFlush) - m_Coder->Flush(); - m_Coder->ReleaseStreams(); - } - }; - friend class CCoderReleaser; - - HRESULT CodeSpec(UInt32 curSize); -public: - bool ZlibMode; - Byte ZlibFooter[4]; - - CCoder(bool deflate64Mode, bool deflateNSIS = false); - void SetKeepHistory(bool keepHistory) { _keepHistory = keepHistory; } - - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - #ifndef NO_READ_FROM_CODER - MY_UNKNOWN_IMP4( - ICompressGetInStreamProcessedSize, - ICompressSetInStream, - ICompressSetOutStreamSize, - ISequentialInStream - ) - #else - MY_UNKNOWN_IMP1( - ICompressGetInStreamProcessedSize) - #endif - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - - #ifndef NO_READ_FROM_CODER - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - #endif - - // IGetInStreamProcessedSize - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); -}; - -class CCOMCoder : public CCoder -{ -public: - CCOMCoder(): CCoder(false) {} -}; - -class CNsisCOMCoder : public CCoder -{ -public: - CNsisCOMCoder(): CCoder(false, true) {} -}; - -class CCOMCoder64 : public CCoder -{ -public: - CCOMCoder64(): CCoder(true) {} -}; - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateNsisRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/DeflateNsisRegister.cpp deleted file mode 100644 index dbb128368..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateNsisRegister.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// DeflateNsisRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "DeflateDecoder.h" - -static void *CreateCodecDeflateNsis() { return (void *)(ICompressCoder *)(new NCompress::NDeflate::NDecoder::CNsisCOMCoder); } - -static CCodecInfo g_CodecInfo = - { CreateCodecDeflateNsis, 0, 0x040901, L"DeflateNSIS", 1, false }; - -REGISTER_CODEC(DeflateNsis) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/DeflateRegister.cpp deleted file mode 100644 index d8a9c8dc8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/DeflateRegister.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// DeflateRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "DeflateDecoder.h" - -static void *CreateCodecDeflate() { return (void *)(ICompressCoder *)(new NCompress::NDeflate::NDecoder::CCOMCoder); } - -#if !defined(EXTRACT_ONLY) && !defined(DEFLATE_EXTRACT_ONLY) -#include "DeflateEncoder.h" -static void *CreateCodecOutDeflate() { return (void *)(ICompressCoder *)(new NCompress::NDeflate::NEncoder::CCOMCoder); } -#else -#define CreateCodecOutDeflate 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodecDeflate, CreateCodecOutDeflate, 0x040108, L"Deflate", 1, false }; - -REGISTER_CODEC(Deflate) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/HuffmanDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/HuffmanDecoder.h deleted file mode 100644 index f71a58282..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/HuffmanDecoder.h +++ /dev/null @@ -1,89 +0,0 @@ -// Compress/HuffmanDecoder.h - -#ifndef __COMPRESS_HUFFMAN_DECODER_H -#define __COMPRESS_HUFFMAN_DECODER_H - -#include "../../Common/Types.h" - -namespace NCompress { -namespace NHuffman { - -const int kNumTableBits = 9; - -template -class CDecoder -{ - UInt32 m_Limits[kNumBitsMax + 1]; // m_Limits[i] = value limit for symbols with length = i - UInt32 m_Positions[kNumBitsMax + 1]; // m_Positions[i] = index in m_Symbols[] of first symbol with length = i - UInt32 m_Symbols[m_NumSymbols]; - Byte m_Lengths[1 << kNumTableBits]; // Table oh length for short codes. - -public: - - bool SetCodeLengths(const Byte *codeLengths) - { - int lenCounts[kNumBitsMax + 1]; - UInt32 tmpPositions[kNumBitsMax + 1]; - int i; - for(i = 1; i <= kNumBitsMax; i++) - lenCounts[i] = 0; - UInt32 symbol; - for (symbol = 0; symbol < m_NumSymbols; symbol++) - { - int len = codeLengths[symbol]; - if (len > kNumBitsMax) - return false; - lenCounts[len]++; - m_Symbols[symbol] = 0xFFFFFFFF; - } - lenCounts[0] = 0; - m_Positions[0] = m_Limits[0] = 0; - UInt32 startPos = 0; - UInt32 index = 0; - const UInt32 kMaxValue = (1 << kNumBitsMax); - for (i = 1; i <= kNumBitsMax; i++) - { - startPos += lenCounts[i] << (kNumBitsMax - i); - if (startPos > kMaxValue) - return false; - m_Limits[i] = (i == kNumBitsMax) ? kMaxValue : startPos; - m_Positions[i] = m_Positions[i - 1] + lenCounts[i - 1]; - tmpPositions[i] = m_Positions[i]; - if(i <= kNumTableBits) - { - UInt32 limit = (m_Limits[i] >> (kNumBitsMax - kNumTableBits)); - for (; index < limit; index++) - m_Lengths[index] = (Byte)i; - } - } - for (symbol = 0; symbol < m_NumSymbols; symbol++) - { - int len = codeLengths[symbol]; - if (len != 0) - m_Symbols[tmpPositions[len]++] = symbol; - } - return true; - } - - template - UInt32 DecodeSymbol(TBitDecoder *bitStream) - { - int numBits; - UInt32 value = bitStream->GetValue(kNumBitsMax); - if (value < m_Limits[kNumTableBits]) - numBits = m_Lengths[value >> (kNumBitsMax - kNumTableBits)]; - else - for (numBits = kNumTableBits + 1; value >= m_Limits[numBits]; numBits++); - bitStream->MovePos(numBits); - UInt32 index = m_Positions[numBits] + - ((value - m_Limits[numBits - 1]) >> (kNumBitsMax - numBits)); - if (index >= m_NumSymbols) - // throw CDecoderException(); // test it - return 0xFFFFFFFF; - return m_Symbols[index]; - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.cpp deleted file mode 100644 index 6c5e36284..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.cpp +++ /dev/null @@ -1,219 +0,0 @@ -// Implode/Decoder.cpp - -#include "StdAfx.h" - -#include "ImplodeDecoder.h" -#include "Common/Defs.h" - -namespace NCompress { -namespace NImplode { -namespace NDecoder { - -class CException -{ -public: - enum ECauseType - { - kData - } m_Cause; - CException(ECauseType cause): m_Cause(cause) {} -}; - -static const int kNumDistanceLowDirectBitsForBigDict = 7; -static const int kNumDistanceLowDirectBitsForSmallDict = 6; - -static const int kNumBitsInByte = 8; - -// static const int kLevelStructuresNumberFieldSize = kNumBitsInByte; -static const int kLevelStructuresNumberAdditionalValue = 1; - -static const int kNumLevelStructureLevelBits = 4; -static const int kLevelStructureLevelAdditionalValue = 1; - -static const int kNumLevelStructureRepNumberBits = 4; -static const int kLevelStructureRepNumberAdditionalValue = 1; - - -static const int kLiteralTableSize = (1 << kNumBitsInByte); -static const int kDistanceTableSize = 64; -static const int kLengthTableSize = 64; - -static const UInt32 kHistorySize = - (1 << MyMax(kNumDistanceLowDirectBitsForBigDict, - kNumDistanceLowDirectBitsForSmallDict)) * - kDistanceTableSize; // = 8 KB; - -static const int kNumAdditionalLengthBits = 8; - -static const UInt32 kMatchMinLenWhenLiteralsOn = 3; -static const UInt32 kMatchMinLenWhenLiteralsOff = 2; - -static const UInt32 kMatchMinLenMax = MyMax(kMatchMinLenWhenLiteralsOn, - kMatchMinLenWhenLiteralsOff); // 3 - -// static const UInt32 kMatchMaxLenMax = kMatchMinLenMax + (kLengthTableSize - 1) + (1 << kNumAdditionalLengthBits) - 1; // or 2 - -enum -{ - kMatchId = 0, - kLiteralId = 1 -}; - - -CCoder::CCoder(): - m_LiteralDecoder(kLiteralTableSize), - m_LengthDecoder(kLengthTableSize), - m_DistanceDecoder(kDistanceTableSize) -{ -} - -void CCoder::ReleaseStreams() -{ - m_OutWindowStream.ReleaseStream(); - m_InBitStream.ReleaseStream(); -} - -bool CCoder::ReadLevelItems(NImplode::NHuffman::CDecoder &decoder, - Byte *levels, int numLevelItems) -{ - int numCodedStructures = m_InBitStream.ReadBits(kNumBitsInByte) + - kLevelStructuresNumberAdditionalValue; - int currentIndex = 0; - for(int i = 0; i < numCodedStructures; i++) - { - int level = m_InBitStream.ReadBits(kNumLevelStructureLevelBits) + - kLevelStructureLevelAdditionalValue; - int rep = m_InBitStream.ReadBits(kNumLevelStructureRepNumberBits) + - kLevelStructureRepNumberAdditionalValue; - if (currentIndex + rep > numLevelItems) - throw CException(CException::kData); - for(int j = 0; j < rep; j++) - levels[currentIndex++] = (Byte)level; - } - if (currentIndex != numLevelItems) - return false; - return decoder.SetCodeLengths(levels); -} - - -bool CCoder::ReadTables(void) -{ - if (m_LiteralsOn) - { - Byte literalLevels[kLiteralTableSize]; - if (!ReadLevelItems(m_LiteralDecoder, literalLevels, kLiteralTableSize)) - return false; - } - - Byte lengthLevels[kLengthTableSize]; - if (!ReadLevelItems(m_LengthDecoder, lengthLevels, kLengthTableSize)) - return false; - - Byte distanceLevels[kDistanceTableSize]; - return ReadLevelItems(m_DistanceDecoder, distanceLevels, kDistanceTableSize); -} - -class CCoderReleaser -{ - CCoder *m_Coder; -public: - CCoderReleaser(CCoder *coder): m_Coder(coder) {} - ~CCoderReleaser() { m_Coder->ReleaseStreams(); } -}; - -HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - if (!m_InBitStream.Create(1 << 20)) - return E_OUTOFMEMORY; - if (!m_OutWindowStream.Create(kHistorySize)) - return E_OUTOFMEMORY; - if (outSize == NULL) - return E_INVALIDARG; - UInt64 pos = 0, unPackSize = *outSize; - - m_OutWindowStream.SetStream(outStream); - m_OutWindowStream.Init(false); - m_InBitStream.SetStream(inStream); - m_InBitStream.Init(); - CCoderReleaser coderReleaser(this); - - if (!ReadTables()) - return S_FALSE; - - while(pos < unPackSize) - { - if (progress != NULL && pos % (1 << 16) == 0) - { - UInt64 packSize = m_InBitStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &pos)); - } - if(m_InBitStream.ReadBits(1) == kMatchId) // match - { - UInt32 lowDistBits = m_InBitStream.ReadBits(m_NumDistanceLowDirectBits); - UInt32 distance = m_DistanceDecoder.DecodeSymbol(&m_InBitStream); - if (distance >= kDistanceTableSize) - return S_FALSE; - distance = (distance << m_NumDistanceLowDirectBits) + lowDistBits; - UInt32 lengthSymbol = m_LengthDecoder.DecodeSymbol(&m_InBitStream); - if (lengthSymbol >= kLengthTableSize) - return S_FALSE; - UInt32 length = lengthSymbol + m_MinMatchLength; - if (lengthSymbol == kLengthTableSize - 1) // special symbol = 63 - length += m_InBitStream.ReadBits(kNumAdditionalLengthBits); - while(distance >= pos && length > 0) - { - m_OutWindowStream.PutByte(0); - pos++; - length--; - } - if (length > 0) - m_OutWindowStream.CopyBlock(distance, length); - pos += length; - } - else - { - Byte b; - if (m_LiteralsOn) - { - UInt32 temp = m_LiteralDecoder.DecodeSymbol(&m_InBitStream); - if (temp >= kLiteralTableSize) - return S_FALSE; - b = (Byte)temp; - } - else - b = (Byte)m_InBitStream.ReadBits(kNumBitsInByte); - m_OutWindowStream.PutByte(b); - pos++; - } - } - if (pos > unPackSize) - return S_FALSE; - return m_OutWindowStream.Flush(); -} - -STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress); } - catch(const CLzOutWindowException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -STDMETHODIMP CCoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - if (size < 1) - return E_INVALIDARG; - Byte flag = data[0]; - m_BigDictionaryOn = ((flag & 2) != 0); - m_NumDistanceLowDirectBits = m_BigDictionaryOn ? - kNumDistanceLowDirectBitsForBigDict: - kNumDistanceLowDirectBitsForSmallDict; - m_LiteralsOn = ((flag & 4) != 0); - m_MinMatchLength = m_LiteralsOn ? - kMatchMinLenWhenLiteralsOn : - kMatchMinLenWhenLiteralsOff; - return S_OK; -} - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.h deleted file mode 100644 index 2b45f05da..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeDecoder.h +++ /dev/null @@ -1,57 +0,0 @@ -// ImplodeDecoder.h - -#ifndef __COMPRESS_IMPLODE_DECODER_H -#define __COMPRESS_IMPLODE_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "ImplodeHuffmanDecoder.h" -#include "LzOutWindow.h" - -namespace NCompress { -namespace NImplode { -namespace NDecoder { - -class CCoder: - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ - CLzOutWindow m_OutWindowStream; - NBitl::CDecoder m_InBitStream; - - NImplode::NHuffman::CDecoder m_LiteralDecoder; - NImplode::NHuffman::CDecoder m_LengthDecoder; - NImplode::NHuffman::CDecoder m_DistanceDecoder; - - bool m_BigDictionaryOn; - bool m_LiteralsOn; - - int m_NumDistanceLowDirectBits; - UInt32 m_MinMatchLength; - - bool ReadLevelItems(NImplode::NHuffman::CDecoder &table, Byte *levels, int numLevelItems); - bool ReadTables(); - void DeCodeLevelTable(Byte *newLevels, int numLevels); -public: - CCoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - void ReleaseStreams(); - HRESULT Flush() { return m_OutWindowStream.Flush(); } - - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); -}; - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.cpp deleted file mode 100644 index c7a163433..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// ImplodeHuffmanDecoder.cpp - -#include "StdAfx.h" - -#include "ImplodeHuffmanDecoder.h" - -namespace NCompress { -namespace NImplode { -namespace NHuffman { - -CDecoder::CDecoder(UInt32 numSymbols): - m_NumSymbols(numSymbols) -{ - m_Symbols = new UInt32[m_NumSymbols]; -} - -CDecoder::~CDecoder() -{ - delete []m_Symbols; -} - -bool CDecoder::SetCodeLengths(const Byte *codeLengths) -{ - // int lenCounts[kNumBitsInLongestCode + 1], tmpPositions[kNumBitsInLongestCode + 1]; - int lenCounts[kNumBitsInLongestCode + 2], tmpPositions[kNumBitsInLongestCode + 1]; - int i; - for(i = 0; i <= kNumBitsInLongestCode; i++) - lenCounts[i] = 0; - UInt32 symbolIndex; - for (symbolIndex = 0; symbolIndex < m_NumSymbols; symbolIndex++) - lenCounts[codeLengths[symbolIndex]]++; - // lenCounts[0] = 0; - - // tmpPositions[0] = m_Positions[0] = m_Limitits[0] = 0; - m_Limitits[kNumBitsInLongestCode + 1] = 0; - m_Positions[kNumBitsInLongestCode + 1] = 0; - lenCounts[kNumBitsInLongestCode + 1] = 0; - - - UInt32 startPos = 0; - static const UInt32 kMaxValue = (1 << kNumBitsInLongestCode); - - for (i = kNumBitsInLongestCode; i > 0; i--) - { - startPos += lenCounts[i] << (kNumBitsInLongestCode - i); - if (startPos > kMaxValue) - return false; - m_Limitits[i] = startPos; - m_Positions[i] = m_Positions[i + 1] + lenCounts[i + 1]; - tmpPositions[i] = m_Positions[i] + lenCounts[i]; - - } - - // if _ZIP_MODE do not throw exception for trees containing only one node - // #ifndef _ZIP_MODE - if (startPos != kMaxValue) - return false; - // #endif - - for (symbolIndex = 0; symbolIndex < m_NumSymbols; symbolIndex++) - if (codeLengths[symbolIndex] != 0) - m_Symbols[--tmpPositions[codeLengths[symbolIndex]]] = symbolIndex; - return true; -} - -UInt32 CDecoder::DecodeSymbol(CInBit *inStream) -{ - UInt32 numBits = 0; - UInt32 value = inStream->GetValue(kNumBitsInLongestCode); - int i; - for(i = kNumBitsInLongestCode; i > 0; i--) - { - if (value < m_Limitits[i]) - { - numBits = i; - break; - } - } - if (i == 0) - return 0xFFFFFFFF; - inStream->MovePos(numBits); - UInt32 index = m_Positions[numBits] + - ((value - m_Limitits[numBits + 1]) >> (kNumBitsInLongestCode - numBits)); - if (index >= m_NumSymbols) - return 0xFFFFFFFF; - return m_Symbols[index]; -} - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.h deleted file mode 100644 index 8936c09e6..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ImplodeHuffmanDecoder.h +++ /dev/null @@ -1,34 +0,0 @@ -// ImplodeHuffmanDecoder.h - -#ifndef __IMPLODE_HUFFMAN_DECODER_H -#define __IMPLODE_HUFFMAN_DECODER_H - -#include "../Common/InBuffer.h" - -#include "BitlDecoder.h" - -namespace NCompress { -namespace NImplode { -namespace NHuffman { - -const int kNumBitsInLongestCode = 16; - -typedef NBitl::CDecoder CInBit; - -class CDecoder -{ - UInt32 m_Limitits[kNumBitsInLongestCode + 2]; // m_Limitits[i] = value limit for symbols with length = i - UInt32 m_Positions[kNumBitsInLongestCode + 2]; // m_Positions[i] = index in m_Symbols[] of first symbol with length = i - UInt32 m_NumSymbols; // number of symbols in m_Symbols - UInt32 *m_Symbols; // symbols: at first with len=1 then 2, ... 15. -public: - CDecoder(UInt32 numSymbols); - ~CDecoder(); - - bool SetCodeLengths(const Byte *codeLengths); - UInt32 DecodeSymbol(CInBit *inStream); -}; - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.cpp deleted file mode 100644 index b04789471..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// LzOutWindow.cpp - -#include "StdAfx.h" - -#include "LzOutWindow.h" - -void CLzOutWindow::Init(bool solid) -{ - if (!solid) - COutBuffer::Init(); - #ifdef _NO_EXCEPTIONS - ErrorCode = S_OK; - #endif -} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.h b/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.h deleted file mode 100644 index bbec7ad5b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzOutWindow.h +++ /dev/null @@ -1,66 +0,0 @@ -// LzOutWindow.h - -#ifndef __LZ_OUT_WINDOW_H -#define __LZ_OUT_WINDOW_H - -#include "../IStream.h" - -#include "../Common/OutBuffer.h" - -#ifndef _NO_EXCEPTIONS -typedef COutBufferException CLzOutWindowException; -#endif - -class CLzOutWindow: public COutBuffer -{ -public: - void Init(bool solid = false); - - // distance >= 0, len > 0, - bool CopyBlock(UInt32 distance, UInt32 len) - { - UInt32 pos = _pos - distance - 1; - if (distance >= _pos) - { - if (!_overDict || distance >= _bufferSize) - return false; - pos += _bufferSize; - } - if (_limitPos - _pos > len && _bufferSize - pos > len) - { - const Byte *src = _buffer + pos; - Byte *dest = _buffer + _pos; - _pos += len; - do - *dest++ = *src++; - while(--len != 0); - } - else do - { - if (pos == _bufferSize) - pos = 0; - _buffer[_pos++] = _buffer[pos++]; - if (_pos == _limitPos) - FlushWithCheck(); - } - while(--len != 0); - return true; - } - - void PutByte(Byte b) - { - _buffer[_pos++] = b; - if (_pos == _limitPos) - FlushWithCheck(); - } - - Byte GetByte(UInt32 distance) const - { - UInt32 pos = _pos - distance - 1; - if (pos >= _bufferSize) - pos += _bufferSize; - return _buffer[pos]; - } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.cpp deleted file mode 100644 index e1591f46f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.cpp +++ /dev/null @@ -1,220 +0,0 @@ -// LzhDecoder.cpp - -#include "StdAfx.h" - -#include "LzhDecoder.h" - -#include "Windows/Defs.h" - -namespace NCompress{ -namespace NLzh { -namespace NDecoder { - -static const UInt32 kHistorySize = (1 << 16); - -static const int kBlockSizeBits = 16; -static const int kNumCBits = 9; -static const int kNumLevelBits = 5; // smallest integer such that (1 << kNumLevelBits) > kNumLevelSymbols/ - -UInt32 CCoder::ReadBits(int numBits) { return m_InBitStream.ReadBits(numBits); } - -HRESULT CCoder::ReadLevelTable() -{ - int n = ReadBits(kNumLevelBits); - if (n == 0) - { - m_LevelHuffman.Symbol = ReadBits(kNumLevelBits); - if (m_LevelHuffman.Symbol >= kNumLevelSymbols) - return S_FALSE; - } - else - { - if (n > kNumLevelSymbols) - return S_FALSE; - m_LevelHuffman.Symbol = -1; - Byte lens[kNumLevelSymbols]; - int i = 0; - while (i < n) - { - int c = m_InBitStream.ReadBits(3); - if (c == 7) - while (ReadBits(1)) - if (c++ > kMaxHuffmanLen) - return S_FALSE; - lens[i++] = (Byte)c; - if (i == kNumSpecLevelSymbols) - { - c = ReadBits(2); - while (--c >= 0) - lens[i++] = 0; - } - } - while (i < kNumLevelSymbols) - lens[i++] = 0; - m_LevelHuffman.SetCodeLengths(lens); - } - return S_OK; -} - -HRESULT CCoder::ReadPTable(int numBits) -{ - int n = ReadBits(numBits); - if (n == 0) - { - m_PHuffmanDecoder.Symbol = ReadBits(numBits); - if (m_PHuffmanDecoder.Symbol >= kNumDistanceSymbols) - return S_FALSE; - } - else - { - if (n > kNumDistanceSymbols) - return S_FALSE; - m_PHuffmanDecoder.Symbol = -1; - Byte lens[kNumDistanceSymbols]; - int i = 0; - while (i < n) - { - int c = m_InBitStream.ReadBits(3); - if (c == 7) - while (ReadBits(1)) - { - if (c > kMaxHuffmanLen) - return S_FALSE; - c++; - } - lens[i++] = (Byte)c; - } - while (i < kNumDistanceSymbols) - lens[i++] = 0; - m_PHuffmanDecoder.SetCodeLengths(lens); - } - return S_OK; -} - -HRESULT CCoder::ReadCTable() -{ - int n = ReadBits(kNumCBits); - if (n == 0) - { - m_CHuffmanDecoder.Symbol = ReadBits(kNumCBits); - if (m_CHuffmanDecoder.Symbol >= kNumCSymbols) - return S_FALSE; - } - else - { - if (n > kNumCSymbols) - return S_FALSE; - m_CHuffmanDecoder.Symbol = -1; - Byte lens[kNumCSymbols]; - int i = 0; - while (i < n) - { - int c = m_LevelHuffman.Decode(&m_InBitStream); - if (c < kNumSpecLevelSymbols) - { - if (c == 0) - c = 1; - else if (c == 1) - c = ReadBits(4) + 3; - else - c = ReadBits(kNumCBits) + 20; - while (--c >= 0) - { - if (i > kNumCSymbols) - return S_FALSE; - lens[i++] = 0; - } - } - else - lens[i++] = (Byte)(c - 2); - } - while (i < kNumCSymbols) - lens[i++] = 0; - m_CHuffmanDecoder.SetCodeLengths(lens); - } - return S_OK; -} - -STDMETHODIMP CCoder::CodeReal(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 * /* inSize */, const UInt64 *outSize, - ICompressProgressInfo *progress) -{ - if (outSize == NULL) - return E_INVALIDARG; - - if (!m_OutWindowStream.Create(kHistorySize)) - return E_OUTOFMEMORY; - if (!m_InBitStream.Create(1 << 20)) - return E_OUTOFMEMORY; - - UInt64 pos = 0; - m_OutWindowStream.SetStream(outStream); - m_OutWindowStream.Init(false); - m_InBitStream.SetStream(inStream); - m_InBitStream.Init(); - - CCoderReleaser coderReleaser(this); - - int pbit; - if (m_NumDictBits <= 13) - pbit = 4; - else - pbit = 5; - - UInt32 blockSize = 0; - - while(pos < *outSize) - { - // for (i = 0; i < dictSize; i++) dtext[i] = 0x20; - - if (blockSize == 0) - { - if (progress != NULL) - { - UInt64 packSize = m_InBitStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &pos)); - } - blockSize = ReadBits(kBlockSizeBits); - ReadLevelTable(); - ReadCTable(); - RINOK(ReadPTable(pbit)); - } - blockSize--; - UInt32 c = m_CHuffmanDecoder.Decode(&m_InBitStream); - if (c < 256) - { - m_OutWindowStream.PutByte((Byte)c); - pos++; - } - else if (c >= kNumCSymbols) - return S_FALSE; - else - { - // offset = (interface->method == LARC_METHOD_NUM) ? 0x100 - 2 : 0x100 - 3; - UInt32 len = c - 256 + kMinMatch; - UInt32 distance = m_PHuffmanDecoder.Decode(&m_InBitStream); - if (distance != 0) - distance = (1 << (distance - 1)) + ReadBits(distance - 1); - if (distance >= pos) - return S_FALSE; - if (pos + len > *outSize) - len = (UInt32)(*outSize - pos); - pos += len; - m_OutWindowStream.CopyBlock(distance, len); - } - } - coderReleaser.NeedFlush = false; - return m_OutWindowStream.Flush(); -} - -STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, - ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress);} - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const CLzOutWindowException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.h deleted file mode 100644 index 3048797fb..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzhDecoder.h +++ /dev/null @@ -1,106 +0,0 @@ -// LzhDecoder.h - -#ifndef __COMPRESS_LZH_DECODER_H -#define __COMPRESS_LZH_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" - -#include "BitmDecoder.h" -#include "HuffmanDecoder.h" -#include "LzOutWindow.h" - -namespace NCompress { -namespace NLzh { -namespace NDecoder { - -const int kMaxHuffmanLen = 16; // Check it - -const int kNumSpecLevelSymbols = 3; -const int kNumLevelSymbols = kNumSpecLevelSymbols + kMaxHuffmanLen; - -const int kDictBitsMax = 16; -const int kNumDistanceSymbols = kDictBitsMax + 1; - -const int kMaxMatch = 256; -const int kMinMatch = 3; -const int kNumCSymbols = 256 + kMaxMatch + 2 - kMinMatch; - -template -class CHuffmanDecoder:public NCompress::NHuffman::CDecoder -{ -public: - int Symbol; - template - UInt32 Decode(TBitDecoder *bitStream) - { - if (Symbol >= 0) - return (UInt32)Symbol; - return DecodeSymbol(bitStream); - } -}; - -class CCoder : - public ICompressCoder, - public CMyUnknownImp -{ - CLzOutWindow m_OutWindowStream; - NBitm::CDecoder m_InBitStream; - - int m_NumDictBits; - - CHuffmanDecoder m_LevelHuffman; - CHuffmanDecoder m_PHuffmanDecoder; - CHuffmanDecoder m_CHuffmanDecoder; - - void ReleaseStreams() - { - m_OutWindowStream.ReleaseStream(); - m_InBitStream.ReleaseStream(); - } - - class CCoderReleaser - { - CCoder *m_Coder; - public: - bool NeedFlush; - CCoderReleaser(CCoder *coder): m_Coder(coder), NeedFlush(true) {} - ~CCoderReleaser() - { - if (NeedFlush) - m_Coder->m_OutWindowStream.Flush(); - m_Coder->ReleaseStreams(); - } - }; - friend class CCoderReleaser; - - void MakeTable(int nchar, Byte *bitlen, int tablebits, - UInt32 *table, int tablesize); - - UInt32 ReadBits(int numBits); - HRESULT ReadLevelTable(); - HRESULT ReadPTable(int numBits); - HRESULT ReadCTable(); - -public: - - MY_UNKNOWN_IMP - - STDMETHOD(CodeReal)(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, - ICompressProgressInfo *progress); - - STDMETHOD(Code)(ISequentialInStream *inStream, - ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, - ICompressProgressInfo *progress); - - void SetDictionary(int numDictBits) { m_NumDictBits = numDictBits; } - CCoder(): m_NumDictBits(0) {} -}; - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.cpp deleted file mode 100644 index 61a8cc009..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.cpp +++ /dev/null @@ -1,190 +0,0 @@ -// LzmaDecoder.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "../Common/StreamUtils.h" - -#include "LzmaDecoder.h" - -static HRESULT SResToHRESULT(SRes res) -{ - switch(res) - { - case SZ_OK: return S_OK; - case SZ_ERROR_MEM: return E_OUTOFMEMORY; - case SZ_ERROR_PARAM: return E_INVALIDARG; - case SZ_ERROR_UNSUPPORTED: return E_NOTIMPL; - // case SZ_ERROR_PROGRESS: return E_ABORT; - case SZ_ERROR_DATA: return S_FALSE; - } - return E_FAIL; -} - -namespace NCompress { -namespace NLzma { - -static const UInt32 kInBufSize = 1 << 20; - -CDecoder::CDecoder(): _inBuf(0), _outSizeDefined(false), FinishStream(false) -{ - LzmaDec_Construct(&_state); -} - -static void *SzAlloc(void *p, size_t size) { p = p; return MyAlloc(size); } -static void SzFree(void *p, void *address) { p = p; MyFree(address); } -static ISzAlloc g_Alloc = { SzAlloc, SzFree }; - -CDecoder::~CDecoder() -{ - LzmaDec_Free(&_state, &g_Alloc); - MyFree(_inBuf); -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *prop, UInt32 size) -{ - RINOK(SResToHRESULT(LzmaDec_Allocate(&_state, prop, size, &g_Alloc))); - - if (_inBuf == 0) - { - _inBuf = (Byte *)MyAlloc(kInBufSize); - if (_inBuf == 0) - return E_OUTOFMEMORY; - } - - return S_OK; -} - -STDMETHODIMP CDecoder::GetInStreamProcessedSize(UInt64 *value) { *value = _inSizeProcessed; return S_OK; } -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) { _inStream = inStream; return S_OK; } -STDMETHODIMP CDecoder::ReleaseInStream() { _inStream.Release(); return S_OK; } - -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) -{ - _outSizeDefined = (outSize != NULL); - if (_outSizeDefined) - _outSize = *outSize; - - LzmaDec_Init(&_state); - - _inPos = _inSize = 0; - _inSizeProcessed = _outSizeProcessed = 0; - return S_OK; -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - if (_inBuf == 0) - return S_FALSE; - SetOutStreamSize(outSize); - - for (;;) - { - if (_inPos == _inSize) - { - _inPos = _inSize = 0; - RINOK(inStream->Read(_inBuf, kInBufSize, &_inSize)); - } - - SizeT dicPos = _state.dicPos; - SizeT curSize = _state.dicBufSize - dicPos; - const UInt32 kStepSize = ((UInt32)1 << 22); - if (curSize > kStepSize) - curSize = (SizeT)kStepSize; - - ELzmaFinishMode finishMode = LZMA_FINISH_ANY; - if (_outSizeDefined) - { - const UInt64 rem = _outSize - _outSizeProcessed; - if (rem < curSize) - { - curSize = (SizeT)rem; - if (FinishStream) - finishMode = LZMA_FINISH_END; - } - } - - SizeT inSizeProcessed = _inSize - _inPos; - ELzmaStatus status; - SRes res = LzmaDec_DecodeToDic(&_state, dicPos + curSize, _inBuf + _inPos, &inSizeProcessed, finishMode, &status); - - _inPos += (UInt32)inSizeProcessed; - _inSizeProcessed += inSizeProcessed; - SizeT outSizeProcessed = _state.dicPos - dicPos; - _outSizeProcessed += outSizeProcessed; - - bool finished = (inSizeProcessed == 0 && outSizeProcessed == 0); - bool stopDecoding = (_outSizeDefined && _outSizeProcessed >= _outSize); - - if (res != 0 || _state.dicPos == _state.dicBufSize || finished || stopDecoding) - { - HRESULT res2 = WriteStream(outStream, _state.dic, _state.dicPos); - if (res != 0) - return S_FALSE; - RINOK(res2); - if (stopDecoding) - return S_OK; - if (finished) - return (status == LZMA_STATUS_FINISHED_WITH_MARK ? S_OK : S_FALSE); - } - if (_state.dicPos == _state.dicBufSize) - _state.dicPos = 0; - - if (progress != NULL) - { - RINOK(progress->SetRatioInfo(&_inSizeProcessed, &_outSizeProcessed)); - } - } -} - -#ifndef NO_READ_FROM_CODER - -STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - if (processedSize) - *processedSize = 0; - do - { - if (_inPos == _inSize) - { - _inPos = _inSize = 0; - RINOK(_inStream->Read(_inBuf, kInBufSize, &_inSize)); - } - { - SizeT inProcessed = _inSize - _inPos; - - if (_outSizeDefined) - { - const UInt64 rem = _outSize - _outSizeProcessed; - if (rem < size) - size = (UInt32)rem; - } - - SizeT outProcessed = size; - ELzmaStatus status; - SRes res = LzmaDec_DecodeToBuf(&_state, (Byte *)data, &outProcessed, - _inBuf + _inPos, &inProcessed, LZMA_FINISH_ANY, &status); - _inPos += (UInt32)inProcessed; - _inSizeProcessed += inProcessed; - _outSizeProcessed += outProcessed; - size -= (UInt32)outProcessed; - data = (Byte *)data + outProcessed; - if (processedSize) - *processedSize += (UInt32)outProcessed; - RINOK(SResToHRESULT(res)); - if (inProcessed == 0 && outProcessed == 0) - return S_OK; - } - } - while (size != 0); - return S_OK; -} - -#endif - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.h deleted file mode 100644 index 16b4791b0..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaDecoder.h +++ /dev/null @@ -1,73 +0,0 @@ -// LzmaDecoder.h - -#ifndef __LZMA_DECODER_H -#define __LZMA_DECODER_H - -extern "C" -{ -#include "../../../C/LzmaDec.h" -} - -#include "../../Common/MyCom.h" -#include "../ICoder.h" - -namespace NCompress { -namespace NLzma { - -class CDecoder: - public ICompressCoder, - public ICompressSetDecoderProperties2, - public ICompressGetInStreamProcessedSize, - #ifndef NO_READ_FROM_CODER - public ICompressSetInStream, - public ICompressSetOutStreamSize, - public ISequentialInStream, - #endif - public CMyUnknownImp -{ - CMyComPtr _inStream; - Byte *_inBuf; - UInt32 _inPos; - UInt32 _inSize; - CLzmaDec _state; - bool _outSizeDefined; - UInt64 _outSize; - UInt64 _inSizeProcessed; - UInt64 _outSizeProcessed; -public: - - #ifndef NO_READ_FROM_CODER - MY_UNKNOWN_IMP5( - ICompressSetDecoderProperties2, - ICompressGetInStreamProcessedSize, - ICompressSetInStream, - ICompressSetOutStreamSize, - ISequentialInStream) - #else - MY_UNKNOWN_IMP2( - ICompressSetDecoderProperties2, - ICompressGetInStreamProcessedSize) - #endif - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - - #ifndef NO_READ_FROM_CODER - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - #endif - - bool FinishStream; - - CDecoder(); - virtual ~CDecoder(); - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/LzmaRegister.cpp deleted file mode 100644 index 9c67eaf94..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/LzmaRegister.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// LzmaRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "LzmaDecoder.h" - -static void *CreateCodec() { return (void *)(ICompressCoder *)(new NCompress::NLzma::CDecoder); } -#ifndef EXTRACT_ONLY -#include "LzmaEncoder.h" -static void *CreateCodecOut() { return (void *)(ICompressCoder *)(new NCompress::NLzma::CEncoder); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x030101, L"LZMA", 1, false }; - -REGISTER_CODEC(LZMA) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Mtf8.h b/desmume/src/windows/7z/CPP/7zip/Compress/Mtf8.h deleted file mode 100644 index e5e0046de..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Mtf8.h +++ /dev/null @@ -1,196 +0,0 @@ -// Mtf8.h - -#ifndef __COMPRESS_MTF8_H -#define __COMPRESS_MTF8_H - -#include "../../Common/Types.h" - -namespace NCompress { - -struct CMtf8Encoder -{ - Byte Buf[256]; - - int FindAndMove(Byte v) - { - int pos; - for (pos = 0; Buf[pos] != v; pos++); - int resPos = pos; - for (; pos >= 8; pos -= 8) - { - Buf[pos] = Buf[pos - 1]; - Buf[pos - 1] = Buf[pos - 2]; - Buf[pos - 2] = Buf[pos - 3]; - Buf[pos - 3] = Buf[pos - 4]; - Buf[pos - 4] = Buf[pos - 5]; - Buf[pos - 5] = Buf[pos - 6]; - Buf[pos - 6] = Buf[pos - 7]; - Buf[pos - 7] = Buf[pos - 8]; - } - for (; pos > 0; pos--) - Buf[pos] = Buf[pos - 1]; - Buf[0] = v; - return resPos; - } -}; - -/* -struct CMtf8Decoder -{ - Byte Buf[256]; - - void Init(int) {}; - Byte GetHead() const { return Buf[0]; } - Byte GetAndMove(int pos) - { - Byte res = Buf[pos]; - for (; pos >= 8; pos -= 8) - { - Buf[pos] = Buf[pos - 1]; - Buf[pos - 1] = Buf[pos - 2]; - Buf[pos - 2] = Buf[pos - 3]; - Buf[pos - 3] = Buf[pos - 4]; - Buf[pos - 4] = Buf[pos - 5]; - Buf[pos - 5] = Buf[pos - 6]; - Buf[pos - 6] = Buf[pos - 7]; - Buf[pos - 7] = Buf[pos - 8]; - } - for (; pos > 0; pos--) - Buf[pos] = Buf[pos - 1]; - Buf[0] = res; - return res; - } -}; -*/ - -#ifdef _WIN64 -#define MODE_64BIT -#endif - -#ifdef MODE_64BIT -typedef UInt64 CMtfVar; -#define MTF_MOVS 3 -#else -typedef UInt32 CMtfVar; -#define MTF_MOVS 2 -#endif - -#define MTF_MASK ((1 << MTF_MOVS) - 1) - - -struct CMtf8Decoder -{ - CMtfVar Buf[256 >> MTF_MOVS]; - - void StartInit() { memset(Buf, 0, sizeof(Buf)); } - void Add(unsigned int pos, Byte val) { Buf[pos >> MTF_MOVS] |= ((CMtfVar)val << ((pos & MTF_MASK) << 3)); } - Byte GetHead() const { return (Byte)Buf[0]; } - Byte GetAndMove(unsigned int pos) - { - UInt32 lim = ((UInt32)pos >> MTF_MOVS); - pos = (pos & MTF_MASK) << 3; - CMtfVar prev = (Buf[lim] >> pos) & 0xFF; - - UInt32 i = 0; - if ((lim & 1) != 0) - { - CMtfVar next = Buf[0]; - Buf[0] = (next << 8) | prev; - prev = (next >> (MTF_MASK << 3)); - i = 1; - lim -= 1; - } - for (; i < lim; i += 2) - { - CMtfVar next = Buf[i]; - Buf[i] = (next << 8) | prev; - prev = (next >> (MTF_MASK << 3)); - next = Buf[i + 1]; - Buf[i + 1] = (next << 8) | prev; - prev = (next >> (MTF_MASK << 3)); - } - CMtfVar next = Buf[i]; - CMtfVar mask = (((CMtfVar)0x100 << pos) - 1); - Buf[i] = (next & ~mask) | (((next << 8) | prev) & mask); - return (Byte)Buf[0]; - } -}; - -/* -const int kSmallSize = 64; -class CMtf8Decoder -{ - Byte SmallBuffer[kSmallSize]; - int SmallSize; - Byte Counts[16]; - int Size; -public: - Byte Buf[256]; - - Byte GetHead() const - { - if (SmallSize > 0) - return SmallBuffer[kSmallSize - SmallSize]; - return Buf[0]; - } - - void Init(int size) - { - Size = size; - SmallSize = 0; - for (int i = 0; i < 16; i++) - { - Counts[i] = ((size >= 16) ? 16 : size); - size -= Counts[i]; - } - } - - Byte GetAndMove(int pos) - { - if (pos < SmallSize) - { - Byte *p = SmallBuffer + kSmallSize - SmallSize; - Byte res = p[pos]; - for (; pos > 0; pos--) - p[pos] = p[pos - 1]; - SmallBuffer[kSmallSize - SmallSize] = res; - return res; - } - if (SmallSize == kSmallSize) - { - int i = Size - 1; - int g = 16; - do - { - g--; - int offset = (g << 4); - for (int t = Counts[g] - 1; t >= 0; t--, i--) - Buf[i] = Buf[offset + t]; - } - while(g != 0); - - for (i = kSmallSize - 1; i >= 0; i--) - Buf[i] = SmallBuffer[i]; - Init(Size); - } - pos -= SmallSize; - int g; - for (g = 0; pos >= Counts[g]; g++) - pos -= Counts[g]; - int offset = (g << 4); - Byte res = Buf[offset + pos]; - for (pos; pos < 16 - 1; pos++) - Buf[offset + pos] = Buf[offset + pos + 1]; - - SmallSize++; - SmallBuffer[kSmallSize - SmallSize] = res; - - Counts[g]--; - return res; - } -}; -*/ - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdContext.h b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdContext.h deleted file mode 100644 index 11502a951..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdContext.h +++ /dev/null @@ -1,489 +0,0 @@ -// PpmdContext.h -// This code is based on Dmitry Shkarin's PPMdH code - -#ifndef __COMPRESS_PPMD_CONTEXT_H -#define __COMPRESS_PPMD_CONTEXT_H - -#include "../../Common/Types.h" - -#include "PpmdSubAlloc.h" -#include "RangeCoder.h" - -namespace NCompress { -namespace NPpmd { - -const int INT_BITS=7, PERIOD_BITS=7, TOT_BITS=INT_BITS+PERIOD_BITS, - INTERVAL=1 << INT_BITS, BIN_SCALE=1 << TOT_BITS, MAX_FREQ=124; - -struct SEE2_CONTEXT -{ - // SEE-contexts for PPM-contexts with masked symbols - UInt16 Summ; - Byte Shift, Count; - void init(int InitVal) { Summ = (UInt16)(InitVal << (Shift=PERIOD_BITS-4)); Count=4; } - unsigned int getMean() - { - unsigned int RetVal=(Summ >> Shift); - Summ = (UInt16)(Summ - RetVal); - return RetVal+(RetVal == 0); - } - void update() - { - if (Shift < PERIOD_BITS && --Count == 0) - { - Summ <<= 1; - Count = (Byte)(3 << Shift++); - } - } -}; - -struct PPM_CONTEXT -{ - UInt16 NumStats; // sizeof(UInt16) > sizeof(Byte) - UInt16 SummFreq; - - struct STATE - { - Byte Symbol, Freq; - UInt16 SuccessorLow; - UInt16 SuccessorHigh; - - UInt32 GetSuccessor() const { return SuccessorLow | ((UInt32)SuccessorHigh << 16); } - void SetSuccessor(UInt32 v) - { - SuccessorLow = (UInt16)(v & 0xFFFF); - SuccessorHigh = (UInt16)((v >> 16) & 0xFFFF); - } - }; - - UInt32 Stats; - UInt32 Suffix; - - PPM_CONTEXT* createChild(CSubAllocator &subAllocator, STATE* pStats, STATE& FirstState) - { - PPM_CONTEXT* pc = (PPM_CONTEXT*) subAllocator.AllocContext(); - if (pc) - { - pc->NumStats = 1; - pc->oneState() = FirstState; - pc->Suffix = subAllocator.GetOffset(this); - pStats->SetSuccessor(subAllocator.GetOffsetNoCheck(pc)); - } - return pc; - } - - STATE& oneState() const { return (STATE&) SummFreq; } -}; - -///////////////////////////////// - -const UInt16 InitBinEsc[] = - {0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051}; - -struct CInfo -{ - CSubAllocator SubAllocator; - SEE2_CONTEXT SEE2Cont[25][16], DummySEE2Cont; - PPM_CONTEXT * MinContext, * MaxContext; - - PPM_CONTEXT::STATE* FoundState; // found next state transition - int NumMasked, InitEsc, OrderFall, RunLength, InitRL, MaxOrder; - Byte CharMask[256], NS2Indx[256], NS2BSIndx[256], HB2Flag[256]; - Byte EscCount, PrintCount, PrevSuccess, HiBitsFlag; - UInt16 BinSumm[128][64]; // binary SEE-contexts - - UInt16 &GetBinSumm(const PPM_CONTEXT::STATE &rs, int numStates) - { - HiBitsFlag = HB2Flag[FoundState->Symbol]; - return BinSumm[rs.Freq - 1][ - PrevSuccess + NS2BSIndx[numStates - 1] + - HiBitsFlag + 2 * HB2Flag[rs.Symbol] + - ((RunLength >> 26) & 0x20)]; - } - - PPM_CONTEXT *GetContext(UInt32 offset) const { return (PPM_CONTEXT *)SubAllocator.GetPtr(offset); } - PPM_CONTEXT *GetContextNoCheck(UInt32 offset) const { return (PPM_CONTEXT *)SubAllocator.GetPtrNoCheck(offset); } - PPM_CONTEXT::STATE *GetState(UInt32 offset) const { return (PPM_CONTEXT::STATE *)SubAllocator.GetPtr(offset); } - PPM_CONTEXT::STATE *GetStateNoCheck(UInt32 offset) const { return (PPM_CONTEXT::STATE *)SubAllocator.GetPtr(offset); } - - void RestartModelRare() - { - int i, k, m; - memset(CharMask,0,sizeof(CharMask)); - SubAllocator.InitSubAllocator(); - InitRL = -((MaxOrder < 12) ? MaxOrder : 12) - 1; - MinContext = MaxContext = (PPM_CONTEXT*) SubAllocator.AllocContext(); - MinContext->Suffix = 0; - OrderFall = MaxOrder; - MinContext->SummFreq = (UInt16)((MinContext->NumStats = 256) + 1); - FoundState = (PPM_CONTEXT::STATE*)SubAllocator.AllocUnits(256 / 2); - MinContext->Stats = SubAllocator.GetOffsetNoCheck(FoundState); - PrevSuccess = 0; - for (RunLength = InitRL, i = 0; i < 256; i++) - { - PPM_CONTEXT::STATE &state = FoundState[i]; - state.Symbol = (Byte)i; - state.Freq = 1; - state.SetSuccessor(0); - } - for (i = 0; i < 128; i++) - for (k = 0; k < 8; k++) - for ( m=0; m < 64; m += 8) - BinSumm[i][k + m] = (UInt16)(BIN_SCALE - InitBinEsc[k] / (i + 2)); - for (i = 0; i < 25; i++) - for (k = 0; k < 16; k++) - SEE2Cont[i][k].init(5*i+10); - } - - void StartModelRare(int maxOrder) - { - int i, k, m ,Step; - EscCount=PrintCount=1; - if (maxOrder < 2) - { - memset(CharMask,0,sizeof(CharMask)); - OrderFall = MaxOrder; - MinContext = MaxContext; - while (MinContext->Suffix != 0) - { - MinContext = GetContextNoCheck(MinContext->Suffix); - OrderFall--; - } - FoundState = GetState(MinContext->Stats); - MinContext = MaxContext; - } - else - { - MaxOrder = maxOrder; - RestartModelRare(); - NS2BSIndx[0] = 2 * 0; - NS2BSIndx[1] = 2 * 1; - memset(NS2BSIndx + 2, 2 * 2, 9); - memset(NS2BSIndx + 11, 2 * 3, 256 - 11); - for (i = 0; i < 3; i++) - NS2Indx[i] = (Byte)i; - for (m = i, k = Step = 1; i < 256; i++) - { - NS2Indx[i] = (Byte)m; - if ( !--k ) - { - k = ++Step; - m++; - } - } - memset(HB2Flag, 0, 0x40); - memset(HB2Flag + 0x40, 0x08, 0x100 - 0x40); - DummySEE2Cont.Shift = PERIOD_BITS; - } - } - - PPM_CONTEXT* CreateSuccessors(bool skip, PPM_CONTEXT::STATE* p1) - { - // static UpState declaration bypasses IntelC bug - // static PPM_CONTEXT::STATE UpState; - PPM_CONTEXT::STATE UpState; - - PPM_CONTEXT *pc = MinContext; - PPM_CONTEXT *UpBranch = GetContext(FoundState->GetSuccessor()); - PPM_CONTEXT::STATE * p, * ps[MAX_O], ** pps = ps; - if ( !skip ) - { - *pps++ = FoundState; - if ( !pc->Suffix ) - goto NO_LOOP; - } - if ( p1 ) - { - p = p1; - pc = GetContext(pc->Suffix); - goto LOOP_ENTRY; - } - do - { - pc = GetContext(pc->Suffix); - if (pc->NumStats != 1) - { - if ((p = GetStateNoCheck(pc->Stats))->Symbol != FoundState->Symbol) - do { p++; } while (p->Symbol != FoundState->Symbol); - } - else - p = &(pc->oneState()); -LOOP_ENTRY: - if (GetContext(p->GetSuccessor()) != UpBranch) - { - pc = GetContext(p->GetSuccessor()); - break; - } - *pps++ = p; - } - while ( pc->Suffix ); -NO_LOOP: - if (pps == ps) - return pc; - UpState.Symbol = *(Byte*) UpBranch; - UpState.SetSuccessor(SubAllocator.GetOffset(UpBranch) + 1); - if (pc->NumStats != 1) - { - if ((p = GetStateNoCheck(pc->Stats))->Symbol != UpState.Symbol) - do { p++; } while (p->Symbol != UpState.Symbol); - unsigned int cf = p->Freq-1; - unsigned int s0 = pc->SummFreq - pc->NumStats - cf; - UpState.Freq = (Byte)(1 + ((2 * cf <= s0) ? (5 * cf > s0) : - ((2 * cf + 3 * s0 - 1) / (2 * s0)))); - } - else - UpState.Freq = pc->oneState().Freq; - do - { - pc = pc->createChild(SubAllocator, *--pps, UpState); - if ( !pc ) - return NULL; - } - while (pps != ps); - return pc; - } - - void UpdateModel() - { - PPM_CONTEXT::STATE fs = *FoundState, * p = NULL; - PPM_CONTEXT* pc, * Successor; - unsigned int ns1, ns, cf, sf, s0; - if (fs.Freq < MAX_FREQ / 4 && MinContext->Suffix != 0) - { - pc = GetContextNoCheck(MinContext->Suffix); - - if (pc->NumStats != 1) - { - if ((p = GetStateNoCheck(pc->Stats))->Symbol != fs.Symbol) - { - do { p++; } while (p->Symbol != fs.Symbol); - if (p[0].Freq >= p[-1].Freq) - { - _PPMD_SWAP(p[0],p[-1]); - p--; - } - } - if (p->Freq < MAX_FREQ-9) - { - p->Freq += 2; - pc->SummFreq += 2; - } - } - else - { - p = &(pc->oneState()); - p->Freq = (Byte)(p->Freq + ((p->Freq < 32) ? 1 : 0)); - } - } - if ( !OrderFall ) - { - MinContext = MaxContext = CreateSuccessors(true, p); - FoundState->SetSuccessor(SubAllocator.GetOffset(MinContext)); - if (MinContext == 0) - goto RESTART_MODEL; - return; - } - *SubAllocator.pText++ = fs.Symbol; - Successor = (PPM_CONTEXT*) SubAllocator.pText; - if (SubAllocator.pText >= SubAllocator.UnitsStart) - goto RESTART_MODEL; - if (fs.GetSuccessor() != 0) - { - if ((Byte *)GetContext(fs.GetSuccessor()) <= SubAllocator.pText) - { - PPM_CONTEXT* cs = CreateSuccessors(false, p); - fs.SetSuccessor(SubAllocator.GetOffset(cs)); - if (cs == NULL) - goto RESTART_MODEL; - } - if ( !--OrderFall ) - { - Successor = GetContext(fs.GetSuccessor()); - SubAllocator.pText -= (MaxContext != MinContext); - } - } - else - { - FoundState->SetSuccessor(SubAllocator.GetOffsetNoCheck(Successor)); - fs.SetSuccessor(SubAllocator.GetOffsetNoCheck(MinContext)); - } - s0 = MinContext->SummFreq - (ns = MinContext->NumStats) - (fs.Freq - 1); - for (pc = MaxContext; pc != MinContext; pc = GetContext(pc->Suffix)) - { - if ((ns1 = pc->NumStats) != 1) - { - if ((ns1 & 1) == 0) - { - void *ppp = SubAllocator.ExpandUnits(GetState(pc->Stats), ns1 >> 1); - pc->Stats = SubAllocator.GetOffset(ppp); - if (!ppp) - goto RESTART_MODEL; - } - pc->SummFreq = (UInt16)(pc->SummFreq + (2 * ns1 < ns) + 2 * ((4 * ns1 <= ns) & - (pc->SummFreq <= 8 * ns1))); - } - else - { - p = (PPM_CONTEXT::STATE*) SubAllocator.AllocUnits(1); - if ( !p ) - goto RESTART_MODEL; - *p = pc->oneState(); - pc->Stats = SubAllocator.GetOffsetNoCheck(p); - if (p->Freq < MAX_FREQ / 4 - 1) - p->Freq <<= 1; - else - p->Freq = MAX_FREQ - 4; - pc->SummFreq = (UInt16)(p->Freq + InitEsc + (ns > 3)); - } - cf = 2 * fs.Freq * (pc->SummFreq+6); - sf = s0 + pc->SummFreq; - if (cf < 6 * sf) - { - cf = 1 + (cf > sf)+(cf >= 4 * sf); - pc->SummFreq += 3; - } - else - { - cf = 4 + (cf >= 9 * sf) + (cf >= 12 * sf) + (cf >= 15 * sf); - pc->SummFreq = (UInt16)(pc->SummFreq + cf); - } - p = GetState(pc->Stats) + ns1; - p->SetSuccessor(SubAllocator.GetOffset(Successor)); - p->Symbol = fs.Symbol; - p->Freq = (Byte)cf; - pc->NumStats = (UInt16)++ns1; - } - MaxContext = MinContext = GetContext(fs.GetSuccessor()); - return; -RESTART_MODEL: - RestartModelRare(); - EscCount = 0; - PrintCount = 0xFF; - } - - void ClearMask() - { - EscCount = 1; - memset(CharMask, 0, sizeof(CharMask)); - // if (++PrintCount == 0) - // PrintInfo(DecodedFile,EncodedFile); - } - - void update1(PPM_CONTEXT::STATE* p) - { - (FoundState = p)->Freq += 4; - MinContext->SummFreq += 4; - if (p[0].Freq > p[-1].Freq) - { - _PPMD_SWAP(p[0],p[-1]); - FoundState = --p; - if (p->Freq > MAX_FREQ) - rescale(); - } - } - - - void update2(PPM_CONTEXT::STATE* p) - { - (FoundState = p)->Freq += 4; - MinContext->SummFreq += 4; - if (p->Freq > MAX_FREQ) - rescale(); - EscCount++; - RunLength = InitRL; - } - - SEE2_CONTEXT* makeEscFreq2(int Diff, UInt32 &scale) - { - SEE2_CONTEXT* psee2c; - if (MinContext->NumStats != 256) - { - psee2c = SEE2Cont[NS2Indx[Diff-1]] + - (Diff < (GetContext(MinContext->Suffix))->NumStats - MinContext->NumStats) + - 2 * (MinContext->SummFreq < 11 * MinContext->NumStats) + - 4 * (NumMasked > Diff) + - HiBitsFlag; - scale = psee2c->getMean(); - } - else - { - psee2c = &DummySEE2Cont; - scale = 1; - } - return psee2c; - } - - - - void rescale() - { - int OldNS = MinContext->NumStats, i = MinContext->NumStats - 1, Adder, EscFreq; - PPM_CONTEXT::STATE* p1, * p; - PPM_CONTEXT::STATE *stats = GetStateNoCheck(MinContext->Stats); - for (p = FoundState; p != stats; p--) - _PPMD_SWAP(p[0], p[-1]); - stats->Freq += 4; - MinContext->SummFreq += 4; - EscFreq = MinContext->SummFreq - p->Freq; - Adder = (OrderFall != 0); - p->Freq = (Byte)((p->Freq + Adder) >> 1); - MinContext->SummFreq = p->Freq; - do - { - EscFreq -= (++p)->Freq; - p->Freq = (Byte)((p->Freq + Adder) >> 1); - MinContext->SummFreq = (UInt16)(MinContext->SummFreq + p->Freq); - if (p[0].Freq > p[-1].Freq) - { - PPM_CONTEXT::STATE tmp = *(p1 = p); - do - { - p1[0] = p1[-1]; - } - while (--p1 != stats && tmp.Freq > p1[-1].Freq); - *p1 = tmp; - } - } - while ( --i ); - if (p->Freq == 0) - { - do { i++; } while ((--p)->Freq == 0); - EscFreq += i; - MinContext->NumStats = (UInt16)(MinContext->NumStats - i); - if (MinContext->NumStats == 1) - { - PPM_CONTEXT::STATE tmp = *stats; - do { tmp.Freq = (Byte)(tmp.Freq - (tmp.Freq >> 1)); EscFreq >>= 1; } while (EscFreq > 1); - SubAllocator.FreeUnits(stats, (OldNS+1) >> 1); - *(FoundState = &MinContext->oneState()) = tmp; return; - } - } - EscFreq -= (EscFreq >> 1); - MinContext->SummFreq = (UInt16)(MinContext->SummFreq + EscFreq); - int n0 = (OldNS+1) >> 1, n1 = (MinContext->NumStats + 1) >> 1; - if (n0 != n1) - MinContext->Stats = SubAllocator.GetOffset(SubAllocator.ShrinkUnits(stats, n0, n1)); - FoundState = GetState(MinContext->Stats); - } - - void NextContext() - { - PPM_CONTEXT *c = GetContext(FoundState->GetSuccessor()); - if (!OrderFall && (Byte *)c > SubAllocator.pText) - MinContext = MaxContext = c; - else - { - UpdateModel(); - if (EscCount == 0) - ClearMask(); - } - } -}; - -// Tabulated escapes for exponential symbol distribution -const Byte ExpEscape[16]={ 25,14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; -#define GET_MEAN(SUMM,SHIFT,ROUND) ((SUMM+(1 << (SHIFT-ROUND))) >> (SHIFT)) - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecode.h b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecode.h deleted file mode 100644 index 3ad037da6..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecode.h +++ /dev/null @@ -1,154 +0,0 @@ -// PpmdDecode.h -// This code is based on Dmitry Shkarin's PPMdH code - -#ifndef __COMPRESS_PPMD_DECODE_H -#define __COMPRESS_PPMD_DECODE_H - -#include "PpmdContext.h" - -namespace NCompress { -namespace NPpmd { - -class CRangeDecoderVirt -{ -public: - virtual UInt32 GetThreshold(UInt32 total) = 0; - virtual void Decode(UInt32 start, UInt32 size) = 0; - virtual UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits) = 0; -}; - -typedef NRangeCoder::CDecoder CRangeDecoderMy; - -class CRangeDecoder:public CRangeDecoderVirt, public CRangeDecoderMy -{ - UInt32 GetThreshold(UInt32 total) { return CRangeDecoderMy::GetThreshold(total); } - void Decode(UInt32 start, UInt32 size) { CRangeDecoderMy::Decode(start, size); } - UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits) { return CRangeDecoderMy::DecodeBit(size0, numTotalBits); } -}; - -struct CDecodeInfo: public CInfo -{ - void DecodeBinSymbol(CRangeDecoderVirt *rangeDecoder) - { - PPM_CONTEXT::STATE& rs = MinContext->oneState(); - UInt16& bs = GetBinSumm(rs, GetContextNoCheck(MinContext->Suffix)->NumStats); - if (rangeDecoder->DecodeBit(bs, TOT_BITS) == 0) - { - FoundState = &rs; - rs.Freq = (Byte)(rs.Freq + (rs.Freq < 128 ? 1: 0)); - bs = (UInt16)(bs + INTERVAL - GET_MEAN(bs, PERIOD_BITS, 2)); - PrevSuccess = 1; - RunLength++; - } - else - { - bs = (UInt16)(bs - GET_MEAN(bs, PERIOD_BITS, 2)); - InitEsc = ExpEscape[bs >> 10]; - NumMasked = 1; - CharMask[rs.Symbol] = EscCount; - PrevSuccess = 0; - FoundState = NULL; - } - } - - void DecodeSymbol1(CRangeDecoderVirt *rangeDecoder) - { - PPM_CONTEXT::STATE* p = GetStateNoCheck(MinContext->Stats); - int i, count, hiCnt; - if ((count = rangeDecoder->GetThreshold(MinContext->SummFreq)) < (hiCnt = p->Freq)) - { - PrevSuccess = (2 * hiCnt > MinContext->SummFreq); - RunLength += PrevSuccess; - rangeDecoder->Decode(0, p->Freq); // MinContext->SummFreq); - (FoundState = p)->Freq = (Byte)(hiCnt += 4); - MinContext->SummFreq += 4; - if (hiCnt > MAX_FREQ) - rescale(); - return; - } - PrevSuccess = 0; - i = MinContext->NumStats - 1; - while ((hiCnt += (++p)->Freq) <= count) - if (--i == 0) - { - HiBitsFlag = HB2Flag[FoundState->Symbol]; - rangeDecoder->Decode(hiCnt, MinContext->SummFreq - hiCnt); // , MinContext->SummFreq); - CharMask[p->Symbol] = EscCount; - i = (NumMasked = MinContext->NumStats)-1; - FoundState = NULL; - do { CharMask[(--p)->Symbol] = EscCount; } while ( --i ); - return; - } - rangeDecoder->Decode(hiCnt - p->Freq, p->Freq); // , MinContext->SummFreq); - update1(p); - } - - - void DecodeSymbol2(CRangeDecoderVirt *rangeDecoder) - { - int count, hiCnt, i = MinContext->NumStats - NumMasked; - UInt32 freqSum; - SEE2_CONTEXT* psee2c = makeEscFreq2(i, freqSum); - PPM_CONTEXT::STATE* ps[256], ** pps = ps, * p = GetStateNoCheck(MinContext->Stats)-1; - hiCnt = 0; - do - { - do { p++; } while (CharMask[p->Symbol] == EscCount); - hiCnt += p->Freq; - *pps++ = p; - } - while ( --i ); - - freqSum += hiCnt; - count = rangeDecoder->GetThreshold(freqSum); - - p = *(pps = ps); - if (count < hiCnt) - { - hiCnt = 0; - while ((hiCnt += p->Freq) <= count) - p=*++pps; - rangeDecoder->Decode(hiCnt - p->Freq, p->Freq); // , freqSum); - - psee2c->update(); - update2(p); - } - else - { - rangeDecoder->Decode(hiCnt, freqSum - hiCnt); // , freqSum); - - i = MinContext->NumStats - NumMasked; - pps--; - do { CharMask[(*++pps)->Symbol] = EscCount; } while ( --i ); - psee2c->Summ = (UInt16)(psee2c->Summ + freqSum); - NumMasked = MinContext->NumStats; - } - } - - int DecodeSymbol(CRangeDecoderVirt *rangeDecoder) - { - if (MinContext->NumStats != 1) - DecodeSymbol1(rangeDecoder); - else - DecodeBinSymbol(rangeDecoder); - while ( !FoundState ) - { - do - { - OrderFall++; - MinContext = GetContext(MinContext->Suffix); - if (MinContext == 0) - return -1; - } - while (MinContext->NumStats == NumMasked); - DecodeSymbol2(rangeDecoder); - } - Byte symbol = FoundState->Symbol; - NextContext(); - return symbol; - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.cpp deleted file mode 100644 index 9049a472b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.cpp +++ /dev/null @@ -1,182 +0,0 @@ -// PpmdDecoder.cpp - -#include "StdAfx.h" - -#include "Common/Defs.h" -#include "Windows/Defs.h" - -#include "PpmdDecoder.h" - -namespace NCompress { -namespace NPpmd { - -const int kLenIdFinished = -1; -const int kLenIdNeedInit = -2; - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *properties, UInt32 size) -{ - if (size < 5) - return E_INVALIDARG; - _order = properties[0]; - _usedMemorySize = 0; - for (int i = 0; i < 4; i++) - _usedMemorySize += ((UInt32)(properties[1 + i])) << (i * 8); - - if (_usedMemorySize > kMaxMemBlockSize) - return E_NOTIMPL; - - if (!_rangeDecoder.Create(1 << 20)) - return E_OUTOFMEMORY; - if (!_info.SubAllocator.StartSubAllocator(_usedMemorySize)) - return E_OUTOFMEMORY; - - return S_OK; -} - -class CDecoderFlusher -{ - CDecoder *_coder; -public: - bool NeedFlush; - CDecoderFlusher(CDecoder *coder): _coder(coder), NeedFlush(true) {} - ~CDecoderFlusher() - { - if (NeedFlush) - _coder->Flush(); - _coder->ReleaseStreams(); - } -}; - -HRESULT CDecoder::CodeSpec(UInt32 size, Byte *memStream) -{ - if (_outSizeDefined) - { - const UInt64 rem = _outSize - _processedSize; - if (size > rem) - size = (UInt32)rem; - } - const UInt32 startSize = size; - - if (_remainLen == kLenIdFinished) - return S_OK; - if (_remainLen == kLenIdNeedInit) - { - _rangeDecoder.Init(); - _remainLen = 0; - _info.MaxOrder = 0; - _info.StartModelRare(_order); - } - while (size != 0) - { - int symbol = _info.DecodeSymbol(&_rangeDecoder); - if (symbol < 0) - { - _remainLen = kLenIdFinished; - break; - } - if (memStream != 0) - *memStream++ = (Byte)symbol; - else - _outStream.WriteByte((Byte)symbol); - size--; - } - _processedSize += startSize - size; - return S_OK; -} - -STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - if (!_outStream.Create(1 << 20)) - return E_OUTOFMEMORY; - - SetInStream(inStream); - _outStream.SetStream(outStream); - SetOutStreamSize(outSize); - CDecoderFlusher flusher(this); - - for (;;) - { - _processedSize = _outStream.GetProcessedSize(); - UInt32 curSize = (1 << 18); - RINOK(CodeSpec(curSize, NULL)); - if (_remainLen == kLenIdFinished) - break; - if (progress != NULL) - { - UInt64 inSize = _rangeDecoder.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&inSize, &_processedSize)); - } - if (_outSizeDefined) - if (_outStream.GetProcessedSize() >= _outSize) - break; - } - flusher.NeedFlush = false; - return Flush(); -} - -#ifdef _NO_EXCEPTIONS - -#define PPMD_TRY_BEGIN -#define PPMD_TRY_END - -#else - -#define PPMD_TRY_BEGIN try { -#define PPMD_TRY_END } \ - catch(const CInBufferException &e) { return e.ErrorCode; } \ - catch(const COutBufferException &e) { return e.ErrorCode; } \ - catch(...) { return S_FALSE; } - -#endif - - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - PPMD_TRY_BEGIN - return CodeReal(inStream, outStream, inSize, outSize, progress); - PPMD_TRY_END -} - -STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream) -{ - _rangeDecoder.SetStream(inStream); - return S_OK; -} - -STDMETHODIMP CDecoder::ReleaseInStream() -{ - _rangeDecoder.ReleaseStream(); - return S_OK; -} - -STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize) -{ - _outSizeDefined = (outSize != NULL); - if (_outSizeDefined) - _outSize = *outSize; - _processedSize = 0; - _remainLen = kLenIdNeedInit; - _outStream.Init(); - return S_OK; -} - -#ifndef NO_READ_FROM_CODER - -STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize) -{ - PPMD_TRY_BEGIN - if (processedSize) - *processedSize = 0; - const UInt64 startPos = _processedSize; - RINOK(CodeSpec(size, (Byte *)data)); - if (processedSize) - *processedSize = (UInt32)(_processedSize - startPos); - return Flush(); - PPMD_TRY_END -} - -#endif - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.h deleted file mode 100644 index e14d37303..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdDecoder.h +++ /dev/null @@ -1,86 +0,0 @@ -// PpmdDecoder.h - -#ifndef __COMPRESS_PPMD_DECODER_H -#define __COMPRESS_PPMD_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/OutBuffer.h" - -#include "PpmdDecode.h" -#include "RangeCoder.h" - -namespace NCompress { -namespace NPpmd { - -class CDecoder : - public ICompressCoder, - public ICompressSetDecoderProperties2, - #ifndef NO_READ_FROM_CODER - public ICompressSetInStream, - public ICompressSetOutStreamSize, - public ISequentialInStream, - #endif - public CMyUnknownImp -{ - CRangeDecoder _rangeDecoder; - - COutBuffer _outStream; - - CDecodeInfo _info; - - Byte _order; - UInt32 _usedMemorySize; - - int _remainLen; - UInt64 _outSize; - bool _outSizeDefined; - UInt64 _processedSize; - - HRESULT CodeSpec(UInt32 num, Byte *memStream); - -public: - - #ifndef NO_READ_FROM_CODER - MY_UNKNOWN_IMP4( - ICompressSetDecoderProperties2, - ICompressSetInStream, - ICompressSetOutStreamSize, - ISequentialInStream) - #else - MY_UNKNOWN_IMP1( - ICompressSetDecoderProperties2) - #endif - - void ReleaseStreams() - { - ReleaseInStream(); - _outStream.ReleaseStream(); - } - - HRESULT Flush() { return _outStream.Flush(); } - - STDMETHOD(CodeReal)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - - STDMETHOD(SetInStream)(ISequentialInStream *inStream); - STDMETHOD(ReleaseInStream)(); - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); - - #ifndef NO_READ_FROM_CODER - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); - #endif - - CDecoder(): _outSizeDefined(false) {} -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdRegister.cpp deleted file mode 100644 index eed3d7b16..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdRegister.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// PpmdRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "PpmdDecoder.h" - -static void *CreateCodec() { return (void *)(ICompressCoder *)(new NCompress::NPpmd::CDecoder); } -#ifndef EXTRACT_ONLY -#include "PpmdEncoder.h" -static void *CreateCodecOut() { return (void *)(ICompressCoder *)(new NCompress::NPpmd::CEncoder); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x030401, L"PPMD", 1, false }; - -REGISTER_CODEC(PPMD) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdSubAlloc.h b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdSubAlloc.h deleted file mode 100644 index fdea6d5df..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdSubAlloc.h +++ /dev/null @@ -1,295 +0,0 @@ -// PpmdSubAlloc.h -// This code is based on Dmitry Shkarin's PPMdH code - -#ifndef __COMPRESS_PPMD_SUB_ALLOC_H -#define __COMPRESS_PPMD_SUB_ALLOC_H - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "PpmdType.h" - -const UINT N1=4, N2=4, N3=4, N4=(128+3-1*N1-2*N2-3*N3)/4; -const UINT UNIT_SIZE=12, N_INDEXES=N1+N2+N3+N4; - -// Extra 1 * UNIT_SIZE for NULL support -// Extra 2 * UNIT_SIZE for s0 in GlueFreeBlocks() -const UInt32 kExtraSize = (UNIT_SIZE * 3); -const UInt32 kMaxMemBlockSize = 0xFFFFFFFF - kExtraSize; - -struct MEM_BLK -{ - UInt16 Stamp, NU; - UInt32 Next, Prev; - void InsertAt(Byte *Base, UInt32 p) - { - Prev = p; - MEM_BLK *pp = (MEM_BLK *)(Base + p); - Next = pp->Next; - pp->Next = ((MEM_BLK *)(Base + Next))->Prev = (UInt32)((Byte *)this - Base); - } - void Remove(Byte *Base) - { - ((MEM_BLK *)(Base + Prev))->Next = Next; - ((MEM_BLK *)(Base + Next))->Prev = Prev; - } -}; - - -class CSubAllocator -{ - UInt32 SubAllocatorSize; - Byte Indx2Units[N_INDEXES], Units2Indx[128], GlueCount; - UInt32 FreeList[N_INDEXES]; - - Byte *Base; - Byte *HeapStart, *LoUnit, *HiUnit; -public: - Byte *pText, *UnitsStart; - CSubAllocator(): - SubAllocatorSize(0), - GlueCount(0), - LoUnit(0), - HiUnit(0), - pText(0), - UnitsStart(0) - { - memset(Indx2Units, 0, sizeof(Indx2Units)); - memset(FreeList, 0, sizeof(FreeList)); - } - ~CSubAllocator() - { - StopSubAllocator(); - }; - - void *GetPtr(UInt32 offset) const { return (offset == 0) ? 0 : (void *)(Base + offset); } - void *GetPtrNoCheck(UInt32 offset) const { return (void *)(Base + offset); } - UInt32 GetOffset(void *ptr) const { return (ptr == 0) ? 0 : (UInt32)((Byte *)ptr - Base); } - UInt32 GetOffsetNoCheck(void *ptr) const { return (UInt32)((Byte *)ptr - Base); } - MEM_BLK *GetBlk(UInt32 offset) const { return (MEM_BLK *)(Base + offset); } - UInt32 *GetNode(UInt32 offset) const { return (UInt32 *)(Base + offset); } - - void InsertNode(void* p, int indx) - { - *(UInt32 *)p = FreeList[indx]; - FreeList[indx] = GetOffsetNoCheck(p); - } - - void* RemoveNode(int indx) - { - UInt32 offset = FreeList[indx]; - UInt32 *p = GetNode(offset); - FreeList[indx] = *p; - return (void *)p; - } - - UINT U2B(int NU) const { return (UINT)(NU) * UNIT_SIZE; } - - void SplitBlock(void* pv, int oldIndx, int newIndx) - { - int i, UDiff = Indx2Units[oldIndx] - Indx2Units[newIndx]; - Byte* p = ((Byte*)pv) + U2B(Indx2Units[newIndx]); - if (Indx2Units[i = Units2Indx[UDiff-1]] != UDiff) - { - InsertNode(p, --i); - p += U2B(i = Indx2Units[i]); - UDiff -= i; - } - InsertNode(p, Units2Indx[UDiff - 1]); - } - - UInt32 GetUsedMemory() const - { - UInt32 RetVal = SubAllocatorSize - (UInt32)(HiUnit - LoUnit) - (UInt32)(UnitsStart - pText); - for (UInt32 i = 0; i < N_INDEXES; i++) - for (UInt32 pn = FreeList[i]; pn != 0; RetVal -= (UInt32)Indx2Units[i] * UNIT_SIZE) - pn = *GetNode(pn); - return (RetVal >> 2); - } - - UInt32 GetSubAllocatorSize() const { return SubAllocatorSize; } - - void StopSubAllocator() - { - if (SubAllocatorSize != 0) - { - BigFree(Base); - SubAllocatorSize = 0; - Base = 0; - } - } - - bool StartSubAllocator(UInt32 size) - { - if (SubAllocatorSize == size) - return true; - StopSubAllocator(); - if (size == 0) - Base = 0; - else - { - if ((Base = (Byte *)::BigAlloc(size + kExtraSize)) == 0) - return false; - HeapStart = Base + UNIT_SIZE; // we need such code to support NULL; - } - SubAllocatorSize = size; - return true; - } - - void InitSubAllocator() - { - int i, k; - memset(FreeList, 0, sizeof(FreeList)); - HiUnit = (pText = HeapStart) + SubAllocatorSize; - UINT Diff = UNIT_SIZE * (SubAllocatorSize / 8 / UNIT_SIZE * 7); - LoUnit = UnitsStart = HiUnit - Diff; - for (i = 0, k=1; i < N1 ; i++, k += 1) Indx2Units[i] = (Byte)k; - for (k++; i < N1 + N2 ;i++, k += 2) Indx2Units[i] = (Byte)k; - for (k++; i < N1 + N2 + N3 ;i++,k += 3) Indx2Units[i] = (Byte)k; - for (k++; i < N1 + N2 + N3 + N4; i++, k += 4) Indx2Units[i] = (Byte)k; - GlueCount = 0; - for (k = i = 0; k < 128; k++) - { - i += (Indx2Units[i] < k+1); - Units2Indx[k] = (Byte)i; - } - } - - void GlueFreeBlocks() - { - UInt32 s0 = (UInt32)(HeapStart + SubAllocatorSize - Base); - - // We need add exta MEM_BLK with Stamp=0 - GetBlk(s0)->Stamp = 0; - s0 += UNIT_SIZE; - MEM_BLK *ps0 = GetBlk(s0); - - UInt32 p; - int i; - if (LoUnit != HiUnit) - *LoUnit=0; - ps0->Next = ps0->Prev = s0; - - for (i = 0; i < N_INDEXES; i++) - while (FreeList[i] != 0) - { - MEM_BLK *pp = (MEM_BLK *)RemoveNode(i); - pp->InsertAt(Base, s0); - pp->Stamp = 0xFFFF; - pp->NU = Indx2Units[i]; - } - for (p = ps0->Next; p != s0; p = GetBlk(p)->Next) - { - for (;;) - { - MEM_BLK *pp = GetBlk(p); - MEM_BLK *pp1 = GetBlk(p + pp->NU * UNIT_SIZE); - if (pp1->Stamp != 0xFFFF || int(pp->NU) + pp1->NU >= 0x10000) - break; - pp1->Remove(Base); - pp->NU = (UInt16)(pp->NU + pp1->NU); - } - } - while ((p = ps0->Next) != s0) - { - MEM_BLK *pp = GetBlk(p); - pp->Remove(Base); - int sz; - for (sz = pp->NU; sz > 128; sz -= 128, p += 128 * UNIT_SIZE) - InsertNode(Base + p, N_INDEXES - 1); - if (Indx2Units[i = Units2Indx[sz-1]] != sz) - { - int k = sz - Indx2Units[--i]; - InsertNode(Base + p + (sz - k) * UNIT_SIZE, k - 1); - } - InsertNode(Base + p, i); - } - } - void* AllocUnitsRare(int indx) - { - if ( !GlueCount ) - { - GlueCount = 255; - GlueFreeBlocks(); - if (FreeList[indx] != 0) - return RemoveNode(indx); - } - int i = indx; - do - { - if (++i == N_INDEXES) - { - GlueCount--; - i = U2B(Indx2Units[indx]); - return (UnitsStart - pText > i) ? (UnitsStart -= i) : (NULL); - } - } while (FreeList[i] == 0); - void* RetVal = RemoveNode(i); - SplitBlock(RetVal, i, indx); - return RetVal; - } - - void* AllocUnits(int NU) - { - int indx = Units2Indx[NU - 1]; - if (FreeList[indx] != 0) - return RemoveNode(indx); - void* RetVal = LoUnit; - LoUnit += U2B(Indx2Units[indx]); - if (LoUnit <= HiUnit) - return RetVal; - LoUnit -= U2B(Indx2Units[indx]); - return AllocUnitsRare(indx); - } - - void* AllocContext() - { - if (HiUnit != LoUnit) - return (HiUnit -= UNIT_SIZE); - if (FreeList[0] != 0) - return RemoveNode(0); - return AllocUnitsRare(0); - } - - void* ExpandUnits(void* oldPtr, int oldNU) - { - int i0=Units2Indx[oldNU - 1], i1=Units2Indx[oldNU - 1 + 1]; - if (i0 == i1) - return oldPtr; - void* ptr = AllocUnits(oldNU + 1); - if (ptr) - { - memcpy(ptr, oldPtr, U2B(oldNU)); - InsertNode(oldPtr, i0); - } - return ptr; - } - - void* ShrinkUnits(void* oldPtr, int oldNU, int newNU) - { - int i0 = Units2Indx[oldNU - 1], i1 = Units2Indx[newNU - 1]; - if (i0 == i1) - return oldPtr; - if (FreeList[i1] != 0) - { - void* ptr = RemoveNode(i1); - memcpy(ptr, oldPtr, U2B(newNU)); - InsertNode(oldPtr,i0); - return ptr; - } - else - { - SplitBlock(oldPtr, i0, i1); - return oldPtr; - } - } - - void FreeUnits(void* ptr, int oldNU) - { - InsertNode(ptr, Units2Indx[oldNU - 1]); - } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdType.h b/desmume/src/windows/7z/CPP/7zip/Compress/PpmdType.h deleted file mode 100644 index 313c5f28e..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/PpmdType.h +++ /dev/null @@ -1,20 +0,0 @@ -/**************************************************************************** - * This file is part of PPMd project * - * Written and distributed to public domain by Dmitry Shkarin 1997, * - * 1999-2001 * - * Contents: compilation parameters and miscelaneous definitions * - * Comments: system & compiler dependent file - - * modified by Igor Pavlov (2004-08-29). - ****************************************************************************/ - -#ifndef __COMPRESS_PPMD_TYPE_H -#define __COMPRESS_PPMD_TYPE_H - -const int kMaxOrderCompress = 32; -const int MAX_O = 255; /* maximum allowed model order */ - -template -inline void _PPMD_SWAP(T& t1,T& t2) { T tmp = t1; t1 = t2; t2 = tmp; } - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoder.h deleted file mode 100644 index 8040bcd06..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoder.h +++ /dev/null @@ -1,204 +0,0 @@ -// Compress/RangeCoder.h - -#ifndef __COMPRESS_RANGE_CODER_H -#define __COMPRESS_RANGE_CODER_H - -#include "../Common/InBuffer.h" -#include "../Common/OutBuffer.h" - -namespace NCompress { -namespace NRangeCoder { - -const int kNumTopBits = 24; -const UInt32 kTopValue = (1 << kNumTopBits); - -class CEncoder -{ - UInt32 _cacheSize; - Byte _cache; -public: - UInt64 Low; - UInt32 Range; - COutBuffer Stream; - bool Create(UInt32 bufferSize) { return Stream.Create(bufferSize); } - - void SetStream(ISequentialOutStream *stream) { Stream.SetStream(stream); } - void Init() - { - Stream.Init(); - Low = 0; - Range = 0xFFFFFFFF; - _cacheSize = 1; - _cache = 0; - } - - void FlushData() - { - // Low += 1; - for(int i = 0; i < 5; i++) - ShiftLow(); - } - - HRESULT FlushStream() { return Stream.Flush(); } - - void ReleaseStream() { Stream.ReleaseStream(); } - - void Encode(UInt32 start, UInt32 size, UInt32 total) - { - Low += start * (Range /= total); - Range *= size; - while (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } - - void ShiftLow() - { - if ((UInt32)Low < (UInt32)0xFF000000 || (int)(Low >> 32) != 0) - { - Byte temp = _cache; - do - { - Stream.WriteByte((Byte)(temp + (Byte)(Low >> 32))); - temp = 0xFF; - } - while(--_cacheSize != 0); - _cache = (Byte)((UInt32)Low >> 24); - } - _cacheSize++; - Low = (UInt32)Low << 8; - } - - void EncodeDirectBits(UInt32 value, int numBits) - { - for (numBits--; numBits >= 0; numBits--) - { - Range >>= 1; - Low += Range & (0 - ((value >> numBits) & 1)); - if (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } - } - - void EncodeBit(UInt32 size0, UInt32 numTotalBits, UInt32 symbol) - { - UInt32 newBound = (Range >> numTotalBits) * size0; - if (symbol == 0) - Range = newBound; - else - { - Low += newBound; - Range -= newBound; - } - while (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } - - UInt64 GetProcessedSize() { return Stream.GetProcessedSize() + _cacheSize + 4; } -}; - -class CDecoder -{ -public: - CInBuffer Stream; - UInt32 Range; - UInt32 Code; - bool Create(UInt32 bufferSize) { return Stream.Create(bufferSize); } - - void Normalize() - { - while (Range < kTopValue) - { - Code = (Code << 8) | Stream.ReadByte(); - Range <<= 8; - } - } - - void SetStream(ISequentialInStream *stream) { Stream.SetStream(stream); } - void Init() - { - Stream.Init(); - Code = 0; - Range = 0xFFFFFFFF; - for(int i = 0; i < 5; i++) - Code = (Code << 8) | Stream.ReadByte(); - } - - void ReleaseStream() { Stream.ReleaseStream(); } - - UInt32 GetThreshold(UInt32 total) - { - return (Code) / ( Range /= total); - } - - void Decode(UInt32 start, UInt32 size) - { - Code -= start * Range; - Range *= size; - Normalize(); - } - - UInt32 DecodeDirectBits(int numTotalBits) - { - UInt32 range = Range; - UInt32 code = Code; - UInt32 result = 0; - for (int i = numTotalBits; i != 0; i--) - { - range >>= 1; - /* - result <<= 1; - if (code >= range) - { - code -= range; - result |= 1; - } - */ - UInt32 t = (code - range) >> 31; - code -= range & (t - 1); - result = (result << 1) | (1 - t); - - if (range < kTopValue) - { - code = (code << 8) | Stream.ReadByte(); - range <<= 8; - } - } - Range = range; - Code = code; - return result; - } - - UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits) - { - UInt32 newBound = (Range >> numTotalBits) * size0; - UInt32 symbol; - if (Code < newBound) - { - symbol = 0; - Range = newBound; - } - else - { - symbol = 1; - Code -= newBound; - Range -= newBound; - } - Normalize(); - return symbol; - } - - UInt64 GetProcessedSize() {return Stream.GetProcessedSize(); } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoderBit.h b/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoderBit.h deleted file mode 100644 index f2fe45d7f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/RangeCoderBit.h +++ /dev/null @@ -1,113 +0,0 @@ -// Compress/RangeCoderBit.h - -#ifndef __COMPRESS_RANGE_CODER_BIT_H -#define __COMPRESS_RANGE_CODER_BIT_H - -#include "RangeCoder.h" - -namespace NCompress { -namespace NRangeCoder { - -const int kNumBitModelTotalBits = 11; -const UInt32 kBitModelTotal = (1 << kNumBitModelTotalBits); - -const int kNumMoveReducingBits = 4; - -const int kNumBitPriceShiftBits = 4; -const UInt32 kBitPrice = 1 << kNumBitPriceShiftBits; - -extern UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits]; - -template -class CBitModel -{ -public: - UInt32 Prob; - void UpdateModel(UInt32 symbol) - { - /* - Prob -= (Prob + ((symbol - 1) & ((1 << numMoveBits) - 1))) >> numMoveBits; - Prob += (1 - symbol) << (kNumBitModelTotalBits - numMoveBits); - */ - if (symbol == 0) - Prob += (kBitModelTotal - Prob) >> numMoveBits; - else - Prob -= (Prob) >> numMoveBits; - } -public: - void Init() { Prob = kBitModelTotal / 2; } -}; - -template -class CBitEncoder: public CBitModel -{ -public: - void Encode(CEncoder *encoder, UInt32 symbol) - { - /* - encoder->EncodeBit(this->Prob, kNumBitModelTotalBits, symbol); - this->UpdateModel(symbol); - */ - UInt32 newBound = (encoder->Range >> kNumBitModelTotalBits) * this->Prob; - if (symbol == 0) - { - encoder->Range = newBound; - this->Prob += (kBitModelTotal - this->Prob) >> numMoveBits; - } - else - { - encoder->Low += newBound; - encoder->Range -= newBound; - this->Prob -= (this->Prob) >> numMoveBits; - } - if (encoder->Range < kTopValue) - { - encoder->Range <<= 8; - encoder->ShiftLow(); - } - } - UInt32 GetPrice(UInt32 symbol) const - { - return ProbPrices[(this->Prob ^ ((-(int)symbol)) & (kBitModelTotal - 1)) >> kNumMoveReducingBits]; - } - UInt32 GetPrice0() const { return ProbPrices[this->Prob >> kNumMoveReducingBits]; } - UInt32 GetPrice1() const { return ProbPrices[(this->Prob ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]; } -}; - - -template -class CBitDecoder: public CBitModel -{ -public: - UInt32 Decode(CDecoder *decoder) - { - UInt32 newBound = (decoder->Range >> kNumBitModelTotalBits) * this->Prob; - if (decoder->Code < newBound) - { - decoder->Range = newBound; - this->Prob += (kBitModelTotal - this->Prob) >> numMoveBits; - if (decoder->Range < kTopValue) - { - decoder->Code = (decoder->Code << 8) | decoder->Stream.ReadByte(); - decoder->Range <<= 8; - } - return 0; - } - else - { - decoder->Range -= newBound; - decoder->Code -= newBound; - this->Prob -= (this->Prob) >> numMoveBits; - if (decoder->Range < kTopValue) - { - decoder->Code = (decoder->Code << 8) | decoder->Stream.ReadByte(); - decoder->Range <<= 8; - } - return 1; - } - } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.cpp deleted file mode 100644 index a6a7c854f..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.cpp +++ /dev/null @@ -1,478 +0,0 @@ -// Rar1Decoder.cpp -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#include "StdAfx.h" - -#include "Rar1Decoder.h" - -namespace NCompress { -namespace NRar1 { - -static UInt32 PosL1[]={0,0,0,2,3,5,7,11,16,20,24,32,32, 256}; -static UInt32 PosL2[]={0,0,0,0,5,7,9,13,18,22,26,34,36, 256}; -static UInt32 PosHf0[]={0,0,0,0,0,8,16,24,33,33,33,33,33, 257}; -static UInt32 PosHf1[]={0,0,0,0,0,0,4,44,60,76,80,80,127, 257}; -static UInt32 PosHf2[]={0,0,0,0,0,0,2,7,53,117,233, 257,0}; -static UInt32 PosHf3[]={0,0,0,0,0,0,0,2,16,218,251, 257,0}; -static UInt32 PosHf4[]={0,0,0,0,0,0,0,0,0,255, 257,0,0}; - -static const UInt32 kHistorySize = (1 << 16); - -class CCoderReleaser -{ - CDecoder *m_Coder; -public: - CCoderReleaser(CDecoder *coder): m_Coder(coder) {} - ~CCoderReleaser() { m_Coder->ReleaseStreams(); } -}; - -CDecoder::CDecoder(): m_IsSolid(false) { } - -void CDecoder::InitStructures() -{ - for(int i = 0; i < kNumRepDists; i++) - m_RepDists[i] = 0; - m_RepDistPtr = 0; - LastLength = 0; - LastDist = 0; -} - -UInt32 CDecoder::ReadBits(int numBits) { return m_InBitStream.ReadBits(numBits); } - -HRESULT CDecoder::CopyBlock(UInt32 distance, UInt32 len) -{ - m_UnpackSize -= len; - return m_OutWindowStream.CopyBlock(distance, len) ? S_OK : S_FALSE; -} - - -UInt32 CDecoder::DecodeNum(const UInt32 *posTab) -{ - UInt32 startPos = 2; - UInt32 num = m_InBitStream.GetValue(12); - for (;;) - { - UInt32 cur = (posTab[startPos + 1] - posTab[startPos]) << (12 - startPos); - if (num < cur) - break; - startPos++; - num -= cur; - } - m_InBitStream.MovePos(startPos); - return((num >> (12 - startPos)) + posTab[startPos]); -} - -static Byte kShortLen1[] = {1,3,4,4,5,6,7,8,8,4,4,5,6,6 }; -static Byte kShortLen1a[] = {1,4,4,4,5,6,7,8,8,4,4,5,6,6,4 }; -static Byte kShortLen2[] = {2,3,3,3,4,4,5,6,6,4,4,5,6,6 }; -static Byte kShortLen2a[] = {2,3,3,4,4,4,5,6,6,4,4,5,6,6,4 }; -static UInt32 kShortXor1[] = {0,0xa0,0xd0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff,0xc0,0x80,0x90,0x98,0x9c,0xb0}; -static UInt32 kShortXor2[] = {0,0x40,0x60,0xa0,0xd0,0xe0,0xf0,0xf8,0xfc,0xc0,0x80,0x90,0x98,0x9c,0xb0}; - -HRESULT CDecoder::ShortLZ() -{ - UInt32 len, saveLen, dist; - int distancePlace; - Byte *kShortLen; - const UInt32 *kShortXor; - NumHuf = 0; - - if (LCount == 2) - { - if (ReadBits(1)) - return CopyBlock(LastDist, LastLength); - LCount = 0; - } - - UInt32 bitField = m_InBitStream.GetValue(8); - - if (AvrLn1 < 37) - { - kShortLen = Buf60 ? kShortLen1a : kShortLen1; - kShortXor = kShortXor1; - } - else - { - kShortLen = Buf60 ? kShortLen2a : kShortLen2; - kShortXor = kShortXor2; - } - - for (len = 0; ((bitField ^ kShortXor[len]) & (~(0xff >> kShortLen[len]))) != 0; len++); - m_InBitStream.MovePos(kShortLen[len]); - - if (len >= 9) - { - if (len == 9) - { - LCount++; - return CopyBlock(LastDist, LastLength); - } - if (len == 14) - { - LCount = 0; - len = DecodeNum(PosL2) + 5; - dist = 0x8000 + ReadBits(15) - 1; - LastLength = len; - LastDist = dist; - return CopyBlock(dist, len); - } - - LCount = 0; - saveLen = len; - dist = m_RepDists[(m_RepDistPtr - (len - 9)) & 3]; - len = DecodeNum(PosL1) + 2; - if (len == 0x101 && saveLen == 10) - { - Buf60 ^= 1; - return S_OK; - } - if (dist >= 256) - len++; - if (dist >= MaxDist3 - 1) - len++; - } - else - { - LCount = 0; - AvrLn1 += len; - AvrLn1 -= AvrLn1 >> 4; - - distancePlace = DecodeNum(PosHf2) & 0xff; - dist = ChSetA[distancePlace]; - if (--distancePlace != -1) - { - PlaceA[dist]--; - UInt32 lastDistance = ChSetA[distancePlace]; - PlaceA[lastDistance]++; - ChSetA[distancePlace + 1] = lastDistance; - ChSetA[distancePlace] = dist; - } - len += 2; - } - m_RepDists[m_RepDistPtr++] = dist; - m_RepDistPtr &= 3; - LastLength = len; - LastDist = dist; - return CopyBlock(dist, len); -} - - -HRESULT CDecoder::LongLZ() -{ - UInt32 len; - UInt32 dist; - UInt32 distancePlace, newDistancePlace; - UInt32 oldAvr2, oldAvr3; - - NumHuf = 0; - Nlzb += 16; - if (Nlzb > 0xff) - { - Nlzb = 0x90; - Nhfb >>= 1; - } - oldAvr2=AvrLn2; - - if (AvrLn2 >= 122) - len = DecodeNum(PosL2); - else if (AvrLn2 >= 64) - len = DecodeNum(PosL1); - else - { - UInt32 bitField = m_InBitStream.GetValue(16); - if (bitField < 0x100) - { - len = bitField; - m_InBitStream.MovePos(16); - } - else - { - for (len = 0; ((bitField << len) & 0x8000) == 0; len++) - ; - m_InBitStream.MovePos(len + 1); - } - } - - AvrLn2 += len; - AvrLn2 -= AvrLn2 >> 5; - - if (AvrPlcB > 0x28ff) - distancePlace = DecodeNum(PosHf2); - else if (AvrPlcB > 0x6ff) - distancePlace = DecodeNum(PosHf1); - else - distancePlace = DecodeNum(PosHf0); - - AvrPlcB += distancePlace; - AvrPlcB -= AvrPlcB >> 8; - for (;;) - { - dist = ChSetB[distancePlace & 0xff]; - newDistancePlace = NToPlB[dist++ & 0xff]++; - if (!(dist & 0xff)) - CorrHuff(ChSetB,NToPlB); - else - break; - } - - ChSetB[distancePlace] = ChSetB[newDistancePlace]; - ChSetB[newDistancePlace] = dist; - - dist = ((dist & 0xff00) >> 1) | ReadBits(7); - - oldAvr3 = AvrLn3; - if (len != 1 && len != 4) - if (len == 0 && dist <= MaxDist3) - { - AvrLn3++; - AvrLn3 -= AvrLn3 >> 8; - } - else - if (AvrLn3 > 0) - AvrLn3--; - len += 3; - if (dist >= MaxDist3) - len++; - if (dist <= 256) - len += 8; - if (oldAvr3 > 0xb0 || AvrPlc >= 0x2a00 && oldAvr2 < 0x40) - MaxDist3 = 0x7f00; - else - MaxDist3 = 0x2001; - m_RepDists[m_RepDistPtr++] = --dist; - m_RepDistPtr &= 3; - LastLength = len; - LastDist = dist; - return CopyBlock(dist, len); -} - - -HRESULT CDecoder::HuffDecode() -{ - UInt32 curByte, newBytePlace; - UInt32 len; - UInt32 dist; - int bytePlace; - - if (AvrPlc > 0x75ff) bytePlace = DecodeNum(PosHf4); - else if (AvrPlc > 0x5dff) bytePlace = DecodeNum(PosHf3); - else if (AvrPlc > 0x35ff) bytePlace = DecodeNum(PosHf2); - else if (AvrPlc > 0x0dff) bytePlace = DecodeNum(PosHf1); - else bytePlace = DecodeNum(PosHf0); - if (StMode) - { - if (--bytePlace == -1) - { - if (ReadBits(1)) - { - NumHuf = StMode = 0; - return S_OK; - } - else - { - len = (ReadBits(1)) ? 4 : 3; - dist = DecodeNum(PosHf2); - dist = (dist << 5) | ReadBits(5); - return CopyBlock(dist - 1, len); - } - } - } - else if (NumHuf++ >= 16 && FlagsCnt == 0) - StMode = 1; - bytePlace &= 0xff; - AvrPlc += bytePlace; - AvrPlc -= AvrPlc >> 8; - Nhfb+=16; - if (Nhfb > 0xff) - { - Nhfb=0x90; - Nlzb >>= 1; - } - - m_UnpackSize --; - m_OutWindowStream.PutByte((Byte)(ChSet[bytePlace] >> 8)); - - for (;;) - { - curByte = ChSet[bytePlace]; - newBytePlace = NToPl[curByte++ & 0xff]++; - if ((curByte & 0xff) > 0xa1) - CorrHuff(ChSet, NToPl); - else - break; - } - - ChSet[bytePlace] = ChSet[newBytePlace]; - ChSet[newBytePlace] = curByte; - return S_OK; -} - - -void CDecoder::GetFlagsBuf() -{ - UInt32 flags, newFlagsPlace; - UInt32 flagsPlace = DecodeNum(PosHf2); - - for (;;) - { - flags = ChSetC[flagsPlace]; - FlagBuf = flags >> 8; - newFlagsPlace = NToPlC[flags++ & 0xff]++; - if ((flags & 0xff) != 0) - break; - CorrHuff(ChSetC, NToPlC); - } - - ChSetC[flagsPlace] = ChSetC[newFlagsPlace]; - ChSetC[newFlagsPlace] = flags; -} - -void CDecoder::InitData() -{ - if (!m_IsSolid) - { - AvrPlcB = AvrLn1 = AvrLn2 = AvrLn3 = NumHuf = Buf60 = 0; - AvrPlc = 0x3500; - MaxDist3 = 0x2001; - Nhfb = Nlzb = 0x80; - } - FlagsCnt = 0; - FlagBuf = 0; - StMode = 0; - LCount = 0; -} - -void CDecoder::CorrHuff(UInt32 *CharSet,UInt32 *NumToPlace) -{ - int i; - for (i = 7; i >= 0; i--) - for (int j = 0; j < 32; j++, CharSet++) - *CharSet = (*CharSet & ~0xff) | i; - memset(NumToPlace, 0, sizeof(NToPl)); - for (i = 6; i >= 0; i--) - NumToPlace[i] = (7 - i) * 32; -} - -void CDecoder::InitHuff() -{ - for (UInt32 i = 0; i < 256; i++) - { - Place[i] = PlaceA[i] = PlaceB[i] = i; - PlaceC[i] = (~i + 1) & 0xff; - ChSet[i] = ChSetB[i] = i << 8; - ChSetA[i] = i; - ChSetC[i] = ((~i + 1) & 0xff) << 8; - } - memset(NToPl, 0, sizeof(NToPl)); - memset(NToPlB, 0, sizeof(NToPlB)); - memset(NToPlC, 0, sizeof(NToPlC)); - CorrHuff(ChSetB, NToPlB); -} - -HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo * /* progress */) -{ - if (inSize == NULL || outSize == NULL) - return E_INVALIDARG; - - if (!m_OutWindowStream.Create(kHistorySize)) - return E_OUTOFMEMORY; - if (!m_InBitStream.Create(1 << 20)) - return E_OUTOFMEMORY; - - m_UnpackSize = (Int64)*outSize; - m_OutWindowStream.SetStream(outStream); - m_OutWindowStream.Init(m_IsSolid); - m_InBitStream.SetStream(inStream); - m_InBitStream.Init(); - - CCoderReleaser coderReleaser(this); - InitData(); - if (!m_IsSolid) - { - InitStructures(); - InitHuff(); - } - if (m_UnpackSize > 0) - { - GetFlagsBuf(); - FlagsCnt = 8; - } - - while (m_UnpackSize > 0) - { - if (StMode) - { - RINOK(HuffDecode()); - continue; - } - - if (--FlagsCnt < 0) - { - GetFlagsBuf(); - FlagsCnt=7; - } - - if (FlagBuf & 0x80) - { - FlagBuf <<= 1; - if (Nlzb > Nhfb) - { - RINOK(LongLZ()); - } - else - { - RINOK(HuffDecode()); - } - } - else - { - FlagBuf <<= 1; - if (--FlagsCnt < 0) - { - GetFlagsBuf(); - FlagsCnt = 7; - } - if (FlagBuf & 0x80) - { - FlagBuf <<= 1; - if (Nlzb > Nhfb) - { - RINOK(HuffDecode()); - } - else - { - RINOK(LongLZ()); - } - } - else - { - FlagBuf <<= 1; - RINOK(ShortLZ()); - } - } - } - if (m_UnpackSize < 0) - return S_FALSE; - return m_OutWindowStream.Flush(); -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress); } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const CLzOutWindowException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - if (size < 1) - return E_INVALIDARG; - m_IsSolid = (data[0] != 0); - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.h deleted file mode 100644 index 1b960e457..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar1Decoder.h +++ /dev/null @@ -1,88 +0,0 @@ -// Rar1Decoder.h -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#ifndef __COMPRESS_RAR1_DECODER_H -#define __COMPRESS_RAR1_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" - -#include "BitmDecoder.h" -#include "HuffmanDecoder.h" -#include "LzOutWindow.h" - -namespace NCompress { -namespace NRar1 { - -const UInt32 kNumRepDists = 4; - -typedef NBitm::CDecoder CBitDecoder; - -class CDecoder : - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ -public: - CLzOutWindow m_OutWindowStream; - CBitDecoder m_InBitStream; - - UInt32 m_RepDists[kNumRepDists]; - UInt32 m_RepDistPtr; - - UInt32 LastDist; - UInt32 LastLength; - - Int64 m_UnpackSize; - bool m_IsSolid; - - UInt32 ReadBits(int numBits); - HRESULT CopyBlock(UInt32 distance, UInt32 len); - - UInt32 DecodeNum(const UInt32 *posTab); - HRESULT ShortLZ(); - HRESULT LongLZ(); - HRESULT HuffDecode(); - void GetFlagsBuf(); - void InitData(); - void InitHuff(); - void CorrHuff(UInt32 *CharSet, UInt32 *NumToPlace); - void OldUnpWriteBuf(); - - UInt32 ChSet[256],ChSetA[256],ChSetB[256],ChSetC[256]; - UInt32 Place[256],PlaceA[256],PlaceB[256],PlaceC[256]; - UInt32 NToPl[256],NToPlB[256],NToPlC[256]; - UInt32 FlagBuf,AvrPlc,AvrPlcB,AvrLn1,AvrLn2,AvrLn3; - int Buf60,NumHuf,StMode,LCount,FlagsCnt; - UInt32 Nhfb,Nlzb,MaxDist3; - - void InitStructures(); - - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - -public: - CDecoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - void ReleaseStreams() - { - m_OutWindowStream.ReleaseStream(); - m_InBitStream.ReleaseStream(); - } - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.cpp deleted file mode 100644 index 194a4bdf3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.cpp +++ /dev/null @@ -1,389 +0,0 @@ -// Rar2Decoder.cpp -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#include "StdAfx.h" - -#include "Rar2Decoder.h" - -namespace NCompress { -namespace NRar2 { - -namespace NMultimedia { - -Byte CFilter::Decode(int &channelDelta, Byte deltaByte) -{ - D4 = D3; - D3 = D2; - D2 = LastDelta - D1; - D1 = LastDelta; - int predictedValue = ((8 * LastChar + K1 * D1 + K2 * D2 + K3 * D3 + K4 * D4 + K5 * channelDelta) >> 3); - - Byte realValue = (Byte)(predictedValue - deltaByte); - int i = ((int)(signed char)deltaByte) << 3; - - Dif[0] += abs(i); - Dif[1] += abs(i - D1); - Dif[2] += abs(i + D1); - Dif[3] += abs(i - D2); - Dif[4] += abs(i + D2); - Dif[5] += abs(i - D3); - Dif[6] += abs(i + D3); - Dif[7] += abs(i - D4); - Dif[8] += abs(i + D4); - Dif[9] += abs(i - channelDelta); - Dif[10] += abs(i + channelDelta); - - channelDelta = LastDelta = (signed char)(realValue - LastChar); - LastChar = realValue; - - if (((++ByteCount) & 0x1F) == 0) - { - UInt32 minDif = Dif[0]; - UInt32 numMinDif = 0; - Dif[0] = 0; - for (i = 1; i < sizeof(Dif) / sizeof(Dif[0]); i++) - { - if (Dif[i] < minDif) - { - minDif = Dif[i]; - numMinDif = i; - } - Dif[i] = 0; - } - switch(numMinDif) - { - case 1: if (K1 >= -16) K1--; break; - case 2: if (K1 < 16) K1++; break; - case 3: if (K2 >= -16) K2--; break; - case 4: if (K2 < 16) K2++; break; - case 5: if (K3 >= -16) K3--; break; - case 6: if (K3 < 16) K3++; break; - case 7: if (K4 >= -16) K4--; break; - case 8: if (K4 < 16) K4++; break; - case 9: if (K5 >= -16) K5--; break; - case 10:if (K5 < 16) K5++; break; - } - } - return realValue; -} -} - -static const char *kNumberErrorMessage = "Number error"; - -static const UInt32 kHistorySize = 1 << 20; - -static const int kNumStats = 11; - -static const UInt32 kWindowReservSize = (1 << 22) + 256; - -CDecoder::CDecoder(): - m_IsSolid(false) -{ -} - -void CDecoder::InitStructures() -{ - m_MmFilter.Init(); - for(int i = 0; i < kNumRepDists; i++) - m_RepDists[i] = 0; - m_RepDistPtr = 0; - m_LastLength = 0; - memset(m_LastLevels, 0, kMaxTableSize); -} - -UInt32 CDecoder::ReadBits(int numBits) { return m_InBitStream.ReadBits(numBits); } - -#define RIF(x) { if (!(x)) return false; } - -bool CDecoder::ReadTables(void) -{ - Byte levelLevels[kLevelTableSize]; - Byte newLevels[kMaxTableSize]; - m_AudioMode = (ReadBits(1) == 1); - - if (ReadBits(1) == 0) - memset(m_LastLevels, 0, kMaxTableSize); - int numLevels; - if (m_AudioMode) - { - m_NumChannels = ReadBits(2) + 1; - if (m_MmFilter.CurrentChannel >= m_NumChannels) - m_MmFilter.CurrentChannel = 0; - numLevels = m_NumChannels * kMMTableSize; - } - else - numLevels = kHeapTablesSizesSum; - - int i; - for (i = 0; i < kLevelTableSize; i++) - levelLevels[i] = (Byte)ReadBits(4); - RIF(m_LevelDecoder.SetCodeLengths(levelLevels)); - i = 0; - while (i < numLevels) - { - UInt32 number = m_LevelDecoder.DecodeSymbol(&m_InBitStream); - if (number < kTableDirectLevels) - { - newLevels[i] = (Byte)((number + m_LastLevels[i]) & kLevelMask); - i++; - } - else - { - if (number == kTableLevelRepNumber) - { - int t = ReadBits(2) + 3; - for (int reps = t; reps > 0 && i < numLevels ; reps--, i++) - newLevels[i] = newLevels[i - 1]; - } - else - { - int num; - if (number == kTableLevel0Number) - num = ReadBits(3) + 3; - else if (number == kTableLevel0Number2) - num = ReadBits(7) + 11; - else - return false; - for (;num > 0 && i < numLevels; num--) - newLevels[i++] = 0; - } - } - } - if (m_AudioMode) - for (i = 0; i < m_NumChannels; i++) - { - RIF(m_MMDecoders[i].SetCodeLengths(&newLevels[i * kMMTableSize])); - } - else - { - RIF(m_MainDecoder.SetCodeLengths(&newLevels[0])); - RIF(m_DistDecoder.SetCodeLengths(&newLevels[kMainTableSize])); - RIF(m_LenDecoder.SetCodeLengths(&newLevels[kMainTableSize + kDistTableSize])); - } - memcpy(m_LastLevels, newLevels, kMaxTableSize); - return true; -} - -bool CDecoder::ReadLastTables() -{ - // it differs a little from pure RAR sources; - // UInt64 ttt = m_InBitStream.GetProcessedSize() + 2; - // + 2 works for: return 0xFF; in CInBuffer::ReadByte. - if (m_InBitStream.GetProcessedSize() + 7 <= m_PackSize) // test it: probably incorrect; - // if (m_InBitStream.GetProcessedSize() + 2 <= m_PackSize) // test it: probably incorrect; - if (m_AudioMode) - { - UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].DecodeSymbol(&m_InBitStream); - if (symbol == 256) - return ReadTables(); - if (symbol >= kMMTableSize) - return false; - } - else - { - UInt32 number = m_MainDecoder.DecodeSymbol(&m_InBitStream); - if (number == kReadTableNumber) - return ReadTables(); - if (number >= kMainTableSize) - return false; - } - return true; -} - -class CCoderReleaser -{ - CDecoder *m_Coder; -public: - CCoderReleaser(CDecoder *coder): m_Coder(coder) {} - ~CCoderReleaser() - { - m_Coder->ReleaseStreams(); - } -}; - -bool CDecoder::DecodeMm(UInt32 pos) -{ - while (pos-- > 0) - { - UInt32 symbol = m_MMDecoders[m_MmFilter.CurrentChannel].DecodeSymbol(&m_InBitStream); - if (symbol == 256) - return true; - if (symbol >= kMMTableSize) - return false; - /* - Byte byPredict = m_Predictor.Predict(); - Byte byReal = (Byte)(byPredict - (Byte)symbol); - m_Predictor.Update(byReal, byPredict); - */ - Byte byReal = m_MmFilter.Decode((Byte)symbol); - m_OutWindowStream.PutByte(byReal); - if (++m_MmFilter.CurrentChannel == m_NumChannels) - m_MmFilter.CurrentChannel = 0; - } - return true; -} - -bool CDecoder::DecodeLz(Int32 pos) -{ - while (pos > 0) - { - UInt32 number = m_MainDecoder.DecodeSymbol(&m_InBitStream); - UInt32 length, distance; - if (number < 256) - { - m_OutWindowStream.PutByte(Byte(number)); - pos--; - continue; - } - else if (number >= kMatchNumber) - { - number -= kMatchNumber; - length = kNormalMatchMinLen + UInt32(kLenStart[number]) + - m_InBitStream.ReadBits(kLenDirectBits[number]); - number = m_DistDecoder.DecodeSymbol(&m_InBitStream); - if (number >= kDistTableSize) - return false; - distance = kDistStart[number] + m_InBitStream.ReadBits(kDistDirectBits[number]); - if (distance >= kDistLimit3) - { - length += 2 - ((distance - kDistLimit4) >> 31); - // length++; - // if (distance >= kDistLimit4) - // length++; - } - } - else if (number == kRepBothNumber) - { - length = m_LastLength; - distance = m_RepDists[(m_RepDistPtr + 4 - 1) & 3]; - } - else if (number < kLen2Number) - { - distance = m_RepDists[(m_RepDistPtr - (number - kRepNumber + 1)) & 3]; - number = m_LenDecoder.DecodeSymbol(&m_InBitStream); - if (number >= kLenTableSize) - return false; - length = 2 + kLenStart[number] + m_InBitStream.ReadBits(kLenDirectBits[number]); - if (distance >= kDistLimit2) - { - length++; - if (distance >= kDistLimit3) - { - length += 2 - ((distance - kDistLimit4) >> 31); - // length++; - // if (distance >= kDistLimit4) - // length++; - } - } - } - else if (number < kReadTableNumber) - { - number -= kLen2Number; - distance = kLen2DistStarts[number] + - m_InBitStream.ReadBits(kLen2DistDirectBits[number]); - length = 2; - } - else if (number == kReadTableNumber) - return true; - else - return false; - m_RepDists[m_RepDistPtr++ & 3] = distance; - m_LastLength = length; - if (!m_OutWindowStream.CopyBlock(distance, length)) - return false; - pos -= length; - } - return true; -} - -HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - if (inSize == NULL || outSize == NULL) - return E_INVALIDARG; - - if (!m_OutWindowStream.Create(kHistorySize)) - return E_OUTOFMEMORY; - if (!m_InBitStream.Create(1 << 20)) - return E_OUTOFMEMORY; - - m_PackSize = *inSize; - - UInt64 pos = 0, unPackSize = *outSize; - - m_OutWindowStream.SetStream(outStream); - m_OutWindowStream.Init(m_IsSolid); - m_InBitStream.SetStream(inStream); - m_InBitStream.Init(); - - CCoderReleaser coderReleaser(this); - if (!m_IsSolid) - { - InitStructures(); - if (unPackSize == 0) - { - if (m_InBitStream.GetProcessedSize() + 2 <= m_PackSize) // test it: probably incorrect; - if (!ReadTables()) - return S_FALSE; - return S_OK; - } - if (!ReadTables()) - return S_FALSE; - } - - UInt64 startPos = m_OutWindowStream.GetProcessedSize(); - while(pos < unPackSize) - { - UInt32 blockSize = 1 << 20; - if (blockSize > unPackSize - pos) - blockSize = (UInt32)(unPackSize - pos); - UInt64 blockStartPos = m_OutWindowStream.GetProcessedSize(); - if (m_AudioMode) - { - if (!DecodeMm(blockSize)) - return S_FALSE; - } - else - { - if (!DecodeLz((Int32)blockSize)) - return S_FALSE; - } - UInt64 globalPos = m_OutWindowStream.GetProcessedSize(); - pos = globalPos - blockStartPos; - if (pos < blockSize) - if (!ReadTables()) - return S_FALSE; - pos = globalPos - startPos; - if (progress != 0) - { - UInt64 packSize = m_InBitStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &pos)); - } - } - if (pos > unPackSize) - return S_FALSE; - - if (!ReadLastTables()) - return S_FALSE; - return m_OutWindowStream.Flush(); -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress); } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const CLzOutWindowException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - if (size < 1) - return E_INVALIDARG; - m_IsSolid = (data[0] != 0); - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.h deleted file mode 100644 index 65cc97307..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar2Decoder.h +++ /dev/null @@ -1,174 +0,0 @@ -// Rar2Decoder.h -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#ifndef __COMPRESS_RAR2_DECODER_H -#define __COMPRESS_RAR2_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" - -#include "BitmDecoder.h" -#include "HuffmanDecoder.h" -#include "LzOutWindow.h" - -namespace NCompress { -namespace NRar2 { - -const UInt32 kNumRepDists = 4; -const UInt32 kDistTableSize = 48; - -const int kMMTableSize = 256 + 1; - -const UInt32 kMainTableSize = 298; -const UInt32 kLenTableSize = 28; - -const UInt32 kDistTableStart = kMainTableSize; -const UInt32 kLenTableStart = kDistTableStart + kDistTableSize; - -const UInt32 kHeapTablesSizesSum = kMainTableSize + kDistTableSize + kLenTableSize; - -const UInt32 kLevelTableSize = 19; - -const UInt32 kMMTablesSizesSum = kMMTableSize * 4; - -const UInt32 kMaxTableSize = kMMTablesSizesSum; - -const UInt32 kTableDirectLevels = 16; -const UInt32 kTableLevelRepNumber = kTableDirectLevels; -const UInt32 kTableLevel0Number = kTableLevelRepNumber + 1; -const UInt32 kTableLevel0Number2 = kTableLevel0Number + 1; - -const UInt32 kLevelMask = 0xF; - - -const UInt32 kRepBothNumber = 256; -const UInt32 kRepNumber = kRepBothNumber + 1; -const UInt32 kLen2Number = kRepNumber + 4; - -const UInt32 kLen2NumNumbers = 8; -const UInt32 kReadTableNumber = kLen2Number + kLen2NumNumbers; -const UInt32 kMatchNumber = kReadTableNumber + 1; - -const Byte kLenStart[kLenTableSize] = {0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224}; -const Byte kLenDirectBits[kLenTableSize] = {0,0,0,0,0,0,0,0,1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5}; - -const UInt32 kDistStart[kDistTableSize] = {0,1,2,3,4,6,8,12,16,24,32,48,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096,6144,8192,12288,16384,24576,32768U,49152U,65536,98304,131072,196608,262144,327680,393216,458752,524288,589824,655360,720896,786432,851968,917504,983040}; -const Byte kDistDirectBits[kDistTableSize] = {0,0,0,0,1,1,2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16}; - -const Byte kLevelDirectBits[kLevelTableSize] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; - -const Byte kLen2DistStarts[kLen2NumNumbers]={0,4,8,16,32,64,128,192}; -const Byte kLen2DistDirectBits[kLen2NumNumbers]={2,2,3, 4, 5, 6, 6, 6}; - -const UInt32 kDistLimit2 = 0x101 - 1; -const UInt32 kDistLimit3 = 0x2000 - 1; -const UInt32 kDistLimit4 = 0x40000 - 1; - -const UInt32 kMatchMaxLen = 255 + 2; -const UInt32 kMatchMaxLenMax = 255 + 5; -const UInt32 kNormalMatchMinLen = 3; - -namespace NMultimedia { - -struct CFilter -{ - int K1,K2,K3,K4,K5; - int D1,D2,D3,D4; - int LastDelta; - UInt32 Dif[11]; - UInt32 ByteCount; - int LastChar; - - Byte Decode(int &channelDelta, Byte delta); - - void Init() { memset(this, 0, sizeof(*this)); } - -}; - -const int kNumChanelsMax = 4; - -class CFilter2 -{ -public: - CFilter m_Filters[kNumChanelsMax]; - int m_ChannelDelta; - int CurrentChannel; - - void Init() { memset(this, 0, sizeof(*this)); } - Byte Decode(Byte delta) - { - return m_Filters[CurrentChannel].Decode(m_ChannelDelta, delta); - } - -}; - -} - -typedef NBitm::CDecoder CBitDecoder; - -const int kNumHuffmanBits = 15; - -class CDecoder : - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ - CLzOutWindow m_OutWindowStream; - CBitDecoder m_InBitStream; - NHuffman::CDecoder m_MainDecoder; - NHuffman::CDecoder m_DistDecoder; - NHuffman::CDecoder m_LenDecoder; - NHuffman::CDecoder m_MMDecoders[NMultimedia::kNumChanelsMax]; - NHuffman::CDecoder m_LevelDecoder; - - bool m_AudioMode; - - NMultimedia::CFilter2 m_MmFilter; - int m_NumChannels; - - UInt32 m_RepDists[kNumRepDists]; - UInt32 m_RepDistPtr; - - UInt32 m_LastLength; - - Byte m_LastLevels[kMaxTableSize]; - - UInt64 m_PackSize; - bool m_IsSolid; - - void InitStructures(); - UInt32 ReadBits(int numBits); - bool ReadTables(); - bool ReadLastTables(); - - bool DecodeMm(UInt32 pos); - bool DecodeLz(Int32 pos); - - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - -public: - CDecoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - void ReleaseStreams() - { - m_OutWindowStream.ReleaseStream(); - m_InBitStream.ReleaseStream(); - } - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.cpp deleted file mode 100644 index fb52437e7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.cpp +++ /dev/null @@ -1,834 +0,0 @@ -// Rar3Decoder.cpp -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#include "StdAfx.h" - -#include "../Common/StreamUtils.h" - -#include "Rar3Decoder.h" - -namespace NCompress { -namespace NRar3 { - -static const UInt32 kNumAlignReps = 15; - -static const UInt32 kSymbolReadTable = 256; -static const UInt32 kSymbolRep = 259; -static const UInt32 kSymbolLen2 = kSymbolRep + kNumReps; - -static const Byte kLenStart[kLenTableSize] = {0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224}; -static const Byte kLenDirectBits[kLenTableSize] = {0,0,0,0,0,0,0,0,1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5}; - -static const Byte kDistDirectBits[kDistTableSize] = - {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15, - 16,16,16,16,16,16,16,16,16,16,16,16,16,16, - 18,18,18,18,18,18,18,18,18,18,18,18}; - -static const Byte kLevelDirectBits[kLevelTableSize] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; - -static const Byte kLen2DistStarts[kNumLen2Symbols]={0,4,8,16,32,64,128,192}; -static const Byte kLen2DistDirectBits[kNumLen2Symbols]={2,2,3, 4, 5, 6, 6, 6}; - -static const UInt32 kDistLimit3 = 0x2000 - 2; -static const UInt32 kDistLimit4 = 0x40000 - 2; - -static const UInt32 kNormalMatchMinLen = 3; - -static const UInt32 kVmDataSizeMax = 1 << 16; -static const UInt32 kVmCodeSizeMax = 1 << 16; - -CDecoder::CDecoder(): - _window(0), - _winPos(0), - _wrPtr(0), - _lzSize(0), - _writtenFileSize(0), - _vmData(0), - _vmCode(0), - m_IsSolid(false) -{ -} - -CDecoder::~CDecoder() -{ - InitFilters(); - ::MidFree(_vmData); - ::MidFree(_window); -} - -HRESULT CDecoder::WriteDataToStream(const Byte *data, UInt32 size) -{ - return WriteStream(_outStream, data, size); -} - -HRESULT CDecoder::WriteData(const Byte *data, UInt32 size) -{ - HRESULT res = S_OK; - if (_writtenFileSize < _unpackSize) - { - UInt32 curSize = size; - UInt64 remain = _unpackSize - _writtenFileSize; - if (remain < curSize) - curSize = (UInt32)remain; - res = WriteDataToStream(data, curSize); - } - _writtenFileSize += size; - return res; -} - -HRESULT CDecoder::WriteArea(UInt32 startPtr, UInt32 endPtr) -{ - if (startPtr <= endPtr) - return WriteData(_window + startPtr, endPtr - startPtr); - RINOK(WriteData(_window + startPtr, kWindowSize - startPtr)); - return WriteData(_window, endPtr); -} - -void CDecoder::ExecuteFilter(int tempFilterIndex, NVm::CBlockRef &outBlockRef) -{ - CTempFilter *tempFilter = _tempFilters[tempFilterIndex]; - tempFilter->InitR[6] = (UInt32)_writtenFileSize; - NVm::SetValue32(&tempFilter->GlobalData[0x24], (UInt32)_writtenFileSize); - NVm::SetValue32(&tempFilter->GlobalData[0x28], (UInt32)(_writtenFileSize >> 32)); - CFilter *filter = _filters[tempFilter->FilterIndex]; - _vm.Execute(filter, tempFilter, outBlockRef, filter->GlobalData); - delete tempFilter; - _tempFilters[tempFilterIndex] = 0; -} - -HRESULT CDecoder::WriteBuf() -{ - UInt32 writtenBorder = _wrPtr; - UInt32 writeSize = (_winPos - writtenBorder) & kWindowMask; - for (int i = 0; i < _tempFilters.Size(); i++) - { - CTempFilter *filter = _tempFilters[i]; - if (filter == NULL) - continue; - if (filter->NextWindow) - { - filter->NextWindow = false; - continue; - } - UInt32 blockStart = filter->BlockStart; - UInt32 blockSize = filter->BlockSize; - if (((blockStart - writtenBorder) & kWindowMask) < writeSize) - { - if (writtenBorder != blockStart) - { - RINOK(WriteArea(writtenBorder, blockStart)); - writtenBorder = blockStart; - writeSize = (_winPos - writtenBorder) & kWindowMask; - } - if (blockSize <= writeSize) - { - UInt32 blockEnd = (blockStart + blockSize) & kWindowMask; - if (blockStart < blockEnd || blockEnd == 0) - _vm.SetMemory(0, _window + blockStart, blockSize); - else - { - UInt32 tailSize = kWindowSize - blockStart; - _vm.SetMemory(0, _window + blockStart, tailSize); - _vm.SetMemory(tailSize, _window, blockEnd); - } - NVm::CBlockRef outBlockRef; - ExecuteFilter(i, outBlockRef); - while (i + 1 < _tempFilters.Size()) - { - CTempFilter *nextFilter = _tempFilters[i + 1]; - if (nextFilter == NULL || nextFilter->BlockStart != blockStart || - nextFilter->BlockSize != outBlockRef.Size || nextFilter->NextWindow) - break; - _vm.SetMemory(0, _vm.GetDataPointer(outBlockRef.Offset), outBlockRef.Size); - ExecuteFilter(++i, outBlockRef); - } - WriteDataToStream(_vm.GetDataPointer(outBlockRef.Offset), outBlockRef.Size); - _writtenFileSize += outBlockRef.Size; - writtenBorder = blockEnd; - writeSize = (_winPos - writtenBorder) & kWindowMask; - } - else - { - for (int j = i; j < _tempFilters.Size(); j++) - { - CTempFilter *filter = _tempFilters[j]; - if (filter != NULL && filter->NextWindow) - filter->NextWindow = false; - } - _wrPtr = writtenBorder; - return S_OK; // check it - } - } - } - - _wrPtr = _winPos; - return WriteArea(writtenBorder, _winPos); -} - -void CDecoder::InitFilters() -{ - _lastFilter = 0; - int i; - for (i = 0; i < _tempFilters.Size(); i++) - delete _tempFilters[i]; - _tempFilters.Clear(); - for (i = 0; i < _filters.Size(); i++) - delete _filters[i]; - _filters.Clear(); -} - -bool CDecoder::AddVmCode(UInt32 firstByte, UInt32 codeSize) -{ - CMemBitDecoder inp; - inp.Init(_vmData, codeSize); - - UInt32 filterIndex; - if (firstByte & 0x80) - { - filterIndex = NVm::ReadEncodedUInt32(inp); - if (filterIndex == 0) - InitFilters(); - else - filterIndex--; - } - else - filterIndex = _lastFilter; - if (filterIndex > (UInt32)_filters.Size()) - return false; - _lastFilter = filterIndex; - bool newFilter = (filterIndex == (UInt32)_filters.Size()); - - CFilter *filter; - if (newFilter) - { - // check if too many filters - if (filterIndex > 1024) - return false; - filter = new CFilter; - _filters.Add(filter); - } - else - { - filter = _filters[filterIndex]; - filter->ExecCount++; - } - - int numEmptyItems = 0; - int i; - for (i = 0; i < _tempFilters.Size(); i++) - { - _tempFilters[i - numEmptyItems] = _tempFilters[i]; - if (_tempFilters[i] == NULL) - numEmptyItems++; - if (numEmptyItems > 0) - _tempFilters[i] = NULL; - } - if (numEmptyItems == 0) - { - _tempFilters.Add(NULL); - numEmptyItems = 1; - } - CTempFilter *tempFilter = new CTempFilter; - _tempFilters[_tempFilters.Size() - numEmptyItems] = tempFilter; - tempFilter->FilterIndex = filterIndex; - tempFilter->ExecCount = filter->ExecCount; - - UInt32 blockStart = NVm::ReadEncodedUInt32(inp); - if (firstByte & 0x40) - blockStart += 258; - tempFilter->BlockStart = (blockStart + _winPos) & kWindowMask; - if (firstByte & 0x20) - filter->BlockSize = NVm::ReadEncodedUInt32(inp); - tempFilter->BlockSize = filter->BlockSize; - tempFilter->NextWindow = _wrPtr != _winPos && ((_wrPtr - _winPos) & kWindowMask) <= blockStart; - - memset(tempFilter->InitR, 0, sizeof(tempFilter->InitR)); - tempFilter->InitR[3] = NVm::kGlobalOffset; - tempFilter->InitR[4] = tempFilter->BlockSize; - tempFilter->InitR[5] = tempFilter->ExecCount; - if (firstByte & 0x10) - { - UInt32 initMask = inp.ReadBits(NVm::kNumGpRegs); - for (int i = 0; i < NVm::kNumGpRegs; i++) - if (initMask & (1 << i)) - tempFilter->InitR[i] = NVm::ReadEncodedUInt32(inp); - } - if (newFilter) - { - UInt32 vmCodeSize = NVm::ReadEncodedUInt32(inp); - if (vmCodeSize >= kVmCodeSizeMax || vmCodeSize == 0) - return false; - for (UInt32 i = 0; i < vmCodeSize; i++) - _vmCode[i] = (Byte)inp.ReadBits(8); - _vm.PrepareProgram(_vmCode, vmCodeSize, filter); - } - - tempFilter->AllocateEmptyFixedGlobal(); - - Byte *globalData = &tempFilter->GlobalData[0]; - for (i = 0; i < NVm::kNumGpRegs; i++) - NVm::SetValue32(&globalData[i * 4], tempFilter->InitR[i]); - NVm::SetValue32(&globalData[NVm::NGlobalOffset::kBlockSize], tempFilter->BlockSize); - NVm::SetValue32(&globalData[NVm::NGlobalOffset::kBlockPos], 0); // It was commented. why? - NVm::SetValue32(&globalData[NVm::NGlobalOffset::kExecCount], tempFilter->ExecCount); - - if (firstByte & 8) - { - UInt32 dataSize = NVm::ReadEncodedUInt32(inp); - if (dataSize > NVm::kGlobalSize - NVm::kFixedGlobalSize) - return false; - CRecordVector &globalData = tempFilter->GlobalData; - int requredSize = (int)(dataSize + NVm::kFixedGlobalSize); - if (globalData.Size() < requredSize) - { - globalData.Reserve(requredSize); - for (; globalData.Size() < requredSize; i++) - globalData.Add(0); - } - for (UInt32 i = 0; i < dataSize; i++) - globalData[NVm::kFixedGlobalSize + i] = (Byte)inp.ReadBits(8); - } - return true; -} - -bool CDecoder::ReadVmCodeLZ() -{ - UInt32 firstByte = m_InBitStream.ReadBits(8); - UInt32 length = (firstByte & 7) + 1; - if (length == 7) - length = m_InBitStream.ReadBits(8) + 7; - else if (length == 8) - length = m_InBitStream.ReadBits(16); - if (length > kVmDataSizeMax) - return false; - for (UInt32 i = 0; i < length; i++) - _vmData[i] = (Byte)m_InBitStream.ReadBits(8); - return AddVmCode(firstByte, length); -} - -bool CDecoder::ReadVmCodePPM() -{ - int firstByte = DecodePpmSymbol(); - if (firstByte == -1) - return false; - UInt32 length = (firstByte & 7) + 1; - if (length == 7) - { - int b1 = DecodePpmSymbol(); - if (b1 == -1) - return false; - length = b1 + 7; - } - else if (length == 8) - { - int b1 = DecodePpmSymbol(); - if (b1 == -1) - return false; - int b2 = DecodePpmSymbol(); - if (b2 == -1) - return false; - length = b1 * 256 + b2; - } - if (length > kVmDataSizeMax) - return false; - for (UInt32 i = 0; i < length; i++) - { - int b = DecodePpmSymbol(); - if (b == -1) - return false; - _vmData[i] = (Byte)b; - } - return AddVmCode(firstByte, length); -} - -#define RIF(x) { if (!(x)) return S_FALSE; } - -UInt32 CDecoder::ReadBits(int numBits) { return m_InBitStream.ReadBits(numBits); } - -///////////////////////////////////////////////// -// PPM - -HRESULT CDecoder::InitPPM() -{ - Byte maxOrder = (Byte)ReadBits(7); - - bool reset = ((maxOrder & 0x20) != 0); - int maxMB = 0; - if (reset) - maxMB = (Byte)ReadBits(8); - else - { - if (_ppm.SubAllocator.GetSubAllocatorSize()== 0) - return S_FALSE; - } - if (maxOrder & 0x40) - PpmEscChar = (Byte)ReadBits(8); - m_InBitStream.InitRangeCoder(); - /* - if (m_InBitStream.m_BitPos != 0) - return S_FALSE; - */ - if (reset) - { - maxOrder = (maxOrder & 0x1F) + 1; - if (maxOrder > 16) - maxOrder = 16 + (maxOrder - 16) * 3; - if (maxOrder == 1) - { - // SubAlloc.StopSubAllocator(); - _ppm.SubAllocator.StopSubAllocator(); - return S_FALSE; - } - // SubAlloc.StartSubAllocator(MaxMB+1); - // StartModelRare(maxOrder); - - if (!_ppm.SubAllocator.StartSubAllocator((maxMB + 1) << 20)) - return E_OUTOFMEMORY; - _ppm.MaxOrder = 0; - _ppm.StartModelRare(maxOrder); - - } - // return (minContext != NULL); - - return S_OK; -} - -int CDecoder::DecodePpmSymbol() { return _ppm.DecodeSymbol(&m_InBitStream); } - -HRESULT CDecoder::DecodePPM(Int32 num, bool &keepDecompressing) -{ - keepDecompressing = false; - do - { - if (((_wrPtr - _winPos) & kWindowMask) < 260 && _wrPtr != _winPos) - { - RINOK(WriteBuf()); - if (_writtenFileSize > _unpackSize) - { - keepDecompressing = false; - return S_OK; - } - } - int c = DecodePpmSymbol(); - if (c == -1) - { - // Original code sets PPMError=true here and then it returns S_OK. Why ??? - // return S_OK; - return S_FALSE; - } - if (c == PpmEscChar) - { - int nextCh = DecodePpmSymbol(); - if (nextCh == 0) - return ReadTables(keepDecompressing); - if (nextCh == 2 || nextCh == -1) - return S_OK; - if (nextCh == 3) - { - if (!ReadVmCodePPM()) - return S_FALSE; - continue; - } - if (nextCh == 4 || nextCh == 5) - { - UInt32 distance = 0; - UInt32 length = 4; - if (nextCh == 4) - { - for (int i = 0; i < 3; i++) - { - int c = DecodePpmSymbol(); - if (c == -1) - return S_OK; - distance = (distance << 8) + (Byte)c; - } - distance++; - length += 28; - } - int c = DecodePpmSymbol(); - if (c == -1) - return S_OK; - length += c; - if (distance >= _lzSize) - return S_FALSE; - CopyBlock(distance, length); - num -= (Int32)length; - continue; - } - } - PutByte((Byte)c); - num--; - } - while (num >= 0); - keepDecompressing = true; - return S_OK; -} - -///////////////////////////////////////////////// -// LZ - -HRESULT CDecoder::ReadTables(bool &keepDecompressing) -{ - keepDecompressing = true; - ReadBits((8 - m_InBitStream.GetBitPosition()) & 7); - if (ReadBits(1) != 0) - { - _lzMode = false; - return InitPPM(); - } - - _lzMode = true; - PrevAlignBits = 0; - PrevAlignCount = 0; - - Byte levelLevels[kLevelTableSize]; - Byte newLevels[kTablesSizesSum]; - - if (ReadBits(1) == 0) - memset(m_LastLevels, 0, kTablesSizesSum); - - int i; - for (i = 0; i < kLevelTableSize; i++) - { - UInt32 length = ReadBits(4); - if (length == 15) - { - UInt32 zeroCount = ReadBits(4); - if (zeroCount != 0) - { - zeroCount += 2; - while (zeroCount-- > 0 && i < kLevelTableSize) - levelLevels[i++]=0; - i--; - continue; - } - } - levelLevels[i] = (Byte)length; - } - RIF(m_LevelDecoder.SetCodeLengths(levelLevels)); - i = 0; - while (i < kTablesSizesSum) - { - UInt32 number = m_LevelDecoder.DecodeSymbol(&m_InBitStream); - if (number < 16) - { - newLevels[i] = Byte((number + m_LastLevels[i]) & 15); - i++; - } - else if (number > kLevelTableSize) - return S_FALSE; - else - { - int num; - if (((number - 16) & 1) == 0) - num = ReadBits(3) + 3; - else - num = ReadBits(7) + 11; - if (number < 18) - { - if (i == 0) - return S_FALSE; - for (; num > 0 && i < kTablesSizesSum; num--, i++) - newLevels[i] = newLevels[i - 1]; - } - else - { - for (; num > 0 && i < kTablesSizesSum; num--) - newLevels[i++] = 0; - } - } - } - TablesRead = true; - - // original code has check here: - /* - if (InAddr > ReadTop) - { - keepDecompressing = false; - return true; - } - */ - - RIF(m_MainDecoder.SetCodeLengths(&newLevels[0])); - RIF(m_DistDecoder.SetCodeLengths(&newLevels[kMainTableSize])); - RIF(m_AlignDecoder.SetCodeLengths(&newLevels[kMainTableSize + kDistTableSize])); - RIF(m_LenDecoder.SetCodeLengths(&newLevels[kMainTableSize + kDistTableSize + kAlignTableSize])); - - memcpy(m_LastLevels, newLevels, kTablesSizesSum); - return S_OK; -} - -class CCoderReleaser -{ - CDecoder *m_Coder; -public: - CCoderReleaser(CDecoder *coder): m_Coder(coder) {} - ~CCoderReleaser() - { - // m_Coder->m_OutWindowStream.Flush(); - m_Coder->ReleaseStreams(); - } -}; - -HRESULT CDecoder::ReadEndOfBlock(bool &keepDecompressing) -{ - if (ReadBits(1) != 0) - { - // old file - TablesRead = false; - return ReadTables(keepDecompressing); - } - // new file - keepDecompressing = false; - TablesRead = (ReadBits(1) == 0); - return S_OK; -} - -UInt32 kDistStart[kDistTableSize]; - -class CDistInit -{ -public: - CDistInit() { Init(); } - void Init() - { - UInt32 start = 0; - for (UInt32 i = 0; i < kDistTableSize; i++) - { - kDistStart[i] = start; - start += (1 << kDistDirectBits[i]); - } - } -} g_DistInit; - -HRESULT CDecoder::DecodeLZ(bool &keepDecompressing) -{ - UInt32 rep0 = _reps[0]; - UInt32 rep1 = _reps[1]; - UInt32 rep2 = _reps[2]; - UInt32 rep3 = _reps[3]; - UInt32 length = _lastLength; - for (;;) - { - if (((_wrPtr - _winPos) & kWindowMask) < 260 && _wrPtr != _winPos) - { - RINOK(WriteBuf()); - if (_writtenFileSize > _unpackSize) - { - keepDecompressing = false; - return S_OK; - } - } - UInt32 number = m_MainDecoder.DecodeSymbol(&m_InBitStream); - if (number < 256) - { - PutByte(Byte(number)); - - continue; - } - else if (number == kSymbolReadTable) - { - RINOK(ReadEndOfBlock(keepDecompressing)); - break; - } - else if (number == 257) - { - if (!ReadVmCodeLZ()) - return S_FALSE; - continue; - } - else if (number == 258) - { - } - else if (number < kSymbolRep + 4) - { - if (number != kSymbolRep) - { - UInt32 distance; - if (number == kSymbolRep + 1) - distance = rep1; - else - { - if (number == kSymbolRep + 2) - distance = rep2; - else - { - distance = rep3; - rep3 = rep2; - } - rep2 = rep1; - } - rep1 = rep0; - rep0 = distance; - } - - UInt32 number = m_LenDecoder.DecodeSymbol(&m_InBitStream); - if (number >= kLenTableSize) - return S_FALSE; - length = 2 + kLenStart[number] + m_InBitStream.ReadBits(kLenDirectBits[number]); - } - else - { - rep3 = rep2; - rep2 = rep1; - rep1 = rep0; - if (number < 271) - { - number -= 263; - rep0 = kLen2DistStarts[number] + m_InBitStream.ReadBits(kLen2DistDirectBits[number]); - length = 2; - } - else if (number < 299) - { - number -= 271; - length = kNormalMatchMinLen + (UInt32)kLenStart[number] + m_InBitStream.ReadBits(kLenDirectBits[number]); - UInt32 number = m_DistDecoder.DecodeSymbol(&m_InBitStream); - if (number >= kDistTableSize) - return S_FALSE; - rep0 = kDistStart[number]; - int numBits = kDistDirectBits[number]; - if (number >= (kNumAlignBits * 2) + 2) - { - if (numBits > kNumAlignBits) - rep0 += (m_InBitStream.ReadBits(numBits - kNumAlignBits) << kNumAlignBits); - if (PrevAlignCount > 0) - { - PrevAlignCount--; - rep0 += PrevAlignBits; - } - else - { - UInt32 number = m_AlignDecoder.DecodeSymbol(&m_InBitStream); - if (number < (1 << kNumAlignBits)) - { - rep0 += number; - PrevAlignBits = number; - } - else if (number == (1 << kNumAlignBits)) - { - PrevAlignCount = kNumAlignReps; - rep0 += PrevAlignBits; - } - else - return S_FALSE; - } - } - else - rep0 += m_InBitStream.ReadBits(numBits); - length += ((kDistLimit4 - rep0) >> 31) + ((kDistLimit3 - rep0) >> 31); - } - else - return S_FALSE; - } - if (rep0 >= _lzSize) - return S_FALSE; - CopyBlock(rep0, length); - } - _reps[0] = rep0; - _reps[1] = rep1; - _reps[2] = rep2; - _reps[3] = rep3; - _lastLength = length; - - return S_OK; -} - -HRESULT CDecoder::CodeReal(ICompressProgressInfo *progress) -{ - _writtenFileSize = 0; - if (!m_IsSolid) - { - _lzSize = 0; - _winPos = 0; - _wrPtr = 0; - for (int i = 0; i < kNumReps; i++) - _reps[i] = 0; - _lastLength = 0; - memset(m_LastLevels, 0, kTablesSizesSum); - TablesRead = false; - PpmEscChar = 2; - InitFilters(); - } - if (!m_IsSolid || !TablesRead) - { - bool keepDecompressing; - RINOK(ReadTables(keepDecompressing)); - if (!keepDecompressing) - return S_OK; - } - - for(;;) - { - bool keepDecompressing; - if (_lzMode) - { - RINOK(DecodeLZ(keepDecompressing)) - } - else - { - RINOK(DecodePPM(1 << 18, keepDecompressing)) - } - UInt64 packSize = m_InBitStream.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &_writtenFileSize)); - if (!keepDecompressing) - break; - } - RINOK(WriteBuf()); - if (_writtenFileSize < _unpackSize) - return S_FALSE; - // return m_OutWindowStream.Flush(); - return S_OK; -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try - { - if (inSize == NULL || outSize == NULL) - return E_INVALIDARG; - - if (_vmData == 0) - { - _vmData = (Byte *)::MidAlloc(kVmDataSizeMax + kVmCodeSizeMax); - if (_vmData == 0) - return E_OUTOFMEMORY; - _vmCode = _vmData + kVmDataSizeMax; - } - - if (_window == 0) - { - _window = (Byte *)::MidAlloc(kWindowSize); - if (_window == 0) - return E_OUTOFMEMORY; - } - if (!m_InBitStream.Create(1 << 20)) - return E_OUTOFMEMORY; - if (!_vm.Create()) - return E_OUTOFMEMORY; - - - m_InBitStream.SetStream(inStream); - m_InBitStream.Init(); - _outStream = outStream; - - CCoderReleaser coderReleaser(this); - _unpackSize = *outSize; - return CodeReal(progress); - } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } - // CNewException is possible here. But probably CNewException is caused - // by error in data stream. -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - if (size < 1) - return E_INVALIDARG; - m_IsSolid = (data[0] != 0); - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.h deleted file mode 100644 index da0b73f19..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Decoder.h +++ /dev/null @@ -1,301 +0,0 @@ -// Rar3Decoder.h -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#ifndef __COMPRESS_RAR3_DECODER_H -#define __COMPRESS_RAR3_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -#include "../Common/InBuffer.h" - -#include "BitmDecoder.h" -#include "HuffmanDecoder.h" -#include "PpmdDecode.h" -#include "Rar3Vm.h" - -namespace NCompress { -namespace NRar3 { - -const UInt32 kWindowSize = 1 << 22; -const UInt32 kWindowMask = (kWindowSize - 1); - -const UInt32 kNumReps = 4; -const UInt32 kNumLen2Symbols = 8; -const UInt32 kLenTableSize = 28; -const UInt32 kMainTableSize = 256 + 1 + 1 + 1 + kNumReps + kNumLen2Symbols + kLenTableSize; -const UInt32 kDistTableSize = 60; - -const int kNumAlignBits = 4; -const UInt32 kAlignTableSize = (1 << kNumAlignBits) + 1; - -const UInt32 kLevelTableSize = 20; - -const UInt32 kTablesSizesSum = kMainTableSize + kDistTableSize + kAlignTableSize + kLenTableSize; - -class CBitDecoder -{ - UInt32 m_Value; -public: - UInt32 m_BitPos; - CInBuffer m_Stream; - bool Create(UInt32 bufferSize) { return m_Stream.Create(bufferSize); } - void SetStream(ISequentialInStream *inStream) { m_Stream.SetStream(inStream);} - void ReleaseStream() { m_Stream.ReleaseStream();} - - void Init() - { - m_Stream.Init(); - m_BitPos = 0; - m_Value = 0; - // m_BitPos = kNumBigValueBits; - // Normalize(); - } - - UInt64 GetProcessedSize() const - { return m_Stream.GetProcessedSize() - (m_BitPos) / 8; } - UInt32 GetBitPosition() const { return ((8 - m_BitPos) & 7); } - - /* - void Normalize() - { - for (;m_BitPos >= 8; m_BitPos -= 8) - m_Value = (m_Value << 8) | m_Stream.ReadByte(); - } - */ - - UInt32 GetValue(UInt32 numBits) - { - // return (m_Value << m_BitPos) >> (kNumBigValueBits - numBits); - // return ((m_Value >> (8 - m_BitPos)) & kMask) >> (kNumValueBits - numBits); - if (m_BitPos < numBits) - { - m_BitPos += 8; - m_Value = (m_Value << 8) | m_Stream.ReadByte(); - if (m_BitPos < numBits) - { - m_BitPos += 8; - m_Value = (m_Value << 8) | m_Stream.ReadByte(); - } - } - return m_Value >> (m_BitPos - numBits); - } - - void MovePos(UInt32 numBits) - { - m_BitPos -= numBits; - m_Value = m_Value & ((1 << m_BitPos) - 1); - } - - UInt32 ReadBits(UInt32 numBits) - { - UInt32 res = GetValue(numBits); - MovePos(numBits); - return res; - } -}; - -const int kNumTopBits = 24; -const UInt32 kTopValue = (1 << kNumTopBits); -const UInt32 kBot = (1 << 15); - -class CRangeDecoder:public NPpmd::CRangeDecoderVirt, public CBitDecoder -{ -public: - UInt32 Range; - UInt32 Low; - UInt32 Code; - - void Normalize() - { - while ((Low ^ (Low + Range)) < kTopValue || - Range < kBot && ((Range = (0 - Low) & (kBot - 1)), 1)) - { - Code = (Code << 8) | m_Stream.ReadByte(); - Range <<= 8; - Low <<= 8; - } - } - - void InitRangeCoder() - { - Code = 0; - Low = 0; - Range = 0xFFFFFFFF; - for(int i = 0; i < 4; i++) - Code = (Code << 8) | ReadBits(8); - } - - virtual UInt32 GetThreshold(UInt32 total) - { - return (Code - Low) / ( Range /= total); - } - - virtual void Decode(UInt32 start, UInt32 size) - { - Low += start * Range; - Range *= size; - Normalize(); - } - - virtual UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits) - { - if (((Code - Low) / (Range >>= numTotalBits)) < size0) - { - Decode(0, size0); - return 0; - } - else - { - Decode(size0, (1 << numTotalBits) - size0); - return 1; - } - } - - // UInt64 GetProcessedSizeRangeCoder() {return Stream.GetProcessedSize(); } -}; - - -struct CFilter: public NVm::CProgram -{ - CRecordVector GlobalData; - UInt32 BlockStart; - UInt32 BlockSize; - UInt32 ExecCount; - CFilter(): BlockStart(0), BlockSize(0), ExecCount(0) {} -}; - -struct CTempFilter: public NVm::CProgramInitState -{ - UInt32 BlockStart; - UInt32 BlockSize; - UInt32 ExecCount; - bool NextWindow; - - UInt32 FilterIndex; -}; - -const int kNumHuffmanBits = 15; - -class CDecoder: - public ICompressCoder, - public ICompressSetDecoderProperties2, - public CMyUnknownImp -{ - CRangeDecoder m_InBitStream; - Byte *_window; - UInt32 _winPos; - UInt32 _wrPtr; - UInt64 _lzSize; - UInt64 _unpackSize; - UInt64 _writtenFileSize; // if it's > _unpackSize, then _unpackSize only written - CMyComPtr _outStream; - NHuffman::CDecoder m_MainDecoder; - NHuffman::CDecoder m_DistDecoder; - NHuffman::CDecoder m_AlignDecoder; - NHuffman::CDecoder m_LenDecoder; - NHuffman::CDecoder m_LevelDecoder; - - UInt32 _reps[kNumReps]; - UInt32 _lastLength; - - Byte m_LastLevels[kTablesSizesSum]; - - Byte *_vmData; - Byte *_vmCode; - NVm::CVm _vm; - CRecordVector _filters; - CRecordVector _tempFilters; - UInt32 _lastFilter; - - bool m_IsSolid; - - bool _lzMode; - - UInt32 PrevAlignBits; - UInt32 PrevAlignCount; - - bool TablesRead; - - NPpmd::CDecodeInfo _ppm; - int PpmEscChar; - - HRESULT WriteDataToStream(const Byte *data, UInt32 size); - HRESULT WriteData(const Byte *data, UInt32 size); - HRESULT WriteArea(UInt32 startPtr, UInt32 endPtr); - void ExecuteFilter(int tempFilterIndex, NVm::CBlockRef &outBlockRef); - HRESULT WriteBuf(); - - void InitFilters(); - bool AddVmCode(UInt32 firstByte, UInt32 codeSize); - bool ReadVmCodeLZ(); - bool ReadVmCodePPM(); - - UInt32 ReadBits(int numBits); - - HRESULT InitPPM(); - int DecodePpmSymbol(); - HRESULT DecodePPM(Int32 num, bool &keepDecompressing); - - HRESULT ReadTables(bool &keepDecompressing); - HRESULT ReadEndOfBlock(bool &keepDecompressing); - HRESULT DecodeLZ(bool &keepDecompressing); - HRESULT CodeReal(ICompressProgressInfo *progress); -public: - CDecoder(); - ~CDecoder(); - - MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2) - - void ReleaseStreams() - { - _outStream.Release(); - m_InBitStream.ReleaseStream(); - } - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - - void CopyBlock(UInt32 distance, UInt32 len) - { - _lzSize += len; - UInt32 pos = (_winPos - distance - 1) & kWindowMask; - Byte *window = _window; - UInt32 winPos = _winPos; - if (kWindowSize - winPos > len && kWindowSize - pos > len) - { - const Byte *src = window + pos; - Byte *dest = window + winPos; - _winPos += len; - do - *dest++ = *src++; - while(--len != 0); - return; - } - do - { - window[winPos] = window[pos]; - winPos = (winPos + 1) & kWindowMask; - pos = (pos + 1) & kWindowMask; - } - while(--len != 0); - _winPos = winPos; - } - - void PutByte(Byte b) - { - _window[_winPos] = b; - _winPos = (_winPos + 1) & kWindowMask; - _lzSize++; - } - - -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.cpp deleted file mode 100644 index 6aeabbccc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.cpp +++ /dev/null @@ -1,1094 +0,0 @@ -// Rar3Vm.cpp -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -/* -Note: - Due to performance considerations Rar VM may set Flags C incorrectly - for some operands (SHL x, 0, ... ). - Check implementation of concrete VM command - to see if it sets flags right. -*/ - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/7zCrc.h" -#include "../../../C/Alloc.h" -} - -#include "Rar3Vm.h" - -namespace NCompress { -namespace NRar3 { - -UInt32 CMemBitDecoder::ReadBits(int numBits) -{ - UInt32 res = 0; - for (;;) - { - Byte b = _bitPos < _bitSize ? _data[_bitPos >> 3] : 0; - int avail = (int)(8 - (_bitPos & 7)); - if (numBits <= avail) - { - _bitPos += numBits; - return res | (b >> (avail - numBits)) & ((1 << numBits) - 1); - } - numBits -= avail; - res |= (UInt32)(b & ((1 << avail) - 1)) << numBits; - _bitPos += avail; - } -} - -UInt32 CMemBitDecoder::ReadBit() { return ReadBits(1); } - -namespace NVm { - -static const UInt32 kStackRegIndex = kNumRegs - 1; - -static const UInt32 FLAG_C = 1; -static const UInt32 FLAG_Z = 2; -static const UInt32 FLAG_S = 0x80000000; - -static const Byte CF_OP0 = 0; -static const Byte CF_OP1 = 1; -static const Byte CF_OP2 = 2; -static const Byte CF_OPMASK = 3; -static const Byte CF_BYTEMODE = 4; -static const Byte CF_JUMP = 8; -static const Byte CF_PROC = 16; -static const Byte CF_USEFLAGS = 32; -static const Byte CF_CHFLAGS = 64; - -static Byte kCmdFlags[]= -{ - /* CMD_MOV */ CF_OP2 | CF_BYTEMODE, - /* CMD_CMP */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_ADD */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_SUB */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_JZ */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JNZ */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_INC */ CF_OP1 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_DEC */ CF_OP1 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_JMP */ CF_OP1 | CF_JUMP, - /* CMD_XOR */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_AND */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_OR */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_TEST */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_JS */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JNS */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JB */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JBE */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JA */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_JAE */ CF_OP1 | CF_JUMP | CF_USEFLAGS, - /* CMD_PUSH */ CF_OP1, - /* CMD_POP */ CF_OP1, - /* CMD_CALL */ CF_OP1 | CF_PROC, - /* CMD_RET */ CF_OP0 | CF_PROC, - /* CMD_NOT */ CF_OP1 | CF_BYTEMODE, - /* CMD_SHL */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_SHR */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_SAR */ CF_OP2 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_NEG */ CF_OP1 | CF_BYTEMODE | CF_CHFLAGS, - /* CMD_PUSHA */ CF_OP0, - /* CMD_POPA */ CF_OP0, - /* CMD_PUSHF */ CF_OP0 | CF_USEFLAGS, - /* CMD_POPF */ CF_OP0 | CF_CHFLAGS, - /* CMD_MOVZX */ CF_OP2, - /* CMD_MOVSX */ CF_OP2, - /* CMD_XCHG */ CF_OP2 | CF_BYTEMODE, - /* CMD_MUL */ CF_OP2 | CF_BYTEMODE, - /* CMD_DIV */ CF_OP2 | CF_BYTEMODE, - /* CMD_ADC */ CF_OP2 | CF_BYTEMODE | CF_USEFLAGS | CF_CHFLAGS , - /* CMD_SBB */ CF_OP2 | CF_BYTEMODE | CF_USEFLAGS | CF_CHFLAGS , - /* CMD_PRINT */ CF_OP0 -}; - -CVm::CVm(): Mem(NULL) {} - -bool CVm::Create() -{ - if (Mem == NULL) - Mem = (Byte *)::MyAlloc(kSpaceSize + 4); - return (Mem != NULL); -} - -CVm::~CVm() -{ - ::MyFree(Mem); -} - -// CVm::Execute can change CProgram object: it clears progarm if VM returns error. - -bool CVm::Execute(CProgram *prg, const CProgramInitState *initState, - CBlockRef &outBlockRef, CRecordVector &outGlobalData) -{ - memcpy(R, initState->InitR, sizeof(initState->InitR)); - R[kStackRegIndex] = kSpaceSize; - R[kNumRegs] = 0; - Flags = 0; - - UInt32 globalSize = MyMin((UInt32)initState->GlobalData.Size(), kGlobalSize); - if (globalSize != 0) - memcpy(Mem + kGlobalOffset, &initState->GlobalData[0], globalSize); - UInt32 staticSize = MyMin((UInt32)prg->StaticData.Size(), kGlobalSize - globalSize); - if (staticSize != 0) - memcpy(Mem + kGlobalOffset + globalSize, &prg->StaticData[0], staticSize); - - bool res = true; - #ifdef RARVM_STANDARD_FILTERS - if (prg->StandardFilterIndex >= 0) - ExecuteStandardFilter(prg->StandardFilterIndex); - else - #endif - { - res = ExecuteCode(prg); - if (!res) - prg->Commands[0].OpCode = CMD_RET; - } - UInt32 newBlockPos = GetFixedGlobalValue32(NGlobalOffset::kBlockPos) & kSpaceMask; - UInt32 newBlockSize = GetFixedGlobalValue32(NGlobalOffset::kBlockSize) & kSpaceMask; - if (newBlockPos + newBlockSize >= kSpaceSize) - newBlockPos = newBlockSize = 0; - outBlockRef.Offset = newBlockPos; - outBlockRef.Size = newBlockSize; - - outGlobalData.Clear(); - UInt32 dataSize = GetFixedGlobalValue32(NGlobalOffset::kGlobalMemOutSize); - dataSize = MyMin(dataSize, kGlobalSize - kFixedGlobalSize); - if (dataSize != 0) - { - dataSize += kFixedGlobalSize; - outGlobalData.Reserve(dataSize); - for (UInt32 i = 0; i < dataSize; i++) - outGlobalData.Add(Mem[kGlobalOffset + i]); - } - return res; -} - - -#define SET_IP(IP) \ - if ((IP) >= numCommands) return true; \ - if (--maxOpCount <= 0) return false; \ - cmd = commands + (IP); - -#define GET_FLAG_S_B(res) (((res) & 0x80) ? FLAG_S : 0) -#define SET_IP_OP1 { UInt32 val = GetOperand32(&cmd->Op1); SET_IP(val); } -#define FLAGS_UPDATE_SZ Flags = res == 0 ? FLAG_Z : res & FLAG_S -#define FLAGS_UPDATE_SZ_B Flags = (res & 0xFF) == 0 ? FLAG_Z : GET_FLAG_S_B(res) - -UInt32 CVm::GetOperand32(const COperand *op) const -{ - switch(op->Type) - { - case OP_TYPE_REG: return R[op->Data]; - case OP_TYPE_REGMEM: return GetValue32(&Mem[(op->Base + R[op->Data]) & kSpaceMask]); - default: return op->Data; - } -} - -void CVm::SetOperand32(const COperand *op, UInt32 val) -{ - switch(op->Type) - { - case OP_TYPE_REG: R[op->Data] = val; return; - case OP_TYPE_REGMEM: SetValue32(&Mem[(op->Base + R[op->Data]) & kSpaceMask], val); return; - } -} - -Byte CVm::GetOperand8(const COperand *op) const -{ - switch(op->Type) - { - case OP_TYPE_REG: return (Byte)R[op->Data]; - case OP_TYPE_REGMEM: return Mem[(op->Base + R[op->Data]) & kSpaceMask];; - default: return (Byte)op->Data; - } -} - -void CVm::SetOperand8(const COperand *op, Byte val) -{ - switch(op->Type) - { - case OP_TYPE_REG: R[op->Data] = (R[op->Data] & 0xFFFFFF00) | val; return; - case OP_TYPE_REGMEM: Mem[(op->Base + R[op->Data]) & kSpaceMask] = val; return; - } -} - -UInt32 CVm::GetOperand(bool byteMode, const COperand *op) const -{ - if (byteMode) - return GetOperand8(op); - return GetOperand32(op); -} - -void CVm::SetOperand(bool byteMode, const COperand *op, UInt32 val) -{ - if (byteMode) - SetOperand8(op, (Byte)(val & 0xFF)); - else - SetOperand32(op, val); -} - -bool CVm::ExecuteCode(const CProgram *prg) -{ - Int32 maxOpCount = 25000000; - const CCommand *commands = &prg->Commands[0]; - const CCommand *cmd = commands; - UInt32 numCommands = prg->Commands.Size(); - for (;;) - { - switch(cmd->OpCode) - { - #ifndef RARVM_NO_VM - - case CMD_MOV: - SetOperand32(&cmd->Op1, GetOperand32(&cmd->Op2)); - break; - case CMD_MOVB: - SetOperand8(&cmd->Op1, GetOperand8(&cmd->Op2)); - break; - case CMD_CMP: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - UInt32 res = v1 - GetOperand32(&cmd->Op2); - Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); - } - break; - case CMD_CMPB: - { - Byte v1 = GetOperand8(&cmd->Op1); - Byte res = v1 - GetOperand8(&cmd->Op2); - res &= 0xFF; - Flags = res == 0 ? FLAG_Z : (res > v1) | GET_FLAG_S_B(res); - } - break; - case CMD_ADD: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - UInt32 res = v1 + GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - Flags = (res < v1) | (res == 0 ? FLAG_Z : (res & FLAG_S)); - } - break; - case CMD_ADDB: - { - Byte v1 = GetOperand8(&cmd->Op1); - Byte res = v1 + GetOperand8(&cmd->Op2); - res &= 0xFF; - SetOperand8(&cmd->Op1, (Byte)res); - Flags = (res < v1) | (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)); - } - break; - case CMD_ADC: - { - UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); - UInt32 FC = (Flags & FLAG_C); - UInt32 res = v1 + GetOperand(cmd->ByteMode, &cmd->Op2) + FC; - if (cmd->ByteMode) - res &= 0xFF; - SetOperand(cmd->ByteMode, &cmd->Op1, res); - Flags = (res < v1 || res == v1 && FC) | (res == 0 ? FLAG_Z : (res & FLAG_S)); - } - break; - case CMD_SUB: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - UInt32 res = v1 - GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); - } - break; - case CMD_SUBB: - { - UInt32 v1 = GetOperand8(&cmd->Op1); - UInt32 res = v1 - GetOperand8(&cmd->Op2); - SetOperand8(&cmd->Op1, (Byte)res); - Flags = res == 0 ? FLAG_Z : (res > v1) | (res & FLAG_S); - } - break; - case CMD_SBB: - { - UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); - UInt32 FC = (Flags & FLAG_C); - UInt32 res = v1 - GetOperand(cmd->ByteMode, &cmd->Op2) - FC; - // Flags = res == 0 ? FLAG_Z : (res > v1 || res == v1 && FC) | (res & FLAG_S); - if (cmd->ByteMode) - res &= 0xFF; - SetOperand(cmd->ByteMode, &cmd->Op1, res); - Flags = (res > v1 || res == v1 && FC) | (res == 0 ? FLAG_Z : (res & FLAG_S)); - } - break; - case CMD_INC: - { - UInt32 res = GetOperand32(&cmd->Op1) + 1; - SetOperand32(&cmd->Op1, res); - FLAGS_UPDATE_SZ; - } - break; - case CMD_INCB: - { - Byte res = GetOperand8(&cmd->Op1) + 1; - SetOperand8(&cmd->Op1, res);; - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_DEC: - { - UInt32 res = GetOperand32(&cmd->Op1) - 1; - SetOperand32(&cmd->Op1, res); - FLAGS_UPDATE_SZ; - } - break; - case CMD_DECB: - { - Byte res = GetOperand8(&cmd->Op1) - 1; - SetOperand8(&cmd->Op1, res);; - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_XOR: - { - UInt32 res = GetOperand32(&cmd->Op1) ^ GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - FLAGS_UPDATE_SZ; - } - break; - case CMD_XORB: - { - Byte res = GetOperand8(&cmd->Op1) ^ GetOperand8(&cmd->Op2); - SetOperand8(&cmd->Op1, res); - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_AND: - { - UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - FLAGS_UPDATE_SZ; - } - break; - case CMD_ANDB: - { - Byte res = GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2); - SetOperand8(&cmd->Op1, res); - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_OR: - { - UInt32 res = GetOperand32(&cmd->Op1) | GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - FLAGS_UPDATE_SZ; - } - break; - case CMD_ORB: - { - Byte res = GetOperand8(&cmd->Op1) | GetOperand8(&cmd->Op2); - SetOperand8(&cmd->Op1, res); - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_TEST: - { - UInt32 res = GetOperand32(&cmd->Op1) & GetOperand32(&cmd->Op2); - FLAGS_UPDATE_SZ; - } - break; - case CMD_TESTB: - { - Byte res = GetOperand8(&cmd->Op1) & GetOperand8(&cmd->Op2); - FLAGS_UPDATE_SZ_B; - } - break; - case CMD_NOT: - SetOperand(cmd->ByteMode, &cmd->Op1, ~GetOperand(cmd->ByteMode, &cmd->Op1)); - break; - case CMD_NEG: - { - UInt32 res = 0 - GetOperand32(&cmd->Op1); - SetOperand32(&cmd->Op1, res); - Flags = res == 0 ? FLAG_Z : FLAG_C | (res & FLAG_S); - } - break; - case CMD_NEGB: - { - Byte res = (Byte)(0 - GetOperand8(&cmd->Op1)); - SetOperand8(&cmd->Op1, res); - Flags = res == 0 ? FLAG_Z : FLAG_C | GET_FLAG_S_B(res); - } - break; - - case CMD_SHL: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - int v2 = (int)GetOperand32(&cmd->Op2); - UInt32 res = v1 << v2; - SetOperand32(&cmd->Op1, res); - Flags = (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 << (v2 - 1)) & 0x80000000 ? FLAG_C : 0); - } - break; - case CMD_SHLB: - { - Byte v1 = GetOperand8(&cmd->Op1); - int v2 = (int)GetOperand8(&cmd->Op2); - Byte res = (Byte)(v1 << v2); - SetOperand8(&cmd->Op1, res); - Flags = (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 << (v2 - 1)) & 0x80 ? FLAG_C : 0); - } - break; - case CMD_SHR: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - int v2 = (int)GetOperand32(&cmd->Op2); - UInt32 res = v1 >> v2; - SetOperand32(&cmd->Op1, res); - Flags = (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 >> (v2 - 1)) & FLAG_C); - } - break; - case CMD_SHRB: - { - Byte v1 = GetOperand8(&cmd->Op1); - int v2 = (int)GetOperand8(&cmd->Op2); - Byte res = (Byte)(v1 >> v2); - SetOperand8(&cmd->Op1, res); - Flags = (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 >> (v2 - 1)) & FLAG_C); - } - break; - case CMD_SAR: - { - UInt32 v1 = GetOperand32(&cmd->Op1); - int v2 = (int)GetOperand32(&cmd->Op2); - UInt32 res = UInt32(((Int32)v1) >> v2); - SetOperand32(&cmd->Op1, res); - Flags= (res == 0 ? FLAG_Z : (res & FLAG_S)) | ((v1 >> (v2 - 1)) & FLAG_C); - } - break; - case CMD_SARB: - { - Byte v1 = GetOperand8(&cmd->Op1); - int v2 = (int)GetOperand8(&cmd->Op2); - Byte res = (Byte)(((signed char)v1) >> v2); - SetOperand8(&cmd->Op1, res); - Flags= (res == 0 ? FLAG_Z : GET_FLAG_S_B(res)) | ((v1 >> (v2 - 1)) & FLAG_C); - } - break; - - case CMD_JMP: - SET_IP_OP1; - continue; - case CMD_JZ: - if ((Flags & FLAG_Z) != 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JNZ: - if ((Flags & FLAG_Z) == 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JS: - if ((Flags & FLAG_S) != 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JNS: - if ((Flags & FLAG_S) == 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JB: - if ((Flags & FLAG_C) != 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JBE: - if ((Flags & (FLAG_C | FLAG_Z)) != 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JA: - if ((Flags & (FLAG_C | FLAG_Z)) == 0) - { - SET_IP_OP1; - continue; - } - break; - case CMD_JAE: - if ((Flags & FLAG_C) == 0) - { - SET_IP_OP1; - continue; - } - break; - - case CMD_PUSH: - R[kStackRegIndex] -= 4; - SetValue32(&Mem[R[kStackRegIndex] & kSpaceMask], GetOperand32(&cmd->Op1)); - break; - case CMD_POP: - SetOperand32(&cmd->Op1, GetValue32(&Mem[R[kStackRegIndex] & kSpaceMask])); - R[kStackRegIndex] += 4; - break; - case CMD_CALL: - R[kStackRegIndex] -= 4; - SetValue32(&Mem[R[kStackRegIndex] & kSpaceMask], (UInt32)(cmd - commands + 1)); - SET_IP_OP1; - continue; - - case CMD_PUSHA: - { - for (UInt32 i = 0, SP = R[kStackRegIndex] - 4; i < kNumRegs; i++, SP -= 4) - SetValue32(&Mem[SP & kSpaceMask], R[i]); - R[kStackRegIndex] -= kNumRegs * 4; - } - break; - case CMD_POPA: - { - for (UInt32 i = 0, SP = R[kStackRegIndex]; i < kNumRegs; i++, SP += 4) - R[kStackRegIndex - i] = GetValue32(&Mem[SP & kSpaceMask]); - } - break; - case CMD_PUSHF: - R[kStackRegIndex] -= 4; - SetValue32(&Mem[R[kStackRegIndex]&kSpaceMask], Flags); - break; - case CMD_POPF: - Flags = GetValue32(&Mem[R[kStackRegIndex] & kSpaceMask]); - R[kStackRegIndex] += 4; - break; - - case CMD_MOVZX: - SetOperand32(&cmd->Op1, GetOperand8(&cmd->Op2)); - break; - case CMD_MOVSX: - SetOperand32(&cmd->Op1, (UInt32)(Int32)(signed char)GetOperand8(&cmd->Op2)); - break; - case CMD_XCHG: - { - UInt32 v1 = GetOperand(cmd->ByteMode, &cmd->Op1); - SetOperand(cmd->ByteMode, &cmd->Op1, GetOperand(cmd->ByteMode, &cmd->Op2)); - SetOperand(cmd->ByteMode, &cmd->Op2, v1); - } - break; - case CMD_MUL: - { - UInt32 res = GetOperand32(&cmd->Op1) * GetOperand32(&cmd->Op2); - SetOperand32(&cmd->Op1, res); - } - break; - case CMD_MULB: - { - Byte res = GetOperand8(&cmd->Op1) * GetOperand8(&cmd->Op2); - SetOperand8(&cmd->Op1, res); - } - break; - case CMD_DIV: - { - UInt32 divider = GetOperand(cmd->ByteMode, &cmd->Op2); - if (divider != 0) - { - UInt32 res = GetOperand(cmd->ByteMode, &cmd->Op1) / divider; - SetOperand(cmd->ByteMode, &cmd->Op1, res); - } - } - break; - - #endif - - case CMD_RET: - { - if (R[kStackRegIndex] >= kSpaceSize) - return true; - UInt32 ip = GetValue32(&Mem[R[kStackRegIndex] & kSpaceMask]); - SET_IP(ip); - R[kStackRegIndex] += 4; - continue; - } - case CMD_PRINT: - break; - } - cmd++; - --maxOpCount; - } -} - - -////////////////////////////////////////////////////// -// Read program - -UInt32 ReadEncodedUInt32(CMemBitDecoder &inp) -{ - switch(inp.ReadBits(2)) - { - case 0: - return inp.ReadBits(4); - case 1: - { - UInt32 v = inp.ReadBits(4); - if (v == 0) - return 0xFFFFFF00 | inp.ReadBits(8); - else - return (v << 4) | inp.ReadBits(4); - } - case 2: - return inp.ReadBits(16); - default: - return inp.ReadBits(32); - } -} - -void CVm::DecodeArg(CMemBitDecoder &inp, COperand &op, bool byteMode) -{ - if (inp.ReadBit()) - { - op.Type = OP_TYPE_REG; - op.Data = inp.ReadBits(kNumRegBits); - } - else if (inp.ReadBit() == 0) - { - op.Type = OP_TYPE_INT; - if (byteMode) - op.Data = inp.ReadBits(8); - else - op.Data = ReadEncodedUInt32(inp); - } - else - { - op.Type = OP_TYPE_REGMEM; - if (inp.ReadBit() == 0) - { - op.Data = inp.ReadBits(kNumRegBits); - op.Base = 0; - } - else - { - if (inp.ReadBit() == 0) - op.Data = inp.ReadBits(kNumRegBits); - else - op.Data = kNumRegs; - op.Base = ReadEncodedUInt32(inp); - } - } -} - -void CVm::ReadVmProgram(const Byte *code, UInt32 codeSize, CProgram *prg) -{ - CMemBitDecoder inp; - inp.Init(code, codeSize); - - prg->StaticData.Clear(); - if (inp.ReadBit()) - { - UInt32 dataSize = ReadEncodedUInt32(inp) + 1; - for (UInt32 i = 0; inp.Avail() && i < dataSize; i++) - prg->StaticData.Add((Byte)inp.ReadBits(8)); - } - while (inp.Avail()) - { - prg->Commands.Add(CCommand()); - CCommand *cmd = &prg->Commands.Back(); - if (inp.ReadBit() == 0) - cmd->OpCode = (ECommand)inp.ReadBits(3); - else - cmd->OpCode = (ECommand)(8 + inp.ReadBits(5)); - if (kCmdFlags[cmd->OpCode] & CF_BYTEMODE) - cmd->ByteMode = (inp.ReadBit()) ? true : false; - else - cmd->ByteMode = 0; - int opNum = (kCmdFlags[cmd->OpCode] & CF_OPMASK); - if (opNum > 0) - { - DecodeArg(inp, cmd->Op1, cmd->ByteMode); - if (opNum == 2) - DecodeArg(inp, cmd->Op2, cmd->ByteMode); - else - { - if (cmd->Op1.Type == OP_TYPE_INT && (kCmdFlags[cmd->OpCode] & (CF_JUMP | CF_PROC))) - { - int Distance = cmd->Op1.Data; - if (Distance >= 256) - Distance -= 256; - else - { - if (Distance >= 136) - Distance -= 264; - else if (Distance >= 16) - Distance -= 8; - else if (Distance >= 8) - Distance -= 16; - Distance += prg->Commands.Size() - 1; - } - cmd->Op1.Data = Distance; - } - } - } - if (cmd->ByteMode) - { - switch (cmd->OpCode) - { - case CMD_MOV: cmd->OpCode = CMD_MOVB; break; - case CMD_CMP: cmd->OpCode = CMD_CMPB; break; - case CMD_ADD: cmd->OpCode = CMD_ADDB; break; - case CMD_SUB: cmd->OpCode = CMD_SUBB; break; - case CMD_INC: cmd->OpCode = CMD_INCB; break; - case CMD_DEC: cmd->OpCode = CMD_DECB; break; - case CMD_XOR: cmd->OpCode = CMD_XORB; break; - case CMD_AND: cmd->OpCode = CMD_ANDB; break; - case CMD_OR: cmd->OpCode = CMD_ORB; break; - case CMD_TEST: cmd->OpCode = CMD_TESTB; break; - case CMD_NEG: cmd->OpCode = CMD_NEGB; break; - case CMD_SHL: cmd->OpCode = CMD_SHLB; break; - case CMD_SHR: cmd->OpCode = CMD_SHRB; break; - case CMD_SAR: cmd->OpCode = CMD_SARB; break; - case CMD_MUL: cmd->OpCode = CMD_MULB; break; - } - } - } -} - -#ifdef RARVM_STANDARD_FILTERS - -enum EStandardFilter -{ - SF_E8, - SF_E8E9, - SF_ITANIUM, - SF_RGB, - SF_AUDIO, - SF_DELTA, - SF_UPCASE -}; - -struct StandardFilterSignature -{ - UInt32 Length; - UInt32 CRC; - EStandardFilter Type; -} -kStdFilters[]= -{ - 53, 0xad576887, SF_E8, - 57, 0x3cd7e57e, SF_E8E9, - 120, 0x3769893f, SF_ITANIUM, - 29, 0x0e06077d, SF_DELTA, - 149, 0x1c2c5dc8, SF_RGB, - 216, 0xbc85e701, SF_AUDIO, - 40, 0x46b9c560, SF_UPCASE -}; - -static int FindStandardFilter(const Byte *code, UInt32 codeSize) -{ - UInt32 crc = CrcCalc(code, codeSize); - for (int i = 0; i < sizeof(kStdFilters) / sizeof(kStdFilters[0]); i++) - { - StandardFilterSignature &sfs = kStdFilters[i]; - if (sfs.CRC == crc && sfs.Length == codeSize) - return i; - } - return -1; -} - -#endif - -void CVm::PrepareProgram(const Byte *code, UInt32 codeSize, CProgram *prg) -{ - Byte xorSum = 0; - for (UInt32 i = 1; i < codeSize; i++) - xorSum ^= code[i]; - - prg->Commands.Clear(); - #ifdef RARVM_STANDARD_FILTERS - prg->StandardFilterIndex = -1; - #endif - - if (xorSum == code[0] && codeSize > 0) - { - #ifdef RARVM_STANDARD_FILTERS - prg->StandardFilterIndex = FindStandardFilter(code, codeSize); - if (prg->StandardFilterIndex >= 0) - return; - #endif - // 1 byte for checksum - ReadVmProgram(code + 1, codeSize - 1, prg); - } - prg->Commands.Add(CCommand()); - CCommand *cmd = &prg->Commands.Back(); - cmd->OpCode = CMD_RET; -} - -void CVm::SetMemory(UInt32 pos, const Byte *data, UInt32 dataSize) -{ - if (pos < kSpaceSize && data != Mem + pos) - memmove(Mem + pos, data, MyMin(dataSize, kSpaceSize - pos)); -} - -#ifdef RARVM_STANDARD_FILTERS - -static void E8E9Decode(Byte *data, UInt32 dataSize, UInt32 fileOffset, bool e9) -{ - if (dataSize <= 4) - return; - dataSize -= 4; - const UInt32 kFileSize = 0x1000000; - Byte cmpByte2 = (e9 ? 0xE9 : 0xE8); - for (UInt32 curPos = 0; curPos < dataSize;) - { - Byte curByte = *(data++); - curPos++; - if (curByte == 0xE8 || curByte == cmpByte2) - { - UInt32 offset = curPos + fileOffset; - UInt32 addr = (Int32)GetValue32(data); - if (addr < kFileSize) - SetValue32(data, addr - offset); - else if ((Int32)addr < 0 && (Int32)(addr + offset) >= 0) - SetValue32(data, addr + kFileSize); - data += 4; - curPos += 4; - } - } -} - -static inline UInt32 ItaniumGetOpType(const Byte *data, int bitPos) -{ - return (data[(unsigned int)bitPos >> 3] >> (bitPos & 7)) & 0xF; -} - - -static void ItaniumDecode(Byte *data, UInt32 dataSize, UInt32 fileOffset) -{ - UInt32 curPos = 0; - fileOffset >>= 4; - while (curPos < dataSize - 21) - { - int b = (data[0] & 0x1F) - 0x10; - if (b >= 0) - { - static Byte kCmdMasks[16] = {4,4,6,6,0,0,7,7,4,4,0,0,4,4,0,0}; - Byte cmdMask = kCmdMasks[b]; - if (cmdMask != 0) - for (int i = 0; i < 3; i++) - if (cmdMask & (1 << i)) - { - int startPos = i * 41 + 18; - if (ItaniumGetOpType(data, startPos + 24) == 5) - { - const UInt32 kMask = 0xFFFFF; - Byte *p = data + ((unsigned int)startPos >> 3); - UInt32 bitField = ((UInt32)p[0]) | ((UInt32)p[1] << 8) | ((UInt32)p[2] << 16); - int inBit = (startPos & 7); - UInt32 offset = (bitField >> inBit) & kMask; - UInt32 andMask = ~(kMask << inBit); - bitField = ((offset - fileOffset) & kMask) << inBit; - for (int j = 0; j < 3; j++) - { - p[j] &= andMask; - p[j] |= bitField; - andMask >>= 8; - bitField >>= 8; - } - } - } - } - data += 16; - curPos += 16; - fileOffset++; - } -} - -static void DeltaDecode(Byte *data, UInt32 dataSize, UInt32 numChannels) -{ - UInt32 srcPos = 0; - UInt32 border = dataSize * 2; - for (UInt32 curChannel = 0; curChannel < numChannels; curChannel++) - { - Byte prevByte = 0; - for (UInt32 destPos = dataSize + curChannel; destPos < border; destPos += numChannels) - data[destPos] = (prevByte = prevByte - data[srcPos++]); - } -} - -static void RgbDecode(Byte *srcData, UInt32 dataSize, UInt32 width, UInt32 posR) -{ - Byte *destData = srcData + dataSize; - const UInt32 numChannels = 3; - for (UInt32 curChannel = 0; curChannel < numChannels; curChannel++) - { - Byte prevByte = 0; - - for (UInt32 i = curChannel; i < dataSize; i+= numChannels) - { - unsigned int predicted; - if (i < width) - predicted = prevByte; - else - { - unsigned int upperLeftByte = destData[i - width]; - unsigned int upperByte = destData[i - width + 3]; - predicted = prevByte + upperByte - upperLeftByte; - int pa = abs((int)(predicted - prevByte)); - int pb = abs((int)(predicted - upperByte)); - int pc = abs((int)(predicted - upperLeftByte)); - if (pa <= pb && pa <= pc) - predicted = prevByte; - else - if (pb <= pc) - predicted = upperByte; - else - predicted = upperLeftByte; - } - destData[i] = prevByte = (Byte)(predicted - *(srcData++)); - } - } - if (dataSize < 3) - return; - for (UInt32 i = posR, border = dataSize - 2; i < border; i += 3) - { - Byte g = destData[i + 1]; - destData[i] = destData[i] + g; - destData[i + 2] = destData[i + 2] + g; - } -} - -static void AudioDecode(Byte *srcData, UInt32 dataSize, UInt32 numChannels) -{ - Byte *destData = srcData + dataSize; - for (UInt32 curChannel = 0; curChannel < numChannels; curChannel++) - { - UInt32 prevByte = 0, prevDelta = 0, dif[7]; - Int32 D1 = 0, D2 = 0, D3; - Int32 K1 = 0, K2 = 0, K3 = 0; - memset(dif, 0, sizeof(dif)); - - for (UInt32 i = curChannel, byteCount = 0; i < dataSize; i += numChannels, byteCount++) - { - D3 = D2; - D2 = prevDelta - D1; - D1 = prevDelta; - - UInt32 predicted = 8 * prevByte + K1 * D1 + K2 * D2 + K3 * D3; - predicted = (predicted >> 3) & 0xFF; - - UInt32 curByte = *(srcData++); - - predicted -= curByte; - destData[i] = (Byte)predicted; - prevDelta = (UInt32)(Int32)(signed char)(predicted - prevByte); - prevByte = predicted; - - Int32 D = ((Int32)(signed char)curByte) << 3; - - dif[0] += abs(D); - dif[1] += abs(D - D1); - dif[2] += abs(D + D1); - dif[3] += abs(D - D2); - dif[4] += abs(D + D2); - dif[5] += abs(D - D3); - dif[6] += abs(D + D3); - - if ((byteCount & 0x1F) == 0) - { - UInt32 minDif = dif[0], numMinDif = 0; - dif[0] = 0; - for (int j = 1; j < sizeof(dif) / sizeof(dif[0]); j++) - { - if (dif[j] < minDif) - { - minDif = dif[j]; - numMinDif = j; - } - dif[j] = 0; - } - switch (numMinDif) - { - case 1: if (K1 >= -16) K1--; break; - case 2: if (K1 < 16) K1++; break; - case 3: if (K2 >= -16) K2--; break; - case 4: if (K2 < 16) K2++; break; - case 5: if (K3 >= -16) K3--; break; - case 6: if (K3 < 16) K3++; break; - } - } - } - } -} - -static UInt32 UpCaseDecode(Byte *data, UInt32 dataSize) -{ - UInt32 srcPos = 0, destPos = dataSize; - while (srcPos < dataSize) - { - Byte curByte = data[srcPos++]; - if (curByte == 2 && (curByte = data[srcPos++]) != 2) - curByte -= 32; - data[destPos++] = curByte; - } - return destPos - dataSize; -} - -void CVm::ExecuteStandardFilter(int filterIndex) -{ - UInt32 dataSize = R[4]; - if (dataSize >= kGlobalOffset) - return; - EStandardFilter filterType = kStdFilters[filterIndex].Type; - - switch (filterType) - { - case SF_E8: - case SF_E8E9: - E8E9Decode(Mem, dataSize, R[6], (filterType == SF_E8E9)); - break; - case SF_ITANIUM: - ItaniumDecode(Mem, dataSize, R[6]); - break; - case SF_DELTA: - if (dataSize >= kGlobalOffset / 2) - break; - SetBlockPos(dataSize); - DeltaDecode(Mem, dataSize, R[0]); - break; - case SF_RGB: - if (dataSize >= kGlobalOffset / 2) - break; - { - UInt32 width = R[0]; - if (width <= 3) - break; - SetBlockPos(dataSize); - RgbDecode(Mem, dataSize, width, R[1]); - } - break; - case SF_AUDIO: - if (dataSize >= kGlobalOffset / 2) - break; - SetBlockPos(dataSize); - AudioDecode(Mem, dataSize, R[0]); - break; - case SF_UPCASE: - if (dataSize >= kGlobalOffset / 2) - break; - UInt32 destSize = UpCaseDecode(Mem, dataSize); - SetBlockSize(destSize); - SetBlockPos(dataSize); - break; - } -} - -#endif - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.h b/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.h deleted file mode 100644 index 0d16e42cc..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/Rar3Vm.h +++ /dev/null @@ -1,179 +0,0 @@ -// Rar3Vm.h -// According to unRAR license, this code may not be used to develop -// a program that creates RAR archives - -#ifndef __COMPRESS_RAR3_VM_H -#define __COMPRESS_RAR3_VM_H - -#include "../../../C/CpuArch.h" - -#include "Common/MyVector.h" -#include "Common/Types.h" - -#define RARVM_STANDARD_FILTERS - -namespace NCompress { -namespace NRar3 { - -class CMemBitDecoder -{ - const Byte *_data; - UInt32 _bitSize; - UInt32 _bitPos; -public: - void Init(const Byte *data, UInt32 byteSize) - { - _data = data; - _bitSize = (byteSize << 3); - _bitPos = 0; - } - UInt32 ReadBits(int numBits); - UInt32 ReadBit(); - bool Avail() const { return (_bitPos < _bitSize); } -}; - -namespace NVm { - -inline UInt32 GetValue32(const void *addr) { return GetUi32(addr); } -inline void SetValue32(void *addr, UInt32 value) { SetUi32(addr, value); } - -UInt32 ReadEncodedUInt32(CMemBitDecoder &inp); - -const int kNumRegBits = 3; -const UInt32 kNumRegs = 1 << kNumRegBits; -const UInt32 kNumGpRegs = kNumRegs - 1; - -const UInt32 kSpaceSize = 0x40000; -const UInt32 kSpaceMask = kSpaceSize -1; -const UInt32 kGlobalOffset = 0x3C000; -const UInt32 kGlobalSize = 0x2000; -const UInt32 kFixedGlobalSize = 64; - -namespace NGlobalOffset -{ - const UInt32 kBlockSize = 0x1C; - const UInt32 kBlockPos = 0x20; - const UInt32 kExecCount = 0x2C; - const UInt32 kGlobalMemOutSize = 0x30; -} - -enum ECommand -{ - CMD_MOV, CMD_CMP, CMD_ADD, CMD_SUB, CMD_JZ, CMD_JNZ, CMD_INC, CMD_DEC, - CMD_JMP, CMD_XOR, CMD_AND, CMD_OR, CMD_TEST, CMD_JS, CMD_JNS, CMD_JB, - CMD_JBE, CMD_JA, CMD_JAE, CMD_PUSH, CMD_POP, CMD_CALL, CMD_RET, CMD_NOT, - CMD_SHL, CMD_SHR, CMD_SAR, CMD_NEG, CMD_PUSHA,CMD_POPA, CMD_PUSHF,CMD_POPF, - CMD_MOVZX,CMD_MOVSX,CMD_XCHG, CMD_MUL, CMD_DIV, CMD_ADC, CMD_SBB, CMD_PRINT, - - CMD_MOVB, CMD_CMPB, CMD_ADDB, CMD_SUBB, CMD_INCB, CMD_DECB, - CMD_XORB, CMD_ANDB, CMD_ORB, CMD_TESTB,CMD_NEGB, - CMD_SHLB, CMD_SHRB, CMD_SARB, CMD_MULB -}; - -enum EOpType {OP_TYPE_REG, OP_TYPE_INT, OP_TYPE_REGMEM, OP_TYPE_NONE}; - -// Addr in COperand object can link (point) to CVm object!!! - -struct COperand -{ - EOpType Type; - UInt32 Data; - UInt32 Base; - COperand(): Type(OP_TYPE_NONE), Data(0), Base(0) {} -}; - -struct CCommand -{ - ECommand OpCode; - bool ByteMode; - COperand Op1, Op2; -}; - -struct CBlockRef -{ - UInt32 Offset; - UInt32 Size; -}; - -struct CProgram -{ - CRecordVector Commands; - #ifdef RARVM_STANDARD_FILTERS - int StandardFilterIndex; - #endif - CRecordVector StaticData; -}; - -struct CProgramInitState -{ - UInt32 InitR[kNumGpRegs]; - CRecordVector GlobalData; - - void AllocateEmptyFixedGlobal() - { - GlobalData.Clear(); - GlobalData.Reserve(NVm::kFixedGlobalSize); - for (UInt32 i = 0; i < NVm::kFixedGlobalSize; i++) - GlobalData.Add(0); - } -}; - -class CVm -{ - static UInt32 GetValue(bool byteMode, const void *addr) - { - if (byteMode) - return(*(const Byte *)addr); - else - return GetUi32(addr); - } - - static void SetValue(bool byteMode, void *addr, UInt32 value) - { - if (byteMode) - *(Byte *)addr = (Byte)value; - else - SetUi32(addr, value); - } - - UInt32 GetFixedGlobalValue32(UInt32 globalOffset) { return GetValue(false, &Mem[kGlobalOffset + globalOffset]); } - - void SetBlockSize(UInt32 v) { SetValue(&Mem[kGlobalOffset + NGlobalOffset::kBlockSize], v); } - void SetBlockPos(UInt32 v) { SetValue(&Mem[kGlobalOffset + NGlobalOffset::kBlockPos], v); } -public: - static void SetValue(void *addr, UInt32 value) { SetValue(false, addr, value); } -private: - UInt32 GetOperand32(const COperand *op) const; - void SetOperand32(const COperand *op, UInt32 val); - Byte GetOperand8(const COperand *op) const; - void SetOperand8(const COperand *op, Byte val); - UInt32 GetOperand(bool byteMode, const COperand *op) const; - void SetOperand(bool byteMode, const COperand *op, UInt32 val); - - void DecodeArg(CMemBitDecoder &inp, COperand &op, bool byteMode); - - bool ExecuteCode(const CProgram *prg); - - #ifdef RARVM_STANDARD_FILTERS - void ExecuteStandardFilter(int filterIndex); - #endif - - Byte *Mem; - UInt32 R[kNumRegs + 1]; // R[kNumRegs] = 0 always (speed optimization) - UInt32 Flags; - void ReadVmProgram(const Byte *code, UInt32 codeSize, CProgram *prg); -public: - CVm(); - ~CVm(); - bool Create(); - void PrepareProgram(const Byte *code, UInt32 codeSize, CProgram *prg); - void SetMemory(UInt32 pos, const Byte *data, UInt32 dataSize); - bool Execute(CProgram *prg, const CProgramInitState *initState, - CBlockRef &outBlockRef, CRecordVector &outGlobalData); - const Byte *GetDataPointer(UInt32 offset) const { return Mem + offset; } - -}; - -#endif - -}}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/RarCodecsRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/RarCodecsRegister.cpp deleted file mode 100644 index cb6242b3d..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/RarCodecsRegister.cpp +++ /dev/null @@ -1,26 +0,0 @@ -// RarCodecsRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" - -#include "Rar1Decoder.h" -#include "Rar2Decoder.h" -#include "Rar3Decoder.h" - -#define CREATE_CODEC(x) static void *CreateCodec ## x() { return (void *)(ICompressCoder *)(new NCompress::NRar ## x::CDecoder); } - -CREATE_CODEC(1) -CREATE_CODEC(2) -CREATE_CODEC(3) - -#define RAR_CODEC(x, name) { CreateCodec ## x, 0, 0x040300 + x, L"Rar" name, 1, false } - -static CCodecInfo g_CodecsInfo[] = -{ - RAR_CODEC(1, L"1"), - RAR_CODEC(2, L"2"), - RAR_CODEC(3, L"3"), -}; - -REGISTER_CODECS(Rar) diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.cpp deleted file mode 100644 index 2146fa733..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.cpp +++ /dev/null @@ -1,148 +0,0 @@ -// ShrinkDecoder.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Alloc.h" -} - -#include "../Common/InBuffer.h" -#include "../Common/OutBuffer.h" - -#include "BitlDecoder.h" -#include "ShrinkDecoder.h" - -namespace NCompress { -namespace NShrink { - -static const UInt32 kBufferSize = (1 << 20); -static const int kNumMinBits = 9; - -HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress) -{ - NBitl::CBaseDecoder inBuffer; - COutBuffer outBuffer; - - if (!inBuffer.Create(kBufferSize)) - return E_OUTOFMEMORY; - inBuffer.SetStream(inStream); - inBuffer.Init(); - - if (!outBuffer.Create(kBufferSize)) - return E_OUTOFMEMORY; - outBuffer.SetStream(outStream); - outBuffer.Init(); - - UInt64 prevPos = 0; - int numBits = kNumMinBits; - UInt32 head = 257; - bool needPrev = false; - UInt32 lastSymbol = 0; - - int i; - for (i = 0; i < kNumItems; i++) - _parents[i] = 0; - for (i = 0; i < kNumItems; i++) - _suffixes[i] = 0; - for (i = 0; i < 257; i++) - _isFree[i] = false; - for (; i < kNumItems; i++) - _isFree[i] = true; - - for (;;) - { - UInt32 symbol = inBuffer.ReadBits(numBits); - if (inBuffer.ExtraBitsWereRead()) - break; - if (_isFree[symbol]) - return S_FALSE; - if (symbol == 256) - { - UInt32 symbol = inBuffer.ReadBits(numBits); - if (symbol == 1) - { - if (numBits < kNumMaxBits) - numBits++; - } - else if (symbol == 2) - { - if (needPrev) - _isFree[head - 1] = true; - for (i = 257; i < kNumItems; i++) - _isParent[i] = false; - for (i = 257; i < kNumItems; i++) - if (!_isFree[i]) - _isParent[_parents[i]] = true; - for (i = 257; i < kNumItems; i++) - if (!_isParent[i]) - _isFree[i] = true; - head = 257; - while (head < kNumItems && !_isFree[head]) - head++; - if (head < kNumItems) - { - needPrev = true; - _isFree[head] = false; - _parents[head] = (UInt16)lastSymbol; - head++; - } - } - else - return S_FALSE; - continue; - } - UInt32 cur = symbol; - i = 0; - int corectionIndex = -1; - while (cur >= 256) - { - if (cur == head - 1) - corectionIndex = i; - _stack[i++] = _suffixes[cur]; - cur = _parents[cur]; - } - _stack[i++] = (Byte)cur; - if (needPrev) - { - _suffixes[head - 1] = (Byte)cur; - if (corectionIndex >= 0) - _stack[corectionIndex] = (Byte)cur; - } - while (i > 0) - outBuffer.WriteByte((_stack[--i])); - while (head < kNumItems && !_isFree[head]) - head++; - if (head < kNumItems) - { - needPrev = true; - _isFree[head] = false; - _parents[head] = (UInt16)symbol; - head++; - } - else - needPrev = false; - lastSymbol = symbol; - - UInt64 nowPos = outBuffer.GetProcessedSize(); - if (progress != NULL && nowPos - prevPos > (1 << 18)) - { - prevPos = nowPos; - UInt64 packSize = inBuffer.GetProcessedSize(); - RINOK(progress->SetRatioInfo(&packSize, &nowPos)); - } - } - return outBuffer.Flush(); -} - -STDMETHODIMP CDecoder ::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - try { return CodeReal(inStream, outStream, inSize, outSize, progress); } - catch(const CInBufferException &e) { return e.ErrorCode; } - catch(const COutBufferException &e) { return e.ErrorCode; } - catch(...) { return S_FALSE; } -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.h deleted file mode 100644 index 00f416402..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ShrinkDecoder.h +++ /dev/null @@ -1,38 +0,0 @@ -// ShrinkDecoder.h - -#ifndef __COMPRESS_SHRINK_DECODER_H -#define __COMPRESS_SHRINK_DECODER_H - -#include "../../Common/MyCom.h" - -#include "../ICoder.h" - -namespace NCompress { -namespace NShrink { - -const int kNumMaxBits = 13; -const UInt32 kNumItems = 1 << kNumMaxBits; - -class CDecoder : - public ICompressCoder, - public CMyUnknownImp -{ - UInt16 _parents[kNumItems]; - Byte _suffixes[kNumItems]; - Byte _stack[kNumItems]; - bool _isFree[kNumItems]; - bool _isParent[kNumItems]; - -public: - MY_UNKNOWN_IMP - - HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Compress/StdAfx.h deleted file mode 100644 index c28ffcea7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.cpp b/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.cpp deleted file mode 100644 index 505f21798..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.cpp +++ /dev/null @@ -1,94 +0,0 @@ -// ZlibDecoder.cpp - -#include "StdAfx.h" - -#include "../Common/StreamUtils.h" - -#include "DeflateDecoder.h" -#include "ZlibDecoder.h" - -namespace NCompress { -namespace NZlib { - -#define DEFLATE_TRY_BEGIN try { -#define DEFLATE_TRY_END } \ - catch(...) { return S_FALSE; } - -#define ADLER_MOD 65521 -#define ADLER_LOOP_MAX 5550 - -static UInt32 Adler32_Update(UInt32 adler, const Byte *buf, size_t size) -{ - UInt32 a = adler & 0xFFFF; - UInt32 b = (adler >> 16) & 0xFFFF; - while (size > 0) - { - unsigned curSize = (size > ADLER_LOOP_MAX) ? ADLER_LOOP_MAX : (unsigned )size; - unsigned i; - for (i = 0; i < curSize; i++) - { - a += buf[i]; - b += a; - } - buf += curSize; - size -= curSize; - a %= ADLER_MOD; - b %= ADLER_MOD; - } - return (b << 16) + a; -} - -STDMETHODIMP COutStreamWithAdler::Write(const void *data, UInt32 size, UInt32 *processedSize) -{ - HRESULT result = _stream->Write(data, size, &size); - _adler = Adler32_Update(_adler, (const Byte *)data, size); - if (processedSize != NULL) - *processedSize = size; - return result; -} - -STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) -{ - DEFLATE_TRY_BEGIN - if (!AdlerStream) - { - AdlerSpec = new COutStreamWithAdler; - AdlerStream = AdlerSpec; - } - if (!DeflateDecoder) - { - DeflateDecoderSpec = new NCompress::NDeflate::NDecoder::CCOMCoder; - DeflateDecoderSpec->ZlibMode = true; - DeflateDecoder = DeflateDecoderSpec; - } - - Byte buf[2]; - RINOK(ReadStream_FALSE(inStream, buf, 2)); - int method = buf[0] & 0xF; - if (method != 8) - return S_FALSE; - // int dicSize = buf[0] >> 4; - if ((((UInt32)buf[0] << 8) + buf[1]) % 31 != 0) - return S_FALSE; - if ((buf[1] & 0x20) != 0) // dictPresent - return S_FALSE; - // int level = (buf[1] >> 6); - - AdlerSpec->SetStream(outStream); - AdlerSpec->Init(); - HRESULT res = DeflateDecoder->Code(inStream, AdlerStream, inSize, outSize, progress); - AdlerSpec->ReleaseStream(); - - if (res == S_OK) - { - const Byte *p = DeflateDecoderSpec->ZlibFooter; - UInt32 adler = ((UInt32)p[0] << 24) | ((UInt32)p[1] << 16) | ((UInt32)p[2] << 8) | p[3]; - if (adler != AdlerSpec->GetAdler()) - return S_FALSE; - } - return res; - DEFLATE_TRY_END -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.h b/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.h deleted file mode 100644 index a7ec07328..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Compress/ZlibDecoder.h +++ /dev/null @@ -1,46 +0,0 @@ -// ZlibDecoder.h - -#ifndef __ZLIB_DECODER_H -#define __ZLIB_DECODER_H - -#include "DeflateDecoder.h" - -namespace NCompress { -namespace NZlib { - -const UInt32 ADLER_INIT_VAL = 1; - -class COutStreamWithAdler: - public ISequentialOutStream, - public CMyUnknownImp -{ - CMyComPtr _stream; - UInt32 _adler; -public: - MY_UNKNOWN_IMP - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize); - void SetStream(ISequentialOutStream *stream) { _stream = stream; } - void ReleaseStream() { _stream.Release(); } - void Init() { _adler = ADLER_INIT_VAL; } - UInt32 GetAdler() const { return _adler; } -}; - -class CDecoder: - public ICompressCoder, - public CMyUnknownImp -{ - COutStreamWithAdler *AdlerSpec; - CMyComPtr AdlerStream; - - NCompress::NDeflate::NDecoder::CCOMCoder *DeflateDecoderSpec; - CMyComPtr DeflateDecoder; -public: - STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, - const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); - - MY_UNKNOWN_IMP -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.cpp deleted file mode 100644 index b5b5b4b43..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.cpp +++ /dev/null @@ -1,245 +0,0 @@ -// 7zAes.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/Sha256.h" -} - -#include "Windows/Synchronization.h" -#include "../Common/StreamObjects.h" -#include "../Common/StreamUtils.h" -#include "7zAes.h" -#include "MyAes.h" - -#ifndef EXTRACT_ONLY -#include "RandGen.h" -#endif - -using namespace NWindows; - -namespace NCrypto { -namespace NSevenZ { - -bool CKeyInfo::IsEqualTo(const CKeyInfo &a) const -{ - if (SaltSize != a.SaltSize || NumCyclesPower != a.NumCyclesPower) - return false; - for (UInt32 i = 0; i < SaltSize; i++) - if (Salt[i] != a.Salt[i]) - return false; - return (Password == a.Password); -} - -void CKeyInfo::CalculateDigest() -{ - if (NumCyclesPower == 0x3F) - { - UInt32 pos; - for (pos = 0; pos < SaltSize; pos++) - Key[pos] = Salt[pos]; - for (UInt32 i = 0; i < Password.GetCapacity() && pos < kKeySize; i++) - Key[pos++] = Password[i]; - for (; pos < kKeySize; pos++) - Key[pos] = 0; - } - else - { - CSha256 sha; - Sha256_Init(&sha); - const UInt64 numRounds = UInt64(1) << (NumCyclesPower); - Byte temp[8] = { 0,0,0,0,0,0,0,0 }; - for (UInt64 round = 0; round < numRounds; round++) - { - Sha256_Update(&sha, Salt, (size_t)SaltSize); - Sha256_Update(&sha, Password, Password.GetCapacity()); - Sha256_Update(&sha, temp, 8); - for (int i = 0; i < 8; i++) - if (++(temp[i]) != 0) - break; - } - Sha256_Final(&sha, Key); - } -} - -bool CKeyInfoCache::Find(CKeyInfo &key) -{ - for (int i = 0; i < Keys.Size(); i++) - { - const CKeyInfo &cached = Keys[i]; - if (key.IsEqualTo(cached)) - { - for (int j = 0; j < kKeySize; j++) - key.Key[j] = cached.Key[j]; - if (i != 0) - { - Keys.Insert(0, cached); - Keys.Delete(i+1); - } - return true; - } - } - return false; -} - -void CKeyInfoCache::Add(CKeyInfo &key) -{ - if (Find(key)) - return; - if (Keys.Size() >= Size) - Keys.DeleteBack(); - Keys.Insert(0, key); -} - -static CKeyInfoCache g_GlobalKeyCache(32); -static NSynchronization::CCriticalSection g_GlobalKeyCacheCriticalSection; - -CBase::CBase(): - _cachedKeys(16), - _ivSize(0) -{ - for (int i = 0; i < sizeof(_iv); i++) - _iv[i] = 0; -} - -void CBase::CalculateDigest() -{ - NSynchronization::CCriticalSectionLock lock(g_GlobalKeyCacheCriticalSection); - if (_cachedKeys.Find(_key)) - g_GlobalKeyCache.Add(_key); - else - { - if (!g_GlobalKeyCache.Find(_key)) - { - _key.CalculateDigest(); - g_GlobalKeyCache.Add(_key); - } - _cachedKeys.Add(_key); - } -} - -#ifndef EXTRACT_ONLY - -/* -STDMETHODIMP CEncoder::ResetSalt() -{ - _key.SaltSize = 4; - g_RandomGenerator.Generate(_key.Salt, _key.SaltSize); - return S_OK; -} -*/ - -STDMETHODIMP CEncoder::ResetInitVector() -{ - _ivSize = 8; - g_RandomGenerator.Generate(_iv, (unsigned)_ivSize); - return S_OK; -} - -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) -{ - // _key.Init(); - for (UInt32 i = _ivSize; i < sizeof(_iv); i++) - _iv[i] = 0; - - UInt32 ivSize = _ivSize; - - // _key.NumCyclesPower = 0x3F; - _key.NumCyclesPower = 19; - - Byte firstByte = (Byte)(_key.NumCyclesPower | - (((_key.SaltSize == 0) ? 0 : 1) << 7) | - (((ivSize == 0) ? 0 : 1) << 6)); - RINOK(outStream->Write(&firstByte, 1, NULL)); - if (_key.SaltSize == 0 && ivSize == 0) - return S_OK; - Byte saltSizeSpec = (Byte)((_key.SaltSize == 0) ? 0 : (_key.SaltSize - 1)); - Byte ivSizeSpec = (Byte)((ivSize == 0) ? 0 : (ivSize - 1)); - Byte secondByte = (Byte)(((saltSizeSpec) << 4) | ivSizeSpec); - RINOK(outStream->Write(&secondByte, 1, NULL)); - if (_key.SaltSize > 0) - { - RINOK(WriteStream(outStream, _key.Salt, _key.SaltSize)); - } - if (ivSize > 0) - { - RINOK(WriteStream(outStream, _iv, ivSize)); - } - return S_OK; -} - -HRESULT CEncoder::CreateFilter() -{ - _aesFilter = new CAesCbcEncoder; - return S_OK; -} - -#endif - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - _key.Init(); - UInt32 i; - for (i = 0; i < sizeof(_iv); i++) - _iv[i] = 0; - if (size == 0) - return S_OK; - UInt32 pos = 0; - Byte firstByte = data[pos++]; - - _key.NumCyclesPower = firstByte & 0x3F; - if ((firstByte & 0xC0) == 0) - return S_OK; - _key.SaltSize = (firstByte >> 7) & 1; - UInt32 ivSize = (firstByte >> 6) & 1; - - if (pos >= size) - return E_INVALIDARG; - Byte secondByte = data[pos++]; - - _key.SaltSize += (secondByte >> 4); - ivSize += (secondByte & 0x0F); - - if (pos + _key.SaltSize + ivSize > size) - return E_INVALIDARG; - for (i = 0; i < _key.SaltSize; i++) - _key.Salt[i] = data[pos++]; - for (i = 0; i < ivSize; i++) - _iv[i] = data[pos++]; - return S_OK; -} - -STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - _key.Password.SetCapacity((size_t)size); - memcpy(_key.Password, data, (size_t)size); - return S_OK; -} - -STDMETHODIMP CBaseCoder::Init() -{ - CalculateDigest(); - if (_aesFilter == 0) - { - RINOK(CreateFilter()); - } - CMyComPtr cp; - RINOK(_aesFilter.QueryInterface(IID_ICryptoProperties, &cp)); - RINOK(cp->SetKey(_key.Key, sizeof(_key.Key))); - RINOK(cp->SetInitVector(_iv, sizeof(_iv))); - return S_OK; -} - -STDMETHODIMP_(UInt32) CBaseCoder::Filter(Byte *data, UInt32 size) -{ - return _aesFilter->Filter(data, size); -} - -HRESULT CDecoder::CreateFilter() -{ - _aesFilter = new CAesCbcDecoder; - return S_OK; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.h b/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.h deleted file mode 100644 index 08da66649..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAes.h +++ /dev/null @@ -1,117 +0,0 @@ -// 7zAes.h - -#ifndef __CRYPTO_7Z_AES_H -#define __CRYPTO_7Z_AES_H - -#include "Common/Buffer.h" -#include "Common/MyCom.h" -#include "Common/MyVector.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -namespace NCrypto { -namespace NSevenZ { - -const int kKeySize = 32; - -class CKeyInfo -{ -public: - int NumCyclesPower; - UInt32 SaltSize; - Byte Salt[16]; - CByteBuffer Password; - Byte Key[kKeySize]; - - bool IsEqualTo(const CKeyInfo &a) const; - void CalculateDigest(); - - CKeyInfo() { Init(); } - void Init() - { - NumCyclesPower = 0; - SaltSize = 0; - for (int i = 0; i < sizeof(Salt); i++) - Salt[i] = 0; - } -}; - -class CKeyInfoCache -{ - int Size; - CObjectVector Keys; -public: - CKeyInfoCache(int size): Size(size) {} - bool Find(CKeyInfo &key); - // HRESULT Calculate(CKeyInfo &key); - void Add(CKeyInfo &key); -}; - -class CBase -{ - CKeyInfoCache _cachedKeys; -protected: - CKeyInfo _key; - Byte _iv[16]; - UInt32 _ivSize; - void CalculateDigest(); - CBase(); -}; - -class CBaseCoder: - public ICompressFilter, - public ICryptoSetPassword, - public CMyUnknownImp, - public CBase -{ -protected: - CMyComPtr _aesFilter; - - virtual HRESULT CreateFilter() = 0; - #ifndef CRYPTO_AES - HRESULT CreateFilterFromDLL(REFCLSID clsID); - #endif -public: - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); -}; - -#ifndef EXTRACT_ONLY - -class CEncoder: - public CBaseCoder, - public ICompressWriteCoderProperties, - // public ICryptoResetSalt, - public ICryptoResetInitVector -{ - virtual HRESULT CreateFilter(); -public: - MY_UNKNOWN_IMP3( - ICryptoSetPassword, - ICompressWriteCoderProperties, - // ICryptoResetSalt, - ICryptoResetInitVector) - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); - // STDMETHOD(ResetSalt)(); - STDMETHOD(ResetInitVector)(); -}; -#endif - -class CDecoder: - public CBaseCoder, - public ICompressSetDecoderProperties2 -{ - virtual HRESULT CreateFilter(); -public: - MY_UNKNOWN_IMP2( - ICryptoSetPassword, - ICompressSetDecoderProperties2) - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAesRegister.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/7zAesRegister.cpp deleted file mode 100644 index 87f8ae9c8..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/7zAesRegister.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// 7zAesRegister.cpp - -#include "StdAfx.h" - -#include "../Common/RegisterCodec.h" -#include "7zAes.h" - -static void *CreateCodec() { return (void *)(ICompressFilter *)(new NCrypto::NSevenZ::CDecoder()); } -#ifndef EXTRACT_ONLY -static void *CreateCodecOut() { return (void *)(ICompressFilter *)(new NCrypto::NSevenZ::CEncoder()); } -#else -#define CreateCodecOut 0 -#endif - -static CCodecInfo g_CodecInfo = - { CreateCodec, CreateCodecOut, 0x06F10701, L"7zAES", 1, true }; - -REGISTER_CODEC(7zAES) diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.cpp deleted file mode 100644 index 09621e958..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.cpp +++ /dev/null @@ -1,109 +0,0 @@ -// HmacSha1.cpp - -#include "StdAfx.h" - -#include "HmacSha1.h" - -namespace NCrypto { -namespace NSha1 { - -void CHmac::SetKey(const Byte *key, size_t keySize) -{ - Byte keyTemp[kBlockSize]; - size_t i; - for (i = 0; i < kBlockSize; i++) - keyTemp[i] = 0; - if(keySize > kBlockSize) - { - _sha.Init(); - _sha.Update(key, keySize); - _sha.Final(keyTemp); - keySize = kDigestSize; - } - else - for (i = 0; i < keySize; i++) - keyTemp[i] = key[i]; - for (i = 0; i < kBlockSize; i++) - keyTemp[i] ^= 0x36; - _sha.Init(); - _sha.Update(keyTemp, kBlockSize); - for (i = 0; i < kBlockSize; i++) - keyTemp[i] ^= 0x36 ^ 0x5C; - _sha2.Init(); - _sha2.Update(keyTemp, kBlockSize); -} - -void CHmac::Final(Byte *mac, size_t macSize) -{ - Byte digest[kDigestSize]; - _sha.Final(digest); - _sha2.Update(digest, kDigestSize); - _sha2.Final(digest); - for(size_t i = 0; i < macSize; i++) - mac[i] = digest[i]; -} - - -void CHmac32::SetKey(const Byte *key, size_t keySize) -{ - UInt32 keyTemp[kBlockSizeInWords]; - size_t i; - for (i = 0; i < kBlockSizeInWords; i++) - keyTemp[i] = 0; - if(keySize > kBlockSize) - { - CContext sha; - sha.Init(); - sha.Update(key, keySize); - Byte digest[kDigestSize]; - sha.Final(digest); - - for (int i = 0 ; i < kDigestSizeInWords; i++) - keyTemp[i] = - ((UInt32)(digest[i * 4 + 0]) << 24) | - ((UInt32)(digest[i * 4 + 1]) << 16) | - ((UInt32)(digest[i * 4 + 2]) << 8) | - ((UInt32)(digest[i * 4 + 3])); - keySize = kDigestSizeInWords; - } - else - for (size_t i = 0; i < keySize; i++) - keyTemp[i / 4] |= (key[i] << (24 - 8 * (i & 3))); - for (i = 0; i < kBlockSizeInWords; i++) - keyTemp[i] ^= 0x36363636; - _sha.Init(); - _sha.Update(keyTemp, kBlockSizeInWords); - for (i = 0; i < kBlockSizeInWords; i++) - keyTemp[i] ^= 0x36363636 ^ 0x5C5C5C5C; - _sha2.Init(); - _sha2.Update(keyTemp, kBlockSizeInWords); -} - -void CHmac32::Final(UInt32 *mac, size_t macSize) -{ - UInt32 digest[kDigestSizeInWords]; - _sha.Final(digest); - _sha2.Update(digest, kDigestSizeInWords); - _sha2.Final(digest); - for(size_t i = 0; i < macSize; i++) - mac[i] = digest[i]; -} - -void CHmac32::GetLoopXorDigest(UInt32 *mac, UInt32 numIteration) -{ - UInt32 block[kBlockSizeInWords]; - UInt32 block2[kBlockSizeInWords]; - _sha.PrepareBlock(block, kDigestSizeInWords); - _sha2.PrepareBlock(block2, kDigestSizeInWords); - for(unsigned int s = 0; s < kDigestSizeInWords; s++) - block[s] = mac[s]; - for(UInt32 i = 0; i < numIteration; i++) - { - _sha.GetBlockDigest(block, block2); - _sha2.GetBlockDigest(block2, block); - for (unsigned int s = 0; s < kDigestSizeInWords; s++) - mac[s] ^= block[s]; - } -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.h b/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.h deleted file mode 100644 index 2b12340ed..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/HmacSha1.h +++ /dev/null @@ -1,39 +0,0 @@ -// HmacSha1.h -// Implements HMAC-SHA-1 (RFC2104, FIPS-198) - -#ifndef __CRYPTO_HMAC_SHA1_H -#define __CRYPTO_HMAC_SHA1_H - -#include "Sha1.h" - -namespace NCrypto { -namespace NSha1 { - -// Use: SetKey(key, keySize); for () Update(data, size); Final(mac, macSize); - -class CHmac -{ - CContext _sha; - CContext _sha2; -public: - void SetKey(const Byte *key, size_t keySize); - void Update(const Byte *data, size_t dataSize) { _sha.Update(data, dataSize); } - void Final(Byte *mac, size_t macSize = kDigestSize); -}; - -class CHmac32 -{ - CContext32 _sha; - CContext32 _sha2; -public: - void SetKey(const Byte *key, size_t keySize); - void Update(const UInt32 *data, size_t dataSize) { _sha.Update(data, dataSize); } - void Final(UInt32 *mac, size_t macSize = kDigestSizeInWords); - - // It'sa for hmac function. in,out: mac[kDigestSizeInWords]. - void GetLoopXorDigest(UInt32 *mac, UInt32 numIteration); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.cpp deleted file mode 100644 index 0f7b74b8d..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// Crypto/MyAes.cpp - -#include "StdAfx.h" - -#include "MyAes.h" - -namespace NCrypto { - -struct CAesTabInit { CAesTabInit() { AesGenTables();} } g_AesTabInit; - -STDMETHODIMP CAesCbcEncoder::Init() { return S_OK; } - -STDMETHODIMP_(UInt32) CAesCbcEncoder::Filter(Byte *data, UInt32 size) -{ - return (UInt32)AesCbc_Encode(&Aes, data, size); -} - -STDMETHODIMP CAesCbcEncoder::SetKey(const Byte *data, UInt32 size) -{ - if ((size & 0x7) != 0 || size < 16 || size > 32) - return E_INVALIDARG; - Aes_SetKeyEncode(&Aes.aes, data, size); - return S_OK; -} - -STDMETHODIMP CAesCbcEncoder::SetInitVector(const Byte *data, UInt32 size) -{ - if (size != AES_BLOCK_SIZE) - return E_INVALIDARG; - AesCbc_Init(&Aes, data); - return S_OK; -} - -STDMETHODIMP CAesCbcDecoder::Init() { return S_OK; } - -STDMETHODIMP_(UInt32) CAesCbcDecoder::Filter(Byte *data, UInt32 size) -{ - return (UInt32)AesCbc_Decode(&Aes, data, size); -} - -STDMETHODIMP CAesCbcDecoder::SetKey(const Byte *data, UInt32 size) -{ - if ((size & 0x7) != 0 || size < 16 || size > 32) - return E_INVALIDARG; - Aes_SetKeyDecode(&Aes.aes, data, size); - return S_OK; -} - -STDMETHODIMP CAesCbcDecoder::SetInitVector(const Byte *data, UInt32 size) -{ - if (size != AES_BLOCK_SIZE) - return E_INVALIDARG; - AesCbc_Init(&Aes, data); - return S_OK; -} - -} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.h b/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.h deleted file mode 100644 index bfa58cdba..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/MyAes.h +++ /dev/null @@ -1,48 +0,0 @@ -// Crypto/MyAes.h - -#ifndef __CRYPTO_MY_AES_H -#define __CRYPTO_MY_AES_H - -extern "C" -{ -#include "../../../C/Aes.h" -} - -#include "../../Common/MyCom.h" -#include "../../Common/Types.h" - -#include "../ICoder.h" - -namespace NCrypto { - -class CAesCbcEncoder: - public ICompressFilter, - public ICryptoProperties, - public CMyUnknownImp -{ - CAesCbc Aes; -public: - MY_UNKNOWN_IMP1(ICryptoProperties) - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - STDMETHOD(SetKey)(const Byte *data, UInt32 size); - STDMETHOD(SetInitVector)(const Byte *data, UInt32 size); -}; - -class CAesCbcDecoder: - public ICompressFilter, - public ICryptoProperties, - public CMyUnknownImp -{ - CAesCbc Aes; -public: - MY_UNKNOWN_IMP1(ICryptoProperties) - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - STDMETHOD(SetKey)(const Byte *data, UInt32 size); - STDMETHOD(SetInitVector)(const Byte *data, UInt32 size); -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp deleted file mode 100644 index 0ac6dc61b..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.cpp +++ /dev/null @@ -1,83 +0,0 @@ -// Pbkdf2HmacSha1.cpp - -#include "StdAfx.h" - -#include "HmacSha1.h" - -namespace NCrypto { -namespace NSha1 { - -void Pbkdf2Hmac(const Byte *pwd, size_t pwdSize, const Byte *salt, size_t saltSize, - UInt32 numIterations, Byte *key, size_t keySize) -{ - CHmac baseCtx; - baseCtx.SetKey(pwd, pwdSize); - for (UInt32 i = 1; keySize > 0; i++) - { - CHmac ctx = baseCtx; - ctx.Update(salt, saltSize); - Byte u[kDigestSize] = { (Byte)(i >> 24), (Byte)(i >> 16), (Byte)(i >> 8), (Byte)(i) }; - const unsigned int curSize = (keySize < kDigestSize) ? (unsigned int)keySize : kDigestSize; - ctx.Update(u, 4); - ctx.Final(u, kDigestSize); - - unsigned int s; - for (s = 0; s < curSize; s++) - key[s] = u[s]; - - for (UInt32 j = numIterations; j > 1; j--) - { - ctx = baseCtx; - ctx.Update(u, kDigestSize); - ctx.Final(u, kDigestSize); - for (s = 0; s < curSize; s++) - key[s] ^= u[s]; - } - - key += curSize; - keySize -= curSize; - } -} - -void Pbkdf2Hmac32(const Byte *pwd, size_t pwdSize, const UInt32 *salt, size_t saltSize, - UInt32 numIterations, UInt32 *key, size_t keySize) -{ - CHmac32 baseCtx; - baseCtx.SetKey(pwd, pwdSize); - for (UInt32 i = 1; keySize > 0; i++) - { - CHmac32 ctx = baseCtx; - ctx.Update(salt, saltSize); - UInt32 u[kDigestSizeInWords] = { i }; - const unsigned int curSize = (keySize < kDigestSizeInWords) ? (unsigned int)keySize : kDigestSizeInWords; - ctx.Update(u, 1); - ctx.Final(u, kDigestSizeInWords); - - // Speed-optimized code start - ctx = baseCtx; - ctx.GetLoopXorDigest(u, numIterations - 1); - // Speed-optimized code end - - unsigned int s; - for (s = 0; s < curSize; s++) - key[s] = u[s]; - - /* - // Default code start - for (UInt32 j = numIterations; j > 1; j--) - { - ctx = baseCtx; - ctx.Update(u, kDigestSizeInWords); - ctx.Final(u, kDigestSizeInWords); - for (s = 0; s < curSize; s++) - key[s] ^= u[s]; - } - // Default code end - */ - - key += curSize; - keySize -= curSize; - } -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.h b/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.h deleted file mode 100644 index ea5d99f18..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Pbkdf2HmacSha1.h +++ /dev/null @@ -1,21 +0,0 @@ -// Pbkdf2HmacSha1.h -// Password-Based Key Derivation Function (RFC 2898, PKCS #5) based on HMAC-SHA-1 - -#ifndef __CRYPTO_PBKDF2_HMAC_SHA1_H -#define __CRYPTO_PBKDF2_HMAC_SHA1_H - -#include -#include "../../Common/Types.h" - -namespace NCrypto { -namespace NSha1 { - -void Pbkdf2Hmac(const Byte *pwd, size_t pwdSize, const Byte *salt, size_t saltSize, - UInt32 numIterations, Byte *key, size_t keySize); - -void Pbkdf2Hmac32(const Byte *pwd, size_t pwdSize, const UInt32 *salt, size_t saltSize, - UInt32 numIterations, UInt32 *key, size_t keySize); - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.cpp deleted file mode 100644 index 66b323168..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.cpp +++ /dev/null @@ -1,107 +0,0 @@ -// RandGen.cpp - -#include "StdAfx.h" - -#include -#include "Windows/Synchronization.h" -#include "RandGen.h" - -#ifndef _WIN32 -#include -#define USE_POSIX_TIME -#define USE_POSIX_TIME2 -#endif - -#ifdef USE_POSIX_TIME -#include -#ifdef USE_POSIX_TIME2 -#include -#endif -#endif - -// This is not very good random number generator. -// Please use it only for salt. -// First generated data block depends from timer and processID. -// Other generated data blocks depend from previous state -// Maybe it's possible to restore original timer value from generated value. - -void CRandomGenerator::Init() -{ - NCrypto::NSha1::CContext hash; - hash.Init(); - - #ifdef _WIN32 - DWORD w = ::GetCurrentProcessId(); - hash.Update((const Byte *)&w, sizeof(w)); - w = ::GetCurrentThreadId(); - hash.Update((const Byte *)&w, sizeof(w)); - #else - pid_t pid = getpid(); - hash.Update((const Byte *)&pid, sizeof(pid)); - pid = getppid(); - hash.Update((const Byte *)&pid, sizeof(pid)); - #endif - - for (int i = 0; i < 1000; i++) - { - #ifdef _WIN32 - LARGE_INTEGER v; - if (::QueryPerformanceCounter(&v)) - hash.Update((const Byte *)&v.QuadPart, sizeof(v.QuadPart)); - #endif - - #ifdef USE_POSIX_TIME - #ifdef USE_POSIX_TIME2 - timeval v; - if (gettimeofday(&v, 0) == 0) - { - hash.Update((const Byte *)&v.tv_sec, sizeof(v.tv_sec)); - hash.Update((const Byte *)&v.tv_usec, sizeof(v.tv_usec)); - } - #endif - time_t v2 = time(NULL); - hash.Update((const Byte *)&v2, sizeof(v2)); - #endif - - DWORD tickCount = ::GetTickCount(); - hash.Update((const Byte *)&tickCount, sizeof(tickCount)); - - for (int j = 0; j < 100; j++) - { - hash.Final(_buff); - hash.Init(); - hash.Update(_buff, NCrypto::NSha1::kDigestSize); - } - } - hash.Final(_buff); - _needInit = false; -} - -static NWindows::NSynchronization::CCriticalSection g_CriticalSection; - -void CRandomGenerator::Generate(Byte *data, unsigned int size) -{ - g_CriticalSection.Enter(); - if (_needInit) - Init(); - while (size > 0) - { - NCrypto::NSha1::CContext hash; - - hash.Init(); - hash.Update(_buff, NCrypto::NSha1::kDigestSize); - hash.Final(_buff); - - hash.Init(); - UInt32 salt = 0xF672ABD1; - hash.Update((const Byte *)&salt, sizeof(salt)); - hash.Update(_buff, NCrypto::NSha1::kDigestSize); - Byte buff[NCrypto::NSha1::kDigestSize]; - hash.Final(buff); - for (unsigned int i = 0; i < NCrypto::NSha1::kDigestSize && size > 0; i++, size--) - *data++ = buff[i]; - } - g_CriticalSection.Leave(); -} - -CRandomGenerator g_RandomGenerator; diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.h b/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.h deleted file mode 100644 index a457897a9..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/RandGen.h +++ /dev/null @@ -1,21 +0,0 @@ -// RandGen.h - -#ifndef __CRYPTO_RAND_GEN_H -#define __CRYPTO_RAND_GEN_H - -#include "Sha1.h" - -class CRandomGenerator -{ - Byte _buff[NCrypto::NSha1::kDigestSize]; - bool _needInit; - - void Init(); -public: - CRandomGenerator(): _needInit(true) {}; - void Generate(Byte *data, unsigned size); -}; - -extern CRandomGenerator g_RandomGenerator; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.cpp deleted file mode 100644 index bf5eb9894..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.cpp +++ /dev/null @@ -1,136 +0,0 @@ -// Crypto/Rar20Crypto.cpp - -#include "StdAfx.h" - -extern "C" -{ - #include "../../../C/7zCrc.h" - #include "../../../C/CpuArch.h" - #include "../../../C/RotateDefs.h" -} - -#include "Rar20Crypto.h" - -namespace NCrypto { -namespace NRar20 { - -static const int kNumRounds = 32; - -static const Byte InitSubstTable[256] = { - 215, 19,149, 35, 73,197,192,205,249, 28, 16,119, 48,221, 2, 42, - 232, 1,177,233, 14, 88,219, 25,223,195,244, 90, 87,239,153,137, - 255,199,147, 70, 92, 66,246, 13,216, 40, 62, 29,217,230, 86, 6, - 71, 24,171,196,101,113,218,123, 93, 91,163,178,202, 67, 44,235, - 107,250, 75,234, 49,167,125,211, 83,114,157,144, 32,193,143, 36, - 158,124,247,187, 89,214,141, 47,121,228, 61,130,213,194,174,251, - 97,110, 54,229,115, 57,152, 94,105,243,212, 55,209,245, 63, 11, - 164,200, 31,156, 81,176,227, 21, 76, 99,139,188,127, 17,248, 51, - 207,120,189,210, 8,226, 41, 72,183,203,135,165,166, 60, 98, 7, - 122, 38,155,170, 69,172,252,238, 39,134, 59,128,236, 27,240, 80, - 131, 3, 85,206,145, 79,154,142,159,220,201,133, 74, 64, 20,129, - 224,185,138,103,173,182, 43, 34,254, 82,198,151,231,180, 58, 10, - 118, 26,102, 12, 50,132, 22,191,136,111,162,179, 45, 4,148,108, - 161, 56, 78,126,242,222, 15,175,146, 23, 33,241,181,190, 77,225, - 0, 46,169,186, 68, 95,237, 65, 53,208,253,168, 9, 18,100, 52, - 116,184,160, 96,109, 37, 30,106,140,104,150, 5,204,117,112, 84 -}; - -void CData::UpdateKeys(const Byte *data) -{ - for (int i = 0; i < 16; i += 4) - for (int j = 0; j < 4; j++) - Keys[j] ^= g_CrcTable[data[i + j]]; -} - -static void Swap(Byte *b1, Byte *b2) -{ - Byte b = *b1; - *b1 = *b2; - *b2 = b; -} - -void CData::SetPassword(const Byte *password, UInt32 passwordLen) -{ - Keys[0] = 0xD3A3B879L; - Keys[1] = 0x3F6D12F7L; - Keys[2] = 0x7515A235L; - Keys[3] = 0xA4E7F123L; - - Byte psw[256]; - memset(psw, 0, sizeof(psw)); - memcpy(psw, password, passwordLen); - memcpy(SubstTable, InitSubstTable, sizeof(SubstTable)); - - for (UInt32 j = 0; j < 256; j++) - for (UInt32 i = 0; i < passwordLen; i += 2) - { - UInt32 n2 = (Byte)g_CrcTable[(psw[i + 1] + j) & 0xFF]; - UInt32 n1 = (Byte)g_CrcTable[(psw[i] - j) & 0xFF]; - for (UInt32 k = 1; (n1 & 0xFF) != n2; n1++, k++) - Swap(&SubstTable[n1 & 0xFF], &SubstTable[(n1 + i + k) & 0xFF]); - } - for (UInt32 i = 0; i < passwordLen; i+= 16) - EncryptBlock(&psw[i]); -} - -void CData::CryptBlock(Byte *buf, bool encrypt) -{ - Byte inBuf[16]; - UInt32 A, B, C, D, T, TA, TB; - - A = GetUi32(buf + 0) ^ Keys[0]; - B = GetUi32(buf + 4) ^ Keys[1]; - C = GetUi32(buf + 8) ^ Keys[2]; - D = GetUi32(buf + 12) ^ Keys[3]; - - if (!encrypt) - memcpy(inBuf, buf, sizeof(inBuf)); - - for (int i = 0; i < kNumRounds; i++) - { - UInt32 key = Keys[(encrypt ? i : (kNumRounds - 1 - i)) & 3]; - T = ((C + rotlFixed(D, 11)) ^ key); - TA = A ^ SubstLong(T); - T = ((D ^ rotlFixed(C, 17)) + key); - TB = B ^ SubstLong(T); - A = C; - B = D; - C = TA; - D = TB; - } - - SetUi32(buf + 0, C ^ Keys[0]); - SetUi32(buf + 4, D ^ Keys[1]); - SetUi32(buf + 8, A ^ Keys[2]); - SetUi32(buf + 12, B ^ Keys[3]); - - UpdateKeys(encrypt ? buf : inBuf); -} - -STDMETHODIMP CDecoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - _cipher.SetPassword(data, size); - return S_OK; -} - -STDMETHODIMP CDecoder::Init() -{ - return S_OK; -} - -static const UInt32 kBlockSize = 16; - -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) -{ - if (size == 0) - return 0; - if (size < kBlockSize) - return kBlockSize; - UInt32 i; - size -= kBlockSize; - for (i = 0; i <= size; i += kBlockSize) - _cipher.DecryptBlock(data + i); - return i; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.h b/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.h deleted file mode 100644 index 36f5590d1..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Rar20Crypto.h +++ /dev/null @@ -1,50 +0,0 @@ -// Crypto/Rar20Crypto.h - -#ifndef __CRYPTO_RAR20_CRYPTO_H -#define __CRYPTO_RAR20_CRYPTO_H - -#include "Common/MyCom.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -namespace NCrypto { -namespace NRar20 { - -class CData -{ - Byte SubstTable[256]; - UInt32 Keys[4]; - - UInt32 SubstLong(UInt32 t) - { - return (UInt32)SubstTable[(int)t & 255] | - ((UInt32)SubstTable[(int)(t >> 8) & 255] << 8) | - ((UInt32)SubstTable[(int)(t >> 16) & 255] << 16) | - ((UInt32)SubstTable[(int)(t >> 24) & 255] << 24); - } - void UpdateKeys(const Byte *data); - void CryptBlock(Byte *buf, bool encrypt); -public: - void EncryptBlock(Byte *buf) { CryptBlock(buf, true); } - void DecryptBlock(Byte *buf) { CryptBlock(buf, false); } - void SetPassword(const Byte *password, UInt32 passwordLen); -}; - -class CDecoder: - public ICompressFilter, - public ICryptoSetPassword, - public CMyUnknownImp -{ - CData _cipher; -public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) - - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.cpp deleted file mode 100644 index be3cefcc4..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.cpp +++ /dev/null @@ -1,139 +0,0 @@ -// Crypto/RarAes.cpp -// Note: you must include MyAes.cpp to project to initialize AES tables - -#include "StdAfx.h" - -#include "RarAes.h" -#include "Sha1.h" - -namespace NCrypto { -namespace NRar29 { - -CDecoder::CDecoder(): - _thereIsSalt(false), - _needCalculate(true), - _rar350Mode(false) -{ - for (int i = 0; i < sizeof(_salt); i++) - _salt[i] = 0; -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - bool thereIsSaltPrev = _thereIsSalt; - _thereIsSalt = false; - if (size == 0) - return S_OK; - if (size < 8) - return E_INVALIDARG; - _thereIsSalt = true; - bool same = false; - if (_thereIsSalt == thereIsSaltPrev) - { - same = true; - if (_thereIsSalt) - { - for (int i = 0; i < sizeof(_salt); i++) - if (_salt[i] != data[i]) - { - same = false; - break; - } - } - } - for (int i = 0; i < sizeof(_salt); i++) - _salt[i] = data[i]; - if (!_needCalculate && !same) - _needCalculate = true; - return S_OK; -} - -static const int kMaxPasswordLength = 127 * 2; - -STDMETHODIMP CDecoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - if (size > kMaxPasswordLength) - size = kMaxPasswordLength; - bool same = false; - if (size == buffer.GetCapacity()) - { - same = true; - for (UInt32 i = 0; i < size; i++) - if (data[i] != buffer[i]) - { - same = false; - break; - } - } - if (!_needCalculate && !same) - _needCalculate = true; - buffer.SetCapacity(size); - memcpy(buffer, data, size); - return S_OK; -} - -STDMETHODIMP CDecoder::Init() -{ - Calculate(); - Aes_SetKeyDecode(&Aes.aes, aesKey, kRarAesKeySize); - AesCbc_Init(&Aes, aesInit); - return S_OK; -} - -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) -{ - return (UInt32)AesCbc_Decode(&Aes, data, size); -} - -void CDecoder::Calculate() -{ - if (_needCalculate) - { - const int kSaltSize = 8; - - Byte rawPassword[kMaxPasswordLength + kSaltSize]; - - memcpy(rawPassword, buffer, buffer.GetCapacity()); - - size_t rawLength = buffer.GetCapacity(); - - if (_thereIsSalt) - { - memcpy(rawPassword + rawLength, _salt, kSaltSize); - rawLength += kSaltSize; - } - - NSha1::CContext sha; - sha.Init(); - - // seems rar reverts hash for sha. - const int hashRounds = 0x40000; - int i; - for (i = 0; i < hashRounds; i++) - { - sha.Update(rawPassword, rawLength, _rar350Mode); - Byte pswNum[3] = { (Byte)i, (Byte)(i >> 8), (Byte)(i >> 16) }; - sha.Update(pswNum, 3, _rar350Mode); - if (i % (hashRounds / 16) == 0) - { - NSha1::CContext shaTemp = sha; - Byte digest[NSha1::kDigestSize]; - shaTemp.Final(digest); - aesInit[i / (hashRounds / 16)] = (Byte)digest[4 * 4 + 3]; - } - } - /* - // it's test message for sha - const char *message = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; - sha.Update((const Byte *)message, strlen(message)); - */ - Byte digest[20]; - sha.Final(digest); - for (i = 0; i < 4; i++) - for (int j = 0; j < 4; j++) - aesKey[i * 4 + j] = (digest[i * 4 + 3 - j]); - } - _needCalculate = false; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.h b/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.h deleted file mode 100644 index d21d12a55..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/RarAes.h +++ /dev/null @@ -1,62 +0,0 @@ -// Crypto/RarAes.h - -#ifndef __CRYPTO_RAR_AES_H -#define __CRYPTO_RAR_AES_H - -extern "C" -{ -#include "../../../C/Aes.h" -} - -#include "Common/Buffer.h" -#include "Common/MyCom.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -namespace NCrypto { -namespace NRar29 { - -const UInt32 kRarAesKeySize = 16; - -class CDecoder: - public ICompressFilter, - public ICompressSetDecoderProperties2, - public ICryptoSetPassword, - public CMyUnknownImp -{ - Byte _salt[8]; - bool _thereIsSalt; - CByteBuffer buffer; - Byte aesKey[kRarAesKeySize]; - Byte aesInit[AES_BLOCK_SIZE]; - bool _needCalculate; - - CAesCbc Aes; - - bool _rar350Mode; - - void Calculate(); - -public: - - MY_UNKNOWN_IMP2( - ICryptoSetPassword, - ICompressSetDecoderProperties2) - - STDMETHOD(Init)(); - - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - - STDMETHOD(CryptoSetPassword)(const Byte *aData, UInt32 aSize); - - // ICompressSetDecoderProperties - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - - CDecoder(); - void SetRar350Mode(bool rar350Mode) { _rar350Mode = rar350Mode; } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.cpp deleted file mode 100644 index 08bb57c94..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.cpp +++ /dev/null @@ -1,213 +0,0 @@ -// Crypto/Sha1.cpp -// This file is based on public domain -// Steve Reid and Wei Dai's code from Crypto++ - -#include "StdAfx.h" - -#include "Sha1.h" -extern "C" -{ -#include "../../../C/RotateDefs.h" -} - -namespace NCrypto { -namespace NSha1 { - -// define it for speed optimization -// #define _SHA1_UNROLL - -static const unsigned kNumW = - #ifdef _SHA1_UNROLL - 16; - #else - 80; - #endif - - -#define w0(i) (W[(i)] = data[(i)]) - -#ifdef _SHA1_UNROLL -#define w1(i) (W[(i)&15] = rotlFixed(W[((i)-3)&15] ^ W[((i)-8)&15] ^ W[((i)-14)&15] ^ W[((i)-16)&15], 1)) -#else -#define w1(i) (W[(i)] = rotlFixed(W[(i)-3] ^ W[(i)-8] ^ W[(i)-14] ^ W[(i)-16], 1)) -#endif - -#define f1(x,y,z) (z^(x&(y^z))) -#define f2(x,y,z) (x^y^z) -#define f3(x,y,z) ((x&y)|(z&(x|y))) -#define f4(x,y,z) (x^y^z) - -#define RK1(a,b,c,d,e,i, f, w, k) e += f(b,c,d) + w(i) + k + rotlFixed(a,5); b = rotlFixed(b,30); - -#define R0(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f1, w0, 0x5A827999) -#define R1(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f1, w1, 0x5A827999) -#define R2(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f2, w1, 0x6ED9EBA1) -#define R3(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f3, w1, 0x8F1BBCDC) -#define R4(a,b,c,d,e,i) RK1(a,b,c,d,e,i, f4, w1, 0xCA62C1D6) - -#define RX_1_4(rx1, rx4, i) rx1(a,b,c,d,e,i); rx4(e,a,b,c,d,i+1); rx4(d,e,a,b,c,i+2); rx4(c,d,e,a,b,i+3); rx4(b,c,d,e,a,i+4); -#define RX_5(rx, i) RX_1_4(rx, rx, i); - -void CContextBase::Init() -{ - _state[0] = 0x67452301; - _state[1] = 0xEFCDAB89; - _state[2] = 0x98BADCFE; - _state[3] = 0x10325476; - _state[4] = 0xC3D2E1F0; - _count = 0; -} - -void CContextBase::GetBlockDigest(UInt32 *data, UInt32 *destDigest, bool returnRes) -{ - UInt32 a, b, c, d, e; - UInt32 W[kNumW]; - - a = _state[0]; - b = _state[1]; - c = _state[2]; - d = _state[3]; - e = _state[4]; - #ifdef _SHA1_UNROLL - RX_5(R0, 0); RX_5(R0, 5); RX_5(R0, 10); - #else - int i; - for (i = 0; i < 15; i += 5) { RX_5(R0, i); } - #endif - - RX_1_4(R0, R1, 15); - - - #ifdef _SHA1_UNROLL - RX_5(R2, 20); RX_5(R2, 25); RX_5(R2, 30); RX_5(R2, 35); - RX_5(R3, 40); RX_5(R3, 45); RX_5(R3, 50); RX_5(R3, 55); - RX_5(R4, 60); RX_5(R4, 65); RX_5(R4, 70); RX_5(R4, 75); - #else - i = 20; - for (; i < 40; i += 5) { RX_5(R2, i); } - for (; i < 60; i += 5) { RX_5(R3, i); } - for (; i < 80; i += 5) { RX_5(R4, i); } - #endif - - destDigest[0] = _state[0] + a; - destDigest[1] = _state[1] + b; - destDigest[2] = _state[2] + c; - destDigest[3] = _state[3] + d; - destDigest[4] = _state[4] + e; - - if (returnRes) - for (int i = 0 ; i < 16; i++) - data[i] = W[kNumW - 16 + i]; - - // Wipe variables - // a = b = c = d = e = 0; -} - -void CContextBase::PrepareBlock(UInt32 *block, unsigned size) const -{ - unsigned curBufferPos = size & 0xF; - block[curBufferPos++] = 0x80000000; - while (curBufferPos != (16 - 2)) - block[curBufferPos++] = 0; - const UInt64 lenInBits = (_count << 9) + ((UInt64)size << 5); - block[curBufferPos++] = (UInt32)(lenInBits >> 32); - block[curBufferPos++] = (UInt32)(lenInBits); -} - -void CContext::Update(Byte *data, size_t size, bool rar350Mode) -{ - bool returnRes = false; - unsigned curBufferPos = _count2; - while (size-- > 0) - { - int pos = (int)(curBufferPos & 3); - if (pos == 0) - _buffer[curBufferPos >> 2] = 0; - _buffer[curBufferPos >> 2] |= ((UInt32)*data++) << (8 * (3 - pos)); - if (++curBufferPos == kBlockSize) - { - curBufferPos = 0; - CContextBase::UpdateBlock(_buffer, returnRes); - if (returnRes) - for (int i = 0; i < kBlockSizeInWords; i++) - { - UInt32 d = _buffer[i]; - data[i * 4 + 0 - kBlockSize] = (Byte)(d); - data[i * 4 + 1 - kBlockSize] = (Byte)(d >> 8); - data[i * 4 + 2 - kBlockSize] = (Byte)(d >> 16); - data[i * 4 + 3 - kBlockSize] = (Byte)(d >> 24); - } - returnRes = rar350Mode; - } - } - _count2 = curBufferPos; -} - -void CContext::Final(Byte *digest) -{ - const UInt64 lenInBits = (_count << 9) + ((UInt64)_count2 << 3); - unsigned curBufferPos = _count2; - int pos = (int)(curBufferPos & 3); - curBufferPos >>= 2; - if (pos == 0) - _buffer[curBufferPos] = 0; - _buffer[curBufferPos++] |= ((UInt32)0x80) << (8 * (3 - pos)); - - while (curBufferPos != (16 - 2)) - { - curBufferPos &= 0xF; - if (curBufferPos == 0) - UpdateBlock(); - _buffer[curBufferPos++] = 0; - } - _buffer[curBufferPos++] = (UInt32)(lenInBits >> 32); - _buffer[curBufferPos++] = (UInt32)(lenInBits); - UpdateBlock(); - - int i; - for (i = 0; i < kDigestSizeInWords; i++) - { - UInt32 state = _state[i] & 0xFFFFFFFF; - *digest++ = (Byte)(state >> 24); - *digest++ = (Byte)(state >> 16); - *digest++ = (Byte)(state >> 8); - *digest++ = (Byte)(state); - } - Init(); -} - -/////////////////////////// -// Words version - -void CContext32::Update(const UInt32 *data, size_t size) -{ - while (size-- > 0) - { - _buffer[_count2++] = *data++; - if (_count2 == kBlockSizeInWords) - { - _count2 = 0; - UpdateBlock(); - } - } -} - -void CContext32::Final(UInt32 *digest) -{ - const UInt64 lenInBits = (_count << 9) + ((UInt64)_count2 << 5); - unsigned curBufferPos = _count2; - _buffer[curBufferPos++] = 0x80000000; - while (curBufferPos != (16 - 2)) - { - curBufferPos &= 0xF; - if (curBufferPos == 0) - UpdateBlock(); - _buffer[curBufferPos++] = 0; - } - _buffer[curBufferPos++] = (UInt32)(lenInBits >> 32); - _buffer[curBufferPos++] = (UInt32)(lenInBits); - GetBlockDigest(_buffer, digest); - Init(); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.h b/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.h deleted file mode 100644 index 06ae27024..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/Sha1.h +++ /dev/null @@ -1,68 +0,0 @@ -// Crypto/Sha1.h -// This file is based on public domain -// Steve Reid and Wei Dai's code from Crypto++ - -#ifndef __CRYPTO_SHA1_H -#define __CRYPTO_SHA1_H - -#include -#include "../../Common/Types.h" - -// Sha1 implementation in RAR before version 3.60 has bug: -// it changes data bytes in some cases. -// So this class supports both versions: normal_SHA and rar3Mode - -namespace NCrypto { -namespace NSha1 { - -const unsigned kBlockSize = 64; -const unsigned kDigestSize = 20; - -const unsigned kBlockSizeInWords = (kBlockSize >> 2); -const unsigned kDigestSizeInWords = (kDigestSize >> 2); - -class CContextBase -{ -protected: - UInt32 _state[5]; - UInt64 _count; - void UpdateBlock(UInt32 *data, bool returnRes = false) - { - GetBlockDigest(data, _state, returnRes); - _count++; - } -public: - void Init(); - void GetBlockDigest(UInt32 *blockData, UInt32 *destDigest, bool returnRes = false); - // PrepareBlock can be used only when size <= 13. size in Words - void PrepareBlock(UInt32 *block, unsigned int size) const; -}; - -class CContextBase2: public CContextBase -{ -protected: - unsigned _count2; - UInt32 _buffer[kBlockSizeInWords]; - void UpdateBlock() { CContextBase::UpdateBlock(_buffer); } -public: - void Init() { CContextBase::Init(); _count2 = 0; } -}; - -class CContext: public CContextBase2 -{ -public: - void Update(Byte *data, size_t size, bool rar350Mode = false); - void Update(const Byte *data, size_t size) { Update((Byte *)data, size, false); } - void Final(Byte *digest); -}; - -class CContext32: public CContextBase2 -{ -public: - void Update(const UInt32 *data, size_t size); - void Final(UInt32 *digest); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/StdAfx.h b/desmume/src/windows/7z/CPP/7zip/Crypto/StdAfx.h deleted file mode 100644 index c28ffcea7..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/StdAfx.h +++ /dev/null @@ -1,8 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../../Common/MyWindows.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.cpp deleted file mode 100644 index b8f003034..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.cpp +++ /dev/null @@ -1,209 +0,0 @@ -// Crypto/WzAes.cpp -/* -This code implements Brian Gladman's scheme -specified in password Based File Encryption Utility. - -Note: you must include MyAes.cpp to project to initialize AES tables -*/ - -#include "StdAfx.h" - -#include "../Common/StreamObjects.h" -#include "../Common/StreamUtils.h" - -#include "Pbkdf2HmacSha1.h" -#include "RandGen.h" -#include "WzAes.h" - -// define it if you don't want to use speed-optimized version of Pbkdf2HmacSha1 -// #define _NO_WZAES_OPTIMIZATIONS - -namespace NCrypto { -namespace NWzAes { - -const unsigned int kAesKeySizeMax = 32; - -static const UInt32 kNumKeyGenIterations = 1000; - -STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - if(size > kPasswordSizeMax) - return E_INVALIDARG; - _key.Password.SetCapacity(size); - memcpy(_key.Password, data, size); - return S_OK; -} - -#define SetUi32(p, d) { UInt32 x = (d); (p)[0] = (Byte)x; (p)[1] = (Byte)(x >> 8); \ - (p)[2] = (Byte)(x >> 16); (p)[3] = (Byte)(x >> 24); } - -void CBaseCoder::EncryptData(Byte *data, UInt32 size) -{ - unsigned int pos = _blockPos; - for (; size > 0; size--) - { - if (pos == AES_BLOCK_SIZE) - { - if (++_counter[0] == 0) - _counter[1]++; - UInt32 temp[4]; - Aes_Encode32(&Aes, temp, _counter); - SetUi32(_buffer, temp[0]); - SetUi32(_buffer + 4, temp[1]); - SetUi32(_buffer + 8, temp[2]); - SetUi32(_buffer + 12, temp[3]); - pos = 0; - } - *data++ ^= _buffer[pos++]; - } - _blockPos = pos; -} - -#ifndef _NO_WZAES_OPTIMIZATIONS - -static void BytesToBeUInt32s(const Byte *src, UInt32 *dest, int destSize) -{ - for (int i = 0 ; i < destSize; i++) - dest[i] = - ((UInt32)(src[i * 4 + 0]) << 24) | - ((UInt32)(src[i * 4 + 1]) << 16) | - ((UInt32)(src[i * 4 + 2]) << 8) | - ((UInt32)(src[i * 4 + 3])); -} - -#endif - -STDMETHODIMP CBaseCoder::Init() -{ - UInt32 keySize = _key.GetKeySize(); - UInt32 keysTotalSize = 2 * keySize + kPwdVerifCodeSize; - Byte buf[2 * kAesKeySizeMax + kPwdVerifCodeSize]; - - // for (int ii = 0; ii < 1000; ii++) - { - #ifdef _NO_WZAES_OPTIMIZATIONS - - NSha1::Pbkdf2Hmac( - _key.Password, _key.Password.GetCapacity(), - _key.Salt, _key.GetSaltSize(), - kNumKeyGenIterations, - buf, keysTotalSize); - - #else - - UInt32 buf32[(2 * kAesKeySizeMax + kPwdVerifCodeSize + 3) / 4]; - UInt32 key32SizeTotal = (keysTotalSize + 3) / 4; - UInt32 salt[kSaltSizeMax * 4]; - UInt32 saltSizeInWords = _key.GetSaltSize() / 4; - BytesToBeUInt32s(_key.Salt, salt, saltSizeInWords); - NSha1::Pbkdf2Hmac32( - _key.Password, _key.Password.GetCapacity(), - salt, saltSizeInWords, - kNumKeyGenIterations, - buf32, key32SizeTotal); - for (UInt32 j = 0; j < keysTotalSize; j++) - buf[j] = (Byte)(buf32[j / 4] >> (24 - 8 * (j & 3))); - - #endif - } - - _hmac.SetKey(buf + keySize, keySize); - memcpy(_key.PwdVerifComputed, buf + 2 * keySize, kPwdVerifCodeSize); - - _blockPos = AES_BLOCK_SIZE; - for (int i = 0; i < 4; i++) - _counter[i] = 0; - - Aes_SetKeyEncode(&Aes, buf, keySize); - return S_OK; -} - -/* -STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream) -{ - Byte keySizeMode = 3; - return outStream->Write(&keySizeMode, 1, NULL); -} -*/ - -HRESULT CEncoder::WriteHeader(ISequentialOutStream *outStream) -{ - UInt32 saltSize = _key.GetSaltSize(); - g_RandomGenerator.Generate(_key.Salt, saltSize); - Init(); - RINOK(WriteStream(outStream, _key.Salt, saltSize)); - return WriteStream(outStream, _key.PwdVerifComputed, kPwdVerifCodeSize); -} - -HRESULT CEncoder::WriteFooter(ISequentialOutStream *outStream) -{ - Byte mac[kMacSize]; - _hmac.Final(mac, kMacSize); - return WriteStream(outStream, mac, kMacSize); -} - -STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *data, UInt32 size) -{ - if (size != 1) - return E_INVALIDARG; - _key.Init(); - Byte keySizeMode = data[0]; - if (keySizeMode < 1 || keySizeMode > 3) - return E_INVALIDARG; - _key.KeySizeMode = keySizeMode; - return S_OK; -} - -HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream) -{ - UInt32 saltSize = _key.GetSaltSize(); - UInt32 extraSize = saltSize + kPwdVerifCodeSize; - Byte temp[kSaltSizeMax + kPwdVerifCodeSize]; - RINOK(ReadStream_FAIL(inStream, temp, extraSize)); - UInt32 i; - for (i = 0; i < saltSize; i++) - _key.Salt[i] = temp[i]; - for (i = 0; i < kPwdVerifCodeSize; i++) - _pwdVerifFromArchive[i] = temp[saltSize + i]; - return S_OK; -} - -static bool CompareArrays(const Byte *p1, const Byte *p2, UInt32 size) -{ - for (UInt32 i = 0; i < size; i++) - if (p1[i] != p2[i]) - return false; - return true; -} - -bool CDecoder::CheckPasswordVerifyCode() -{ - return CompareArrays(_key.PwdVerifComputed, _pwdVerifFromArchive, kPwdVerifCodeSize); -} - -HRESULT CDecoder::CheckMac(ISequentialInStream *inStream, bool &isOK) -{ - isOK = false; - Byte mac1[kMacSize]; - RINOK(ReadStream_FAIL(inStream, mac1, kMacSize)); - Byte mac2[kMacSize]; - _hmac.Final(mac2, kMacSize); - isOK = CompareArrays(mac1, mac2, kMacSize); - return S_OK; -} - -STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) -{ - EncryptData(data, size); - _hmac.Update(data, size); - return size; -} - -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) -{ - _hmac.Update(data, size); - EncryptData(data, size); - return size; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.h b/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.h deleted file mode 100644 index 8d68cc2f3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/WzAes.h +++ /dev/null @@ -1,119 +0,0 @@ -// Crypto/WzAes.h -/* -This code implements Brian Gladman's scheme -specified in password Based File Encryption Utility: - - AES encryption (128,192,256-bit) in Counter (CTR) mode. - - HMAC-SHA1 authentication for encrypted data (10 bytes) - - Keys are derived by PPKDF2(RFC2898)-HMAC-SHA1 from ASCII password and - Salt (saltSize = aesKeySize / 2). - - 2 bytes contain Password Verifier's Code -*/ - -#ifndef __CRYPTO_WZ_AES_H -#define __CRYPTO_WZ_AES_H - -extern "C" -{ -#include "../../../C/Aes.h" -} - -#include "Common/Buffer.h" -#include "Common/MyCom.h" -#include "Common/MyVector.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -#include "HmacSha1.h" - -namespace NCrypto { -namespace NWzAes { - -const unsigned int kSaltSizeMax = 16; -const unsigned int kMacSize = 10; - -const UInt32 kPasswordSizeMax = 99; // 128; - -// Password Verification Code Size -const unsigned int kPwdVerifCodeSize = 2; - -class CKeyInfo -{ -public: - Byte KeySizeMode; // 1 - 128-bit , 2 - 192-bit , 3 - 256-bit - Byte Salt[kSaltSizeMax]; - Byte PwdVerifComputed[kPwdVerifCodeSize]; - - CByteBuffer Password; - - UInt32 GetKeySize() const { return (8 * (KeySizeMode & 3) + 8); } - UInt32 GetSaltSize() const { return (4 * (KeySizeMode & 3) + 4); } - - CKeyInfo() { Init(); } - void Init() { KeySizeMode = 3; } -}; - -class CBaseCoder: - public ICompressFilter, - public ICryptoSetPassword, - public CMyUnknownImp -{ -protected: - CKeyInfo _key; - UInt32 _counter[AES_BLOCK_SIZE / 4]; - Byte _buffer[AES_BLOCK_SIZE]; - NSha1::CHmac _hmac; - unsigned int _blockPos; - Byte _pwdVerifFromArchive[kPwdVerifCodeSize]; - - void EncryptData(Byte *data, UInt32 size); - - CAes Aes; - -public: - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size) = 0; - - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - - UInt32 GetHeaderSize() const { return _key.GetSaltSize() + kPwdVerifCodeSize; } -}; - -class CEncoder: - public CBaseCoder - // public ICompressWriteCoderProperties -{ -public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) - // ICompressWriteCoderProperties - // STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - HRESULT WriteHeader(ISequentialOutStream *outStream); - HRESULT WriteFooter(ISequentialOutStream *outStream); - bool SetKeyMode(Byte mode) - { - if (mode < 1 || mode > 3) - return false; - _key.KeySizeMode = mode; - return true; - } -}; - -class CDecoder: - public CBaseCoder, - public ICompressSetDecoderProperties2 -{ -public: - MY_UNKNOWN_IMP2( - ICryptoSetPassword, - ICompressSetDecoderProperties2) - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); - HRESULT ReadHeader(ISequentialInStream *inStream); - bool CheckPasswordVerifyCode(); - HRESULT CheckMac(ISequentialInStream *inStream, bool &isOK); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.cpp deleted file mode 100644 index b699d8950..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.cpp +++ /dev/null @@ -1,131 +0,0 @@ -// Crypto/ZipCrypto.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/7zCrc.h" -} - -#include "../Common/StreamUtils.h" - -#include "RandGen.h" -#include "ZipCrypto.h" - -namespace NCrypto { -namespace NZip { - -void CCipher::UpdateKeys(Byte b) -{ - Keys[0] = CRC_UPDATE_BYTE(Keys[0], b); - Keys[1] += Keys[0] & 0xff; - Keys[1] = Keys[1] * 134775813L + 1; - Keys[2] = CRC_UPDATE_BYTE(Keys[2], (Byte)(Keys[1] >> 24)); -} - -void CCipher::SetPassword(const Byte *password, UInt32 passwordLen) -{ - Keys[0] = 305419896L; - Keys[1] = 591751049L; - Keys[2] = 878082192L; - for (UInt32 i = 0; i < passwordLen; i++) - UpdateKeys(password[i]); -} - -Byte CCipher::DecryptByteSpec() -{ - UInt32 temp = Keys[2] | 2; - return (Byte)((temp * (temp ^ 1)) >> 8); -} - -Byte CCipher::DecryptByte(Byte b) -{ - Byte c = (Byte)(b ^ DecryptByteSpec()); - UpdateKeys(c); - return c; -} - -Byte CCipher::EncryptByte(Byte b) -{ - Byte c = (Byte)(b ^ DecryptByteSpec()); - UpdateKeys(b); - return c; -} - -void CCipher::DecryptHeader(Byte *buf) -{ - for (unsigned i = 0; i < kHeaderSize; i++) - buf[i] = DecryptByte(buf[i]); -} - -void CCipher::EncryptHeader(Byte *buf) -{ - for (unsigned i = 0; i < kHeaderSize; i++) - buf[i] = EncryptByte(buf[i]); -} - -STDMETHODIMP CEncoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - _cipher.SetPassword(data, size); - return S_OK; -} - -STDMETHODIMP CEncoder::CryptoSetCRC(UInt32 crc) -{ - _crc = crc; - return S_OK; -} - -STDMETHODIMP CEncoder::Init() -{ - return S_OK; -} - -HRESULT CEncoder::WriteHeader(ISequentialOutStream *outStream) -{ - Byte header[kHeaderSize]; - g_RandomGenerator.Generate(header, kHeaderSize - 2); - - header[kHeaderSize - 1] = Byte(_crc >> 24); - header[kHeaderSize - 2] = Byte(_crc >> 16); - - _cipher.EncryptHeader(header); - return WriteStream(outStream, header, kHeaderSize); -} - -STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size) -{ - UInt32 i; - for (i = 0; i < size; i++) - data[i] = _cipher.EncryptByte(data[i]); - return i; -} - -STDMETHODIMP CDecoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - _cipher.SetPassword(data, size); - return S_OK; -} - -HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream) -{ - Byte header[kHeaderSize]; - RINOK(ReadStream_FAIL(inStream, header, kHeaderSize)); - _cipher.DecryptHeader(header); - return S_OK; -} - -STDMETHODIMP CDecoder::Init() -{ - return S_OK; -} - -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) -{ - UInt32 i; - for (i = 0; i < size; i++) - data[i] = _cipher.DecryptByte(data[i]); - return i; -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.h b/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.h deleted file mode 100644 index 2f8f335ae..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipCrypto.h +++ /dev/null @@ -1,71 +0,0 @@ -// Crypto/ZipCrypto.h - -#ifndef __CRYPTO_ZIP_CRYPTO_H -#define __CRYPTO_ZIP_CRYPTO_H - -#include "Common/MyCom.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -namespace NCrypto { -namespace NZip { - -const unsigned kHeaderSize = 12; - -class CCipher -{ - UInt32 Keys[3]; - - void UpdateKeys(Byte b); - Byte DecryptByteSpec(); -public: - void SetPassword(const Byte *password, UInt32 passwordLen); - Byte DecryptByte(Byte b); - Byte EncryptByte(Byte b); - void DecryptHeader(Byte *buf); - void EncryptHeader(Byte *buf); -}; - -class CEncoder : - public ICompressFilter, - public ICryptoSetPassword, - public ICryptoSetCRC, - public CMyUnknownImp -{ - CCipher _cipher; - UInt32 _crc; -public: - MY_UNKNOWN_IMP2( - ICryptoSetPassword, - ICryptoSetCRC - ) - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - STDMETHOD(CryptoSetCRC)(UInt32 crc); - HRESULT WriteHeader(ISequentialOutStream *outStream); -}; - - -class CDecoder: - public ICompressFilter, - public ICryptoSetPassword, - public CMyUnknownImp -{ - CCipher _cipher; -public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) - - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); - - HRESULT ReadHeader(ISequentialInStream *inStream); -}; - - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.cpp b/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.cpp deleted file mode 100644 index 2302450f5..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.cpp +++ /dev/null @@ -1,180 +0,0 @@ -// Crypto/ZipStrong.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../../C/7zCrc.h" -#include "../../../C/CpuArch.h" -} - -#include "../Common/StreamUtils.h" - -#include "MyAES.h" -#include "Sha1.h" -#include "ZipStrong.h" - -namespace NCrypto { -namespace NZipStrong { - -static const UInt16 kAES128 = 0x660E; - -// DeriveKey* function is similar to CryptDeriveKey() from Windows. -// But MSDN tells that we need such scheme only if -// "the required key length is longer than the hash value" -// but ZipStrong uses it always. - -static void DeriveKey2(const Byte *digest, Byte c, Byte *dest) -{ - Byte buf[64]; - memset(buf, c, 64); - for (unsigned i = 0; i < NSha1::kDigestSize; i++) - buf[i] ^= digest[i]; - NSha1::CContext sha; - sha.Init(); - sha.Update(buf, 64); - sha.Final(dest); -} - -static void DeriveKey(NSha1::CContext &sha, Byte *key) -{ - Byte digest[NSha1::kDigestSize]; - sha.Final(digest); - Byte temp[NSha1::kDigestSize * 2]; - DeriveKey2(digest, 0x36, temp); - DeriveKey2(digest, 0x5C, temp + NSha1::kDigestSize); - memcpy(key, temp, 32); -} - -void CKeyInfo::SetPassword(const Byte *data, UInt32 size) -{ - NSha1::CContext sha; - sha.Init(); - sha.Update(data, size); - DeriveKey(sha, MasterKey); -} - -STDMETHODIMP CBaseCoder::CryptoSetPassword(const Byte *data, UInt32 size) -{ - _key.SetPassword(data, size); - return S_OK; -} - -STDMETHODIMP CBaseCoder::Init() -{ - return S_OK; -} - -HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream, UInt32 /* crc */, UInt64 /* unpackSize */) -{ - Byte temp[4]; - RINOK(ReadStream_FALSE(inStream, temp, 2)); - _ivSize = GetUi16(temp); - if (_ivSize == 0) - { - return E_NOTIMPL; - /* - SetUi32(_iv, crc); - for (int i = 0; i < 8; i++) - _iv[4 + i] = (Byte)(unpackSize >> (8 * i)); - SetUi32(_iv + 12, 0); - */ - } - else if (_ivSize == 16) - { - RINOK(ReadStream_FALSE(inStream, _iv, _ivSize)); - } - else - return E_NOTIMPL; - RINOK(ReadStream_FALSE(inStream, temp, 4)); - _remSize = GetUi32(temp); - if (_remSize > _buf.GetCapacity()) - { - _buf.Free(); - _buf.SetCapacity(_remSize); - } - return ReadStream_FALSE(inStream, _buf, _remSize); -} - -HRESULT CDecoder::CheckPassword(bool &passwOK) -{ - passwOK = false; - if (_remSize < 10) - return E_NOTIMPL; - Byte *p = _buf; - UInt16 format = GetUi16(p); - if (format != 3) - return E_NOTIMPL; - UInt16 algId = GetUi16(p + 2); - if (algId < kAES128) - return E_NOTIMPL; - algId -= kAES128; - if (algId > 2) - return E_NOTIMPL; - UInt16 bitLen = GetUi16(p + 4); - UInt16 flags = GetUi16(p + 6); - if (algId * 64 + 128 != bitLen) - return E_NOTIMPL; - _key.KeySize = 16 + algId * 8; - if ((flags & 1) == 0) - return E_NOTIMPL; - UInt32 rdSize = GetUi16(p + 8); - UInt32 pos = 10; - Byte *rd = p + pos; - pos += rdSize; - if (pos + 4 > _remSize) - return E_NOTIMPL; - UInt32 reserved = GetUi32(p + pos); - pos += 4; - if (reserved != 0) - return E_NOTIMPL; - if (pos + 2 > _remSize) - return E_NOTIMPL; - UInt32 validSize = GetUi16(p + pos); - pos += 2; - Byte *validData = p + pos; - if (pos + validSize != _remSize) - return E_NOTIMPL; - - if (!_aesFilter) - _aesFilter = new CAesCbcDecoder; - - CMyComPtr cp; - RINOK(_aesFilter.QueryInterface(IID_ICryptoProperties, &cp)); - { - RINOK(cp->SetKey(_key.MasterKey, _key.KeySize)); - RINOK(cp->SetInitVector(_iv, 16)); - _aesFilter->Init(); - if (_aesFilter->Filter(rd, rdSize) != rdSize) - return E_NOTIMPL; - } - - Byte fileKey[32]; - NSha1::CContext sha; - sha.Init(); - sha.Update(_iv, 16); - sha.Update(rd, rdSize - 16); // we don't use last 16 bytes (PAD bytes) - DeriveKey(sha, fileKey); - - RINOK(cp->SetKey(fileKey, _key.KeySize)); - RINOK(cp->SetInitVector(_iv, 16)); - _aesFilter->Init(); - if (_aesFilter->Filter(validData, validSize) != validSize) - return E_NOTIMPL; - - if (validSize < 4) - return E_NOTIMPL; - validSize -= 4; - if (GetUi32(validData + validSize) != CrcCalc(validData, validSize)) - return S_OK; - passwOK = true; - _aesFilter->Init(); - return S_OK; -} - -STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size) -{ - return _aesFilter->Filter(data, size); -} - -}} diff --git a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.h b/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.h deleted file mode 100644 index 33adbaa2a..000000000 --- a/desmume/src/windows/7z/CPP/7zip/Crypto/ZipStrong.h +++ /dev/null @@ -1,53 +0,0 @@ -// Crypto/ZipStrong.h - -#ifndef __CRYPTO_ZIP_STRONG_H -#define __CRYPTO_ZIP_STRONG_H - -#include "Common/MyCom.h" -#include "Common/Buffer.h" - -#include "../ICoder.h" -#include "../IPassword.h" - -namespace NCrypto { -namespace NZipStrong { - -struct CKeyInfo -{ - Byte MasterKey[32]; - UInt32 KeySize; - void SetPassword(const Byte *data, UInt32 size); -}; - -class CBaseCoder: - public ICompressFilter, - public ICryptoSetPassword, - public CMyUnknownImp -{ -protected: - CKeyInfo _key; - CMyComPtr _aesFilter; - CByteBuffer _buf; -public: - STDMETHOD(Init)(); - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size) = 0; - - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size); -}; - -class CDecoder: - public CBaseCoder -{ - UInt32 _ivSize; - Byte _iv[16]; - UInt32 _remSize; -public: - MY_UNKNOWN_IMP1(ICryptoSetPassword) - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size); - HRESULT ReadHeader(ISequentialInStream *inStream, UInt32 crc, UInt64 unpackSize); - HRESULT CheckPassword(bool &passwOK); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/ICoder.h b/desmume/src/windows/7z/CPP/7zip/ICoder.h deleted file mode 100644 index 150118c2c..000000000 --- a/desmume/src/windows/7z/CPP/7zip/ICoder.h +++ /dev/null @@ -1,186 +0,0 @@ -// ICoder.h - -#ifndef __ICODER_H -#define __ICODER_H - -#include "IStream.h" - -#define CODER_INTERFACE(i, x) DECL_INTERFACE(i, 4, x) - -CODER_INTERFACE(ICompressProgressInfo, 0x04) -{ - STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize) PURE; -}; - -CODER_INTERFACE(ICompressCoder, 0x05) -{ - STDMETHOD(Code)(ISequentialInStream *inStream, - ISequentialOutStream *outStream, - const UInt64 *inSize, - const UInt64 *outSize, - ICompressProgressInfo *progress) PURE; -}; - -CODER_INTERFACE(ICompressCoder2, 0x18) -{ - STDMETHOD(Code)(ISequentialInStream **inStreams, - const UInt64 **inSizes, - UInt32 numInStreams, - ISequentialOutStream **outStreams, - const UInt64 **outSizes, - UInt32 numOutStreams, - ICompressProgressInfo *progress) PURE; -}; - -namespace NCoderPropID -{ - enum EEnum - { - kDictionarySize = 0x400, - kUsedMemorySize, - kOrder, - kBlockSize, - kPosStateBits = 0x440, - kLitContextBits, - kLitPosBits, - kNumFastBytes = 0x450, - kMatchFinder, - kMatchFinderCycles, - kNumPasses = 0x460, - kAlgorithm = 0x470, - kMultiThread = 0x480, - kNumThreads, - kEndMarker = 0x490 - }; -} - -CODER_INTERFACE(ICompressSetCoderProperties, 0x20) -{ - STDMETHOD(SetCoderProperties)(const PROPID *propIDs, - const PROPVARIANT *properties, UInt32 numProperties) PURE; -}; - -/* -CODER_INTERFACE(ICompressSetCoderProperties, 0x21) -{ - STDMETHOD(SetDecoderProperties)(ISequentialInStream *inStream) PURE; -}; -*/ - -CODER_INTERFACE(ICompressSetDecoderProperties2, 0x22) -{ - STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size) PURE; -}; - -CODER_INTERFACE(ICompressWriteCoderProperties, 0x23) -{ - STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStreams) PURE; -}; - -CODER_INTERFACE(ICompressGetInStreamProcessedSize, 0x24) -{ - STDMETHOD(GetInStreamProcessedSize)(UInt64 *value) PURE; -}; - -CODER_INTERFACE(ICompressSetCoderMt, 0x25) -{ - STDMETHOD(SetNumberOfThreads)(UInt32 numThreads) PURE; -}; - -CODER_INTERFACE(ICompressGetSubStreamSize, 0x30) -{ - STDMETHOD(GetSubStreamSize)(UInt64 subStream, UInt64 *value) PURE; -}; - -CODER_INTERFACE(ICompressSetInStream, 0x31) -{ - STDMETHOD(SetInStream)(ISequentialInStream *inStream) PURE; - STDMETHOD(ReleaseInStream)() PURE; -}; - -CODER_INTERFACE(ICompressSetOutStream, 0x32) -{ - STDMETHOD(SetOutStream)(ISequentialOutStream *outStream) PURE; - STDMETHOD(ReleaseOutStream)() PURE; -}; - -CODER_INTERFACE(ICompressSetInStreamSize, 0x33) -{ - STDMETHOD(SetInStreamSize)(const UInt64 *inSize) PURE; -}; - -CODER_INTERFACE(ICompressSetOutStreamSize, 0x34) -{ - STDMETHOD(SetOutStreamSize)(const UInt64 *outSize) PURE; -}; - -CODER_INTERFACE(ICompressFilter, 0x40) -{ - STDMETHOD(Init)() PURE; - STDMETHOD_(UInt32, Filter)(Byte *data, UInt32 size) PURE; - // Filter return outSize (UInt32) - // if (outSize <= size): Filter have converted outSize bytes - // if (outSize > size): Filter have not converted anything. - // and it needs at least outSize bytes to convert one block - // (it's for crypto block algorithms). -}; - -CODER_INTERFACE(ICompressCodecsInfo, 0x60) -{ - STDMETHOD(GetNumberOfMethods)(UInt32 *numMethods) PURE; - STDMETHOD(GetProperty)(UInt32 index, PROPID propID, PROPVARIANT *value) PURE; - STDMETHOD(CreateDecoder)(UInt32 index, const GUID *iid, void **coder) PURE; - STDMETHOD(CreateEncoder)(UInt32 index, const GUID *iid, void **coder) PURE; -}; -CODER_INTERFACE(ISetCompressCodecsInfo, 0x61) -{ - STDMETHOD(SetCompressCodecsInfo)(ICompressCodecsInfo *compressCodecsInfo) PURE; -}; - -CODER_INTERFACE(ICryptoProperties, 0x80) -{ - STDMETHOD(SetKey)(const Byte *data, UInt32 size) PURE; - STDMETHOD(SetInitVector)(const Byte *data, UInt32 size) PURE; -}; - -/* -CODER_INTERFACE(ICryptoResetSalt, 0x88) -{ - STDMETHOD(ResetSalt)() PURE; -}; -*/ - -CODER_INTERFACE(ICryptoResetInitVector, 0x8C) -{ - STDMETHOD(ResetInitVector)() PURE; -}; - -CODER_INTERFACE(ICryptoSetPassword, 0x90) -{ - STDMETHOD(CryptoSetPassword)(const Byte *data, UInt32 size) PURE; -}; - -CODER_INTERFACE(ICryptoSetCRC, 0xA0) -{ - STDMETHOD(CryptoSetCRC)(UInt32 crc) PURE; -}; - -////////////////////// -// It's for DLL file -namespace NMethodPropID -{ - enum EEnum - { - kID, - kName, - kDecoder, - kEncoder, - kInStreams, - kOutStreams, - kDescription, - kDecoderIsAssigned, - kEncoderIsAssigned - }; -} - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/IDecl.h b/desmume/src/windows/7z/CPP/7zip/IDecl.h deleted file mode 100644 index 768bbe710..000000000 --- a/desmume/src/windows/7z/CPP/7zip/IDecl.h +++ /dev/null @@ -1,15 +0,0 @@ -// IDecl.h - -#ifndef __IDECL_H -#define __IDECL_H - -#include "../Common/MyUnknown.h" - -#define DECL_INTERFACE_SUB(i, base, groupId, subId) \ -DEFINE_GUID(IID_ ## i, \ -0x23170F69, 0x40C1, 0x278A, 0, 0, 0, (groupId), 0, (subId), 0, 0); \ -struct i: public base - -#define DECL_INTERFACE(i, groupId, subId) DECL_INTERFACE_SUB(i, IUnknown, groupId, subId) - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/IPassword.h b/desmume/src/windows/7z/CPP/7zip/IPassword.h deleted file mode 100644 index 5679d84ce..000000000 --- a/desmume/src/windows/7z/CPP/7zip/IPassword.h +++ /dev/null @@ -1,24 +0,0 @@ -// IPassword.h - -#ifndef __IPASSWORD_H -#define __IPASSWORD_H - -#include "../Common/MyUnknown.h" -#include "../Common/Types.h" - -#include "IDecl.h" - -#define PASSWORD_INTERFACE(i, x) DECL_INTERFACE(i, 5, x) - -PASSWORD_INTERFACE(ICryptoGetTextPassword, 0x10) -{ - STDMETHOD(CryptoGetTextPassword)(BSTR *password) PURE; -}; - -PASSWORD_INTERFACE(ICryptoGetTextPassword2, 0x11) -{ - STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password) PURE; -}; - -#endif - diff --git a/desmume/src/windows/7z/CPP/7zip/IProgress.h b/desmume/src/windows/7z/CPP/7zip/IProgress.h deleted file mode 100644 index 09486baf3..000000000 --- a/desmume/src/windows/7z/CPP/7zip/IProgress.h +++ /dev/null @@ -1,33 +0,0 @@ -// Interface/IProgress.h - -#ifndef __IPROGRESS_H -#define __IPROGRESS_H - -#include "../Common/MyUnknown.h" -#include "../Common/Types.h" - -#include "IDecl.h" - -#define INTERFACE_IProgress(x) \ - STDMETHOD(SetTotal)(UInt64 total) x; \ - STDMETHOD(SetCompleted)(const UInt64 *completeValue) x; \ - -DECL_INTERFACE(IProgress, 0, 5) -{ - INTERFACE_IProgress(PURE) -}; - -/* -// {23170F69-40C1-278A-0000-000000050002} -DEFINE_GUID(IID_IProgress2, -0x23170F69, 0x40C1, 0x278A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x02); -MIDL_INTERFACE("23170F69-40C1-278A-0000-000000050002") -IProgress2: public IUnknown -{ -public: - STDMETHOD(SetTotal)(const UInt64 *total) PURE; - STDMETHOD(SetCompleted)(const UInt64 *completeValue) PURE; -}; -*/ - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/IStream.h b/desmume/src/windows/7z/CPP/7zip/IStream.h deleted file mode 100644 index d5ed723fe..000000000 --- a/desmume/src/windows/7z/CPP/7zip/IStream.h +++ /dev/null @@ -1,58 +0,0 @@ -// IStream.h - -#ifndef __ISTREAM_H -#define __ISTREAM_H - -#include "../Common/MyUnknown.h" -#include "../Common/Types.h" - -#include "IDecl.h" - -#define STREAM_INTERFACE_SUB(i, base, x) DECL_INTERFACE_SUB(i, base, 3, x) -#define STREAM_INTERFACE(i, x) STREAM_INTERFACE_SUB(i, IUnknown, x) - -STREAM_INTERFACE(ISequentialInStream, 0x01) -{ - STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize) PURE; - /* - Out: if size != 0, return_value = S_OK and (*processedSize == 0), - then there are no more bytes in stream. - if (size > 0) && there are bytes in stream, - this function must read at least 1 byte. - This function is allowed to read less than number of remaining bytes in stream. - You must call Read function in loop, if you need exact amount of data - */ -}; - -STREAM_INTERFACE(ISequentialOutStream, 0x02) -{ - STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize) PURE; - /* - if (size > 0) this function must write at least 1 byte. - This function is allowed to write less than "size". - You must call Write function in loop, if you need to write exact amount of data - */ -}; - -STREAM_INTERFACE_SUB(IInStream, ISequentialInStream, 0x03) -{ - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) PURE; -}; - -STREAM_INTERFACE_SUB(IOutStream, ISequentialOutStream, 0x04) -{ - STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition) PURE; - STDMETHOD(SetSize)(Int64 newSize) PURE; -}; - -STREAM_INTERFACE(IStreamGetSize, 0x06) -{ - STDMETHOD(GetSize)(UInt64 *size) PURE; -}; - -STREAM_INTERFACE(IOutStreamFlush, 0x07) -{ - STDMETHOD(Flush)() PURE; -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/7zip/PropID.h b/desmume/src/windows/7z/CPP/7zip/PropID.h deleted file mode 100644 index 695f80295..000000000 --- a/desmume/src/windows/7z/CPP/7zip/PropID.h +++ /dev/null @@ -1,69 +0,0 @@ -// PropID.h - -#ifndef __7ZIP_PROPID_H -#define __7ZIP_PROPID_H - -enum -{ - kpidNoProperty = 0, - - kpidHandlerItemIndex = 2, - kpidPath, - kpidName, - kpidExtension, - kpidIsDir, - kpidSize, - kpidPackSize, - kpidAttrib, - kpidCTime, - kpidATime, - kpidMTime, - kpidSolid, - kpidCommented, - kpidEncrypted, - kpidSplitBefore, - kpidSplitAfter, - kpidDictionarySize, - kpidCRC, - kpidType, - kpidIsAnti, - kpidMethod, - kpidHostOS, - kpidFileSystem, - kpidUser, - kpidGroup, - kpidBlock, - kpidComment, - kpidPosition, - kpidPrefix, - kpidNumSubDirs, - kpidNumSubFiles, - kpidUnpackVer, - kpidVolume, - kpidIsVolume, - kpidOffset, - kpidLinks, - kpidNumBlocks, - kpidNumVolumes, - kpidTimeType, - kpidBit64, - kpidBigEndian, - kpidCpu, - kpidPhySize, - kpidHeadersSize, - kpidChecksum, - kpidCharacts, - kpidVa, - - kpidTotalSize = 0x1100, - kpidFreeSpace, - kpidClusterSize, - kpidVolumeName, - - kpidLocalName = 0x1200, - kpidProvider, - - kpidUserDefined = 0x10000 -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/Buffer.h b/desmume/src/windows/7z/CPP/Common/Buffer.h deleted file mode 100644 index b0959eddb..000000000 --- a/desmume/src/windows/7z/CPP/Common/Buffer.h +++ /dev/null @@ -1,77 +0,0 @@ -// Common/Buffer.h - -#ifndef __COMMON_BUFFER_H -#define __COMMON_BUFFER_H - -#include "Defs.h" - -template class CBuffer -{ -protected: - size_t _capacity; - T *_items; -public: - void Free() - { - delete []_items; - _items = 0; - _capacity = 0; - } - CBuffer(): _capacity(0), _items(0) {}; - CBuffer(const CBuffer &buffer): _capacity(0), _items(0) { *this = buffer; } - CBuffer(size_t size): _items(0), _capacity(0) { SetCapacity(size); } - virtual ~CBuffer() { delete []_items; } - operator T *() { return _items; }; - operator const T *() const { return _items; }; - size_t GetCapacity() const { return _capacity; } - void SetCapacity(size_t newCapacity) - { - if (newCapacity == _capacity) - return; - T *newBuffer; - if (newCapacity > 0) - { - newBuffer = new T[newCapacity]; - if (_capacity > 0) - memmove(newBuffer, _items, MyMin(_capacity, newCapacity) * sizeof(T)); - } - else - newBuffer = 0; - delete []_items; - _items = newBuffer; - _capacity = newCapacity; - } - CBuffer& operator=(const CBuffer &buffer) - { - Free(); - if (buffer._capacity > 0) - { - SetCapacity(buffer._capacity); - memmove(_items, buffer._items, buffer._capacity * sizeof(T)); - } - return *this; - } -}; - -template -bool operator==(const CBuffer& b1, const CBuffer& b2) -{ - if (b1.GetCapacity() != b2.GetCapacity()) - return false; - for (size_t i = 0; i < b1.GetCapacity(); i++) - if (b1[i] != b2[i]) - return false; - return true; -} - -template -bool operator!=(const CBuffer& b1, const CBuffer& b2) -{ - return !(b1 == b2); -} - -typedef CBuffer CCharBuffer; -typedef CBuffer CWCharBuffer; -typedef CBuffer CByteBuffer; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/CRC.cpp b/desmume/src/windows/7z/CPP/Common/CRC.cpp deleted file mode 100644 index 987b8a03a..000000000 --- a/desmume/src/windows/7z/CPP/Common/CRC.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Common/CRC.cpp - -#include "StdAfx.h" - -extern "C" -{ -#include "../../C/7zCrc.h" -} - -struct CCRCTableInit { CCRCTableInit() { CrcGenerateTable(); } } g_CRCTableInit; diff --git a/desmume/src/windows/7z/CPP/Common/ComTry.h b/desmume/src/windows/7z/CPP/Common/ComTry.h deleted file mode 100644 index 98e592766..000000000 --- a/desmume/src/windows/7z/CPP/Common/ComTry.h +++ /dev/null @@ -1,17 +0,0 @@ -// ComTry.h - -#ifndef __COM_TRY_H -#define __COM_TRY_H - -#include "MyWindows.h" -// #include "Exception.h" -// #include "NewHandler.h" - -#define COM_TRY_BEGIN try { -#define COM_TRY_END } catch(...) { return E_OUTOFMEMORY; } - - // catch(const CNewException &) { return E_OUTOFMEMORY; }\ - // catch(const CSystemException &e) { return e.ErrorCode; }\ - // catch(...) { return E_FAIL; } - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/Defs.h b/desmume/src/windows/7z/CPP/Common/Defs.h deleted file mode 100644 index 69b8ecea8..000000000 --- a/desmume/src/windows/7z/CPP/Common/Defs.h +++ /dev/null @@ -1,20 +0,0 @@ -// Common/Defs.h - -#ifndef __COMMON_DEFS_H -#define __COMMON_DEFS_H - -template inline T MyMin(T a, T b) - { return a < b ? a : b; } -template inline T MyMax(T a, T b) - { return a > b ? a : b; } - -template inline int MyCompare(T a, T b) - { return a < b ? -1 : (a == b ? 0 : 1); } - -inline int BoolToInt(bool value) - { return (value ? 1: 0); } - -inline bool IntToBool(int value) - { return (value != 0); } - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/DynamicBuffer.h b/desmume/src/windows/7z/CPP/Common/DynamicBuffer.h deleted file mode 100644 index 83ef0ea2c..000000000 --- a/desmume/src/windows/7z/CPP/Common/DynamicBuffer.h +++ /dev/null @@ -1,47 +0,0 @@ -// Common/DynamicBuffer.h - -#ifndef __COMMON_DYNAMICBUFFER_H -#define __COMMON_DYNAMICBUFFER_H - -#include "Buffer.h" - -template class CDynamicBuffer: public CBuffer -{ - void GrowLength(size_t size) - { - size_t delta; - if (this->_capacity > 64) - delta = this->_capacity / 4; - else if (this->_capacity > 8) - delta = 16; - else - delta = 4; - delta = MyMax(delta, size); - SetCapacity(this->_capacity + delta); - } -public: - CDynamicBuffer(): CBuffer() {}; - CDynamicBuffer(const CDynamicBuffer &buffer): CBuffer(buffer) {}; - CDynamicBuffer(size_t size): CBuffer(size) {}; - CDynamicBuffer& operator=(const CDynamicBuffer &buffer) - { - this->Free(); - if (buffer._capacity > 0) - { - SetCapacity(buffer._capacity); - memmove(this->_items, buffer._items, buffer._capacity * sizeof(T)); - } - return *this; - } - void EnsureCapacity(size_t capacity) - { - if (this->_capacity < capacity) - GrowLength(capacity - this->_capacity); - } -}; - -typedef CDynamicBuffer CCharDynamicBuffer; -typedef CDynamicBuffer CWCharDynamicBuffer; -typedef CDynamicBuffer CByteDynamicBuffer; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/InitializeStaticLib.h b/desmume/src/windows/7z/CPP/Common/InitializeStaticLib.h deleted file mode 100644 index a0d70b6fd..000000000 --- a/desmume/src/windows/7z/CPP/Common/InitializeStaticLib.h +++ /dev/null @@ -1,29 +0,0 @@ -// Common/InitializeStaticLib.h -// -// it's necessary to include this from one cpp file in order to use 7zip as a static library, -// otherwise the linker will optimize away some important internals of 7zip. - -#ifndef __COMMON_INITIALIZESTATICLIB_H -#define __COMMON_INITIALIZESTATICLIB_H - -#define FORCE_REF(dec, var) extern dec var; void* var##ref = (void*)&var; - -#include "../7zip/Common/DeclareCodecs.h" -#include "../7zip/Common/DeclareArcs.h" - -FORCE_REF(struct CCRCTableInit, g_CRCTableInit) - - -// these don't seem to be necessary with my compiler, -// but they're here in case a different compiler more aggressively strips out unreferenced code -FORCE_REF(class CBZip2CrcTableInit, g_BZip2CrcTableInit) -namespace NCrypto { struct CAesTabInit; FORCE_REF(CAesTabInit, g_AesTabInit) } -namespace NBitl { struct CInverterTableInitializer; FORCE_REF(CInverterTableInitializer, g_InverterTableInitializer) } -namespace NCompress { namespace NRar3 { class CDistInit; FORCE_REF(CDistInit, g_DistInit) }} -namespace NArchive { namespace NLzh { class CCRCTableInit; FORCE_REF(CCRCTableInit, g_CRCTableInit) }} -namespace NArchive { namespace N7z { class SignatureInitializer; FORCE_REF(SignatureInitializer, g_SignatureInitializer) }} -namespace NArchive{ namespace NRar{ namespace NHeader{ class CMarkerInitializer; FORCE_REF(CMarkerInitializer, g_MarkerInitializer) }}} -namespace NArchive { namespace NZip { namespace NSignature{ class CMarkersInitializer; FORCE_REF(CMarkersInitializer, g_MarkerInitializer) }}} - - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/IntToString.cpp b/desmume/src/windows/7z/CPP/Common/IntToString.cpp deleted file mode 100644 index f0a499d6b..000000000 --- a/desmume/src/windows/7z/CPP/Common/IntToString.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// Common/IntToString.cpp - -#include "StdAfx.h" - -#include "IntToString.h" - -void ConvertUInt64ToString(UInt64 value, char *s, UInt32 base) -{ - if (base < 2 || base > 36) - { - *s = '\0'; - return; - } - char temp[72]; - int pos = 0; - do - { - int delta = (int)(value % base); - temp[pos++] = (char)((delta < 10) ? ('0' + delta) : ('a' + (delta - 10))); - value /= base; - } - while (value != 0); - do - *s++ = temp[--pos]; - while (pos > 0); - *s = '\0'; -} - -void ConvertUInt64ToString(UInt64 value, wchar_t *s) -{ - wchar_t temp[32]; - int pos = 0; - do - { - temp[pos++] = (wchar_t)(L'0' + (int)(value % 10)); - value /= 10; - } - while (value != 0); - do - *s++ = temp[--pos]; - while (pos > 0); - *s = L'\0'; -} - -void ConvertInt64ToString(Int64 value, char *s) -{ - if (value < 0) - { - *s++ = '-'; - value = -value; - } - ConvertUInt64ToString(value, s); -} - -void ConvertInt64ToString(Int64 value, wchar_t *s) -{ - if (value < 0) - { - *s++ = L'-'; - value = -value; - } - ConvertUInt64ToString(value, s); -} diff --git a/desmume/src/windows/7z/CPP/Common/IntToString.h b/desmume/src/windows/7z/CPP/Common/IntToString.h deleted file mode 100644 index 2f50ba95a..000000000 --- a/desmume/src/windows/7z/CPP/Common/IntToString.h +++ /dev/null @@ -1,15 +0,0 @@ -// Common/IntToString.h - -#ifndef __COMMON_INTTOSTRING_H -#define __COMMON_INTTOSTRING_H - -#include -#include "Types.h" - -void ConvertUInt64ToString(UInt64 value, char *s, UInt32 base = 10); -void ConvertUInt64ToString(UInt64 value, wchar_t *s); - -void ConvertInt64ToString(Int64 value, char *s); -void ConvertInt64ToString(Int64 value, wchar_t *s); - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyCom.h b/desmume/src/windows/7z/CPP/Common/MyCom.h deleted file mode 100644 index d04fa4c3d..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyCom.h +++ /dev/null @@ -1,225 +0,0 @@ -// MyCom.h - -#ifndef __MYCOM_H -#define __MYCOM_H - -#include "MyWindows.h" - -#ifndef RINOK -#define RINOK(x) { HRESULT __result_ = (x); if (__result_ != S_OK) return __result_; } -#endif - -template -class CMyComPtr -{ - T* _p; -public: - // typedef T _PtrClass; - CMyComPtr() { _p = NULL;} - CMyComPtr(T* p) {if ((_p = p) != NULL) p->AddRef(); } - CMyComPtr(const CMyComPtr& lp) - { - if ((_p = lp._p) != NULL) - _p->AddRef(); - } - ~CMyComPtr() { if (_p) _p->Release(); } - void Release() { if (_p) { _p->Release(); _p = NULL; } } - operator T*() const { return (T*)_p; } - // T& operator*() const { return *_p; } - T** operator&() { return &_p; } - T* operator->() const { return _p; } - T* operator=(T* p) - { - if (p != 0) - p->AddRef(); - if (_p) - _p->Release(); - _p = p; - return p; - } - T* operator=(const CMyComPtr& lp) { return (*this = lp._p); } - bool operator!() const { return (_p == NULL); } - // bool operator==(T* pT) const { return _p == pT; } - // Compare two objects for equivalence - void Attach(T* p2) - { - Release(); - _p = p2; - } - T* Detach() - { - T* pt = _p; - _p = NULL; - return pt; - } - #ifdef _WIN32 - HRESULT CoCreateInstance(REFCLSID rclsid, REFIID iid, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL) - { - return ::CoCreateInstance(rclsid, pUnkOuter, dwClsContext, iid, (void**)&_p); - } - #endif - /* - HRESULT CoCreateInstance(LPCOLESTR szProgID, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL) - { - CLSID clsid; - HRESULT hr = CLSIDFromProgID(szProgID, &clsid); - ATLASSERT(_p == NULL); - if (SUCCEEDED(hr)) - hr = ::CoCreateInstance(clsid, pUnkOuter, dwClsContext, __uuidof(T), (void**)&_p); - return hr; - } - */ - template - HRESULT QueryInterface(REFGUID iid, Q** pp) const - { - return _p->QueryInterface(iid, (void**)pp); - } -}; - -////////////////////////////////////////////////////////// - -inline HRESULT StringToBstr(LPCOLESTR src, BSTR *bstr) -{ - *bstr = ::SysAllocString(src); - return (*bstr != 0) ? S_OK : E_OUTOFMEMORY; -} - -class CMyComBSTR -{ -public: - BSTR m_str; - CMyComBSTR(): m_str(NULL) {} - CMyComBSTR(LPCOLESTR src) { m_str = ::SysAllocString(src); } - // CMyComBSTR(int nSize) { m_str = ::SysAllocStringLen(NULL, nSize); } - // CMyComBSTR(int nSize, LPCOLESTR sz) { m_str = ::SysAllocStringLen(sz, nSize); } - CMyComBSTR(const CMyComBSTR& src) { m_str = src.MyCopy(); } - /* - CMyComBSTR(REFGUID src) - { - LPOLESTR szGuid; - StringFromCLSID(src, &szGuid); - m_str = ::SysAllocString(szGuid); - CoTaskMemFree(szGuid); - } - */ - ~CMyComBSTR() { ::SysFreeString(m_str); } - CMyComBSTR& operator=(const CMyComBSTR& src) - { - if (m_str != src.m_str) - { - if (m_str) - ::SysFreeString(m_str); - m_str = src.MyCopy(); - } - return *this; - } - CMyComBSTR& operator=(LPCOLESTR src) - { - ::SysFreeString(m_str); - m_str = ::SysAllocString(src); - return *this; - } - unsigned int Length() const { return ::SysStringLen(m_str); } - operator BSTR() const { return m_str; } - BSTR* operator&() { return &m_str; } - BSTR MyCopy() const - { - int byteLen = ::SysStringByteLen(m_str); - BSTR res = ::SysAllocStringByteLen(NULL, byteLen); - memcpy(res, m_str, byteLen); - return res; - } - /* - void Attach(BSTR src) { m_str = src; } - BSTR Detach() - { - BSTR s = m_str; - m_str = NULL; - return s; - } - */ - void Empty() - { - ::SysFreeString(m_str); - m_str = NULL; - } - bool operator!() const { return (m_str == NULL); } -}; - -////////////////////////////////////////////////////////// - -class CMyUnknownImp -{ -public: - ULONG __m_RefCount; - CMyUnknownImp(): __m_RefCount(0) {} -}; - -#define MY_QUERYINTERFACE_BEGIN STDMETHOD(QueryInterface) \ - (REFGUID iid, void **outObject) { - -#define MY_QUERYINTERFACE_ENTRY(i) if (iid == IID_ ## i) \ - { *outObject = (void *)(i *)this; AddRef(); return S_OK; } - -#define MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) if (iid == IID_IUnknown) \ - { *outObject = (void *)(IUnknown *)(i *)this; AddRef(); return S_OK; } - -#define MY_QUERYINTERFACE_BEGIN2(i) MY_QUERYINTERFACE_BEGIN \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) \ - MY_QUERYINTERFACE_ENTRY(i) - -#define MY_QUERYINTERFACE_END return E_NOINTERFACE; } - -#define MY_ADDREF_RELEASE \ -STDMETHOD_(ULONG, AddRef)() { return ++__m_RefCount; } \ -STDMETHOD_(ULONG, Release)() { if (--__m_RefCount != 0) \ - return __m_RefCount; delete this; return 0; } - -#define MY_UNKNOWN_IMP_SPEC(i) \ - MY_QUERYINTERFACE_BEGIN \ - i \ - MY_QUERYINTERFACE_END \ - MY_ADDREF_RELEASE - - -#define MY_UNKNOWN_IMP MY_QUERYINTERFACE_BEGIN \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(IUnknown) \ - MY_QUERYINTERFACE_END \ - MY_ADDREF_RELEASE - -#define MY_UNKNOWN_IMP1(i) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i) \ - MY_QUERYINTERFACE_ENTRY(i) \ - ) - -#define MY_UNKNOWN_IMP2(i1, i2) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - ) - -#define MY_UNKNOWN_IMP3(i1, i2, i3) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ - ) - -#define MY_UNKNOWN_IMP4(i1, i2, i3, i4) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ - MY_QUERYINTERFACE_ENTRY(i4) \ - ) - -#define MY_UNKNOWN_IMP5(i1, i2, i3, i4, i5) MY_UNKNOWN_IMP_SPEC( \ - MY_QUERYINTERFACE_ENTRY_UNKNOWN(i1) \ - MY_QUERYINTERFACE_ENTRY(i1) \ - MY_QUERYINTERFACE_ENTRY(i2) \ - MY_QUERYINTERFACE_ENTRY(i3) \ - MY_QUERYINTERFACE_ENTRY(i4) \ - MY_QUERYINTERFACE_ENTRY(i5) \ - ) - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyException.h b/desmume/src/windows/7z/CPP/Common/MyException.h deleted file mode 100644 index cd9fe6948..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyException.h +++ /dev/null @@ -1,14 +0,0 @@ -// Common/Exception.h - -#ifndef __COMMON_EXCEPTION_H -#define __COMMON_EXCEPTION_H - -#include "MyWindows.h" - -struct CSystemException -{ - HRESULT ErrorCode; - CSystemException(HRESULT errorCode): ErrorCode(errorCode) {} -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyInitGuid.h b/desmume/src/windows/7z/CPP/Common/MyInitGuid.h deleted file mode 100644 index b1e70d868..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyInitGuid.h +++ /dev/null @@ -1,15 +0,0 @@ -// Common/MyInitGuid.h - -#ifndef __COMMON_MYINITGUID_H -#define __COMMON_MYINITGUID_H - -#ifdef _WIN32 -#include -#else -#define INITGUID -#include "MyGuidDef.h" -DEFINE_GUID(IID_IUnknown, -0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); -#endif - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyMap.cpp b/desmume/src/windows/7z/CPP/Common/MyMap.cpp deleted file mode 100644 index a69c61a04..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyMap.cpp +++ /dev/null @@ -1,140 +0,0 @@ -// MyMap.cpp - -#include "StdAfx.h" - -#include "MyMap.h" - -static const unsigned kNumBitsMax = sizeof(UInt32) * 8; - -static UInt32 GetSubBits(UInt32 value, unsigned startPos, unsigned numBits) -{ - if (startPos == sizeof(value) * 8) - return 0; - value >>= startPos; - if (numBits == sizeof(value) * 8) - return value; - return value & (((UInt32)1 << numBits) - 1); -} - -static inline unsigned GetSubBit(UInt32 v, unsigned n) { return (unsigned)(v >> n) & 1; } - -bool CMap32::Find(UInt32 key, UInt32 &valueRes) const -{ - valueRes = (UInt32)(Int32)-1; - if (Nodes.Size() == 0) - return false; - if (Nodes.Size() == 1) - { - const CNode &n = Nodes[0]; - if (n.Len == kNumBitsMax) - { - valueRes = n.Values[0]; - return (key == n.Key); - } - } - - int cur = 0; - unsigned bitPos = kNumBitsMax; - for (;;) - { - const CNode &n = Nodes[cur]; - bitPos -= n.Len; - if (GetSubBits(key, bitPos, n.Len) != GetSubBits(n.Key, bitPos, n.Len)) - return false; - unsigned bit = GetSubBit(key, --bitPos); - if (n.IsLeaf[bit]) - { - valueRes = n.Values[bit]; - return (key == n.Keys[bit]); - } - cur = (int)n.Keys[bit]; - } -} - -bool CMap32::Set(UInt32 key, UInt32 value) -{ - if (Nodes.Size() == 0) - { - CNode n; - n.Key = n.Keys[0] = n.Keys[1] = key; - n.Values[0] = n.Values[1] = value; - n.IsLeaf[0] = n.IsLeaf[1] = 1; - n.Len = kNumBitsMax; - Nodes.Add(n); - return false; - } - if (Nodes.Size() == 1) - { - CNode &n = Nodes[0]; - if (n.Len == kNumBitsMax) - { - if (key == n.Key) - { - n.Values[0] = n.Values[1] = value; - return true; - } - unsigned i = kNumBitsMax - 1; - for (;GetSubBit(key, i) == GetSubBit(n.Key, i); i--); - n.Len = (UInt16)(kNumBitsMax - (1 + i)); - unsigned newBit = GetSubBit(key, i); - n.Values[newBit] = value; - n.Keys[newBit] = key; - return false; - } - } - - int cur = 0; - unsigned bitPos = kNumBitsMax; - for (;;) - { - CNode &n = Nodes[cur]; - bitPos -= n.Len; - if (GetSubBits(key, bitPos, n.Len) != GetSubBits(n.Key, bitPos, n.Len)) - { - unsigned i = n.Len - 1; - for (; GetSubBit(key, bitPos + i) == GetSubBit(n.Key, bitPos + i); i--); - - CNode e2(n); - e2.Len = (UInt16)i; - - n.Len = (UInt16)(n.Len - (1 + i)); - unsigned newBit = GetSubBit(key, bitPos + i); - n.Values[newBit] = value; - n.IsLeaf[newBit] = 1; - n.IsLeaf[1 - newBit] = 0; - n.Keys[newBit] = key; - n.Keys[1 - newBit] = Nodes.Size(); - Nodes.Add(e2); - return false; - } - unsigned bit = GetSubBit(key, --bitPos); - - if (n.IsLeaf[bit]) - { - if (key == n.Keys[bit]) - { - n.Values[bit] = value; - return true; - } - unsigned i = bitPos - 1; - for (;GetSubBit(key, i) == GetSubBit(n.Keys[bit], i); i--); - - CNode e2; - - unsigned newBit = GetSubBit(key, i); - e2.Values[newBit] = value; - e2.Values[1 - newBit] = n.Values[bit]; - e2.IsLeaf[newBit] = e2.IsLeaf[1 - newBit] = 1; - e2.Keys[newBit] = key; - e2.Keys[1 - newBit] = e2.Key = n.Keys[bit]; - e2.Len = (UInt16)(bitPos - (1 + i)); - - n.IsLeaf[bit] = 0; - n.Keys[bit] = Nodes.Size(); - - Nodes.Add(e2); - return false; - } - cur = (int)n.Keys[bit]; - } -} diff --git a/desmume/src/windows/7z/CPP/Common/MyMap.h b/desmume/src/windows/7z/CPP/Common/MyMap.h deleted file mode 100644 index 4545bcef4..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyMap.h +++ /dev/null @@ -1,28 +0,0 @@ -// MyMap.h - -#ifndef __COMMON_MYMAP_H -#define __COMMON_MYMAP_H - -#include "MyVector.h" -#include "Types.h" - -class CMap32 -{ - struct CNode - { - UInt32 Key; - UInt32 Keys[2]; - UInt32 Values[2]; - UInt16 Len; - Byte IsLeaf[2]; - }; - CRecordVector Nodes; - -public: - - void Clear() { Nodes.Clear(); } - bool Find(UInt32 key, UInt32 &valueRes) const; - bool Set(UInt32 key, UInt32 value); // returns true, if there is such key already -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyString.cpp b/desmume/src/windows/7z/CPP/Common/MyString.cpp deleted file mode 100644 index efab50350..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyString.cpp +++ /dev/null @@ -1,198 +0,0 @@ -// Common/MyString.cpp - -#include "StdAfx.h" - -#ifdef _WIN32 -#include "StringConvert.h" -#else -#include -#endif - -#include "MyString.h" - - -#ifdef _WIN32 - -#ifndef _UNICODE - -wchar_t MyCharUpper(wchar_t c) -{ - if (c == 0) - return 0; - wchar_t *res = CharUpperW((LPWSTR)(UINT_PTR)(unsigned int)c); - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return (wchar_t)(unsigned int)(UINT_PTR)res; - const int kBufferSize = 4; - char s[kBufferSize + 1]; - int numChars = ::WideCharToMultiByte(CP_ACP, 0, &c, 1, s, kBufferSize, 0, 0); - if (numChars == 0 || numChars > kBufferSize) - return c; - s[numChars] = 0; - ::CharUpperA(s); - ::MultiByteToWideChar(CP_ACP, 0, s, numChars, &c, 1); - return c; -} - -wchar_t MyCharLower(wchar_t c) -{ - if (c == 0) - return 0; - wchar_t *res = CharLowerW((LPWSTR)(UINT_PTR)(unsigned int)c); - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return (wchar_t)(unsigned int)(UINT_PTR)res; - const int kBufferSize = 4; - char s[kBufferSize + 1]; - int numChars = ::WideCharToMultiByte(CP_ACP, 0, &c, 1, s, kBufferSize, 0, 0); - if (numChars == 0 || numChars > kBufferSize) - return c; - s[numChars] = 0; - ::CharLowerA(s); - ::MultiByteToWideChar(CP_ACP, 0, s, numChars, &c, 1); - return c; -} - -wchar_t * MyStringUpper(wchar_t *s) -{ - if (s == 0) - return 0; - wchar_t *res = CharUpperW(s); - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return res; - AString a = UnicodeStringToMultiByte(s); - a.MakeUpper(); - return MyStringCopy(s, (const wchar_t *)MultiByteToUnicodeString(a)); -} - -wchar_t * MyStringLower(wchar_t *s) -{ - if (s == 0) - return 0; - wchar_t *res = CharLowerW(s); - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return res; - AString a = UnicodeStringToMultiByte(s); - a.MakeLower(); - return MyStringCopy(s, (const wchar_t *)MultiByteToUnicodeString(a)); -} - -#endif - -/* -inline int ConvertCompareResult(int r) { return r - 2; } - -int MyStringCollate(const wchar_t *s1, const wchar_t *s2) -{ - int res = CompareStringW( - LOCALE_USER_DEFAULT, SORT_STRINGSORT, s1, -1, s2, -1); - #ifdef _UNICODE - return ConvertCompareResult(res); - #else - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return ConvertCompareResult(res); - return MyStringCollate(UnicodeStringToMultiByte(s1), - UnicodeStringToMultiByte(s2)); - #endif -} - -#ifndef _WIN32_WCE -int MyStringCollate(const char *s1, const char *s2) -{ - return ConvertCompareResult(CompareStringA( - LOCALE_USER_DEFAULT, SORT_STRINGSORT, s1, -1, s2, -1)); -} - -int MyStringCollateNoCase(const char *s1, const char *s2) -{ - return ConvertCompareResult(CompareStringA( - LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT, s1, -1, s2, -1)); -} -#endif - -int MyStringCollateNoCase(const wchar_t *s1, const wchar_t *s2) -{ - int res = CompareStringW( - LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT, s1, -1, s2, -1); - #ifdef _UNICODE - return ConvertCompareResult(res); - #else - if (res != 0 || ::GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return ConvertCompareResult(res); - return MyStringCollateNoCase(UnicodeStringToMultiByte(s1), - UnicodeStringToMultiByte(s2)); - #endif -} -*/ - -#else - -wchar_t MyCharUpper(wchar_t c) -{ - return toupper(c); -} - -/* -int MyStringCollateNoCase(const wchar_t *s1, const wchar_t *s2) -{ - for (;;) - { - wchar_t c1 = *s1++; - wchar_t c2 = *s2++; - wchar_t u1 = MyCharUpper(c1); - wchar_t u2 = MyCharUpper(c2); - - if (u1 < u2) return -1; - if (u1 > u2) return 1; - if (u1 == 0) return 0; - } -} -*/ - -#endif - -int MyStringCompare(const char *s1, const char *s2) -{ - for (;;) - { - unsigned char c1 = (unsigned char)*s1++; - unsigned char c2 = (unsigned char)*s2++; - if (c1 < c2) return -1; - if (c1 > c2) return 1; - if (c1 == 0) return 0; - } -} - -int MyStringCompare(const wchar_t *s1, const wchar_t *s2) -{ - for (;;) - { - wchar_t c1 = *s1++; - wchar_t c2 = *s2++; - if (c1 < c2) return -1; - if (c1 > c2) return 1; - if (c1 == 0) return 0; - } -} - -int MyStringCompareNoCase(const wchar_t *s1, const wchar_t *s2) -{ - for (;;) - { - wchar_t c1 = *s1++; - wchar_t c2 = *s2++; - if (c1 != c2) - { - wchar_t u1 = MyCharUpper(c1); - wchar_t u2 = MyCharUpper(c2); - if (u1 < u2) return -1; - if (u1 > u2) return 1; - } - if (c1 == 0) return 0; - } -} - -#ifdef _WIN32 -int MyStringCompareNoCase(const char *s1, const char *s2) -{ - return MyStringCompareNoCase(MultiByteToUnicodeString(s1), MultiByteToUnicodeString(s2)); -} -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyString.h b/desmume/src/windows/7z/CPP/Common/MyString.h deleted file mode 100644 index 74c8af2fc..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyString.h +++ /dev/null @@ -1,631 +0,0 @@ -// Common/String.h - -#ifndef __COMMON_STRING_H -#define __COMMON_STRING_H - -#include -// #include - -#include "MyVector.h" - -#ifdef _WIN32 -#include "MyWindows.h" -#endif - -template -inline int MyStringLen(const T *s) -{ - int i; - for (i = 0; s[i] != '\0'; i++); - return i; -} - -template -inline T * MyStringCopy(T *dest, const T *src) -{ - T *destStart = dest; - while ((*dest++ = *src++) != 0); - return destStart; -} - -inline wchar_t* MyStringGetNextCharPointer(wchar_t *p) - { return (p + 1); } -inline const wchar_t* MyStringGetNextCharPointer(const wchar_t *p) - { return (p + 1); } -inline wchar_t* MyStringGetPrevCharPointer(const wchar_t *, wchar_t *p) - { return (p - 1); } -inline const wchar_t* MyStringGetPrevCharPointer(const wchar_t *, const wchar_t *p) - { return (p - 1); } - -#ifdef _WIN32 - -inline char* MyStringGetNextCharPointer(char *p) - { return CharNextA(p); } -inline const char* MyStringGetNextCharPointer(const char *p) - { return CharNextA(p); } - -inline char* MyStringGetPrevCharPointer(char *base, char *p) - { return CharPrevA(base, p); } -inline const char* MyStringGetPrevCharPointer(const char *base, const char *p) - { return CharPrevA(base, p); } - -inline char MyCharUpper(char c) - { return (char)(unsigned int)(UINT_PTR)CharUpperA((LPSTR)(UINT_PTR)(unsigned int)(unsigned char)c); } -#ifdef _UNICODE -inline wchar_t MyCharUpper(wchar_t c) - { return (wchar_t)(unsigned int)(UINT_PTR)CharUpperW((LPWSTR)(UINT_PTR)(unsigned int)c); } -#else -wchar_t MyCharUpper(wchar_t c); -#endif - -inline char MyCharLower(char c) - { return (char)(unsigned int)(UINT_PTR)CharLowerA((LPSTR)(UINT_PTR)(unsigned int)(unsigned char)c); } -#ifdef _UNICODE -inline wchar_t MyCharLower(wchar_t c) - { return (wchar_t)(unsigned int)(UINT_PTR)CharLowerW((LPWSTR)(UINT_PTR)(unsigned int)c); } -#else -wchar_t MyCharLower(wchar_t c); -#endif - -inline char * MyStringUpper(char *s) { return CharUpperA(s); } -#ifdef _UNICODE -inline wchar_t * MyStringUpper(wchar_t *s) { return CharUpperW(s); } -#else -wchar_t * MyStringUpper(wchar_t *s); -#endif - -inline char * MyStringLower(char *s) { return CharLowerA(s); } -#ifdef _UNICODE -inline wchar_t * MyStringLower(wchar_t *s) { return CharLowerW(s); } -#else -wchar_t * MyStringLower(wchar_t *s); -#endif - -#else // Standard-C -wchar_t MyCharUpper(wchar_t c); -#endif - -////////////////////////////////////// -// Compare - -/* -#ifndef _WIN32_WCE -int MyStringCollate(const char *s1, const char *s2); -int MyStringCollateNoCase(const char *s1, const char *s2); -#endif -int MyStringCollate(const wchar_t *s1, const wchar_t *s2); -int MyStringCollateNoCase(const wchar_t *s1, const wchar_t *s2); -*/ - -int MyStringCompare(const char *s1, const char *s2); -int MyStringCompare(const wchar_t *s1, const wchar_t *s2); - -#ifdef _WIN32 -int MyStringCompareNoCase(const char *s1, const char *s2); -#endif - -int MyStringCompareNoCase(const wchar_t *s1, const wchar_t *s2); - -template -class CStringBase -{ - void TrimLeftWithCharSet(const CStringBase &charSet) - { - const T *p = _chars; - while (charSet.Find(*p) >= 0 && (*p != 0)) - p = GetNextCharPointer(p); - Delete(0, (int)(p - _chars)); - } - void TrimRightWithCharSet(const CStringBase &charSet) - { - const T *p = _chars; - const T *pLast = NULL; - while (*p != 0) - { - if (charSet.Find(*p) >= 0) - { - if (pLast == NULL) - pLast = p; - } - else - pLast = NULL; - p = GetNextCharPointer(p); - } - if (pLast != NULL) - { - int i = (int)(pLast - _chars); - Delete(i, _length - i); - } - - } - void MoveItems(int destIndex, int srcIndex) - { - memmove(_chars + destIndex, _chars + srcIndex, - sizeof(T) * (_length - srcIndex + 1)); - } - - void InsertSpace(int &index, int size) - { - CorrectIndex(index); - GrowLength(size); - MoveItems(index + size, index); - } - - static T *GetNextCharPointer(T *p) - { return MyStringGetNextCharPointer(p); } - static const T *GetNextCharPointer(const T *p) - { return MyStringGetNextCharPointer(p); } - static T *GetPrevCharPointer(T *base, T *p) - { return MyStringGetPrevCharPointer(base, p); } - static const T *GetPrevCharPointer(const T *base, const T *p) - { return MyStringGetPrevCharPointer(base, p); } -protected: - T *_chars; - int _length; - int _capacity; - - void SetCapacity(int newCapacity) - { - int realCapacity = newCapacity + 1; - if (realCapacity == _capacity) - return; - /* - const int kMaxStringSize = 0x20000000; - #ifndef _WIN32_WCE - if (newCapacity > kMaxStringSize || newCapacity < _length) - throw 1052337; - #endif - */ - T *newBuffer = new T[realCapacity]; - if (_capacity > 0) - { - for (int i = 0; i < _length; i++) - newBuffer[i] = _chars[i]; - delete []_chars; - } - _chars = newBuffer; - _chars[_length] = 0; - _capacity = realCapacity; - } - - void GrowLength(int n) - { - int freeSize = _capacity - _length - 1; - if (n <= freeSize) - return; - int delta; - if (_capacity > 64) - delta = _capacity / 2; - else if (_capacity > 8) - delta = 16; - else - delta = 4; - if (freeSize + delta < n) - delta = n - freeSize; - SetCapacity(_capacity + delta); - } - - void CorrectIndex(int &index) const - { - if (index > _length) - index = _length; - } - -public: - CStringBase(): _chars(0), _length(0), _capacity(0) { SetCapacity(3); } - CStringBase(T c): _chars(0), _length(0), _capacity(0) - { - SetCapacity(1); - _chars[0] = c; - _chars[1] = 0; - _length = 1; - } - CStringBase(const T *chars): _chars(0), _length(0), _capacity(0) - { - int length = MyStringLen(chars); - SetCapacity(length); - MyStringCopy(_chars, chars); // can be optimized by memove() - _length = length; - } - CStringBase(const CStringBase &s): _chars(0), _length(0), _capacity(0) - { - SetCapacity(s._length); - MyStringCopy(_chars, s._chars); - _length = s._length; - } - ~CStringBase() { delete []_chars; } - - operator const T*() const { return _chars;} - - // The minimum size of the character buffer in characters. - // This value does not include space for a null terminator. - T* GetBuffer(int minBufLength) - { - if (minBufLength >= _capacity) - SetCapacity(minBufLength); - return _chars; - } - void ReleaseBuffer() { ReleaseBuffer(MyStringLen(_chars)); } - void ReleaseBuffer(int newLength) - { - /* - #ifndef _WIN32_WCE - if (newLength >= _capacity) - throw 282217; - #endif - */ - _chars[newLength] = 0; - _length = newLength; - } - - CStringBase& operator=(T c) - { - Empty(); - SetCapacity(1); - _chars[0] = c; - _chars[1] = 0; - _length = 1; - return *this; - } - CStringBase& operator=(const T *chars) - { - Empty(); - int length = MyStringLen(chars); - SetCapacity(length); - MyStringCopy(_chars, chars); - _length = length; - return *this; - } - CStringBase& operator=(const CStringBase& s) - { - if (&s == this) - return *this; - Empty(); - SetCapacity(s._length); - MyStringCopy(_chars, s._chars); - _length = s._length; - return *this; - } - - CStringBase& operator+=(T c) - { - GrowLength(1); - _chars[_length] = c; - _chars[++_length] = 0; - return *this; - } - CStringBase& operator+=(const T *s) - { - int len = MyStringLen(s); - GrowLength(len); - MyStringCopy(_chars + _length, s); - _length += len; - return *this; - } - CStringBase& operator+=(const CStringBase &s) - { - GrowLength(s._length); - MyStringCopy(_chars + _length, s._chars); - _length += s._length; - return *this; - } - void Empty() - { - _length = 0; - _chars[0] = 0; - } - int Length() const { return _length; } - bool IsEmpty() const { return (_length == 0); } - - CStringBase Mid(int startIndex) const - { return Mid(startIndex, _length - startIndex); } - CStringBase Mid(int startIndex, int count ) const - { - if (startIndex + count > _length) - count = _length - startIndex; - - if (startIndex == 0 && startIndex + count == _length) - return *this; - - CStringBase result; - result.SetCapacity(count); - // MyStringNCopy(result._chars, _chars + startIndex, count); - for (int i = 0; i < count; i++) - result._chars[i] = _chars[startIndex + i]; - result._chars[count] = 0; - result._length = count; - return result; - } - CStringBase Left(int count) const - { return Mid(0, count); } - CStringBase Right(int count) const - { - if (count > _length) - count = _length; - return Mid(_length - count, count); - } - - void MakeUpper() - { MyStringUpper(_chars); } - void MakeLower() - { MyStringLower(_chars); } - - int Compare(const CStringBase& s) const - { return MyStringCompare(_chars, s._chars); } - - int Compare(const T *s) const - { return MyStringCompare(_chars, s); } - - int CompareNoCase(const CStringBase& s) const - { return MyStringCompareNoCase(_chars, s._chars); } - - int CompareNoCase(const T *s) const - { return MyStringCompareNoCase(_chars, s); } - - /* - int Collate(const CStringBase& s) const - { return MyStringCollate(_chars, s._chars); } - int CollateNoCase(const CStringBase& s) const - { return MyStringCollateNoCase(_chars, s._chars); } - */ - - int Find(T c) const { return Find(c, 0); } - int Find(T c, int startIndex) const - { - T *p = _chars + startIndex; - for (;;) - { - if (*p == c) - return (int)(p - _chars); - if (*p == 0) - return -1; - p = GetNextCharPointer(p); - } - } - int Find(const CStringBase &s) const { return Find(s, 0); } - int Find(const CStringBase &s, int startIndex) const - { - if (s.IsEmpty()) - return startIndex; - for (; startIndex < _length; startIndex++) - { - int j; - for (j = 0; j < s._length && startIndex + j < _length; j++) - if (_chars[startIndex+j] != s._chars[j]) - break; - if (j == s._length) - return startIndex; - } - return -1; - } - int ReverseFind(T c) const - { - if (_length == 0) - return -1; - T *p = _chars + _length - 1; - for (;;) - { - if (*p == c) - return (int)(p - _chars); - if (p == _chars) - return -1; - p = GetPrevCharPointer(_chars, p); - } - } - int FindOneOf(const CStringBase &s) const - { - for (int i = 0; i < _length; i++) - if (s.Find(_chars[i]) >= 0) - return i; - return -1; - } - - void TrimLeft(T c) - { - const T *p = _chars; - while (c == *p) - p = GetNextCharPointer(p); - Delete(0, p - _chars); - } - private: - CStringBase GetTrimDefaultCharSet() - { - CStringBase charSet; - charSet += (T)' '; - charSet += (T)'\n'; - charSet += (T)'\t'; - return charSet; - } - public: - - void TrimLeft() - { - TrimLeftWithCharSet(GetTrimDefaultCharSet()); - } - void TrimRight() - { - TrimRightWithCharSet(GetTrimDefaultCharSet()); - } - void TrimRight(T c) - { - const T *p = _chars; - const T *pLast = NULL; - while (*p != 0) - { - if (*p == c) - { - if (pLast == NULL) - pLast = p; - } - else - pLast = NULL; - p = GetNextCharPointer(p); - } - if (pLast != NULL) - { - int i = pLast - _chars; - Delete(i, _length - i); - } - } - void Trim() - { - TrimRight(); - TrimLeft(); - } - - int Insert(int index, T c) - { - InsertSpace(index, 1); - _chars[index] = c; - _length++; - return _length; - } - int Insert(int index, const CStringBase &s) - { - CorrectIndex(index); - if (s.IsEmpty()) - return _length; - int numInsertChars = s.Length(); - InsertSpace(index, numInsertChars); - for (int i = 0; i < numInsertChars; i++) - _chars[index + i] = s[i]; - _length += numInsertChars; - return _length; - } - - // !!!!!!!!!!!!!!! test it if newChar = '\0' - int Replace(T oldChar, T newChar) - { - if (oldChar == newChar) - return 0; - int number = 0; - int pos = 0; - while (pos < Length()) - { - pos = Find(oldChar, pos); - if (pos < 0) - break; - _chars[pos] = newChar; - pos++; - number++; - } - return number; - } - int Replace(const CStringBase &oldString, const CStringBase &newString) - { - if (oldString.IsEmpty()) - return 0; - if (oldString == newString) - return 0; - int oldStringLength = oldString.Length(); - int newStringLength = newString.Length(); - int number = 0; - int pos = 0; - while (pos < _length) - { - pos = Find(oldString, pos); - if (pos < 0) - break; - Delete(pos, oldStringLength); - Insert(pos, newString); - pos += newStringLength; - number++; - } - return number; - } - int Delete(int index, int count = 1 ) - { - if (index + count > _length) - count = _length - index; - if (count > 0) - { - MoveItems(index, index + count); - _length -= count; - } - return _length; - } -}; - -template -CStringBase operator+(const CStringBase& s1, const CStringBase& s2) -{ - CStringBase result(s1); - result += s2; - return result; -} - -template -CStringBase operator+(const CStringBase& s, T c) -{ - CStringBase result(s); - result += c; - return result; -} - -template -CStringBase operator+(T c, const CStringBase& s) -{ - CStringBase result(c); - result += s; - return result; -} - -template -CStringBase operator+(const CStringBase& s, const T * chars) -{ - CStringBase result(s); - result += chars; - return result; -} - -template -CStringBase operator+(const T * chars, const CStringBase& s) -{ - CStringBase result(chars); - result += s; - return result; -} - -template -bool operator==(const CStringBase& s1, const CStringBase& s2) - { return (s1.Compare(s2) == 0); } - -template -bool operator<(const CStringBase& s1, const CStringBase& s2) - { return (s1.Compare(s2) < 0); } - -template -bool operator==(const T *s1, const CStringBase& s2) - { return (s2.Compare(s1) == 0); } - -template -bool operator==(const CStringBase& s1, const T *s2) - { return (s1.Compare(s2) == 0); } - -template -bool operator!=(const CStringBase& s1, const CStringBase& s2) - { return (s1.Compare(s2) != 0); } - -template -bool operator!=(const T *s1, const CStringBase& s2) - { return (s2.Compare(s1) != 0); } - -template -bool operator!=(const CStringBase& s1, const T *s2) - { return (s1.Compare(s2) != 0); } - -typedef CStringBase AString; -typedef CStringBase UString; - -typedef CObjectVector AStringVector; -typedef CObjectVector UStringVector; - -#ifdef _UNICODE - typedef UString CSysString; -#else - typedef AString CSysString; -#endif - -typedef CObjectVector CSysStringVector; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyUnknown.h b/desmume/src/windows/7z/CPP/Common/MyUnknown.h deleted file mode 100644 index 257fa4ab7..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyUnknown.h +++ /dev/null @@ -1,24 +0,0 @@ -// MyUnknown.h - -#ifndef __MYUNKNOWN_H -#define __MYUNKNOWN_H - -#ifdef _WIN32 - -#ifdef _WIN32_WCE -#if (_WIN32_WCE > 300) -#include -#else -#define MIDL_INTERFACE(x) struct -#endif -#else -#include -#endif - -#include - -#else -#include "MyWindows.h" -#endif - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyVector.cpp b/desmume/src/windows/7z/CPP/Common/MyVector.cpp deleted file mode 100644 index e0788b751..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyVector.cpp +++ /dev/null @@ -1,90 +0,0 @@ -// Common/MyVector.cpp - -#include "StdAfx.h" - -#include - -#include "MyVector.h" - -CBaseRecordVector::~CBaseRecordVector() { ClearAndFree(); } - -void CBaseRecordVector::ClearAndFree() -{ - Clear(); - delete []((unsigned char *)_items); - _capacity = 0; - _size = 0; - _items = 0; -} - -void CBaseRecordVector::Clear() { DeleteFrom(0); } -void CBaseRecordVector::DeleteBack() { Delete(_size - 1); } -void CBaseRecordVector::DeleteFrom(int index) -{ - Delete(index, _size - index); -} - -void CBaseRecordVector::ReserveOnePosition() -{ - if (_size != _capacity) - return; - int delta = 1; - if (_capacity >= 64) - delta = _capacity / 4; - else if (_capacity >= 8) - delta = 8; - Reserve(_capacity + delta); -} - -void CBaseRecordVector::Reserve(int newCapacity) -{ - // if (newCapacity <= _capacity) - if (newCapacity == _capacity) - return; - if ((unsigned)newCapacity >= ((unsigned)1 << (sizeof(unsigned) * 8 - 1))) - throw 1052353; - size_t newSize = (size_t)(unsigned)newCapacity * _itemSize; - if (newSize / _itemSize != (size_t)(unsigned)newCapacity) - throw 1052354; - unsigned char *p = NULL; - if (newSize > 0) - { - p = new unsigned char[newSize]; - if (p == 0) - throw 1052355; - int numRecordsToMove = (_size < newCapacity ? _size : newCapacity); - memcpy(p, _items, _itemSize * numRecordsToMove); - } - delete [](unsigned char *)_items; - _items = p; - _capacity = newCapacity; -} - -void CBaseRecordVector::ReserveDown() -{ - Reserve(_size); -} - -void CBaseRecordVector::MoveItems(int destIndex, int srcIndex) -{ - memmove(((unsigned char *)_items) + destIndex * _itemSize, - ((unsigned char *)_items) + srcIndex * _itemSize, - _itemSize * (_size - srcIndex)); -} - -void CBaseRecordVector::InsertOneItem(int index) -{ - ReserveOnePosition(); - MoveItems(index + 1, index); - _size++; -} - -void CBaseRecordVector::Delete(int index, int num) -{ - TestIndexAndCorrectNum(index, num); - if (num > 0) - { - MoveItems(index, index + num); - _size -= num; - } -} diff --git a/desmume/src/windows/7z/CPP/Common/MyVector.h b/desmume/src/windows/7z/CPP/Common/MyVector.h deleted file mode 100644 index b8f4cd929..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyVector.h +++ /dev/null @@ -1,256 +0,0 @@ -// Common/Vector.h - -#ifndef __COMMON_VECTOR_H -#define __COMMON_VECTOR_H - -#include "Defs.h" - -class CBaseRecordVector -{ - void MoveItems(int destIndex, int srcIndex); -protected: - int _capacity; - int _size; - void *_items; - size_t _itemSize; - - void ReserveOnePosition(); - void InsertOneItem(int index); - void TestIndexAndCorrectNum(int index, int &num) const - { if (index + num > _size) num = _size - index; } -public: - CBaseRecordVector(size_t itemSize): _capacity(0), _size(0), _items(0), _itemSize(itemSize) {} - virtual ~CBaseRecordVector(); - void ClearAndFree(); - int Size() const { return _size; } - bool IsEmpty() const { return (_size == 0); } - void Reserve(int newCapacity); - void ReserveDown(); - virtual void Delete(int index, int num = 1); - void Clear(); - void DeleteFrom(int index); - void DeleteBack(); -}; - -template -class CRecordVector: public CBaseRecordVector -{ -public: - CRecordVector(): CBaseRecordVector(sizeof(T)){}; - CRecordVector(const CRecordVector &v): CBaseRecordVector(sizeof(T)) { *this = v; } - CRecordVector& operator=(const CRecordVector &v) - { - Clear(); - return (*this += v); - } - CRecordVector& operator+=(const CRecordVector &v) - { - int size = v.Size(); - Reserve(Size() + size); - for (int i = 0; i < size; i++) - Add(v[i]); - return *this; - } - int Add(T item) - { - ReserveOnePosition(); - ((T *)_items)[_size] = item; - return _size++; - } - void Insert(int index, T item) - { - InsertOneItem(index); - ((T *)_items)[index] = item; - } - // T* GetPointer() const { return (T*)_items; } - // operator const T *() const { return _items; }; - const T& operator[](int index) const { return ((T *)_items)[index]; } - T& operator[](int index) { return ((T *)_items)[index]; } - const T& Front() const { return operator[](0); } - T& Front() { return operator[](0); } - const T& Back() const { return operator[](_size - 1); } - T& Back() { return operator[](_size - 1); } - - void Swap(int i, int j) - { - T temp = operator[](i); - operator[](i) = operator[](j); - operator[](j) = temp; - } - - int FindInSorted(const T& item) const - { - int left = 0, right = Size(); - while (left != right) - { - int mid = (left + right) / 2; - const T& midValue = (*this)[mid]; - if (item == midValue) - return mid; - if (item < midValue) - right = mid; - else - left = mid + 1; - } - return -1; - } - - int AddToUniqueSorted(const T& item) - { - int left = 0, right = Size(); - while (left != right) - { - int mid = (left + right) / 2; - const T& midValue = (*this)[mid]; - if (item == midValue) - return mid; - if (item < midValue) - right = mid; - else - left = mid + 1; - } - Insert(right, item); - return right; - } - - static void SortRefDown(T* p, int k, int size, int (*compare)(const T*, const T*, void *), void *param) - { - T temp = p[k]; - for (;;) - { - int s = (k << 1); - if (s > size) - break; - if (s < size && compare(p + s + 1, p + s, param) > 0) - s++; - if (compare(&temp, p + s, param) >= 0) - break; - p[k] = p[s]; - k = s; - } - p[k] = temp; - } - - void Sort(int (*compare)(const T*, const T*, void *), void *param) - { - int size = _size; - if (size <= 1) - return; - T* p = (&Front()) - 1; - { - int i = size / 2; - do - SortRefDown(p, i, size, compare, param); - while (--i != 0); - } - do - { - T temp = p[size]; - p[size--] = p[1]; - p[1] = temp; - SortRefDown(p, 1, size, compare, param); - } - while (size > 1); - } -}; - -typedef CRecordVector CIntVector; -typedef CRecordVector CUIntVector; -typedef CRecordVector CBoolVector; -typedef CRecordVector CByteVector; -typedef CRecordVector CPointerVector; - -template -class CObjectVector: public CPointerVector -{ -public: - CObjectVector() {}; - ~CObjectVector() { Clear(); }; - CObjectVector(const CObjectVector &v) { *this = v; } - CObjectVector& operator=(const CObjectVector &v) - { - Clear(); - return (*this += v); - } - CObjectVector& operator+=(const CObjectVector &v) - { - int size = v.Size(); - Reserve(Size() + size); - for (int i = 0; i < size; i++) - Add(v[i]); - return *this; - } - const T& operator[](int index) const - { - return *((T *)CPointerVector::operator[](index)); - } - T& operator[](int index) - { - return *((T *)CPointerVector::operator[](index)); - } - T& Front() { return operator[](0); } - const T& Front() const { return operator[](0); } - T& Back() { return operator[](_size - 1); } - const T& Back() const { return operator[](_size - 1); } - int Add(const T& item) { return CPointerVector::Add(new T(item)); } - void Insert(int index, const T& item) { CPointerVector::Insert(index, new T(item)); } - virtual void Delete(int index, int num = 1) - { - TestIndexAndCorrectNum(index, num); - for (int i = 0; i < num; i++) - delete (T *)(((void **)_items)[index + i]); - CPointerVector::Delete(index, num); - } - int Find(const T& item) const - { - for (int i = 0; i < Size(); i++) - if (item == (*this)[i]) - return i; - return -1; - } - int FindInSorted(const T& item) const - { - int left = 0, right = Size(); - while (left != right) - { - int mid = (left + right) / 2; - const T& midValue = (*this)[mid]; - if (item == midValue) - return mid; - if (item < midValue) - right = mid; - else - left = mid + 1; - } - return -1; - } - int AddToSorted(const T& item) - { - int left = 0, right = Size(); - while (left != right) - { - int mid = (left + right) / 2; - const T& midValue = (*this)[mid]; - if (item == midValue) - { - right = mid + 1; - break; - } - if (item < midValue) - right = mid; - else - left = mid + 1; - } - Insert(right, item); - return right; - } - - void Sort(int (*compare)(void *const *, void *const *, void *), void *param) - { CPointerVector::Sort(compare, param); } - - static int CompareObjectItems(void *const *a1, void *const *a2, void * /* param */) - { return MyCompare(*(*((const T **)a1)), *(*((const T **)a2))); } - void Sort() { CPointerVector::Sort(CompareObjectItems, 0); } -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyWindows.h b/desmume/src/windows/7z/CPP/Common/MyWindows.h deleted file mode 100644 index 0329ff709..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyWindows.h +++ /dev/null @@ -1,214 +0,0 @@ -// MyWindows.h - -#ifndef __MYWINDOWS_H -#define __MYWINDOWS_H - -#ifdef _WIN32 - -#include - -#define CHAR_PATH_SEPARATOR '\\' -#define WCHAR_PATH_SEPARATOR L'\\' -#define STRING_PATH_SEPARATOR "\\" -#define WSTRING_PATH_SEPARATOR L"\\" - -#else - -#define CHAR_PATH_SEPARATOR '/' -#define WCHAR_PATH_SEPARATOR L'/' -#define STRING_PATH_SEPARATOR "/" -#define WSTRING_PATH_SEPARATOR L"/" - -#include // for wchar_t -#include - -#include "MyGuidDef.h" - -typedef char CHAR; -typedef unsigned char UCHAR; - -#undef BYTE -typedef unsigned char BYTE; - -typedef short SHORT; -typedef unsigned short USHORT; - -#undef WORD -typedef unsigned short WORD; -typedef short VARIANT_BOOL; - -typedef int INT; -typedef Int32 INT32; -typedef unsigned int UINT; -typedef UInt32 UINT32; -typedef INT32 LONG; // LONG, ULONG and DWORD must be 32-bit -typedef UINT32 ULONG; - -#undef DWORD -typedef UINT32 DWORD; - -typedef Int64 LONGLONG; -typedef UInt64 ULONGLONG; - -typedef struct LARGE_INTEGER { LONGLONG QuadPart; }LARGE_INTEGER; -typedef struct _ULARGE_INTEGER { ULONGLONG QuadPart;} ULARGE_INTEGER; - -typedef const CHAR *LPCSTR; -typedef CHAR TCHAR; -typedef const TCHAR *LPCTSTR; -typedef wchar_t WCHAR; -typedef WCHAR OLECHAR; -typedef const WCHAR *LPCWSTR; -typedef OLECHAR *BSTR; -typedef const OLECHAR *LPCOLESTR; -typedef OLECHAR *LPOLESTR; - -typedef struct _FILETIME -{ - DWORD dwLowDateTime; - DWORD dwHighDateTime; -}FILETIME; - -#define HRESULT LONG -#define FAILED(Status) ((HRESULT)(Status)<0) -typedef ULONG PROPID; -typedef LONG SCODE; - -#define S_OK ((HRESULT)0x00000000L) -#define S_FALSE ((HRESULT)0x00000001L) -#define E_NOTIMPL ((HRESULT)0x80004001L) -#define E_NOINTERFACE ((HRESULT)0x80004002L) -#define E_ABORT ((HRESULT)0x80004004L) -#define E_FAIL ((HRESULT)0x80004005L) -#define STG_E_INVALIDFUNCTION ((HRESULT)0x80030001L) -#define E_OUTOFMEMORY ((HRESULT)0x8007000EL) -#define E_INVALIDARG ((HRESULT)0x80070057L) - -#ifdef _MSC_VER -#define STDMETHODCALLTYPE __stdcall -#else -#define STDMETHODCALLTYPE -#endif - -#define STDMETHOD_(t, f) virtual t STDMETHODCALLTYPE f -#define STDMETHOD(f) STDMETHOD_(HRESULT, f) -#define STDMETHODIMP_(type) type STDMETHODCALLTYPE -#define STDMETHODIMP STDMETHODIMP_(HRESULT) - -#define PURE = 0 - -#define MIDL_INTERFACE(x) struct - -#ifdef __cplusplus - -DEFINE_GUID(IID_IUnknown, -0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); -struct IUnknown -{ - STDMETHOD(QueryInterface) (REFIID iid, void **outObject) PURE; - STDMETHOD_(ULONG, AddRef)() PURE; - STDMETHOD_(ULONG, Release)() PURE; - #ifndef _WIN32 - virtual ~IUnknown() {} - #endif -}; - -typedef IUnknown *LPUNKNOWN; - -#endif - -#define VARIANT_TRUE ((VARIANT_BOOL)-1) -#define VARIANT_FALSE ((VARIANT_BOOL)0) - -enum VARENUM -{ - VT_EMPTY = 0, - VT_NULL = 1, - VT_I2 = 2, - VT_I4 = 3, - VT_R4 = 4, - VT_R8 = 5, - VT_CY = 6, - VT_DATE = 7, - VT_BSTR = 8, - VT_DISPATCH = 9, - VT_ERROR = 10, - VT_BOOL = 11, - VT_VARIANT = 12, - VT_UNKNOWN = 13, - VT_DECIMAL = 14, - VT_I1 = 16, - VT_UI1 = 17, - VT_UI2 = 18, - VT_UI4 = 19, - VT_I8 = 20, - VT_UI8 = 21, - VT_INT = 22, - VT_UINT = 23, - VT_VOID = 24, - VT_HRESULT = 25, - VT_FILETIME = 64 -}; - -typedef unsigned short VARTYPE; -typedef WORD PROPVAR_PAD1; -typedef WORD PROPVAR_PAD2; -typedef WORD PROPVAR_PAD3; - -#ifdef __cplusplus - -typedef struct tagPROPVARIANT -{ - VARTYPE vt; - PROPVAR_PAD1 wReserved1; - PROPVAR_PAD2 wReserved2; - PROPVAR_PAD3 wReserved3; - union - { - CHAR cVal; - UCHAR bVal; - SHORT iVal; - USHORT uiVal; - LONG lVal; - ULONG ulVal; - INT intVal; - UINT uintVal; - LARGE_INTEGER hVal; - ULARGE_INTEGER uhVal; - VARIANT_BOOL boolVal; - SCODE scode; - FILETIME filetime; - BSTR bstrVal; - }; -} PROPVARIANT; - -typedef PROPVARIANT tagVARIANT; -typedef tagVARIANT VARIANT; -typedef VARIANT VARIANTARG; - -MY_EXTERN_C HRESULT VariantClear(VARIANTARG *prop); -MY_EXTERN_C HRESULT VariantCopy(VARIANTARG *dest, VARIANTARG *src); - -#endif - -MY_EXTERN_C BSTR SysAllocStringByteLen(LPCSTR psz, UINT len); -MY_EXTERN_C BSTR SysAllocString(const OLECHAR *sz); -MY_EXTERN_C void SysFreeString(BSTR bstr); -MY_EXTERN_C UINT SysStringByteLen(BSTR bstr); -MY_EXTERN_C UINT SysStringLen(BSTR bstr); - -MY_EXTERN_C DWORD GetLastError(); -MY_EXTERN_C LONG CompareFileTime(const FILETIME* ft1, const FILETIME* ft2); - -#define CP_ACP 0 -#define CP_OEMCP 1 - -typedef enum tagSTREAM_SEEK -{ - STREAM_SEEK_SET = 0, - STREAM_SEEK_CUR = 1, - STREAM_SEEK_END = 2 -} STREAM_SEEK; - -#endif -#endif diff --git a/desmume/src/windows/7z/CPP/Common/MyXml.cpp b/desmume/src/windows/7z/CPP/Common/MyXml.cpp deleted file mode 100644 index c18570e93..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyXml.cpp +++ /dev/null @@ -1,209 +0,0 @@ -// MyXml.cpp - -#include "StdAfx.h" - -#include "MyXml.h" - -static bool IsValidChar(char c) -{ - return - c >= 'a' && c <= 'z' || - c >= 'A' && c <= 'Z' || - c >= '0' && c <= '9' || - c == '-'; -} - -static bool IsSpaceChar(char c) -{ - return (c == ' ' || c == '\t' || c == 0x0D || c == 0x0A); -} - -#define SKEEP_SPACES(s, pos) while (IsSpaceChar(s[pos])) pos++; - -static bool ReadProperty(const AString &s, int &pos, CXmlProp &prop) -{ - prop.Name.Empty(); - prop.Value.Empty(); - for (; pos < s.Length(); pos++) - { - char c = s[pos]; - if (!IsValidChar(c)) - break; - prop.Name += c; - } - - if (prop.Name.IsEmpty()) - return false; - - SKEEP_SPACES(s, pos); - if (s[pos++] != '=') - return false; - - SKEEP_SPACES(s, pos); - if (s[pos++] != '\"') - return false; - - while (pos < s.Length()) - { - char c = s[pos++]; - if (c == '\"') - return true; - prop.Value += c; - } - return false; -} - -int CXmlItem::FindProperty(const AString &propName) const -{ - for (int i = 0; i < Props.Size(); i++) - if (Props[i].Name == propName) - return i; - return -1; -} - -AString CXmlItem::GetPropertyValue(const AString &propName) const -{ - int index = FindProperty(propName); - if (index >= 0) - return Props[index].Value; - return AString(); -} - -bool CXmlItem::IsTagged(const AString &tag) const -{ - return (IsTag && Name == tag); -} - -int CXmlItem::FindSubTag(const AString &tag) const -{ - for (int i = 0; i < SubItems.Size(); i++) - if (SubItems[i].IsTagged(tag)) - return i; - return -1; -} - -AString CXmlItem::GetSubString() const -{ - if (SubItems.Size() == 1) - { - const CXmlItem &item = SubItems[0]; - if (!item.IsTag) - return item.Name; - } - return AString(); -} - -AString CXmlItem::GetSubStringForTag(const AString &tag) const -{ - int index = FindSubTag(tag); - if (index >= 0) - return SubItems[index].GetSubString(); - return AString(); -} - -bool CXmlItem::ParseItems(const AString &s, int &pos, int numAllowedLevels) -{ - if (numAllowedLevels == 0) - return false; - SubItems.Clear(); - AString finishString = "'); - } - if (s[pos] == '>') - { - if (!ParseItems(s, ++pos, numAllowedLevels)) - return false; - AString finishString = AString(""); - if (s.Mid(pos, finishString.Length()) != finishString) - return false; - pos += finishString.Length(); - return true; - } - if (posTemp == pos) - return false; - - CXmlProp prop; - if (!ReadProperty(s, pos, prop)) - return false; - Props.Add(prop); - posTemp = pos; - } -} - -bool SkeepHeader(const AString &s, int &pos, const AString &startString, const AString &endString) -{ - SKEEP_SPACES(s, pos); - if (s.Mid(pos, startString.Length()) == startString) - { - pos = s.Find(endString, pos); - if (pos < 0) - return false; - pos += endString.Length(); - SKEEP_SPACES(s, pos); - } - return true; -} - -bool CXml::Parse(const AString &s) -{ - int pos = 0; - if (!SkeepHeader(s, pos, "")) - return false; - if (!SkeepHeader(s, pos, "")) - return false; - if (!Root.ParseItem(s, pos, 1000)) - return false; - SKEEP_SPACES(s, pos); - return (pos == s.Length() && Root.IsTag); -} diff --git a/desmume/src/windows/7z/CPP/Common/MyXml.h b/desmume/src/windows/7z/CPP/Common/MyXml.h deleted file mode 100644 index 52e23d19c..000000000 --- a/desmume/src/windows/7z/CPP/Common/MyXml.h +++ /dev/null @@ -1,40 +0,0 @@ -// MyXml.h - -#ifndef __MYXML_H -#define __MYXML_H - -#include "MyString.h" - -struct CXmlProp -{ - AString Name; - AString Value; -}; - -class CXmlItem -{ - bool ParseItems(const AString &s, int &pos, int numAllowedLevels); - -public: - AString Name; - bool IsTag; - CObjectVector Props; - CObjectVector SubItems; - - bool ParseItem(const AString &s, int &pos, int numAllowedLevels); - - bool IsTagged(const AString &tag) const; - int FindProperty(const AString &propName) const; - AString GetPropertyValue(const AString &propName) const; - AString GetSubString() const; - int FindSubTag(const AString &tag) const; - AString GetSubStringForTag(const AString &tag) const; -}; - -struct CXml -{ - CXmlItem Root; - bool Parse(const AString &s); -}; - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/NewHandler.cpp b/desmume/src/windows/7z/CPP/Common/NewHandler.cpp deleted file mode 100644 index 611bbd8f5..000000000 --- a/desmume/src/windows/7z/CPP/Common/NewHandler.cpp +++ /dev/null @@ -1,116 +0,0 @@ -// NewHandler.cpp - -#include "StdAfx.h" - -#include - -#include "NewHandler.h" - -// #define DEBUG_MEMORY_LEAK - -#ifndef DEBUG_MEMORY_LEAK - -#ifdef _WIN32 -void * -#ifdef _MSC_VER -__cdecl -#endif -operator new(size_t size) -{ - // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size); - void *p = ::malloc(size); - if (p == 0) - throw CNewException(); - return p; -} - -void -#ifdef _MSC_VER -__cdecl -#endif -operator delete(void *p) throw() -{ - /* - if (p == 0) - return; - ::HeapFree(::GetProcessHeap(), 0, p); - */ - ::free(p); -} -#endif - -#else - -#pragma init_seg(lib) -const int kDebugSize = 1000000; -static void *a[kDebugSize]; -static int index = 0; - -static int numAllocs = 0; -void * __cdecl operator new(size_t size) -{ - numAllocs++; - void *p = HeapAlloc(GetProcessHeap(), 0, size); - if (index == 40) - { - int t = 1; - } - if (index < kDebugSize) - { - a[index] = p; - index++; - } - if (p == 0) - throw CNewException(); - printf("Alloc %6d, size = %8d\n", numAllocs, size); - return p; -} - -class CC -{ -public: - CC() - { - for (int i = 0; i < kDebugSize; i++) - a[i] = 0; - } - ~CC() - { - for (int i = 0; i < kDebugSize; i++) - if (a[i] != 0) - return; - } -} g_CC; - - -void __cdecl operator delete(void *p) -{ - if (p == 0) - return; - /* - for (int i = 0; i < index; i++) - if (a[i] == p) - a[i] = 0; - */ - HeapFree(GetProcessHeap(), 0, p); - numAllocs--; - printf("Free %d\n", numAllocs); -} - -#endif - -/* -int MemErrorVC(size_t) -{ - throw CNewException(); - // return 1; -} -CNewHandlerSetter::CNewHandlerSetter() -{ - // MemErrorOldVCFunction = _set_new_handler(MemErrorVC); -} -CNewHandlerSetter::~CNewHandlerSetter() -{ - // _set_new_handler(MemErrorOldVCFunction); -} -*/ diff --git a/desmume/src/windows/7z/CPP/Common/NewHandler.h b/desmume/src/windows/7z/CPP/Common/NewHandler.h deleted file mode 100644 index 6f710cda1..000000000 --- a/desmume/src/windows/7z/CPP/Common/NewHandler.h +++ /dev/null @@ -1,16 +0,0 @@ -// Common/NewHandler.h - -#ifndef __COMMON_NEWHANDLER_H -#define __COMMON_NEWHANDLER_H - -class CNewException {}; - -#ifdef _WIN32 -void -#ifdef _MSC_VER -__cdecl -#endif -operator delete(void *p) throw(); -#endif - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/StringConvert.cpp b/desmume/src/windows/7z/CPP/Common/StringConvert.cpp deleted file mode 100644 index ebd014831..000000000 --- a/desmume/src/windows/7z/CPP/Common/StringConvert.cpp +++ /dev/null @@ -1,102 +0,0 @@ -// Common/StringConvert.cpp - -#include "StdAfx.h" - -#include "StringConvert.h" - -#ifndef _WIN32 -#include -#endif - -#ifdef _WIN32 -UString MultiByteToUnicodeString(const AString &srcString, UINT codePage) -{ - UString resultString; - if (!srcString.IsEmpty()) - { - int numChars = MultiByteToWideChar(codePage, 0, srcString, - srcString.Length(), resultString.GetBuffer(srcString.Length()), - srcString.Length() + 1); - #ifndef _WIN32_WCE - if (numChars == 0) - throw 282228; - #endif - resultString.ReleaseBuffer(numChars); - } - return resultString; -} - -AString UnicodeStringToMultiByte(const UString &s, UINT codePage, char defaultChar, bool &defaultCharWasUsed) -{ - AString dest; - defaultCharWasUsed = false; - if (!s.IsEmpty()) - { - int numRequiredBytes = s.Length() * 2; - BOOL defUsed; - int numChars = WideCharToMultiByte(codePage, 0, s, s.Length(), - dest.GetBuffer(numRequiredBytes), numRequiredBytes + 1, - &defaultChar, &defUsed); - defaultCharWasUsed = (defUsed != FALSE); - #ifndef _WIN32_WCE - if (numChars == 0) - throw 282229; - #endif - dest.ReleaseBuffer(numChars); - } - return dest; -} - -AString UnicodeStringToMultiByte(const UString &srcString, UINT codePage) -{ - bool defaultCharWasUsed; - return UnicodeStringToMultiByte(srcString, codePage, '_', defaultCharWasUsed); -} - -#ifndef _WIN32_WCE -AString SystemStringToOemString(const CSysString &srcString) -{ - AString result; - CharToOem(srcString, result.GetBuffer(srcString.Length() * 2)); - result.ReleaseBuffer(); - return result; -} -#endif - -#else - -UString MultiByteToUnicodeString(const AString &srcString, UINT codePage) -{ - UString resultString; - for (int i = 0; i < srcString.Length(); i++) - resultString += wchar_t(srcString[i]); - /* - if (!srcString.IsEmpty()) - { - int numChars = mbstowcs(resultString.GetBuffer(srcString.Length()), srcString, srcString.Length() + 1); - if (numChars < 0) throw "Your environment does not support UNICODE"; - resultString.ReleaseBuffer(numChars); - } - */ - return resultString; -} - -AString UnicodeStringToMultiByte(const UString &srcString, UINT codePage) -{ - AString resultString; - for (int i = 0; i < srcString.Length(); i++) - resultString += char(srcString[i]); - /* - if (!srcString.IsEmpty()) - { - int numRequiredBytes = srcString.Length() * 6 + 1; - int numChars = wcstombs(resultString.GetBuffer(numRequiredBytes), srcString, numRequiredBytes); - if (numChars < 0) throw "Your environment does not support UNICODE"; - resultString.ReleaseBuffer(numChars); - } - */ - return resultString; -} - -#endif - diff --git a/desmume/src/windows/7z/CPP/Common/StringConvert.h b/desmume/src/windows/7z/CPP/Common/StringConvert.h deleted file mode 100644 index e0a2332c9..000000000 --- a/desmume/src/windows/7z/CPP/Common/StringConvert.h +++ /dev/null @@ -1,73 +0,0 @@ -// Common/StringConvert.h - -#ifndef __COMMON_STRINGCONVERT_H -#define __COMMON_STRINGCONVERT_H - -#include "MyWindows.h" -#include "MyString.h" -#include "Types.h" - -UString MultiByteToUnicodeString(const AString &srcString, UINT codePage = CP_ACP); -AString UnicodeStringToMultiByte(const UString &srcString, UINT codePage, char defaultChar, bool &defaultCharWasUsed); -AString UnicodeStringToMultiByte(const UString &srcString, UINT codePage = CP_ACP); - - -inline const wchar_t* GetUnicodeString(const wchar_t* unicodeString) - { return unicodeString; } -inline const UString& GetUnicodeString(const UString &unicodeString) - { return unicodeString; } -inline UString GetUnicodeString(const AString &ansiString) - { return MultiByteToUnicodeString(ansiString); } -inline UString GetUnicodeString(const AString &multiByteString, UINT codePage) - { return MultiByteToUnicodeString(multiByteString, codePage); } -inline const wchar_t* GetUnicodeString(const wchar_t* unicodeString, UINT) - { return unicodeString; } -inline const UString& GetUnicodeString(const UString &unicodeString, UINT) - { return unicodeString; } - -inline const char* GetAnsiString(const char* ansiString) - { return ansiString; } -inline const AString& GetAnsiString(const AString &ansiString) - { return ansiString; } -inline AString GetAnsiString(const UString &unicodeString) - { return UnicodeStringToMultiByte(unicodeString); } - -inline const char* GetOemString(const char* oemString) - { return oemString; } -inline const AString& GetOemString(const AString &oemString) - { return oemString; } -inline AString GetOemString(const UString &unicodeString) - { return UnicodeStringToMultiByte(unicodeString, CP_OEMCP); } - - -#ifdef _UNICODE - inline const wchar_t* GetSystemString(const wchar_t* unicodeString) - { return unicodeString;} - inline const UString& GetSystemString(const UString &unicodeString) - { return unicodeString;} - inline const wchar_t* GetSystemString(const wchar_t* unicodeString, UINT /* codePage */) - { return unicodeString;} - inline const UString& GetSystemString(const UString &unicodeString, UINT /* codePage */) - { return unicodeString;} - inline UString GetSystemString(const AString &multiByteString, UINT codePage) - { return MultiByteToUnicodeString(multiByteString, codePage);} - inline UString GetSystemString(const AString &multiByteString) - { return MultiByteToUnicodeString(multiByteString);} -#else - inline const char* GetSystemString(const char *ansiString) - { return ansiString; } - inline const AString& GetSystemString(const AString &multiByteString, UINT) - { return multiByteString; } - inline const char * GetSystemString(const char *multiByteString, UINT) - { return multiByteString; } - inline AString GetSystemString(const UString &unicodeString) - { return UnicodeStringToMultiByte(unicodeString); } - inline AString GetSystemString(const UString &unicodeString, UINT codePage) - { return UnicodeStringToMultiByte(unicodeString, codePage); } -#endif - -#ifndef _WIN32_WCE -AString SystemStringToOemString(const CSysString &srcString); -#endif - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/StringToInt.cpp b/desmume/src/windows/7z/CPP/Common/StringToInt.cpp deleted file mode 100644 index 77ce7c50b..000000000 --- a/desmume/src/windows/7z/CPP/Common/StringToInt.cpp +++ /dev/null @@ -1,90 +0,0 @@ -// Common/StringToInt.cpp - -#include "StdAfx.h" - -#include "StringToInt.h" - -UInt64 ConvertStringToUInt64(const char *s, const char **end) -{ - UInt64 result = 0; - for (;;) - { - char c = *s; - if (c < '0' || c > '9') - { - if (end != NULL) - *end = s; - return result; - } - result *= 10; - result += (c - '0'); - s++; - } -} - -UInt64 ConvertOctStringToUInt64(const char *s, const char **end) -{ - UInt64 result = 0; - for (;;) - { - char c = *s; - if (c < '0' || c > '7') - { - if (end != NULL) - *end = s; - return result; - } - result <<= 3; - result += (c - '0'); - s++; - } -} - -UInt64 ConvertHexStringToUInt64(const char *s, const char **end) -{ - UInt64 result = 0; - for (;;) - { - char c = *s; - UInt32 v; - if (c >= '0' && c <= '9') v = (c - '0'); - else if (c >= 'A' && c <= 'F') v = 10 + (c - 'A'); - else if (c >= 'a' && c <= 'f') v = 10 + (c - 'a'); - else - { - if (end != NULL) - *end = s; - return result; - } - result <<= 4; - result |= v; - s++; - } -} - - -UInt64 ConvertStringToUInt64(const wchar_t *s, const wchar_t **end) -{ - UInt64 result = 0; - for (;;) - { - wchar_t c = *s; - if (c < '0' || c > '9') - { - if (end != NULL) - *end = s; - return result; - } - result *= 10; - result += (c - '0'); - s++; - } -} - - -Int64 ConvertStringToInt64(const char *s, const char **end) -{ - if (*s == '-') - return -(Int64)ConvertStringToUInt64(s + 1, end); - return ConvertStringToUInt64(s, end); -} diff --git a/desmume/src/windows/7z/CPP/Common/StringToInt.h b/desmume/src/windows/7z/CPP/Common/StringToInt.h deleted file mode 100644 index 16a1a4fc8..000000000 --- a/desmume/src/windows/7z/CPP/Common/StringToInt.h +++ /dev/null @@ -1,18 +0,0 @@ -// Common/StringToInt.h - -#ifndef __COMMON_STRINGTOINT_H -#define __COMMON_STRINGTOINT_H - -#include -#include "Types.h" - -UInt64 ConvertStringToUInt64(const char *s, const char **end); -UInt64 ConvertOctStringToUInt64(const char *s, const char **end); -UInt64 ConvertHexStringToUInt64(const char *s, const char **end); -UInt64 ConvertStringToUInt64(const wchar_t *s, const wchar_t **end); - -Int64 ConvertStringToInt64(const char *s, const char **end); - -#endif - - diff --git a/desmume/src/windows/7z/CPP/Common/Types.h b/desmume/src/windows/7z/CPP/Common/Types.h deleted file mode 100644 index ba696772d..000000000 --- a/desmume/src/windows/7z/CPP/Common/Types.h +++ /dev/null @@ -1,14 +0,0 @@ -// Common/Types.h - -#ifndef __COMMON_TYPES_H -#define __COMMON_TYPES_H - -extern "C" -{ -#include "../../C/Types.h" -} - -typedef int HRes; - -#endif - diff --git a/desmume/src/windows/7z/CPP/Common/UTFConvert.cpp b/desmume/src/windows/7z/CPP/Common/UTFConvert.cpp deleted file mode 100644 index dae8f551b..000000000 --- a/desmume/src/windows/7z/CPP/Common/UTFConvert.cpp +++ /dev/null @@ -1,145 +0,0 @@ -// UTFConvert.cpp - -#include "StdAfx.h" - -#include "UTFConvert.h" -#include "Types.h" - -static const Byte kUtf8Limits[5] = { 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - -static Bool Utf8_To_Utf16(wchar_t *dest, size_t *destLen, const char *src, size_t srcLen) -{ - size_t destPos = 0, srcPos = 0; - for (;;) - { - Byte c; - int numAdds; - if (srcPos == srcLen) - { - *destLen = destPos; - return True; - } - c = (Byte)src[srcPos++]; - - if (c < 0x80) - { - if (dest) - dest[destPos] = (wchar_t)c; - destPos++; - continue; - } - if (c < 0xC0) - break; - for (numAdds = 1; numAdds < 5; numAdds++) - if (c < kUtf8Limits[numAdds]) - break; - UInt32 value = (c - kUtf8Limits[numAdds - 1]); - - do - { - Byte c2; - if (srcPos == srcLen) - break; - c2 = (Byte)src[srcPos++]; - if (c2 < 0x80 || c2 >= 0xC0) - break; - value <<= 6; - value |= (c2 - 0x80); - } - while (--numAdds != 0); - - if (value < 0x10000) - { - if (dest) - dest[destPos] = (wchar_t)value; - destPos++; - } - else - { - value -= 0x10000; - if (value >= 0x100000) - break; - if (dest) - { - dest[destPos + 0] = (wchar_t)(0xD800 + (value >> 10)); - dest[destPos + 1] = (wchar_t)(0xDC00 + (value & 0x3FF)); - } - destPos += 2; - } - } - *destLen = destPos; - return False; -} - -static Bool Utf16_To_Utf8(char *dest, size_t *destLen, const wchar_t *src, size_t srcLen) -{ - size_t destPos = 0, srcPos = 0; - for (;;) - { - unsigned numAdds; - UInt32 value; - if (srcPos == srcLen) - { - *destLen = destPos; - return True; - } - value = src[srcPos++]; - if (value < 0x80) - { - if (dest) - dest[destPos] = (char)value; - destPos++; - continue; - } - if (value >= 0xD800 && value < 0xE000) - { - UInt32 c2; - if (value >= 0xDC00 || srcPos == srcLen) - break; - c2 = src[srcPos++]; - if (c2 < 0xDC00 || c2 >= 0xE000) - break; - value = ((value - 0xD800) << 10) | (c2 - 0xDC00); - } - for (numAdds = 1; numAdds < 5; numAdds++) - if (value < (((UInt32)1) << (numAdds * 5 + 6))) - break; - if (dest) - dest[destPos] = (char)(kUtf8Limits[numAdds - 1] + (value >> (6 * numAdds))); - destPos++; - do - { - numAdds--; - if (dest) - dest[destPos] = (char)(0x80 + ((value >> (6 * numAdds)) & 0x3F)); - destPos++; - } - while (numAdds != 0); - } - *destLen = destPos; - return False; -} - -bool ConvertUTF8ToUnicode(const AString &src, UString &dest) -{ - dest.Empty(); - size_t destLen = 0; - Utf8_To_Utf16(NULL, &destLen, src, src.Length()); - wchar_t *p = dest.GetBuffer((int)destLen); - Bool res = Utf8_To_Utf16(p, &destLen, src, src.Length()); - p[destLen] = 0; - dest.ReleaseBuffer(); - return res ? true : false; -} - -bool ConvertUnicodeToUTF8(const UString &src, AString &dest) -{ - dest.Empty(); - size_t destLen = 0; - Utf16_To_Utf8(NULL, &destLen, src, src.Length()); - char *p = dest.GetBuffer((int)destLen); - Bool res = Utf16_To_Utf8(p, &destLen, src, src.Length()); - p[destLen] = 0; - dest.ReleaseBuffer(); - return res ? true : false; -} diff --git a/desmume/src/windows/7z/CPP/Common/UTFConvert.h b/desmume/src/windows/7z/CPP/Common/UTFConvert.h deleted file mode 100644 index d55310144..000000000 --- a/desmume/src/windows/7z/CPP/Common/UTFConvert.h +++ /dev/null @@ -1,11 +0,0 @@ -// Common/UTFConvert.h - -#ifndef __COMMON_UTFCONVERT_H -#define __COMMON_UTFCONVERT_H - -#include "MyString.h" - -bool ConvertUTF8ToUnicode(const AString &utfString, UString &resultString); -bool ConvertUnicodeToUTF8(const UString &unicodeString, AString &resultString); - -#endif diff --git a/desmume/src/windows/7z/CPP/Common/Wildcard.cpp b/desmume/src/windows/7z/CPP/Common/Wildcard.cpp deleted file mode 100644 index b4a86cadb..000000000 --- a/desmume/src/windows/7z/CPP/Common/Wildcard.cpp +++ /dev/null @@ -1,458 +0,0 @@ -// Common/Wildcard.cpp - -#include "StdAfx.h" - -#include "Wildcard.h" - -bool g_CaseSensitive = - #ifdef _WIN32 - false; - #else - true; - #endif - -static const wchar_t kAnyCharsChar = L'*'; -static const wchar_t kAnyCharChar = L'?'; - -#ifdef _WIN32 -static const wchar_t kDirDelimiter1 = L'\\'; -#endif -static const wchar_t kDirDelimiter2 = L'/'; - -static const UString kWildCardCharSet = L"?*"; - -static const UString kIllegalWildCardFileNameChars= - L"\x1\x2\x3\x4\x5\x6\x7\x8\x9\xA\xB\xC\xD\xE\xF" - L"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F" - L"\"/:<>\\|"; - - -static inline bool IsCharDirLimiter(wchar_t c) -{ - return ( - #ifdef _WIN32 - c == kDirDelimiter1 || - #endif - c == kDirDelimiter2); -} - -int CompareFileNames(const UString &s1, const UString &s2) -{ - if (g_CaseSensitive) - return s1.Compare(s2); - return s1.CompareNoCase(s2); -} - -// ----------------------------------------- -// this function compares name with mask -// ? - any char -// * - any char or empty - -static bool EnhancedMaskTest(const wchar_t *mask, const wchar_t *name) -{ - for (;;) - { - wchar_t m = *mask; - wchar_t c = *name; - if (m == 0) - return (c == 0); - if (m == kAnyCharsChar) - { - if (EnhancedMaskTest(mask + 1, name)) - return true; - if (c == 0) - return false; - } - else - { - if (m == kAnyCharChar) - { - if (c == 0) - return false; - } - else if (m != c) - if (g_CaseSensitive || MyCharUpper(m) != MyCharUpper(c)) - return false; - mask++; - } - name++; - } -} - -// -------------------------------------------------- -// Splits path to strings - -void SplitPathToParts(const UString &path, UStringVector &pathParts) -{ - pathParts.Clear(); - UString name; - int len = path.Length(); - if (len == 0) - return; - for (int i = 0; i < len; i++) - { - wchar_t c = path[i]; - if (IsCharDirLimiter(c)) - { - pathParts.Add(name); - name.Empty(); - } - else - name += c; - } - pathParts.Add(name); -} - -void SplitPathToParts(const UString &path, UString &dirPrefix, UString &name) -{ - int i; - for (i = path.Length() - 1; i >= 0; i--) - if (IsCharDirLimiter(path[i])) - break; - dirPrefix = path.Left(i + 1); - name = path.Mid(i + 1); -} - -UString ExtractDirPrefixFromPath(const UString &path) -{ - int i; - for (i = path.Length() - 1; i >= 0; i--) - if (IsCharDirLimiter(path[i])) - break; - return path.Left(i + 1); -} - -UString ExtractFileNameFromPath(const UString &path) -{ - int i; - for (i = path.Length() - 1; i >= 0; i--) - if (IsCharDirLimiter(path[i])) - break; - return path.Mid(i + 1); -} - - -bool CompareWildCardWithName(const UString &mask, const UString &name) -{ - return EnhancedMaskTest(mask, name); -} - -bool DoesNameContainWildCard(const UString &path) -{ - return (path.FindOneOf(kWildCardCharSet) >= 0); -} - - -// ----------------------------------------------------------' -// NWildcard - -namespace NWildcard { - - -/* -M = MaskParts.Size(); -N = TestNameParts.Size(); - - File Dir -ForFile req M<=N [N-M, N) - - nonreq M=N [0, M) - - -ForDir req M 1) - return true; - } - return false; -} - -bool CCensorNode::AreThereIncludeItems() const -{ - if (IncludeItems.Size() > 0) - return true; - for (int i = 0; i < SubNodes.Size(); i++) - if (SubNodes[i].AreThereIncludeItems()) - return true; - return false; -} - -bool CCensorNode::CheckPathCurrent(bool include, const UStringVector &pathParts, bool isFile) const -{ - const CObjectVector &items = include ? IncludeItems : ExcludeItems; - for (int i = 0; i < items.Size(); i++) - if (items[i].CheckPath(pathParts, isFile)) - return true; - return false; -} - -bool CCensorNode::CheckPath(UStringVector &pathParts, bool isFile, bool &include) const -{ - if (CheckPathCurrent(false, pathParts, isFile)) - { - include = false; - return true; - } - include = true; - bool finded = CheckPathCurrent(true, pathParts, isFile); - if (pathParts.Size() == 1) - return finded; - int index = FindSubNode(pathParts.Front()); - if (index >= 0) - { - UStringVector pathParts2 = pathParts; - pathParts2.Delete(0); - if (SubNodes[index].CheckPath(pathParts2, isFile, include)) - return true; - } - return finded; -} - -bool CCensorNode::CheckPath(const UString &path, bool isFile, bool &include) const -{ - UStringVector pathParts; - SplitPathToParts(path, pathParts); - return CheckPath(pathParts, isFile, include); -} - -bool CCensorNode::CheckPath(const UString &path, bool isFile) const -{ - bool include; - if (CheckPath(path, isFile, include)) - return include; - return false; -} - -bool CCensorNode::CheckPathToRoot(bool include, UStringVector &pathParts, bool isFile) const -{ - if (CheckPathCurrent(include, pathParts, isFile)) - return true; - if (Parent == 0) - return false; - pathParts.Insert(0, Name); - return Parent->CheckPathToRoot(include, pathParts, isFile); -} - -/* -bool CCensorNode::CheckPathToRoot(bool include, const UString &path, bool isFile) const -{ - UStringVector pathParts; - SplitPathToParts(path, pathParts); - return CheckPathToRoot(include, pathParts, isFile); -} -*/ - -void CCensorNode::AddItem2(bool include, const UString &path, bool recursive) -{ - if (path.IsEmpty()) - return; - bool forFile = true; - bool forFolder = true; - UString path2 = path; - if (IsCharDirLimiter(path[path.Length() - 1])) - { - path2.Delete(path.Length() - 1); - forFile = false; - } - AddItem(include, path2, recursive, forFile, forFolder); -} - -void CCensorNode::ExtendExclude(const CCensorNode &fromNodes) -{ - ExcludeItems += fromNodes.ExcludeItems; - for (int i = 0; i < fromNodes.SubNodes.Size(); i++) - { - const CCensorNode &node = fromNodes.SubNodes[i]; - int subNodeIndex = FindSubNode(node.Name); - if (subNodeIndex < 0) - subNodeIndex = SubNodes.Add(CCensorNode(node.Name, this)); - SubNodes[subNodeIndex].ExtendExclude(node); - } -} - -int CCensor::FindPrefix(const UString &prefix) const -{ - for (int i = 0; i < Pairs.Size(); i++) - if (CompareFileNames(Pairs[i].Prefix, prefix) == 0) - return i; - return -1; -} - -void CCensor::AddItem(bool include, const UString &path, bool recursive) -{ - UStringVector pathParts; - SplitPathToParts(path, pathParts); - bool forFile = true; - if (pathParts.Back().IsEmpty()) - { - forFile = false; - pathParts.DeleteBack(); - } - const UString &front = pathParts.Front(); - bool isAbs = false; - if (front.IsEmpty()) - isAbs = true; - else if (front.Length() == 2 && front[1] == L':') - isAbs = true; - else - { - for (int i = 0; i < pathParts.Size(); i++) - { - const UString &part = pathParts[i]; - if (part == L".." || part == L".") - { - isAbs = true; - break; - } - } - } - int numAbsParts = 0; - if (isAbs) - if (pathParts.Size() > 1) - numAbsParts = pathParts.Size() - 1; - else - numAbsParts = 1; - UString prefix; - for (int i = 0; i < numAbsParts; i++) - { - const UString &front = pathParts.Front(); - if (DoesNameContainWildCard(front)) - break; - prefix += front; - prefix += WCHAR_PATH_SEPARATOR; - pathParts.Delete(0); - } - int index = FindPrefix(prefix); - if (index < 0) - index = Pairs.Add(CPair(prefix)); - - CItem item; - item.PathParts = pathParts; - item.ForDir = true; - item.ForFile = forFile; - item.Recursive = recursive; - Pairs[index].Head.AddItem(include, item); -} - -bool CCensor::CheckPath(const UString &path, bool isFile) const -{ - bool finded = false; - for (int i = 0; i < Pairs.Size(); i++) - { - bool include; - if (Pairs[i].Head.CheckPath(path, isFile, include)) - { - if (!include) - return false; - finded = true; - } - } - return finded; -} - -void CCensor::ExtendExclude() -{ - int i; - for (i = 0; i < Pairs.Size(); i++) - if (Pairs[i].Prefix.IsEmpty()) - break; - if (i == Pairs.Size()) - return; - int index = i; - for (i = 0; i < Pairs.Size(); i++) - if (index != i) - Pairs[i].Head.ExtendExclude(Pairs[index].Head); -} - -} diff --git a/desmume/src/windows/7z/CPP/Common/Wildcard.h b/desmume/src/windows/7z/CPP/Common/Wildcard.h deleted file mode 100644 index e2a42c831..000000000 --- a/desmume/src/windows/7z/CPP/Common/Wildcard.h +++ /dev/null @@ -1,80 +0,0 @@ -// Common/Wildcard.h - -#ifndef __COMMON_WILDCARD_H -#define __COMMON_WILDCARD_H - -#include "MyString.h" - -int CompareFileNames(const UString &s1, const UString &s2); - -void SplitPathToParts(const UString &path, UStringVector &pathParts); -void SplitPathToParts(const UString &path, UString &dirPrefix, UString &name); -UString ExtractDirPrefixFromPath(const UString &path); -UString ExtractFileNameFromPath(const UString &path); -bool DoesNameContainWildCard(const UString &path); -bool CompareWildCardWithName(const UString &mask, const UString &name); - -namespace NWildcard { - -struct CItem -{ - UStringVector PathParts; - bool Recursive; - bool ForFile; - bool ForDir; - bool CheckPath(const UStringVector &pathParts, bool isFile) const; -}; - -class CCensorNode -{ - CCensorNode *Parent; - bool CheckPathCurrent(bool include, const UStringVector &pathParts, bool isFile) const; - void AddItemSimple(bool include, CItem &item); - bool CheckPath(UStringVector &pathParts, bool isFile, bool &include) const; -public: - CCensorNode(): Parent(0) { }; - CCensorNode(const UString &name, CCensorNode *parent): Name(name), Parent(parent) { }; - UString Name; - CObjectVector SubNodes; - CObjectVector IncludeItems; - CObjectVector ExcludeItems; - - int FindSubNode(const UString &path) const; - - void AddItem(bool include, CItem &item); - void AddItem(bool include, const UString &path, bool recursive, bool forFile, bool forDir); - void AddItem2(bool include, const UString &path, bool recursive); - - bool NeedCheckSubDirs() const; - bool AreThereIncludeItems() const; - - bool CheckPath(const UString &path, bool isFile, bool &include) const; - bool CheckPath(const UString &path, bool isFile) const; - - bool CheckPathToRoot(bool include, UStringVector &pathParts, bool isFile) const; - // bool CheckPathToRoot(const UString &path, bool isFile, bool include) const; - void ExtendExclude(const CCensorNode &fromNodes); -}; - -struct CPair -{ - UString Prefix; - CCensorNode Head; - CPair(const UString &prefix): Prefix(prefix) { }; -}; - -class CCensor -{ - int FindPrefix(const UString &prefix) const; -public: - CObjectVector Pairs; - bool AllAreRelative() const - { return (Pairs.Size() == 1 && Pairs.Front().Prefix.IsEmpty()); } - void AddItem(bool include, const UString &path, bool recursive); - bool CheckPath(const UString &path, bool isFile) const; - void ExtendExclude(); -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/Defs.h b/desmume/src/windows/7z/CPP/Windows/Defs.h deleted file mode 100644 index e8a655a4b..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Defs.h +++ /dev/null @@ -1,23 +0,0 @@ -// Windows/Defs.h - -#ifndef __WINDOWS_DEFS_H -#define __WINDOWS_DEFS_H - -inline bool BOOLToBool(BOOL value) - { return (value != FALSE); } - -#ifdef _WIN32 -inline bool LRESULTToBool(LRESULT value) - { return (value != FALSE); } -#endif - -inline BOOL BoolToBOOL(bool value) - { return (value ? TRUE: FALSE); } - -inline VARIANT_BOOL BoolToVARIANT_BOOL(bool value) - { return (value ? VARIANT_TRUE: VARIANT_FALSE); } - -inline bool VARIANT_BOOLToBool(VARIANT_BOOL value) - { return (value != VARIANT_FALSE); } - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/FileDir.cpp b/desmume/src/windows/7z/CPP/Windows/FileDir.cpp deleted file mode 100644 index 38eb1083c..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileDir.cpp +++ /dev/null @@ -1,841 +0,0 @@ -// Windows/FileDir.cpp - -#include "StdAfx.h" - -#include "FileDir.h" -#include "FileName.h" -#include "FileFind.h" -#include "Defs.h" -#ifndef _UNICODE -#include "../Common/StringConvert.h" -#endif - -#ifndef _UNICODE -extern bool g_IsNT; -#endif - -namespace NWindows { -namespace NFile { - -#if defined(WIN_LONG_PATH) && defined(_UNICODE) -#define WIN_LONG_PATH2 -#endif - -// SetCurrentDirectory doesn't support \\?\ prefix - -#ifdef WIN_LONG_PATH -bool GetLongPathBase(LPCWSTR fileName, UString &res); -bool GetLongPath(LPCWSTR fileName, UString &res); -#endif - -namespace NDirectory { - -#ifndef _UNICODE -static inline UINT GetCurrentCodePage() { return ::AreFileApisANSI() ? CP_ACP : CP_OEMCP; } -static UString GetUnicodePath(const CSysString &sysPath) - { return MultiByteToUnicodeString(sysPath, GetCurrentCodePage()); } -static CSysString GetSysPath(LPCWSTR sysPath) - { return UnicodeStringToMultiByte(sysPath, GetCurrentCodePage()); } -#endif - -bool MyGetWindowsDirectory(CSysString &path) -{ - UINT needLength = ::GetWindowsDirectory(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); -} - -bool MyGetSystemDirectory(CSysString &path) -{ - UINT needLength = ::GetSystemDirectory(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); -} - -#ifndef _UNICODE -bool MyGetWindowsDirectory(UString &path) -{ - if (g_IsNT) - { - UINT needLength = ::GetWindowsDirectoryW(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); - } - CSysString sysPath; - if (!MyGetWindowsDirectory(sysPath)) - return false; - path = GetUnicodePath(sysPath); - return true; -} - -bool MyGetSystemDirectory(UString &path) -{ - if (g_IsNT) - { - UINT needLength = ::GetSystemDirectoryW(path.GetBuffer(MAX_PATH + 1), MAX_PATH + 1); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); - } - CSysString sysPath; - if (!MyGetSystemDirectory(sysPath)) - return false; - path = GetUnicodePath(sysPath); - return true; -} -#endif - -bool SetDirTime(LPCWSTR fileName, const FILETIME *cTime, const FILETIME *aTime, const FILETIME *mTime) -{ - #ifndef _UNICODE - if (!g_IsNT) - { - ::SetLastError(ERROR_CALL_NOT_IMPLEMENTED); - return false; - } - #endif - HANDLE hDir = ::CreateFileW(fileName, GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - #ifdef WIN_LONG_PATH - if (hDir == INVALID_HANDLE_VALUE) - { - UString longPath; - if (GetLongPath(fileName, longPath)) - hDir = ::CreateFileW(longPath, GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - } - #endif - - bool res = false; - if (hDir != INVALID_HANDLE_VALUE) - { - res = BOOLToBool(::SetFileTime(hDir, cTime, aTime, mTime)); - ::CloseHandle(hDir); - } - return res; -} - -bool MySetFileAttributes(LPCTSTR fileName, DWORD fileAttributes) -{ - if (::SetFileAttributes(fileName, fileAttributes)) - return true; - #ifdef WIN_LONG_PATH2 - UString longPath; - if (GetLongPath(fileName, longPath)) - return BOOLToBool(::SetFileAttributesW(longPath, fileAttributes)); - #endif - return false; -} - -bool MyRemoveDirectory(LPCTSTR pathName) -{ - if (::RemoveDirectory(pathName)) - return true; - #ifdef WIN_LONG_PATH2 - UString longPath; - if (GetLongPath(pathName, longPath)) - return BOOLToBool(::RemoveDirectoryW(longPath)); - #endif - return false; -} - -#ifdef WIN_LONG_PATH -bool GetLongPaths(LPCWSTR s1, LPCWSTR s2, UString &d1, UString &d2) -{ - if (!GetLongPathBase(s1, d1) || !GetLongPathBase(s2, d2)) - return false; - if (d1.IsEmpty() && d2.IsEmpty()) return false; - if (d1.IsEmpty()) d1 = s1; - if (d2.IsEmpty()) d2 = s2; - return true; -} -#endif - -bool MyMoveFile(LPCTSTR existFileName, LPCTSTR newFileName) -{ - if (::MoveFile(existFileName, newFileName)) - return true; - #ifdef WIN_LONG_PATH2 - UString d1, d2; - if (GetLongPaths(existFileName, newFileName, d1, d2)) - return BOOLToBool(::MoveFileW(d1, d2)); - #endif - return false; -} - -#ifndef _UNICODE -bool MySetFileAttributes(LPCWSTR fileName, DWORD fileAttributes) -{ - if (!g_IsNT) - return MySetFileAttributes(GetSysPath(fileName), fileAttributes); - if (::SetFileAttributesW(fileName, fileAttributes)) - return true; - #ifdef WIN_LONG_PATH - UString longPath; - if (GetLongPath(fileName, longPath)) - return BOOLToBool(::SetFileAttributesW(longPath, fileAttributes)); - #endif - return false; -} - - -bool MyRemoveDirectory(LPCWSTR pathName) -{ - if (!g_IsNT) - return MyRemoveDirectory(GetSysPath(pathName)); - if (::RemoveDirectoryW(pathName)) - return true; - #ifdef WIN_LONG_PATH - UString longPath; - if (GetLongPath(pathName, longPath)) - return BOOLToBool(::RemoveDirectoryW(longPath)); - #endif - return false; -} - -bool MyMoveFile(LPCWSTR existFileName, LPCWSTR newFileName) -{ - if (!g_IsNT) - return MyMoveFile(GetSysPath(existFileName), GetSysPath(newFileName)); - if (::MoveFileW(existFileName, newFileName)) - return true; - #ifdef WIN_LONG_PATH - UString d1, d2; - if (GetLongPaths(existFileName, newFileName, d1, d2)) - return BOOLToBool(::MoveFileW(d1, d2)); - #endif - return false; -} -#endif - -bool MyCreateDirectory(LPCTSTR pathName) -{ - if (::CreateDirectory(pathName, NULL)) - return true; - #ifdef WIN_LONG_PATH2 - if (::GetLastError() != ERROR_ALREADY_EXISTS) - { - UString longPath; - if (GetLongPath(pathName, longPath)) - return BOOLToBool(::CreateDirectoryW(longPath, NULL)); - } - #endif - return false; -} - -#ifndef _UNICODE -bool MyCreateDirectory(LPCWSTR pathName) -{ - if (!g_IsNT) - return MyCreateDirectory(GetSysPath(pathName)); - if (::CreateDirectoryW(pathName, NULL)) - return true; - #ifdef WIN_LONG_PATH - if (::GetLastError() != ERROR_ALREADY_EXISTS) - { - UString longPath; - if (GetLongPath(pathName, longPath)) - return BOOLToBool(::CreateDirectoryW(longPath, NULL)); - } - #endif - return false; -} -#endif - -/* -bool CreateComplexDirectory(LPCTSTR pathName) -{ - NName::CParsedPath path; - path.ParsePath(pathName); - CSysString fullPath = path.Prefix; - DWORD errorCode = ERROR_SUCCESS; - for (int i = 0; i < path.PathParts.Size(); i++) - { - const CSysString &string = path.PathParts[i]; - if (string.IsEmpty()) - { - if (i != path.PathParts.Size() - 1) - return false; - return true; - } - fullPath += path.PathParts[i]; - if (!MyCreateDirectory(fullPath)) - { - DWORD errorCode = GetLastError(); - if (errorCode != ERROR_ALREADY_EXISTS) - return false; - } - fullPath += NName::kDirDelimiter; - } - return true; -} -*/ - -bool CreateComplexDirectory(LPCTSTR _aPathName) -{ - CSysString pathName = _aPathName; - int pos = pathName.ReverseFind(TEXT(CHAR_PATH_SEPARATOR)); - if (pos > 0 && pos == pathName.Length() - 1) - { - if (pathName.Length() == 3 && pathName[1] == ':') - return true; // Disk folder; - pathName.Delete(pos); - } - CSysString pathName2 = pathName; - pos = pathName.Length(); - for (;;) - { - if (MyCreateDirectory(pathName)) - break; - if (::GetLastError() == ERROR_ALREADY_EXISTS) - { - NFind::CFileInfo fileInfo; - if (!NFind::FindFile(pathName, fileInfo)) // For network folders - return true; - if (!fileInfo.IsDir()) - return false; - break; - } - pos = pathName.ReverseFind(TEXT(CHAR_PATH_SEPARATOR)); - if (pos < 0 || pos == 0) - return false; - if (pathName[pos - 1] == ':') - return false; - pathName = pathName.Left(pos); - } - pathName = pathName2; - while (pos < pathName.Length()) - { - pos = pathName.Find(TEXT(CHAR_PATH_SEPARATOR), pos + 1); - if (pos < 0) - pos = pathName.Length(); - if (!MyCreateDirectory(pathName.Left(pos))) - return false; - } - return true; -} - -#ifndef _UNICODE - -bool CreateComplexDirectory(LPCWSTR _aPathName) -{ - UString pathName = _aPathName; - int pos = pathName.ReverseFind(WCHAR_PATH_SEPARATOR); - if (pos > 0 && pos == pathName.Length() - 1) - { - if (pathName.Length() == 3 && pathName[1] == L':') - return true; // Disk folder; - pathName.Delete(pos); - } - UString pathName2 = pathName; - pos = pathName.Length(); - for (;;) - { - if (MyCreateDirectory(pathName)) - break; - if (::GetLastError() == ERROR_ALREADY_EXISTS) - { - NFind::CFileInfoW fileInfo; - if (!NFind::FindFile(pathName, fileInfo)) // For network folders - return true; - if (!fileInfo.IsDir()) - return false; - break; - } - pos = pathName.ReverseFind(WCHAR_PATH_SEPARATOR); - if (pos < 0 || pos == 0) - return false; - if (pathName[pos - 1] == L':') - return false; - pathName = pathName.Left(pos); - } - pathName = pathName2; - while (pos < pathName.Length()) - { - pos = pathName.Find(WCHAR_PATH_SEPARATOR, pos + 1); - if (pos < 0) - pos = pathName.Length(); - if (!MyCreateDirectory(pathName.Left(pos))) - return false; - } - return true; -} - -#endif - -bool DeleteFileAlways(LPCTSTR name) -{ - if (!MySetFileAttributes(name, 0)) - return false; - if (::DeleteFile(name)) - return true; - #ifdef WIN_LONG_PATH2 - UString longPath; - if (GetLongPath(name, longPath)) - return BOOLToBool(::DeleteFileW(longPath)); - #endif - return false; -} - -#ifndef _UNICODE -bool DeleteFileAlways(LPCWSTR name) -{ - if (!g_IsNT) - return DeleteFileAlways(GetSysPath(name)); - if (!MySetFileAttributes(name, 0)) - return false; - if (::DeleteFileW(name)) - return true; - #ifdef WIN_LONG_PATH - UString longPath; - if (GetLongPath(name, longPath)) - return BOOLToBool(::DeleteFileW(longPath)); - #endif - return false; -} -#endif - -static bool RemoveDirectorySubItems2(const CSysString pathPrefix, const NFind::CFileInfo &fileInfo) -{ - if (fileInfo.IsDir()) - return RemoveDirectoryWithSubItems(pathPrefix + fileInfo.Name); - return DeleteFileAlways(pathPrefix + fileInfo.Name); -} - -bool RemoveDirectoryWithSubItems(const CSysString &path) -{ - NFind::CFileInfo fileInfo; - CSysString pathPrefix = path + NName::kDirDelimiter; - { - NFind::CEnumerator enumerator(pathPrefix + TCHAR(NName::kAnyStringWildcard)); - while (enumerator.Next(fileInfo)) - if (!RemoveDirectorySubItems2(pathPrefix, fileInfo)) - return false; - } - if (!MySetFileAttributes(path, 0)) - return false; - return MyRemoveDirectory(path); -} - -#ifndef _UNICODE -static bool RemoveDirectorySubItems2(const UString pathPrefix, const NFind::CFileInfoW &fileInfo) -{ - if (fileInfo.IsDir()) - return RemoveDirectoryWithSubItems(pathPrefix + fileInfo.Name); - return DeleteFileAlways(pathPrefix + fileInfo.Name); -} -bool RemoveDirectoryWithSubItems(const UString &path) -{ - NFind::CFileInfoW fileInfo; - UString pathPrefix = path + UString(NName::kDirDelimiter); - { - NFind::CEnumeratorW enumerator(pathPrefix + UString(NName::kAnyStringWildcard)); - while (enumerator.Next(fileInfo)) - if (!RemoveDirectorySubItems2(pathPrefix, fileInfo)) - return false; - } - if (!MySetFileAttributes(path, 0)) - return false; - return MyRemoveDirectory(path); -} -#endif - -#ifndef _WIN32_WCE - -bool MyGetShortPathName(LPCTSTR longPath, CSysString &shortPath) -{ - DWORD needLength = ::GetShortPathName(longPath, shortPath.GetBuffer(MAX_PATH + 1), MAX_PATH + 1); - shortPath.ReleaseBuffer(); - return (needLength > 0 && needLength < MAX_PATH); -} - -bool MyGetFullPathName(LPCTSTR fileName, CSysString &resultPath, int &fileNamePartStartIndex) -{ - resultPath.Empty(); - LPTSTR fileNamePointer = 0; - LPTSTR buffer = resultPath.GetBuffer(MAX_PATH); - DWORD needLength = ::GetFullPathName(fileName, MAX_PATH + 1, buffer, &fileNamePointer); - resultPath.ReleaseBuffer(); - if (needLength == 0) - return false; - if (needLength >= MAX_PATH) - { - #ifdef WIN_LONG_PATH2 - needLength++; - buffer = resultPath.GetBuffer(needLength + 1); - DWORD needLength2 = ::GetFullPathNameW(fileName, needLength, buffer, &fileNamePointer); - resultPath.ReleaseBuffer(); - if (needLength2 == 0 || needLength2 > needLength) - #endif - return false; - } - if (fileNamePointer == 0) - fileNamePartStartIndex = lstrlen(fileName); - else - fileNamePartStartIndex = (int)(fileNamePointer - buffer); - return true; -} - -#ifndef _UNICODE -bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath, int &fileNamePartStartIndex) -{ - resultPath.Empty(); - if (g_IsNT) - { - LPWSTR fileNamePointer = 0; - LPWSTR buffer = resultPath.GetBuffer(MAX_PATH); - DWORD needLength = ::GetFullPathNameW(fileName, MAX_PATH + 1, buffer, &fileNamePointer); - resultPath.ReleaseBuffer(); - if (needLength == 0) - return false; - if (needLength >= MAX_PATH) - { - #ifdef WIN_LONG_PATH - needLength++; - buffer = resultPath.GetBuffer(needLength + 1); - DWORD needLength2 = ::GetFullPathNameW(fileName, needLength, buffer, &fileNamePointer); - resultPath.ReleaseBuffer(); - if (needLength2 == 0 || needLength2 > needLength) - #endif - return false; - } - if (fileNamePointer == 0) - fileNamePartStartIndex = MyStringLen(fileName); - else - fileNamePartStartIndex = (int)(fileNamePointer - buffer); - } - else - { - CSysString sysPath; - if (!MyGetFullPathName(GetSysPath(fileName), sysPath, fileNamePartStartIndex)) - return false; - UString resultPath1 = GetUnicodePath(sysPath.Left(fileNamePartStartIndex)); - UString resultPath2 = GetUnicodePath(sysPath.Mid(fileNamePartStartIndex)); - fileNamePartStartIndex = resultPath1.Length(); - resultPath = resultPath1 + resultPath2; - } - return true; -} -#endif - - -bool MyGetFullPathName(LPCTSTR fileName, CSysString &path) -{ - int index; - return MyGetFullPathName(fileName, path, index); -} - -#ifndef _UNICODE -bool MyGetFullPathName(LPCWSTR fileName, UString &path) -{ - int index; - return MyGetFullPathName(fileName, path, index); -} -#endif - -bool GetOnlyName(LPCTSTR fileName, CSysString &resultName) -{ - int index; - if (!MyGetFullPathName(fileName, resultName, index)) - return false; - resultName = resultName.Mid(index); - return true; -} - -#ifndef _UNICODE -bool GetOnlyName(LPCWSTR fileName, UString &resultName) -{ - int index; - if (!MyGetFullPathName(fileName, resultName, index)) - return false; - resultName = resultName.Mid(index); - return true; -} -#endif - -bool GetOnlyDirPrefix(LPCTSTR fileName, CSysString &resultName) -{ - int index; - if (!MyGetFullPathName(fileName, resultName, index)) - return false; - resultName = resultName.Left(index); - return true; -} - -#ifndef _UNICODE -bool GetOnlyDirPrefix(LPCWSTR fileName, UString &resultName) -{ - int index; - if (!MyGetFullPathName(fileName, resultName, index)) - return false; - resultName = resultName.Left(index); - return true; -} -#endif - -bool MyGetCurrentDirectory(CSysString &path) -{ - DWORD needLength = ::GetCurrentDirectory(MAX_PATH + 1, path.GetBuffer(MAX_PATH + 1)); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); -} - -#ifndef _UNICODE -bool MySetCurrentDirectory(LPCWSTR path) -{ - if (g_IsNT) - return BOOLToBool(::SetCurrentDirectoryW(path)); - return MySetCurrentDirectory(GetSysPath(path)); -} -bool MyGetCurrentDirectory(UString &path) -{ - if (g_IsNT) - { - DWORD needLength = ::GetCurrentDirectoryW(MAX_PATH + 1, path.GetBuffer(MAX_PATH + 1)); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); - } - CSysString sysPath; - if (!MyGetCurrentDirectory(sysPath)) - return false; - path = GetUnicodePath(sysPath); - return true; -} -#endif -#endif - -bool MySearchPath(LPCTSTR path, LPCTSTR fileName, LPCTSTR extension, - CSysString &resultPath, UINT32 &filePart) -{ - LPTSTR filePartPointer; - DWORD value = ::SearchPath(path, fileName, extension, - MAX_PATH, resultPath.GetBuffer(MAX_PATH + 1), &filePartPointer); - filePart = (UINT32)(filePartPointer - (LPCTSTR)resultPath); - resultPath.ReleaseBuffer(); - return (value > 0 && value <= MAX_PATH); -} - -#ifndef _UNICODE -bool MySearchPath(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension, - UString &resultPath, UINT32 &filePart) -{ - if (g_IsNT) - { - LPWSTR filePartPointer = 0; - DWORD value = ::SearchPathW(path, fileName, extension, - MAX_PATH, resultPath.GetBuffer(MAX_PATH + 1), &filePartPointer); - filePart = (UINT32)(filePartPointer - (LPCWSTR)resultPath); - resultPath.ReleaseBuffer(); - return (value > 0 && value <= MAX_PATH); - } - - CSysString sysPath; - if (!MySearchPath( - path != 0 ? (LPCTSTR)GetSysPath(path): 0, - fileName != 0 ? (LPCTSTR)GetSysPath(fileName): 0, - extension != 0 ? (LPCTSTR)GetSysPath(extension): 0, - sysPath, filePart)) - return false; - UString resultPath1 = GetUnicodePath(sysPath.Left(filePart)); - UString resultPath2 = GetUnicodePath(sysPath.Mid(filePart)); - filePart = resultPath1.Length(); - resultPath = resultPath1 + resultPath2; - return true; -} -#endif - -bool MyGetTempPath(CSysString &path) -{ - DWORD needLength = ::GetTempPath(MAX_PATH + 1, path.GetBuffer(MAX_PATH + 1)); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); -} - -#ifndef _UNICODE -bool MyGetTempPath(UString &path) -{ - path.Empty(); - if (g_IsNT) - { - DWORD needLength = ::GetTempPathW(MAX_PATH + 1, path.GetBuffer(MAX_PATH + 1)); - path.ReleaseBuffer(); - return (needLength > 0 && needLength <= MAX_PATH); - } - CSysString sysPath; - if (!MyGetTempPath(sysPath)) - return false; - path = GetUnicodePath(sysPath); - return true; -} -#endif - -UINT MyGetTempFileName(LPCTSTR dirPath, LPCTSTR prefix, CSysString &path) -{ - UINT number = ::GetTempFileName(dirPath, prefix, 0, path.GetBuffer(MAX_PATH + 1)); - path.ReleaseBuffer(); - return number; -} - -#ifndef _UNICODE -UINT MyGetTempFileName(LPCWSTR dirPath, LPCWSTR prefix, UString &path) -{ - if (g_IsNT) - { - UINT number = ::GetTempFileNameW(dirPath, prefix, 0, path.GetBuffer(MAX_PATH)); - path.ReleaseBuffer(); - return number; - } - CSysString sysPath; - UINT number = MyGetTempFileName( - dirPath ? (LPCTSTR)GetSysPath(dirPath): 0, - prefix ? (LPCTSTR)GetSysPath(prefix): 0, - sysPath); - path = GetUnicodePath(sysPath); - return number; -} -#endif - -UINT CTempFile::Create(LPCTSTR dirPath, LPCTSTR prefix, CSysString &resultPath) -{ - Remove(); - UINT number = MyGetTempFileName(dirPath, prefix, resultPath); - if (number != 0) - { - _fileName = resultPath; - _mustBeDeleted = true; - } - return number; -} - -bool CTempFile::Create(LPCTSTR prefix, CSysString &resultPath) -{ - CSysString tempPath; - if (!MyGetTempPath(tempPath)) - return false; - if (Create(tempPath, prefix, resultPath) != 0) - return true; - if (!MyGetWindowsDirectory(tempPath)) - return false; - return (Create(tempPath, prefix, resultPath) != 0); -} - -bool CTempFile::Remove() -{ - if (!_mustBeDeleted) - return true; - _mustBeDeleted = !DeleteFileAlways(_fileName); - return !_mustBeDeleted; -} - -#ifndef _UNICODE - -UINT CTempFileW::Create(LPCWSTR dirPath, LPCWSTR prefix, UString &resultPath) -{ - Remove(); - UINT number = MyGetTempFileName(dirPath, prefix, resultPath); - if (number != 0) - { - _fileName = resultPath; - _mustBeDeleted = true; - } - return number; -} - -bool CTempFileW::Create(LPCWSTR prefix, UString &resultPath) -{ - UString tempPath; - if (!MyGetTempPath(tempPath)) - return false; - if (Create(tempPath, prefix, resultPath) != 0) - return true; - if (!MyGetWindowsDirectory(tempPath)) - return false; - return (Create(tempPath, prefix, resultPath) != 0); -} - -bool CTempFileW::Remove() -{ - if (!_mustBeDeleted) - return true; - _mustBeDeleted = !DeleteFileAlways(_fileName); - return !_mustBeDeleted; -} - -#endif - -bool CreateTempDirectory(LPCTSTR prefix, CSysString &dirName) -{ - /* - CSysString prefix = tempPath + prefixChars; - CRandom random; - random.Init(); - */ - for (;;) - { - CTempFile tempFile; - if (!tempFile.Create(prefix, dirName)) - return false; - if (!::DeleteFile(dirName)) - return false; - /* - UINT32 randomNumber = random.Generate(); - TCHAR randomNumberString[32]; - _stprintf(randomNumberString, _T("%04X"), randomNumber); - dirName = prefix + randomNumberString; - */ - if (NFind::DoesFileExist(dirName)) - continue; - if (MyCreateDirectory(dirName)) - return true; - if (::GetLastError() != ERROR_ALREADY_EXISTS) - return false; - } -} - -bool CTempDirectory::Create(LPCTSTR prefix) -{ - Remove(); - return (_mustBeDeleted = CreateTempDirectory(prefix, _tempDir)); -} - -#ifndef _UNICODE - -bool CreateTempDirectory(LPCWSTR prefix, UString &dirName) -{ - /* - CSysString prefix = tempPath + prefixChars; - CRandom random; - random.Init(); - */ - for (;;) - { - CTempFileW tempFile; - if (!tempFile.Create(prefix, dirName)) - return false; - if (!DeleteFileAlways(dirName)) - return false; - /* - UINT32 randomNumber = random.Generate(); - TCHAR randomNumberString[32]; - _stprintf(randomNumberString, _T("%04X"), randomNumber); - dirName = prefix + randomNumberString; - */ - if (NFind::DoesFileExist(dirName)) - continue; - if (MyCreateDirectory(dirName)) - return true; - if (::GetLastError() != ERROR_ALREADY_EXISTS) - return false; - } -} - -bool CTempDirectoryW::Create(LPCWSTR prefix) -{ - Remove(); - return (_mustBeDeleted = CreateTempDirectory(prefix, _tempDir)); -} - -#endif - -}}} diff --git a/desmume/src/windows/7z/CPP/Windows/FileDir.h b/desmume/src/windows/7z/CPP/Windows/FileDir.h deleted file mode 100644 index ea49264b5..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileDir.h +++ /dev/null @@ -1,178 +0,0 @@ -// Windows/FileDir.h - -#ifndef __WINDOWS_FILEDIR_H -#define __WINDOWS_FILEDIR_H - -#include "../Common/MyString.h" -#include "Defs.h" - -namespace NWindows { -namespace NFile { -namespace NDirectory { - -#ifdef WIN_LONG_PATH -bool GetLongPaths(LPCWSTR s1, LPCWSTR s2, UString &d1, UString &d2); -#endif - -bool MyGetWindowsDirectory(CSysString &path); -bool MyGetSystemDirectory(CSysString &path); -#ifndef _UNICODE -bool MyGetWindowsDirectory(UString &path); -bool MyGetSystemDirectory(UString &path); -#endif - -bool SetDirTime(LPCWSTR fileName, const FILETIME *cTime, const FILETIME *aTime, const FILETIME *mTime); - -bool MySetFileAttributes(LPCTSTR fileName, DWORD fileAttributes); -bool MyMoveFile(LPCTSTR existFileName, LPCTSTR newFileName); -bool MyRemoveDirectory(LPCTSTR pathName); -bool MyCreateDirectory(LPCTSTR pathName); -bool CreateComplexDirectory(LPCTSTR pathName); -bool DeleteFileAlways(LPCTSTR name); -bool RemoveDirectoryWithSubItems(const CSysString &path); - -#ifndef _UNICODE -bool MySetFileAttributes(LPCWSTR fileName, DWORD fileAttributes); -bool MyMoveFile(LPCWSTR existFileName, LPCWSTR newFileName); -bool MyRemoveDirectory(LPCWSTR pathName); -bool MyCreateDirectory(LPCWSTR pathName); -bool CreateComplexDirectory(LPCWSTR pathName); -bool DeleteFileAlways(LPCWSTR name); -bool RemoveDirectoryWithSubItems(const UString &path); -#endif - -#ifndef _WIN32_WCE -bool MyGetShortPathName(LPCTSTR longPath, CSysString &shortPath); - -bool MyGetFullPathName(LPCTSTR fileName, CSysString &resultPath, - int &fileNamePartStartIndex); -bool MyGetFullPathName(LPCTSTR fileName, CSysString &resultPath); -bool GetOnlyName(LPCTSTR fileName, CSysString &resultName); -bool GetOnlyDirPrefix(LPCTSTR fileName, CSysString &resultName); -#ifndef _UNICODE -bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath, - int &fileNamePartStartIndex); -bool MyGetFullPathName(LPCWSTR fileName, UString &resultPath); -bool GetOnlyName(LPCWSTR fileName, UString &resultName); -bool GetOnlyDirPrefix(LPCWSTR fileName, UString &resultName); -#endif - -inline bool MySetCurrentDirectory(LPCTSTR path) - { return BOOLToBool(::SetCurrentDirectory(path)); } -bool MyGetCurrentDirectory(CSysString &resultPath); -#ifndef _UNICODE -bool MySetCurrentDirectory(LPCWSTR path); -bool MyGetCurrentDirectory(UString &resultPath); -#endif -#endif - -bool MySearchPath(LPCTSTR path, LPCTSTR fileName, LPCTSTR extension, - CSysString &resultPath, UINT32 &filePart); -#ifndef _UNICODE -bool MySearchPath(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension, - UString &resultPath, UINT32 &filePart); -#endif - -inline bool MySearchPath(LPCTSTR path, LPCTSTR fileName, LPCTSTR extension, - CSysString &resultPath) -{ - UINT32 value; - return MySearchPath(path, fileName, extension, resultPath, value); -} - -#ifndef _UNICODE -inline bool MySearchPath(LPCWSTR path, LPCWSTR fileName, LPCWSTR extension, - UString &resultPath) -{ - UINT32 value; - return MySearchPath(path, fileName, extension, resultPath, value); -} -#endif - -bool MyGetTempPath(CSysString &resultPath); -#ifndef _UNICODE -bool MyGetTempPath(UString &resultPath); -#endif - -UINT MyGetTempFileName(LPCTSTR dirPath, LPCTSTR prefix, CSysString &resultPath); -#ifndef _UNICODE -UINT MyGetTempFileName(LPCWSTR dirPath, LPCWSTR prefix, UString &resultPath); -#endif - -class CTempFile -{ - bool _mustBeDeleted; - CSysString _fileName; -public: - CTempFile(): _mustBeDeleted(false) {} - ~CTempFile() { Remove(); } - void DisableDeleting() { _mustBeDeleted = false; } - UINT Create(LPCTSTR dirPath, LPCTSTR prefix, CSysString &resultPath); - bool Create(LPCTSTR prefix, CSysString &resultPath); - bool Remove(); -}; - -#ifdef _UNICODE -typedef CTempFile CTempFileW; -#else -class CTempFileW -{ - bool _mustBeDeleted; - UString _fileName; -public: - CTempFileW(): _mustBeDeleted(false) {} - ~CTempFileW() { Remove(); } - void DisableDeleting() { _mustBeDeleted = false; } - UINT Create(LPCWSTR dirPath, LPCWSTR prefix, UString &resultPath); - bool Create(LPCWSTR prefix, UString &resultPath); - bool Remove(); -}; -#endif - -bool CreateTempDirectory(LPCTSTR prefixChars, CSysString &dirName); - -class CTempDirectory -{ - bool _mustBeDeleted; - CSysString _tempDir; -public: - const CSysString &GetPath() const { return _tempDir; } - CTempDirectory(): _mustBeDeleted(false) {} - ~CTempDirectory() { Remove(); } - bool Create(LPCTSTR prefix) ; - bool Remove() - { - if (!_mustBeDeleted) - return true; - _mustBeDeleted = !RemoveDirectoryWithSubItems(_tempDir); - return (!_mustBeDeleted); - } - void DisableDeleting() { _mustBeDeleted = false; } -}; - -#ifdef _UNICODE -typedef CTempDirectory CTempDirectoryW; -#else -class CTempDirectoryW -{ - bool _mustBeDeleted; - UString _tempDir; -public: - const UString &GetPath() const { return _tempDir; } - CTempDirectoryW(): _mustBeDeleted(false) {} - ~CTempDirectoryW() { Remove(); } - bool Create(LPCWSTR prefix) ; - bool Remove() - { - if (!_mustBeDeleted) - return true; - _mustBeDeleted = !RemoveDirectoryWithSubItems(_tempDir); - return (!_mustBeDeleted); - } - void DisableDeleting() { _mustBeDeleted = false; } -}; -#endif - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/FileFind.cpp b/desmume/src/windows/7z/CPP/Windows/FileFind.cpp deleted file mode 100644 index 7e6b30a6b..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileFind.cpp +++ /dev/null @@ -1,402 +0,0 @@ -// Windows/FileFind.cpp - -#include "StdAfx.h" - -#include "FileFind.h" -#ifndef _UNICODE -#include "../Common/StringConvert.h" -#endif - -#ifndef _UNICODE -extern bool g_IsNT; -#endif - -namespace NWindows { -namespace NFile { - -#if defined(WIN_LONG_PATH) && defined(_UNICODE) -#define WIN_LONG_PATH2 -#endif - -bool GetLongPath(LPCWSTR fileName, UString &res); - -namespace NFind { - -static const TCHAR kDot = TEXT('.'); - -bool CFileInfo::IsDots() const -{ - if (!IsDir() || Name.IsEmpty()) - return false; - if (Name[0] != kDot) - return false; - return Name.Length() == 1 || (Name[1] == kDot && Name.Length() == 2); -} - -#ifndef _UNICODE -bool CFileInfoW::IsDots() const -{ - if (!IsDir() || Name.IsEmpty()) - return false; - if (Name[0] != kDot) - return false; - return Name.Length() == 1 || (Name[1] == kDot && Name.Length() == 2); -} -#endif - -static void ConvertWIN32_FIND_DATA_To_FileInfo(const WIN32_FIND_DATA &fd, CFileInfo &fi) -{ - fi.Attrib = fd.dwFileAttributes; - fi.CTime = fd.ftCreationTime; - fi.ATime = fd.ftLastAccessTime; - fi.MTime = fd.ftLastWriteTime; - fi.Size = (((UInt64)fd.nFileSizeHigh) << 32) + fd.nFileSizeLow; - fi.Name = fd.cFileName; - #ifndef _WIN32_WCE - fi.ReparseTag = fd.dwReserved0; - #else - fi.ObjectID = fd.dwOID; - #endif -} - -#ifndef _UNICODE - -static inline UINT GetCurrentCodePage() { return ::AreFileApisANSI() ? CP_ACP : CP_OEMCP; } - -static void ConvertWIN32_FIND_DATA_To_FileInfo(const WIN32_FIND_DATAW &fd, CFileInfoW &fi) -{ - fi.Attrib = fd.dwFileAttributes; - fi.CTime = fd.ftCreationTime; - fi.ATime = fd.ftLastAccessTime; - fi.MTime = fd.ftLastWriteTime; - fi.Size = (((UInt64)fd.nFileSizeHigh) << 32) + fd.nFileSizeLow; - fi.Name = fd.cFileName; - #ifndef _WIN32_WCE - fi.ReparseTag = fd.dwReserved0; - #else - fi.ObjectID = fd.dwOID; - #endif -} - -static void ConvertWIN32_FIND_DATA_To_FileInfo(const WIN32_FIND_DATA &fd, CFileInfoW &fi) -{ - fi.Attrib = fd.dwFileAttributes; - fi.CTime = fd.ftCreationTime; - fi.ATime = fd.ftLastAccessTime; - fi.MTime = fd.ftLastWriteTime; - fi.Size = (((UInt64)fd.nFileSizeHigh) << 32) + fd.nFileSizeLow; - fi.Name = GetUnicodeString(fd.cFileName, GetCurrentCodePage()); - #ifndef _WIN32_WCE - fi.ReparseTag = fd.dwReserved0; - #else - fi.ObjectID = fd.dwOID; - #endif -} -#endif - -//////////////////////////////// -// CFindFile - -bool CFindFile::Close() -{ - if (_handle == INVALID_HANDLE_VALUE) - return true; - if (!::FindClose(_handle)) - return false; - _handle = INVALID_HANDLE_VALUE; - return true; -} - - -bool CFindFile::FindFirst(LPCTSTR wildcard, CFileInfo &fileInfo) -{ - if (!Close()) - return false; - WIN32_FIND_DATA fd; - _handle = ::FindFirstFile(wildcard, &fd); - #ifdef WIN_LONG_PATH2 - if (_handle == INVALID_HANDLE_VALUE) - { - UString longPath; - if (GetLongPath(wildcard, longPath)) - _handle = ::FindFirstFileW(longPath, &fd); - } - #endif - if (_handle == INVALID_HANDLE_VALUE) - return false; - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - return true; -} - -#ifndef _UNICODE -bool CFindFile::FindFirst(LPCWSTR wildcard, CFileInfoW &fileInfo) -{ - if (!Close()) - return false; - if (g_IsNT) - { - WIN32_FIND_DATAW fd; - _handle = ::FindFirstFileW(wildcard, &fd); - #ifdef WIN_LONG_PATH - if (_handle == INVALID_HANDLE_VALUE) - { - UString longPath; - if (GetLongPath(wildcard, longPath)) - _handle = ::FindFirstFileW(longPath, &fd); - } - #endif - if (_handle != INVALID_HANDLE_VALUE) - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - } - else - { - WIN32_FIND_DATAA fd; - _handle = ::FindFirstFileA(UnicodeStringToMultiByte(wildcard, - GetCurrentCodePage()), &fd); - if (_handle != INVALID_HANDLE_VALUE) - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - } - return (_handle != INVALID_HANDLE_VALUE); -} -#endif - -bool CFindFile::FindNext(CFileInfo &fileInfo) -{ - WIN32_FIND_DATA fd; - bool result = BOOLToBool(::FindNextFile(_handle, &fd)); - if (result) - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - return result; -} - -#ifndef _UNICODE -bool CFindFile::FindNext(CFileInfoW &fileInfo) -{ - if (g_IsNT) - { - WIN32_FIND_DATAW fd; - if (!::FindNextFileW(_handle, &fd)) - return false; - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - } - else - { - WIN32_FIND_DATAA fd; - if (!::FindNextFileA(_handle, &fd)) - return false; - ConvertWIN32_FIND_DATA_To_FileInfo(fd, fileInfo); - } - return true; -} -#endif - -bool FindFile(LPCTSTR wildcard, CFileInfo &fileInfo) -{ - CFindFile finder; - return finder.FindFirst(wildcard, fileInfo); -} - -#ifndef _UNICODE -bool FindFile(LPCWSTR wildcard, CFileInfoW &fileInfo) -{ - CFindFile finder; - return finder.FindFirst(wildcard, fileInfo); -} -#endif - -bool DoesFileExist(LPCTSTR name) -{ - CFileInfo fileInfo; - return FindFile(name, fileInfo); -} - -#ifndef _UNICODE -bool DoesFileExist(LPCWSTR name) -{ - CFileInfoW fileInfo; - return FindFile(name, fileInfo); -} -#endif - -///////////////////////////////////// -// CEnumerator - -bool CEnumerator::NextAny(CFileInfo &fileInfo) -{ - if (_findFile.IsHandleAllocated()) - return _findFile.FindNext(fileInfo); - else - return _findFile.FindFirst(_wildcard, fileInfo); -} - -bool CEnumerator::Next(CFileInfo &fileInfo) -{ - for (;;) - { - if (!NextAny(fileInfo)) - return false; - if (!fileInfo.IsDots()) - return true; - } -} - -bool CEnumerator::Next(CFileInfo &fileInfo, bool &found) -{ - if (Next(fileInfo)) - { - found = true; - return true; - } - found = false; - return (::GetLastError() == ERROR_NO_MORE_FILES); -} - -#ifndef _UNICODE -bool CEnumeratorW::NextAny(CFileInfoW &fileInfo) -{ - if (_findFile.IsHandleAllocated()) - return _findFile.FindNext(fileInfo); - else - return _findFile.FindFirst(_wildcard, fileInfo); -} - -bool CEnumeratorW::Next(CFileInfoW &fileInfo) -{ - for (;;) - { - if (!NextAny(fileInfo)) - return false; - if (!fileInfo.IsDots()) - return true; - } -} - -bool CEnumeratorW::Next(CFileInfoW &fileInfo, bool &found) -{ - if (Next(fileInfo)) - { - found = true; - return true; - } - found = false; - return (::GetLastError() == ERROR_NO_MORE_FILES); -} - -#endif - -//////////////////////////////// -// CFindChangeNotification -// FindFirstChangeNotification can return 0. MSDN doesn't tell about it. - -bool CFindChangeNotification::Close() -{ - if (!IsHandleAllocated()) - return true; - if (!::FindCloseChangeNotification(_handle)) - return false; - _handle = INVALID_HANDLE_VALUE; - return true; -} - -HANDLE CFindChangeNotification::FindFirst(LPCTSTR pathName, bool watchSubtree, DWORD notifyFilter) -{ - _handle = ::FindFirstChangeNotification(pathName, BoolToBOOL(watchSubtree), notifyFilter); - #ifdef WIN_LONG_PATH2 - if (!IsHandleAllocated()) - { - UString longPath; - if (GetLongPath(pathName, longPath)) - _handle = ::FindFirstChangeNotificationW(longPath, BoolToBOOL(watchSubtree), notifyFilter); - } - #endif - return _handle; -} - -#ifndef _UNICODE -HANDLE CFindChangeNotification::FindFirst(LPCWSTR pathName, bool watchSubtree, DWORD notifyFilter) -{ - if (!g_IsNT) - return FindFirst(UnicodeStringToMultiByte(pathName, GetCurrentCodePage()), watchSubtree, notifyFilter); - _handle = ::FindFirstChangeNotificationW(pathName, BoolToBOOL(watchSubtree), notifyFilter); - #ifdef WIN_LONG_PATH - if (!IsHandleAllocated()) - { - UString longPath; - if (GetLongPath(pathName, longPath)) - _handle = ::FindFirstChangeNotificationW(longPath, BoolToBOOL(watchSubtree), notifyFilter); - } - #endif - return _handle; -} -#endif - -#ifndef _WIN32_WCE -bool MyGetLogicalDriveStrings(CSysStringVector &driveStrings) -{ - driveStrings.Clear(); - UINT32 size = GetLogicalDriveStrings(0, NULL); - if (size == 0) - return false; - CSysString buffer; - UINT32 newSize = GetLogicalDriveStrings(size, buffer.GetBuffer(size)); - if (newSize == 0) - return false; - if (newSize > size) - return false; - CSysString string; - for (UINT32 i = 0; i < newSize; i++) - { - TCHAR c = buffer[i]; - if (c == TEXT('\0')) - { - driveStrings.Add(string); - string.Empty(); - } - else - string += c; - } - if (!string.IsEmpty()) - return false; - return true; -} - -#ifndef _UNICODE -bool MyGetLogicalDriveStrings(UStringVector &driveStrings) -{ - driveStrings.Clear(); - if (g_IsNT) - { - UINT32 size = GetLogicalDriveStringsW(0, NULL); - if (size == 0) - return false; - UString buffer; - UINT32 newSize = GetLogicalDriveStringsW(size, buffer.GetBuffer(size)); - if (newSize == 0) - return false; - if (newSize > size) - return false; - UString string; - for (UINT32 i = 0; i < newSize; i++) - { - WCHAR c = buffer[i]; - if (c == L'\0') - { - driveStrings.Add(string); - string.Empty(); - } - else - string += c; - } - return string.IsEmpty(); - } - CSysStringVector driveStringsA; - bool res = MyGetLogicalDriveStrings(driveStringsA); - for (int i = 0; i < driveStringsA.Size(); i++) - driveStrings.Add(GetUnicodeString(driveStringsA[i])); - return res; -} -#endif - -#endif - -}}} diff --git a/desmume/src/windows/7z/CPP/Windows/FileFind.h b/desmume/src/windows/7z/CPP/Windows/FileFind.h deleted file mode 100644 index f01c1357e..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileFind.h +++ /dev/null @@ -1,153 +0,0 @@ -// Windows/FileFind.h - -#ifndef __WINDOWS_FILEFIND_H -#define __WINDOWS_FILEFIND_H - -#include "../Common/MyString.h" -#include "../Common/Types.h" -#include "FileName.h" -#include "Defs.h" - -namespace NWindows { -namespace NFile { -namespace NFind { - -namespace NAttributes -{ - inline bool IsReadOnly(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_READONLY) != 0; } - inline bool IsHidden(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_HIDDEN) != 0; } - inline bool IsSystem(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_SYSTEM) != 0; } - inline bool IsDir(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_DIRECTORY) != 0; } - inline bool IsArchived(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_ARCHIVE) != 0; } - inline bool IsCompressed(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_COMPRESSED) != 0; } - inline bool IsEncrypted(DWORD attrib) { return (attrib & FILE_ATTRIBUTE_ENCRYPTED) != 0; } -} - -class CFileInfoBase -{ - bool MatchesMask(UINT32 mask) const { return ((Attrib & mask) != 0); } -public: - UInt64 Size; - FILETIME CTime; - FILETIME ATime; - FILETIME MTime; - DWORD Attrib; - - #ifndef _WIN32_WCE - UINT32 ReparseTag; - #else - DWORD ObjectID; - #endif - - bool IsArchived() const { return MatchesMask(FILE_ATTRIBUTE_ARCHIVE); } - bool IsCompressed() const { return MatchesMask(FILE_ATTRIBUTE_COMPRESSED); } - bool IsDir() const { return MatchesMask(FILE_ATTRIBUTE_DIRECTORY); } - bool IsEncrypted() const { return MatchesMask(FILE_ATTRIBUTE_ENCRYPTED); } - bool IsHidden() const { return MatchesMask(FILE_ATTRIBUTE_HIDDEN); } - bool IsNormal() const { return MatchesMask(FILE_ATTRIBUTE_NORMAL); } - bool IsOffline() const { return MatchesMask(FILE_ATTRIBUTE_OFFLINE); } - bool IsReadOnly() const { return MatchesMask(FILE_ATTRIBUTE_READONLY); } - bool HasReparsePoint() const { return MatchesMask(FILE_ATTRIBUTE_REPARSE_POINT); } - bool IsSparse() const { return MatchesMask(FILE_ATTRIBUTE_SPARSE_FILE); } - bool IsSystem() const { return MatchesMask(FILE_ATTRIBUTE_SYSTEM); } - bool IsTemporary() const { return MatchesMask(FILE_ATTRIBUTE_TEMPORARY); } -}; - -class CFileInfo: public CFileInfoBase -{ -public: - CSysString Name; - bool IsDots() const; -}; - -#ifdef _UNICODE -typedef CFileInfo CFileInfoW; -#else -class CFileInfoW: public CFileInfoBase -{ -public: - UString Name; - bool IsDots() const; -}; -#endif - -class CFindFile -{ - friend class CEnumerator; - HANDLE _handle; -public: - bool IsHandleAllocated() const { return _handle != INVALID_HANDLE_VALUE; } - CFindFile(): _handle(INVALID_HANDLE_VALUE) {} - ~CFindFile() { Close(); } - bool FindFirst(LPCTSTR wildcard, CFileInfo &fileInfo); - bool FindNext(CFileInfo &fileInfo); - #ifndef _UNICODE - bool FindFirst(LPCWSTR wildcard, CFileInfoW &fileInfo); - bool FindNext(CFileInfoW &fileInfo); - #endif - bool Close(); -}; - -bool FindFile(LPCTSTR wildcard, CFileInfo &fileInfo); - -bool DoesFileExist(LPCTSTR name); -#ifndef _UNICODE -bool FindFile(LPCWSTR wildcard, CFileInfoW &fileInfo); -bool DoesFileExist(LPCWSTR name); -#endif - -class CEnumerator -{ - CFindFile _findFile; - CSysString _wildcard; - bool NextAny(CFileInfo &fileInfo); -public: - CEnumerator(): _wildcard(NName::kAnyStringWildcard) {} - CEnumerator(const CSysString &wildcard): _wildcard(wildcard) {} - bool Next(CFileInfo &fileInfo); - bool Next(CFileInfo &fileInfo, bool &found); -}; - -#ifdef _UNICODE -typedef CEnumerator CEnumeratorW; -#else -class CEnumeratorW -{ - CFindFile _findFile; - UString _wildcard; - bool NextAny(CFileInfoW &fileInfo); -public: - CEnumeratorW(): _wildcard(NName::kAnyStringWildcard) {} - CEnumeratorW(const UString &wildcard): _wildcard(wildcard) {} - bool Next(CFileInfoW &fileInfo); - bool Next(CFileInfoW &fileInfo, bool &found); -}; -#endif - -class CFindChangeNotification -{ - HANDLE _handle; -public: - operator HANDLE () { return _handle; } - bool IsHandleAllocated() const { return _handle != INVALID_HANDLE_VALUE && _handle != 0; } - CFindChangeNotification(): _handle(INVALID_HANDLE_VALUE) {} - ~CFindChangeNotification() { Close(); } - bool Close(); - HANDLE FindFirst(LPCTSTR pathName, bool watchSubtree, DWORD notifyFilter); - #ifndef _UNICODE - HANDLE FindFirst(LPCWSTR pathName, bool watchSubtree, DWORD notifyFilter); - #endif - bool FindNext() { return BOOLToBool(::FindNextChangeNotification(_handle)); } -}; - -#ifndef _WIN32_WCE -bool MyGetLogicalDriveStrings(CSysStringVector &driveStrings); -#ifndef _UNICODE -bool MyGetLogicalDriveStrings(UStringVector &driveStrings); -#endif -#endif - -}}} - -#endif - diff --git a/desmume/src/windows/7z/CPP/Windows/FileIO.cpp b/desmume/src/windows/7z/CPP/Windows/FileIO.cpp deleted file mode 100644 index 520d9a2ba..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileIO.cpp +++ /dev/null @@ -1,317 +0,0 @@ -// Windows/FileIO.cpp - -#include "StdAfx.h" - -#include "FileIO.h" -#include "Defs.h" -#ifdef WIN_LONG_PATH -#include "../Common/MyString.h" -#endif -#ifndef _UNICODE -#include "../Common/StringConvert.h" -#endif - -#ifndef _UNICODE -extern bool g_IsNT; -#endif - -namespace NWindows { -namespace NFile { - -#if defined(WIN_LONG_PATH) && defined(_UNICODE) -#define WIN_LONG_PATH2 -#endif - -#ifdef WIN_LONG_PATH -bool GetLongPathBase(LPCWSTR s, UString &res) -{ - res.Empty(); - int len = MyStringLen(s); - wchar_t c = s[0]; - if (len < 1 || c == L'\\' || c == L'.' && (len == 1 || len == 2 && s[1] == L'.')) - return true; - UString curDir; - bool isAbs = false; - if (len > 3) - isAbs = (s[1] == L':' && s[2] == L'\\' && (c >= L'a' && c <= L'z' || c >= L'A' && c <= L'Z')); - - if (!isAbs) - { - DWORD needLength = ::GetCurrentDirectoryW(MAX_PATH + 1, curDir.GetBuffer(MAX_PATH + 1)); - curDir.ReleaseBuffer(); - if (needLength == 0 || needLength > MAX_PATH) - return false; - if (curDir[curDir.Length() - 1] != L'\\') - curDir += L'\\'; - } - res = UString(L"\\\\?\\") + curDir + s; - return true; -} - -bool GetLongPath(LPCWSTR path, UString &longPath) -{ - if (GetLongPathBase(path, longPath)) - return !longPath.IsEmpty(); - return false; -} -#endif - -namespace NIO { - -CFileBase::~CFileBase() { Close(); } - -bool CFileBase::Create(LPCTSTR fileName, DWORD desiredAccess, - DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) -{ - if (!Close()) - return false; - _handle = ::CreateFile(fileName, desiredAccess, shareMode, - (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, - flagsAndAttributes, (HANDLE)NULL); - #ifdef WIN_LONG_PATH2 - if (_handle == INVALID_HANDLE_VALUE) - { - UString longPath; - if (GetLongPath(fileName, longPath)) - _handle = ::CreateFileW(longPath, desiredAccess, shareMode, - (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, - flagsAndAttributes, (HANDLE)NULL); - } - #endif - return (_handle != INVALID_HANDLE_VALUE); -} - -#ifndef _UNICODE -bool CFileBase::Create(LPCWSTR fileName, DWORD desiredAccess, - DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) -{ - if (!g_IsNT) - return Create(UnicodeStringToMultiByte(fileName, ::AreFileApisANSI() ? CP_ACP : CP_OEMCP), - desiredAccess, shareMode, creationDisposition, flagsAndAttributes); - if (!Close()) - return false; - _handle = ::CreateFileW(fileName, desiredAccess, shareMode, - (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, - flagsAndAttributes, (HANDLE)NULL); - #ifdef WIN_LONG_PATH - if (_handle == INVALID_HANDLE_VALUE) - { - UString longPath; - if (GetLongPath(fileName, longPath)) - _handle = ::CreateFileW(longPath, desiredAccess, shareMode, - (LPSECURITY_ATTRIBUTES)NULL, creationDisposition, - flagsAndAttributes, (HANDLE)NULL); - } - #endif - return (_handle != INVALID_HANDLE_VALUE); -} -#endif - -bool CFileBase::Close() -{ - if (_handle == INVALID_HANDLE_VALUE) - return true; - if (!::CloseHandle(_handle)) - return false; - _handle = INVALID_HANDLE_VALUE; - return true; -} - -bool CFileBase::GetPosition(UInt64 &position) const -{ - return Seek(0, FILE_CURRENT, position); -} - -bool CFileBase::GetLength(UInt64 &length) const -{ - DWORD sizeHigh; - DWORD sizeLow = ::GetFileSize(_handle, &sizeHigh); - if (sizeLow == 0xFFFFFFFF) - if (::GetLastError() != NO_ERROR) - return false; - length = (((UInt64)sizeHigh) << 32) + sizeLow; - return true; -} - -bool CFileBase::Seek(Int64 distanceToMove, DWORD moveMethod, UInt64 &newPosition) const -{ - LARGE_INTEGER value; - value.QuadPart = distanceToMove; - value.LowPart = ::SetFilePointer(_handle, value.LowPart, &value.HighPart, moveMethod); - if (value.LowPart == 0xFFFFFFFF) - if (::GetLastError() != NO_ERROR) - return false; - newPosition = value.QuadPart; - return true; -} - -bool CFileBase::Seek(UInt64 position, UInt64 &newPosition) -{ - return Seek(position, FILE_BEGIN, newPosition); -} - -bool CFileBase::SeekToBegin() -{ - UInt64 newPosition; - return Seek(0, newPosition); -} - -bool CFileBase::SeekToEnd(UInt64 &newPosition) -{ - return Seek(0, FILE_END, newPosition); -} - -bool CFileBase::GetFileInformation(CByHandleFileInfo &fileInfo) const -{ - BY_HANDLE_FILE_INFORMATION winFileInfo; - if (!::GetFileInformationByHandle(_handle, &winFileInfo)) - return false; - fileInfo.Attributes = winFileInfo.dwFileAttributes; - fileInfo.CTime = winFileInfo.ftCreationTime; - fileInfo.ATime = winFileInfo.ftLastAccessTime; - fileInfo.MTime = winFileInfo.ftLastWriteTime; - fileInfo.VolumeSerialNumber = winFileInfo.dwFileAttributes; - fileInfo.Size = (((UInt64)winFileInfo.nFileSizeHigh) << 32) + winFileInfo.nFileSizeLow; - fileInfo.NumberOfLinks = winFileInfo.nNumberOfLinks; - fileInfo.FileIndex = (((UInt64)winFileInfo.nFileIndexHigh) << 32) + winFileInfo.nFileIndexLow; - return true; -} - -///////////////////////// -// CInFile - -bool CInFile::Open(LPCTSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) - { return Create(fileName, GENERIC_READ, shareMode, creationDisposition, flagsAndAttributes); } - -bool CInFile::OpenShared(LPCTSTR fileName, bool shareForWrite) -{ return Open(fileName, FILE_SHARE_READ | (shareForWrite ? FILE_SHARE_WRITE : 0), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL); } - -bool CInFile::Open(LPCTSTR fileName) - { return OpenShared(fileName, false); } - -#ifndef _UNICODE -bool CInFile::Open(LPCWSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) - { return Create(fileName, GENERIC_READ, shareMode, creationDisposition, flagsAndAttributes); } - -bool CInFile::OpenShared(LPCWSTR fileName, bool shareForWrite) -{ return Open(fileName, FILE_SHARE_READ | (shareForWrite ? FILE_SHARE_WRITE : 0), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL); } - -bool CInFile::Open(LPCWSTR fileName) - { return OpenShared(fileName, false); } -#endif - -// ReadFile and WriteFile functions in Windows have BUG: -// If you Read or Write 64MB or more (probably min_failure_size = 64MB - 32KB + 1) -// from/to Network file, it returns ERROR_NO_SYSTEM_RESOURCES -// (Insufficient system resources exist to complete the requested service). - -// Probably in some version of Windows there are problems with other sizes: -// for 32 MB (maybe also for 16 MB). -// And message can be "Network connection was lost" - -static UInt32 kChunkSizeMax = (1 << 22); - -bool CInFile::ReadPart(void *data, UInt32 size, UInt32 &processedSize) -{ - if (size > kChunkSizeMax) - size = kChunkSizeMax; - DWORD processedLoc = 0; - bool res = BOOLToBool(::ReadFile(_handle, data, size, &processedLoc, NULL)); - processedSize = (UInt32)processedLoc; - return res; -} - -bool CInFile::Read(void *data, UInt32 size, UInt32 &processedSize) -{ - processedSize = 0; - do - { - UInt32 processedLoc = 0; - bool res = ReadPart(data, size, processedLoc); - processedSize += processedLoc; - if (!res) - return false; - if (processedLoc == 0) - return true; - data = (void *)((unsigned char *)data + processedLoc); - size -= processedLoc; - } - while (size > 0); - return true; -} - -///////////////////////// -// COutFile - -bool COutFile::Open(LPCTSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) - { return CFileBase::Create(fileName, GENERIC_WRITE, shareMode, creationDisposition, flagsAndAttributes); } - -static inline DWORD GetCreationDisposition(bool createAlways) - { return createAlways? CREATE_ALWAYS: CREATE_NEW; } - -bool COutFile::Open(LPCTSTR fileName, DWORD creationDisposition) - { return Open(fileName, FILE_SHARE_READ, creationDisposition, FILE_ATTRIBUTE_NORMAL); } - -bool COutFile::Create(LPCTSTR fileName, bool createAlways) - { return Open(fileName, GetCreationDisposition(createAlways)); } - -#ifndef _UNICODE - -bool COutFile::Open(LPCWSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes) - { return CFileBase::Create(fileName, GENERIC_WRITE, shareMode, creationDisposition, flagsAndAttributes); } - -bool COutFile::Open(LPCWSTR fileName, DWORD creationDisposition) - { return Open(fileName, FILE_SHARE_READ, creationDisposition, FILE_ATTRIBUTE_NORMAL); } - -bool COutFile::Create(LPCWSTR fileName, bool createAlways) - { return Open(fileName, GetCreationDisposition(createAlways)); } - -#endif - -bool COutFile::SetTime(const FILETIME *cTime, const FILETIME *aTime, const FILETIME *mTime) - { return BOOLToBool(::SetFileTime(_handle, cTime, aTime, mTime)); } - -bool COutFile::SetMTime(const FILETIME *mTime) { return SetTime(NULL, NULL, mTime); } - -bool COutFile::WritePart(const void *data, UInt32 size, UInt32 &processedSize) -{ - if (size > kChunkSizeMax) - size = kChunkSizeMax; - DWORD processedLoc = 0; - bool res = BOOLToBool(::WriteFile(_handle, data, size, &processedLoc, NULL)); - processedSize = (UInt32)processedLoc; - return res; -} - -bool COutFile::Write(const void *data, UInt32 size, UInt32 &processedSize) -{ - processedSize = 0; - do - { - UInt32 processedLoc = 0; - bool res = WritePart(data, size, processedLoc); - processedSize += processedLoc; - if (!res) - return false; - if (processedLoc == 0) - return true; - data = (const void *)((const unsigned char *)data + processedLoc); - size -= processedLoc; - } - while (size > 0); - return true; -} - -bool COutFile::SetEndOfFile() { return BOOLToBool(::SetEndOfFile(_handle)); } - -bool COutFile::SetLength(UInt64 length) -{ - UInt64 newPosition; - if (!Seek(length, newPosition)) - return false; - if (newPosition != length) - return false; - return SetEndOfFile(); -} - -}}} diff --git a/desmume/src/windows/7z/CPP/Windows/FileIO.h b/desmume/src/windows/7z/CPP/Windows/FileIO.h deleted file mode 100644 index 930a13d94..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileIO.h +++ /dev/null @@ -1,99 +0,0 @@ -// Windows/FileIO.h - -#ifndef __WINDOWS_FILEIO_H -#define __WINDOWS_FILEIO_H - -#include "../Common/Types.h" - -namespace NWindows { -namespace NFile { -namespace NIO { - -struct CByHandleFileInfo -{ - DWORD Attributes; - FILETIME CTime; - FILETIME ATime; - FILETIME MTime; - DWORD VolumeSerialNumber; - UInt64 Size; - DWORD NumberOfLinks; - UInt64 FileIndex; -}; - -class CFileBase -{ -protected: - HANDLE _handle; - bool Create(LPCTSTR fileName, DWORD desiredAccess, - DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - #ifndef _UNICODE - bool Create(LPCWSTR fileName, DWORD desiredAccess, - DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - #endif - -public: - CFileBase(): _handle(INVALID_HANDLE_VALUE){}; - ~CFileBase(); - - bool Close(); - - bool GetPosition(UInt64 &position) const; - bool GetLength(UInt64 &length) const; - - bool Seek(Int64 distanceToMove, DWORD moveMethod, UInt64 &newPosition) const; - bool Seek(UInt64 position, UInt64 &newPosition); - bool SeekToBegin(); - bool SeekToEnd(UInt64 &newPosition); - - bool GetFileInformation(CByHandleFileInfo &fileInfo) const; -}; - -class CInFile: public CFileBase -{ -public: - bool Open(LPCTSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - bool OpenShared(LPCTSTR fileName, bool shareForWrite); - bool Open(LPCTSTR fileName); - #ifndef _UNICODE - bool Open(LPCWSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - bool OpenShared(LPCWSTR fileName, bool shareForWrite); - bool Open(LPCWSTR fileName); - #endif - bool ReadPart(void *data, UInt32 size, UInt32 &processedSize); - bool Read(void *data, UInt32 size, UInt32 &processedSize); -}; - -class COutFile: public CFileBase -{ - // DWORD m_CreationDisposition; -public: - // COutFile(): m_CreationDisposition(CREATE_NEW){}; - bool Open(LPCTSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - bool Open(LPCTSTR fileName, DWORD creationDisposition); - bool Create(LPCTSTR fileName, bool createAlways); - - #ifndef _UNICODE - bool Open(LPCWSTR fileName, DWORD shareMode, DWORD creationDisposition, DWORD flagsAndAttributes); - bool Open(LPCWSTR fileName, DWORD creationDisposition); - bool Create(LPCWSTR fileName, bool createAlways); - #endif - - /* - void SetOpenCreationDisposition(DWORD creationDisposition) - { m_CreationDisposition = creationDisposition; } - void SetOpenCreationDispositionCreateAlways() - { m_CreationDisposition = CREATE_ALWAYS; } - */ - - bool SetTime(const FILETIME *cTime, const FILETIME *aTime, const FILETIME *mTime); - bool SetMTime(const FILETIME *mTime); - bool WritePart(const void *data, UInt32 size, UInt32 &processedSize); - bool Write(const void *data, UInt32 size, UInt32 &processedSize); - bool SetEndOfFile(); - bool SetLength(UInt64 length); -}; - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/FileName.h b/desmume/src/windows/7z/CPP/Windows/FileName.h deleted file mode 100644 index 02dba3b69..000000000 --- a/desmume/src/windows/7z/CPP/Windows/FileName.h +++ /dev/null @@ -1,25 +0,0 @@ -// Windows/FileName.h - -#ifndef __WINDOWS_FILENAME_H -#define __WINDOWS_FILENAME_H - -#include "../Common/MyString.h" - -namespace NWindows { -namespace NFile { -namespace NName { - -const TCHAR kDirDelimiter = CHAR_PATH_SEPARATOR; -const TCHAR kAnyStringWildcard = '*'; - -void NormalizeDirPathPrefix(CSysString &dirPath); // ensures that it ended with '\\' -#ifndef _UNICODE -void NormalizeDirPathPrefix(UString &dirPath); // ensures that it ended with '\\' -#endif - -void SplitNameToPureNameAndExtension(const UString &fullName, - UString &pureName, UString &extensionDelimiter, UString &extension); - -}}} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/Handle.h b/desmume/src/windows/7z/CPP/Windows/Handle.h deleted file mode 100644 index 16546079d..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Handle.h +++ /dev/null @@ -1,37 +0,0 @@ -// Windows/Handle.h - -#ifndef __WINDOWS_HANDLE_H -#define __WINDOWS_HANDLE_H - -namespace NWindows { - -class CHandle -{ -protected: - HANDLE _handle; -public: - operator HANDLE() { return _handle; } - CHandle(): _handle(NULL) {} - ~CHandle() { Close(); } - bool Close() - { - if (_handle == NULL) - return true; - if (!::CloseHandle(_handle)) - return false; - _handle = NULL; - return true; - } - void Attach(HANDLE handle) - { _handle = handle; } - HANDLE Detach() - { - HANDLE handle = _handle; - _handle = NULL; - return handle; - } -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/PropVariant.cpp b/desmume/src/windows/7z/CPP/Windows/PropVariant.cpp deleted file mode 100644 index fff513d18..000000000 --- a/desmume/src/windows/7z/CPP/Windows/PropVariant.cpp +++ /dev/null @@ -1,312 +0,0 @@ -// Windows/PropVariant.cpp - -#include "StdAfx.h" - -#include "PropVariant.h" - -#include "../Common/Defs.h" - -namespace NWindows { -namespace NCOM { - -CPropVariant::CPropVariant(const PROPVARIANT& varSrc) -{ - vt = VT_EMPTY; - InternalCopy(&varSrc); -} - -CPropVariant::CPropVariant(const CPropVariant& varSrc) -{ - vt = VT_EMPTY; - InternalCopy(&varSrc); -} - -CPropVariant::CPropVariant(BSTR bstrSrc) -{ - vt = VT_EMPTY; - *this = bstrSrc; -} - -CPropVariant::CPropVariant(LPCOLESTR lpszSrc) -{ - vt = VT_EMPTY; - *this = lpszSrc; -} - -CPropVariant& CPropVariant::operator=(const CPropVariant& varSrc) -{ - InternalCopy(&varSrc); - return *this; -} -CPropVariant& CPropVariant::operator=(const PROPVARIANT& varSrc) -{ - InternalCopy(&varSrc); - return *this; -} - -CPropVariant& CPropVariant::operator=(BSTR bstrSrc) -{ - *this = (LPCOLESTR)bstrSrc; - return *this; -} - -CPropVariant& CPropVariant::operator=(LPCOLESTR lpszSrc) -{ - InternalClear(); - vt = VT_BSTR; - wReserved1 = 0; - bstrVal = ::SysAllocString(lpszSrc); - if (bstrVal == NULL && lpszSrc != NULL) - { - vt = VT_ERROR; - scode = E_OUTOFMEMORY; - } - return *this; -} - - -CPropVariant& CPropVariant::operator=(bool bSrc) -{ - if (vt != VT_BOOL) - { - InternalClear(); - vt = VT_BOOL; - } - boolVal = bSrc ? VARIANT_TRUE : VARIANT_FALSE; - return *this; -} - -CPropVariant& CPropVariant::operator=(UInt32 value) -{ - if (vt != VT_UI4) - { - InternalClear(); - vt = VT_UI4; - } - ulVal = value; - return *this; -} - -CPropVariant& CPropVariant::operator=(UInt64 value) -{ - if (vt != VT_UI8) - { - InternalClear(); - vt = VT_UI8; - } - uhVal.QuadPart = value; - return *this; -} - -CPropVariant& CPropVariant::operator=(const FILETIME &value) -{ - if (vt != VT_FILETIME) - { - InternalClear(); - vt = VT_FILETIME; - } - filetime = value; - return *this; -} - -CPropVariant& CPropVariant::operator=(Int32 value) -{ - if (vt != VT_I4) - { - InternalClear(); - vt = VT_I4; - } - lVal = value; - - return *this; -} - -CPropVariant& CPropVariant::operator=(Byte value) -{ - if (vt != VT_UI1) - { - InternalClear(); - vt = VT_UI1; - } - bVal = value; - return *this; -} - -CPropVariant& CPropVariant::operator=(Int16 value) -{ - if (vt != VT_I2) - { - InternalClear(); - vt = VT_I2; - } - iVal = value; - return *this; -} - -/* -CPropVariant& CPropVariant::operator=(LONG value) -{ - if (vt != VT_I4) - { - InternalClear(); - vt = VT_I4; - } - lVal = value; - return *this; -} -*/ - -static HRESULT MyPropVariantClear(PROPVARIANT *propVariant) -{ - switch(propVariant->vt) - { - case VT_UI1: - case VT_I1: - case VT_I2: - case VT_UI2: - case VT_BOOL: - case VT_I4: - case VT_UI4: - case VT_R4: - case VT_INT: - case VT_UINT: - case VT_ERROR: - case VT_FILETIME: - case VT_UI8: - case VT_R8: - case VT_CY: - case VT_DATE: - propVariant->vt = VT_EMPTY; - propVariant->wReserved1 = 0; - return S_OK; - } - return ::VariantClear((VARIANTARG *)propVariant); -} - -HRESULT CPropVariant::Clear() -{ - return MyPropVariantClear(this); -} - -HRESULT CPropVariant::Copy(const PROPVARIANT* pSrc) -{ - ::VariantClear((tagVARIANT *)this); - switch(pSrc->vt) - { - case VT_UI1: - case VT_I1: - case VT_I2: - case VT_UI2: - case VT_BOOL: - case VT_I4: - case VT_UI4: - case VT_R4: - case VT_INT: - case VT_UINT: - case VT_ERROR: - case VT_FILETIME: - case VT_UI8: - case VT_R8: - case VT_CY: - case VT_DATE: - memmove((PROPVARIANT*)this, pSrc, sizeof(PROPVARIANT)); - return S_OK; - } - return ::VariantCopy((tagVARIANT *)this, (tagVARIANT *)(pSrc)); -} - - -HRESULT CPropVariant::Attach(PROPVARIANT* pSrc) -{ - HRESULT hr = Clear(); - if (FAILED(hr)) - return hr; - memcpy(this, pSrc, sizeof(PROPVARIANT)); - pSrc->vt = VT_EMPTY; - return S_OK; -} - -HRESULT CPropVariant::Detach(PROPVARIANT* pDest) -{ - HRESULT hr = MyPropVariantClear(pDest); - if (FAILED(hr)) - return hr; - memcpy(pDest, this, sizeof(PROPVARIANT)); - vt = VT_EMPTY; - return S_OK; -} - -HRESULT CPropVariant::InternalClear() -{ - HRESULT hr = Clear(); - if (FAILED(hr)) - { - vt = VT_ERROR; - scode = hr; - } - return hr; -} - -void CPropVariant::InternalCopy(const PROPVARIANT* pSrc) -{ - HRESULT hr = Copy(pSrc); - if (FAILED(hr)) - { - vt = VT_ERROR; - scode = hr; - } -} - -int CPropVariant::Compare(const CPropVariant &a) -{ - if (vt != a.vt) - return 0; // it's mean some bug - switch (vt) - { - case VT_EMPTY: - return 0; - - /* - case VT_I1: - return MyCompare(cVal, a.cVal); - */ - case VT_UI1: - return MyCompare(bVal, a.bVal); - - case VT_I2: - return MyCompare(iVal, a.iVal); - case VT_UI2: - return MyCompare(uiVal, a.uiVal); - - case VT_I4: - return MyCompare(lVal, a.lVal); - /* - case VT_INT: - return MyCompare(intVal, a.intVal); - */ - case VT_UI4: - return MyCompare(ulVal, a.ulVal); - /* - case VT_UINT: - return MyCompare(uintVal, a.uintVal); - */ - case VT_I8: - return MyCompare(hVal.QuadPart, a.hVal.QuadPart); - case VT_UI8: - return MyCompare(uhVal.QuadPart, a.uhVal.QuadPart); - - case VT_BOOL: - return -MyCompare(boolVal, a.boolVal); - - case VT_FILETIME: - return ::CompareFileTime(&filetime, &a.filetime); - case VT_BSTR: - return 0; // Not implemented - // return MyCompare(aPropVarint.cVal); - - default: - return 0; - } -} - -}} diff --git a/desmume/src/windows/7z/CPP/Windows/PropVariant.h b/desmume/src/windows/7z/CPP/Windows/PropVariant.h deleted file mode 100644 index 85284e030..000000000 --- a/desmume/src/windows/7z/CPP/Windows/PropVariant.h +++ /dev/null @@ -1,57 +0,0 @@ -// Windows/PropVariant.h - -#ifndef __WINDOWS_PROPVARIANT_H -#define __WINDOWS_PROPVARIANT_H - -#include "../Common/MyWindows.h" -#include "../Common/Types.h" - -namespace NWindows { -namespace NCOM { - -class CPropVariant : public tagPROPVARIANT -{ -public: - CPropVariant() { vt = VT_EMPTY; wReserved1 = 0; } - ~CPropVariant() { Clear(); } - CPropVariant(const PROPVARIANT& varSrc); - CPropVariant(const CPropVariant& varSrc); - CPropVariant(BSTR bstrSrc); - CPropVariant(LPCOLESTR lpszSrc); - CPropVariant(bool bSrc) { vt = VT_BOOL; wReserved1 = 0; boolVal = (bSrc ? VARIANT_TRUE : VARIANT_FALSE); }; - CPropVariant(UInt32 value) { vt = VT_UI4; wReserved1 = 0; ulVal = value; } - CPropVariant(UInt64 value) { vt = VT_UI8; wReserved1 = 0; uhVal = *(ULARGE_INTEGER*)&value; } - CPropVariant(const FILETIME &value) { vt = VT_FILETIME; wReserved1 = 0; filetime = value; } - CPropVariant(Int32 value) { vt = VT_I4; wReserved1 = 0; lVal = value; } - CPropVariant(Byte value) { vt = VT_UI1; wReserved1 = 0; bVal = value; } - CPropVariant(Int16 value) { vt = VT_I2; wReserved1 = 0; iVal = value; } - // CPropVariant(LONG value, VARTYPE vtSrc = VT_I4) { vt = vtSrc; lVal = value; } - - CPropVariant& operator=(const CPropVariant& varSrc); - CPropVariant& operator=(const PROPVARIANT& varSrc); - CPropVariant& operator=(BSTR bstrSrc); - CPropVariant& operator=(LPCOLESTR lpszSrc); - CPropVariant& operator=(bool bSrc); - CPropVariant& operator=(UInt32 value); - CPropVariant& operator=(UInt64 value); - CPropVariant& operator=(const FILETIME &value); - - CPropVariant& operator=(Int32 value); - CPropVariant& operator=(Byte value); - CPropVariant& operator=(Int16 value); - // CPropVariant& operator=(LONG value); - - HRESULT Clear(); - HRESULT Copy(const PROPVARIANT* pSrc); - HRESULT Attach(PROPVARIANT* pSrc); - HRESULT Detach(PROPVARIANT* pDest); - - HRESULT InternalClear(); - void InternalCopy(const PROPVARIANT* pSrc); - - int Compare(const CPropVariant &a1); -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/StdAfx.h b/desmume/src/windows/7z/CPP/Windows/StdAfx.h deleted file mode 100644 index 5308d632d..000000000 --- a/desmume/src/windows/7z/CPP/Windows/StdAfx.h +++ /dev/null @@ -1,9 +0,0 @@ -// StdAfx.h - -#ifndef __STDAFX_H -#define __STDAFX_H - -#include "../Common/MyWindows.h" -#include "../Common/NewHandler.h" - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/Synchronization.h b/desmume/src/windows/7z/CPP/Windows/Synchronization.h deleted file mode 100644 index 1aeb91a6e..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Synchronization.h +++ /dev/null @@ -1,168 +0,0 @@ -// Windows/Synchronization.h - -#ifndef __WINDOWS_SYNCHRONIZATION_H -#define __WINDOWS_SYNCHRONIZATION_H - -#include "Defs.h" - -extern "C" -{ -#include "../../C/Threads.h" -} - -#ifdef _WIN32 -#include "Handle.h" -#endif - -namespace NWindows { -namespace NSynchronization { - -class CBaseEvent -{ -protected: - ::CEvent _object; -public: - bool IsCreated() { return Event_IsCreated(&_object) != 0; } - operator HANDLE() { return _object.handle; } - CBaseEvent() { Event_Construct(&_object); } - ~CBaseEvent() { Close(); } - WRes Close() { return Event_Close(&_object); } - #ifdef _WIN32 - WRes Create(bool manualReset, bool initiallyOwn, LPCTSTR name = NULL, - LPSECURITY_ATTRIBUTES securityAttributes = NULL) - { - _object.handle = ::CreateEvent(securityAttributes, BoolToBOOL(manualReset), - BoolToBOOL(initiallyOwn), name); - if (_object.handle != 0) - return 0; - return ::GetLastError(); - } - WRes Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name) - { - _object.handle = ::OpenEvent(desiredAccess, BoolToBOOL(inheritHandle), name); - if (_object.handle != 0) - return 0; - return ::GetLastError(); - } - #endif - - WRes Set() { return Event_Set(&_object); } - // bool Pulse() { return BOOLToBool(::PulseEvent(_handle)); } - WRes Reset() { return Event_Reset(&_object); } - WRes Lock() { return Event_Wait(&_object); } -}; - -class CManualResetEvent: public CBaseEvent -{ -public: - WRes Create(bool initiallyOwn = false) - { - return ManualResetEvent_Create(&_object, initiallyOwn ? 1: 0); - } - WRes CreateIfNotCreated() - { - if (IsCreated()) - return 0; - return ManualResetEvent_CreateNotSignaled(&_object); - } - #ifdef _WIN32 - WRes CreateWithName(bool initiallyOwn, LPCTSTR name) - { - return CBaseEvent::Create(true, initiallyOwn, name); - } - #endif -}; - -class CAutoResetEvent: public CBaseEvent -{ -public: - WRes Create() - { - return AutoResetEvent_CreateNotSignaled(&_object); - } - WRes CreateIfNotCreated() - { - if (IsCreated()) - return 0; - return AutoResetEvent_CreateNotSignaled(&_object); - } -}; - -#ifdef _WIN32 -class CObject: public CHandle -{ -public: - WRes Lock(DWORD timeoutInterval = INFINITE) - { return (::WaitForSingleObject(_handle, timeoutInterval) == WAIT_OBJECT_0 ? 0 : ::GetLastError()); } -}; -class CMutex: public CObject -{ -public: - WRes Create(bool initiallyOwn, LPCTSTR name = NULL, - LPSECURITY_ATTRIBUTES securityAttributes = NULL) - { - _handle = ::CreateMutex(securityAttributes, BoolToBOOL(initiallyOwn), name); - if (_handle != 0) - return 0; - return ::GetLastError(); - } - WRes Open(DWORD desiredAccess, bool inheritHandle, LPCTSTR name) - { - _handle = ::OpenMutex(desiredAccess, BoolToBOOL(inheritHandle), name); - if (_handle != 0) - return 0; - return ::GetLastError(); - } - WRes Release() - { - return ::ReleaseMutex(_handle) ? 0 : ::GetLastError(); - } -}; -class CMutexLock -{ - CMutex *_object; -public: - CMutexLock(CMutex &object): _object(&object) { _object->Lock(); } - ~CMutexLock() { _object->Release(); } -}; -#endif - -class CSemaphore -{ - ::CSemaphore _object; -public: - CSemaphore() { Semaphore_Construct(&_object); } - ~CSemaphore() { Close(); } - WRes Close() { return Semaphore_Close(&_object); } - operator HANDLE() { return _object.handle; } - WRes Create(UInt32 initiallyCount, UInt32 maxCount) - { - return Semaphore_Create(&_object, initiallyCount, maxCount); - } - WRes Release() { return Semaphore_Release1(&_object); } - WRes Release(UInt32 releaseCount) { return Semaphore_ReleaseN(&_object, releaseCount); } - WRes Lock() { return Semaphore_Wait(&_object); } -}; - -class CCriticalSection -{ - ::CCriticalSection _object; -public: - CCriticalSection() { CriticalSection_Init(&_object); } - ~CCriticalSection() { CriticalSection_Delete(&_object); } - void Enter() { CriticalSection_Enter(&_object); } - void Leave() { CriticalSection_Leave(&_object); } -}; - -class CCriticalSectionLock -{ - CCriticalSection *_object; - void Unlock() { _object->Leave(); } -public: - CCriticalSectionLock(CCriticalSection &object): _object(&object) {_object->Enter(); } - ~CCriticalSectionLock() { Unlock(); } -}; - -}} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/Thread.h b/desmume/src/windows/7z/CPP/Windows/Thread.h deleted file mode 100644 index 6a1e63f23..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Thread.h +++ /dev/null @@ -1,38 +0,0 @@ -// Windows/Thread.h - -#ifndef __WINDOWS_THREAD_H -#define __WINDOWS_THREAD_H - -#include "Defs.h" - -extern "C" -{ -#include "../../C/Threads.h" -} - -namespace NWindows { - -class CThread -{ - ::CThread thread; -public: - CThread() { Thread_Construct(&thread); } - ~CThread() { Close(); } - bool IsCreated() { return Thread_WasCreated(&thread) != 0; } - WRes Close() { return Thread_Close(&thread); } - WRes Create(THREAD_FUNC_RET_TYPE (THREAD_FUNC_CALL_TYPE *startAddress)(void *), LPVOID parameter) - { return Thread_Create(&thread, startAddress, parameter); } - WRes Wait() { return Thread_Wait(&thread); } - - #ifdef _WIN32 - DWORD Resume() { return ::ResumeThread(thread.handle); } - DWORD Suspend() { return ::SuspendThread(thread.handle); } - bool Terminate(DWORD exitCode) { return BOOLToBool(::TerminateThread(thread.handle, exitCode)); } - int GetPriority() { return ::GetThreadPriority(thread.handle); } - bool SetPriority(int priority) { return BOOLToBool(::SetThreadPriority(thread.handle, priority)); } - #endif -}; - -} - -#endif diff --git a/desmume/src/windows/7z/CPP/Windows/Time.cpp b/desmume/src/windows/7z/CPP/Windows/Time.cpp deleted file mode 100644 index ff49803ab..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Time.cpp +++ /dev/null @@ -1,86 +0,0 @@ -// Windows/Time.cpp - -#include "StdAfx.h" - -#include "Time.h" -#include "Windows/Defs.h" - -namespace NWindows { -namespace NTime { - -bool DosTimeToFileTime(UInt32 dosTime, FILETIME &fileTime) -{ - return BOOLToBool(::DosDateTimeToFileTime((UInt16)(dosTime >> 16), (UInt16)(dosTime & 0xFFFF), &fileTime)); -} - -static const UInt32 kHighDosTime = 0xFF9FBF7D; -static const UInt32 kLowDosTime = 0x210000; - -bool FileTimeToDosTime(const FILETIME &fileTime, UInt32 &dosTime) -{ - WORD datePart, timePart; - if (!::FileTimeToDosDateTime(&fileTime, &datePart, &timePart)) - { - dosTime = (fileTime.dwHighDateTime >= 0x01C00000) ? kHighDosTime : kLowDosTime; - return false; - } - dosTime = (((UInt32)datePart) << 16) + timePart; - return true; -} - -static const UInt32 kNumTimeQuantumsInSecond = 10000000; -static const UInt64 kUnixTimeStartValue = ((UInt64)kNumTimeQuantumsInSecond) * 60 * 60 * 24 * 134774; - -void UnixTimeToFileTime(UInt32 unixTime, FILETIME &fileTime) -{ - UInt64 v = kUnixTimeStartValue + ((UInt64)unixTime) * kNumTimeQuantumsInSecond; - fileTime.dwLowDateTime = (DWORD)v; - fileTime.dwHighDateTime = (DWORD)(v >> 32); -} - -bool FileTimeToUnixTime(const FILETIME &fileTime, UInt32 &unixTime) -{ - UInt64 winTime = (((UInt64)fileTime.dwHighDateTime) << 32) + fileTime.dwLowDateTime; - if (winTime < kUnixTimeStartValue) - { - unixTime = 0; - return false; - } - winTime = (winTime - kUnixTimeStartValue) / kNumTimeQuantumsInSecond; - if (winTime > 0xFFFFFFFF) - { - unixTime = 0xFFFFFFFF; - return false; - } - unixTime = (UInt32)winTime; - return true; -} - -bool GetSecondsSince1601(unsigned year, unsigned month, unsigned day, - unsigned hour, unsigned min, unsigned sec, UInt64 &resSeconds) -{ - resSeconds = 0; - if (year < 1601 || year >= 10000 || month < 1 || month > 12 || - day < 1 || day > 31 || hour > 23 || min > 59 || sec > 59) - return false; - UInt32 numYears = year - 1601; - UInt32 numDays = numYears * 365 + numYears / 4 - numYears / 100 + numYears / 400; - Byte ms[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; - if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) - ms[1] = 29; - month--; - for (unsigned i = 0; i < month; i++) - numDays += ms[i]; - numDays += day - 1; - resSeconds = ((UInt64)(numDays * 24 + hour) * 60 + min) * 60 + sec; - return true; -} - -void GetCurUtcFileTime(FILETIME &ft) -{ - SYSTEMTIME st; - GetSystemTime(&st); - SystemTimeToFileTime(&st, &ft); -} - -}} diff --git a/desmume/src/windows/7z/CPP/Windows/Time.h b/desmume/src/windows/7z/CPP/Windows/Time.h deleted file mode 100644 index 7ecb204b2..000000000 --- a/desmume/src/windows/7z/CPP/Windows/Time.h +++ /dev/null @@ -1,21 +0,0 @@ -// Windows/Time.h - -#ifndef __WINDOWS_TIME_H -#define __WINDOWS_TIME_H - -#include "Common/Types.h" - -namespace NWindows { -namespace NTime { - -bool DosTimeToFileTime(UInt32 dosTime, FILETIME &fileTime); -bool FileTimeToDosTime(const FILETIME &fileTime, UInt32 &dosTime); -void UnixTimeToFileTime(UInt32 unixTime, FILETIME &fileTime); -bool FileTimeToUnixTime(const FILETIME &fileTime, UInt32 &unixTime); -bool GetSecondsSince1601(unsigned year, unsigned month, unsigned day, - unsigned hour, unsigned min, unsigned sec, UInt64 &resSeconds); -void GetCurUtcFileTime(FILETIME &ft); - -}} - -#endif diff --git a/desmume/src/windows/7z/DOC/License.txt b/desmume/src/windows/7z/DOC/License.txt deleted file mode 100644 index b472b97a8..000000000 --- a/desmume/src/windows/7z/DOC/License.txt +++ /dev/null @@ -1,57 +0,0 @@ -NOTE: The 7-zip library source is available under the LGPL, -however, this copy of it is distributed under the GPL 2.0. -This license has been modified accordingly. - - - 7-Zip source code - ~~~~~~~~~~~~~~~~~ - License for use and distribution - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - 7-Zip Copyright (C) 1999-2009 Igor Pavlov. - - Licenses for files are: - - 1) The 8 files in CPP/7zip/Compress/Rar*: GNU GPL 2.0 + unRAR restriction - 2) All other files: GNU GPL 2.0 - - The GNU GPL + unRAR restriction means that you must follow both - GNU GPL rules and unRAR restriction rules. - - - GNU GPL information - -------------------- - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - - unRAR restriction - ----------------- - - The decompression engine for RAR archives was developed using source - code of unRAR program. - All copyrights to original unRAR code are owned by Alexander Roshal. - - The license for original unRAR code has the following restriction: - - The unRAR sources cannot be used to re-create the RAR compression algorithm, - which is proprietary. Distribution of modified unRAR sources in separate form - or as a part of other software is permitted, provided that it is clearly - stated in the documentation and source comments that the code may - not be used to develop a RAR (WinRAR) compatible archiver. - - - -- - Igor Pavlov diff --git a/desmume/src/windows/7z/DOC/gpl.txt b/desmume/src/windows/7z/DOC/gpl.txt deleted file mode 100644 index 82fa1daad..000000000 --- a/desmume/src/windows/7z/DOC/gpl.txt +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/desmume/src/windows/7z/DOC/readme.txt b/desmume/src/windows/7z/DOC/readme.txt deleted file mode 100644 index d7de5c264..000000000 --- a/desmume/src/windows/7z/DOC/readme.txt +++ /dev/null @@ -1,48 +0,0 @@ -This copy of the 7-zip source code has been modified as follows: -- Encoding support has been disabled, so only archive extraction is supported. -- Some archive formats have been removed, so only 7z, bzip2, gzip, lzh, lzma, rar, split, tar, and zip are supported. -- Support for using it as a static library has been added. (specifically, a file called InitializeStaticLib.h) -- Occasional minor fixes/customization not really worth describing in detail. -- The LGPL part of the 7-zip library source license has been upgraded to GPL 2.0 (as per condition 3 of the LGPL 2.1) - -You can find most of the files in this library in the "7-Zip Source code" download at http://www.7-zip.org/ distributed under the LGPL 2.1. A small subset of them are in the LZMA SDK which is public domain and can be found at http://www.7-zip.org/sdk.html - - - -7-Zip 4.64 Sources ------------------- - -7-Zip is a file archiver for Windows 95/98/ME/NT/2000/2003/XP/Vista. - -7-Zip Copyright (C) 1999-2009 Igor Pavlov. - - -License Info ------------- - -This copy of 7-Zip is free software distributed under the GNU GPL 2.0 -(with an additional restriction that has always applied to the unRar code). -read License.txt for more infomation about license. - -Notes about unRAR license: - -Please check main restriction from unRar license: - - 2. The unRAR sources may be used in any software to handle RAR - archives without limitations free of charge, but cannot be used - to re-create the RAR compression algorithm, which is proprietary. - Distribution of modified unRAR sources in separate form or as a - part of other software is permitted, provided that it is clearly - stated in the documentation and source comments that the code may - not be used to develop a RAR (WinRAR) compatible archiver. - -In brief it means: -1) You can compile and use compiled files under GNU GPL rules, since - unRAR license almost has no restrictions for compiled files. - You can link these compiled files to GPL programs. -2) You can fix bugs in source code and use compiled fixed version. -3) You can not use unRAR sources to re-create the RAR compression algorithm. - ---- -Igor Pavlov -http://www.7-zip.org diff --git a/desmume/src/windows/7z/DOC/unRarLicense.txt b/desmume/src/windows/7z/DOC/unRarLicense.txt deleted file mode 100644 index 5f78b728d..000000000 --- a/desmume/src/windows/7z/DOC/unRarLicense.txt +++ /dev/null @@ -1,41 +0,0 @@ - ****** ***** ****** unRAR - free utility for RAR archives - ** ** ** ** ** ** ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ****** ******* ****** License for use and distribution of - ** ** ** ** ** ** ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ** ** ** ** ** ** FREE portable version - ~~~~~~~~~~~~~~~~~~~~~ - - The source code of unRAR utility is freeware. This means: - - 1. All copyrights to RAR and the utility unRAR are exclusively - owned by the author - Alexander Roshal. - - 2. The unRAR sources may be used in any software to handle RAR - archives without limitations free of charge, but cannot be used - to re-create the RAR compression algorithm, which is proprietary. - Distribution of modified unRAR sources in separate form or as a - part of other software is permitted, provided that it is clearly - stated in the documentation and source comments that the code may - not be used to develop a RAR (WinRAR) compatible archiver. - - 3. The unRAR utility may be freely distributed. No person or company - may charge a fee for the distribution of unRAR without written - permission from the copyright holder. - - 4. THE RAR ARCHIVER AND THE UNRAR UTILITY ARE DISTRIBUTED "AS IS". - NO WARRANTY OF ANY KIND IS EXPRESSED OR IMPLIED. YOU USE AT - YOUR OWN RISK. THE AUTHOR WILL NOT BE LIABLE FOR DATA LOSS, - DAMAGES, LOSS OF PROFITS OR ANY OTHER KIND OF LOSS WHILE USING - OR MISUSING THIS SOFTWARE. - - 5. Installing and using the unRAR utility signifies acceptance of - these terms and conditions of the license. - - 6. If you don't agree with terms of the license you must remove - unRAR files from your storage devices and cease to use the - utility. - - Thank you for your interest in RAR and unRAR. - - - Alexander L. Roshal \ No newline at end of file diff --git a/desmume/src/windows/7zip.cpp b/desmume/src/windows/7zip.cpp deleted file mode 100644 index 90c82027f..000000000 --- a/desmume/src/windows/7zip.cpp +++ /dev/null @@ -1,369 +0,0 @@ -#include "7zip.h" - -#include "7z/C/Types.h" -#include "7z/CPP/7zip/Archive/IArchive.h" -#include "7z/CPP/Common/InitializeStaticLib.h" // important! (if using a static lib) - -#include -#include -#include - -#include "7zipstreams.h" // defines OutStream and InFileStream - -#define _NO_CRYPTO - -STDAPI GetNumberOfFormats(UINT32 *numFormats); -STDAPI GetHandlerProperty2(UInt32 formatIndex, PROPID propID, PROPVARIANT *value); -STDAPI CreateObject(const GUID *clsid, const GUID *iid, void **outObject); - -struct ArchiveFormatInfo -{ - std::string name; - std::vector extensions; - std::string signature; - GUID guid; -}; - -static std::vector s_formatInfos; - -static std::string wstrToStr(const wchar_t* wstr) -{ - char* str = (char*)_alloca((wcslen(wstr)+1)); - sprintf(str, "%S", wstr); - return std::string(str); -} - -static std::vector tokenize(const std::string & str, const std::string & delim) -{ - std::vector tokens; - size_t p0 = 0, p1 = std::string::npos; - while(p0 != std::string::npos) - { - p1 = str.find_first_of(delim, p0); - if(p1 != p0) - { - std::string token = str.substr(p0, p1 - p0); - tokens.push_back(token); - } - p0 = str.find_first_not_of(delim, p1); - } - return tokens; -} - -static std::string s_supportedFormatsFilter; -const char* GetSupportedFormatsFilter() -{ - assert(!s_formatInfos.empty()); - if(s_supportedFormatsFilter.empty()) - { - s_supportedFormatsFilter = ""; - for(size_t i = 0; i < s_formatInfos.size(); i++) - { - for(size_t j = 0; j < s_formatInfos[i].extensions.size(); j++) - { - s_supportedFormatsFilter += ";*."; - s_supportedFormatsFilter += s_formatInfos[i].extensions[j]; - } - } - } - return s_supportedFormatsFilter.c_str(); -} - -void InitDecoder() -{ - CleanupDecoder(); - - UINT32 numFormats = 0; - GetNumberOfFormats(&numFormats); - - for(unsigned int i = 0; i < numFormats; i++) - { - PROPVARIANT var = {VT_EMPTY}; - ArchiveFormatInfo info; - - GetHandlerProperty2(i, NArchive::kName, &var); - if(var.vt == VT_BSTR) - info.name = wstrToStr(var.bstrVal); - - GetHandlerProperty2(i, NArchive::kExtension, &var); - if(var.vt == VT_BSTR) - info.extensions = tokenize(wstrToStr(var.bstrVal), " "); - - GetHandlerProperty2(i, NArchive::kStartSignature, &var); - if(var.vt == VT_BSTR) - info.signature = (const char*)var.bstrVal; // note: there's no 100% correct way of doing this with the existing 7-zip interface, but this is much better than using SysStringLen() in any way (it would return 1 for the signature "BZh", for example) - - GetHandlerProperty2(i,NArchive::kClassID,&var); - if(var.vt == VT_BSTR) - memcpy(&info.guid, var.bstrVal, 16); - else - memset(&info.guid, 0, 16); - - s_formatInfos.push_back(info); - - VariantClear((VARIANTARG*)&var); - } -} - -void CleanupDecoder() -{ - s_formatInfos.clear(); - s_supportedFormatsFilter.clear(); -} - -#include "7z/CPP/7zip/Archive/Zip/ZipHandler.h" - - -ArchiveFile::ArchiveFile(const char* filename) -{ - assert(!s_formatInfos.empty()); - - m_typeIndex = -1; - m_numItems = 0; - m_items = NULL; - m_filename = NULL; - - FILE* file = fopen(filename, "rb"); - if(!file) - return; - - m_filename = new char[strlen(filename)+1]; - strcpy(m_filename, filename); - - // detect archive type using format signature in file - for(size_t i = 0; i < s_formatInfos.size() && m_typeIndex < 0; i++) - { - fseek(file, 0, SEEK_SET); - - std::string& formatSig = s_formatInfos[i].signature; - int len = formatSig.size(); - - if(len == 0) - continue; // because some formats have no signature - - char* fileSig = (char*)_alloca(len); - fread(fileSig, 1, len, file); - - if(!memcmp(formatSig.c_str(), fileSig, len)) - m_typeIndex = i; - } - - // if no signature match has been found, detect archive type using filename. - // this is only for signature-less formats - const char* fileExt = strrchr(filename, '.'); - if(fileExt++) - { - for(size_t i = 0; i < s_formatInfos.size() && m_typeIndex < 0; i++) - { - if(s_formatInfos[i].signature.empty()) - { - std::vector& formatExts = s_formatInfos[i].extensions; - for(size_t j = 0; j < formatExts.size(); j++) - { - if(!_stricmp(formatExts[j].c_str(), fileExt)) - { - m_typeIndex = i; - break; - } - } - } - } - } - - if(m_typeIndex < 0) - { - // uncompressed - - m_numItems = 1; - m_items = new ArchiveItem[m_numItems]; - - fseek(file, 0, SEEK_END); - m_items[0].size = ftell(file); - - m_items[0].name = new char[strlen(filename)+1]; - strcpy(m_items[0].name, filename); - } - else - { - IInArchive* object = NULL; - if(SUCCEEDED(CreateObject(&s_formatInfos[m_typeIndex].guid, &IID_IInArchive, (void**)&object))) - { - InFileStream* ifs = new InFileStream(filename); - if(SUCCEEDED(object->Open(ifs,0,0))) - { - UInt32 numItems = 0; - object->GetNumberOfItems(&numItems); - m_numItems = numItems; - m_items = new ArchiveItem[m_numItems]; - - for(int i = 0; i < m_numItems; i++) - { - PROPVARIANT var = {VT_EMPTY}; - ArchiveItem& item = m_items[i]; - - object->GetProperty(i, kpidSize, &var); - item.size = var.uhVal.LowPart; - - object->GetProperty(i, kpidPath, &var); - std::string& path = wstrToStr(var.bstrVal); - item.name = new char[path.size()+1]; - strcpy(item.name, path.c_str()); - - //object->GetProperty(i, kpidMethod, &var); - //std::string& method = wstrToStr(var.bstrVal); - //item.method = new char[method.size()+1]; - //strcpy(item.method, method.c_str()); - - object->GetProperty(i, kpidEncrypted, &var); -#ifdef _NO_CRYPTO - if(var.boolVal) - item.size = 0; // don't support decompressing it, pretend size zero -#else - #error password support NYI... see client7z.cpp - item.encrypted = !!var.boolVal; -#endif - - VariantClear((VARIANTARG*)&var); - } - - object->Close(); - } - - object->Release(); - } - } - - fclose(file); -} - -ArchiveFile::~ArchiveFile() -{ - for(int i = 0; i < m_numItems; i++) - { - delete[] m_items[i].name; - } - delete[] m_items; - delete[] m_filename; -} - -const char* ArchiveFile::GetArchiveTypeName() -{ - assert(!s_formatInfos.empty()); - - if((size_t)m_typeIndex >= s_formatInfos.size()) - return ""; - - return s_formatInfos[m_typeIndex].name.c_str(); -} - -int ArchiveFile::GetNumItems() -{ - return m_numItems; -} - -int ArchiveFile::GetItemSize(int item) -{ - assert(item >= 0 && item < m_numItems); - if(!(item >= 0 && item < m_numItems)) return 0; - return m_items[item].size; -} - -const char* ArchiveFile::GetItemName(int item) -{ - //assert(item >= 0 && item < m_numItems); - if(!(item >= 0 && item < m_numItems)) return ""; - return m_items[item].name; -} - -bool ArchiveFile::IsCompressed() -{ - return (m_typeIndex >= 0); -} - -int ArchiveFile::ExtractItem(int index, unsigned char* outBuffer, int bufSize) const -{ - assert(!s_formatInfos.empty()); - //assert(index >= 0 && index < m_numItems); - if(!(index >= 0 && index < m_numItems)) return 0; - - ArchiveItem& item = m_items[index]; - - if(bufSize < item.size) - return 0; - - if(m_typeIndex < 0) - { - // uncompressed - FILE* file = fopen(m_filename, "rb"); - fread(outBuffer, 1, item.size, file); - fclose(file); - } - else - { - IInArchive* object = NULL; - HRESULT hr = E_FAIL; - if(SUCCEEDED(CreateObject(&s_formatInfos[m_typeIndex].guid, &IID_IInArchive, (void**)&object))) - { - InFileStream* ifs = new InFileStream(m_filename); - if(SUCCEEDED(object->Open(ifs,0,0))) - { - OutStream* os = new OutStream(index, outBuffer, item.size); - const UInt32 indices [1] = {index}; - hr = object->Extract(indices, 1, 0, os); - object->Close(); - } - object->Release(); - } - if(FAILED(hr)) - return 0; - } - - return item.size; -} - - - -int ArchiveFile::ExtractItem(int index, const char* outFilename) const -{ - assert(!s_formatInfos.empty()); - //assert(index >= 0 && index < m_numItems); - if(!(index >= 0 && index < m_numItems)) return 0; - - ArchiveItem& item = m_items[index]; - int rv = item.size; - - DWORD outAttributes = GetFileAttributes(outFilename); - if(outAttributes & FILE_ATTRIBUTE_READONLY) - SetFileAttributes(outFilename, outAttributes & ~FILE_ATTRIBUTE_READONLY); // temporarily remove read-only attribute so we can decompress to there - - if(m_typeIndex < 0) - { - // uncompressed - if(!CopyFile(m_filename, outFilename, false)) - rv = 0; - } - else - { - IInArchive* object = NULL; - HRESULT hr = E_FAIL; - if(SUCCEEDED(CreateObject(&s_formatInfos[m_typeIndex].guid, &IID_IInArchive, (void**)&object))) - { - InFileStream* ifs = new InFileStream(m_filename); - if(SUCCEEDED(object->Open(ifs,0,0))) - { - OutStream* os = new OutStream(index, outFilename); - const UInt32 indices [1] = {index}; - hr = object->Extract(indices, 1, 0, os); - object->Close(); - } - object->Release(); - } - if(FAILED(hr)) - rv = 0; - } - - if(outAttributes & FILE_ATTRIBUTE_READONLY) - SetFileAttributes(outFilename, outAttributes); // restore read-only attribute - - return rv; -} diff --git a/desmume/src/windows/7zip.h b/desmume/src/windows/7zip.h deleted file mode 100644 index c5d6f0af7..000000000 --- a/desmume/src/windows/7zip.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef _7ZIP_DEC_HEADER -#define _7ZIP_DEC_HEADER - -// 7zip file extraction -// NOTE: if you want to add support for opening files within archives to some part of Gens, -// consider using the higher-level interface provided by OpenArchive.h instead - -void InitDecoder(); -void CleanupDecoder(); -const char* GetSupportedFormatsFilter(); - -// simplest way of extracting a file after calling InitDecoder(): -// int size = ArchiveFile(filename).ExtractItem(0, buf, sizeof(buf)); - -struct ArchiveFile -{ - ArchiveFile(const char* filename); - virtual ~ArchiveFile(); - - int GetNumItems(); - int GetItemSize(int item); - const char* GetItemName(int item); - int ExtractItem(int item, unsigned char* outBuffer, int bufSize) const; // returns size, or 0 if failed - int ExtractItem(int item, const char* outFilename) const; - - bool IsCompressed(); - const char* GetArchiveTypeName(); - -protected: - struct ArchiveItem - { - int size; - char* name; - }; - ArchiveItem* m_items; - int m_numItems; - int m_typeIndex; - char* m_filename; -}; - -#endif diff --git a/desmume/src/windows/7zipstreams.h b/desmume/src/windows/7zipstreams.h deleted file mode 100644 index 3f44cab35..000000000 --- a/desmume/src/windows/7zipstreams.h +++ /dev/null @@ -1,315 +0,0 @@ -// This file is (modified) from -// FCEUX (2009) -// FCE Ultra - NES/Famicom Emulator -// Copyright (C) 2003 Xodnizel -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -#ifndef _7ZIPSTREAMS_HEADER -#define _7ZIPSTREAMS_HEADER - -#include "7z/CPP/Common/MyCom.h" - -class ICountedSequentialOutStream : public ISequentialOutStream -{ -public: - virtual UINT32 Size() const = 0; -}; - -class SeqMemoryOutStream : public ICountedSequentialOutStream, private CMyUnknownImp -{ - UINT8* const output; - UINT32 pos; - const UINT32 size; - ULONG refCount; - - HRESULT STDMETHODCALLTYPE QueryInterface(REFGUID, void**) - { - return E_NOINTERFACE; - } - - HRESULT STDMETHODCALLTYPE Write(const void* data, UInt32 length, UInt32* bytesWritten) - { - if (data != NULL || size == 0) - { - //assert(length <= size - pos); - - if (length > size - pos) - length = size - pos; - - if(data) - memcpy(output + pos, data, length); - pos += length; - - if (bytesWritten) - *bytesWritten = length; - - return S_OK; - } - else - { - return E_INVALIDARG; - } - } - - MY_ADDREF_RELEASE - -public: - - SeqMemoryOutStream(void* d, UINT32 s) : output((UINT8*)d), pos(0), size(s), refCount(0) {} - - virtual ~SeqMemoryOutStream() - { - int a = 0; - } - - UINT32 Size() const - { - return pos; - } -}; - -class SeqFileOutStream : public ICountedSequentialOutStream, private CMyUnknownImp -{ - FILE* file; - UINT32 pos; - ULONG refCount; - - HRESULT STDMETHODCALLTYPE QueryInterface(REFGUID, void**) - { - return E_NOINTERFACE; - } - - HRESULT STDMETHODCALLTYPE Write(const void* data, UInt32 length, UInt32* bytesWritten) - { - if(!file) - return E_FAIL; - - if (data != NULL) - { - int written = 0; - if(data) - written = fwrite(data, 1, length, file); - - pos += written; - if (bytesWritten) - *bytesWritten = written; - - return S_OK; - } - else - { - return E_INVALIDARG; - } - } - - MY_ADDREF_RELEASE - -public: - - SeqFileOutStream(const char* outFilename) : pos(0), refCount(0) - { - file = fopen(outFilename, "wb"); - } - virtual ~SeqFileOutStream() - { - if(file) - fclose(file); - } - - UINT32 Size() const - { - return pos; - } -}; - - -class OutStream : public IArchiveExtractCallback, private CMyUnknownImp -{ - ICountedSequentialOutStream* seqStream; - const UINT32 index; - ULONG refCount; - - HRESULT STDMETHODCALLTYPE QueryInterface(REFGUID, void**) - { - return E_NOINTERFACE; - } - - HRESULT STDMETHODCALLTYPE PrepareOperation(Int32) - { - return S_OK; - } - - HRESULT STDMETHODCALLTYPE SetTotal(UInt64) - { - return S_OK; - } - - HRESULT STDMETHODCALLTYPE SetCompleted(const UInt64*) - { - return S_OK; - } - - HRESULT STDMETHODCALLTYPE SetOperationResult(Int32) - { - return S_OK; - } - - HRESULT STDMETHODCALLTYPE GetStream(UInt32 id, ISequentialOutStream** ptr, Int32 mode) - { - switch (mode) - { - case NArchive::NExtract::NAskMode::kExtract: - case NArchive::NExtract::NAskMode::kTest: - - if (id != index || ptr == NULL) - return S_FALSE; - else - *ptr = seqStream; - // fall through - case NArchive::NExtract::NAskMode::kSkip: - return S_OK; - - default: - return E_INVALIDARG; - } - } - - MY_ADDREF_RELEASE - -public: - - OutStream(UINT32 index, void* data, UINT32 size) : index(index), refCount(0) - { - seqStream = new SeqMemoryOutStream(data, size); - seqStream->AddRef(); - } - OutStream(UINT32 index, const char* outFilename) : index(index), refCount(0) - { - seqStream = new SeqFileOutStream(outFilename); - seqStream->AddRef(); - } - virtual ~OutStream() - { - //seqStream->Release(); // commented out because apparently IInArchive::Extract() calls Release one more time than it calls AddRef - } - UINT32 Size() const - { - return seqStream->Size(); - } -}; - -class InStream : public IInStream, private IStreamGetSize, private CMyUnknownImp -{ - ULONG refCount; - - HRESULT STDMETHODCALLTYPE QueryInterface(REFGUID, void**) - { - return E_NOINTERFACE; - } - - HRESULT STDMETHODCALLTYPE GetSize(UInt64* outSize) - { - if (outSize) - { - *outSize = size; - return S_OK; - } - else - { - return E_INVALIDARG; - } - } - - MY_ADDREF_RELEASE - -protected: - - UINT32 size; - -public: - - explicit InStream() : refCount(0) {} - virtual ~InStream() {} -}; - - -class InFileStream : public InStream -{ -public: - - virtual ~InFileStream() - { - if(file) - fclose(file); - } - - FILE* file; - - InFileStream(const char* fname) : file(NULL) - { - file = fopen(fname, "rb"); - if(file) - { - fseek(file, 0, SEEK_END); - size = ftell(file); - fseek(file, 0, SEEK_SET); - } - } - - HRESULT STDMETHODCALLTYPE Read(void* data, UInt32 length, UInt32* bytesRead) - { - if(!file) - return E_FAIL; - - if (data != NULL || length == 0) - { - int read = fread(data, 1, length, file); - - if (bytesRead) - *bytesRead = read; - - return S_OK; - } - else - { - return E_INVALIDARG; - } - } - - HRESULT STDMETHODCALLTYPE Seek(Int64 offset, UInt32 origin, UInt64* pos) - { - if(!file) - return E_FAIL; - - if (origin < 3) - { - fseek(file, (long)offset, origin); - origin = ftell(file); - - if (pos) - *pos = origin; - - return S_OK; - } - else - { - return E_INVALIDARG; - } - - } -}; - -#endif diff --git a/desmume/src/windows/OpenArchive.cpp b/desmume/src/windows/OpenArchive.cpp deleted file mode 100644 index 207a19970..000000000 --- a/desmume/src/windows/OpenArchive.cpp +++ /dev/null @@ -1,674 +0,0 @@ -#include "common.h" -#include "main.h" -#include "driver.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include "7zip.h" -//#include "G_main.h" -//#include "G_dsound.h" -#include "resource.h" -#include "OpenArchive.h" - -static char Str_Tmp[1024]; - -LRESULT CALLBACK ArchiveFileChooser(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); -static int s_archiveFileChooserResult = -1; - -static HWND s_parentHWND = NULL; -void SetArchiveParentHWND(void* hwnd) { s_parentHWND = (HWND)hwnd; } -static HWND GetArchiveParentHWND() { return s_parentHWND ? s_parentHWND : MainWindow->getHWnd(); } - -struct ArchiveFileChooserInfo -{ - ArchiveFileChooserInfo(ArchiveFile& theArchive, const char** ignoreExtensions, int& numIgnoreExtensions) : archive(theArchive) - { -tryagain: - int numItems = archive.GetNumItems(); - for(int i = 0; i < numItems; i++) - { - if(archive.GetItemSize(i)) - { - const char* name = archive.GetItemName(i); - const char* ext = strrchr(name, '.'); - bool ok = true; - if(ext++) - { - for(int j = 0; j < numIgnoreExtensions; j++) - { - const char* ext2 = ignoreExtensions[j]; - const char* wild = strchr(ext2, '*'); - if(!wild) - { - if(!_stricmp(ext, ext2)) - { - ok = false; - break; - } - } - else // very limited (end only) wildcard support - { - if(!_strnicmp(ext, ext2, wild - ext2)) - { - ok = false; - break; - } - } - } - } - if(ok) - { - ArchiveFileChooserInfo::FileInfo fi = { name, i }; - files.push_back(fi); - } - } - } - - if(files.empty() && numIgnoreExtensions) - { - // try again without any exclusions if we excluded everything in the archive - numIgnoreExtensions = 0; - goto tryagain; - } - - // strip away prefix paths that are common to all the files - bool stripping = !files.empty(); - while(stripping) - { - const char* firstName = files[0].name.c_str(); - const char* slash = strchr(firstName, '\\'); - const char* slash2 = strchr(firstName, '/'); - slash = std::max(slash, slash2); - if(!slash++) - break; - for(size_t i = 1; i < files.size(); i++) - if(strncmp(firstName, files[i].name.c_str(), slash - firstName)) - stripping = false; - if(stripping) - for(size_t i = 0; i < files.size(); i++) - files[i].name = files[i].name.substr(slash - firstName, files[i].name.length() - (slash - firstName)); - } - - // sort by filename - std::sort(files.begin(), files.end(), FileInfo::Sort); - } - -//protected: - - struct FileInfo - { - std::string name; - int itemIndex; - - static bool Sort(const FileInfo& elem1, const FileInfo& elem2) - { - int comp = elem1.name.compare(elem2.name); - return comp ? (comp < 0) : (elem1.itemIndex < elem2.itemIndex); - } - }; - - ArchiveFile& archive; - std::vector files; -}; - -int ChooseItemFromArchive(ArchiveFile& archive, bool autoChooseIfOnly1, const char** ignoreExtensions, int numIgnoreExtensions) -{ - int prevNumIgnoreExtensions = numIgnoreExtensions; - - // prepare a list of files to choose from the archive - ArchiveFileChooserInfo info (archive, ignoreExtensions, numIgnoreExtensions); - - // based on our list, decide which item in the archive to choose - - // check if there's nothing - if(info.files.size() < 1) - { -// DialogsOpen++; - MessageBox(GetArchiveParentHWND(), "The archive is either empty or encrypted.", "Nothing to load!", MB_OK | MB_ICONWARNING); -// DialogsOpen--; - return -1; - } - - // if there's only 1 item, choose it - if(info.files.size() == 1 && autoChooseIfOnly1 && numIgnoreExtensions == prevNumIgnoreExtensions) - return info.files[0].itemIndex; - - // bring up a dialog to choose the index if there's more than 1 - DialogBoxParam(hAppInst, MAKEINTRESOURCE(IDD_ARCHIVEFILECHOOSER), GetArchiveParentHWND(), (DLGPROC) ArchiveFileChooser,(LPARAM) &info); - return s_archiveFileChooserResult; -} - - - - -#define DEFAULT_EXTENSION ".tmp" -#define DEFAULT_CATEGORY "gens" - -static struct TempFiles -{ - struct TemporaryFile - { - TemporaryFile(const char* cat, const char* ext) - { - if(!ext || !*ext) ext = DEFAULT_EXTENSION; - if(!cat || !*cat) cat = DEFAULT_CATEGORY; - category = cat; - - char tempPath [1024]; - GetTempPath(1024, tempPath); - //GetTempFileName(tempPath, cat, 0, filename, ext); // alas - - char*const fname = tempPath + strlen(tempPath); - unsigned short start = (unsigned short)(timeGetTime() & 0xFFFF); - unsigned short n = start + 1; - while(n != start) - { - _snprintf(fname, 1024 - (fname - tempPath), "%s%04X%s", cat, n, ext); - FILE* file = fopen(tempPath, "wb"); - if(file) - { - // mark the temporary file as read-only and (whatever this does) temporary - DWORD attributes = GetFileAttributes(tempPath); - attributes |= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_TEMPORARY; - SetFileAttributes(tempPath, attributes); - - fclose(file); - - // add it to our registry of files that need to be deleted, in case we fail to terminate properly - TempFiles::AddEntryToGarbageRegistry(tempPath); - - break; - } - n++; - } - strcpy(filename, tempPath); - } - TemporaryFile(const TemporaryFile& copy) - { - strcpy(filename, copy.filename); - category = copy.category; - } - TemporaryFile() - { - filename[0] = 0; - category[0] = 0; - } - bool Delete(bool returnFalseOnRegistryRemovalFailure=false) - { - if(!*filename) - return true; // guess it already didn't exist - - // remove read-only attribute so Windows will let us delete it - // (our temporary files are read-only to discourage other apps from tampering) - DWORD attributes = GetFileAttributes(filename); - if(attributes & FILE_ATTRIBUTE_READONLY) - SetFileAttributes(filename, attributes & ~FILE_ATTRIBUTE_READONLY); - - if(_unlink(filename) == 0 || errno != EACCES) - { - // remove it from our registry of files that need to be deleted, to reduce accumulation - bool removed = TempFiles::RemoveEntryFromGarbageRegistry(filename); - - *filename = '\0'; - return removed || !returnFalseOnRegistryRemovalFailure; // successfully deleted or already didn't exist, return true unless registry removal failure notification was requested and that failed - } - - // restore read-only if we couldn't delete it (not sure if this ever succeeds or matters though) - if(attributes & FILE_ATTRIBUTE_READONLY) - SetFileAttributes(filename, attributes); - - return false; // failed to delete read-only or in-use file - } - char filename [MAX_PATH]; - std::string category; - }; - - std::vector tempFiles; - - const char* GetFile(const char* category, const char* extension) - { - tempFiles.push_back(TemporaryFile(category, extension)); - return tempFiles.back().filename; - } - - void ReleaseFile(const char* filename) - { - for(int i = (int)tempFiles.size()-1; i >= 0; i--) - { - if(!strcmp(filename, tempFiles[i].filename)) - { - if(tempFiles[i].Delete()) - tempFiles.erase(tempFiles.begin() + i); - } - } - } - - void ReleaseCategory(const char* cat, const char* exceptionFilename) - { - for(int i = (int)tempFiles.size()-1; i >= 0; i--) - { - if(!strcmp(cat, tempFiles[i].category.c_str()) && - (!exceptionFilename || - strcmp(exceptionFilename, tempFiles[i].filename))) - { - if(tempFiles[i].Delete()) - tempFiles.erase(tempFiles.begin() + i); - } - } - } - - // delete all temporary files on shutdown - ~TempFiles() - { - for(size_t i = 0; i < tempFiles.size(); i++) - { - tempFiles[i].Delete(); - } - - TempFiles::CleanOutGarbageRegistry(); - } - - // run this on startup to delete any files that we failed to delete last time - // in case we crashed or were forcefully terminated - TempFiles() - { - TempFiles::CleanOutGarbageRegistry(); - } - - static void AddEntryToGarbageRegistry(const char* filename) - { - char gbgFile[1024]; - GetTempPath(1024, gbgFile); - strcat(gbgFile, "GensTempFileRecords"); - char key[64]; - int i = 0; - while(true) - { - sprintf(key, "File%d", i); - GetPrivateProfileString("Files", key, "", Str_Tmp, 1024, gbgFile); - if(!*Str_Tmp) - break; - i++; - } - WritePrivateProfileString("Files", key, filename, gbgFile); - } - static bool RemoveEntryFromGarbageRegistry(const char* filename) - { - char gbgFile[1024]; - GetTempPath(1024, gbgFile); - strcat(gbgFile, "GensTempFileRecords"); - char key[64]; - int i = 0; - int deleteSlot = -1; - while(true) - { - sprintf(key, "File%d", i); - GetPrivateProfileString("Files", key, "", Str_Tmp, 1024, gbgFile); - if(!*Str_Tmp) - break; - if(!strcmp(Str_Tmp, filename)) - deleteSlot = i; - i++; - } - --i; - if(i >= 0 && deleteSlot >= 0) - { - if(i != deleteSlot) - { - sprintf(key, "File%d", i); - GetPrivateProfileString("Files", key, "", Str_Tmp, 1024, gbgFile); - sprintf(key, "File%d", deleteSlot); - WritePrivateProfileString("Files", key, Str_Tmp, gbgFile); - } - sprintf(key, "File%d", i); - if(0 == WritePrivateProfileString("Files", key, NULL, gbgFile)) - return false; - } - if(i <= 0 && deleteSlot == 0) - _unlink(gbgFile); - return true; - } - -private: - static void CleanOutGarbageRegistry() - { - char gbgFile[1024]; - GetTempPath(1024, gbgFile); - strcat(gbgFile, "GensTempFileRecords"); - - char key[64]; - int i = 0; - while(true) - { - sprintf(key, "File%d", i); - GetPrivateProfileString("Files", key, "", Str_Tmp, 1024, gbgFile); - if(!*Str_Tmp) - break; - TemporaryFile temp; - strcpy(temp.filename, Str_Tmp); - if(!temp.Delete(true)) - i++; - } - } - -} s_tempFiles; - - -const char* GetTempFile(const char* category, const char* extension) -{ - return s_tempFiles.GetFile(category, extension); -} -void ReleaseTempFile(const char* filename) -{ - s_tempFiles.ReleaseFile(filename); -} -void ReleaseTempFileCategory(const char* cat, const char* exceptionFilename) -{ - if(!cat || !*cat) cat = DEFAULT_CATEGORY; - s_tempFiles.ReleaseCategory(cat, exceptionFilename); -} - - - -// example input Name: "C:\games.zip" -// example output LogicalName: "C:\games.zip|Sonic.smd" -// example output PhysicalName: "C:\Documents and Settings\User\Local Settings\Temp\Gens\dec3.tmp" -// assumes arguments are character buffers with 1024 bytes each -bool ObtainFile(const char* Name, char *const & LogicalName, char *const & PhysicalName, const char* category, const char** ignoreExtensions, int numIgnoreExtensions) -{ - char ArchivePaths [1024]; - strcpy(LogicalName, Name); - strcpy(PhysicalName, Name); - strcpy(ArchivePaths, Name); - char* bar = strchr(ArchivePaths, '|'); - if(bar) - { - PhysicalName[bar - ArchivePaths] = 0; // doesn't belong in the physical name - LogicalName[bar - ArchivePaths] = 0; // we'll reconstruct the logical name as we go - *bar++ = 0; // bar becomes the next logical archive path component - } - - while(true) - { - ArchiveFile archive (PhysicalName); - if(!archive.IsCompressed()) - { - return archive.GetNumItems() > 0; - } - else - { - int item = -1; - bool forceManual = false; - if(bar && *bar) // try following the in-archive part of the logical path - { - char* bar2 = strchr(bar, '|'); - if(bar2) *bar2++ = 0; - int numItems = archive.GetNumItems(); - for(int i = 0; i < numItems; i++) - { - if(archive.GetItemSize(i)) - { - const char* itemName = archive.GetItemName(i); - if(!_stricmp(itemName, bar)) - { - item = i; // match found, now we'll auto-follow the path - break; - } - } - } - if(item < 0) - { - forceManual = true; // we don't want it choosing something else without user permission - bar = NULL; // remaining archive path is invalid - } - else - bar = bar2; // advance to next archive path part - } - if(item < 0) - item = ChooseItemFromArchive(archive, !forceManual, ignoreExtensions, numIgnoreExtensions); - - const char* TempFileName = s_tempFiles.GetFile(category, strrchr(archive.GetItemName(item), '.')); - if(!archive.ExtractItem(item, TempFileName)) - s_tempFiles.ReleaseFile(TempFileName); - s_tempFiles.ReleaseFile(PhysicalName); - strcpy(PhysicalName, TempFileName); - _snprintf(LogicalName + strlen(LogicalName), 1024 - (strlen(LogicalName)+1), "|%s", archive.GetItemName(item)); - } - } -} - - - -struct ControlLayoutInfo -{ - int controlID; - - enum LayoutType // what to do when the containing window resizes - { - NONE, // leave the control where it was - RESIZE_END, // resize the control - MOVE_START, // move the control - }; - LayoutType horizontalLayout; - LayoutType verticalLayout; -}; -struct ControlLayoutState -{ - int x,y,width,height; - bool valid; - ControlLayoutState() : valid(false) {} -}; - -static ControlLayoutInfo controlLayoutInfos [] = { - {IDC_LIST1, ControlLayoutInfo::RESIZE_END, ControlLayoutInfo::RESIZE_END}, - {IDOK, ControlLayoutInfo::MOVE_START, ControlLayoutInfo::MOVE_START}, - {IDCANCEL, ControlLayoutInfo::MOVE_START, ControlLayoutInfo::MOVE_START}, -}; -static const int numControlLayoutInfos = sizeof(controlLayoutInfos)/sizeof(*controlLayoutInfos); - -static ControlLayoutState s_layoutState [numControlLayoutInfos]; -static int s_windowWidth = 182, s_windowHeight = 113; - - -LRESULT CALLBACK ArchiveFileChooser(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - RECT r, r2; - int dx1, dy1, dx2, dy2; - static std::map s_listToItemsMap; - - switch(uMsg) - { - case WM_INITDIALOG: - { -// DialogsOpen++; -// Clear_Sound_Buffer(); - -// if(Full_Screen) -// { -// while (ShowCursor(false) >= 0); -// while (ShowCursor(true) < 0); -// } - - GetWindowRect(MainWindow->getHWnd(), &r); - dx1 = (r.right - r.left) / 2; - dy1 = (r.bottom - r.top) / 2; - - GetWindowRect(hDlg, &r2); - dx2 = (r2.right - r2.left) / 2; - dy2 = (r2.bottom - r2.top) / 2; - - //SetWindowPos(hDlg, NULL, max(0, r.left + (dx1 - dx2)), max(0, r.top + (dy1 - dy2)), NULL, NULL, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW); - SetWindowPos(hDlg, NULL, r.left, r.top, NULL, NULL, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW); - - ArchiveFileChooserInfo& info = *(ArchiveFileChooserInfo*)lParam; - std::vector& files = info.files; - ArchiveFile& archive = info.archive; - - std::string title = "Choose File in "; - title += archive.GetArchiveTypeName(); - title += " Archive"; - SetWindowText(hDlg, title.c_str()); - - // populate list - for(size_t i = 0; i < files.size(); i++) - { - int listIndex = SendDlgItemMessage(hDlg, IDC_LIST1, LB_ADDSTRING, (WPARAM) 0, (LONG) (LPTSTR) files[i].name.c_str()); - s_listToItemsMap[listIndex] = files[i].itemIndex; - } - - SendDlgItemMessage(hDlg, IDC_LIST1, LB_SETCURSEL, (WPARAM) 0, (LPARAM) 0); - - { - RECT r3; - GetClientRect(hDlg, &r3); - s_windowWidth = r3.right - r3.left; - s_windowHeight = r3.bottom - r3.top; - } - - return true; - } break; - - case WM_SIZING: - { - // enforce a minimum window size - - LPRECT r = (LPRECT) lParam; - int minimumWidth = 281; - int minimumHeight = 117; - if(r->right - r->left < minimumWidth) - if(wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT) - r->left = r->right - minimumWidth; - else - r->right = r->left + minimumWidth; - if(r->bottom - r->top < minimumHeight) - if(wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT) - r->top = r->bottom - minimumHeight; - else - r->bottom = r->top + minimumHeight; - return TRUE; - } - - case WM_SIZE: - { - // resize or move controls in the window as necessary when the window is resized - - int prevDlgWidth = s_windowWidth; - int prevDlgHeight = s_windowHeight; - - int dlgWidth = LOWORD(lParam); - int dlgHeight = HIWORD(lParam); - - int deltaWidth = dlgWidth - prevDlgWidth; - int deltaHeight = dlgHeight - prevDlgHeight; - - for(int i = 0; i < numControlLayoutInfos; i++) - { - ControlLayoutInfo layoutInfo = controlLayoutInfos[i]; - ControlLayoutState& layoutState = s_layoutState[i]; - - HWND hCtrl = GetDlgItem(hDlg,layoutInfo.controlID); - - int x,y,width,height; - if(layoutState.valid) - { - x = layoutState.x; - y = layoutState.y; - width = layoutState.width; - height = layoutState.height; - } - else - { - RECT r; - GetWindowRect(hCtrl, &r); - POINT p = {r.left, r.top}; - ScreenToClient(hDlg, &p); - x = p.x; - y = p.y; - width = r.right - r.left; - height = r.bottom - r.top; - } - - switch(layoutInfo.horizontalLayout) - { - case ControlLayoutInfo::RESIZE_END: width += deltaWidth; break; - case ControlLayoutInfo::MOVE_START: x += deltaWidth; break; - default: break; - } - switch(layoutInfo.verticalLayout) - { - case ControlLayoutInfo::RESIZE_END: height += deltaHeight; break; - case ControlLayoutInfo::MOVE_START: y += deltaHeight; break; - default: break; - } - - SetWindowPos(hCtrl, 0, x,y, width,height, 0); - - layoutState.x = x; - layoutState.y = y; - layoutState.width = width; - layoutState.height = height; - layoutState.valid = true; - } - - s_windowWidth = dlgWidth; - s_windowHeight = dlgHeight; - - RedrawWindow(hDlg, NULL, NULL, RDW_INVALIDATE); - } - break; - - case WM_COMMAND: - switch(LOWORD(wParam)) - { - case IDC_LIST1: - if(HIWORD(wParam) == LBN_DBLCLK) - SendMessage(hDlg, WM_COMMAND, IDOK, 0); - return TRUE; - - case IDOK: - { - int listIndex = SendDlgItemMessage(hDlg, IDC_LIST1, LB_GETCURSEL, (WPARAM) 0, (LPARAM) 0); - s_archiveFileChooserResult = s_listToItemsMap[listIndex]; - s_listToItemsMap.clear(); -// if(Full_Screen) -// { -// while (ShowCursor(true) < 0); -// while (ShowCursor(false) >= 0); -// } -// DialogsOpen--; - EndDialog(hDlg, false); - } return TRUE; - - case IDCANCEL: - s_archiveFileChooserResult = -1; - s_listToItemsMap.clear(); -// if(Full_Screen) -// { -// while (ShowCursor(true) < 0); -// while (ShowCursor(false) >= 0); -// } -// DialogsOpen--; - EndDialog(hDlg, false); - return TRUE; - } - - case WM_CLOSE: - s_archiveFileChooserResult = -1; - s_listToItemsMap.clear(); -// if(Full_Screen) -// { -// while (ShowCursor(true) < 0); -// while (ShowCursor(false) >= 0); -// } -// DialogsOpen--; - EndDialog(hDlg, false); - return TRUE; - } - - return false; -} diff --git a/desmume/src/windows/OpenArchive.h b/desmume/src/windows/OpenArchive.h deleted file mode 100644 index 52a04c89c..000000000 --- a/desmume/src/windows/OpenArchive.h +++ /dev/null @@ -1,43 +0,0 @@ -// for retrieving files from archives and/or managing temporary files - -#ifndef OPENARCHIVE_HEADER -#define OPENARCHIVE_HEADER - -#include "7zip.h" - -// ObtainFile() -// this is the main, high-level function for opening possibly-compressed files. -// you don't need to check whether the file is compressed beforehand, -// this function will figure that out and work correctly either way. -// it also does the work of bringing up a within-archive file selector dialog if necessary, -// which even allows navigating to a file within an archive that's within the archive. -// the output PhysicalName is the filename of an uncompressed file -// for you to load with fopen or whatever, -// unless the function fails (or is cancelled) in which case it will return false. -// example input Name: "C:\games.zip" -// example output LogicalName: "C:\games.zip|Sonic.smd" -// example output PhysicalName: "C:\Documents and Settings\User\Local Settings\Temp\Gens\rom7A37.smd" -// assumes the three name arguments are unique character buffers with exactly 1024 bytes each -bool ObtainFile(const char* Name, char *const & LogicalName, char *const & PhysicalName, const char* category=NULL, const char** ignoreExtensions=NULL, int numIgnoreExtensions=0); - -// ReleaseTempFileCategory() -// this is for deleting the temporary files that ObtainFile() can create. -// using it is optional because they will auto-delete on proper shutdown of the program, -// but it's nice to be able to clean up the files as early as possible. -// pass in the same "category" string you passed into ObtainFile(), -// and this will delete all files of that category. -// you can optionally specify one filename to not delete even if its category matches. -// note that any still-open files cannot be deleted yet and will be skipped. -void ReleaseTempFileCategory(const char* category, const char* exceptionFilename=NULL); - -// sets the parent window of subsequent archive selector dialogs -// NULL resets this to the default (main Gens emulator window) -void SetArchiveParentHWND(void* hwnd=NULL); - -// the rest of these are more internal utility functions, -// but they could be generally useful outside of that -const char* GetTempFile(const char* category=NULL, const char* extension=NULL); // creates a temp file and returns a path to it. extension if any should include the '.' -void ReleaseTempFile(const char* filename); // deletes a particular temporary file, by filename -int ChooseItemFromArchive(ArchiveFile& archive, bool autoChooseIfOnly1=true, const char** ignoreExtensions=0, int numIgnoreExtensions=0); // gets an index to a file within an already-open archive, using the file chooser if there's more than one choice - -#endif \ No newline at end of file diff --git a/desmume/src/windows/lua/lib/lua-5.1.4-x86.lib b/desmume/src/windows/lua/lib/lua-5.1.4-x86.lib deleted file mode 100644 index 8e5eae2f3..000000000 Binary files a/desmume/src/windows/lua/lib/lua-5.1.4-x86.lib and /dev/null differ diff --git a/desmume/src/windows/lua/lua-5.1.4/COPYRIGHT b/desmume/src/windows/lua/lua-5.1.4/COPYRIGHT deleted file mode 100644 index 3a53e741e..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/COPYRIGHT +++ /dev/null @@ -1,34 +0,0 @@ -Lua License ------------ - -Lua is licensed under the terms of the MIT license reproduced below. -This means that Lua is free software and can be used for both academic -and commercial purposes at absolutely no cost. - -For details and rationale, see http://www.lua.org/license.html . - -=============================================================================== - -Copyright (C) 1994-2008 Lua.org, PUC-Rio. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -=============================================================================== - -(end of COPYRIGHT) diff --git a/desmume/src/windows/lua/lua-5.1.4/src/Makefile b/desmume/src/windows/lua/lua-5.1.4/src/Makefile deleted file mode 100644 index e4a3cd610..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/Makefile +++ /dev/null @@ -1,182 +0,0 @@ -# makefile for building Lua -# see ../INSTALL for installation instructions -# see ../Makefile and luaconf.h for further customization - -# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT ======================= - -# Your platform. See PLATS for possible values. -PLAT= none - -CC= gcc -CFLAGS= -O2 -Wall $(MYCFLAGS) -AR= ar rcu -RANLIB= ranlib -RM= rm -f -LIBS= -lm $(MYLIBS) - -MYCFLAGS= -MYLDFLAGS= -MYLIBS= - -# == END OF USER SETTINGS. NO NEED TO CHANGE ANYTHING BELOW THIS LINE ========= - -PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris - -LUA_A= liblua.a -CORE_O= lapi.o lcode.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o \ - lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o \ - lundump.o lvm.o lzio.o -LIB_O= lauxlib.o lbaselib.o ldblib.o liolib.o lmathlib.o loslib.o ltablib.o \ - lstrlib.o loadlib.o linit.o - -LUA_T= lua -LUA_O= lua.o - -LUAC_T= luac -LUAC_O= luac.o print.o - -ALL_O= $(CORE_O) $(LIB_O) $(LUA_O) $(LUAC_O) -ALL_T= $(LUA_A) $(LUA_T) $(LUAC_T) -ALL_A= $(LUA_A) - -default: $(PLAT) - -all: $(ALL_T) - -o: $(ALL_O) - -a: $(ALL_A) - -$(LUA_A): $(CORE_O) $(LIB_O) - $(AR) $@ $? - $(RANLIB) $@ - -$(LUA_T): $(LUA_O) $(LUA_A) - $(CC) -o $@ $(MYLDFLAGS) $(LUA_O) $(LUA_A) $(LIBS) - -$(LUAC_T): $(LUAC_O) $(LUA_A) - $(CC) -o $@ $(MYLDFLAGS) $(LUAC_O) $(LUA_A) $(LIBS) - -clean: - $(RM) $(ALL_T) $(ALL_O) - -depend: - @$(CC) $(CFLAGS) -MM l*.c print.c - -echo: - @echo "PLAT = $(PLAT)" - @echo "CC = $(CC)" - @echo "CFLAGS = $(CFLAGS)" - @echo "AR = $(AR)" - @echo "RANLIB = $(RANLIB)" - @echo "RM = $(RM)" - @echo "MYCFLAGS = $(MYCFLAGS)" - @echo "MYLDFLAGS = $(MYLDFLAGS)" - @echo "MYLIBS = $(MYLIBS)" - -# convenience targets for popular platforms - -none: - @echo "Please choose a platform:" - @echo " $(PLATS)" - -aix: - $(MAKE) all CC="xlc" CFLAGS="-O2 -DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-ldl" MYLDFLAGS="-brtl -bexpall" - -ansi: - $(MAKE) all MYCFLAGS=-DLUA_ANSI - -bsd: - $(MAKE) all MYCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-Wl,-E" - -freebsd: - $(MAKE) all MYCFLAGS="-DLUA_USE_LINUX" MYLIBS="-Wl,-E -lreadline" - -generic: - $(MAKE) all MYCFLAGS= - -linux: - $(MAKE) all MYCFLAGS=-DLUA_USE_LINUX MYLIBS="-Wl,-E -ldl -lreadline -lhistory -lncurses" - -macosx: - $(MAKE) all MYCFLAGS=-DLUA_USE_LINUX MYLIBS="-lreadline" -# use this on Mac OS X 10.3- -# $(MAKE) all MYCFLAGS=-DLUA_USE_MACOSX - -mingw: - $(MAKE) "LUA_A=lua51.dll" "LUA_T=lua.exe" \ - "AR=$(CC) -shared -o" "RANLIB=strip --strip-unneeded" \ - "MYCFLAGS=-DLUA_BUILD_AS_DLL" "MYLIBS=" "MYLDFLAGS=-s" lua.exe - $(MAKE) "LUAC_T=luac.exe" luac.exe - -posix: - $(MAKE) all MYCFLAGS=-DLUA_USE_POSIX - -solaris: - $(MAKE) all MYCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" MYLIBS="-ldl" - -# list targets that do not create files (but not all makes understand .PHONY) -.PHONY: all $(PLATS) default o a clean depend echo none - -# DO NOT DELETE - -lapi.o: lapi.c lua.h luaconf.h lapi.h lobject.h llimits.h ldebug.h \ - lstate.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h \ - lundump.h lvm.h -lauxlib.o: lauxlib.c lua.h luaconf.h lauxlib.h -lbaselib.o: lbaselib.c lua.h luaconf.h lauxlib.h lualib.h -lcode.o: lcode.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \ - lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lgc.h \ - ltable.h -ldblib.o: ldblib.c lua.h luaconf.h lauxlib.h lualib.h -ldebug.o: ldebug.c lua.h luaconf.h lapi.h lobject.h llimits.h lcode.h \ - llex.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h \ - lfunc.h lstring.h lgc.h ltable.h lvm.h -ldo.o: ldo.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ - lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lparser.h lstring.h \ - ltable.h lundump.h lvm.h -ldump.o: ldump.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h \ - lzio.h lmem.h lundump.h -lfunc.o: lfunc.c lua.h luaconf.h lfunc.h lobject.h llimits.h lgc.h lmem.h \ - lstate.h ltm.h lzio.h -lgc.o: lgc.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ - lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h -linit.o: linit.c lua.h luaconf.h lualib.h lauxlib.h -liolib.o: liolib.c lua.h luaconf.h lauxlib.h lualib.h -llex.o: llex.c lua.h luaconf.h ldo.h lobject.h llimits.h lstate.h ltm.h \ - lzio.h lmem.h llex.h lparser.h lstring.h lgc.h ltable.h -lmathlib.o: lmathlib.c lua.h luaconf.h lauxlib.h lualib.h -lmem.o: lmem.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \ - ltm.h lzio.h lmem.h ldo.h -loadlib.o: loadlib.c lua.h luaconf.h lauxlib.h lualib.h -lobject.o: lobject.c lua.h luaconf.h ldo.h lobject.h llimits.h lstate.h \ - ltm.h lzio.h lmem.h lstring.h lgc.h lvm.h -lopcodes.o: lopcodes.c lopcodes.h llimits.h lua.h luaconf.h -loslib.o: loslib.c lua.h luaconf.h lauxlib.h lualib.h -lparser.o: lparser.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \ - lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h \ - lfunc.h lstring.h lgc.h ltable.h -lstate.o: lstate.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \ - ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h llex.h lstring.h ltable.h -lstring.o: lstring.c lua.h luaconf.h lmem.h llimits.h lobject.h lstate.h \ - ltm.h lzio.h lstring.h lgc.h -lstrlib.o: lstrlib.c lua.h luaconf.h lauxlib.h lualib.h -ltable.o: ltable.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \ - ltm.h lzio.h lmem.h ldo.h lgc.h ltable.h -ltablib.o: ltablib.c lua.h luaconf.h lauxlib.h lualib.h -ltm.o: ltm.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h lzio.h \ - lmem.h lstring.h lgc.h ltable.h -lua.o: lua.c lua.h luaconf.h lauxlib.h lualib.h -luac.o: luac.c lua.h luaconf.h lauxlib.h ldo.h lobject.h llimits.h \ - lstate.h ltm.h lzio.h lmem.h lfunc.h lopcodes.h lstring.h lgc.h \ - lundump.h -lundump.o: lundump.c lua.h luaconf.h ldebug.h lstate.h lobject.h \ - llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h lundump.h -lvm.o: lvm.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ - lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h ltable.h lvm.h -lzio.o: lzio.c lua.h luaconf.h llimits.h lmem.h lstate.h lobject.h ltm.h \ - lzio.h -print.o: print.c ldebug.h lstate.h lua.h luaconf.h lobject.h llimits.h \ - ltm.h lzio.h lmem.h lopcodes.h lundump.h - -# (end of Makefile) diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lapi.c b/desmume/src/windows/lua/lua-5.1.4/src/lapi.c deleted file mode 100644 index 5d5145d2e..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lapi.c +++ /dev/null @@ -1,1087 +0,0 @@ -/* -** $Id: lapi.c,v 2.55.1.5 2008/07/04 18:41:18 roberto Exp $ -** Lua API -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include - -#define lapi_c -#define LUA_CORE - -#include "lua.h" - -#include "lapi.h" -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lgc.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" -#include "lundump.h" -#include "lvm.h" - - - -const char lua_ident[] = - "$Lua: " LUA_RELEASE " " LUA_COPYRIGHT " $\n" - "$Authors: " LUA_AUTHORS " $\n" - "$URL: www.lua.org $\n"; - - - -#define api_checknelems(L, n) api_check(L, (n) <= (L->top - L->base)) - -#define api_checkvalidindex(L, i) api_check(L, (i) != luaO_nilobject) - -#define api_incr_top(L) {api_check(L, L->top < L->ci->top); L->top++;} - - - -static TValue *index2adr (lua_State *L, int idx) { - if (idx > 0) { - TValue *o = L->base + (idx - 1); - api_check(L, idx <= L->ci->top - L->base); - if (o >= L->top) return cast(TValue *, luaO_nilobject); - else return o; - } - else if (idx > LUA_REGISTRYINDEX) { - api_check(L, idx != 0 && -idx <= L->top - L->base); - return L->top + idx; - } - else switch (idx) { /* pseudo-indices */ - case LUA_REGISTRYINDEX: return registry(L); - case LUA_ENVIRONINDEX: { - Closure *func = curr_func(L); - sethvalue(L, &L->env, func->c.env); - return &L->env; - } - case LUA_GLOBALSINDEX: return gt(L); - default: { - Closure *func = curr_func(L); - idx = LUA_GLOBALSINDEX - idx; - return (idx <= func->c.nupvalues) - ? &func->c.upvalue[idx-1] - : cast(TValue *, luaO_nilobject); - } - } -} - - -static Table *getcurrenv (lua_State *L) { - if (L->ci == L->base_ci) /* no enclosing function? */ - return hvalue(gt(L)); /* use global table as environment */ - else { - Closure *func = curr_func(L); - return func->c.env; - } -} - - -void luaA_pushobject (lua_State *L, const TValue *o) { - setobj2s(L, L->top, o); - api_incr_top(L); -} - - -LUA_API int lua_checkstack (lua_State *L, int size) { - int res = 1; - lua_lock(L); - if (size > LUAI_MAXCSTACK || (L->top - L->base + size) > LUAI_MAXCSTACK) - res = 0; /* stack overflow */ - else if (size > 0) { - luaD_checkstack(L, size); - if (L->ci->top < L->top + size) - L->ci->top = L->top + size; - } - lua_unlock(L); - return res; -} - - -LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) { - int i; - if (from == to) return; - lua_lock(to); - api_checknelems(from, n); - api_check(from, G(from) == G(to)); - api_check(from, to->ci->top - to->top >= n); - from->top -= n; - for (i = 0; i < n; i++) { - setobj2s(to, to->top++, from->top + i); - } - lua_unlock(to); -} - - -LUA_API void lua_setlevel (lua_State *from, lua_State *to) { - to->nCcalls = from->nCcalls; -} - - -LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) { - lua_CFunction old; - lua_lock(L); - old = G(L)->panic; - G(L)->panic = panicf; - lua_unlock(L); - return old; -} - - -LUA_API lua_State *lua_newthread (lua_State *L) { - lua_State *L1; - lua_lock(L); - luaC_checkGC(L); - L1 = luaE_newthread(L); - setthvalue(L, L->top, L1); - api_incr_top(L); - lua_unlock(L); - luai_userstatethread(L, L1); - return L1; -} - - - -/* -** basic stack manipulation -*/ - - -LUA_API int lua_gettop (lua_State *L) { - return cast_int(L->top - L->base); -} - - -LUA_API void lua_settop (lua_State *L, int idx) { - lua_lock(L); - if (idx >= 0) { - api_check(L, idx <= L->stack_last - L->base); - while (L->top < L->base + idx) - setnilvalue(L->top++); - L->top = L->base + idx; - } - else { - api_check(L, -(idx+1) <= (L->top - L->base)); - L->top += idx+1; /* `subtract' index (index is negative) */ - } - lua_unlock(L); -} - - -LUA_API void lua_remove (lua_State *L, int idx) { - StkId p; - lua_lock(L); - p = index2adr(L, idx); - api_checkvalidindex(L, p); - while (++p < L->top) setobjs2s(L, p-1, p); - L->top--; - lua_unlock(L); -} - - -LUA_API void lua_insert (lua_State *L, int idx) { - StkId p; - StkId q; - lua_lock(L); - p = index2adr(L, idx); - api_checkvalidindex(L, p); - for (q = L->top; q>p; q--) setobjs2s(L, q, q-1); - setobjs2s(L, p, L->top); - lua_unlock(L); -} - - -LUA_API void lua_replace (lua_State *L, int idx) { - StkId o; - lua_lock(L); - /* explicit test for incompatible code */ - if (idx == LUA_ENVIRONINDEX && L->ci == L->base_ci) - luaG_runerror(L, "no calling environment"); - api_checknelems(L, 1); - o = index2adr(L, idx); - api_checkvalidindex(L, o); - if (idx == LUA_ENVIRONINDEX) { - Closure *func = curr_func(L); - api_check(L, ttistable(L->top - 1)); - func->c.env = hvalue(L->top - 1); - luaC_barrier(L, func, L->top - 1); - } - else { - setobj(L, o, L->top - 1); - if (idx < LUA_GLOBALSINDEX) /* function upvalue? */ - luaC_barrier(L, curr_func(L), L->top - 1); - } - L->top--; - lua_unlock(L); -} - - -LUA_API void lua_pushvalue (lua_State *L, int idx) { - lua_lock(L); - setobj2s(L, L->top, index2adr(L, idx)); - api_incr_top(L); - lua_unlock(L); -} - - - -/* -** access functions (stack -> C) -*/ - - -LUA_API int lua_type (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - return (o == luaO_nilobject) ? LUA_TNONE : ttype(o); -} - - -LUA_API const char *lua_typename (lua_State *L, int t) { - UNUSED(L); - return (t == LUA_TNONE) ? "no value" : luaT_typenames[t]; -} - - -LUA_API int lua_iscfunction (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - return iscfunction(o); -} - - -LUA_API int lua_isnumber (lua_State *L, int idx) { - TValue n; - const TValue *o = index2adr(L, idx); - return tonumber(o, &n); -} - - -LUA_API int lua_isstring (lua_State *L, int idx) { - int t = lua_type(L, idx); - return (t == LUA_TSTRING || t == LUA_TNUMBER); -} - - -LUA_API int lua_isuserdata (lua_State *L, int idx) { - const TValue *o = index2adr(L, idx); - return (ttisuserdata(o) || ttislightuserdata(o)); -} - - -LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { - StkId o1 = index2adr(L, index1); - StkId o2 = index2adr(L, index2); - return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 - : luaO_rawequalObj(o1, o2); -} - - -LUA_API int lua_equal (lua_State *L, int index1, int index2) { - StkId o1, o2; - int i; - lua_lock(L); /* may call tag method */ - o1 = index2adr(L, index1); - o2 = index2adr(L, index2); - i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : equalobj(L, o1, o2); - lua_unlock(L); - return i; -} - - -LUA_API int lua_lessthan (lua_State *L, int index1, int index2) { - StkId o1, o2; - int i; - lua_lock(L); /* may call tag method */ - o1 = index2adr(L, index1); - o2 = index2adr(L, index2); - i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 - : luaV_lessthan(L, o1, o2); - lua_unlock(L); - return i; -} - - - -LUA_API lua_Number lua_tonumber (lua_State *L, int idx) { - TValue n; - const TValue *o = index2adr(L, idx); - if (tonumber(o, &n)) - return nvalue(o); - else - return 0; -} - - -LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) { - TValue n; - const TValue *o = index2adr(L, idx); - if (tonumber(o, &n)) { - lua_Integer res; - lua_Number num = nvalue(o); - lua_number2integer(res, num); - return res; - } - else - return 0; -} - - -LUA_API int lua_toboolean (lua_State *L, int idx) { - const TValue *o = index2adr(L, idx); - return !l_isfalse(o); -} - - -LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { - StkId o = index2adr(L, idx); - if (!ttisstring(o)) { - lua_lock(L); /* `luaV_tostring' may create a new string */ - if (!luaV_tostring(L, o)) { /* conversion failed? */ - if (len != NULL) *len = 0; - lua_unlock(L); - return NULL; - } - luaC_checkGC(L); - o = index2adr(L, idx); /* previous call may reallocate the stack */ - lua_unlock(L); - } - if (len != NULL) *len = tsvalue(o)->len; - return svalue(o); -} - - -LUA_API size_t lua_objlen (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - switch (ttype(o)) { - case LUA_TSTRING: return tsvalue(o)->len; - case LUA_TUSERDATA: return uvalue(o)->len; - case LUA_TTABLE: return luaH_getn(hvalue(o)); - case LUA_TNUMBER: { - size_t l; - lua_lock(L); /* `luaV_tostring' may create a new string */ - l = (luaV_tostring(L, o) ? tsvalue(o)->len : 0); - lua_unlock(L); - return l; - } - default: return 0; - } -} - - -LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - return (!iscfunction(o)) ? NULL : clvalue(o)->c.f; -} - - -LUA_API void *lua_touserdata (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - switch (ttype(o)) { - case LUA_TUSERDATA: return (rawuvalue(o) + 1); - case LUA_TLIGHTUSERDATA: return pvalue(o); - default: return NULL; - } -} - - -LUA_API lua_State *lua_tothread (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - return (!ttisthread(o)) ? NULL : thvalue(o); -} - - -LUA_API const void *lua_topointer (lua_State *L, int idx) { - StkId o = index2adr(L, idx); - switch (ttype(o)) { - case LUA_TTABLE: return hvalue(o); - case LUA_TFUNCTION: return clvalue(o); - case LUA_TTHREAD: return thvalue(o); - case LUA_TUSERDATA: - case LUA_TLIGHTUSERDATA: - return lua_touserdata(L, idx); - default: return NULL; - } -} - - - -/* -** push functions (C -> stack) -*/ - - -LUA_API void lua_pushnil (lua_State *L) { - lua_lock(L); - setnilvalue(L->top); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { - lua_lock(L); - setnvalue(L->top, n); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { - lua_lock(L); - setnvalue(L->top, cast_num(n)); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len) { - lua_lock(L); - luaC_checkGC(L); - setsvalue2s(L, L->top, luaS_newlstr(L, s, len)); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushstring (lua_State *L, const char *s) { - if (s == NULL) - lua_pushnil(L); - else - lua_pushlstring(L, s, strlen(s)); -} - - -LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, - va_list argp) { - const char *ret; - lua_lock(L); - luaC_checkGC(L); - ret = luaO_pushvfstring(L, fmt, argp); - lua_unlock(L); - return ret; -} - - -LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { - const char *ret; - va_list argp; - lua_lock(L); - luaC_checkGC(L); - va_start(argp, fmt); - ret = luaO_pushvfstring(L, fmt, argp); - va_end(argp); - lua_unlock(L); - return ret; -} - - -LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { - Closure *cl; - lua_lock(L); - luaC_checkGC(L); - api_checknelems(L, n); - cl = luaF_newCclosure(L, n, getcurrenv(L)); - cl->c.f = fn; - L->top -= n; - while (n--) - setobj2n(L, &cl->c.upvalue[n], L->top+n); - setclvalue(L, L->top, cl); - lua_assert(iswhite(obj2gco(cl))); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushboolean (lua_State *L, int b) { - lua_lock(L); - setbvalue(L->top, (b != 0)); /* ensure that true is 1 */ - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { - lua_lock(L); - setpvalue(L->top, p); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API int lua_pushthread (lua_State *L) { - lua_lock(L); - setthvalue(L, L->top, L); - api_incr_top(L); - lua_unlock(L); - return (G(L)->mainthread == L); -} - - - -/* -** get functions (Lua -> stack) -*/ - - -LUA_API void lua_gettable (lua_State *L, int idx) { - StkId t; - lua_lock(L); - t = index2adr(L, idx); - api_checkvalidindex(L, t); - luaV_gettable(L, t, L->top - 1, L->top - 1); - lua_unlock(L); -} - - -LUA_API void lua_getfield (lua_State *L, int idx, const char *k) { - StkId t; - TValue key; - lua_lock(L); - t = index2adr(L, idx); - api_checkvalidindex(L, t); - setsvalue(L, &key, luaS_new(L, k)); - luaV_gettable(L, t, &key, L->top); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_rawget (lua_State *L, int idx) { - StkId t; - lua_lock(L); - t = index2adr(L, idx); - api_check(L, ttistable(t)); - setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1)); - lua_unlock(L); -} - - -LUA_API void lua_rawgeti (lua_State *L, int idx, int n) { - StkId o; - lua_lock(L); - o = index2adr(L, idx); - api_check(L, ttistable(o)); - setobj2s(L, L->top, luaH_getnum(hvalue(o), n)); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API void lua_createtable (lua_State *L, int narray, int nrec) { - lua_lock(L); - luaC_checkGC(L); - sethvalue(L, L->top, luaH_new(L, narray, nrec)); - api_incr_top(L); - lua_unlock(L); -} - - -LUA_API int lua_getmetatable (lua_State *L, int objindex) { - const TValue *obj; - Table *mt = NULL; - int res; - lua_lock(L); - obj = index2adr(L, objindex); - switch (ttype(obj)) { - case LUA_TTABLE: - mt = hvalue(obj)->metatable; - break; - case LUA_TUSERDATA: - mt = uvalue(obj)->metatable; - break; - default: - mt = G(L)->mt[ttype(obj)]; - break; - } - if (mt == NULL) - res = 0; - else { - sethvalue(L, L->top, mt); - api_incr_top(L); - res = 1; - } - lua_unlock(L); - return res; -} - - -LUA_API void lua_getfenv (lua_State *L, int idx) { - StkId o; - lua_lock(L); - o = index2adr(L, idx); - api_checkvalidindex(L, o); - switch (ttype(o)) { - case LUA_TFUNCTION: - sethvalue(L, L->top, clvalue(o)->c.env); - break; - case LUA_TUSERDATA: - sethvalue(L, L->top, uvalue(o)->env); - break; - case LUA_TTHREAD: - setobj2s(L, L->top, gt(thvalue(o))); - break; - default: - setnilvalue(L->top); - break; - } - api_incr_top(L); - lua_unlock(L); -} - - -/* -** set functions (stack -> Lua) -*/ - - -LUA_API void lua_settable (lua_State *L, int idx) { - StkId t; - lua_lock(L); - api_checknelems(L, 2); - t = index2adr(L, idx); - api_checkvalidindex(L, t); - luaV_settable(L, t, L->top - 2, L->top - 1); - L->top -= 2; /* pop index and value */ - lua_unlock(L); -} - - -LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { - StkId t; - TValue key; - lua_lock(L); - api_checknelems(L, 1); - t = index2adr(L, idx); - api_checkvalidindex(L, t); - setsvalue(L, &key, luaS_new(L, k)); - luaV_settable(L, t, &key, L->top - 1); - L->top--; /* pop value */ - lua_unlock(L); -} - - -LUA_API void lua_rawset (lua_State *L, int idx) { - StkId t; - lua_lock(L); - api_checknelems(L, 2); - t = index2adr(L, idx); - api_check(L, ttistable(t)); - setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1); - luaC_barriert(L, hvalue(t), L->top-1); - L->top -= 2; - lua_unlock(L); -} - - -LUA_API void lua_rawseti (lua_State *L, int idx, int n) { - StkId o; - lua_lock(L); - api_checknelems(L, 1); - o = index2adr(L, idx); - api_check(L, ttistable(o)); - setobj2t(L, luaH_setnum(L, hvalue(o), n), L->top-1); - luaC_barriert(L, hvalue(o), L->top-1); - L->top--; - lua_unlock(L); -} - - -LUA_API int lua_setmetatable (lua_State *L, int objindex) { - TValue *obj; - Table *mt; - lua_lock(L); - api_checknelems(L, 1); - obj = index2adr(L, objindex); - api_checkvalidindex(L, obj); - if (ttisnil(L->top - 1)) - mt = NULL; - else { - api_check(L, ttistable(L->top - 1)); - mt = hvalue(L->top - 1); - } - switch (ttype(obj)) { - case LUA_TTABLE: { - hvalue(obj)->metatable = mt; - if (mt) - luaC_objbarriert(L, hvalue(obj), mt); - break; - } - case LUA_TUSERDATA: { - uvalue(obj)->metatable = mt; - if (mt) - luaC_objbarrier(L, rawuvalue(obj), mt); - break; - } - default: { - G(L)->mt[ttype(obj)] = mt; - break; - } - } - L->top--; - lua_unlock(L); - return 1; -} - - -LUA_API int lua_setfenv (lua_State *L, int idx) { - StkId o; - int res = 1; - lua_lock(L); - api_checknelems(L, 1); - o = index2adr(L, idx); - api_checkvalidindex(L, o); - api_check(L, ttistable(L->top - 1)); - switch (ttype(o)) { - case LUA_TFUNCTION: - clvalue(o)->c.env = hvalue(L->top - 1); - break; - case LUA_TUSERDATA: - uvalue(o)->env = hvalue(L->top - 1); - break; - case LUA_TTHREAD: - sethvalue(L, gt(thvalue(o)), hvalue(L->top - 1)); - break; - default: - res = 0; - break; - } - if (res) luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1)); - L->top--; - lua_unlock(L); - return res; -} - - -/* -** `load' and `call' functions (run Lua code) -*/ - - -#define adjustresults(L,nres) \ - { if (nres == LUA_MULTRET && L->top >= L->ci->top) L->ci->top = L->top; } - - -#define checkresults(L,na,nr) \ - api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na))) - - -LUA_API void lua_call (lua_State *L, int nargs, int nresults) { - StkId func; - lua_lock(L); - api_checknelems(L, nargs+1); - checkresults(L, nargs, nresults); - func = L->top - (nargs+1); - luaD_call(L, func, nresults); - adjustresults(L, nresults); - lua_unlock(L); -} - - - -/* -** Execute a protected call. -*/ -struct CallS { /* data to `f_call' */ - StkId func; - int nresults; -}; - - -static void f_call (lua_State *L, void *ud) { - struct CallS *c = cast(struct CallS *, ud); - luaD_call(L, c->func, c->nresults); -} - - - -LUA_API int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc) { - struct CallS c; - int status; - ptrdiff_t func; - lua_lock(L); - api_checknelems(L, nargs+1); - checkresults(L, nargs, nresults); - if (errfunc == 0) - func = 0; - else { - StkId o = index2adr(L, errfunc); - api_checkvalidindex(L, o); - func = savestack(L, o); - } - c.func = L->top - (nargs+1); /* function to be called */ - c.nresults = nresults; - status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); - adjustresults(L, nresults); - lua_unlock(L); - return status; -} - - -/* -** Execute a protected C call. -*/ -struct CCallS { /* data to `f_Ccall' */ - lua_CFunction func; - void *ud; -}; - - -static void f_Ccall (lua_State *L, void *ud) { - struct CCallS *c = cast(struct CCallS *, ud); - Closure *cl; - cl = luaF_newCclosure(L, 0, getcurrenv(L)); - cl->c.f = c->func; - setclvalue(L, L->top, cl); /* push function */ - api_incr_top(L); - setpvalue(L->top, c->ud); /* push only argument */ - api_incr_top(L); - luaD_call(L, L->top - 2, 0); -} - - -LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud) { - struct CCallS c; - int status; - lua_lock(L); - c.func = func; - c.ud = ud; - status = luaD_pcall(L, f_Ccall, &c, savestack(L, L->top), 0); - lua_unlock(L); - return status; -} - - -LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, - const char *chunkname) { - ZIO z; - int status; - lua_lock(L); - if (!chunkname) chunkname = "?"; - luaZ_init(L, &z, reader, data); - status = luaD_protectedparser(L, &z, chunkname); - lua_unlock(L); - return status; -} - - -LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) { - int status; - TValue *o; - lua_lock(L); - api_checknelems(L, 1); - o = L->top - 1; - if (isLfunction(o)) - status = luaU_dump(L, clvalue(o)->l.p, writer, data, 0); - else - status = 1; - lua_unlock(L); - return status; -} - - -LUA_API int lua_status (lua_State *L) { - return L->status; -} - - -/* -** Garbage-collection function -*/ - -LUA_API int lua_gc (lua_State *L, int what, int data) { - int res = 0; - global_State *g; - lua_lock(L); - g = G(L); - switch (what) { - case LUA_GCSTOP: { - g->GCthreshold = MAX_LUMEM; - break; - } - case LUA_GCRESTART: { - g->GCthreshold = g->totalbytes; - break; - } - case LUA_GCCOLLECT: { - luaC_fullgc(L); - break; - } - case LUA_GCCOUNT: { - /* GC values are expressed in Kbytes: #bytes/2^10 */ - res = cast_int(g->totalbytes >> 10); - break; - } - case LUA_GCCOUNTB: { - res = cast_int(g->totalbytes & 0x3ff); - break; - } - case LUA_GCSTEP: { - lu_mem a = (cast(lu_mem, data) << 10); - if (a <= g->totalbytes) - g->GCthreshold = g->totalbytes - a; - else - g->GCthreshold = 0; - while (g->GCthreshold <= g->totalbytes) { - luaC_step(L); - if (g->gcstate == GCSpause) { /* end of cycle? */ - res = 1; /* signal it */ - break; - } - } - break; - } - case LUA_GCSETPAUSE: { - res = g->gcpause; - g->gcpause = data; - break; - } - case LUA_GCSETSTEPMUL: { - res = g->gcstepmul; - g->gcstepmul = data; - break; - } - default: res = -1; /* invalid option */ - } - lua_unlock(L); - return res; -} - - - -/* -** miscellaneous functions -*/ - - -LUA_API int lua_error (lua_State *L) { - lua_lock(L); - api_checknelems(L, 1); - luaG_errormsg(L); - lua_unlock(L); - return 0; /* to avoid warnings */ -} - - -LUA_API int lua_next (lua_State *L, int idx) { - StkId t; - int more; - lua_lock(L); - t = index2adr(L, idx); - api_check(L, ttistable(t)); - more = luaH_next(L, hvalue(t), L->top - 1); - if (more) { - api_incr_top(L); - } - else /* no more elements */ - L->top -= 1; /* remove key */ - lua_unlock(L); - return more; -} - - -LUA_API void lua_concat (lua_State *L, int n) { - lua_lock(L); - api_checknelems(L, n); - if (n >= 2) { - luaC_checkGC(L); - luaV_concat(L, n, cast_int(L->top - L->base) - 1); - L->top -= (n-1); - } - else if (n == 0) { /* push empty string */ - setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); - api_incr_top(L); - } - /* else n == 1; nothing to do */ - lua_unlock(L); -} - - -LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) { - lua_Alloc f; - lua_lock(L); - if (ud) *ud = G(L)->ud; - f = G(L)->frealloc; - lua_unlock(L); - return f; -} - - -LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) { - lua_lock(L); - G(L)->ud = ud; - G(L)->frealloc = f; - lua_unlock(L); -} - - -LUA_API void *lua_newuserdata (lua_State *L, size_t size) { - Udata *u; - lua_lock(L); - luaC_checkGC(L); - u = luaS_newudata(L, size, getcurrenv(L)); - setuvalue(L, L->top, u); - api_incr_top(L); - lua_unlock(L); - return u + 1; -} - - - - -static const char *aux_upvalue (StkId fi, int n, TValue **val) { - Closure *f; - if (!ttisfunction(fi)) return NULL; - f = clvalue(fi); - if (f->c.isC) { - if (!(1 <= n && n <= f->c.nupvalues)) return NULL; - *val = &f->c.upvalue[n-1]; - return ""; - } - else { - Proto *p = f->l.p; - if (!(1 <= n && n <= p->sizeupvalues)) return NULL; - *val = f->l.upvals[n-1]->v; - return getstr(p->upvalues[n-1]); - } -} - - -LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { - const char *name; - TValue *val; - lua_lock(L); - name = aux_upvalue(index2adr(L, funcindex), n, &val); - if (name) { - setobj2s(L, L->top, val); - api_incr_top(L); - } - lua_unlock(L); - return name; -} - - -LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { - const char *name; - TValue *val; - StkId fi; - lua_lock(L); - fi = index2adr(L, funcindex); - api_checknelems(L, 1); - name = aux_upvalue(fi, n, &val); - if (name) { - L->top--; - setobj(L, val, L->top); - luaC_barrier(L, clvalue(fi), L->top); - } - lua_unlock(L); - return name; -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lapi.h b/desmume/src/windows/lua/lua-5.1.4/src/lapi.h deleted file mode 100644 index 2c3fab244..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lapi.h +++ /dev/null @@ -1,16 +0,0 @@ -/* -** $Id: lapi.h,v 2.2.1.1 2007/12/27 13:02:25 roberto Exp $ -** Auxiliary functions from Lua API -** See Copyright Notice in lua.h -*/ - -#ifndef lapi_h -#define lapi_h - - -#include "lobject.h" - - -LUAI_FUNC void luaA_pushobject (lua_State *L, const TValue *o); - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lauxlib.c b/desmume/src/windows/lua/lua-5.1.4/src/lauxlib.c deleted file mode 100644 index 10f14e2c0..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lauxlib.c +++ /dev/null @@ -1,652 +0,0 @@ -/* -** $Id: lauxlib.c,v 1.159.1.3 2008/01/21 13:20:51 roberto Exp $ -** Auxiliary functions for building Lua libraries -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include -#include -#include - - -/* This file uses only the official API of Lua. -** Any function declared here could be written as an application function. -*/ - -#define lauxlib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" - - -#define FREELIST_REF 0 /* free list of references */ - - -/* convert a stack index to positive */ -#define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \ - lua_gettop(L) + (i) + 1) - - -/* -** {====================================================== -** Error-report functions -** ======================================================= -*/ - - -LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) { - lua_Debug ar; - if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ - return luaL_error(L, "bad argument #%d (%s)", narg, extramsg); - lua_getinfo(L, "n", &ar); - if (strcmp(ar.namewhat, "method") == 0) { - narg--; /* do not count `self' */ - if (narg == 0) /* error is in the self argument itself? */ - return luaL_error(L, "calling " LUA_QS " on bad self (%s)", - ar.name, extramsg); - } - if (ar.name == NULL) - ar.name = "?"; - return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)", - narg, ar.name, extramsg); -} - - -LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) { - const char *msg = lua_pushfstring(L, "%s expected, got %s", - tname, luaL_typename(L, narg)); - return luaL_argerror(L, narg, msg); -} - - -static void tag_error (lua_State *L, int narg, int tag) { - luaL_typerror(L, narg, lua_typename(L, tag)); -} - - -LUALIB_API void luaL_where (lua_State *L, int level) { - lua_Debug ar; - if (lua_getstack(L, level, &ar)) { /* check function at level */ - lua_getinfo(L, "Sl", &ar); /* get info about it */ - if (ar.currentline > 0) { /* is there info? */ - lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); - return; - } - } - lua_pushliteral(L, ""); /* else, no information available... */ -} - - -LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { - va_list argp; - va_start(argp, fmt); - luaL_where(L, 1); - lua_pushvfstring(L, fmt, argp); - va_end(argp); - lua_concat(L, 2); - return lua_error(L); -} - -/* }====================================================== */ - - -LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def, - const char *const lst[]) { - const char *name = (def) ? luaL_optstring(L, narg, def) : - luaL_checkstring(L, narg); - int i; - for (i=0; lst[i]; i++) - if (strcmp(lst[i], name) == 0) - return i; - return luaL_argerror(L, narg, - lua_pushfstring(L, "invalid option " LUA_QS, name)); -} - - -LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { - lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */ - if (!lua_isnil(L, -1)) /* name already in use? */ - return 0; /* leave previous value on top, but return 0 */ - lua_pop(L, 1); - lua_newtable(L); /* create metatable */ - lua_pushvalue(L, -1); - lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ - return 1; -} - - -LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { - void *p = lua_touserdata(L, ud); - if (p != NULL) { /* value is a userdata? */ - if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ - lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ - if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */ - lua_pop(L, 2); /* remove both metatables */ - return p; - } - } - } - luaL_typerror(L, ud, tname); /* else error */ - return NULL; /* to avoid warnings */ -} - - -LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) { - if (!lua_checkstack(L, space)) - luaL_error(L, "stack overflow (%s)", mes); -} - - -LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) { - if (lua_type(L, narg) != t) - tag_error(L, narg, t); -} - - -LUALIB_API void luaL_checkany (lua_State *L, int narg) { - if (lua_type(L, narg) == LUA_TNONE) - luaL_argerror(L, narg, "value expected"); -} - - -LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) { - const char *s = lua_tolstring(L, narg, len); - if (!s) tag_error(L, narg, LUA_TSTRING); - return s; -} - - -LUALIB_API const char *luaL_optlstring (lua_State *L, int narg, - const char *def, size_t *len) { - if (lua_isnoneornil(L, narg)) { - if (len) - *len = (def ? strlen(def) : 0); - return def; - } - else return luaL_checklstring(L, narg, len); -} - - -LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) { - lua_Number d = lua_tonumber(L, narg); - if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */ - tag_error(L, narg, LUA_TNUMBER); - return d; -} - - -LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) { - return luaL_opt(L, luaL_checknumber, narg, def); -} - - -LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) { - lua_Integer d = lua_tointeger(L, narg); - if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */ - tag_error(L, narg, LUA_TNUMBER); - return d; -} - - -LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg, - lua_Integer def) { - return luaL_opt(L, luaL_checkinteger, narg, def); -} - - -LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { - if (!lua_getmetatable(L, obj)) /* no metatable? */ - return 0; - lua_pushstring(L, event); - lua_rawget(L, -2); - if (lua_isnil(L, -1)) { - lua_pop(L, 2); /* remove metatable and metafield */ - return 0; - } - else { - lua_remove(L, -2); /* remove only metatable */ - return 1; - } -} - - -LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { - obj = abs_index(L, obj); - if (!luaL_getmetafield(L, obj, event)) /* no metafield? */ - return 0; - lua_pushvalue(L, obj); - lua_call(L, 1, 1); - return 1; -} - - -LUALIB_API void (luaL_register) (lua_State *L, const char *libname, - const luaL_Reg *l) { - luaI_openlib(L, libname, l, 0); -} - - -static int libsize (const luaL_Reg *l) { - int size = 0; - for (; l->name; l++) size++; - return size; -} - - -LUALIB_API void luaI_openlib (lua_State *L, const char *libname, - const luaL_Reg *l, int nup) { - if (libname) { - int size = libsize(l); - /* check whether lib already exists */ - luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); - lua_getfield(L, -1, libname); /* get _LOADED[libname] */ - if (!lua_istable(L, -1)) { /* not found? */ - lua_pop(L, 1); /* remove previous result */ - /* try global variable (and create one if it does not exist) */ - if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL) - luaL_error(L, "name conflict for module " LUA_QS, libname); - lua_pushvalue(L, -1); - lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */ - } - lua_remove(L, -2); /* remove _LOADED table */ - lua_insert(L, -(nup+1)); /* move library table to below upvalues */ - } - for (; l->name; l++) { - int i; - for (i=0; ifunc, nup); - lua_setfield(L, -(nup+2), l->name); - } - lua_pop(L, nup); /* remove upvalues */ -} - - - -/* -** {====================================================== -** getn-setn: size for arrays -** ======================================================= -*/ - -#if defined(LUA_COMPAT_GETN) - -static int checkint (lua_State *L, int topop) { - int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1; - lua_pop(L, topop); - return n; -} - - -static void getsizes (lua_State *L) { - lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); - if (lua_isnil(L, -1)) { /* no `size' table? */ - lua_pop(L, 1); /* remove nil */ - lua_newtable(L); /* create it */ - lua_pushvalue(L, -1); /* `size' will be its own metatable */ - lua_setmetatable(L, -2); - lua_pushliteral(L, "kv"); - lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */ - lua_pushvalue(L, -1); - lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); /* store in register */ - } -} - - -LUALIB_API void luaL_setn (lua_State *L, int t, int n) { - t = abs_index(L, t); - lua_pushliteral(L, "n"); - lua_rawget(L, t); - if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */ - lua_pushliteral(L, "n"); /* use it */ - lua_pushinteger(L, n); - lua_rawset(L, t); - } - else { /* use `sizes' */ - getsizes(L); - lua_pushvalue(L, t); - lua_pushinteger(L, n); - lua_rawset(L, -3); /* sizes[t] = n */ - lua_pop(L, 1); /* remove `sizes' */ - } -} - - -LUALIB_API int luaL_getn (lua_State *L, int t) { - int n; - t = abs_index(L, t); - lua_pushliteral(L, "n"); /* try t.n */ - lua_rawget(L, t); - if ((n = checkint(L, 1)) >= 0) return n; - getsizes(L); /* else try sizes[t] */ - lua_pushvalue(L, t); - lua_rawget(L, -2); - if ((n = checkint(L, 2)) >= 0) return n; - return (int)lua_objlen(L, t); -} - -#endif - -/* }====================================================== */ - - - -LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p, - const char *r) { - const char *wild; - size_t l = strlen(p); - luaL_Buffer b; - luaL_buffinit(L, &b); - while ((wild = strstr(s, p)) != NULL) { - luaL_addlstring(&b, s, wild - s); /* push prefix */ - luaL_addstring(&b, r); /* push replacement in place of pattern */ - s = wild + l; /* continue after `p' */ - } - luaL_addstring(&b, s); /* push last suffix */ - luaL_pushresult(&b); - return lua_tostring(L, -1); -} - - -LUALIB_API const char *luaL_findtable (lua_State *L, int idx, - const char *fname, int szhint) { - const char *e; - lua_pushvalue(L, idx); - do { - e = strchr(fname, '.'); - if (e == NULL) e = fname + strlen(fname); - lua_pushlstring(L, fname, e - fname); - lua_rawget(L, -2); - if (lua_isnil(L, -1)) { /* no such field? */ - lua_pop(L, 1); /* remove this nil */ - lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */ - lua_pushlstring(L, fname, e - fname); - lua_pushvalue(L, -2); - lua_settable(L, -4); /* set new table into field */ - } - else if (!lua_istable(L, -1)) { /* field has a non-table value? */ - lua_pop(L, 2); /* remove table and value */ - return fname; /* return problematic part of the name */ - } - lua_remove(L, -2); /* remove previous table */ - fname = e + 1; - } while (*e == '.'); - return NULL; -} - - - -/* -** {====================================================== -** Generic Buffer manipulation -** ======================================================= -*/ - - -#define bufflen(B) ((B)->p - (B)->buffer) -#define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B))) - -#define LIMIT (LUA_MINSTACK/2) - - -static int emptybuffer (luaL_Buffer *B) { - size_t l = bufflen(B); - if (l == 0) return 0; /* put nothing on stack */ - else { - lua_pushlstring(B->L, B->buffer, l); - B->p = B->buffer; - B->lvl++; - return 1; - } -} - - -static void adjuststack (luaL_Buffer *B) { - if (B->lvl > 1) { - lua_State *L = B->L; - int toget = 1; /* number of levels to concat */ - size_t toplen = lua_strlen(L, -1); - do { - size_t l = lua_strlen(L, -(toget+1)); - if (B->lvl - toget + 1 >= LIMIT || toplen > l) { - toplen += l; - toget++; - } - else break; - } while (toget < B->lvl); - lua_concat(L, toget); - B->lvl = B->lvl - toget + 1; - } -} - - -LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) { - if (emptybuffer(B)) - adjuststack(B); - return B->buffer; -} - - -LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { - while (l--) - luaL_addchar(B, *s++); -} - - -LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { - luaL_addlstring(B, s, strlen(s)); -} - - -LUALIB_API void luaL_pushresult (luaL_Buffer *B) { - emptybuffer(B); - lua_concat(B->L, B->lvl); - B->lvl = 1; -} - - -LUALIB_API void luaL_addvalue (luaL_Buffer *B) { - lua_State *L = B->L; - size_t vl; - const char *s = lua_tolstring(L, -1, &vl); - if (vl <= bufffree(B)) { /* fit into buffer? */ - memcpy(B->p, s, vl); /* put it there */ - B->p += vl; - lua_pop(L, 1); /* remove from stack */ - } - else { - if (emptybuffer(B)) - lua_insert(L, -2); /* put buffer before new value */ - B->lvl++; /* add new value into B stack */ - adjuststack(B); - } -} - - -LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { - B->L = L; - B->p = B->buffer; - B->lvl = 0; -} - -/* }====================================================== */ - - -LUALIB_API int luaL_ref (lua_State *L, int t) { - int ref; - t = abs_index(L, t); - if (lua_isnil(L, -1)) { - lua_pop(L, 1); /* remove from stack */ - return LUA_REFNIL; /* `nil' has a unique fixed reference */ - } - lua_rawgeti(L, t, FREELIST_REF); /* get first free element */ - ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */ - lua_pop(L, 1); /* remove it from stack */ - if (ref != 0) { /* any free element? */ - lua_rawgeti(L, t, ref); /* remove it from list */ - lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */ - } - else { /* no free elements */ - ref = (int)lua_objlen(L, t); - ref++; /* create new reference */ - } - lua_rawseti(L, t, ref); - return ref; -} - - -LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { - if (ref >= 0) { - t = abs_index(L, t); - lua_rawgeti(L, t, FREELIST_REF); - lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */ - lua_pushinteger(L, ref); - lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */ - } -} - - - -/* -** {====================================================== -** Load functions -** ======================================================= -*/ - -typedef struct LoadF { - int extraline; - FILE *f; - char buff[LUAL_BUFFERSIZE]; -} LoadF; - - -static const char *getF (lua_State *L, void *ud, size_t *size) { - LoadF *lf = (LoadF *)ud; - (void)L; - if (lf->extraline) { - lf->extraline = 0; - *size = 1; - return "\n"; - } - if (feof(lf->f)) return NULL; - *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); - return (*size > 0) ? lf->buff : NULL; -} - - -static int errfile (lua_State *L, const char *what, int fnameindex) { - const char *serr = strerror(errno); - const char *filename = lua_tostring(L, fnameindex) + 1; - lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr); - lua_remove(L, fnameindex); - return LUA_ERRFILE; -} - - -LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) { - LoadF lf; - int status, readstatus; - int c; - int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ - lf.extraline = 0; - if (filename == NULL) { - lua_pushliteral(L, "=stdin"); - lf.f = stdin; - } - else { - lua_pushfstring(L, "@%s", filename); - lf.f = fopen(filename, "r"); - if (lf.f == NULL) return errfile(L, "open", fnameindex); - } - c = getc(lf.f); - if (c == '#') { /* Unix exec. file? */ - lf.extraline = 1; - while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */ - if (c == '\n') c = getc(lf.f); - } - if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ - lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ - if (lf.f == NULL) return errfile(L, "reopen", fnameindex); - /* skip eventual `#!...' */ - while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ; - lf.extraline = 0; - } - ungetc(c, lf.f); - status = lua_load(L, getF, &lf, lua_tostring(L, -1)); - readstatus = ferror(lf.f); - if (filename) fclose(lf.f); /* close file (even in case of errors) */ - if (readstatus) { - lua_settop(L, fnameindex); /* ignore results from `lua_load' */ - return errfile(L, "read", fnameindex); - } - lua_remove(L, fnameindex); - return status; -} - - -typedef struct LoadS { - const char *s; - size_t size; -} LoadS; - - -static const char *getS (lua_State *L, void *ud, size_t *size) { - LoadS *ls = (LoadS *)ud; - (void)L; - if (ls->size == 0) return NULL; - *size = ls->size; - ls->size = 0; - return ls->s; -} - - -LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size, - const char *name) { - LoadS ls; - ls.s = buff; - ls.size = size; - return lua_load(L, getS, &ls, name); -} - - -LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) { - return luaL_loadbuffer(L, s, strlen(s), s); -} - - - -/* }====================================================== */ - - -static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { - (void)ud; - (void)osize; - if (nsize == 0) { - free(ptr); - return NULL; - } - else - return realloc(ptr, nsize); -} - - -static int panic (lua_State *L) { - (void)L; /* to avoid warnings */ - fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n", - lua_tostring(L, -1)); - return 0; -} - - -LUALIB_API lua_State *luaL_newstate (void) { - lua_State *L = lua_newstate(l_alloc, NULL); - if (L) lua_atpanic(L, &panic); - return L; -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lauxlib.h b/desmume/src/windows/lua/lua-5.1.4/src/lauxlib.h deleted file mode 100644 index 34258235d..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lauxlib.h +++ /dev/null @@ -1,174 +0,0 @@ -/* -** $Id: lauxlib.h,v 1.88.1.1 2007/12/27 13:02:25 roberto Exp $ -** Auxiliary functions for building Lua libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lauxlib_h -#define lauxlib_h - - -#include -#include - -#include "lua.h" - - -#if defined(LUA_COMPAT_GETN) -LUALIB_API int (luaL_getn) (lua_State *L, int t); -LUALIB_API void (luaL_setn) (lua_State *L, int t, int n); -#else -#define luaL_getn(L,i) ((int)lua_objlen(L, i)) -#define luaL_setn(L,i,j) ((void)0) /* no op! */ -#endif - -#if defined(LUA_COMPAT_OPENLIB) -#define luaI_openlib luaL_openlib -#endif - - -/* extra error code for `luaL_load' */ -#define LUA_ERRFILE (LUA_ERRERR+1) - - -typedef struct luaL_Reg { - const char *name; - lua_CFunction func; -} luaL_Reg; - - - -LUALIB_API void (luaI_openlib) (lua_State *L, const char *libname, - const luaL_Reg *l, int nup); -LUALIB_API void (luaL_register) (lua_State *L, const char *libname, - const luaL_Reg *l); -LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e); -LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e); -LUALIB_API int (luaL_typerror) (lua_State *L, int narg, const char *tname); -LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg); -LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg, - size_t *l); -LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg, - const char *def, size_t *l); -LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg); -LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def); - -LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg); -LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg, - lua_Integer def); - -LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg); -LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t); -LUALIB_API void (luaL_checkany) (lua_State *L, int narg); - -LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); -LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); - -LUALIB_API void (luaL_where) (lua_State *L, int lvl); -LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); - -LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def, - const char *const lst[]); - -LUALIB_API int (luaL_ref) (lua_State *L, int t); -LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); - -LUALIB_API int (luaL_loadfile) (lua_State *L, const char *filename); -LUALIB_API int (luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz, - const char *name); -LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); - -LUALIB_API lua_State *(luaL_newstate) (void); - - -LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, - const char *r); - -LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx, - const char *fname, int szhint); - - - - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - -#define luaL_argcheck(L, cond,numarg,extramsg) \ - ((void)((cond) || luaL_argerror(L, (numarg), (extramsg)))) -#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) -#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) -#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) -#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) -#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) -#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) - -#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) - -#define luaL_dofile(L, fn) \ - (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_dostring(L, s) \ - (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) - -#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) - -#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) - -/* -** {====================================================== -** Generic Buffer manipulation -** ======================================================= -*/ - - - -typedef struct luaL_Buffer { - char *p; /* current position in buffer */ - int lvl; /* number of strings in the stack (level) */ - lua_State *L; - char buffer[LUAL_BUFFERSIZE]; -} luaL_Buffer; - -#define luaL_addchar(B,c) \ - ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \ - (*(B)->p++ = (char)(c))) - -/* compatibility only */ -#define luaL_putchar(B,c) luaL_addchar(B,c) - -#define luaL_addsize(B,n) ((B)->p += (n)) - -LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); -LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B); -LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l); -LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); -LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); -LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); - - -/* }====================================================== */ - - -/* compatibility with ref system */ - -/* pre-defined references */ -#define LUA_NOREF (-2) -#define LUA_REFNIL (-1) - -#define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \ - (lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0)) - -#define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref)) - -#define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, (ref)) - - -#define luaL_reg luaL_Reg - -#endif - - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lbaselib.c b/desmume/src/windows/lua/lua-5.1.4/src/lbaselib.c deleted file mode 100644 index 2a4c079d3..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lbaselib.c +++ /dev/null @@ -1,653 +0,0 @@ -/* -** $Id: lbaselib.c,v 1.191.1.6 2008/02/14 16:46:22 roberto Exp $ -** Basic library -** See Copyright Notice in lua.h -*/ - - - -#include -#include -#include -#include - -#define lbaselib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - - - -/* -** If your system does not support `stdout', you can just remove this function. -** If you need, you can define your own `print' function, following this -** model but changing `fputs' to put the strings at a proper place -** (a console window or a log file, for instance). -*/ -static int luaB_print (lua_State *L) { - int n = lua_gettop(L); /* number of arguments */ - int i; - lua_getglobal(L, "tostring"); - for (i=1; i<=n; i++) { - const char *s; - lua_pushvalue(L, -1); /* function to be called */ - lua_pushvalue(L, i); /* value to print */ - lua_call(L, 1, 1); - s = lua_tostring(L, -1); /* get result */ - if (s == NULL) - return luaL_error(L, LUA_QL("tostring") " must return a string to " - LUA_QL("print")); - if (i>1) fputs("\t", stdout); - fputs(s, stdout); - lua_pop(L, 1); /* pop result */ - } - fputs("\n", stdout); - return 0; -} - - -static int luaB_tonumber (lua_State *L) { - int base = luaL_optint(L, 2, 10); - if (base == 10) { /* standard conversion */ - luaL_checkany(L, 1); - if (lua_isnumber(L, 1)) { - lua_pushnumber(L, lua_tonumber(L, 1)); - return 1; - } - } - else { - const char *s1 = luaL_checkstring(L, 1); - char *s2; - unsigned long n; - luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); - n = strtoul(s1, &s2, base); - if (s1 != s2) { /* at least one valid digit? */ - while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */ - if (*s2 == '\0') { /* no invalid trailing characters? */ - lua_pushnumber(L, (lua_Number)n); - return 1; - } - } - } - lua_pushnil(L); /* else not a number */ - return 1; -} - - -static int luaB_error (lua_State *L) { - int level = luaL_optint(L, 2, 1); - lua_settop(L, 1); - if (lua_isstring(L, 1) && level > 0) { /* add extra information? */ - luaL_where(L, level); - lua_pushvalue(L, 1); - lua_concat(L, 2); - } - return lua_error(L); -} - - -static int luaB_getmetatable (lua_State *L) { - luaL_checkany(L, 1); - if (!lua_getmetatable(L, 1)) { - lua_pushnil(L); - return 1; /* no metatable */ - } - luaL_getmetafield(L, 1, "__metatable"); - return 1; /* returns either __metatable field (if present) or metatable */ -} - - -static int luaB_setmetatable (lua_State *L) { - int t = lua_type(L, 2); - luaL_checktype(L, 1, LUA_TTABLE); - luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, - "nil or table expected"); - if (luaL_getmetafield(L, 1, "__metatable")) - luaL_error(L, "cannot change a protected metatable"); - lua_settop(L, 2); - lua_setmetatable(L, 1); - return 1; -} - - -static void getfunc (lua_State *L, int opt) { - if (lua_isfunction(L, 1)) lua_pushvalue(L, 1); - else { - lua_Debug ar; - int level = opt ? luaL_optint(L, 1, 1) : luaL_checkint(L, 1); - luaL_argcheck(L, level >= 0, 1, "level must be non-negative"); - if (lua_getstack(L, level, &ar) == 0) - luaL_argerror(L, 1, "invalid level"); - lua_getinfo(L, "f", &ar); - if (lua_isnil(L, -1)) - luaL_error(L, "no function environment for tail call at level %d", - level); - } -} - - -static int luaB_getfenv (lua_State *L) { - getfunc(L, 1); - if (lua_iscfunction(L, -1)) /* is a C function? */ - lua_pushvalue(L, LUA_GLOBALSINDEX); /* return the thread's global env. */ - else - lua_getfenv(L, -1); - return 1; -} - - -static int luaB_setfenv (lua_State *L) { - luaL_checktype(L, 2, LUA_TTABLE); - getfunc(L, 0); - lua_pushvalue(L, 2); - if (lua_isnumber(L, 1) && lua_tonumber(L, 1) == 0) { - /* change environment of current thread */ - lua_pushthread(L); - lua_insert(L, -2); - lua_setfenv(L, -2); - return 0; - } - else if (lua_iscfunction(L, -2) || lua_setfenv(L, -2) == 0) - luaL_error(L, - LUA_QL("setfenv") " cannot change environment of given object"); - return 1; -} - - -static int luaB_rawequal (lua_State *L) { - luaL_checkany(L, 1); - luaL_checkany(L, 2); - lua_pushboolean(L, lua_rawequal(L, 1, 2)); - return 1; -} - - -static int luaB_rawget (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - luaL_checkany(L, 2); - lua_settop(L, 2); - lua_rawget(L, 1); - return 1; -} - -static int luaB_rawset (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - luaL_checkany(L, 2); - luaL_checkany(L, 3); - lua_settop(L, 3); - lua_rawset(L, 1); - return 1; -} - - -static int luaB_gcinfo (lua_State *L) { - lua_pushinteger(L, lua_getgccount(L)); - return 1; -} - - -static int luaB_collectgarbage (lua_State *L) { - static const char *const opts[] = {"stop", "restart", "collect", - "count", "step", "setpause", "setstepmul", NULL}; - static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, - LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL}; - int o = luaL_checkoption(L, 1, "collect", opts); - int ex = luaL_optint(L, 2, 0); - int res = lua_gc(L, optsnum[o], ex); - switch (optsnum[o]) { - case LUA_GCCOUNT: { - int b = lua_gc(L, LUA_GCCOUNTB, 0); - lua_pushnumber(L, res + ((lua_Number)b/1024)); - return 1; - } - case LUA_GCSTEP: { - lua_pushboolean(L, res); - return 1; - } - default: { - lua_pushnumber(L, res); - return 1; - } - } -} - - -static int luaB_type (lua_State *L) { - luaL_checkany(L, 1); - lua_pushstring(L, luaL_typename(L, 1)); - return 1; -} - - -static int luaB_next (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - lua_settop(L, 2); /* create a 2nd argument if there isn't one */ - if (lua_next(L, 1)) - return 2; - else { - lua_pushnil(L); - return 1; - } -} - - -static int luaB_pairs (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */ - lua_pushvalue(L, 1); /* state, */ - lua_pushnil(L); /* and initial value */ - return 3; -} - - -static int ipairsaux (lua_State *L) { - int i = luaL_checkint(L, 2); - luaL_checktype(L, 1, LUA_TTABLE); - i++; /* next value */ - lua_pushinteger(L, i); - lua_rawgeti(L, 1, i); - return (lua_isnil(L, -1)) ? 0 : 2; -} - - -static int luaB_ipairs (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */ - lua_pushvalue(L, 1); /* state, */ - lua_pushinteger(L, 0); /* and initial value */ - return 3; -} - - -static int load_aux (lua_State *L, int status) { - if (status == 0) /* OK? */ - return 1; - else { - lua_pushnil(L); - lua_insert(L, -2); /* put before error message */ - return 2; /* return nil plus error message */ - } -} - - -static int luaB_loadstring (lua_State *L) { - size_t l; - const char *s = luaL_checklstring(L, 1, &l); - const char *chunkname = luaL_optstring(L, 2, s); - return load_aux(L, luaL_loadbuffer(L, s, l, chunkname)); -} - - -static int luaB_loadfile (lua_State *L) { - const char *fname = luaL_optstring(L, 1, NULL); - return load_aux(L, luaL_loadfile(L, fname)); -} - - -/* -** Reader for generic `load' function: `lua_load' uses the -** stack for internal stuff, so the reader cannot change the -** stack top. Instead, it keeps its resulting string in a -** reserved slot inside the stack. -*/ -static const char *generic_reader (lua_State *L, void *ud, size_t *size) { - (void)ud; /* to avoid warnings */ - luaL_checkstack(L, 2, "too many nested functions"); - lua_pushvalue(L, 1); /* get function */ - lua_call(L, 0, 1); /* call it */ - if (lua_isnil(L, -1)) { - *size = 0; - return NULL; - } - else if (lua_isstring(L, -1)) { - lua_replace(L, 3); /* save string in a reserved stack slot */ - return lua_tolstring(L, 3, size); - } - else luaL_error(L, "reader function must return a string"); - return NULL; /* to avoid warnings */ -} - - -static int luaB_load (lua_State *L) { - int status; - const char *cname = luaL_optstring(L, 2, "=(load)"); - luaL_checktype(L, 1, LUA_TFUNCTION); - lua_settop(L, 3); /* function, eventual name, plus one reserved slot */ - status = lua_load(L, generic_reader, NULL, cname); - return load_aux(L, status); -} - - -static int luaB_dofile (lua_State *L) { - const char *fname = luaL_optstring(L, 1, NULL); - int n = lua_gettop(L); - if (luaL_loadfile(L, fname) != 0) lua_error(L); - lua_call(L, 0, LUA_MULTRET); - return lua_gettop(L) - n; -} - - -static int luaB_assert (lua_State *L) { - luaL_checkany(L, 1); - if (!lua_toboolean(L, 1)) - return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!")); - return lua_gettop(L); -} - - -static int luaB_unpack (lua_State *L) { - int i, e, n; - luaL_checktype(L, 1, LUA_TTABLE); - i = luaL_optint(L, 2, 1); - e = luaL_opt(L, luaL_checkint, 3, luaL_getn(L, 1)); - if (i > e) return 0; /* empty range */ - n = e - i + 1; /* number of elements */ - if (n <= 0 || !lua_checkstack(L, n)) /* n <= 0 means arith. overflow */ - return luaL_error(L, "too many results to unpack"); - lua_rawgeti(L, 1, i); /* push arg[i] (avoiding overflow problems) */ - while (i++ < e) /* push arg[i + 1...e] */ - lua_rawgeti(L, 1, i); - return n; -} - - -static int luaB_select (lua_State *L) { - int n = lua_gettop(L); - if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { - lua_pushinteger(L, n-1); - return 1; - } - else { - int i = luaL_checkint(L, 1); - if (i < 0) i = n + i; - else if (i > n) i = n; - luaL_argcheck(L, 1 <= i, 1, "index out of range"); - return n - i; - } -} - - -static int luaB_pcall (lua_State *L) { - int status; - luaL_checkany(L, 1); - status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0); - lua_pushboolean(L, (status == 0)); - lua_insert(L, 1); - return lua_gettop(L); /* return status + all results */ -} - - -static int luaB_xpcall (lua_State *L) { - int status; - luaL_checkany(L, 2); - lua_settop(L, 2); - lua_insert(L, 1); /* put error function under function to be called */ - status = lua_pcall(L, 0, LUA_MULTRET, 1); - lua_pushboolean(L, (status == 0)); - lua_replace(L, 1); - return lua_gettop(L); /* return status + all results */ -} - - -static int luaB_tostring (lua_State *L) { - luaL_checkany(L, 1); - if (luaL_callmeta(L, 1, "__tostring")) /* is there a metafield? */ - return 1; /* use its value */ - switch (lua_type(L, 1)) { - case LUA_TNUMBER: - lua_pushstring(L, lua_tostring(L, 1)); - break; - case LUA_TSTRING: - lua_pushvalue(L, 1); - break; - case LUA_TBOOLEAN: - lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false")); - break; - case LUA_TNIL: - lua_pushliteral(L, "nil"); - break; - default: - lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1)); - break; - } - return 1; -} - - -static int luaB_newproxy (lua_State *L) { - lua_settop(L, 1); - lua_newuserdata(L, 0); /* create proxy */ - if (lua_toboolean(L, 1) == 0) - return 1; /* no metatable */ - else if (lua_isboolean(L, 1)) { - lua_newtable(L); /* create a new metatable `m' ... */ - lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */ - lua_pushboolean(L, 1); - lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */ - } - else { - int validproxy = 0; /* to check if weaktable[metatable(u)] == true */ - if (lua_getmetatable(L, 1)) { - lua_rawget(L, lua_upvalueindex(1)); - validproxy = lua_toboolean(L, -1); - lua_pop(L, 1); /* remove value */ - } - luaL_argcheck(L, validproxy, 1, "boolean or proxy expected"); - lua_getmetatable(L, 1); /* metatable is valid; get it */ - } - lua_setmetatable(L, 2); - return 1; -} - - -static const luaL_Reg base_funcs[] = { - {"assert", luaB_assert}, - {"collectgarbage", luaB_collectgarbage}, - {"dofile", luaB_dofile}, - {"error", luaB_error}, - {"gcinfo", luaB_gcinfo}, - {"getfenv", luaB_getfenv}, - {"getmetatable", luaB_getmetatable}, - {"loadfile", luaB_loadfile}, - {"load", luaB_load}, - {"loadstring", luaB_loadstring}, - {"next", luaB_next}, - {"pcall", luaB_pcall}, - {"print", luaB_print}, - {"rawequal", luaB_rawequal}, - {"rawget", luaB_rawget}, - {"rawset", luaB_rawset}, - {"select", luaB_select}, - {"setfenv", luaB_setfenv}, - {"setmetatable", luaB_setmetatable}, - {"tonumber", luaB_tonumber}, - {"tostring", luaB_tostring}, - {"type", luaB_type}, - {"unpack", luaB_unpack}, - {"xpcall", luaB_xpcall}, - {NULL, NULL} -}; - - -/* -** {====================================================== -** Coroutine library -** ======================================================= -*/ - -#define CO_RUN 0 /* running */ -#define CO_SUS 1 /* suspended */ -#define CO_NOR 2 /* 'normal' (it resumed another coroutine) */ -#define CO_DEAD 3 - -static const char *const statnames[] = - {"running", "suspended", "normal", "dead"}; - -static int costatus (lua_State *L, lua_State *co) { - if (L == co) return CO_RUN; - switch (lua_status(co)) { - case LUA_YIELD: - return CO_SUS; - case 0: { - lua_Debug ar; - if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */ - return CO_NOR; /* it is running */ - else if (lua_gettop(co) == 0) - return CO_DEAD; - else - return CO_SUS; /* initial state */ - } - default: /* some error occured */ - return CO_DEAD; - } -} - - -static int luaB_costatus (lua_State *L) { - lua_State *co = lua_tothread(L, 1); - luaL_argcheck(L, co, 1, "coroutine expected"); - lua_pushstring(L, statnames[costatus(L, co)]); - return 1; -} - - -static int auxresume (lua_State *L, lua_State *co, int narg) { - int status = costatus(L, co); - if (!lua_checkstack(co, narg)) - luaL_error(L, "too many arguments to resume"); - if (status != CO_SUS) { - lua_pushfstring(L, "cannot resume %s coroutine", statnames[status]); - return -1; /* error flag */ - } - lua_xmove(L, co, narg); - lua_setlevel(L, co); - status = lua_resume(co, narg); - if (status == 0 || status == LUA_YIELD) { - int nres = lua_gettop(co); - if (!lua_checkstack(L, nres + 1)) - luaL_error(L, "too many results to resume"); - lua_xmove(co, L, nres); /* move yielded values */ - return nres; - } - else { - lua_xmove(co, L, 1); /* move error message */ - return -1; /* error flag */ - } -} - - -static int luaB_coresume (lua_State *L) { - lua_State *co = lua_tothread(L, 1); - int r; - luaL_argcheck(L, co, 1, "coroutine expected"); - r = auxresume(L, co, lua_gettop(L) - 1); - if (r < 0) { - lua_pushboolean(L, 0); - lua_insert(L, -2); - return 2; /* return false + error message */ - } - else { - lua_pushboolean(L, 1); - lua_insert(L, -(r + 1)); - return r + 1; /* return true + `resume' returns */ - } -} - - -static int luaB_auxwrap (lua_State *L) { - lua_State *co = lua_tothread(L, lua_upvalueindex(1)); - int r = auxresume(L, co, lua_gettop(L)); - if (r < 0) { - if (lua_isstring(L, -1)) { /* error object is a string? */ - luaL_where(L, 1); /* add extra info */ - lua_insert(L, -2); - lua_concat(L, 2); - } - lua_error(L); /* propagate error */ - } - return r; -} - - -static int luaB_cocreate (lua_State *L) { - lua_State *NL = lua_newthread(L); - luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1, - "Lua function expected"); - lua_pushvalue(L, 1); /* move function to top */ - lua_xmove(L, NL, 1); /* move function from L to NL */ - return 1; -} - - -static int luaB_cowrap (lua_State *L) { - luaB_cocreate(L); - lua_pushcclosure(L, luaB_auxwrap, 1); - return 1; -} - - -static int luaB_yield (lua_State *L) { - return lua_yield(L, lua_gettop(L)); -} - - -static int luaB_corunning (lua_State *L) { - if (lua_pushthread(L)) - lua_pushnil(L); /* main thread is not a coroutine */ - return 1; -} - - -static const luaL_Reg co_funcs[] = { - {"create", luaB_cocreate}, - {"resume", luaB_coresume}, - {"running", luaB_corunning}, - {"status", luaB_costatus}, - {"wrap", luaB_cowrap}, - {"yield", luaB_yield}, - {NULL, NULL} -}; - -/* }====================================================== */ - - -static void auxopen (lua_State *L, const char *name, - lua_CFunction f, lua_CFunction u) { - lua_pushcfunction(L, u); - lua_pushcclosure(L, f, 1); - lua_setfield(L, -2, name); -} - - -static void base_open (lua_State *L) { - /* set global _G */ - lua_pushvalue(L, LUA_GLOBALSINDEX); - lua_setglobal(L, "_G"); - /* open lib into global table */ - luaL_register(L, "_G", base_funcs); - lua_pushliteral(L, LUA_VERSION); - lua_setglobal(L, "_VERSION"); /* set global _VERSION */ - /* `ipairs' and `pairs' need auxliliary functions as upvalues */ - auxopen(L, "ipairs", luaB_ipairs, ipairsaux); - auxopen(L, "pairs", luaB_pairs, luaB_next); - /* `newproxy' needs a weaktable as upvalue */ - lua_createtable(L, 0, 1); /* new table `w' */ - lua_pushvalue(L, -1); /* `w' will be its own metatable */ - lua_setmetatable(L, -2); - lua_pushliteral(L, "kv"); - lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */ - lua_pushcclosure(L, luaB_newproxy, 1); - lua_setglobal(L, "newproxy"); /* set global `newproxy' */ -} - - -LUALIB_API int luaopen_base (lua_State *L) { - base_open(L); - luaL_register(L, LUA_COLIBNAME, co_funcs); - return 2; -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lcode.c b/desmume/src/windows/lua/lua-5.1.4/src/lcode.c deleted file mode 100644 index cff626b7f..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lcode.c +++ /dev/null @@ -1,839 +0,0 @@ -/* -** $Id: lcode.c,v 2.25.1.3 2007/12/28 15:32:23 roberto Exp $ -** Code generator for Lua -** See Copyright Notice in lua.h -*/ - - -#include - -#define lcode_c -#define LUA_CORE - -#include "lua.h" - -#include "lcode.h" -#include "ldebug.h" -#include "ldo.h" -#include "lgc.h" -#include "llex.h" -#include "lmem.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lparser.h" -#include "ltable.h" - - -#define hasjumps(e) ((e)->t != (e)->f) - - -static int isnumeral(expdesc *e) { - return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP); -} - - -void luaK_nil (FuncState *fs, int from, int n) { - Instruction *previous; - if (fs->pc > fs->lasttarget) { /* no jumps to current position? */ - if (fs->pc == 0) { /* function start? */ - if (from >= fs->nactvar) - return; /* positions are already clean */ - } - else { - previous = &fs->f->code[fs->pc-1]; - if (GET_OPCODE(*previous) == OP_LOADNIL) { - int pfrom = GETARG_A(*previous); - int pto = GETARG_B(*previous); - if (pfrom <= from && from <= pto+1) { /* can connect both? */ - if (from+n-1 > pto) - SETARG_B(*previous, from+n-1); - return; - } - } - } - } - luaK_codeABC(fs, OP_LOADNIL, from, from+n-1, 0); /* else no optimization */ -} - - -int luaK_jump (FuncState *fs) { - int jpc = fs->jpc; /* save list of jumps to here */ - int j; - fs->jpc = NO_JUMP; - j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP); - luaK_concat(fs, &j, jpc); /* keep them on hold */ - return j; -} - - -void luaK_ret (FuncState *fs, int first, int nret) { - luaK_codeABC(fs, OP_RETURN, first, nret+1, 0); -} - - -static int condjump (FuncState *fs, OpCode op, int A, int B, int C) { - luaK_codeABC(fs, op, A, B, C); - return luaK_jump(fs); -} - - -static void fixjump (FuncState *fs, int pc, int dest) { - Instruction *jmp = &fs->f->code[pc]; - int offset = dest-(pc+1); - lua_assert(dest != NO_JUMP); - if (abs(offset) > MAXARG_sBx) - luaX_syntaxerror(fs->ls, "control structure too long"); - SETARG_sBx(*jmp, offset); -} - - -/* -** returns current `pc' and marks it as a jump target (to avoid wrong -** optimizations with consecutive instructions not in the same basic block). -*/ -int luaK_getlabel (FuncState *fs) { - fs->lasttarget = fs->pc; - return fs->pc; -} - - -static int getjump (FuncState *fs, int pc) { - int offset = GETARG_sBx(fs->f->code[pc]); - if (offset == NO_JUMP) /* point to itself represents end of list */ - return NO_JUMP; /* end of list */ - else - return (pc+1)+offset; /* turn offset into absolute position */ -} - - -static Instruction *getjumpcontrol (FuncState *fs, int pc) { - Instruction *pi = &fs->f->code[pc]; - if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) - return pi-1; - else - return pi; -} - - -/* -** check whether list has any jump that do not produce a value -** (or produce an inverted value) -*/ -static int need_value (FuncState *fs, int list) { - for (; list != NO_JUMP; list = getjump(fs, list)) { - Instruction i = *getjumpcontrol(fs, list); - if (GET_OPCODE(i) != OP_TESTSET) return 1; - } - return 0; /* not found */ -} - - -static int patchtestreg (FuncState *fs, int node, int reg) { - Instruction *i = getjumpcontrol(fs, node); - if (GET_OPCODE(*i) != OP_TESTSET) - return 0; /* cannot patch other instructions */ - if (reg != NO_REG && reg != GETARG_B(*i)) - SETARG_A(*i, reg); - else /* no register to put value or register already has the value */ - *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i)); - - return 1; -} - - -static void removevalues (FuncState *fs, int list) { - for (; list != NO_JUMP; list = getjump(fs, list)) - patchtestreg(fs, list, NO_REG); -} - - -static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, - int dtarget) { - while (list != NO_JUMP) { - int next = getjump(fs, list); - if (patchtestreg(fs, list, reg)) - fixjump(fs, list, vtarget); - else - fixjump(fs, list, dtarget); /* jump to default target */ - list = next; - } -} - - -static void dischargejpc (FuncState *fs) { - patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc); - fs->jpc = NO_JUMP; -} - - -void luaK_patchlist (FuncState *fs, int list, int target) { - if (target == fs->pc) - luaK_patchtohere(fs, list); - else { - lua_assert(target < fs->pc); - patchlistaux(fs, list, target, NO_REG, target); - } -} - - -void luaK_patchtohere (FuncState *fs, int list) { - luaK_getlabel(fs); - luaK_concat(fs, &fs->jpc, list); -} - - -void luaK_concat (FuncState *fs, int *l1, int l2) { - if (l2 == NO_JUMP) return; - else if (*l1 == NO_JUMP) - *l1 = l2; - else { - int list = *l1; - int next; - while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ - list = next; - fixjump(fs, list, l2); - } -} - - -void luaK_checkstack (FuncState *fs, int n) { - int newstack = fs->freereg + n; - if (newstack > fs->f->maxstacksize) { - if (newstack >= MAXSTACK) - luaX_syntaxerror(fs->ls, "function or expression too complex"); - fs->f->maxstacksize = cast_byte(newstack); - } -} - - -void luaK_reserveregs (FuncState *fs, int n) { - luaK_checkstack(fs, n); - fs->freereg += n; -} - - -static void freereg (FuncState *fs, int reg) { - if (!ISK(reg) && reg >= fs->nactvar) { - fs->freereg--; - lua_assert(reg == fs->freereg); - } -} - - -static void freeexp (FuncState *fs, expdesc *e) { - if (e->k == VNONRELOC) - freereg(fs, e->u.s.info); -} - - -static int addk (FuncState *fs, TValue *k, TValue *v) { - lua_State *L = fs->L; - TValue *idx = luaH_set(L, fs->h, k); - Proto *f = fs->f; - int oldsize = f->sizek; - if (ttisnumber(idx)) { - lua_assert(luaO_rawequalObj(&fs->f->k[cast_int(nvalue(idx))], v)); - return cast_int(nvalue(idx)); - } - else { /* constant not found; create a new entry */ - setnvalue(idx, cast_num(fs->nk)); - luaM_growvector(L, f->k, fs->nk, f->sizek, TValue, - MAXARG_Bx, "constant table overflow"); - while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); - setobj(L, &f->k[fs->nk], v); - luaC_barrier(L, f, v); - return fs->nk++; - } -} - - -int luaK_stringK (FuncState *fs, TString *s) { - TValue o; - setsvalue(fs->L, &o, s); - return addk(fs, &o, &o); -} - - -int luaK_numberK (FuncState *fs, lua_Number r) { - TValue o; - setnvalue(&o, r); - return addk(fs, &o, &o); -} - - -static int boolK (FuncState *fs, int b) { - TValue o; - setbvalue(&o, b); - return addk(fs, &o, &o); -} - - -static int nilK (FuncState *fs) { - TValue k, v; - setnilvalue(&v); - /* cannot use nil as key; instead use table itself to represent nil */ - sethvalue(fs->L, &k, fs->h); - return addk(fs, &k, &v); -} - - -void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { - if (e->k == VCALL) { /* expression is an open function call? */ - SETARG_C(getcode(fs, e), nresults+1); - } - else if (e->k == VVARARG) { - SETARG_B(getcode(fs, e), nresults+1); - SETARG_A(getcode(fs, e), fs->freereg); - luaK_reserveregs(fs, 1); - } -} - - -void luaK_setoneret (FuncState *fs, expdesc *e) { - if (e->k == VCALL) { /* expression is an open function call? */ - e->k = VNONRELOC; - e->u.s.info = GETARG_A(getcode(fs, e)); - } - else if (e->k == VVARARG) { - SETARG_B(getcode(fs, e), 2); - e->k = VRELOCABLE; /* can relocate its simple result */ - } -} - - -void luaK_dischargevars (FuncState *fs, expdesc *e) { - switch (e->k) { - case VLOCAL: { - e->k = VNONRELOC; - break; - } - case VUPVAL: { - e->u.s.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.s.info, 0); - e->k = VRELOCABLE; - break; - } - case VGLOBAL: { - e->u.s.info = luaK_codeABx(fs, OP_GETGLOBAL, 0, e->u.s.info); - e->k = VRELOCABLE; - break; - } - case VINDEXED: { - freereg(fs, e->u.s.aux); - freereg(fs, e->u.s.info); - e->u.s.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.s.info, e->u.s.aux); - e->k = VRELOCABLE; - break; - } - case VVARARG: - case VCALL: { - luaK_setoneret(fs, e); - break; - } - default: break; /* there is one value available (somewhere) */ - } -} - - -static int code_label (FuncState *fs, int A, int b, int jump) { - luaK_getlabel(fs); /* those instructions may be jump targets */ - return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump); -} - - -static void discharge2reg (FuncState *fs, expdesc *e, int reg) { - luaK_dischargevars(fs, e); - switch (e->k) { - case VNIL: { - luaK_nil(fs, reg, 1); - break; - } - case VFALSE: case VTRUE: { - luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0); - break; - } - case VK: { - luaK_codeABx(fs, OP_LOADK, reg, e->u.s.info); - break; - } - case VKNUM: { - luaK_codeABx(fs, OP_LOADK, reg, luaK_numberK(fs, e->u.nval)); - break; - } - case VRELOCABLE: { - Instruction *pc = &getcode(fs, e); - SETARG_A(*pc, reg); - break; - } - case VNONRELOC: { - if (reg != e->u.s.info) - luaK_codeABC(fs, OP_MOVE, reg, e->u.s.info, 0); - break; - } - default: { - lua_assert(e->k == VVOID || e->k == VJMP); - return; /* nothing to do... */ - } - } - e->u.s.info = reg; - e->k = VNONRELOC; -} - - -static void discharge2anyreg (FuncState *fs, expdesc *e) { - if (e->k != VNONRELOC) { - luaK_reserveregs(fs, 1); - discharge2reg(fs, e, fs->freereg-1); - } -} - - -static void exp2reg (FuncState *fs, expdesc *e, int reg) { - discharge2reg(fs, e, reg); - if (e->k == VJMP) - luaK_concat(fs, &e->t, e->u.s.info); /* put this jump in `t' list */ - if (hasjumps(e)) { - int final; /* position after whole expression */ - int p_f = NO_JUMP; /* position of an eventual LOAD false */ - int p_t = NO_JUMP; /* position of an eventual LOAD true */ - if (need_value(fs, e->t) || need_value(fs, e->f)) { - int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); - p_f = code_label(fs, reg, 0, 1); - p_t = code_label(fs, reg, 1, 0); - luaK_patchtohere(fs, fj); - } - final = luaK_getlabel(fs); - patchlistaux(fs, e->f, final, reg, p_f); - patchlistaux(fs, e->t, final, reg, p_t); - } - e->f = e->t = NO_JUMP; - e->u.s.info = reg; - e->k = VNONRELOC; -} - - -void luaK_exp2nextreg (FuncState *fs, expdesc *e) { - luaK_dischargevars(fs, e); - freeexp(fs, e); - luaK_reserveregs(fs, 1); - exp2reg(fs, e, fs->freereg - 1); -} - - -int luaK_exp2anyreg (FuncState *fs, expdesc *e) { - luaK_dischargevars(fs, e); - if (e->k == VNONRELOC) { - if (!hasjumps(e)) return e->u.s.info; /* exp is already in a register */ - if (e->u.s.info >= fs->nactvar) { /* reg. is not a local? */ - exp2reg(fs, e, e->u.s.info); /* put value on it */ - return e->u.s.info; - } - } - luaK_exp2nextreg(fs, e); /* default */ - return e->u.s.info; -} - - -void luaK_exp2val (FuncState *fs, expdesc *e) { - if (hasjumps(e)) - luaK_exp2anyreg(fs, e); - else - luaK_dischargevars(fs, e); -} - - -int luaK_exp2RK (FuncState *fs, expdesc *e) { - luaK_exp2val(fs, e); - switch (e->k) { - case VKNUM: - case VTRUE: - case VFALSE: - case VNIL: { - if (fs->nk <= MAXINDEXRK) { /* constant fit in RK operand? */ - e->u.s.info = (e->k == VNIL) ? nilK(fs) : - (e->k == VKNUM) ? luaK_numberK(fs, e->u.nval) : - boolK(fs, (e->k == VTRUE)); - e->k = VK; - return RKASK(e->u.s.info); - } - else break; - } - case VK: { - if (e->u.s.info <= MAXINDEXRK) /* constant fit in argC? */ - return RKASK(e->u.s.info); - else break; - } - default: break; - } - /* not a constant in the right range: put it in a register */ - return luaK_exp2anyreg(fs, e); -} - - -void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { - switch (var->k) { - case VLOCAL: { - freeexp(fs, ex); - exp2reg(fs, ex, var->u.s.info); - return; - } - case VUPVAL: { - int e = luaK_exp2anyreg(fs, ex); - luaK_codeABC(fs, OP_SETUPVAL, e, var->u.s.info, 0); - break; - } - case VGLOBAL: { - int e = luaK_exp2anyreg(fs, ex); - luaK_codeABx(fs, OP_SETGLOBAL, e, var->u.s.info); - break; - } - case VINDEXED: { - int e = luaK_exp2RK(fs, ex); - luaK_codeABC(fs, OP_SETTABLE, var->u.s.info, var->u.s.aux, e); - break; - } - default: { - lua_assert(0); /* invalid var kind to store */ - break; - } - } - freeexp(fs, ex); -} - - -void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { - int func; - luaK_exp2anyreg(fs, e); - freeexp(fs, e); - func = fs->freereg; - luaK_reserveregs(fs, 2); - luaK_codeABC(fs, OP_SELF, func, e->u.s.info, luaK_exp2RK(fs, key)); - freeexp(fs, key); - e->u.s.info = func; - e->k = VNONRELOC; -} - - -static void invertjump (FuncState *fs, expdesc *e) { - Instruction *pc = getjumpcontrol(fs, e->u.s.info); - lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && - GET_OPCODE(*pc) != OP_TEST); - SETARG_A(*pc, !(GETARG_A(*pc))); -} - - -static int jumponcond (FuncState *fs, expdesc *e, int cond) { - if (e->k == VRELOCABLE) { - Instruction ie = getcode(fs, e); - if (GET_OPCODE(ie) == OP_NOT) { - fs->pc--; /* remove previous OP_NOT */ - return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond); - } - /* else go through */ - } - discharge2anyreg(fs, e); - freeexp(fs, e); - return condjump(fs, OP_TESTSET, NO_REG, e->u.s.info, cond); -} - - -void luaK_goiftrue (FuncState *fs, expdesc *e) { - int pc; /* pc of last jump */ - luaK_dischargevars(fs, e); - switch (e->k) { - case VK: case VKNUM: case VTRUE: { - pc = NO_JUMP; /* always true; do nothing */ - break; - } - case VFALSE: { - pc = luaK_jump(fs); /* always jump */ - break; - } - case VJMP: { - invertjump(fs, e); - pc = e->u.s.info; - break; - } - default: { - pc = jumponcond(fs, e, 0); - break; - } - } - luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */ - luaK_patchtohere(fs, e->t); - e->t = NO_JUMP; -} - - -static void luaK_goiffalse (FuncState *fs, expdesc *e) { - int pc; /* pc of last jump */ - luaK_dischargevars(fs, e); - switch (e->k) { - case VNIL: case VFALSE: { - pc = NO_JUMP; /* always false; do nothing */ - break; - } - case VTRUE: { - pc = luaK_jump(fs); /* always jump */ - break; - } - case VJMP: { - pc = e->u.s.info; - break; - } - default: { - pc = jumponcond(fs, e, 1); - break; - } - } - luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */ - luaK_patchtohere(fs, e->f); - e->f = NO_JUMP; -} - - -static void codenot (FuncState *fs, expdesc *e) { - luaK_dischargevars(fs, e); - switch (e->k) { - case VNIL: case VFALSE: { - e->k = VTRUE; - break; - } - case VK: case VKNUM: case VTRUE: { - e->k = VFALSE; - break; - } - case VJMP: { - invertjump(fs, e); - break; - } - case VRELOCABLE: - case VNONRELOC: { - discharge2anyreg(fs, e); - freeexp(fs, e); - e->u.s.info = luaK_codeABC(fs, OP_NOT, 0, e->u.s.info, 0); - e->k = VRELOCABLE; - break; - } - default: { - lua_assert(0); /* cannot happen */ - break; - } - } - /* interchange true and false lists */ - { int temp = e->f; e->f = e->t; e->t = temp; } - removevalues(fs, e->f); - removevalues(fs, e->t); -} - - -void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { - t->u.s.aux = luaK_exp2RK(fs, k); - t->k = VINDEXED; -} - - -static int constfolding (OpCode op, expdesc *e1, expdesc *e2) { - lua_Number v1, v2, r; - if (!isnumeral(e1) || !isnumeral(e2)) return 0; - v1 = e1->u.nval; - v2 = e2->u.nval; - switch (op) { - case OP_ADD: r = luai_numadd(v1, v2); break; - case OP_SUB: r = luai_numsub(v1, v2); break; - case OP_MUL: r = luai_nummul(v1, v2); break; - case OP_DIV: - if (v2 == 0) return 0; /* do not attempt to divide by 0 */ - r = luai_numdiv(v1, v2); break; - case OP_MOD: - if (v2 == 0) return 0; /* do not attempt to divide by 0 */ - r = luai_nummod(v1, v2); break; - case OP_POW: r = luai_numpow(v1, v2); break; - case OP_UNM: r = luai_numunm(v1); break; - case OP_LEN: return 0; /* no constant folding for 'len' */ - default: lua_assert(0); r = 0; break; - } - if (luai_numisnan(r)) return 0; /* do not attempt to produce NaN */ - e1->u.nval = r; - return 1; -} - - -static void codearith (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) { - if (constfolding(op, e1, e2)) - return; - else { - int o2 = (op != OP_UNM && op != OP_LEN) ? luaK_exp2RK(fs, e2) : 0; - int o1 = luaK_exp2RK(fs, e1); - if (o1 > o2) { - freeexp(fs, e1); - freeexp(fs, e2); - } - else { - freeexp(fs, e2); - freeexp(fs, e1); - } - e1->u.s.info = luaK_codeABC(fs, op, 0, o1, o2); - e1->k = VRELOCABLE; - } -} - - -static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1, - expdesc *e2) { - int o1 = luaK_exp2RK(fs, e1); - int o2 = luaK_exp2RK(fs, e2); - freeexp(fs, e2); - freeexp(fs, e1); - if (cond == 0 && op != OP_EQ) { - int temp; /* exchange args to replace by `<' or `<=' */ - temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */ - cond = 1; - } - e1->u.s.info = condjump(fs, op, cond, o1, o2); - e1->k = VJMP; -} - - -void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e) { - expdesc e2; - e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0; - switch (op) { - case OPR_MINUS: { - if (!isnumeral(e)) - luaK_exp2anyreg(fs, e); /* cannot operate on non-numeric constants */ - codearith(fs, OP_UNM, e, &e2); - break; - } - case OPR_NOT: codenot(fs, e); break; - case OPR_LEN: { - luaK_exp2anyreg(fs, e); /* cannot operate on constants */ - codearith(fs, OP_LEN, e, &e2); - break; - } - default: lua_assert(0); - } -} - - -void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { - switch (op) { - case OPR_AND: { - luaK_goiftrue(fs, v); - break; - } - case OPR_OR: { - luaK_goiffalse(fs, v); - break; - } - case OPR_CONCAT: { - luaK_exp2nextreg(fs, v); /* operand must be on the `stack' */ - break; - } - case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: - case OPR_MOD: case OPR_POW: { - if (!isnumeral(v)) luaK_exp2RK(fs, v); - break; - } - default: { - luaK_exp2RK(fs, v); - break; - } - } -} - - -void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2) { - switch (op) { - case OPR_AND: { - lua_assert(e1->t == NO_JUMP); /* list must be closed */ - luaK_dischargevars(fs, e2); - luaK_concat(fs, &e2->f, e1->f); - *e1 = *e2; - break; - } - case OPR_OR: { - lua_assert(e1->f == NO_JUMP); /* list must be closed */ - luaK_dischargevars(fs, e2); - luaK_concat(fs, &e2->t, e1->t); - *e1 = *e2; - break; - } - case OPR_CONCAT: { - luaK_exp2val(fs, e2); - if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) { - lua_assert(e1->u.s.info == GETARG_B(getcode(fs, e2))-1); - freeexp(fs, e1); - SETARG_B(getcode(fs, e2), e1->u.s.info); - e1->k = VRELOCABLE; e1->u.s.info = e2->u.s.info; - } - else { - luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */ - codearith(fs, OP_CONCAT, e1, e2); - } - break; - } - case OPR_ADD: codearith(fs, OP_ADD, e1, e2); break; - case OPR_SUB: codearith(fs, OP_SUB, e1, e2); break; - case OPR_MUL: codearith(fs, OP_MUL, e1, e2); break; - case OPR_DIV: codearith(fs, OP_DIV, e1, e2); break; - case OPR_MOD: codearith(fs, OP_MOD, e1, e2); break; - case OPR_POW: codearith(fs, OP_POW, e1, e2); break; - case OPR_EQ: codecomp(fs, OP_EQ, 1, e1, e2); break; - case OPR_NE: codecomp(fs, OP_EQ, 0, e1, e2); break; - case OPR_LT: codecomp(fs, OP_LT, 1, e1, e2); break; - case OPR_LE: codecomp(fs, OP_LE, 1, e1, e2); break; - case OPR_GT: codecomp(fs, OP_LT, 0, e1, e2); break; - case OPR_GE: codecomp(fs, OP_LE, 0, e1, e2); break; - default: lua_assert(0); - } -} - - -void luaK_fixline (FuncState *fs, int line) { - fs->f->lineinfo[fs->pc - 1] = line; -} - - -static int luaK_code (FuncState *fs, Instruction i, int line) { - Proto *f = fs->f; - dischargejpc(fs); /* `pc' will change */ - /* put new instruction in code array */ - luaM_growvector(fs->L, f->code, fs->pc, f->sizecode, Instruction, - MAX_INT, "code size overflow"); - f->code[fs->pc] = i; - /* save corresponding line information */ - luaM_growvector(fs->L, f->lineinfo, fs->pc, f->sizelineinfo, int, - MAX_INT, "code size overflow"); - f->lineinfo[fs->pc] = line; - return fs->pc++; -} - - -int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) { - lua_assert(getOpMode(o) == iABC); - lua_assert(getBMode(o) != OpArgN || b == 0); - lua_assert(getCMode(o) != OpArgN || c == 0); - return luaK_code(fs, CREATE_ABC(o, a, b, c), fs->ls->lastline); -} - - -int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { - lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx); - lua_assert(getCMode(o) == OpArgN); - return luaK_code(fs, CREATE_ABx(o, a, bc), fs->ls->lastline); -} - - -void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { - int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1; - int b = (tostore == LUA_MULTRET) ? 0 : tostore; - lua_assert(tostore != 0); - if (c <= MAXARG_C) - luaK_codeABC(fs, OP_SETLIST, base, b, c); - else { - luaK_codeABC(fs, OP_SETLIST, base, b, 0); - luaK_code(fs, cast(Instruction, c), fs->ls->lastline); - } - fs->freereg = base + 1; /* free registers with list values */ -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lcode.h b/desmume/src/windows/lua/lua-5.1.4/src/lcode.h deleted file mode 100644 index b941c6072..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lcode.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -** $Id: lcode.h,v 1.48.1.1 2007/12/27 13:02:25 roberto Exp $ -** Code generator for Lua -** See Copyright Notice in lua.h -*/ - -#ifndef lcode_h -#define lcode_h - -#include "llex.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lparser.h" - - -/* -** Marks the end of a patch list. It is an invalid value both as an absolute -** address, and as a list link (would link an element to itself). -*/ -#define NO_JUMP (-1) - - -/* -** grep "ORDER OPR" if you change these enums -*/ -typedef enum BinOpr { - OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW, - OPR_CONCAT, - OPR_NE, OPR_EQ, - OPR_LT, OPR_LE, OPR_GT, OPR_GE, - OPR_AND, OPR_OR, - OPR_NOBINOPR -} BinOpr; - - -typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr; - - -#define getcode(fs,e) ((fs)->f->code[(e)->u.s.info]) - -#define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx) - -#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET) - -LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx); -LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C); -LUAI_FUNC void luaK_fixline (FuncState *fs, int line); -LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n); -LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n); -LUAI_FUNC void luaK_checkstack (FuncState *fs, int n); -LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s); -LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r); -LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e); -LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e); -LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e); -LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e); -LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e); -LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key); -LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k); -LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e); -LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e); -LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults); -LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e); -LUAI_FUNC int luaK_jump (FuncState *fs); -LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret); -LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target); -LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list); -LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2); -LUAI_FUNC int luaK_getlabel (FuncState *fs); -LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v); -LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v); -LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, expdesc *v2); -LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore); - - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/ldblib.c b/desmume/src/windows/lua/lua-5.1.4/src/ldblib.c deleted file mode 100644 index 67de1222a..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/ldblib.c +++ /dev/null @@ -1,397 +0,0 @@ -/* -** $Id: ldblib.c,v 1.104.1.3 2008/01/21 13:11:21 roberto Exp $ -** Interface from Lua to its debug API -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include - -#define ldblib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - - -static int db_getregistry (lua_State *L) { - lua_pushvalue(L, LUA_REGISTRYINDEX); - return 1; -} - - -static int db_getmetatable (lua_State *L) { - luaL_checkany(L, 1); - if (!lua_getmetatable(L, 1)) { - lua_pushnil(L); /* no metatable */ - } - return 1; -} - - -static int db_setmetatable (lua_State *L) { - int t = lua_type(L, 2); - luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, - "nil or table expected"); - lua_settop(L, 2); - lua_pushboolean(L, lua_setmetatable(L, 1)); - return 1; -} - - -static int db_getfenv (lua_State *L) { - lua_getfenv(L, 1); - return 1; -} - - -static int db_setfenv (lua_State *L) { - luaL_checktype(L, 2, LUA_TTABLE); - lua_settop(L, 2); - if (lua_setfenv(L, 1) == 0) - luaL_error(L, LUA_QL("setfenv") - " cannot change environment of given object"); - return 1; -} - - -static void settabss (lua_State *L, const char *i, const char *v) { - lua_pushstring(L, v); - lua_setfield(L, -2, i); -} - - -static void settabsi (lua_State *L, const char *i, int v) { - lua_pushinteger(L, v); - lua_setfield(L, -2, i); -} - - -static lua_State *getthread (lua_State *L, int *arg) { - if (lua_isthread(L, 1)) { - *arg = 1; - return lua_tothread(L, 1); - } - else { - *arg = 0; - return L; - } -} - - -static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) { - if (L == L1) { - lua_pushvalue(L, -2); - lua_remove(L, -3); - } - else - lua_xmove(L1, L, 1); - lua_setfield(L, -2, fname); -} - - -static int db_getinfo (lua_State *L) { - lua_Debug ar; - int arg; - lua_State *L1 = getthread(L, &arg); - const char *options = luaL_optstring(L, arg+2, "flnSu"); - if (lua_isnumber(L, arg+1)) { - if (!lua_getstack(L1, (int)lua_tointeger(L, arg+1), &ar)) { - lua_pushnil(L); /* level out of range */ - return 1; - } - } - else if (lua_isfunction(L, arg+1)) { - lua_pushfstring(L, ">%s", options); - options = lua_tostring(L, -1); - lua_pushvalue(L, arg+1); - lua_xmove(L, L1, 1); - } - else - return luaL_argerror(L, arg+1, "function or level expected"); - if (!lua_getinfo(L1, options, &ar)) - return luaL_argerror(L, arg+2, "invalid option"); - lua_createtable(L, 0, 2); - if (strchr(options, 'S')) { - settabss(L, "source", ar.source); - settabss(L, "short_src", ar.short_src); - settabsi(L, "linedefined", ar.linedefined); - settabsi(L, "lastlinedefined", ar.lastlinedefined); - settabss(L, "what", ar.what); - } - if (strchr(options, 'l')) - settabsi(L, "currentline", ar.currentline); - if (strchr(options, 'u')) - settabsi(L, "nups", ar.nups); - if (strchr(options, 'n')) { - settabss(L, "name", ar.name); - settabss(L, "namewhat", ar.namewhat); - } - if (strchr(options, 'L')) - treatstackoption(L, L1, "activelines"); - if (strchr(options, 'f')) - treatstackoption(L, L1, "func"); - return 1; /* return table */ -} - - -static int db_getlocal (lua_State *L) { - int arg; - lua_State *L1 = getthread(L, &arg); - lua_Debug ar; - const char *name; - if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ - return luaL_argerror(L, arg+1, "level out of range"); - name = lua_getlocal(L1, &ar, luaL_checkint(L, arg+2)); - if (name) { - lua_xmove(L1, L, 1); - lua_pushstring(L, name); - lua_pushvalue(L, -2); - return 2; - } - else { - lua_pushnil(L); - return 1; - } -} - - -static int db_setlocal (lua_State *L) { - int arg; - lua_State *L1 = getthread(L, &arg); - lua_Debug ar; - if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ - return luaL_argerror(L, arg+1, "level out of range"); - luaL_checkany(L, arg+3); - lua_settop(L, arg+3); - lua_xmove(L, L1, 1); - lua_pushstring(L, lua_setlocal(L1, &ar, luaL_checkint(L, arg+2))); - return 1; -} - - -static int auxupvalue (lua_State *L, int get) { - const char *name; - int n = luaL_checkint(L, 2); - luaL_checktype(L, 1, LUA_TFUNCTION); - if (lua_iscfunction(L, 1)) return 0; /* cannot touch C upvalues from Lua */ - name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n); - if (name == NULL) return 0; - lua_pushstring(L, name); - lua_insert(L, -(get+1)); - return get + 1; -} - - -static int db_getupvalue (lua_State *L) { - return auxupvalue(L, 1); -} - - -static int db_setupvalue (lua_State *L) { - luaL_checkany(L, 3); - return auxupvalue(L, 0); -} - - - -static const char KEY_HOOK = 'h'; - - -static void hookf (lua_State *L, lua_Debug *ar) { - static const char *const hooknames[] = - {"call", "return", "line", "count", "tail return"}; - lua_pushlightuserdata(L, (void *)&KEY_HOOK); - lua_rawget(L, LUA_REGISTRYINDEX); - lua_pushlightuserdata(L, L); - lua_rawget(L, -2); - if (lua_isfunction(L, -1)) { - lua_pushstring(L, hooknames[(int)ar->event]); - if (ar->currentline >= 0) - lua_pushinteger(L, ar->currentline); - else lua_pushnil(L); - lua_assert(lua_getinfo(L, "lS", ar)); - lua_call(L, 2, 0); - } -} - - -static int makemask (const char *smask, int count) { - int mask = 0; - if (strchr(smask, 'c')) mask |= LUA_MASKCALL; - if (strchr(smask, 'r')) mask |= LUA_MASKRET; - if (strchr(smask, 'l')) mask |= LUA_MASKLINE; - if (count > 0) mask |= LUA_MASKCOUNT; - return mask; -} - - -static char *unmakemask (int mask, char *smask) { - int i = 0; - if (mask & LUA_MASKCALL) smask[i++] = 'c'; - if (mask & LUA_MASKRET) smask[i++] = 'r'; - if (mask & LUA_MASKLINE) smask[i++] = 'l'; - smask[i] = '\0'; - return smask; -} - - -static void gethooktable (lua_State *L) { - lua_pushlightuserdata(L, (void *)&KEY_HOOK); - lua_rawget(L, LUA_REGISTRYINDEX); - if (!lua_istable(L, -1)) { - lua_pop(L, 1); - lua_createtable(L, 0, 1); - lua_pushlightuserdata(L, (void *)&KEY_HOOK); - lua_pushvalue(L, -2); - lua_rawset(L, LUA_REGISTRYINDEX); - } -} - - -static int db_sethook (lua_State *L) { - int arg, mask, count; - lua_Hook func; - lua_State *L1 = getthread(L, &arg); - if (lua_isnoneornil(L, arg+1)) { - lua_settop(L, arg+1); - func = NULL; mask = 0; count = 0; /* turn off hooks */ - } - else { - const char *smask = luaL_checkstring(L, arg+2); - luaL_checktype(L, arg+1, LUA_TFUNCTION); - count = luaL_optint(L, arg+3, 0); - func = hookf; mask = makemask(smask, count); - } - gethooktable(L); - lua_pushlightuserdata(L, L1); - lua_pushvalue(L, arg+1); - lua_rawset(L, -3); /* set new hook */ - lua_pop(L, 1); /* remove hook table */ - lua_sethook(L1, func, mask, count); /* set hooks */ - return 0; -} - - -static int db_gethook (lua_State *L) { - int arg; - lua_State *L1 = getthread(L, &arg); - char buff[5]; - int mask = lua_gethookmask(L1); - lua_Hook hook = lua_gethook(L1); - if (hook != NULL && hook != hookf) /* external hook? */ - lua_pushliteral(L, "external hook"); - else { - gethooktable(L); - lua_pushlightuserdata(L, L1); - lua_rawget(L, -2); /* get hook */ - lua_remove(L, -2); /* remove hook table */ - } - lua_pushstring(L, unmakemask(mask, buff)); - lua_pushinteger(L, lua_gethookcount(L1)); - return 3; -} - - -static int db_debug (lua_State *L) { - for (;;) { - char buffer[250]; - fputs("lua_debug> ", stderr); - if (fgets(buffer, sizeof(buffer), stdin) == 0 || - strcmp(buffer, "cont\n") == 0) - return 0; - if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || - lua_pcall(L, 0, 0, 0)) { - fputs(lua_tostring(L, -1), stderr); - fputs("\n", stderr); - } - lua_settop(L, 0); /* remove eventual returns */ - } -} - - -#define LEVELS1 12 /* size of the first part of the stack */ -#define LEVELS2 10 /* size of the second part of the stack */ - -static int db_errorfb (lua_State *L) { - int level; - int firstpart = 1; /* still before eventual `...' */ - int arg; - lua_State *L1 = getthread(L, &arg); - lua_Debug ar; - if (lua_isnumber(L, arg+2)) { - level = (int)lua_tointeger(L, arg+2); - lua_pop(L, 1); - } - else - level = (L == L1) ? 1 : 0; /* level 0 may be this own function */ - if (lua_gettop(L) == arg) - lua_pushliteral(L, ""); - else if (!lua_isstring(L, arg+1)) return 1; /* message is not a string */ - else lua_pushliteral(L, "\n"); - lua_pushliteral(L, "stack traceback:"); - while (lua_getstack(L1, level++, &ar)) { - if (level > LEVELS1 && firstpart) { - /* no more than `LEVELS2' more levels? */ - if (!lua_getstack(L1, level+LEVELS2, &ar)) - level--; /* keep going */ - else { - lua_pushliteral(L, "\n\t..."); /* too many levels */ - while (lua_getstack(L1, level+LEVELS2, &ar)) /* find last levels */ - level++; - } - firstpart = 0; - continue; - } - lua_pushliteral(L, "\n\t"); - lua_getinfo(L1, "Snl", &ar); - lua_pushfstring(L, "%s:", ar.short_src); - if (ar.currentline > 0) - lua_pushfstring(L, "%d:", ar.currentline); - if (*ar.namewhat != '\0') /* is there a name? */ - lua_pushfstring(L, " in function " LUA_QS, ar.name); - else { - if (*ar.what == 'm') /* main? */ - lua_pushfstring(L, " in main chunk"); - else if (*ar.what == 'C' || *ar.what == 't') - lua_pushliteral(L, " ?"); /* C function or tail call */ - else - lua_pushfstring(L, " in function <%s:%d>", - ar.short_src, ar.linedefined); - } - lua_concat(L, lua_gettop(L) - arg); - } - lua_concat(L, lua_gettop(L) - arg); - return 1; -} - - -static const luaL_Reg dblib[] = { - {"debug", db_debug}, - {"getfenv", db_getfenv}, - {"gethook", db_gethook}, - {"getinfo", db_getinfo}, - {"getlocal", db_getlocal}, - {"getregistry", db_getregistry}, - {"getmetatable", db_getmetatable}, - {"getupvalue", db_getupvalue}, - {"setfenv", db_setfenv}, - {"sethook", db_sethook}, - {"setlocal", db_setlocal}, - {"setmetatable", db_setmetatable}, - {"setupvalue", db_setupvalue}, - {"traceback", db_errorfb}, - {NULL, NULL} -}; - - -LUALIB_API int luaopen_debug (lua_State *L) { - luaL_register(L, LUA_DBLIBNAME, dblib); - return 1; -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/ldebug.c b/desmume/src/windows/lua/lua-5.1.4/src/ldebug.c deleted file mode 100644 index 50ad3d380..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/ldebug.c +++ /dev/null @@ -1,638 +0,0 @@ -/* -** $Id: ldebug.c,v 2.29.1.6 2008/05/08 16:56:26 roberto Exp $ -** Debug Interface -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include - - -#define ldebug_c -#define LUA_CORE - -#include "lua.h" - -#include "lapi.h" -#include "lcode.h" -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" -#include "lvm.h" - - - -static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name); - - -static int currentpc (lua_State *L, CallInfo *ci) { - if (!isLua(ci)) return -1; /* function is not a Lua function? */ - if (ci == L->ci) - ci->savedpc = L->savedpc; - return pcRel(ci->savedpc, ci_func(ci)->l.p); -} - - -static int currentline (lua_State *L, CallInfo *ci) { - int pc = currentpc(L, ci); - if (pc < 0) - return -1; /* only active lua functions have current-line information */ - else - return getline(ci_func(ci)->l.p, pc); -} - - -/* -** this function can be called asynchronous (e.g. during a signal) -*/ -LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { - if (func == NULL || mask == 0) { /* turn off hooks? */ - mask = 0; - func = NULL; - } - L->hook = func; - L->basehookcount = count; - resethookcount(L); - L->hookmask = cast_byte(mask); - return 1; -} - - -LUA_API lua_Hook lua_gethook (lua_State *L) { - return L->hook; -} - - -LUA_API int lua_gethookmask (lua_State *L) { - return L->hookmask; -} - - -LUA_API int lua_gethookcount (lua_State *L) { - return L->basehookcount; -} - - -LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { - int status; - CallInfo *ci; - lua_lock(L); - for (ci = L->ci; level > 0 && ci > L->base_ci; ci--) { - level--; - if (f_isLua(ci)) /* Lua function? */ - level -= ci->tailcalls; /* skip lost tail calls */ - } - if (level == 0 && ci > L->base_ci) { /* level found? */ - status = 1; - ar->i_ci = cast_int(ci - L->base_ci); - } - else if (level < 0) { /* level is of a lost tail call? */ - status = 1; - ar->i_ci = 0; - } - else status = 0; /* no such level */ - lua_unlock(L); - return status; -} - - -static Proto *getluaproto (CallInfo *ci) { - return (isLua(ci) ? ci_func(ci)->l.p : NULL); -} - - -static const char *findlocal (lua_State *L, CallInfo *ci, int n) { - const char *name; - Proto *fp = getluaproto(ci); - if (fp && (name = luaF_getlocalname(fp, n, currentpc(L, ci))) != NULL) - return name; /* is a local variable in a Lua function */ - else { - StkId limit = (ci == L->ci) ? L->top : (ci+1)->func; - if (limit - ci->base >= n && n > 0) /* is 'n' inside 'ci' stack? */ - return "(*temporary)"; - else - return NULL; - } -} - - -LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { - CallInfo *ci = L->base_ci + ar->i_ci; - const char *name = findlocal(L, ci, n); - lua_lock(L); - if (name) - luaA_pushobject(L, ci->base + (n - 1)); - lua_unlock(L); - return name; -} - - -LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { - CallInfo *ci = L->base_ci + ar->i_ci; - const char *name = findlocal(L, ci, n); - lua_lock(L); - if (name) - setobjs2s(L, ci->base + (n - 1), L->top - 1); - L->top--; /* pop value */ - lua_unlock(L); - return name; -} - - -static void funcinfo (lua_Debug *ar, Closure *cl) { - if (cl->c.isC) { - ar->source = "=[C]"; - ar->linedefined = -1; - ar->lastlinedefined = -1; - ar->what = "C"; - } - else { - ar->source = getstr(cl->l.p->source); - ar->linedefined = cl->l.p->linedefined; - ar->lastlinedefined = cl->l.p->lastlinedefined; - ar->what = (ar->linedefined == 0) ? "main" : "Lua"; - } - luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); -} - - -static void info_tailcall (lua_Debug *ar) { - ar->name = ar->namewhat = ""; - ar->what = "tail"; - ar->lastlinedefined = ar->linedefined = ar->currentline = -1; - ar->source = "=(tail call)"; - luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); - ar->nups = 0; -} - - -static void collectvalidlines (lua_State *L, Closure *f) { - if (f == NULL || f->c.isC) { - setnilvalue(L->top); - } - else { - Table *t = luaH_new(L, 0, 0); - int *lineinfo = f->l.p->lineinfo; - int i; - for (i=0; il.p->sizelineinfo; i++) - setbvalue(luaH_setnum(L, t, lineinfo[i]), 1); - sethvalue(L, L->top, t); - } - incr_top(L); -} - - -static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, - Closure *f, CallInfo *ci) { - int status = 1; - if (f == NULL) { - info_tailcall(ar); - return status; - } - for (; *what; what++) { - switch (*what) { - case 'S': { - funcinfo(ar, f); - break; - } - case 'l': { - ar->currentline = (ci) ? currentline(L, ci) : -1; - break; - } - case 'u': { - ar->nups = f->c.nupvalues; - break; - } - case 'n': { - ar->namewhat = (ci) ? getfuncname(L, ci, &ar->name) : NULL; - if (ar->namewhat == NULL) { - ar->namewhat = ""; /* not found */ - ar->name = NULL; - } - break; - } - case 'L': - case 'f': /* handled by lua_getinfo */ - break; - default: status = 0; /* invalid option */ - } - } - return status; -} - - -LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { - int status; - Closure *f = NULL; - CallInfo *ci = NULL; - lua_lock(L); - if (*what == '>') { - StkId func = L->top - 1; - luai_apicheck(L, ttisfunction(func)); - what++; /* skip the '>' */ - f = clvalue(func); - L->top--; /* pop function */ - } - else if (ar->i_ci != 0) { /* no tail call? */ - ci = L->base_ci + ar->i_ci; - lua_assert(ttisfunction(ci->func)); - f = clvalue(ci->func); - } - status = auxgetinfo(L, what, ar, f, ci); - if (strchr(what, 'f')) { - if (f == NULL) setnilvalue(L->top); - else setclvalue(L, L->top, f); - incr_top(L); - } - if (strchr(what, 'L')) - collectvalidlines(L, f); - lua_unlock(L); - return status; -} - - -/* -** {====================================================== -** Symbolic Execution and code checker -** ======================================================= -*/ - -#define check(x) if (!(x)) return 0; - -#define checkjump(pt,pc) check(0 <= pc && pc < pt->sizecode) - -#define checkreg(pt,reg) check((reg) < (pt)->maxstacksize) - - - -static int precheck (const Proto *pt) { - check(pt->maxstacksize <= MAXSTACK); - check(pt->numparams+(pt->is_vararg & VARARG_HASARG) <= pt->maxstacksize); - check(!(pt->is_vararg & VARARG_NEEDSARG) || - (pt->is_vararg & VARARG_HASARG)); - check(pt->sizeupvalues <= pt->nups); - check(pt->sizelineinfo == pt->sizecode || pt->sizelineinfo == 0); - check(pt->sizecode > 0 && GET_OPCODE(pt->code[pt->sizecode-1]) == OP_RETURN); - return 1; -} - - -#define checkopenop(pt,pc) luaG_checkopenop((pt)->code[(pc)+1]) - -int luaG_checkopenop (Instruction i) { - switch (GET_OPCODE(i)) { - case OP_CALL: - case OP_TAILCALL: - case OP_RETURN: - case OP_SETLIST: { - check(GETARG_B(i) == 0); - return 1; - } - default: return 0; /* invalid instruction after an open call */ - } -} - - -static int checkArgMode (const Proto *pt, int r, enum OpArgMask mode) { - switch (mode) { - case OpArgN: check(r == 0); break; - case OpArgU: break; - case OpArgR: checkreg(pt, r); break; - case OpArgK: - check(ISK(r) ? INDEXK(r) < pt->sizek : r < pt->maxstacksize); - break; - } - return 1; -} - - -static Instruction symbexec (const Proto *pt, int lastpc, int reg) { - int pc; - int last; /* stores position of last instruction that changed `reg' */ - last = pt->sizecode-1; /* points to final return (a `neutral' instruction) */ - check(precheck(pt)); - for (pc = 0; pc < lastpc; pc++) { - Instruction i = pt->code[pc]; - OpCode op = GET_OPCODE(i); - int a = GETARG_A(i); - int b = 0; - int c = 0; - check(op < NUM_OPCODES); - checkreg(pt, a); - switch (getOpMode(op)) { - case iABC: { - b = GETARG_B(i); - c = GETARG_C(i); - check(checkArgMode(pt, b, getBMode(op))); - check(checkArgMode(pt, c, getCMode(op))); - break; - } - case iABx: { - b = GETARG_Bx(i); - if (getBMode(op) == OpArgK) check(b < pt->sizek); - break; - } - case iAsBx: { - b = GETARG_sBx(i); - if (getBMode(op) == OpArgR) { - int dest = pc+1+b; - check(0 <= dest && dest < pt->sizecode); - if (dest > 0) { - int j; - /* check that it does not jump to a setlist count; this - is tricky, because the count from a previous setlist may - have the same value of an invalid setlist; so, we must - go all the way back to the first of them (if any) */ - for (j = 0; j < dest; j++) { - Instruction d = pt->code[dest-1-j]; - if (!(GET_OPCODE(d) == OP_SETLIST && GETARG_C(d) == 0)) break; - } - /* if 'j' is even, previous value is not a setlist (even if - it looks like one) */ - check((j&1) == 0); - } - } - break; - } - } - if (testAMode(op)) { - if (a == reg) last = pc; /* change register `a' */ - } - if (testTMode(op)) { - check(pc+2 < pt->sizecode); /* check skip */ - check(GET_OPCODE(pt->code[pc+1]) == OP_JMP); - } - switch (op) { - case OP_LOADBOOL: { - if (c == 1) { /* does it jump? */ - check(pc+2 < pt->sizecode); /* check its jump */ - check(GET_OPCODE(pt->code[pc+1]) != OP_SETLIST || - GETARG_C(pt->code[pc+1]) != 0); - } - break; - } - case OP_LOADNIL: { - if (a <= reg && reg <= b) - last = pc; /* set registers from `a' to `b' */ - break; - } - case OP_GETUPVAL: - case OP_SETUPVAL: { - check(b < pt->nups); - break; - } - case OP_GETGLOBAL: - case OP_SETGLOBAL: { - check(ttisstring(&pt->k[b])); - break; - } - case OP_SELF: { - checkreg(pt, a+1); - if (reg == a+1) last = pc; - break; - } - case OP_CONCAT: { - check(b < c); /* at least two operands */ - break; - } - case OP_TFORLOOP: { - check(c >= 1); /* at least one result (control variable) */ - checkreg(pt, a+2+c); /* space for results */ - if (reg >= a+2) last = pc; /* affect all regs above its base */ - break; - } - case OP_FORLOOP: - case OP_FORPREP: - checkreg(pt, a+3); - /* go through */ - case OP_JMP: { - int dest = pc+1+b; - /* not full check and jump is forward and do not skip `lastpc'? */ - if (reg != NO_REG && pc < dest && dest <= lastpc) - pc += b; /* do the jump */ - break; - } - case OP_CALL: - case OP_TAILCALL: { - if (b != 0) { - checkreg(pt, a+b-1); - } - c--; /* c = num. returns */ - if (c == LUA_MULTRET) { - check(checkopenop(pt, pc)); - } - else if (c != 0) - checkreg(pt, a+c-1); - if (reg >= a) last = pc; /* affect all registers above base */ - break; - } - case OP_RETURN: { - b--; /* b = num. returns */ - if (b > 0) checkreg(pt, a+b-1); - break; - } - case OP_SETLIST: { - if (b > 0) checkreg(pt, a + b); - if (c == 0) { - pc++; - check(pc < pt->sizecode - 1); - } - break; - } - case OP_CLOSURE: { - int nup, j; - check(b < pt->sizep); - nup = pt->p[b]->nups; - check(pc + nup < pt->sizecode); - for (j = 1; j <= nup; j++) { - OpCode op1 = GET_OPCODE(pt->code[pc + j]); - check(op1 == OP_GETUPVAL || op1 == OP_MOVE); - } - if (reg != NO_REG) /* tracing? */ - pc += nup; /* do not 'execute' these pseudo-instructions */ - break; - } - case OP_VARARG: { - check((pt->is_vararg & VARARG_ISVARARG) && - !(pt->is_vararg & VARARG_NEEDSARG)); - b--; - if (b == LUA_MULTRET) check(checkopenop(pt, pc)); - checkreg(pt, a+b-1); - break; - } - default: break; - } - } - return pt->code[last]; -} - -#undef check -#undef checkjump -#undef checkreg - -/* }====================================================== */ - - -int luaG_checkcode (const Proto *pt) { - return (symbexec(pt, pt->sizecode, NO_REG) != 0); -} - - -static const char *kname (Proto *p, int c) { - if (ISK(c) && ttisstring(&p->k[INDEXK(c)])) - return svalue(&p->k[INDEXK(c)]); - else - return "?"; -} - - -static const char *getobjname (lua_State *L, CallInfo *ci, int stackpos, - const char **name) { - if (isLua(ci)) { /* a Lua function? */ - Proto *p = ci_func(ci)->l.p; - int pc = currentpc(L, ci); - Instruction i; - *name = luaF_getlocalname(p, stackpos+1, pc); - if (*name) /* is a local? */ - return "local"; - i = symbexec(p, pc, stackpos); /* try symbolic execution */ - lua_assert(pc != -1); - switch (GET_OPCODE(i)) { - case OP_GETGLOBAL: { - int g = GETARG_Bx(i); /* global index */ - lua_assert(ttisstring(&p->k[g])); - *name = svalue(&p->k[g]); - return "global"; - } - case OP_MOVE: { - int a = GETARG_A(i); - int b = GETARG_B(i); /* move from `b' to `a' */ - if (b < a) - return getobjname(L, ci, b, name); /* get name for `b' */ - break; - } - case OP_GETTABLE: { - int k = GETARG_C(i); /* key index */ - *name = kname(p, k); - return "field"; - } - case OP_GETUPVAL: { - int u = GETARG_B(i); /* upvalue index */ - *name = p->upvalues ? getstr(p->upvalues[u]) : "?"; - return "upvalue"; - } - case OP_SELF: { - int k = GETARG_C(i); /* key index */ - *name = kname(p, k); - return "method"; - } - default: break; - } - } - return NULL; /* no useful name found */ -} - - -static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { - Instruction i; - if ((isLua(ci) && ci->tailcalls > 0) || !isLua(ci - 1)) - return NULL; /* calling function is not Lua (or is unknown) */ - ci--; /* calling function */ - i = ci_func(ci)->l.p->code[currentpc(L, ci)]; - if (GET_OPCODE(i) == OP_CALL || GET_OPCODE(i) == OP_TAILCALL || - GET_OPCODE(i) == OP_TFORLOOP) - return getobjname(L, ci, GETARG_A(i), name); - else - return NULL; /* no useful name can be found */ -} - - -/* only ANSI way to check whether a pointer points to an array */ -static int isinstack (CallInfo *ci, const TValue *o) { - StkId p; - for (p = ci->base; p < ci->top; p++) - if (o == p) return 1; - return 0; -} - - -void luaG_typeerror (lua_State *L, const TValue *o, const char *op) { - const char *name = NULL; - const char *t = luaT_typenames[ttype(o)]; - const char *kind = (isinstack(L->ci, o)) ? - getobjname(L, L->ci, cast_int(o - L->base), &name) : - NULL; - if (kind) - luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)", - op, kind, name, t); - else - luaG_runerror(L, "attempt to %s a %s value", op, t); -} - - -void luaG_concaterror (lua_State *L, StkId p1, StkId p2) { - if (ttisstring(p1) || ttisnumber(p1)) p1 = p2; - lua_assert(!ttisstring(p1) && !ttisnumber(p1)); - luaG_typeerror(L, p1, "concatenate"); -} - - -void luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) { - TValue temp; - if (luaV_tonumber(p1, &temp) == NULL) - p2 = p1; /* first operand is wrong */ - luaG_typeerror(L, p2, "perform arithmetic on"); -} - - -int luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { - const char *t1 = luaT_typenames[ttype(p1)]; - const char *t2 = luaT_typenames[ttype(p2)]; - if (t1[2] == t2[2]) - luaG_runerror(L, "attempt to compare two %s values", t1); - else - luaG_runerror(L, "attempt to compare %s with %s", t1, t2); - return 0; -} - - -static void addinfo (lua_State *L, const char *msg) { - CallInfo *ci = L->ci; - if (isLua(ci)) { /* is Lua code? */ - char buff[LUA_IDSIZE]; /* add file:line information */ - int line = currentline(L, ci); - luaO_chunkid(buff, getstr(getluaproto(ci)->source), LUA_IDSIZE); - luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); - } -} - - -void luaG_errormsg (lua_State *L) { - if (L->errfunc != 0) { /* is there an error handling function? */ - StkId errfunc = restorestack(L, L->errfunc); - if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR); - setobjs2s(L, L->top, L->top - 1); /* move argument */ - setobjs2s(L, L->top - 1, errfunc); /* push function */ - incr_top(L); - luaD_call(L, L->top - 2, 1); /* call it */ - } - luaD_throw(L, LUA_ERRRUN); -} - - -void luaG_runerror (lua_State *L, const char *fmt, ...) { - va_list argp; - va_start(argp, fmt); - addinfo(L, luaO_pushvfstring(L, fmt, argp)); - va_end(argp); - luaG_errormsg(L); -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/ldebug.h b/desmume/src/windows/lua/lua-5.1.4/src/ldebug.h deleted file mode 100644 index ba28a9724..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/ldebug.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -** $Id: ldebug.h,v 2.3.1.1 2007/12/27 13:02:25 roberto Exp $ -** Auxiliary functions from Debug Interface module -** See Copyright Notice in lua.h -*/ - -#ifndef ldebug_h -#define ldebug_h - - -#include "lstate.h" - - -#define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1) - -#define getline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0) - -#define resethookcount(L) (L->hookcount = L->basehookcount) - - -LUAI_FUNC void luaG_typeerror (lua_State *L, const TValue *o, - const char *opname); -LUAI_FUNC void luaG_concaterror (lua_State *L, StkId p1, StkId p2); -LUAI_FUNC void luaG_aritherror (lua_State *L, const TValue *p1, - const TValue *p2); -LUAI_FUNC int luaG_ordererror (lua_State *L, const TValue *p1, - const TValue *p2); -LUAI_FUNC void luaG_runerror (lua_State *L, const char *fmt, ...); -LUAI_FUNC void luaG_errormsg (lua_State *L); -LUAI_FUNC int luaG_checkcode (const Proto *pt); -LUAI_FUNC int luaG_checkopenop (Instruction i); - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/ldo.c b/desmume/src/windows/lua/lua-5.1.4/src/ldo.c deleted file mode 100644 index 8de05f728..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/ldo.c +++ /dev/null @@ -1,518 +0,0 @@ -/* -** $Id: ldo.c,v 2.38.1.3 2008/01/18 22:31:22 roberto Exp $ -** Stack and Call structure of Lua -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include - -#define ldo_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lgc.h" -#include "lmem.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lparser.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" -#include "lundump.h" -#include "lvm.h" -#include "lzio.h" - - - - -/* -** {====================================================== -** Error-recovery functions -** ======================================================= -*/ - - -/* chain list of long jump buffers */ -struct lua_longjmp { - struct lua_longjmp *previous; - luai_jmpbuf b; - volatile int status; /* error code */ -}; - - -void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) { - switch (errcode) { - case LUA_ERRMEM: { - setsvalue2s(L, oldtop, luaS_newliteral(L, MEMERRMSG)); - break; - } - case LUA_ERRERR: { - setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); - break; - } - case LUA_ERRSYNTAX: - case LUA_ERRRUN: { - setobjs2s(L, oldtop, L->top - 1); /* error message on current top */ - break; - } - } - L->top = oldtop + 1; -} - - -static void restore_stack_limit (lua_State *L) { - lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1); - if (L->size_ci > LUAI_MAXCALLS) { /* there was an overflow? */ - int inuse = cast_int(L->ci - L->base_ci); - if (inuse + 1 < LUAI_MAXCALLS) /* can `undo' overflow? */ - luaD_reallocCI(L, LUAI_MAXCALLS); - } -} - - -static void resetstack (lua_State *L, int status) { - L->ci = L->base_ci; - L->base = L->ci->base; - luaF_close(L, L->base); /* close eventual pending closures */ - luaD_seterrorobj(L, status, L->base); - L->nCcalls = L->baseCcalls; - L->allowhook = 1; - restore_stack_limit(L); - L->errfunc = 0; - L->errorJmp = NULL; -} - - -void luaD_throw (lua_State *L, int errcode) { - if (L->errorJmp) { - L->errorJmp->status = errcode; - LUAI_THROW(L, L->errorJmp); - } - else { - L->status = cast_byte(errcode); - if (G(L)->panic) { - resetstack(L, errcode); - lua_unlock(L); - G(L)->panic(L); - } - exit(EXIT_FAILURE); - } -} - - -int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { - struct lua_longjmp lj; - lj.status = 0; - lj.previous = L->errorJmp; /* chain new error handler */ - L->errorJmp = &lj; - LUAI_TRY(L, &lj, - (*f)(L, ud); - ); - L->errorJmp = lj.previous; /* restore old error handler */ - return lj.status; -} - -/* }====================================================== */ - - -static void correctstack (lua_State *L, TValue *oldstack) { - CallInfo *ci; - GCObject *up; - L->top = (L->top - oldstack) + L->stack; - for (up = L->openupval; up != NULL; up = up->gch.next) - gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack; - for (ci = L->base_ci; ci <= L->ci; ci++) { - ci->top = (ci->top - oldstack) + L->stack; - ci->base = (ci->base - oldstack) + L->stack; - ci->func = (ci->func - oldstack) + L->stack; - } - L->base = (L->base - oldstack) + L->stack; -} - - -void luaD_reallocstack (lua_State *L, int newsize) { - TValue *oldstack = L->stack; - int realsize = newsize + 1 + EXTRA_STACK; - lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1); - luaM_reallocvector(L, L->stack, L->stacksize, realsize, TValue); - L->stacksize = realsize; - L->stack_last = L->stack+newsize; - correctstack(L, oldstack); -} - - -void luaD_reallocCI (lua_State *L, int newsize) { - CallInfo *oldci = L->base_ci; - luaM_reallocvector(L, L->base_ci, L->size_ci, newsize, CallInfo); - L->size_ci = newsize; - L->ci = (L->ci - oldci) + L->base_ci; - L->end_ci = L->base_ci + L->size_ci - 1; -} - - -void luaD_growstack (lua_State *L, int n) { - if (n <= L->stacksize) /* double size is enough? */ - luaD_reallocstack(L, 2*L->stacksize); - else - luaD_reallocstack(L, L->stacksize + n); -} - - -static CallInfo *growCI (lua_State *L) { - if (L->size_ci > LUAI_MAXCALLS) /* overflow while handling overflow? */ - luaD_throw(L, LUA_ERRERR); - else { - luaD_reallocCI(L, 2*L->size_ci); - if (L->size_ci > LUAI_MAXCALLS) - luaG_runerror(L, "stack overflow"); - } - return ++L->ci; -} - - -void luaD_callhook (lua_State *L, int event, int line) { - lua_Hook hook = L->hook; - if (hook && L->allowhook) { - ptrdiff_t top = savestack(L, L->top); - ptrdiff_t ci_top = savestack(L, L->ci->top); - lua_Debug ar; - ar.event = event; - ar.currentline = line; - if (event == LUA_HOOKTAILRET) - ar.i_ci = 0; /* tail call; no debug information about it */ - else - ar.i_ci = cast_int(L->ci - L->base_ci); - luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ - L->ci->top = L->top + LUA_MINSTACK; - lua_assert(L->ci->top <= L->stack_last); - L->allowhook = 0; /* cannot call hooks inside a hook */ - lua_unlock(L); - (*hook)(L, &ar); - lua_lock(L); - lua_assert(!L->allowhook); - L->allowhook = 1; - L->ci->top = restorestack(L, ci_top); - L->top = restorestack(L, top); - } -} - - -static StkId adjust_varargs (lua_State *L, Proto *p, int actual) { - int i; - int nfixargs = p->numparams; - Table *htab = NULL; - StkId base, fixed; - for (; actual < nfixargs; ++actual) - setnilvalue(L->top++); -#if defined(LUA_COMPAT_VARARG) - if (p->is_vararg & VARARG_NEEDSARG) { /* compat. with old-style vararg? */ - int nvar = actual - nfixargs; /* number of extra arguments */ - lua_assert(p->is_vararg & VARARG_HASARG); - luaC_checkGC(L); - htab = luaH_new(L, nvar, 1); /* create `arg' table */ - for (i=0; itop - nvar + i); - /* store counter in field `n' */ - setnvalue(luaH_setstr(L, htab, luaS_newliteral(L, "n")), cast_num(nvar)); - } -#endif - /* move fixed parameters to final position */ - fixed = L->top - actual; /* first fixed argument */ - base = L->top; /* final position of first argument */ - for (i=0; itop++, fixed+i); - setnilvalue(fixed+i); - } - /* add `arg' parameter */ - if (htab) { - sethvalue(L, L->top++, htab); - lua_assert(iswhite(obj2gco(htab))); - } - return base; -} - - -static StkId tryfuncTM (lua_State *L, StkId func) { - const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL); - StkId p; - ptrdiff_t funcr = savestack(L, func); - if (!ttisfunction(tm)) - luaG_typeerror(L, func, "call"); - /* Open a hole inside the stack at `func' */ - for (p = L->top; p > func; p--) setobjs2s(L, p, p-1); - incr_top(L); - func = restorestack(L, funcr); /* previous call may change stack */ - setobj2s(L, func, tm); /* tag method is the new function to be called */ - return func; -} - - - -#define inc_ci(L) \ - ((L->ci == L->end_ci) ? growCI(L) : \ - (condhardstacktests(luaD_reallocCI(L, L->size_ci)), ++L->ci)) - - -int luaD_precall (lua_State *L, StkId func, int nresults) { - LClosure *cl; - ptrdiff_t funcr; - if (!ttisfunction(func)) /* `func' is not a function? */ - func = tryfuncTM(L, func); /* check the `function' tag method */ - funcr = savestack(L, func); - cl = &clvalue(func)->l; - L->ci->savedpc = L->savedpc; - if (!cl->isC) { /* Lua function? prepare its call */ - CallInfo *ci; - StkId st, base; - Proto *p = cl->p; - luaD_checkstack(L, p->maxstacksize); - func = restorestack(L, funcr); - if (!p->is_vararg) { /* no varargs? */ - base = func + 1; - if (L->top > base + p->numparams) - L->top = base + p->numparams; - } - else { /* vararg function */ - int nargs = cast_int(L->top - func) - 1; - base = adjust_varargs(L, p, nargs); - func = restorestack(L, funcr); /* previous call may change the stack */ - } - ci = inc_ci(L); /* now `enter' new function */ - ci->func = func; - L->base = ci->base = base; - ci->top = L->base + p->maxstacksize; - lua_assert(ci->top <= L->stack_last); - L->savedpc = p->code; /* starting point */ - ci->tailcalls = 0; - ci->nresults = nresults; - for (st = L->top; st < ci->top; st++) - setnilvalue(st); - L->top = ci->top; - if (L->hookmask & LUA_MASKCALL) { - L->savedpc++; /* hooks assume 'pc' is already incremented */ - luaD_callhook(L, LUA_HOOKCALL, -1); - L->savedpc--; /* correct 'pc' */ - } - return PCRLUA; - } - else { /* if is a C function, call it */ - CallInfo *ci; - int n; - luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ - ci = inc_ci(L); /* now `enter' new function */ - ci->func = restorestack(L, funcr); - L->base = ci->base = ci->func + 1; - ci->top = L->top + LUA_MINSTACK; - lua_assert(ci->top <= L->stack_last); - ci->nresults = nresults; - if (L->hookmask & LUA_MASKCALL) - luaD_callhook(L, LUA_HOOKCALL, -1); - lua_unlock(L); - n = (*curr_func(L)->c.f)(L); /* do the actual call */ - lua_lock(L); - if (n < 0) /* yielding? */ - return PCRYIELD; - else { - luaD_poscall(L, L->top - n); - return PCRC; - } - } -} - - -static StkId callrethooks (lua_State *L, StkId firstResult) { - ptrdiff_t fr = savestack(L, firstResult); /* next call may change stack */ - luaD_callhook(L, LUA_HOOKRET, -1); - if (f_isLua(L->ci)) { /* Lua function? */ - while ((L->hookmask & LUA_MASKRET) && L->ci->tailcalls--) /* tail calls */ - luaD_callhook(L, LUA_HOOKTAILRET, -1); - } - return restorestack(L, fr); -} - - -int luaD_poscall (lua_State *L, StkId firstResult) { - StkId res; - int wanted, i; - CallInfo *ci; - if (L->hookmask & LUA_MASKRET) - firstResult = callrethooks(L, firstResult); - ci = L->ci--; - res = ci->func; /* res == final position of 1st result */ - wanted = ci->nresults; - L->base = (ci - 1)->base; /* restore base */ - L->savedpc = (ci - 1)->savedpc; /* restore savedpc */ - /* move results to correct place */ - for (i = wanted; i != 0 && firstResult < L->top; i--) - setobjs2s(L, res++, firstResult++); - while (i-- > 0) - setnilvalue(res++); - L->top = res; - return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */ -} - - -/* -** Call a function (C or Lua). The function to be called is at *func. -** The arguments are on the stack, right after the function. -** When returns, all the results are on the stack, starting at the original -** function position. -*/ -void luaD_call (lua_State *L, StkId func, int nResults) { - if (++L->nCcalls >= LUAI_MAXCCALLS) { - if (L->nCcalls == LUAI_MAXCCALLS) - luaG_runerror(L, "C stack overflow"); - else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) - luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ - } - if (luaD_precall(L, func, nResults) == PCRLUA) /* is a Lua function? */ - luaV_execute(L, 1); /* call it */ - L->nCcalls--; - luaC_checkGC(L); -} - - -static void resume (lua_State *L, void *ud) { - StkId firstArg = cast(StkId, ud); - CallInfo *ci = L->ci; - if (L->status == 0) { /* start coroutine? */ - lua_assert(ci == L->base_ci && firstArg > L->base); - if (luaD_precall(L, firstArg - 1, LUA_MULTRET) != PCRLUA) - return; - } - else { /* resuming from previous yield */ - lua_assert(L->status == LUA_YIELD); - L->status = 0; - if (!f_isLua(ci)) { /* `common' yield? */ - /* finish interrupted execution of `OP_CALL' */ - lua_assert(GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_CALL || - GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_TAILCALL); - if (luaD_poscall(L, firstArg)) /* complete it... */ - L->top = L->ci->top; /* and correct top if not multiple results */ - } - else /* yielded inside a hook: just continue its execution */ - L->base = L->ci->base; - } - luaV_execute(L, cast_int(L->ci - L->base_ci)); -} - - -static int resume_error (lua_State *L, const char *msg) { - L->top = L->ci->base; - setsvalue2s(L, L->top, luaS_new(L, msg)); - incr_top(L); - lua_unlock(L); - return LUA_ERRRUN; -} - - -LUA_API int lua_resume (lua_State *L, int nargs) { - int status; - lua_lock(L); - if (L->status != LUA_YIELD && (L->status != 0 || L->ci != L->base_ci)) - return resume_error(L, "cannot resume non-suspended coroutine"); - if (L->nCcalls >= LUAI_MAXCCALLS) - return resume_error(L, "C stack overflow"); - luai_userstateresume(L, nargs); - lua_assert(L->errfunc == 0); - L->baseCcalls = ++L->nCcalls; - status = luaD_rawrunprotected(L, resume, L->top - nargs); - if (status != 0) { /* error? */ - L->status = cast_byte(status); /* mark thread as `dead' */ - luaD_seterrorobj(L, status, L->top); - L->ci->top = L->top; - } - else { - lua_assert(L->nCcalls == L->baseCcalls); - status = L->status; - } - --L->nCcalls; - lua_unlock(L); - return status; -} - - -LUA_API int lua_yield (lua_State *L, int nresults) { - luai_userstateyield(L, nresults); - lua_lock(L); - if (L->nCcalls > L->baseCcalls) - luaG_runerror(L, "attempt to yield across metamethod/C-call boundary"); - L->base = L->top - nresults; /* protect stack slots below */ - L->status = LUA_YIELD; - lua_unlock(L); - return -1; -} - - -int luaD_pcall (lua_State *L, Pfunc func, void *u, - ptrdiff_t old_top, ptrdiff_t ef) { - int status; - unsigned short oldnCcalls = L->nCcalls; - ptrdiff_t old_ci = saveci(L, L->ci); - lu_byte old_allowhooks = L->allowhook; - ptrdiff_t old_errfunc = L->errfunc; - L->errfunc = ef; - status = luaD_rawrunprotected(L, func, u); - if (status != 0) { /* an error occurred? */ - StkId oldtop = restorestack(L, old_top); - luaF_close(L, oldtop); /* close eventual pending closures */ - luaD_seterrorobj(L, status, oldtop); - L->nCcalls = oldnCcalls; - L->ci = restoreci(L, old_ci); - L->base = L->ci->base; - L->savedpc = L->ci->savedpc; - L->allowhook = old_allowhooks; - restore_stack_limit(L); - } - L->errfunc = old_errfunc; - return status; -} - - - -/* -** Execute a protected parser. -*/ -struct SParser { /* data to `f_parser' */ - ZIO *z; - Mbuffer buff; /* buffer to be used by the scanner */ - const char *name; -}; - -static void f_parser (lua_State *L, void *ud) { - int i; - Proto *tf; - Closure *cl; - struct SParser *p = cast(struct SParser *, ud); - int c = luaZ_lookahead(p->z); - luaC_checkGC(L); - tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z, - &p->buff, p->name); - cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); - cl->l.p = tf; - for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ - cl->l.upvals[i] = luaF_newupval(L); - setclvalue(L, L->top, cl); - incr_top(L); -} - - -int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) { - struct SParser p; - int status; - p.z = z; p.name = name; - luaZ_initbuffer(L, &p.buff); - status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc); - luaZ_freebuffer(L, &p.buff); - return status; -} - - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/ldo.h b/desmume/src/windows/lua/lua-5.1.4/src/ldo.h deleted file mode 100644 index 98fddac59..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/ldo.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -** $Id: ldo.h,v 2.7.1.1 2007/12/27 13:02:25 roberto Exp $ -** Stack and Call structure of Lua -** See Copyright Notice in lua.h -*/ - -#ifndef ldo_h -#define ldo_h - - -#include "lobject.h" -#include "lstate.h" -#include "lzio.h" - - -#define luaD_checkstack(L,n) \ - if ((char *)L->stack_last - (char *)L->top <= (n)*(int)sizeof(TValue)) \ - luaD_growstack(L, n); \ - else condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); - - -#define incr_top(L) {luaD_checkstack(L,1); L->top++;} - -#define savestack(L,p) ((char *)(p) - (char *)L->stack) -#define restorestack(L,n) ((TValue *)((char *)L->stack + (n))) - -#define saveci(L,p) ((char *)(p) - (char *)L->base_ci) -#define restoreci(L,n) ((CallInfo *)((char *)L->base_ci + (n))) - - -/* results from luaD_precall */ -#define PCRLUA 0 /* initiated a call to a Lua function */ -#define PCRC 1 /* did a call to a C function */ -#define PCRYIELD 2 /* C funtion yielded */ - - -/* type of protected functions, to be ran by `runprotected' */ -typedef void (*Pfunc) (lua_State *L, void *ud); - -LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name); -LUAI_FUNC void luaD_callhook (lua_State *L, int event, int line); -LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults); -LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); -LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, - ptrdiff_t oldtop, ptrdiff_t ef); -LUAI_FUNC int luaD_poscall (lua_State *L, StkId firstResult); -LUAI_FUNC void luaD_reallocCI (lua_State *L, int newsize); -LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize); -LUAI_FUNC void luaD_growstack (lua_State *L, int n); - -LUAI_FUNC void luaD_throw (lua_State *L, int errcode); -LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); - -LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop); - -#endif - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/ldump.c b/desmume/src/windows/lua/lua-5.1.4/src/ldump.c deleted file mode 100644 index c9d3d4870..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/ldump.c +++ /dev/null @@ -1,164 +0,0 @@ -/* -** $Id: ldump.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $ -** save precompiled Lua chunks -** See Copyright Notice in lua.h -*/ - -#include - -#define ldump_c -#define LUA_CORE - -#include "lua.h" - -#include "lobject.h" -#include "lstate.h" -#include "lundump.h" - -typedef struct { - lua_State* L; - lua_Writer writer; - void* data; - int strip; - int status; -} DumpState; - -#define DumpMem(b,n,size,D) DumpBlock(b,(n)*(size),D) -#define DumpVar(x,D) DumpMem(&x,1,sizeof(x),D) - -static void DumpBlock(const void* b, size_t size, DumpState* D) -{ - if (D->status==0) - { - lua_unlock(D->L); - D->status=(*D->writer)(D->L,b,size,D->data); - lua_lock(D->L); - } -} - -static void DumpChar(int y, DumpState* D) -{ - char x=(char)y; - DumpVar(x,D); -} - -static void DumpInt(int x, DumpState* D) -{ - DumpVar(x,D); -} - -static void DumpNumber(lua_Number x, DumpState* D) -{ - DumpVar(x,D); -} - -static void DumpVector(const void* b, int n, size_t size, DumpState* D) -{ - DumpInt(n,D); - DumpMem(b,n,size,D); -} - -static void DumpString(const TString* s, DumpState* D) -{ - if (s==NULL || getstr(s)==NULL) - { - size_t size=0; - DumpVar(size,D); - } - else - { - size_t size=s->tsv.len+1; /* include trailing '\0' */ - DumpVar(size,D); - DumpBlock(getstr(s),size,D); - } -} - -#define DumpCode(f,D) DumpVector(f->code,f->sizecode,sizeof(Instruction),D) - -static void DumpFunction(const Proto* f, const TString* p, DumpState* D); - -static void DumpConstants(const Proto* f, DumpState* D) -{ - int i,n=f->sizek; - DumpInt(n,D); - for (i=0; ik[i]; - DumpChar(ttype(o),D); - switch (ttype(o)) - { - case LUA_TNIL: - break; - case LUA_TBOOLEAN: - DumpChar(bvalue(o),D); - break; - case LUA_TNUMBER: - DumpNumber(nvalue(o),D); - break; - case LUA_TSTRING: - DumpString(rawtsvalue(o),D); - break; - default: - lua_assert(0); /* cannot happen */ - break; - } - } - n=f->sizep; - DumpInt(n,D); - for (i=0; ip[i],f->source,D); -} - -static void DumpDebug(const Proto* f, DumpState* D) -{ - int i,n; - n= (D->strip) ? 0 : f->sizelineinfo; - DumpVector(f->lineinfo,n,sizeof(int),D); - n= (D->strip) ? 0 : f->sizelocvars; - DumpInt(n,D); - for (i=0; ilocvars[i].varname,D); - DumpInt(f->locvars[i].startpc,D); - DumpInt(f->locvars[i].endpc,D); - } - n= (D->strip) ? 0 : f->sizeupvalues; - DumpInt(n,D); - for (i=0; iupvalues[i],D); -} - -static void DumpFunction(const Proto* f, const TString* p, DumpState* D) -{ - DumpString((f->source==p || D->strip) ? NULL : f->source,D); - DumpInt(f->linedefined,D); - DumpInt(f->lastlinedefined,D); - DumpChar(f->nups,D); - DumpChar(f->numparams,D); - DumpChar(f->is_vararg,D); - DumpChar(f->maxstacksize,D); - DumpCode(f,D); - DumpConstants(f,D); - DumpDebug(f,D); -} - -static void DumpHeader(DumpState* D) -{ - char h[LUAC_HEADERSIZE]; - luaU_header(h); - DumpBlock(h,LUAC_HEADERSIZE,D); -} - -/* -** dump Lua function as precompiled chunk -*/ -int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip) -{ - DumpState D; - D.L=L; - D.writer=w; - D.data=data; - D.strip=strip; - D.status=0; - DumpHeader(&D); - DumpFunction(f,NULL,&D); - return D.status; -} diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lfunc.c b/desmume/src/windows/lua/lua-5.1.4/src/lfunc.c deleted file mode 100644 index 813e88f58..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lfunc.c +++ /dev/null @@ -1,174 +0,0 @@ -/* -** $Id: lfunc.c,v 2.12.1.2 2007/12/28 14:58:43 roberto Exp $ -** Auxiliary functions to manipulate prototypes and closures -** See Copyright Notice in lua.h -*/ - - -#include - -#define lfunc_c -#define LUA_CORE - -#include "lua.h" - -#include "lfunc.h" -#include "lgc.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" - - - -Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e) { - Closure *c = cast(Closure *, luaM_malloc(L, sizeCclosure(nelems))); - luaC_link(L, obj2gco(c), LUA_TFUNCTION); - c->c.isC = 1; - c->c.env = e; - c->c.nupvalues = cast_byte(nelems); - return c; -} - - -Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e) { - Closure *c = cast(Closure *, luaM_malloc(L, sizeLclosure(nelems))); - luaC_link(L, obj2gco(c), LUA_TFUNCTION); - c->l.isC = 0; - c->l.env = e; - c->l.nupvalues = cast_byte(nelems); - while (nelems--) c->l.upvals[nelems] = NULL; - return c; -} - - -UpVal *luaF_newupval (lua_State *L) { - UpVal *uv = luaM_new(L, UpVal); - luaC_link(L, obj2gco(uv), LUA_TUPVAL); - uv->v = &uv->u.value; - setnilvalue(uv->v); - return uv; -} - - -UpVal *luaF_findupval (lua_State *L, StkId level) { - global_State *g = G(L); - GCObject **pp = &L->openupval; - UpVal *p; - UpVal *uv; - while (*pp != NULL && (p = ngcotouv(*pp))->v >= level) { - lua_assert(p->v != &p->u.value); - if (p->v == level) { /* found a corresponding upvalue? */ - if (isdead(g, obj2gco(p))) /* is it dead? */ - changewhite(obj2gco(p)); /* ressurect it */ - return p; - } - pp = &p->next; - } - uv = luaM_new(L, UpVal); /* not found: create a new one */ - uv->tt = LUA_TUPVAL; - uv->marked = luaC_white(g); - uv->v = level; /* current value lives in the stack */ - uv->next = *pp; /* chain it in the proper position */ - *pp = obj2gco(uv); - uv->u.l.prev = &g->uvhead; /* double link it in `uvhead' list */ - uv->u.l.next = g->uvhead.u.l.next; - uv->u.l.next->u.l.prev = uv; - g->uvhead.u.l.next = uv; - lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); - return uv; -} - - -static void unlinkupval (UpVal *uv) { - lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); - uv->u.l.next->u.l.prev = uv->u.l.prev; /* remove from `uvhead' list */ - uv->u.l.prev->u.l.next = uv->u.l.next; -} - - -void luaF_freeupval (lua_State *L, UpVal *uv) { - if (uv->v != &uv->u.value) /* is it open? */ - unlinkupval(uv); /* remove from open list */ - luaM_free(L, uv); /* free upvalue */ -} - - -void luaF_close (lua_State *L, StkId level) { - UpVal *uv; - global_State *g = G(L); - while (L->openupval != NULL && (uv = ngcotouv(L->openupval))->v >= level) { - GCObject *o = obj2gco(uv); - lua_assert(!isblack(o) && uv->v != &uv->u.value); - L->openupval = uv->next; /* remove from `open' list */ - if (isdead(g, o)) - luaF_freeupval(L, uv); /* free upvalue */ - else { - unlinkupval(uv); - setobj(L, &uv->u.value, uv->v); - uv->v = &uv->u.value; /* now current value lives here */ - luaC_linkupval(L, uv); /* link upvalue into `gcroot' list */ - } - } -} - - -Proto *luaF_newproto (lua_State *L) { - Proto *f = luaM_new(L, Proto); - luaC_link(L, obj2gco(f), LUA_TPROTO); - f->k = NULL; - f->sizek = 0; - f->p = NULL; - f->sizep = 0; - f->code = NULL; - f->sizecode = 0; - f->sizelineinfo = 0; - f->sizeupvalues = 0; - f->nups = 0; - f->upvalues = NULL; - f->numparams = 0; - f->is_vararg = 0; - f->maxstacksize = 0; - f->lineinfo = NULL; - f->sizelocvars = 0; - f->locvars = NULL; - f->linedefined = 0; - f->lastlinedefined = 0; - f->source = NULL; - return f; -} - - -void luaF_freeproto (lua_State *L, Proto *f) { - luaM_freearray(L, f->code, f->sizecode, Instruction); - luaM_freearray(L, f->p, f->sizep, Proto *); - luaM_freearray(L, f->k, f->sizek, TValue); - luaM_freearray(L, f->lineinfo, f->sizelineinfo, int); - luaM_freearray(L, f->locvars, f->sizelocvars, struct LocVar); - luaM_freearray(L, f->upvalues, f->sizeupvalues, TString *); - luaM_free(L, f); -} - - -void luaF_freeclosure (lua_State *L, Closure *c) { - int size = (c->c.isC) ? sizeCclosure(c->c.nupvalues) : - sizeLclosure(c->l.nupvalues); - luaM_freemem(L, c, size); -} - - -/* -** Look for n-th local variable at line `line' in function `func'. -** Returns NULL if not found. -*/ -const char *luaF_getlocalname (const Proto *f, int local_number, int pc) { - int i; - for (i = 0; isizelocvars && f->locvars[i].startpc <= pc; i++) { - if (pc < f->locvars[i].endpc) { /* is variable active? */ - local_number--; - if (local_number == 0) - return getstr(f->locvars[i].varname); - } - } - return NULL; /* not found */ -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lfunc.h b/desmume/src/windows/lua/lua-5.1.4/src/lfunc.h deleted file mode 100644 index a68cf5151..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lfunc.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -** $Id: lfunc.h,v 2.4.1.1 2007/12/27 13:02:25 roberto Exp $ -** Auxiliary functions to manipulate prototypes and closures -** See Copyright Notice in lua.h -*/ - -#ifndef lfunc_h -#define lfunc_h - - -#include "lobject.h" - - -#define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \ - cast(int, sizeof(TValue)*((n)-1))) - -#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \ - cast(int, sizeof(TValue *)*((n)-1))) - - -LUAI_FUNC Proto *luaF_newproto (lua_State *L); -LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e); -LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e); -LUAI_FUNC UpVal *luaF_newupval (lua_State *L); -LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); -LUAI_FUNC void luaF_close (lua_State *L, StkId level); -LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); -LUAI_FUNC void luaF_freeclosure (lua_State *L, Closure *c); -LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv); -LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, - int pc); - - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lgc.c b/desmume/src/windows/lua/lua-5.1.4/src/lgc.c deleted file mode 100644 index d9e0b7829..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lgc.c +++ /dev/null @@ -1,711 +0,0 @@ -/* -** $Id: lgc.c,v 2.38.1.1 2007/12/27 13:02:25 roberto Exp $ -** Garbage Collector -** See Copyright Notice in lua.h -*/ - -#include - -#define lgc_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lgc.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" - - -#define GCSTEPSIZE 1024u -#define GCSWEEPMAX 40 -#define GCSWEEPCOST 10 -#define GCFINALIZECOST 100 - - -#define maskmarks cast_byte(~(bitmask(BLACKBIT)|WHITEBITS)) - -#define makewhite(g,x) \ - ((x)->gch.marked = cast_byte(((x)->gch.marked & maskmarks) | luaC_white(g))) - -#define white2gray(x) reset2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT) -#define black2gray(x) resetbit((x)->gch.marked, BLACKBIT) - -#define stringmark(s) reset2bits((s)->tsv.marked, WHITE0BIT, WHITE1BIT) - - -#define isfinalized(u) testbit((u)->marked, FINALIZEDBIT) -#define markfinalized(u) l_setbit((u)->marked, FINALIZEDBIT) - - -#define KEYWEAK bitmask(KEYWEAKBIT) -#define VALUEWEAK bitmask(VALUEWEAKBIT) - - - -#define markvalue(g,o) { checkconsistency(o); \ - if (iscollectable(o) && iswhite(gcvalue(o))) reallymarkobject(g,gcvalue(o)); } - -#define markobject(g,t) { if (iswhite(obj2gco(t))) \ - reallymarkobject(g, obj2gco(t)); } - - -#define setthreshold(g) (g->GCthreshold = (g->estimate/100) * g->gcpause) - - -static void removeentry (Node *n) { - lua_assert(ttisnil(gval(n))); - if (iscollectable(gkey(n))) - setttype(gkey(n), LUA_TDEADKEY); /* dead key; remove it */ -} - - -static void reallymarkobject (global_State *g, GCObject *o) { - lua_assert(iswhite(o) && !isdead(g, o)); - white2gray(o); - switch (o->gch.tt) { - case LUA_TSTRING: { - return; - } - case LUA_TUSERDATA: { - Table *mt = gco2u(o)->metatable; - gray2black(o); /* udata are never gray */ - if (mt) markobject(g, mt); - markobject(g, gco2u(o)->env); - return; - } - case LUA_TUPVAL: { - UpVal *uv = gco2uv(o); - markvalue(g, uv->v); - if (uv->v == &uv->u.value) /* closed? */ - gray2black(o); /* open upvalues are never black */ - return; - } - case LUA_TFUNCTION: { - gco2cl(o)->c.gclist = g->gray; - g->gray = o; - break; - } - case LUA_TTABLE: { - gco2h(o)->gclist = g->gray; - g->gray = o; - break; - } - case LUA_TTHREAD: { - gco2th(o)->gclist = g->gray; - g->gray = o; - break; - } - case LUA_TPROTO: { - gco2p(o)->gclist = g->gray; - g->gray = o; - break; - } - default: lua_assert(0); - } -} - - -static void marktmu (global_State *g) { - GCObject *u = g->tmudata; - if (u) { - do { - u = u->gch.next; - makewhite(g, u); /* may be marked, if left from previous GC */ - reallymarkobject(g, u); - } while (u != g->tmudata); - } -} - - -/* move `dead' udata that need finalization to list `tmudata' */ -size_t luaC_separateudata (lua_State *L, int all) { - global_State *g = G(L); - size_t deadmem = 0; - GCObject **p = &g->mainthread->next; - GCObject *curr; - while ((curr = *p) != NULL) { - if (!(iswhite(curr) || all) || isfinalized(gco2u(curr))) - p = &curr->gch.next; /* don't bother with them */ - else if (fasttm(L, gco2u(curr)->metatable, TM_GC) == NULL) { - markfinalized(gco2u(curr)); /* don't need finalization */ - p = &curr->gch.next; - } - else { /* must call its gc method */ - deadmem += sizeudata(gco2u(curr)); - markfinalized(gco2u(curr)); - *p = curr->gch.next; - /* link `curr' at the end of `tmudata' list */ - if (g->tmudata == NULL) /* list is empty? */ - g->tmudata = curr->gch.next = curr; /* creates a circular list */ - else { - curr->gch.next = g->tmudata->gch.next; - g->tmudata->gch.next = curr; - g->tmudata = curr; - } - } - } - return deadmem; -} - - -static int traversetable (global_State *g, Table *h) { - int i; - int weakkey = 0; - int weakvalue = 0; - const TValue *mode; - if (h->metatable) - markobject(g, h->metatable); - mode = gfasttm(g, h->metatable, TM_MODE); - if (mode && ttisstring(mode)) { /* is there a weak mode? */ - weakkey = (strchr(svalue(mode), 'k') != NULL); - weakvalue = (strchr(svalue(mode), 'v') != NULL); - if (weakkey || weakvalue) { /* is really weak? */ - h->marked &= ~(KEYWEAK | VALUEWEAK); /* clear bits */ - h->marked |= cast_byte((weakkey << KEYWEAKBIT) | - (weakvalue << VALUEWEAKBIT)); - h->gclist = g->weak; /* must be cleared after GC, ... */ - g->weak = obj2gco(h); /* ... so put in the appropriate list */ - } - } - if (weakkey && weakvalue) return 1; - if (!weakvalue) { - i = h->sizearray; - while (i--) - markvalue(g, &h->array[i]); - } - i = sizenode(h); - while (i--) { - Node *n = gnode(h, i); - lua_assert(ttype(gkey(n)) != LUA_TDEADKEY || ttisnil(gval(n))); - if (ttisnil(gval(n))) - removeentry(n); /* remove empty entries */ - else { - lua_assert(!ttisnil(gkey(n))); - if (!weakkey) markvalue(g, gkey(n)); - if (!weakvalue) markvalue(g, gval(n)); - } - } - return weakkey || weakvalue; -} - - -/* -** All marks are conditional because a GC may happen while the -** prototype is still being created -*/ -static void traverseproto (global_State *g, Proto *f) { - int i; - if (f->source) stringmark(f->source); - for (i=0; isizek; i++) /* mark literals */ - markvalue(g, &f->k[i]); - for (i=0; isizeupvalues; i++) { /* mark upvalue names */ - if (f->upvalues[i]) - stringmark(f->upvalues[i]); - } - for (i=0; isizep; i++) { /* mark nested protos */ - if (f->p[i]) - markobject(g, f->p[i]); - } - for (i=0; isizelocvars; i++) { /* mark local-variable names */ - if (f->locvars[i].varname) - stringmark(f->locvars[i].varname); - } -} - - - -static void traverseclosure (global_State *g, Closure *cl) { - markobject(g, cl->c.env); - if (cl->c.isC) { - int i; - for (i=0; ic.nupvalues; i++) /* mark its upvalues */ - markvalue(g, &cl->c.upvalue[i]); - } - else { - int i; - lua_assert(cl->l.nupvalues == cl->l.p->nups); - markobject(g, cl->l.p); - for (i=0; il.nupvalues; i++) /* mark its upvalues */ - markobject(g, cl->l.upvals[i]); - } -} - - -static void checkstacksizes (lua_State *L, StkId max) { - int ci_used = cast_int(L->ci - L->base_ci); /* number of `ci' in use */ - int s_used = cast_int(max - L->stack); /* part of stack in use */ - if (L->size_ci > LUAI_MAXCALLS) /* handling overflow? */ - return; /* do not touch the stacks */ - if (4*ci_used < L->size_ci && 2*BASIC_CI_SIZE < L->size_ci) - luaD_reallocCI(L, L->size_ci/2); /* still big enough... */ - condhardstacktests(luaD_reallocCI(L, ci_used + 1)); - if (4*s_used < L->stacksize && - 2*(BASIC_STACK_SIZE+EXTRA_STACK) < L->stacksize) - luaD_reallocstack(L, L->stacksize/2); /* still big enough... */ - condhardstacktests(luaD_reallocstack(L, s_used)); -} - - -static void traversestack (global_State *g, lua_State *l) { - StkId o, lim; - CallInfo *ci; - markvalue(g, gt(l)); - lim = l->top; - for (ci = l->base_ci; ci <= l->ci; ci++) { - lua_assert(ci->top <= l->stack_last); - if (lim < ci->top) lim = ci->top; - } - for (o = l->stack; o < l->top; o++) - markvalue(g, o); - for (; o <= lim; o++) - setnilvalue(o); - checkstacksizes(l, lim); -} - - -/* -** traverse one gray object, turning it to black. -** Returns `quantity' traversed. -*/ -static l_mem propagatemark (global_State *g) { - GCObject *o = g->gray; - lua_assert(isgray(o)); - gray2black(o); - switch (o->gch.tt) { - case LUA_TTABLE: { - Table *h = gco2h(o); - g->gray = h->gclist; - if (traversetable(g, h)) /* table is weak? */ - black2gray(o); /* keep it gray */ - return sizeof(Table) + sizeof(TValue) * h->sizearray + - sizeof(Node) * sizenode(h); - } - case LUA_TFUNCTION: { - Closure *cl = gco2cl(o); - g->gray = cl->c.gclist; - traverseclosure(g, cl); - return (cl->c.isC) ? sizeCclosure(cl->c.nupvalues) : - sizeLclosure(cl->l.nupvalues); - } - case LUA_TTHREAD: { - lua_State *th = gco2th(o); - g->gray = th->gclist; - th->gclist = g->grayagain; - g->grayagain = o; - black2gray(o); - traversestack(g, th); - return sizeof(lua_State) + sizeof(TValue) * th->stacksize + - sizeof(CallInfo) * th->size_ci; - } - case LUA_TPROTO: { - Proto *p = gco2p(o); - g->gray = p->gclist; - traverseproto(g, p); - return sizeof(Proto) + sizeof(Instruction) * p->sizecode + - sizeof(Proto *) * p->sizep + - sizeof(TValue) * p->sizek + - sizeof(int) * p->sizelineinfo + - sizeof(LocVar) * p->sizelocvars + - sizeof(TString *) * p->sizeupvalues; - } - default: lua_assert(0); return 0; - } -} - - -static size_t propagateall (global_State *g) { - size_t m = 0; - while (g->gray) m += propagatemark(g); - return m; -} - - -/* -** The next function tells whether a key or value can be cleared from -** a weak table. Non-collectable objects are never removed from weak -** tables. Strings behave as `values', so are never removed too. for -** other objects: if really collected, cannot keep them; for userdata -** being finalized, keep them in keys, but not in values -*/ -static int iscleared (const TValue *o, int iskey) { - if (!iscollectable(o)) return 0; - if (ttisstring(o)) { - stringmark(rawtsvalue(o)); /* strings are `values', so are never weak */ - return 0; - } - return iswhite(gcvalue(o)) || - (ttisuserdata(o) && (!iskey && isfinalized(uvalue(o)))); -} - - -/* -** clear collected entries from weaktables -*/ -static void cleartable (GCObject *l) { - while (l) { - Table *h = gco2h(l); - int i = h->sizearray; - lua_assert(testbit(h->marked, VALUEWEAKBIT) || - testbit(h->marked, KEYWEAKBIT)); - if (testbit(h->marked, VALUEWEAKBIT)) { - while (i--) { - TValue *o = &h->array[i]; - if (iscleared(o, 0)) /* value was collected? */ - setnilvalue(o); /* remove value */ - } - } - i = sizenode(h); - while (i--) { - Node *n = gnode(h, i); - if (!ttisnil(gval(n)) && /* non-empty entry? */ - (iscleared(key2tval(n), 1) || iscleared(gval(n), 0))) { - setnilvalue(gval(n)); /* remove value ... */ - removeentry(n); /* remove entry from table */ - } - } - l = h->gclist; - } -} - - -static void freeobj (lua_State *L, GCObject *o) { - switch (o->gch.tt) { - case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break; - case LUA_TFUNCTION: luaF_freeclosure(L, gco2cl(o)); break; - case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break; - case LUA_TTABLE: luaH_free(L, gco2h(o)); break; - case LUA_TTHREAD: { - lua_assert(gco2th(o) != L && gco2th(o) != G(L)->mainthread); - luaE_freethread(L, gco2th(o)); - break; - } - case LUA_TSTRING: { - G(L)->strt.nuse--; - luaM_freemem(L, o, sizestring(gco2ts(o))); - break; - } - case LUA_TUSERDATA: { - luaM_freemem(L, o, sizeudata(gco2u(o))); - break; - } - default: lua_assert(0); - } -} - - - -#define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM) - - -static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) { - GCObject *curr; - global_State *g = G(L); - int deadmask = otherwhite(g); - while ((curr = *p) != NULL && count-- > 0) { - if (curr->gch.tt == LUA_TTHREAD) /* sweep open upvalues of each thread */ - sweepwholelist(L, &gco2th(curr)->openupval); - if ((curr->gch.marked ^ WHITEBITS) & deadmask) { /* not dead? */ - lua_assert(!isdead(g, curr) || testbit(curr->gch.marked, FIXEDBIT)); - makewhite(g, curr); /* make it white (for next cycle) */ - p = &curr->gch.next; - } - else { /* must erase `curr' */ - lua_assert(isdead(g, curr) || deadmask == bitmask(SFIXEDBIT)); - *p = curr->gch.next; - if (curr == g->rootgc) /* is the first element of the list? */ - g->rootgc = curr->gch.next; /* adjust first */ - freeobj(L, curr); - } - } - return p; -} - - -static void checkSizes (lua_State *L) { - global_State *g = G(L); - /* check size of string hash */ - if (g->strt.nuse < cast(lu_int32, g->strt.size/4) && - g->strt.size > MINSTRTABSIZE*2) - luaS_resize(L, g->strt.size/2); /* table is too big */ - /* check size of buffer */ - if (luaZ_sizebuffer(&g->buff) > LUA_MINBUFFER*2) { /* buffer too big? */ - size_t newsize = luaZ_sizebuffer(&g->buff) / 2; - luaZ_resizebuffer(L, &g->buff, newsize); - } -} - - -static void GCTM (lua_State *L) { - global_State *g = G(L); - GCObject *o = g->tmudata->gch.next; /* get first element */ - Udata *udata = rawgco2u(o); - const TValue *tm; - /* remove udata from `tmudata' */ - if (o == g->tmudata) /* last element? */ - g->tmudata = NULL; - else - g->tmudata->gch.next = udata->uv.next; - udata->uv.next = g->mainthread->next; /* return it to `root' list */ - g->mainthread->next = o; - makewhite(g, o); - tm = fasttm(L, udata->uv.metatable, TM_GC); - if (tm != NULL) { - lu_byte oldah = L->allowhook; - lu_mem oldt = g->GCthreshold; - L->allowhook = 0; /* stop debug hooks during GC tag method */ - g->GCthreshold = 2*g->totalbytes; /* avoid GC steps */ - setobj2s(L, L->top, tm); - setuvalue(L, L->top+1, udata); - L->top += 2; - luaD_call(L, L->top - 2, 0); - L->allowhook = oldah; /* restore hooks */ - g->GCthreshold = oldt; /* restore threshold */ - } -} - - -/* -** Call all GC tag methods -*/ -void luaC_callGCTM (lua_State *L) { - while (G(L)->tmudata) - GCTM(L); -} - - -void luaC_freeall (lua_State *L) { - global_State *g = G(L); - int i; - g->currentwhite = WHITEBITS | bitmask(SFIXEDBIT); /* mask to collect all elements */ - sweepwholelist(L, &g->rootgc); - for (i = 0; i < g->strt.size; i++) /* free all string lists */ - sweepwholelist(L, &g->strt.hash[i]); -} - - -static void markmt (global_State *g) { - int i; - for (i=0; imt[i]) markobject(g, g->mt[i]); -} - - -/* mark root set */ -static void markroot (lua_State *L) { - global_State *g = G(L); - g->gray = NULL; - g->grayagain = NULL; - g->weak = NULL; - markobject(g, g->mainthread); - /* make global table be traversed before main stack */ - markvalue(g, gt(g->mainthread)); - markvalue(g, registry(L)); - markmt(g); - g->gcstate = GCSpropagate; -} - - -static void remarkupvals (global_State *g) { - UpVal *uv; - for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) { - lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv); - if (isgray(obj2gco(uv))) - markvalue(g, uv->v); - } -} - - -static void atomic (lua_State *L) { - global_State *g = G(L); - size_t udsize; /* total size of userdata to be finalized */ - /* remark occasional upvalues of (maybe) dead threads */ - remarkupvals(g); - /* traverse objects cautch by write barrier and by 'remarkupvals' */ - propagateall(g); - /* remark weak tables */ - g->gray = g->weak; - g->weak = NULL; - lua_assert(!iswhite(obj2gco(g->mainthread))); - markobject(g, L); /* mark running thread */ - markmt(g); /* mark basic metatables (again) */ - propagateall(g); - /* remark gray again */ - g->gray = g->grayagain; - g->grayagain = NULL; - propagateall(g); - udsize = luaC_separateudata(L, 0); /* separate userdata to be finalized */ - marktmu(g); /* mark `preserved' userdata */ - udsize += propagateall(g); /* remark, to propagate `preserveness' */ - cleartable(g->weak); /* remove collected objects from weak tables */ - /* flip current white */ - g->currentwhite = cast_byte(otherwhite(g)); - g->sweepstrgc = 0; - g->sweepgc = &g->rootgc; - g->gcstate = GCSsweepstring; - g->estimate = g->totalbytes - udsize; /* first estimate */ -} - - -static l_mem singlestep (lua_State *L) { - global_State *g = G(L); - /*lua_checkmemory(L);*/ - switch (g->gcstate) { - case GCSpause: { - markroot(L); /* start a new collection */ - return 0; - } - case GCSpropagate: { - if (g->gray) - return propagatemark(g); - else { /* no more `gray' objects */ - atomic(L); /* finish mark phase */ - return 0; - } - } - case GCSsweepstring: { - lu_mem old = g->totalbytes; - sweepwholelist(L, &g->strt.hash[g->sweepstrgc++]); - if (g->sweepstrgc >= g->strt.size) /* nothing more to sweep? */ - g->gcstate = GCSsweep; /* end sweep-string phase */ - lua_assert(old >= g->totalbytes); - g->estimate -= old - g->totalbytes; - return GCSWEEPCOST; - } - case GCSsweep: { - lu_mem old = g->totalbytes; - g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX); - if (*g->sweepgc == NULL) { /* nothing more to sweep? */ - checkSizes(L); - g->gcstate = GCSfinalize; /* end sweep phase */ - } - lua_assert(old >= g->totalbytes); - g->estimate -= old - g->totalbytes; - return GCSWEEPMAX*GCSWEEPCOST; - } - case GCSfinalize: { - if (g->tmudata) { - GCTM(L); - if (g->estimate > GCFINALIZECOST) - g->estimate -= GCFINALIZECOST; - return GCFINALIZECOST; - } - else { - g->gcstate = GCSpause; /* end collection */ - g->gcdept = 0; - return 0; - } - } - default: lua_assert(0); return 0; - } -} - - -void luaC_step (lua_State *L) { - global_State *g = G(L); - l_mem lim = (GCSTEPSIZE/100) * g->gcstepmul; - if (lim == 0) - lim = (MAX_LUMEM-1)/2; /* no limit */ - g->gcdept += g->totalbytes - g->GCthreshold; - do { - lim -= singlestep(L); - if (g->gcstate == GCSpause) - break; - } while (lim > 0); - if (g->gcstate != GCSpause) { - if (g->gcdept < GCSTEPSIZE) - g->GCthreshold = g->totalbytes + GCSTEPSIZE; /* - lim/g->gcstepmul;*/ - else { - g->gcdept -= GCSTEPSIZE; - g->GCthreshold = g->totalbytes; - } - } - else { - lua_assert(g->totalbytes >= g->estimate); - setthreshold(g); - } -} - - -void luaC_fullgc (lua_State *L) { - global_State *g = G(L); - if (g->gcstate <= GCSpropagate) { - /* reset sweep marks to sweep all elements (returning them to white) */ - g->sweepstrgc = 0; - g->sweepgc = &g->rootgc; - /* reset other collector lists */ - g->gray = NULL; - g->grayagain = NULL; - g->weak = NULL; - g->gcstate = GCSsweepstring; - } - lua_assert(g->gcstate != GCSpause && g->gcstate != GCSpropagate); - /* finish any pending sweep phase */ - while (g->gcstate != GCSfinalize) { - lua_assert(g->gcstate == GCSsweepstring || g->gcstate == GCSsweep); - singlestep(L); - } - markroot(L); - while (g->gcstate != GCSpause) { - singlestep(L); - } - setthreshold(g); -} - - -void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v) { - global_State *g = G(L); - lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); - lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause); - lua_assert(ttype(&o->gch) != LUA_TTABLE); - /* must keep invariant? */ - if (g->gcstate == GCSpropagate) - reallymarkobject(g, v); /* restore invariant */ - else /* don't mind */ - makewhite(g, o); /* mark as white just to avoid other barriers */ -} - - -void luaC_barrierback (lua_State *L, Table *t) { - global_State *g = G(L); - GCObject *o = obj2gco(t); - lua_assert(isblack(o) && !isdead(g, o)); - lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause); - black2gray(o); /* make table gray (again) */ - t->gclist = g->grayagain; - g->grayagain = o; -} - - -void luaC_link (lua_State *L, GCObject *o, lu_byte tt) { - global_State *g = G(L); - o->gch.next = g->rootgc; - g->rootgc = o; - o->gch.marked = luaC_white(g); - o->gch.tt = tt; -} - - -void luaC_linkupval (lua_State *L, UpVal *uv) { - global_State *g = G(L); - GCObject *o = obj2gco(uv); - o->gch.next = g->rootgc; /* link upvalue into `rootgc' list */ - g->rootgc = o; - if (isgray(o)) { - if (g->gcstate == GCSpropagate) { - gray2black(o); /* closed upvalues need barrier */ - luaC_barrier(L, uv, uv->v); - } - else { /* sweep phase: sweep it (turning it into white) */ - makewhite(g, o); - lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause); - } - } -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lgc.h b/desmume/src/windows/lua/lua-5.1.4/src/lgc.h deleted file mode 100644 index 5a8dc605b..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lgc.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -** $Id: lgc.h,v 2.15.1.1 2007/12/27 13:02:25 roberto Exp $ -** Garbage Collector -** See Copyright Notice in lua.h -*/ - -#ifndef lgc_h -#define lgc_h - - -#include "lobject.h" - - -/* -** Possible states of the Garbage Collector -*/ -#define GCSpause 0 -#define GCSpropagate 1 -#define GCSsweepstring 2 -#define GCSsweep 3 -#define GCSfinalize 4 - - -/* -** some userful bit tricks -*/ -#define resetbits(x,m) ((x) &= cast(lu_byte, ~(m))) -#define setbits(x,m) ((x) |= (m)) -#define testbits(x,m) ((x) & (m)) -#define bitmask(b) (1<<(b)) -#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) -#define l_setbit(x,b) setbits(x, bitmask(b)) -#define resetbit(x,b) resetbits(x, bitmask(b)) -#define testbit(x,b) testbits(x, bitmask(b)) -#define set2bits(x,b1,b2) setbits(x, (bit2mask(b1, b2))) -#define reset2bits(x,b1,b2) resetbits(x, (bit2mask(b1, b2))) -#define test2bits(x,b1,b2) testbits(x, (bit2mask(b1, b2))) - - - -/* -** Layout for bit use in `marked' field: -** bit 0 - object is white (type 0) -** bit 1 - object is white (type 1) -** bit 2 - object is black -** bit 3 - for userdata: has been finalized -** bit 3 - for tables: has weak keys -** bit 4 - for tables: has weak values -** bit 5 - object is fixed (should not be collected) -** bit 6 - object is "super" fixed (only the main thread) -*/ - - -#define WHITE0BIT 0 -#define WHITE1BIT 1 -#define BLACKBIT 2 -#define FINALIZEDBIT 3 -#define KEYWEAKBIT 3 -#define VALUEWEAKBIT 4 -#define FIXEDBIT 5 -#define SFIXEDBIT 6 -#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) - - -#define iswhite(x) test2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT) -#define isblack(x) testbit((x)->gch.marked, BLACKBIT) -#define isgray(x) (!isblack(x) && !iswhite(x)) - -#define otherwhite(g) (g->currentwhite ^ WHITEBITS) -#define isdead(g,v) ((v)->gch.marked & otherwhite(g) & WHITEBITS) - -#define changewhite(x) ((x)->gch.marked ^= WHITEBITS) -#define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT) - -#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) - -#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) - - -#define luaC_checkGC(L) { \ - condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); \ - if (G(L)->totalbytes >= G(L)->GCthreshold) \ - luaC_step(L); } - - -#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ - luaC_barrierf(L,obj2gco(p),gcvalue(v)); } - -#define luaC_barriert(L,t,v) { if (valiswhite(v) && isblack(obj2gco(t))) \ - luaC_barrierback(L,t); } - -#define luaC_objbarrier(L,p,o) \ - { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \ - luaC_barrierf(L,obj2gco(p),obj2gco(o)); } - -#define luaC_objbarriert(L,t,o) \ - { if (iswhite(obj2gco(o)) && isblack(obj2gco(t))) luaC_barrierback(L,t); } - -LUAI_FUNC size_t luaC_separateudata (lua_State *L, int all); -LUAI_FUNC void luaC_callGCTM (lua_State *L); -LUAI_FUNC void luaC_freeall (lua_State *L); -LUAI_FUNC void luaC_step (lua_State *L); -LUAI_FUNC void luaC_fullgc (lua_State *L); -LUAI_FUNC void luaC_link (lua_State *L, GCObject *o, lu_byte tt); -LUAI_FUNC void luaC_linkupval (lua_State *L, UpVal *uv); -LUAI_FUNC void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v); -LUAI_FUNC void luaC_barrierback (lua_State *L, Table *t); - - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/linit.c b/desmume/src/windows/lua/lua-5.1.4/src/linit.c deleted file mode 100644 index c1f90dfab..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/linit.c +++ /dev/null @@ -1,38 +0,0 @@ -/* -** $Id: linit.c,v 1.14.1.1 2007/12/27 13:02:25 roberto Exp $ -** Initialization of libraries for lua.c -** See Copyright Notice in lua.h -*/ - - -#define linit_c -#define LUA_LIB - -#include "lua.h" - -#include "lualib.h" -#include "lauxlib.h" - - -static const luaL_Reg lualibs[] = { - {"", luaopen_base}, - {LUA_LOADLIBNAME, luaopen_package}, - {LUA_TABLIBNAME, luaopen_table}, - {LUA_IOLIBNAME, luaopen_io}, - {LUA_OSLIBNAME, luaopen_os}, - {LUA_STRLIBNAME, luaopen_string}, - {LUA_MATHLIBNAME, luaopen_math}, - {LUA_DBLIBNAME, luaopen_debug}, - {NULL, NULL} -}; - - -LUALIB_API void luaL_openlibs (lua_State *L) { - const luaL_Reg *lib = lualibs; - for (; lib->func; lib++) { - lua_pushcfunction(L, lib->func); - lua_pushstring(L, lib->name); - lua_call(L, 1, 0); - } -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/liolib.c b/desmume/src/windows/lua/lua-5.1.4/src/liolib.c deleted file mode 100644 index e79ed1cb2..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/liolib.c +++ /dev/null @@ -1,553 +0,0 @@ -/* -** $Id: liolib.c,v 2.73.1.3 2008/01/18 17:47:43 roberto Exp $ -** Standard I/O (and system) library -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include - -#define liolib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - - -#define IO_INPUT 1 -#define IO_OUTPUT 2 - - -static const char *const fnames[] = {"input", "output"}; - - -static int pushresult (lua_State *L, int i, const char *filename) { - int en = errno; /* calls to Lua API may change this value */ - if (i) { - lua_pushboolean(L, 1); - return 1; - } - else { - lua_pushnil(L); - if (filename) - lua_pushfstring(L, "%s: %s", filename, strerror(en)); - else - lua_pushfstring(L, "%s", strerror(en)); - lua_pushinteger(L, en); - return 3; - } -} - - -static void fileerror (lua_State *L, int arg, const char *filename) { - lua_pushfstring(L, "%s: %s", filename, strerror(errno)); - luaL_argerror(L, arg, lua_tostring(L, -1)); -} - - -#define tofilep(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE)) - - -static int io_type (lua_State *L) { - void *ud; - luaL_checkany(L, 1); - ud = lua_touserdata(L, 1); - lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE); - if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1)) - lua_pushnil(L); /* not a file */ - else if (*((FILE **)ud) == NULL) - lua_pushliteral(L, "closed file"); - else - lua_pushliteral(L, "file"); - return 1; -} - - -static FILE *tofile (lua_State *L) { - FILE **f = tofilep(L); - if (*f == NULL) - luaL_error(L, "attempt to use a closed file"); - return *f; -} - - - -/* -** When creating file handles, always creates a `closed' file handle -** before opening the actual file; so, if there is a memory error, the -** file is not left opened. -*/ -static FILE **newfile (lua_State *L) { - FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *)); - *pf = NULL; /* file handle is currently `closed' */ - luaL_getmetatable(L, LUA_FILEHANDLE); - lua_setmetatable(L, -2); - return pf; -} - - -/* -** function to (not) close the standard files stdin, stdout, and stderr -*/ -static int io_noclose (lua_State *L) { - lua_pushnil(L); - lua_pushliteral(L, "cannot close standard file"); - return 2; -} - - -/* -** function to close 'popen' files -*/ -static int io_pclose (lua_State *L) { - FILE **p = tofilep(L); - int ok = lua_pclose(L, *p); - *p = NULL; - return pushresult(L, ok, NULL); -} - - -/* -** function to close regular files -*/ -static int io_fclose (lua_State *L) { - FILE **p = tofilep(L); - int ok = (fclose(*p) == 0); - *p = NULL; - return pushresult(L, ok, NULL); -} - - -static int aux_close (lua_State *L) { - lua_getfenv(L, 1); - lua_getfield(L, -1, "__close"); - return (lua_tocfunction(L, -1))(L); -} - - -static int io_close (lua_State *L) { - if (lua_isnone(L, 1)) - lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT); - tofile(L); /* make sure argument is a file */ - return aux_close(L); -} - - -static int io_gc (lua_State *L) { - FILE *f = *tofilep(L); - /* ignore closed files */ - if (f != NULL) - aux_close(L); - return 0; -} - - -static int io_tostring (lua_State *L) { - FILE *f = *tofilep(L); - if (f == NULL) - lua_pushliteral(L, "file (closed)"); - else - lua_pushfstring(L, "file (%p)", f); - return 1; -} - - -static int io_open (lua_State *L) { - const char *filename = luaL_checkstring(L, 1); - const char *mode = luaL_optstring(L, 2, "r"); - FILE **pf = newfile(L); - *pf = fopen(filename, mode); - return (*pf == NULL) ? pushresult(L, 0, filename) : 1; -} - - -/* -** this function has a separated environment, which defines the -** correct __close for 'popen' files -*/ -static int io_popen (lua_State *L) { - const char *filename = luaL_checkstring(L, 1); - const char *mode = luaL_optstring(L, 2, "r"); - FILE **pf = newfile(L); - *pf = lua_popen(L, filename, mode); - return (*pf == NULL) ? pushresult(L, 0, filename) : 1; -} - - -static int io_tmpfile (lua_State *L) { - FILE **pf = newfile(L); - *pf = tmpfile(); - return (*pf == NULL) ? pushresult(L, 0, NULL) : 1; -} - - -static FILE *getiofile (lua_State *L, int findex) { - FILE *f; - lua_rawgeti(L, LUA_ENVIRONINDEX, findex); - f = *(FILE **)lua_touserdata(L, -1); - if (f == NULL) - luaL_error(L, "standard %s file is closed", fnames[findex - 1]); - return f; -} - - -static int g_iofile (lua_State *L, int f, const char *mode) { - if (!lua_isnoneornil(L, 1)) { - const char *filename = lua_tostring(L, 1); - if (filename) { - FILE **pf = newfile(L); - *pf = fopen(filename, mode); - if (*pf == NULL) - fileerror(L, 1, filename); - } - else { - tofile(L); /* check that it's a valid file handle */ - lua_pushvalue(L, 1); - } - lua_rawseti(L, LUA_ENVIRONINDEX, f); - } - /* return current value */ - lua_rawgeti(L, LUA_ENVIRONINDEX, f); - return 1; -} - - -static int io_input (lua_State *L) { - return g_iofile(L, IO_INPUT, "r"); -} - - -static int io_output (lua_State *L) { - return g_iofile(L, IO_OUTPUT, "w"); -} - - -static int io_readline (lua_State *L); - - -static void aux_lines (lua_State *L, int idx, int toclose) { - lua_pushvalue(L, idx); - lua_pushboolean(L, toclose); /* close/not close file when finished */ - lua_pushcclosure(L, io_readline, 2); -} - - -static int f_lines (lua_State *L) { - tofile(L); /* check that it's a valid file handle */ - aux_lines(L, 1, 0); - return 1; -} - - -static int io_lines (lua_State *L) { - if (lua_isnoneornil(L, 1)) { /* no arguments? */ - /* will iterate over default input */ - lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT); - return f_lines(L); - } - else { - const char *filename = luaL_checkstring(L, 1); - FILE **pf = newfile(L); - *pf = fopen(filename, "r"); - if (*pf == NULL) - fileerror(L, 1, filename); - aux_lines(L, lua_gettop(L), 1); - return 1; - } -} - - -/* -** {====================================================== -** READ -** ======================================================= -*/ - - -static int read_number (lua_State *L, FILE *f) { - lua_Number d; - if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) { - lua_pushnumber(L, d); - return 1; - } - else return 0; /* read fails */ -} - - -static int test_eof (lua_State *L, FILE *f) { - int c = getc(f); - ungetc(c, f); - lua_pushlstring(L, NULL, 0); - return (c != EOF); -} - - -static int read_line (lua_State *L, FILE *f) { - luaL_Buffer b; - luaL_buffinit(L, &b); - for (;;) { - size_t l; - char *p = luaL_prepbuffer(&b); - if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */ - luaL_pushresult(&b); /* close buffer */ - return (lua_objlen(L, -1) > 0); /* check whether read something */ - } - l = strlen(p); - if (l == 0 || p[l-1] != '\n') - luaL_addsize(&b, l); - else { - luaL_addsize(&b, l - 1); /* do not include `eol' */ - luaL_pushresult(&b); /* close buffer */ - return 1; /* read at least an `eol' */ - } - } -} - - -static int read_chars (lua_State *L, FILE *f, size_t n) { - size_t rlen; /* how much to read */ - size_t nr; /* number of chars actually read */ - luaL_Buffer b; - luaL_buffinit(L, &b); - rlen = LUAL_BUFFERSIZE; /* try to read that much each time */ - do { - char *p = luaL_prepbuffer(&b); - if (rlen > n) rlen = n; /* cannot read more than asked */ - nr = fread(p, sizeof(char), rlen, f); - luaL_addsize(&b, nr); - n -= nr; /* still have to read `n' chars */ - } while (n > 0 && nr == rlen); /* until end of count or eof */ - luaL_pushresult(&b); /* close buffer */ - return (n == 0 || lua_objlen(L, -1) > 0); -} - - -static int g_read (lua_State *L, FILE *f, int first) { - int nargs = lua_gettop(L) - 1; - int success; - int n; - clearerr(f); - if (nargs == 0) { /* no arguments? */ - success = read_line(L, f); - n = first+1; /* to return 1 result */ - } - else { /* ensure stack space for all results and for auxlib's buffer */ - luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments"); - success = 1; - for (n = first; nargs-- && success; n++) { - if (lua_type(L, n) == LUA_TNUMBER) { - size_t l = (size_t)lua_tointeger(L, n); - success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); - } - else { - const char *p = lua_tostring(L, n); - luaL_argcheck(L, p && p[0] == '*', n, "invalid option"); - switch (p[1]) { - case 'n': /* number */ - success = read_number(L, f); - break; - case 'l': /* line */ - success = read_line(L, f); - break; - case 'a': /* file */ - read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */ - success = 1; /* always success */ - break; - default: - return luaL_argerror(L, n, "invalid format"); - } - } - } - } - if (ferror(f)) - return pushresult(L, 0, NULL); - if (!success) { - lua_pop(L, 1); /* remove last result */ - lua_pushnil(L); /* push nil instead */ - } - return n - first; -} - - -static int io_read (lua_State *L) { - return g_read(L, getiofile(L, IO_INPUT), 1); -} - - -static int f_read (lua_State *L) { - return g_read(L, tofile(L), 2); -} - - -static int io_readline (lua_State *L) { - FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1)); - int sucess; - if (f == NULL) /* file is already closed? */ - luaL_error(L, "file is already closed"); - sucess = read_line(L, f); - if (ferror(f)) - return luaL_error(L, "%s", strerror(errno)); - if (sucess) return 1; - else { /* EOF */ - if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */ - lua_settop(L, 0); - lua_pushvalue(L, lua_upvalueindex(1)); - aux_close(L); /* close it */ - } - return 0; - } -} - -/* }====================================================== */ - - -static int g_write (lua_State *L, FILE *f, int arg) { - int nargs = lua_gettop(L) - 1; - int status = 1; - for (; nargs--; arg++) { - if (lua_type(L, arg) == LUA_TNUMBER) { - /* optimization: could be done exactly as for strings */ - status = status && - fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0; - } - else { - size_t l; - const char *s = luaL_checklstring(L, arg, &l); - status = status && (fwrite(s, sizeof(char), l, f) == l); - } - } - return pushresult(L, status, NULL); -} - - -static int io_write (lua_State *L) { - return g_write(L, getiofile(L, IO_OUTPUT), 1); -} - - -static int f_write (lua_State *L) { - return g_write(L, tofile(L), 2); -} - - -static int f_seek (lua_State *L) { - static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END}; - static const char *const modenames[] = {"set", "cur", "end", NULL}; - FILE *f = tofile(L); - int op = luaL_checkoption(L, 2, "cur", modenames); - long offset = luaL_optlong(L, 3, 0); - op = fseek(f, offset, mode[op]); - if (op) - return pushresult(L, 0, NULL); /* error */ - else { - lua_pushinteger(L, ftell(f)); - return 1; - } -} - - -static int f_setvbuf (lua_State *L) { - static const int mode[] = {_IONBF, _IOFBF, _IOLBF}; - static const char *const modenames[] = {"no", "full", "line", NULL}; - FILE *f = tofile(L); - int op = luaL_checkoption(L, 2, NULL, modenames); - lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE); - int res = setvbuf(f, NULL, mode[op], sz); - return pushresult(L, res == 0, NULL); -} - - - -static int io_flush (lua_State *L) { - return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL); -} - - -static int f_flush (lua_State *L) { - return pushresult(L, fflush(tofile(L)) == 0, NULL); -} - - -static const luaL_Reg iolib[] = { - {"close", io_close}, - {"flush", io_flush}, - {"input", io_input}, - {"lines", io_lines}, - {"open", io_open}, - {"output", io_output}, - {"popen", io_popen}, - {"read", io_read}, - {"tmpfile", io_tmpfile}, - {"type", io_type}, - {"write", io_write}, - {NULL, NULL} -}; - - -static const luaL_Reg flib[] = { - {"close", io_close}, - {"flush", f_flush}, - {"lines", f_lines}, - {"read", f_read}, - {"seek", f_seek}, - {"setvbuf", f_setvbuf}, - {"write", f_write}, - {"__gc", io_gc}, - {"__tostring", io_tostring}, - {NULL, NULL} -}; - - -static void createmeta (lua_State *L) { - luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */ - lua_pushvalue(L, -1); /* push metatable */ - lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */ - luaL_register(L, NULL, flib); /* file methods */ -} - - -static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) { - *newfile(L) = f; - if (k > 0) { - lua_pushvalue(L, -1); - lua_rawseti(L, LUA_ENVIRONINDEX, k); - } - lua_pushvalue(L, -2); /* copy environment */ - lua_setfenv(L, -2); /* set it */ - lua_setfield(L, -3, fname); -} - - -static void newfenv (lua_State *L, lua_CFunction cls) { - lua_createtable(L, 0, 1); - lua_pushcfunction(L, cls); - lua_setfield(L, -2, "__close"); -} - - -LUALIB_API int luaopen_io (lua_State *L) { - createmeta(L); - /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */ - newfenv(L, io_fclose); - lua_replace(L, LUA_ENVIRONINDEX); - /* open library */ - luaL_register(L, LUA_IOLIBNAME, iolib); - /* create (and set) default files */ - newfenv(L, io_noclose); /* close function for default files */ - createstdfile(L, stdin, IO_INPUT, "stdin"); - createstdfile(L, stdout, IO_OUTPUT, "stdout"); - createstdfile(L, stderr, 0, "stderr"); - lua_pop(L, 1); /* pop environment for default files */ - lua_getfield(L, -1, "popen"); - newfenv(L, io_pclose); /* create environment for 'popen' */ - lua_setfenv(L, -2); /* set fenv for 'popen' */ - lua_pop(L, 1); /* pop 'popen' */ - return 1; -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/llex.c b/desmume/src/windows/lua/lua-5.1.4/src/llex.c deleted file mode 100644 index 6dc319358..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/llex.c +++ /dev/null @@ -1,461 +0,0 @@ -/* -** $Id: llex.c,v 2.20.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lexical Analyzer -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include - -#define llex_c -#define LUA_CORE - -#include "lua.h" - -#include "ldo.h" -#include "llex.h" -#include "lobject.h" -#include "lparser.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "lzio.h" - - - -#define next(ls) (ls->current = zgetc(ls->z)) - - - - -#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') - - -/* ORDER RESERVED */ -const char *const luaX_tokens [] = { - "and", "break", "do", "else", "elseif", - "end", "false", "for", "function", "if", - "in", "local", "nil", "not", "or", "repeat", - "return", "then", "true", "until", "while", - "..", "...", "==", ">=", "<=", "~=", - "", "", "", "", - NULL -}; - - -#define save_and_next(ls) (save(ls, ls->current), next(ls)) - - -static void save (LexState *ls, int c) { - Mbuffer *b = ls->buff; - if (b->n + 1 > b->buffsize) { - size_t newsize; - if (b->buffsize >= MAX_SIZET/2) - luaX_lexerror(ls, "lexical element too long", 0); - newsize = b->buffsize * 2; - luaZ_resizebuffer(ls->L, b, newsize); - } - b->buffer[b->n++] = cast(char, c); -} - - -void luaX_init (lua_State *L) { - int i; - for (i=0; itsv.reserved = cast_byte(i+1); /* reserved word */ - } -} - - -#define MAXSRC 80 - - -const char *luaX_token2str (LexState *ls, int token) { - if (token < FIRST_RESERVED) { - lua_assert(token == cast(unsigned char, token)); - return (iscntrl(token)) ? luaO_pushfstring(ls->L, "char(%d)", token) : - luaO_pushfstring(ls->L, "%c", token); - } - else - return luaX_tokens[token-FIRST_RESERVED]; -} - - -static const char *txtToken (LexState *ls, int token) { - switch (token) { - case TK_NAME: - case TK_STRING: - case TK_NUMBER: - save(ls, '\0'); - return luaZ_buffer(ls->buff); - default: - return luaX_token2str(ls, token); - } -} - - -void luaX_lexerror (LexState *ls, const char *msg, int token) { - char buff[MAXSRC]; - luaO_chunkid(buff, getstr(ls->source), MAXSRC); - msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg); - if (token) - luaO_pushfstring(ls->L, "%s near " LUA_QS, msg, txtToken(ls, token)); - luaD_throw(ls->L, LUA_ERRSYNTAX); -} - - -void luaX_syntaxerror (LexState *ls, const char *msg) { - luaX_lexerror(ls, msg, ls->t.token); -} - - -TString *luaX_newstring (LexState *ls, const char *str, size_t l) { - lua_State *L = ls->L; - TString *ts = luaS_newlstr(L, str, l); - TValue *o = luaH_setstr(L, ls->fs->h, ts); /* entry for `str' */ - if (ttisnil(o)) - setbvalue(o, 1); /* make sure `str' will not be collected */ - return ts; -} - - -static void inclinenumber (LexState *ls) { - int old = ls->current; - lua_assert(currIsNewline(ls)); - next(ls); /* skip `\n' or `\r' */ - if (currIsNewline(ls) && ls->current != old) - next(ls); /* skip `\n\r' or `\r\n' */ - if (++ls->linenumber >= MAX_INT) - luaX_syntaxerror(ls, "chunk has too many lines"); -} - - -void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source) { - ls->decpoint = '.'; - ls->L = L; - ls->lookahead.token = TK_EOS; /* no look-ahead token */ - ls->z = z; - ls->fs = NULL; - ls->linenumber = 1; - ls->lastline = 1; - ls->source = source; - luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ - next(ls); /* read first char */ -} - - - -/* -** ======================================================= -** LEXICAL ANALYZER -** ======================================================= -*/ - - - -static int check_next (LexState *ls, const char *set) { - if (!strchr(set, ls->current)) - return 0; - save_and_next(ls); - return 1; -} - - -static void buffreplace (LexState *ls, char from, char to) { - size_t n = luaZ_bufflen(ls->buff); - char *p = luaZ_buffer(ls->buff); - while (n--) - if (p[n] == from) p[n] = to; -} - - -static void trydecpoint (LexState *ls, SemInfo *seminfo) { - /* format error: try to update decimal point separator */ - struct lconv *cv = localeconv(); - char old = ls->decpoint; - ls->decpoint = (cv ? cv->decimal_point[0] : '.'); - buffreplace(ls, old, ls->decpoint); /* try updated decimal separator */ - if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) { - /* format error with correct decimal point: no more options */ - buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */ - luaX_lexerror(ls, "malformed number", TK_NUMBER); - } -} - - -/* LUA_NUMBER */ -static void read_numeral (LexState *ls, SemInfo *seminfo) { - lua_assert(isdigit(ls->current)); - do { - save_and_next(ls); - } while (isdigit(ls->current) || ls->current == '.'); - if (check_next(ls, "Ee")) /* `E'? */ - check_next(ls, "+-"); /* optional exponent sign */ - while (isalnum(ls->current) || ls->current == '_') - save_and_next(ls); - save(ls, '\0'); - buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */ - if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) /* format error? */ - trydecpoint(ls, seminfo); /* try to update decimal point separator */ -} - - -static int skip_sep (LexState *ls) { - int count = 0; - int s = ls->current; - lua_assert(s == '[' || s == ']'); - save_and_next(ls); - while (ls->current == '=') { - save_and_next(ls); - count++; - } - return (ls->current == s) ? count : (-count) - 1; -} - - -static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { - int cont = 0; - (void)(cont); /* avoid warnings when `cont' is not used */ - save_and_next(ls); /* skip 2nd `[' */ - if (currIsNewline(ls)) /* string starts with a newline? */ - inclinenumber(ls); /* skip it */ - for (;;) { - switch (ls->current) { - case EOZ: - luaX_lexerror(ls, (seminfo) ? "unfinished long string" : - "unfinished long comment", TK_EOS); - break; /* to avoid warnings */ -#if defined(LUA_COMPAT_LSTR) - case '[': { - if (skip_sep(ls) == sep) { - save_and_next(ls); /* skip 2nd `[' */ - cont++; -#if LUA_COMPAT_LSTR == 1 - if (sep == 0) - luaX_lexerror(ls, "nesting of [[...]] is deprecated", '['); -#endif - } - break; - } -#endif - case ']': { - if (skip_sep(ls) == sep) { - save_and_next(ls); /* skip 2nd `]' */ -#if defined(LUA_COMPAT_LSTR) && LUA_COMPAT_LSTR == 2 - cont--; - if (sep == 0 && cont >= 0) break; -#endif - goto endloop; - } - break; - } - case '\n': - case '\r': { - save(ls, '\n'); - inclinenumber(ls); - if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ - break; - } - default: { - if (seminfo) save_and_next(ls); - else next(ls); - } - } - } endloop: - if (seminfo) - seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep), - luaZ_bufflen(ls->buff) - 2*(2 + sep)); -} - - -static void read_string (LexState *ls, int del, SemInfo *seminfo) { - save_and_next(ls); - while (ls->current != del) { - switch (ls->current) { - case EOZ: - luaX_lexerror(ls, "unfinished string", TK_EOS); - continue; /* to avoid warnings */ - case '\n': - case '\r': - luaX_lexerror(ls, "unfinished string", TK_STRING); - continue; /* to avoid warnings */ - case '\\': { - int c; - next(ls); /* do not save the `\' */ - switch (ls->current) { - case 'a': c = '\a'; break; - case 'b': c = '\b'; break; - case 'f': c = '\f'; break; - case 'n': c = '\n'; break; - case 'r': c = '\r'; break; - case 't': c = '\t'; break; - case 'v': c = '\v'; break; - case '\n': /* go through */ - case '\r': save(ls, '\n'); inclinenumber(ls); continue; - case EOZ: continue; /* will raise an error next loop */ - default: { - if (!isdigit(ls->current)) - save_and_next(ls); /* handles \\, \", \', and \? */ - else { /* \xxx */ - int i = 0; - c = 0; - do { - c = 10*c + (ls->current-'0'); - next(ls); - } while (++i<3 && isdigit(ls->current)); - if (c > UCHAR_MAX) - luaX_lexerror(ls, "escape sequence too large", TK_STRING); - save(ls, c); - } - continue; - } - } - save(ls, c); - next(ls); - continue; - } - default: - save_and_next(ls); - } - } - save_and_next(ls); /* skip delimiter */ - seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, - luaZ_bufflen(ls->buff) - 2); -} - - -static int llex (LexState *ls, SemInfo *seminfo) { - luaZ_resetbuffer(ls->buff); - for (;;) { - switch (ls->current) { - case '\n': - case '\r': { - inclinenumber(ls); - continue; - } - case '-': { - next(ls); - if (ls->current != '-') return '-'; - /* else is a comment */ - next(ls); - if (ls->current == '[') { - int sep = skip_sep(ls); - luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */ - if (sep >= 0) { - read_long_string(ls, NULL, sep); /* long comment */ - luaZ_resetbuffer(ls->buff); - continue; - } - } - /* else short comment */ - while (!currIsNewline(ls) && ls->current != EOZ) - next(ls); - continue; - } - case '[': { - int sep = skip_sep(ls); - if (sep >= 0) { - read_long_string(ls, seminfo, sep); - return TK_STRING; - } - else if (sep == -1) return '['; - else luaX_lexerror(ls, "invalid long string delimiter", TK_STRING); - } - case '=': { - next(ls); - if (ls->current != '=') return '='; - else { next(ls); return TK_EQ; } - } - case '<': { - next(ls); - if (ls->current != '=') return '<'; - else { next(ls); return TK_LE; } - } - case '>': { - next(ls); - if (ls->current != '=') return '>'; - else { next(ls); return TK_GE; } - } - case '~': { - next(ls); - if (ls->current != '=') return '~'; - else { next(ls); return TK_NE; } - } - case '"': - case '\'': { - read_string(ls, ls->current, seminfo); - return TK_STRING; - } - case '.': { - save_and_next(ls); - if (check_next(ls, ".")) { - if (check_next(ls, ".")) - return TK_DOTS; /* ... */ - else return TK_CONCAT; /* .. */ - } - else if (!isdigit(ls->current)) return '.'; - else { - read_numeral(ls, seminfo); - return TK_NUMBER; - } - } - case EOZ: { - return TK_EOS; - } - default: { - if (isspace(ls->current)) { - lua_assert(!currIsNewline(ls)); - next(ls); - continue; - } - else if (isdigit(ls->current)) { - read_numeral(ls, seminfo); - return TK_NUMBER; - } - else if (isalpha(ls->current) || ls->current == '_') { - /* identifier or reserved word */ - TString *ts; - do { - save_and_next(ls); - } while (isalnum(ls->current) || ls->current == '_'); - ts = luaX_newstring(ls, luaZ_buffer(ls->buff), - luaZ_bufflen(ls->buff)); - if (ts->tsv.reserved > 0) /* reserved word? */ - return ts->tsv.reserved - 1 + FIRST_RESERVED; - else { - seminfo->ts = ts; - return TK_NAME; - } - } - else { - int c = ls->current; - next(ls); - return c; /* single-char tokens (+ - / ...) */ - } - } - } - } -} - - -void luaX_next (LexState *ls) { - ls->lastline = ls->linenumber; - if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ - ls->t = ls->lookahead; /* use this one */ - ls->lookahead.token = TK_EOS; /* and discharge it */ - } - else - ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ -} - - -void luaX_lookahead (LexState *ls) { - lua_assert(ls->lookahead.token == TK_EOS); - ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/llex.h b/desmume/src/windows/lua/lua-5.1.4/src/llex.h deleted file mode 100644 index a9201cee4..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/llex.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -** $Id: llex.h,v 1.58.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lexical Analyzer -** See Copyright Notice in lua.h -*/ - -#ifndef llex_h -#define llex_h - -#include "lobject.h" -#include "lzio.h" - - -#define FIRST_RESERVED 257 - -/* maximum length of a reserved word */ -#define TOKEN_LEN (sizeof("function")/sizeof(char)) - - -/* -* WARNING: if you change the order of this enumeration, -* grep "ORDER RESERVED" -*/ -enum RESERVED { - /* terminal symbols denoted by reserved words */ - TK_AND = FIRST_RESERVED, TK_BREAK, - TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION, - TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, - TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE, - /* other terminal symbols */ - TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NUMBER, - TK_NAME, TK_STRING, TK_EOS -}; - -/* number of reserved words */ -#define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1)) - - -/* array with token `names' */ -LUAI_DATA const char *const luaX_tokens []; - - -typedef union { - lua_Number r; - TString *ts; -} SemInfo; /* semantics information */ - - -typedef struct Token { - int token; - SemInfo seminfo; -} Token; - - -typedef struct LexState { - int current; /* current character (charint) */ - int linenumber; /* input line counter */ - int lastline; /* line of last token `consumed' */ - Token t; /* current token */ - Token lookahead; /* look ahead token */ - struct FuncState *fs; /* `FuncState' is private to the parser */ - struct lua_State *L; - ZIO *z; /* input stream */ - Mbuffer *buff; /* buffer for tokens */ - TString *source; /* current source name */ - char decpoint; /* locale decimal point */ -} LexState; - - -LUAI_FUNC void luaX_init (lua_State *L); -LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, - TString *source); -LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l); -LUAI_FUNC void luaX_next (LexState *ls); -LUAI_FUNC void luaX_lookahead (LexState *ls); -LUAI_FUNC void luaX_lexerror (LexState *ls, const char *msg, int token); -LUAI_FUNC void luaX_syntaxerror (LexState *ls, const char *s); -LUAI_FUNC const char *luaX_token2str (LexState *ls, int token); - - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/llimits.h b/desmume/src/windows/lua/lua-5.1.4/src/llimits.h deleted file mode 100644 index ca8dcb722..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/llimits.h +++ /dev/null @@ -1,128 +0,0 @@ -/* -** $Id: llimits.h,v 1.69.1.1 2007/12/27 13:02:25 roberto Exp $ -** Limits, basic types, and some other `installation-dependent' definitions -** See Copyright Notice in lua.h -*/ - -#ifndef llimits_h -#define llimits_h - - -#include -#include - - -#include "lua.h" - - -typedef LUAI_UINT32 lu_int32; - -typedef LUAI_UMEM lu_mem; - -typedef LUAI_MEM l_mem; - - - -/* chars used as small naturals (so that `char' is reserved for characters) */ -typedef unsigned char lu_byte; - - -#define MAX_SIZET ((size_t)(~(size_t)0)-2) - -#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2) - - -#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */ - -/* -** conversion of pointer to integer -** this is for hashing only; there is no problem if the integer -** cannot hold the whole pointer value -*/ -#define IntPoint(p) ((unsigned int)(lu_mem)(p)) - - - -/* type to ensure maximum alignment */ -typedef LUAI_USER_ALIGNMENT_T L_Umaxalign; - - -/* result of a `usual argument conversion' over lua_Number */ -typedef LUAI_UACNUMBER l_uacNumber; - - -/* internal assertions for in-house debugging */ -#ifdef lua_assert - -#define check_exp(c,e) (lua_assert(c), (e)) -#define api_check(l,e) lua_assert(e) - -#else - -#define lua_assert(c) ((void)0) -#define check_exp(c,e) (e) -#define api_check luai_apicheck - -#endif - - -#ifndef UNUSED -#define UNUSED(x) ((void)(x)) /* to avoid warnings */ -#endif - - -#ifndef cast -#define cast(t, exp) ((t)(exp)) -#endif - -#define cast_byte(i) cast(lu_byte, (i)) -#define cast_num(i) cast(lua_Number, (i)) -#define cast_int(i) cast(int, (i)) - - - -/* -** type for virtual-machine instructions -** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h) -*/ -typedef lu_int32 Instruction; - - - -/* maximum stack for a Lua function */ -#define MAXSTACK 250 - - - -/* minimum size for the string table (must be power of 2) */ -#ifndef MINSTRTABSIZE -#define MINSTRTABSIZE 32 -#endif - - -/* minimum size for string buffer */ -#ifndef LUA_MINBUFFER -#define LUA_MINBUFFER 32 -#endif - - -#ifndef lua_lock -#define lua_lock(L) ((void) 0) -#define lua_unlock(L) ((void) 0) -#endif - -#ifndef luai_threadyield -#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} -#endif - - -/* -** macro to control inclusion of some hard tests on stack reallocation -*/ -#ifndef HARDSTACKTESTS -#define condhardstacktests(x) ((void)0) -#else -#define condhardstacktests(x) x -#endif - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lmathlib.c b/desmume/src/windows/lua/lua-5.1.4/src/lmathlib.c deleted file mode 100644 index 441fbf736..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lmathlib.c +++ /dev/null @@ -1,263 +0,0 @@ -/* -** $Id: lmathlib.c,v 1.67.1.1 2007/12/27 13:02:25 roberto Exp $ -** Standard mathematical library -** See Copyright Notice in lua.h -*/ - - -#include -#include - -#define lmathlib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - -#undef PI -#define PI (3.14159265358979323846) -#define RADIANS_PER_DEGREE (PI/180.0) - - - -static int math_abs (lua_State *L) { - lua_pushnumber(L, fabs(luaL_checknumber(L, 1))); - return 1; -} - -static int math_sin (lua_State *L) { - lua_pushnumber(L, sin(luaL_checknumber(L, 1))); - return 1; -} - -static int math_sinh (lua_State *L) { - lua_pushnumber(L, sinh(luaL_checknumber(L, 1))); - return 1; -} - -static int math_cos (lua_State *L) { - lua_pushnumber(L, cos(luaL_checknumber(L, 1))); - return 1; -} - -static int math_cosh (lua_State *L) { - lua_pushnumber(L, cosh(luaL_checknumber(L, 1))); - return 1; -} - -static int math_tan (lua_State *L) { - lua_pushnumber(L, tan(luaL_checknumber(L, 1))); - return 1; -} - -static int math_tanh (lua_State *L) { - lua_pushnumber(L, tanh(luaL_checknumber(L, 1))); - return 1; -} - -static int math_asin (lua_State *L) { - lua_pushnumber(L, asin(luaL_checknumber(L, 1))); - return 1; -} - -static int math_acos (lua_State *L) { - lua_pushnumber(L, acos(luaL_checknumber(L, 1))); - return 1; -} - -static int math_atan (lua_State *L) { - lua_pushnumber(L, atan(luaL_checknumber(L, 1))); - return 1; -} - -static int math_atan2 (lua_State *L) { - lua_pushnumber(L, atan2(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); - return 1; -} - -static int math_ceil (lua_State *L) { - lua_pushnumber(L, ceil(luaL_checknumber(L, 1))); - return 1; -} - -static int math_floor (lua_State *L) { - lua_pushnumber(L, floor(luaL_checknumber(L, 1))); - return 1; -} - -static int math_fmod (lua_State *L) { - lua_pushnumber(L, fmod(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); - return 1; -} - -static int math_modf (lua_State *L) { - double ip; - double fp = modf(luaL_checknumber(L, 1), &ip); - lua_pushnumber(L, ip); - lua_pushnumber(L, fp); - return 2; -} - -static int math_sqrt (lua_State *L) { - lua_pushnumber(L, sqrt(luaL_checknumber(L, 1))); - return 1; -} - -static int math_pow (lua_State *L) { - lua_pushnumber(L, pow(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); - return 1; -} - -static int math_log (lua_State *L) { - lua_pushnumber(L, log(luaL_checknumber(L, 1))); - return 1; -} - -static int math_log10 (lua_State *L) { - lua_pushnumber(L, log10(luaL_checknumber(L, 1))); - return 1; -} - -static int math_exp (lua_State *L) { - lua_pushnumber(L, exp(luaL_checknumber(L, 1))); - return 1; -} - -static int math_deg (lua_State *L) { - lua_pushnumber(L, luaL_checknumber(L, 1)/RADIANS_PER_DEGREE); - return 1; -} - -static int math_rad (lua_State *L) { - lua_pushnumber(L, luaL_checknumber(L, 1)*RADIANS_PER_DEGREE); - return 1; -} - -static int math_frexp (lua_State *L) { - int e; - lua_pushnumber(L, frexp(luaL_checknumber(L, 1), &e)); - lua_pushinteger(L, e); - return 2; -} - -static int math_ldexp (lua_State *L) { - lua_pushnumber(L, ldexp(luaL_checknumber(L, 1), luaL_checkint(L, 2))); - return 1; -} - - - -static int math_min (lua_State *L) { - int n = lua_gettop(L); /* number of arguments */ - lua_Number dmin = luaL_checknumber(L, 1); - int i; - for (i=2; i<=n; i++) { - lua_Number d = luaL_checknumber(L, i); - if (d < dmin) - dmin = d; - } - lua_pushnumber(L, dmin); - return 1; -} - - -static int math_max (lua_State *L) { - int n = lua_gettop(L); /* number of arguments */ - lua_Number dmax = luaL_checknumber(L, 1); - int i; - for (i=2; i<=n; i++) { - lua_Number d = luaL_checknumber(L, i); - if (d > dmax) - dmax = d; - } - lua_pushnumber(L, dmax); - return 1; -} - - -static int math_random (lua_State *L) { - /* the `%' avoids the (rare) case of r==1, and is needed also because on - some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */ - lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX; - switch (lua_gettop(L)) { /* check number of arguments */ - case 0: { /* no arguments */ - lua_pushnumber(L, r); /* Number between 0 and 1 */ - break; - } - case 1: { /* only upper limit */ - int u = luaL_checkint(L, 1); - luaL_argcheck(L, 1<=u, 1, "interval is empty"); - lua_pushnumber(L, floor(r*u)+1); /* int between 1 and `u' */ - break; - } - case 2: { /* lower and upper limits */ - int l = luaL_checkint(L, 1); - int u = luaL_checkint(L, 2); - luaL_argcheck(L, l<=u, 2, "interval is empty"); - lua_pushnumber(L, floor(r*(u-l+1))+l); /* int between `l' and `u' */ - break; - } - default: return luaL_error(L, "wrong number of arguments"); - } - return 1; -} - - -static int math_randomseed (lua_State *L) { - srand(luaL_checkint(L, 1)); - return 0; -} - - -static const luaL_Reg mathlib[] = { - {"abs", math_abs}, - {"acos", math_acos}, - {"asin", math_asin}, - {"atan2", math_atan2}, - {"atan", math_atan}, - {"ceil", math_ceil}, - {"cosh", math_cosh}, - {"cos", math_cos}, - {"deg", math_deg}, - {"exp", math_exp}, - {"floor", math_floor}, - {"fmod", math_fmod}, - {"frexp", math_frexp}, - {"ldexp", math_ldexp}, - {"log10", math_log10}, - {"log", math_log}, - {"max", math_max}, - {"min", math_min}, - {"modf", math_modf}, - {"pow", math_pow}, - {"rad", math_rad}, - {"random", math_random}, - {"randomseed", math_randomseed}, - {"sinh", math_sinh}, - {"sin", math_sin}, - {"sqrt", math_sqrt}, - {"tanh", math_tanh}, - {"tan", math_tan}, - {NULL, NULL} -}; - - -/* -** Open math library -*/ -LUALIB_API int luaopen_math (lua_State *L) { - luaL_register(L, LUA_MATHLIBNAME, mathlib); - lua_pushnumber(L, PI); - lua_setfield(L, -2, "pi"); - lua_pushnumber(L, HUGE_VAL); - lua_setfield(L, -2, "huge"); -#if defined(LUA_COMPAT_MOD) - lua_getfield(L, -1, "fmod"); - lua_setfield(L, -2, "mod"); -#endif - return 1; -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lmem.c b/desmume/src/windows/lua/lua-5.1.4/src/lmem.c deleted file mode 100644 index ae7d8c965..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lmem.c +++ /dev/null @@ -1,86 +0,0 @@ -/* -** $Id: lmem.c,v 1.70.1.1 2007/12/27 13:02:25 roberto Exp $ -** Interface to Memory Manager -** See Copyright Notice in lua.h -*/ - - -#include - -#define lmem_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" - - - -/* -** About the realloc function: -** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize); -** (`osize' is the old size, `nsize' is the new size) -** -** Lua ensures that (ptr == NULL) iff (osize == 0). -** -** * frealloc(ud, NULL, 0, x) creates a new block of size `x' -** -** * frealloc(ud, p, x, 0) frees the block `p' -** (in this specific case, frealloc must return NULL). -** particularly, frealloc(ud, NULL, 0, 0) does nothing -** (which is equivalent to free(NULL) in ANSI C) -** -** frealloc returns NULL if it cannot create or reallocate the area -** (any reallocation to an equal or smaller size cannot fail!) -*/ - - - -#define MINSIZEARRAY 4 - - -void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems, - int limit, const char *errormsg) { - void *newblock; - int newsize; - if (*size >= limit/2) { /* cannot double it? */ - if (*size >= limit) /* cannot grow even a little? */ - luaG_runerror(L, errormsg); - newsize = limit; /* still have at least one free place */ - } - else { - newsize = (*size)*2; - if (newsize < MINSIZEARRAY) - newsize = MINSIZEARRAY; /* minimum size */ - } - newblock = luaM_reallocv(L, block, *size, newsize, size_elems); - *size = newsize; /* update only when everything else is OK */ - return newblock; -} - - -void *luaM_toobig (lua_State *L) { - luaG_runerror(L, "memory allocation error: block too big"); - return NULL; /* to avoid warnings */ -} - - - -/* -** generic allocation routine. -*/ -void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { - global_State *g = G(L); - lua_assert((osize == 0) == (block == NULL)); - block = (*g->frealloc)(g->ud, block, osize, nsize); - if (block == NULL && nsize > 0) - luaD_throw(L, LUA_ERRMEM); - lua_assert((nsize == 0) == (block == NULL)); - g->totalbytes = (g->totalbytes - osize) + nsize; - return block; -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lmem.h b/desmume/src/windows/lua/lua-5.1.4/src/lmem.h deleted file mode 100644 index 7c2dcb322..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lmem.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -** $Id: lmem.h,v 1.31.1.1 2007/12/27 13:02:25 roberto Exp $ -** Interface to Memory Manager -** See Copyright Notice in lua.h -*/ - -#ifndef lmem_h -#define lmem_h - - -#include - -#include "llimits.h" -#include "lua.h" - -#define MEMERRMSG "not enough memory" - - -#define luaM_reallocv(L,b,on,n,e) \ - ((cast(size_t, (n)+1) <= MAX_SIZET/(e)) ? /* +1 to avoid warnings */ \ - luaM_realloc_(L, (b), (on)*(e), (n)*(e)) : \ - luaM_toobig(L)) - -#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0) -#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0) -#define luaM_freearray(L, b, n, t) luaM_reallocv(L, (b), n, 0, sizeof(t)) - -#define luaM_malloc(L,t) luaM_realloc_(L, NULL, 0, (t)) -#define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t))) -#define luaM_newvector(L,n,t) \ - cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t))) - -#define luaM_growvector(L,v,nelems,size,t,limit,e) \ - if ((nelems)+1 > (size)) \ - ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e))) - -#define luaM_reallocvector(L, v,oldn,n,t) \ - ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t)))) - - -LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, - size_t size); -LUAI_FUNC void *luaM_toobig (lua_State *L); -LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size, - size_t size_elem, int limit, - const char *errormsg); - -#endif - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/loadlib.c b/desmume/src/windows/lua/lua-5.1.4/src/loadlib.c deleted file mode 100644 index 0d401eba1..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/loadlib.c +++ /dev/null @@ -1,666 +0,0 @@ -/* -** $Id: loadlib.c,v 1.52.1.3 2008/08/06 13:29:28 roberto Exp $ -** Dynamic library loader for Lua -** See Copyright Notice in lua.h -** -** This module contains an implementation of loadlib for Unix systems -** that have dlfcn, an implementation for Darwin (Mac OS X), an -** implementation for Windows, and a stub for other systems. -*/ - - -#include -#include - - -#define loadlib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - -/* prefix for open functions in C libraries */ -#define LUA_POF "luaopen_" - -/* separator for open functions in C libraries */ -#define LUA_OFSEP "_" - - -#define LIBPREFIX "LOADLIB: " - -#define POF LUA_POF -#define LIB_FAIL "open" - - -/* error codes for ll_loadfunc */ -#define ERRLIB 1 -#define ERRFUNC 2 - -#define setprogdir(L) ((void)0) - - -static void ll_unloadlib (void *lib); -static void *ll_load (lua_State *L, const char *path); -static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym); - - - -#if defined(LUA_DL_DLOPEN) -/* -** {======================================================================== -** This is an implementation of loadlib based on the dlfcn interface. -** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD, -** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least -** as an emulation layer on top of native functions. -** ========================================================================= -*/ - -#include - -static void ll_unloadlib (void *lib) { - dlclose(lib); -} - - -static void *ll_load (lua_State *L, const char *path) { - void *lib = dlopen(path, RTLD_NOW); - if (lib == NULL) lua_pushstring(L, dlerror()); - return lib; -} - - -static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { - lua_CFunction f = (lua_CFunction)dlsym(lib, sym); - if (f == NULL) lua_pushstring(L, dlerror()); - return f; -} - -/* }====================================================== */ - - - -#elif defined(LUA_DL_DLL) -/* -** {====================================================================== -** This is an implementation of loadlib for Windows using native functions. -** ======================================================================= -*/ - -#include - - -#undef setprogdir - -static void setprogdir (lua_State *L) { - char buff[MAX_PATH + 1]; - char *lb; - DWORD nsize = sizeof(buff)/sizeof(char); - DWORD n = GetModuleFileNameA(NULL, buff, nsize); - if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) - luaL_error(L, "unable to get ModuleFileName"); - else { - *lb = '\0'; - luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff); - lua_remove(L, -2); /* remove original string */ - } -} - - -static void pusherror (lua_State *L) { - int error = GetLastError(); - char buffer[128]; - if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, error, 0, buffer, sizeof(buffer), NULL)) - lua_pushstring(L, buffer); - else - lua_pushfstring(L, "system error %d\n", error); -} - -static void ll_unloadlib (void *lib) { - FreeLibrary((HINSTANCE)lib); -} - - -static void *ll_load (lua_State *L, const char *path) { - HINSTANCE lib = LoadLibraryA(path); - if (lib == NULL) pusherror(L); - return lib; -} - - -static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { - lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym); - if (f == NULL) pusherror(L); - return f; -} - -/* }====================================================== */ - - - -#elif defined(LUA_DL_DYLD) -/* -** {====================================================================== -** Native Mac OS X / Darwin Implementation -** ======================================================================= -*/ - -#include - - -/* Mac appends a `_' before C function names */ -#undef POF -#define POF "_" LUA_POF - - -static void pusherror (lua_State *L) { - const char *err_str; - const char *err_file; - NSLinkEditErrors err; - int err_num; - NSLinkEditError(&err, &err_num, &err_file, &err_str); - lua_pushstring(L, err_str); -} - - -static const char *errorfromcode (NSObjectFileImageReturnCode ret) { - switch (ret) { - case NSObjectFileImageInappropriateFile: - return "file is not a bundle"; - case NSObjectFileImageArch: - return "library is for wrong CPU type"; - case NSObjectFileImageFormat: - return "bad format"; - case NSObjectFileImageAccess: - return "cannot access file"; - case NSObjectFileImageFailure: - default: - return "unable to load library"; - } -} - - -static void ll_unloadlib (void *lib) { - NSUnLinkModule((NSModule)lib, NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES); -} - - -static void *ll_load (lua_State *L, const char *path) { - NSObjectFileImage img; - NSObjectFileImageReturnCode ret; - /* this would be a rare case, but prevents crashing if it happens */ - if(!_dyld_present()) { - lua_pushliteral(L, "dyld not present"); - return NULL; - } - ret = NSCreateObjectFileImageFromFile(path, &img); - if (ret == NSObjectFileImageSuccess) { - NSModule mod = NSLinkModule(img, path, NSLINKMODULE_OPTION_PRIVATE | - NSLINKMODULE_OPTION_RETURN_ON_ERROR); - NSDestroyObjectFileImage(img); - if (mod == NULL) pusherror(L); - return mod; - } - lua_pushstring(L, errorfromcode(ret)); - return NULL; -} - - -static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { - NSSymbol nss = NSLookupSymbolInModule((NSModule)lib, sym); - if (nss == NULL) { - lua_pushfstring(L, "symbol " LUA_QS " not found", sym); - return NULL; - } - return (lua_CFunction)NSAddressOfSymbol(nss); -} - -/* }====================================================== */ - - - -#else -/* -** {====================================================== -** Fallback for other systems -** ======================================================= -*/ - -#undef LIB_FAIL -#define LIB_FAIL "absent" - - -#define DLMSG "dynamic libraries not enabled; check your Lua installation" - - -static void ll_unloadlib (void *lib) { - (void)lib; /* to avoid warnings */ -} - - -static void *ll_load (lua_State *L, const char *path) { - (void)path; /* to avoid warnings */ - lua_pushliteral(L, DLMSG); - return NULL; -} - - -static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { - (void)lib; (void)sym; /* to avoid warnings */ - lua_pushliteral(L, DLMSG); - return NULL; -} - -/* }====================================================== */ -#endif - - - -static void **ll_register (lua_State *L, const char *path) { - void **plib; - lua_pushfstring(L, "%s%s", LIBPREFIX, path); - lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */ - if (!lua_isnil(L, -1)) /* is there an entry? */ - plib = (void **)lua_touserdata(L, -1); - else { /* no entry yet; create one */ - lua_pop(L, 1); - plib = (void **)lua_newuserdata(L, sizeof(const void *)); - *plib = NULL; - luaL_getmetatable(L, "_LOADLIB"); - lua_setmetatable(L, -2); - lua_pushfstring(L, "%s%s", LIBPREFIX, path); - lua_pushvalue(L, -2); - lua_settable(L, LUA_REGISTRYINDEX); - } - return plib; -} - - -/* -** __gc tag method: calls library's `ll_unloadlib' function with the lib -** handle -*/ -static int gctm (lua_State *L) { - void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB"); - if (*lib) ll_unloadlib(*lib); - *lib = NULL; /* mark library as closed */ - return 0; -} - - -static int ll_loadfunc (lua_State *L, const char *path, const char *sym) { - void **reg = ll_register(L, path); - if (*reg == NULL) *reg = ll_load(L, path); - if (*reg == NULL) - return ERRLIB; /* unable to load library */ - else { - lua_CFunction f = ll_sym(L, *reg, sym); - if (f == NULL) - return ERRFUNC; /* unable to find function */ - lua_pushcfunction(L, f); - return 0; /* return function */ - } -} - - -static int ll_loadlib (lua_State *L) { - const char *path = luaL_checkstring(L, 1); - const char *init = luaL_checkstring(L, 2); - int stat = ll_loadfunc(L, path, init); - if (stat == 0) /* no errors? */ - return 1; /* return the loaded function */ - else { /* error; error message is on stack top */ - lua_pushnil(L); - lua_insert(L, -2); - lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); - return 3; /* return nil, error message, and where */ - } -} - - - -/* -** {====================================================== -** 'require' function -** ======================================================= -*/ - - -static int readable (const char *filename) { - FILE *f = fopen(filename, "r"); /* try to open file */ - if (f == NULL) return 0; /* open failed */ - fclose(f); - return 1; -} - - -static const char *pushnexttemplate (lua_State *L, const char *path) { - const char *l; - while (*path == *LUA_PATHSEP) path++; /* skip separators */ - if (*path == '\0') return NULL; /* no more templates */ - l = strchr(path, *LUA_PATHSEP); /* find next separator */ - if (l == NULL) l = path + strlen(path); - lua_pushlstring(L, path, l - path); /* template */ - return l; -} - - -static const char *findfile (lua_State *L, const char *name, - const char *pname) { - const char *path; - name = luaL_gsub(L, name, ".", LUA_DIRSEP); - lua_getfield(L, LUA_ENVIRONINDEX, pname); - path = lua_tostring(L, -1); - if (path == NULL) - luaL_error(L, LUA_QL("package.%s") " must be a string", pname); - lua_pushliteral(L, ""); /* error accumulator */ - while ((path = pushnexttemplate(L, path)) != NULL) { - const char *filename; - filename = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name); - lua_remove(L, -2); /* remove path template */ - if (readable(filename)) /* does file exist and is readable? */ - return filename; /* return that file name */ - lua_pushfstring(L, "\n\tno file " LUA_QS, filename); - lua_remove(L, -2); /* remove file name */ - lua_concat(L, 2); /* add entry to possible error message */ - } - return NULL; /* not found */ -} - - -static void loaderror (lua_State *L, const char *filename) { - luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s", - lua_tostring(L, 1), filename, lua_tostring(L, -1)); -} - - -static int loader_Lua (lua_State *L) { - const char *filename; - const char *name = luaL_checkstring(L, 1); - filename = findfile(L, name, "path"); - if (filename == NULL) return 1; /* library not found in this path */ - if (luaL_loadfile(L, filename) != 0) - loaderror(L, filename); - return 1; /* library loaded successfully */ -} - - -static const char *mkfuncname (lua_State *L, const char *modname) { - const char *funcname; - const char *mark = strchr(modname, *LUA_IGMARK); - if (mark) modname = mark + 1; - funcname = luaL_gsub(L, modname, ".", LUA_OFSEP); - funcname = lua_pushfstring(L, POF"%s", funcname); - lua_remove(L, -2); /* remove 'gsub' result */ - return funcname; -} - - -static int loader_C (lua_State *L) { - const char *funcname; - const char *name = luaL_checkstring(L, 1); - const char *filename = findfile(L, name, "cpath"); - if (filename == NULL) return 1; /* library not found in this path */ - funcname = mkfuncname(L, name); - if (ll_loadfunc(L, filename, funcname) != 0) - loaderror(L, filename); - return 1; /* library loaded successfully */ -} - - -static int loader_Croot (lua_State *L) { - const char *funcname; - const char *filename; - const char *name = luaL_checkstring(L, 1); - const char *p = strchr(name, '.'); - int stat; - if (p == NULL) return 0; /* is root */ - lua_pushlstring(L, name, p - name); - filename = findfile(L, lua_tostring(L, -1), "cpath"); - if (filename == NULL) return 1; /* root not found */ - funcname = mkfuncname(L, name); - if ((stat = ll_loadfunc(L, filename, funcname)) != 0) { - if (stat != ERRFUNC) loaderror(L, filename); /* real error */ - lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS, - name, filename); - return 1; /* function not found */ - } - return 1; -} - - -static int loader_preload (lua_State *L) { - const char *name = luaL_checkstring(L, 1); - lua_getfield(L, LUA_ENVIRONINDEX, "preload"); - if (!lua_istable(L, -1)) - luaL_error(L, LUA_QL("package.preload") " must be a table"); - lua_getfield(L, -1, name); - if (lua_isnil(L, -1)) /* not found? */ - lua_pushfstring(L, "\n\tno field package.preload['%s']", name); - return 1; -} - - -static const int sentinel_ = 0; -#define sentinel ((void *)&sentinel_) - - -static int ll_require (lua_State *L) { - const char *name = luaL_checkstring(L, 1); - int i; - lua_settop(L, 1); /* _LOADED table will be at index 2 */ - lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); - lua_getfield(L, 2, name); - if (lua_toboolean(L, -1)) { /* is it there? */ - if (lua_touserdata(L, -1) == sentinel) /* check loops */ - luaL_error(L, "loop or previous error loading module " LUA_QS, name); - return 1; /* package is already loaded */ - } - /* else must load it; iterate over available loaders */ - lua_getfield(L, LUA_ENVIRONINDEX, "loaders"); - if (!lua_istable(L, -1)) - luaL_error(L, LUA_QL("package.loaders") " must be a table"); - lua_pushliteral(L, ""); /* error message accumulator */ - for (i=1; ; i++) { - lua_rawgeti(L, -2, i); /* get a loader */ - if (lua_isnil(L, -1)) - luaL_error(L, "module " LUA_QS " not found:%s", - name, lua_tostring(L, -2)); - lua_pushstring(L, name); - lua_call(L, 1, 1); /* call it */ - if (lua_isfunction(L, -1)) /* did it find module? */ - break; /* module loaded successfully */ - else if (lua_isstring(L, -1)) /* loader returned error message? */ - lua_concat(L, 2); /* accumulate it */ - else - lua_pop(L, 1); - } - lua_pushlightuserdata(L, sentinel); - lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */ - lua_pushstring(L, name); /* pass name as argument to module */ - lua_call(L, 1, 1); /* run loaded module */ - if (!lua_isnil(L, -1)) /* non-nil return? */ - lua_setfield(L, 2, name); /* _LOADED[name] = returned value */ - lua_getfield(L, 2, name); - if (lua_touserdata(L, -1) == sentinel) { /* module did not set a value? */ - lua_pushboolean(L, 1); /* use true as result */ - lua_pushvalue(L, -1); /* extra copy to be returned */ - lua_setfield(L, 2, name); /* _LOADED[name] = true */ - } - return 1; -} - -/* }====================================================== */ - - - -/* -** {====================================================== -** 'module' function -** ======================================================= -*/ - - -static void setfenv (lua_State *L) { - lua_Debug ar; - if (lua_getstack(L, 1, &ar) == 0 || - lua_getinfo(L, "f", &ar) == 0 || /* get calling function */ - lua_iscfunction(L, -1)) - luaL_error(L, LUA_QL("module") " not called from a Lua function"); - lua_pushvalue(L, -2); - lua_setfenv(L, -2); - lua_pop(L, 1); -} - - -static void dooptions (lua_State *L, int n) { - int i; - for (i = 2; i <= n; i++) { - lua_pushvalue(L, i); /* get option (a function) */ - lua_pushvalue(L, -2); /* module */ - lua_call(L, 1, 0); - } -} - - -static void modinit (lua_State *L, const char *modname) { - const char *dot; - lua_pushvalue(L, -1); - lua_setfield(L, -2, "_M"); /* module._M = module */ - lua_pushstring(L, modname); - lua_setfield(L, -2, "_NAME"); - dot = strrchr(modname, '.'); /* look for last dot in module name */ - if (dot == NULL) dot = modname; - else dot++; - /* set _PACKAGE as package name (full module name minus last part) */ - lua_pushlstring(L, modname, dot - modname); - lua_setfield(L, -2, "_PACKAGE"); -} - - -static int ll_module (lua_State *L) { - const char *modname = luaL_checkstring(L, 1); - int loaded = lua_gettop(L) + 1; /* index of _LOADED table */ - lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); - lua_getfield(L, loaded, modname); /* get _LOADED[modname] */ - if (!lua_istable(L, -1)) { /* not found? */ - lua_pop(L, 1); /* remove previous result */ - /* try global variable (and create one if it does not exist) */ - if (luaL_findtable(L, LUA_GLOBALSINDEX, modname, 1) != NULL) - return luaL_error(L, "name conflict for module " LUA_QS, modname); - lua_pushvalue(L, -1); - lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */ - } - /* check whether table already has a _NAME field */ - lua_getfield(L, -1, "_NAME"); - if (!lua_isnil(L, -1)) /* is table an initialized module? */ - lua_pop(L, 1); - else { /* no; initialize it */ - lua_pop(L, 1); - modinit(L, modname); - } - lua_pushvalue(L, -1); - setfenv(L); - dooptions(L, loaded - 1); - return 0; -} - - -static int ll_seeall (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - if (!lua_getmetatable(L, 1)) { - lua_createtable(L, 0, 1); /* create new metatable */ - lua_pushvalue(L, -1); - lua_setmetatable(L, 1); - } - lua_pushvalue(L, LUA_GLOBALSINDEX); - lua_setfield(L, -2, "__index"); /* mt.__index = _G */ - return 0; -} - - -/* }====================================================== */ - - - -/* auxiliary mark (for internal use) */ -#define AUXMARK "\1" - -static void setpath (lua_State *L, const char *fieldname, const char *envname, - const char *def) { - const char *path = getenv(envname); - if (path == NULL) /* no environment variable? */ - lua_pushstring(L, def); /* use default */ - else { - /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */ - path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP, - LUA_PATHSEP AUXMARK LUA_PATHSEP); - luaL_gsub(L, path, AUXMARK, def); - lua_remove(L, -2); - } - setprogdir(L); - lua_setfield(L, -2, fieldname); -} - - -static const luaL_Reg pk_funcs[] = { - {"loadlib", ll_loadlib}, - {"seeall", ll_seeall}, - {NULL, NULL} -}; - - -static const luaL_Reg ll_funcs[] = { - {"module", ll_module}, - {"require", ll_require}, - {NULL, NULL} -}; - - -static const lua_CFunction loaders[] = - {loader_preload, loader_Lua, loader_C, loader_Croot, NULL}; - - -LUALIB_API int luaopen_package (lua_State *L) { - int i; - /* create new type _LOADLIB */ - luaL_newmetatable(L, "_LOADLIB"); - lua_pushcfunction(L, gctm); - lua_setfield(L, -2, "__gc"); - /* create `package' table */ - luaL_register(L, LUA_LOADLIBNAME, pk_funcs); -#if defined(LUA_COMPAT_LOADLIB) - lua_getfield(L, -1, "loadlib"); - lua_setfield(L, LUA_GLOBALSINDEX, "loadlib"); -#endif - lua_pushvalue(L, -1); - lua_replace(L, LUA_ENVIRONINDEX); - /* create `loaders' table */ - lua_createtable(L, 0, sizeof(loaders)/sizeof(loaders[0]) - 1); - /* fill it with pre-defined loaders */ - for (i=0; loaders[i] != NULL; i++) { - lua_pushcfunction(L, loaders[i]); - lua_rawseti(L, -2, i+1); - } - lua_setfield(L, -2, "loaders"); /* put it in field `loaders' */ - setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT); /* set field `path' */ - setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT); /* set field `cpath' */ - /* store config information */ - lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATHSEP "\n" LUA_PATH_MARK "\n" - LUA_EXECDIR "\n" LUA_IGMARK); - lua_setfield(L, -2, "config"); - /* set field `loaded' */ - luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 2); - lua_setfield(L, -2, "loaded"); - /* set field `preload' */ - lua_newtable(L); - lua_setfield(L, -2, "preload"); - lua_pushvalue(L, LUA_GLOBALSINDEX); - luaL_register(L, NULL, ll_funcs); /* open lib into global table */ - lua_pop(L, 1); - return 1; /* return 'package' table */ -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lobject.c b/desmume/src/windows/lua/lua-5.1.4/src/lobject.c deleted file mode 100644 index 4ff50732a..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lobject.c +++ /dev/null @@ -1,214 +0,0 @@ -/* -** $Id: lobject.c,v 2.22.1.1 2007/12/27 13:02:25 roberto Exp $ -** Some generic functions over Lua objects -** See Copyright Notice in lua.h -*/ - -#include -#include -#include -#include -#include - -#define lobject_c -#define LUA_CORE - -#include "lua.h" - -#include "ldo.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" -#include "lstring.h" -#include "lvm.h" - - - -const TValue luaO_nilobject_ = {{NULL}, LUA_TNIL}; - - -/* -** converts an integer to a "floating point byte", represented as -** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if -** eeeee != 0 and (xxx) otherwise. -*/ -int luaO_int2fb (unsigned int x) { - int e = 0; /* expoent */ - while (x >= 16) { - x = (x+1) >> 1; - e++; - } - if (x < 8) return x; - else return ((e+1) << 3) | (cast_int(x) - 8); -} - - -/* converts back */ -int luaO_fb2int (int x) { - int e = (x >> 3) & 31; - if (e == 0) return x; - else return ((x & 7)+8) << (e - 1); -} - - -int luaO_log2 (unsigned int x) { - static const lu_byte log_2[256] = { - 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, - 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 - }; - int l = -1; - while (x >= 256) { l += 8; x >>= 8; } - return l + log_2[x]; - -} - - -int luaO_rawequalObj (const TValue *t1, const TValue *t2) { - if (ttype(t1) != ttype(t2)) return 0; - else switch (ttype(t1)) { - case LUA_TNIL: - return 1; - case LUA_TNUMBER: - return luai_numeq(nvalue(t1), nvalue(t2)); - case LUA_TBOOLEAN: - return bvalue(t1) == bvalue(t2); /* boolean true must be 1 !! */ - case LUA_TLIGHTUSERDATA: - return pvalue(t1) == pvalue(t2); - default: - lua_assert(iscollectable(t1)); - return gcvalue(t1) == gcvalue(t2); - } -} - - -int luaO_str2d (const char *s, lua_Number *result) { - char *endptr; - *result = lua_str2number(s, &endptr); - if (endptr == s) return 0; /* conversion failed */ - if (*endptr == 'x' || *endptr == 'X') /* maybe an hexadecimal constant? */ - *result = cast_num(strtoul(s, &endptr, 16)); - if (*endptr == '\0') return 1; /* most common case */ - while (isspace(cast(unsigned char, *endptr))) endptr++; - if (*endptr != '\0') return 0; /* invalid trailing characters? */ - return 1; -} - - - -static void pushstr (lua_State *L, const char *str) { - setsvalue2s(L, L->top, luaS_new(L, str)); - incr_top(L); -} - - -/* this function handles only `%d', `%c', %f, %p, and `%s' formats */ -const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { - int n = 1; - pushstr(L, ""); - for (;;) { - const char *e = strchr(fmt, '%'); - if (e == NULL) break; - setsvalue2s(L, L->top, luaS_newlstr(L, fmt, e-fmt)); - incr_top(L); - switch (*(e+1)) { - case 's': { - const char *s = va_arg(argp, char *); - if (s == NULL) s = "(null)"; - pushstr(L, s); - break; - } - case 'c': { - char buff[2]; - buff[0] = cast(char, va_arg(argp, int)); - buff[1] = '\0'; - pushstr(L, buff); - break; - } - case 'd': { - setnvalue(L->top, cast_num(va_arg(argp, int))); - incr_top(L); - break; - } - case 'f': { - setnvalue(L->top, cast_num(va_arg(argp, l_uacNumber))); - incr_top(L); - break; - } - case 'p': { - char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */ - sprintf(buff, "%p", va_arg(argp, void *)); - pushstr(L, buff); - break; - } - case '%': { - pushstr(L, "%"); - break; - } - default: { - char buff[3]; - buff[0] = '%'; - buff[1] = *(e+1); - buff[2] = '\0'; - pushstr(L, buff); - break; - } - } - n += 2; - fmt = e+2; - } - pushstr(L, fmt); - luaV_concat(L, n+1, cast_int(L->top - L->base) - 1); - L->top -= n; - return svalue(L->top - 1); -} - - -const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) { - const char *msg; - va_list argp; - va_start(argp, fmt); - msg = luaO_pushvfstring(L, fmt, argp); - va_end(argp); - return msg; -} - - -void luaO_chunkid (char *out, const char *source, size_t bufflen) { - if (*source == '=') { - strncpy(out, source+1, bufflen); /* remove first char */ - out[bufflen-1] = '\0'; /* ensures null termination */ - } - else { /* out = "source", or "...source" */ - if (*source == '@') { - size_t l; - source++; /* skip the `@' */ - bufflen -= sizeof(" '...' "); - l = strlen(source); - strcpy(out, ""); - if (l > bufflen) { - source += (l-bufflen); /* get last part of file name */ - strcat(out, "..."); - } - strcat(out, source); - } - else { /* out = [string "string"] */ - size_t len = strcspn(source, "\n\r"); /* stop at first newline */ - bufflen -= sizeof(" [string \"...\"] "); - if (len > bufflen) len = bufflen; - strcpy(out, "[string \""); - if (source[len] != '\0') { /* must truncate? */ - strncat(out, source, len); - strcat(out, "..."); - } - else - strcat(out, source); - strcat(out, "\"]"); - } - } -} diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lobject.h b/desmume/src/windows/lua/lua-5.1.4/src/lobject.h deleted file mode 100644 index f1e447ef3..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lobject.h +++ /dev/null @@ -1,381 +0,0 @@ -/* -** $Id: lobject.h,v 2.20.1.2 2008/08/06 13:29:48 roberto Exp $ -** Type definitions for Lua objects -** See Copyright Notice in lua.h -*/ - - -#ifndef lobject_h -#define lobject_h - - -#include - - -#include "llimits.h" -#include "lua.h" - - -/* tags for values visible from Lua */ -#define LAST_TAG LUA_TTHREAD - -#define NUM_TAGS (LAST_TAG+1) - - -/* -** Extra tags for non-values -*/ -#define LUA_TPROTO (LAST_TAG+1) -#define LUA_TUPVAL (LAST_TAG+2) -#define LUA_TDEADKEY (LAST_TAG+3) - - -/* -** Union of all collectable objects -*/ -typedef union GCObject GCObject; - - -/* -** Common Header for all collectable objects (in macro form, to be -** included in other objects) -*/ -#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked - - -/* -** Common header in struct form -*/ -typedef struct GCheader { - CommonHeader; -} GCheader; - - - - -/* -** Union of all Lua values -*/ -typedef union { - GCObject *gc; - void *p; - lua_Number n; - int b; -} Value; - - -/* -** Tagged Values -*/ - -#define TValuefields Value value; int tt - -typedef struct lua_TValue { - TValuefields; -} TValue; - - -/* Macros to test type */ -#define ttisnil(o) (ttype(o) == LUA_TNIL) -#define ttisnumber(o) (ttype(o) == LUA_TNUMBER) -#define ttisstring(o) (ttype(o) == LUA_TSTRING) -#define ttistable(o) (ttype(o) == LUA_TTABLE) -#define ttisfunction(o) (ttype(o) == LUA_TFUNCTION) -#define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN) -#define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA) -#define ttisthread(o) (ttype(o) == LUA_TTHREAD) -#define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA) - -/* Macros to access values */ -#define ttype(o) ((o)->tt) -#define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc) -#define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p) -#define nvalue(o) check_exp(ttisnumber(o), (o)->value.n) -#define rawtsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts) -#define tsvalue(o) (&rawtsvalue(o)->tsv) -#define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u) -#define uvalue(o) (&rawuvalue(o)->uv) -#define clvalue(o) check_exp(ttisfunction(o), &(o)->value.gc->cl) -#define hvalue(o) check_exp(ttistable(o), &(o)->value.gc->h) -#define bvalue(o) check_exp(ttisboolean(o), (o)->value.b) -#define thvalue(o) check_exp(ttisthread(o), &(o)->value.gc->th) - -#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) - -/* -** for internal debug only -*/ -#define checkconsistency(obj) \ - lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch.tt)) - -#define checkliveness(g,obj) \ - lua_assert(!iscollectable(obj) || \ - ((ttype(obj) == (obj)->value.gc->gch.tt) && !isdead(g, (obj)->value.gc))) - - -/* Macros to set values */ -#define setnilvalue(obj) ((obj)->tt=LUA_TNIL) - -#define setnvalue(obj,x) \ - { TValue *i_o=(obj); i_o->value.n=(x); i_o->tt=LUA_TNUMBER; } - -#define setpvalue(obj,x) \ - { TValue *i_o=(obj); i_o->value.p=(x); i_o->tt=LUA_TLIGHTUSERDATA; } - -#define setbvalue(obj,x) \ - { TValue *i_o=(obj); i_o->value.b=(x); i_o->tt=LUA_TBOOLEAN; } - -#define setsvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TSTRING; \ - checkliveness(G(L),i_o); } - -#define setuvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TUSERDATA; \ - checkliveness(G(L),i_o); } - -#define setthvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTHREAD; \ - checkliveness(G(L),i_o); } - -#define setclvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TFUNCTION; \ - checkliveness(G(L),i_o); } - -#define sethvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TTABLE; \ - checkliveness(G(L),i_o); } - -#define setptvalue(L,obj,x) \ - { TValue *i_o=(obj); \ - i_o->value.gc=cast(GCObject *, (x)); i_o->tt=LUA_TPROTO; \ - checkliveness(G(L),i_o); } - - - - -#define setobj(L,obj1,obj2) \ - { const TValue *o2=(obj2); TValue *o1=(obj1); \ - o1->value = o2->value; o1->tt=o2->tt; \ - checkliveness(G(L),o1); } - - -/* -** different types of sets, according to destination -*/ - -/* from stack to (same) stack */ -#define setobjs2s setobj -/* to stack (not from same stack) */ -#define setobj2s setobj -#define setsvalue2s setsvalue -#define sethvalue2s sethvalue -#define setptvalue2s setptvalue -/* from table to same table */ -#define setobjt2t setobj -/* to table */ -#define setobj2t setobj -/* to new object */ -#define setobj2n setobj -#define setsvalue2n setsvalue - -#define setttype(obj, tt) (ttype(obj) = (tt)) - - -#define iscollectable(o) (ttype(o) >= LUA_TSTRING) - - - -typedef TValue *StkId; /* index to stack elements */ - - -/* -** String headers for string table -*/ -typedef union TString { - L_Umaxalign dummy; /* ensures maximum alignment for strings */ - struct { - CommonHeader; - lu_byte reserved; - unsigned int hash; - size_t len; - } tsv; -} TString; - - -#define getstr(ts) cast(const char *, (ts) + 1) -#define svalue(o) getstr(rawtsvalue(o)) - - - -typedef union Udata { - L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ - struct { - CommonHeader; - struct Table *metatable; - struct Table *env; - size_t len; - } uv; -} Udata; - - - - -/* -** Function Prototypes -*/ -typedef struct Proto { - CommonHeader; - TValue *k; /* constants used by the function */ - Instruction *code; - struct Proto **p; /* functions defined inside the function */ - int *lineinfo; /* map from opcodes to source lines */ - struct LocVar *locvars; /* information about local variables */ - TString **upvalues; /* upvalue names */ - TString *source; - int sizeupvalues; - int sizek; /* size of `k' */ - int sizecode; - int sizelineinfo; - int sizep; /* size of `p' */ - int sizelocvars; - int linedefined; - int lastlinedefined; - GCObject *gclist; - lu_byte nups; /* number of upvalues */ - lu_byte numparams; - lu_byte is_vararg; - lu_byte maxstacksize; -} Proto; - - -/* masks for new-style vararg */ -#define VARARG_HASARG 1 -#define VARARG_ISVARARG 2 -#define VARARG_NEEDSARG 4 - - -typedef struct LocVar { - TString *varname; - int startpc; /* first point where variable is active */ - int endpc; /* first point where variable is dead */ -} LocVar; - - - -/* -** Upvalues -*/ - -typedef struct UpVal { - CommonHeader; - TValue *v; /* points to stack or to its own value */ - union { - TValue value; /* the value (when closed) */ - struct { /* double linked list (when open) */ - struct UpVal *prev; - struct UpVal *next; - } l; - } u; -} UpVal; - - -/* -** Closures -*/ - -#define ClosureHeader \ - CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist; \ - struct Table *env - -typedef struct CClosure { - ClosureHeader; - lua_CFunction f; - TValue upvalue[1]; -} CClosure; - - -typedef struct LClosure { - ClosureHeader; - struct Proto *p; - UpVal *upvals[1]; -} LClosure; - - -typedef union Closure { - CClosure c; - LClosure l; -} Closure; - - -#define iscfunction(o) (ttype(o) == LUA_TFUNCTION && clvalue(o)->c.isC) -#define isLfunction(o) (ttype(o) == LUA_TFUNCTION && !clvalue(o)->c.isC) - - -/* -** Tables -*/ - -typedef union TKey { - struct { - TValuefields; - struct Node *next; /* for chaining */ - } nk; - TValue tvk; -} TKey; - - -typedef struct Node { - TValue i_val; - TKey i_key; -} Node; - - -typedef struct Table { - CommonHeader; - lu_byte flags; /* 1<

lsizenode)) - - -#define luaO_nilobject (&luaO_nilobject_) - -LUAI_DATA const TValue luaO_nilobject_; - -#define ceillog2(x) (luaO_log2((x)-1) + 1) - -LUAI_FUNC int luaO_log2 (unsigned int x); -LUAI_FUNC int luaO_int2fb (unsigned int x); -LUAI_FUNC int luaO_fb2int (int x); -LUAI_FUNC int luaO_rawequalObj (const TValue *t1, const TValue *t2); -LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result); -LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, - va_list argp); -LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); -LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len); - - -#endif - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lopcodes.c b/desmume/src/windows/lua/lua-5.1.4/src/lopcodes.c deleted file mode 100644 index 4cc745230..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lopcodes.c +++ /dev/null @@ -1,102 +0,0 @@ -/* -** $Id: lopcodes.c,v 1.37.1.1 2007/12/27 13:02:25 roberto Exp $ -** See Copyright Notice in lua.h -*/ - - -#define lopcodes_c -#define LUA_CORE - - -#include "lopcodes.h" - - -/* ORDER OP */ - -const char *const luaP_opnames[NUM_OPCODES+1] = { - "MOVE", - "LOADK", - "LOADBOOL", - "LOADNIL", - "GETUPVAL", - "GETGLOBAL", - "GETTABLE", - "SETGLOBAL", - "SETUPVAL", - "SETTABLE", - "NEWTABLE", - "SELF", - "ADD", - "SUB", - "MUL", - "DIV", - "MOD", - "POW", - "UNM", - "NOT", - "LEN", - "CONCAT", - "JMP", - "EQ", - "LT", - "LE", - "TEST", - "TESTSET", - "CALL", - "TAILCALL", - "RETURN", - "FORLOOP", - "FORPREP", - "TFORLOOP", - "SETLIST", - "CLOSE", - "CLOSURE", - "VARARG", - NULL -}; - - -#define opmode(t,a,b,c,m) (((t)<<7) | ((a)<<6) | ((b)<<4) | ((c)<<2) | (m)) - -const lu_byte luaP_opmodes[NUM_OPCODES] = { -/* T A B C mode opcode */ - opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */ - ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */ - ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */ - ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LOADNIL */ - ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */ - ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_GETGLOBAL */ - ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */ - ,opmode(0, 0, OpArgK, OpArgN, iABx) /* OP_SETGLOBAL */ - ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_SETUPVAL */ - ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABLE */ - ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_NEWTABLE */ - ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_SELF */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ADD */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SUB */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MUL */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_DIV */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MOD */ - ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_POW */ - ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_UNM */ - ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_NOT */ - ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LEN */ - ,opmode(0, 1, OpArgR, OpArgR, iABC) /* OP_CONCAT */ - ,opmode(0, 0, OpArgR, OpArgN, iAsBx) /* OP_JMP */ - ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */ - ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */ - ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */ - ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TEST */ - ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */ - ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */ - ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */ - ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_RETURN */ - ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORLOOP */ - ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORPREP */ - ,opmode(1, 0, OpArgN, OpArgU, iABC) /* OP_TFORLOOP */ - ,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */ - ,opmode(0, 0, OpArgN, OpArgN, iABC) /* OP_CLOSE */ - ,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */ - ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */ -}; - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lopcodes.h b/desmume/src/windows/lua/lua-5.1.4/src/lopcodes.h deleted file mode 100644 index 41224d6ee..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lopcodes.h +++ /dev/null @@ -1,268 +0,0 @@ -/* -** $Id: lopcodes.h,v 1.125.1.1 2007/12/27 13:02:25 roberto Exp $ -** Opcodes for Lua virtual machine -** See Copyright Notice in lua.h -*/ - -#ifndef lopcodes_h -#define lopcodes_h - -#include "llimits.h" - - -/*=========================================================================== - We assume that instructions are unsigned numbers. - All instructions have an opcode in the first 6 bits. - Instructions can have the following fields: - `A' : 8 bits - `B' : 9 bits - `C' : 9 bits - `Bx' : 18 bits (`B' and `C' together) - `sBx' : signed Bx - - A signed argument is represented in excess K; that is, the number - value is the unsigned value minus K. K is exactly the maximum value - for that argument (so that -max is represented by 0, and +max is - represented by 2*max), which is half the maximum for the corresponding - unsigned argument. -===========================================================================*/ - - -enum OpMode {iABC, iABx, iAsBx}; /* basic instruction format */ - - -/* -** size and position of opcode arguments. -*/ -#define SIZE_C 9 -#define SIZE_B 9 -#define SIZE_Bx (SIZE_C + SIZE_B) -#define SIZE_A 8 - -#define SIZE_OP 6 - -#define POS_OP 0 -#define POS_A (POS_OP + SIZE_OP) -#define POS_C (POS_A + SIZE_A) -#define POS_B (POS_C + SIZE_C) -#define POS_Bx POS_C - - -/* -** limits for opcode arguments. -** we use (signed) int to manipulate most arguments, -** so they must fit in LUAI_BITSINT-1 bits (-1 for sign) -*/ -#if SIZE_Bx < LUAI_BITSINT-1 -#define MAXARG_Bx ((1<>1) /* `sBx' is signed */ -#else -#define MAXARG_Bx MAX_INT -#define MAXARG_sBx MAX_INT -#endif - - -#define MAXARG_A ((1<>POS_OP) & MASK1(SIZE_OP,0))) -#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \ - ((cast(Instruction, o)<>POS_A) & MASK1(SIZE_A,0))) -#define SETARG_A(i,u) ((i) = (((i)&MASK0(SIZE_A,POS_A)) | \ - ((cast(Instruction, u)<>POS_B) & MASK1(SIZE_B,0))) -#define SETARG_B(i,b) ((i) = (((i)&MASK0(SIZE_B,POS_B)) | \ - ((cast(Instruction, b)<>POS_C) & MASK1(SIZE_C,0))) -#define SETARG_C(i,b) ((i) = (((i)&MASK0(SIZE_C,POS_C)) | \ - ((cast(Instruction, b)<>POS_Bx) & MASK1(SIZE_Bx,0))) -#define SETARG_Bx(i,b) ((i) = (((i)&MASK0(SIZE_Bx,POS_Bx)) | \ - ((cast(Instruction, b)< C) then pc++ */ -OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ - -OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */ -OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */ -OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */ - -OP_FORLOOP,/* A sBx R(A)+=R(A+2); - if R(A) =) R(A)*/ -OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n)) */ - -OP_VARARG/* A B R(A), R(A+1), ..., R(A+B-1) = vararg */ -} OpCode; - - -#define NUM_OPCODES (cast(int, OP_VARARG) + 1) - - - -/*=========================================================================== - Notes: - (*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1, - and can be 0: OP_CALL then sets `top' to last_result+1, so - next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'. - - (*) In OP_VARARG, if (B == 0) then use actual number of varargs and - set top (like in OP_CALL with C == 0). - - (*) In OP_RETURN, if (B == 0) then return up to `top' - - (*) In OP_SETLIST, if (B == 0) then B = `top'; - if (C == 0) then next `instruction' is real C - - (*) For comparisons, A specifies what condition the test should accept - (true or false). - - (*) All `skips' (pc++) assume that next instruction is a jump -===========================================================================*/ - - -/* -** masks for instruction properties. The format is: -** bits 0-1: op mode -** bits 2-3: C arg mode -** bits 4-5: B arg mode -** bit 6: instruction set register A -** bit 7: operator is a test -*/ - -enum OpArgMask { - OpArgN, /* argument is not used */ - OpArgU, /* argument is used */ - OpArgR, /* argument is a register or a jump offset */ - OpArgK /* argument is a constant or register/constant */ -}; - -LUAI_DATA const lu_byte luaP_opmodes[NUM_OPCODES]; - -#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 3)) -#define getBMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3)) -#define getCMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3)) -#define testAMode(m) (luaP_opmodes[m] & (1 << 6)) -#define testTMode(m) (luaP_opmodes[m] & (1 << 7)) - - -LUAI_DATA const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names */ - - -/* number of list items to accumulate before a SETLIST instruction */ -#define LFIELDS_PER_FLUSH 50 - - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/loslib.c b/desmume/src/windows/lua/lua-5.1.4/src/loslib.c deleted file mode 100644 index da06a572a..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/loslib.c +++ /dev/null @@ -1,243 +0,0 @@ -/* -** $Id: loslib.c,v 1.19.1.3 2008/01/18 16:38:18 roberto Exp $ -** Standard Operating System library -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include -#include - -#define loslib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - -static int os_pushresult (lua_State *L, int i, const char *filename) { - int en = errno; /* calls to Lua API may change this value */ - if (i) { - lua_pushboolean(L, 1); - return 1; - } - else { - lua_pushnil(L); - lua_pushfstring(L, "%s: %s", filename, strerror(en)); - lua_pushinteger(L, en); - return 3; - } -} - - -static int os_execute (lua_State *L) { - lua_pushinteger(L, system(luaL_optstring(L, 1, NULL))); - return 1; -} - - -static int os_remove (lua_State *L) { - const char *filename = luaL_checkstring(L, 1); - return os_pushresult(L, remove(filename) == 0, filename); -} - - -static int os_rename (lua_State *L) { - const char *fromname = luaL_checkstring(L, 1); - const char *toname = luaL_checkstring(L, 2); - return os_pushresult(L, rename(fromname, toname) == 0, fromname); -} - - -static int os_tmpname (lua_State *L) { - char buff[LUA_TMPNAMBUFSIZE]; - int err; - lua_tmpnam(buff, err); - if (err) - return luaL_error(L, "unable to generate a unique filename"); - lua_pushstring(L, buff); - return 1; -} - - -static int os_getenv (lua_State *L) { - lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */ - return 1; -} - - -static int os_clock (lua_State *L) { - lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC); - return 1; -} - - -/* -** {====================================================== -** Time/Date operations -** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S, -** wday=%w+1, yday=%j, isdst=? } -** ======================================================= -*/ - -static void setfield (lua_State *L, const char *key, int value) { - lua_pushinteger(L, value); - lua_setfield(L, -2, key); -} - -static void setboolfield (lua_State *L, const char *key, int value) { - if (value < 0) /* undefined? */ - return; /* does not set field */ - lua_pushboolean(L, value); - lua_setfield(L, -2, key); -} - -static int getboolfield (lua_State *L, const char *key) { - int res; - lua_getfield(L, -1, key); - res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1); - lua_pop(L, 1); - return res; -} - - -static int getfield (lua_State *L, const char *key, int d) { - int res; - lua_getfield(L, -1, key); - if (lua_isnumber(L, -1)) - res = (int)lua_tointeger(L, -1); - else { - if (d < 0) - return luaL_error(L, "field " LUA_QS " missing in date table", key); - res = d; - } - lua_pop(L, 1); - return res; -} - - -static int os_date (lua_State *L) { - const char *s = luaL_optstring(L, 1, "%c"); - time_t t = luaL_opt(L, (time_t)luaL_checknumber, 2, time(NULL)); - struct tm *stm; - if (*s == '!') { /* UTC? */ - stm = gmtime(&t); - s++; /* skip `!' */ - } - else - stm = localtime(&t); - if (stm == NULL) /* invalid date? */ - lua_pushnil(L); - else if (strcmp(s, "*t") == 0) { - lua_createtable(L, 0, 9); /* 9 = number of fields */ - setfield(L, "sec", stm->tm_sec); - setfield(L, "min", stm->tm_min); - setfield(L, "hour", stm->tm_hour); - setfield(L, "day", stm->tm_mday); - setfield(L, "month", stm->tm_mon+1); - setfield(L, "year", stm->tm_year+1900); - setfield(L, "wday", stm->tm_wday+1); - setfield(L, "yday", stm->tm_yday+1); - setboolfield(L, "isdst", stm->tm_isdst); - } - else { - char cc[3]; - luaL_Buffer b; - cc[0] = '%'; cc[2] = '\0'; - luaL_buffinit(L, &b); - for (; *s; s++) { - if (*s != '%' || *(s + 1) == '\0') /* no conversion specifier? */ - luaL_addchar(&b, *s); - else { - size_t reslen; - char buff[200]; /* should be big enough for any conversion result */ - cc[1] = *(++s); - reslen = strftime(buff, sizeof(buff), cc, stm); - luaL_addlstring(&b, buff, reslen); - } - } - luaL_pushresult(&b); - } - return 1; -} - - -static int os_time (lua_State *L) { - time_t t; - if (lua_isnoneornil(L, 1)) /* called without args? */ - t = time(NULL); /* get current time */ - else { - struct tm ts; - luaL_checktype(L, 1, LUA_TTABLE); - lua_settop(L, 1); /* make sure table is at the top */ - ts.tm_sec = getfield(L, "sec", 0); - ts.tm_min = getfield(L, "min", 0); - ts.tm_hour = getfield(L, "hour", 12); - ts.tm_mday = getfield(L, "day", -1); - ts.tm_mon = getfield(L, "month", -1) - 1; - ts.tm_year = getfield(L, "year", -1) - 1900; - ts.tm_isdst = getboolfield(L, "isdst"); - t = mktime(&ts); - } - if (t == (time_t)(-1)) - lua_pushnil(L); - else - lua_pushnumber(L, (lua_Number)t); - return 1; -} - - -static int os_difftime (lua_State *L) { - lua_pushnumber(L, difftime((time_t)(luaL_checknumber(L, 1)), - (time_t)(luaL_optnumber(L, 2, 0)))); - return 1; -} - -/* }====================================================== */ - - -static int os_setlocale (lua_State *L) { - static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, - LC_NUMERIC, LC_TIME}; - static const char *const catnames[] = {"all", "collate", "ctype", "monetary", - "numeric", "time", NULL}; - const char *l = luaL_optstring(L, 1, NULL); - int op = luaL_checkoption(L, 2, "all", catnames); - lua_pushstring(L, setlocale(cat[op], l)); - return 1; -} - - -static int os_exit (lua_State *L) { - exit(luaL_optint(L, 1, EXIT_SUCCESS)); -} - -static const luaL_Reg syslib[] = { - {"clock", os_clock}, - {"date", os_date}, - {"difftime", os_difftime}, - {"execute", os_execute}, - {"exit", os_exit}, - {"getenv", os_getenv}, - {"remove", os_remove}, - {"rename", os_rename}, - {"setlocale", os_setlocale}, - {"time", os_time}, - {"tmpname", os_tmpname}, - {NULL, NULL} -}; - -/* }====================================================== */ - - - -LUALIB_API int luaopen_os (lua_State *L) { - luaL_register(L, LUA_OSLIBNAME, syslib); - return 1; -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lparser.c b/desmume/src/windows/lua/lua-5.1.4/src/lparser.c deleted file mode 100644 index 1e2a9a88b..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lparser.c +++ /dev/null @@ -1,1339 +0,0 @@ -/* -** $Id: lparser.c,v 2.42.1.3 2007/12/28 15:32:23 roberto Exp $ -** Lua Parser -** See Copyright Notice in lua.h -*/ - - -#include - -#define lparser_c -#define LUA_CORE - -#include "lua.h" - -#include "lcode.h" -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "llex.h" -#include "lmem.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lparser.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" - - - -#define hasmultret(k) ((k) == VCALL || (k) == VVARARG) - -#define getlocvar(fs, i) ((fs)->f->locvars[(fs)->actvar[i]]) - -#define luaY_checklimit(fs,v,l,m) if ((v)>(l)) errorlimit(fs,l,m) - - -/* -** nodes for block list (list of active blocks) -*/ -typedef struct BlockCnt { - struct BlockCnt *previous; /* chain */ - int breaklist; /* list of jumps out of this loop */ - lu_byte nactvar; /* # active locals outside the breakable structure */ - lu_byte upval; /* true if some variable in the block is an upvalue */ - lu_byte isbreakable; /* true if `block' is a loop */ -} BlockCnt; - - - -/* -** prototypes for recursive non-terminal functions -*/ -static void chunk (LexState *ls); -static void expr (LexState *ls, expdesc *v); - - -static void anchor_token (LexState *ls) { - if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) { - TString *ts = ls->t.seminfo.ts; - luaX_newstring(ls, getstr(ts), ts->tsv.len); - } -} - - -static void error_expected (LexState *ls, int token) { - luaX_syntaxerror(ls, - luaO_pushfstring(ls->L, LUA_QS " expected", luaX_token2str(ls, token))); -} - - -static void errorlimit (FuncState *fs, int limit, const char *what) { - const char *msg = (fs->f->linedefined == 0) ? - luaO_pushfstring(fs->L, "main function has more than %d %s", limit, what) : - luaO_pushfstring(fs->L, "function at line %d has more than %d %s", - fs->f->linedefined, limit, what); - luaX_lexerror(fs->ls, msg, 0); -} - - -static int testnext (LexState *ls, int c) { - if (ls->t.token == c) { - luaX_next(ls); - return 1; - } - else return 0; -} - - -static void check (LexState *ls, int c) { - if (ls->t.token != c) - error_expected(ls, c); -} - -static void checknext (LexState *ls, int c) { - check(ls, c); - luaX_next(ls); -} - - -#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); } - - - -static void check_match (LexState *ls, int what, int who, int where) { - if (!testnext(ls, what)) { - if (where == ls->linenumber) - error_expected(ls, what); - else { - luaX_syntaxerror(ls, luaO_pushfstring(ls->L, - LUA_QS " expected (to close " LUA_QS " at line %d)", - luaX_token2str(ls, what), luaX_token2str(ls, who), where)); - } - } -} - - -static TString *str_checkname (LexState *ls) { - TString *ts; - check(ls, TK_NAME); - ts = ls->t.seminfo.ts; - luaX_next(ls); - return ts; -} - - -static void init_exp (expdesc *e, expkind k, int i) { - e->f = e->t = NO_JUMP; - e->k = k; - e->u.s.info = i; -} - - -static void codestring (LexState *ls, expdesc *e, TString *s) { - init_exp(e, VK, luaK_stringK(ls->fs, s)); -} - - -static void checkname(LexState *ls, expdesc *e) { - codestring(ls, e, str_checkname(ls)); -} - - -static int registerlocalvar (LexState *ls, TString *varname) { - FuncState *fs = ls->fs; - Proto *f = fs->f; - int oldsize = f->sizelocvars; - luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars, - LocVar, SHRT_MAX, "too many local variables"); - while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL; - f->locvars[fs->nlocvars].varname = varname; - luaC_objbarrier(ls->L, f, varname); - return fs->nlocvars++; -} - - -#define new_localvarliteral(ls,v,n) \ - new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n) - - -static void new_localvar (LexState *ls, TString *name, int n) { - FuncState *fs = ls->fs; - luaY_checklimit(fs, fs->nactvar+n+1, LUAI_MAXVARS, "local variables"); - fs->actvar[fs->nactvar+n] = cast(unsigned short, registerlocalvar(ls, name)); -} - - -static void adjustlocalvars (LexState *ls, int nvars) { - FuncState *fs = ls->fs; - fs->nactvar = cast_byte(fs->nactvar + nvars); - for (; nvars; nvars--) { - getlocvar(fs, fs->nactvar - nvars).startpc = fs->pc; - } -} - - -static void removevars (LexState *ls, int tolevel) { - FuncState *fs = ls->fs; - while (fs->nactvar > tolevel) - getlocvar(fs, --fs->nactvar).endpc = fs->pc; -} - - -static int indexupvalue (FuncState *fs, TString *name, expdesc *v) { - int i; - Proto *f = fs->f; - int oldsize = f->sizeupvalues; - for (i=0; inups; i++) { - if (fs->upvalues[i].k == v->k && fs->upvalues[i].info == v->u.s.info) { - lua_assert(f->upvalues[i] == name); - return i; - } - } - /* new one */ - luaY_checklimit(fs, f->nups + 1, LUAI_MAXUPVALUES, "upvalues"); - luaM_growvector(fs->L, f->upvalues, f->nups, f->sizeupvalues, - TString *, MAX_INT, ""); - while (oldsize < f->sizeupvalues) f->upvalues[oldsize++] = NULL; - f->upvalues[f->nups] = name; - luaC_objbarrier(fs->L, f, name); - lua_assert(v->k == VLOCAL || v->k == VUPVAL); - fs->upvalues[f->nups].k = cast_byte(v->k); - fs->upvalues[f->nups].info = cast_byte(v->u.s.info); - return f->nups++; -} - - -static int searchvar (FuncState *fs, TString *n) { - int i; - for (i=fs->nactvar-1; i >= 0; i--) { - if (n == getlocvar(fs, i).varname) - return i; - } - return -1; /* not found */ -} - - -static void markupval (FuncState *fs, int level) { - BlockCnt *bl = fs->bl; - while (bl && bl->nactvar > level) bl = bl->previous; - if (bl) bl->upval = 1; -} - - -static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { - if (fs == NULL) { /* no more levels? */ - init_exp(var, VGLOBAL, NO_REG); /* default is global variable */ - return VGLOBAL; - } - else { - int v = searchvar(fs, n); /* look up at current level */ - if (v >= 0) { - init_exp(var, VLOCAL, v); - if (!base) - markupval(fs, v); /* local will be used as an upval */ - return VLOCAL; - } - else { /* not found at current level; try upper one */ - if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL) - return VGLOBAL; - var->u.s.info = indexupvalue(fs, n, var); /* else was LOCAL or UPVAL */ - var->k = VUPVAL; /* upvalue in this level */ - return VUPVAL; - } - } -} - - -static void singlevar (LexState *ls, expdesc *var) { - TString *varname = str_checkname(ls); - FuncState *fs = ls->fs; - if (singlevaraux(fs, varname, var, 1) == VGLOBAL) - var->u.s.info = luaK_stringK(fs, varname); /* info points to global name */ -} - - -static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { - FuncState *fs = ls->fs; - int extra = nvars - nexps; - if (hasmultret(e->k)) { - extra++; /* includes call itself */ - if (extra < 0) extra = 0; - luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ - if (extra > 1) luaK_reserveregs(fs, extra-1); - } - else { - if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */ - if (extra > 0) { - int reg = fs->freereg; - luaK_reserveregs(fs, extra); - luaK_nil(fs, reg, extra); - } - } -} - - -static void enterlevel (LexState *ls) { - if (++ls->L->nCcalls > LUAI_MAXCCALLS) - luaX_lexerror(ls, "chunk has too many syntax levels", 0); -} - - -#define leavelevel(ls) ((ls)->L->nCcalls--) - - -static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) { - bl->breaklist = NO_JUMP; - bl->isbreakable = isbreakable; - bl->nactvar = fs->nactvar; - bl->upval = 0; - bl->previous = fs->bl; - fs->bl = bl; - lua_assert(fs->freereg == fs->nactvar); -} - - -static void leaveblock (FuncState *fs) { - BlockCnt *bl = fs->bl; - fs->bl = bl->previous; - removevars(fs->ls, bl->nactvar); - if (bl->upval) - luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0); - /* a block either controls scope or breaks (never both) */ - lua_assert(!bl->isbreakable || !bl->upval); - lua_assert(bl->nactvar == fs->nactvar); - fs->freereg = fs->nactvar; /* free registers */ - luaK_patchtohere(fs, bl->breaklist); -} - - -static void pushclosure (LexState *ls, FuncState *func, expdesc *v) { - FuncState *fs = ls->fs; - Proto *f = fs->f; - int oldsize = f->sizep; - int i; - luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *, - MAXARG_Bx, "constant table overflow"); - while (oldsize < f->sizep) f->p[oldsize++] = NULL; - f->p[fs->np++] = func->f; - luaC_objbarrier(ls->L, f, func->f); - init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1)); - for (i=0; if->nups; i++) { - OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL; - luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0); - } -} - - -static void open_func (LexState *ls, FuncState *fs) { - lua_State *L = ls->L; - Proto *f = luaF_newproto(L); - fs->f = f; - fs->prev = ls->fs; /* linked list of funcstates */ - fs->ls = ls; - fs->L = L; - ls->fs = fs; - fs->pc = 0; - fs->lasttarget = -1; - fs->jpc = NO_JUMP; - fs->freereg = 0; - fs->nk = 0; - fs->np = 0; - fs->nlocvars = 0; - fs->nactvar = 0; - fs->bl = NULL; - f->source = ls->source; - f->maxstacksize = 2; /* registers 0/1 are always valid */ - fs->h = luaH_new(L, 0, 0); - /* anchor table of constants and prototype (to avoid being collected) */ - sethvalue2s(L, L->top, fs->h); - incr_top(L); - setptvalue2s(L, L->top, f); - incr_top(L); -} - - -static void close_func (LexState *ls) { - lua_State *L = ls->L; - FuncState *fs = ls->fs; - Proto *f = fs->f; - removevars(ls, 0); - luaK_ret(fs, 0, 0); /* final return */ - luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction); - f->sizecode = fs->pc; - luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int); - f->sizelineinfo = fs->pc; - luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue); - f->sizek = fs->nk; - luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *); - f->sizep = fs->np; - luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar); - f->sizelocvars = fs->nlocvars; - luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *); - f->sizeupvalues = f->nups; - lua_assert(luaG_checkcode(f)); - lua_assert(fs->bl == NULL); - ls->fs = fs->prev; - L->top -= 2; /* remove table and prototype from the stack */ - /* last token read was anchored in defunct function; must reanchor it */ - if (fs) anchor_token(ls); -} - - -Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) { - struct LexState lexstate; - struct FuncState funcstate; - lexstate.buff = buff; - luaX_setinput(L, &lexstate, z, luaS_new(L, name)); - open_func(&lexstate, &funcstate); - funcstate.f->is_vararg = VARARG_ISVARARG; /* main func. is always vararg */ - luaX_next(&lexstate); /* read first token */ - chunk(&lexstate); - check(&lexstate, TK_EOS); - close_func(&lexstate); - lua_assert(funcstate.prev == NULL); - lua_assert(funcstate.f->nups == 0); - lua_assert(lexstate.fs == NULL); - return funcstate.f; -} - - - -/*============================================================*/ -/* GRAMMAR RULES */ -/*============================================================*/ - - -static void field (LexState *ls, expdesc *v) { - /* field -> ['.' | ':'] NAME */ - FuncState *fs = ls->fs; - expdesc key; - luaK_exp2anyreg(fs, v); - luaX_next(ls); /* skip the dot or colon */ - checkname(ls, &key); - luaK_indexed(fs, v, &key); -} - - -static void yindex (LexState *ls, expdesc *v) { - /* index -> '[' expr ']' */ - luaX_next(ls); /* skip the '[' */ - expr(ls, v); - luaK_exp2val(ls->fs, v); - checknext(ls, ']'); -} - - -/* -** {====================================================================== -** Rules for Constructors -** ======================================================================= -*/ - - -struct ConsControl { - expdesc v; /* last list item read */ - expdesc *t; /* table descriptor */ - int nh; /* total number of `record' elements */ - int na; /* total number of array elements */ - int tostore; /* number of array elements pending to be stored */ -}; - - -static void recfield (LexState *ls, struct ConsControl *cc) { - /* recfield -> (NAME | `['exp1`]') = exp1 */ - FuncState *fs = ls->fs; - int reg = ls->fs->freereg; - expdesc key, val; - int rkkey; - if (ls->t.token == TK_NAME) { - luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor"); - checkname(ls, &key); - } - else /* ls->t.token == '[' */ - yindex(ls, &key); - cc->nh++; - checknext(ls, '='); - rkkey = luaK_exp2RK(fs, &key); - expr(ls, &val); - luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, rkkey, luaK_exp2RK(fs, &val)); - fs->freereg = reg; /* free registers */ -} - - -static void closelistfield (FuncState *fs, struct ConsControl *cc) { - if (cc->v.k == VVOID) return; /* there is no list item */ - luaK_exp2nextreg(fs, &cc->v); - cc->v.k = VVOID; - if (cc->tostore == LFIELDS_PER_FLUSH) { - luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore); /* flush */ - cc->tostore = 0; /* no more items pending */ - } -} - - -static void lastlistfield (FuncState *fs, struct ConsControl *cc) { - if (cc->tostore == 0) return; - if (hasmultret(cc->v.k)) { - luaK_setmultret(fs, &cc->v); - luaK_setlist(fs, cc->t->u.s.info, cc->na, LUA_MULTRET); - cc->na--; /* do not count last expression (unknown number of elements) */ - } - else { - if (cc->v.k != VVOID) - luaK_exp2nextreg(fs, &cc->v); - luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore); - } -} - - -static void listfield (LexState *ls, struct ConsControl *cc) { - expr(ls, &cc->v); - luaY_checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor"); - cc->na++; - cc->tostore++; -} - - -static void constructor (LexState *ls, expdesc *t) { - /* constructor -> ?? */ - FuncState *fs = ls->fs; - int line = ls->linenumber; - int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0); - struct ConsControl cc; - cc.na = cc.nh = cc.tostore = 0; - cc.t = t; - init_exp(t, VRELOCABLE, pc); - init_exp(&cc.v, VVOID, 0); /* no value (yet) */ - luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */ - checknext(ls, '{'); - do { - lua_assert(cc.v.k == VVOID || cc.tostore > 0); - if (ls->t.token == '}') break; - closelistfield(fs, &cc); - switch(ls->t.token) { - case TK_NAME: { /* may be listfields or recfields */ - luaX_lookahead(ls); - if (ls->lookahead.token != '=') /* expression? */ - listfield(ls, &cc); - else - recfield(ls, &cc); - break; - } - case '[': { /* constructor_item -> recfield */ - recfield(ls, &cc); - break; - } - default: { /* constructor_part -> listfield */ - listfield(ls, &cc); - break; - } - } - } while (testnext(ls, ',') || testnext(ls, ';')); - check_match(ls, '}', '{', line); - lastlistfield(fs, &cc); - SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */ - SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */ -} - -/* }====================================================================== */ - - - -static void parlist (LexState *ls) { - /* parlist -> [ param { `,' param } ] */ - FuncState *fs = ls->fs; - Proto *f = fs->f; - int nparams = 0; - f->is_vararg = 0; - if (ls->t.token != ')') { /* is `parlist' not empty? */ - do { - switch (ls->t.token) { - case TK_NAME: { /* param -> NAME */ - new_localvar(ls, str_checkname(ls), nparams++); - break; - } - case TK_DOTS: { /* param -> `...' */ - luaX_next(ls); -#if defined(LUA_COMPAT_VARARG) - /* use `arg' as default name */ - new_localvarliteral(ls, "arg", nparams++); - f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG; -#endif - f->is_vararg |= VARARG_ISVARARG; - break; - } - default: luaX_syntaxerror(ls, " or " LUA_QL("...") " expected"); - } - } while (!f->is_vararg && testnext(ls, ',')); - } - adjustlocalvars(ls, nparams); - f->numparams = cast_byte(fs->nactvar - (f->is_vararg & VARARG_HASARG)); - luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */ -} - - -static void body (LexState *ls, expdesc *e, int needself, int line) { - /* body -> `(' parlist `)' chunk END */ - FuncState new_fs; - open_func(ls, &new_fs); - new_fs.f->linedefined = line; - checknext(ls, '('); - if (needself) { - new_localvarliteral(ls, "self", 0); - adjustlocalvars(ls, 1); - } - parlist(ls); - checknext(ls, ')'); - chunk(ls); - new_fs.f->lastlinedefined = ls->linenumber; - check_match(ls, TK_END, TK_FUNCTION, line); - close_func(ls); - pushclosure(ls, &new_fs, e); -} - - -static int explist1 (LexState *ls, expdesc *v) { - /* explist1 -> expr { `,' expr } */ - int n = 1; /* at least one expression */ - expr(ls, v); - while (testnext(ls, ',')) { - luaK_exp2nextreg(ls->fs, v); - expr(ls, v); - n++; - } - return n; -} - - -static void funcargs (LexState *ls, expdesc *f) { - FuncState *fs = ls->fs; - expdesc args; - int base, nparams; - int line = ls->linenumber; - switch (ls->t.token) { - case '(': { /* funcargs -> `(' [ explist1 ] `)' */ - if (line != ls->lastline) - luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)"); - luaX_next(ls); - if (ls->t.token == ')') /* arg list is empty? */ - args.k = VVOID; - else { - explist1(ls, &args); - luaK_setmultret(fs, &args); - } - check_match(ls, ')', '(', line); - break; - } - case '{': { /* funcargs -> constructor */ - constructor(ls, &args); - break; - } - case TK_STRING: { /* funcargs -> STRING */ - codestring(ls, &args, ls->t.seminfo.ts); - luaX_next(ls); /* must use `seminfo' before `next' */ - break; - } - default: { - luaX_syntaxerror(ls, "function arguments expected"); - return; - } - } - lua_assert(f->k == VNONRELOC); - base = f->u.s.info; /* base register for call */ - if (hasmultret(args.k)) - nparams = LUA_MULTRET; /* open call */ - else { - if (args.k != VVOID) - luaK_exp2nextreg(fs, &args); /* close last argument */ - nparams = fs->freereg - (base+1); - } - init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); - luaK_fixline(fs, line); - fs->freereg = base+1; /* call remove function and arguments and leaves - (unless changed) one result */ -} - - - - -/* -** {====================================================================== -** Expression parsing -** ======================================================================= -*/ - - -static void prefixexp (LexState *ls, expdesc *v) { - /* prefixexp -> NAME | '(' expr ')' */ - switch (ls->t.token) { - case '(': { - int line = ls->linenumber; - luaX_next(ls); - expr(ls, v); - check_match(ls, ')', '(', line); - luaK_dischargevars(ls->fs, v); - return; - } - case TK_NAME: { - singlevar(ls, v); - return; - } - default: { - luaX_syntaxerror(ls, "unexpected symbol"); - return; - } - } -} - - -static void primaryexp (LexState *ls, expdesc *v) { - /* primaryexp -> - prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */ - FuncState *fs = ls->fs; - prefixexp(ls, v); - for (;;) { - switch (ls->t.token) { - case '.': { /* field */ - field(ls, v); - break; - } - case '[': { /* `[' exp1 `]' */ - expdesc key; - luaK_exp2anyreg(fs, v); - yindex(ls, &key); - luaK_indexed(fs, v, &key); - break; - } - case ':': { /* `:' NAME funcargs */ - expdesc key; - luaX_next(ls); - checkname(ls, &key); - luaK_self(fs, v, &key); - funcargs(ls, v); - break; - } - case '(': case TK_STRING: case '{': { /* funcargs */ - luaK_exp2nextreg(fs, v); - funcargs(ls, v); - break; - } - default: return; - } - } -} - - -static void simpleexp (LexState *ls, expdesc *v) { - /* simpleexp -> NUMBER | STRING | NIL | true | false | ... | - constructor | FUNCTION body | primaryexp */ - switch (ls->t.token) { - case TK_NUMBER: { - init_exp(v, VKNUM, 0); - v->u.nval = ls->t.seminfo.r; - break; - } - case TK_STRING: { - codestring(ls, v, ls->t.seminfo.ts); - break; - } - case TK_NIL: { - init_exp(v, VNIL, 0); - break; - } - case TK_TRUE: { - init_exp(v, VTRUE, 0); - break; - } - case TK_FALSE: { - init_exp(v, VFALSE, 0); - break; - } - case TK_DOTS: { /* vararg */ - FuncState *fs = ls->fs; - check_condition(ls, fs->f->is_vararg, - "cannot use " LUA_QL("...") " outside a vararg function"); - fs->f->is_vararg &= ~VARARG_NEEDSARG; /* don't need 'arg' */ - init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0)); - break; - } - case '{': { /* constructor */ - constructor(ls, v); - return; - } - case TK_FUNCTION: { - luaX_next(ls); - body(ls, v, 0, ls->linenumber); - return; - } - default: { - primaryexp(ls, v); - return; - } - } - luaX_next(ls); -} - - -static UnOpr getunopr (int op) { - switch (op) { - case TK_NOT: return OPR_NOT; - case '-': return OPR_MINUS; - case '#': return OPR_LEN; - default: return OPR_NOUNOPR; - } -} - - -static BinOpr getbinopr (int op) { - switch (op) { - case '+': return OPR_ADD; - case '-': return OPR_SUB; - case '*': return OPR_MUL; - case '/': return OPR_DIV; - case '%': return OPR_MOD; - case '^': return OPR_POW; - case TK_CONCAT: return OPR_CONCAT; - case TK_NE: return OPR_NE; - case TK_EQ: return OPR_EQ; - case '<': return OPR_LT; - case TK_LE: return OPR_LE; - case '>': return OPR_GT; - case TK_GE: return OPR_GE; - case TK_AND: return OPR_AND; - case TK_OR: return OPR_OR; - default: return OPR_NOBINOPR; - } -} - - -static const struct { - lu_byte left; /* left priority for each binary operator */ - lu_byte right; /* right priority */ -} priority[] = { /* ORDER OPR */ - {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `/' `%' */ - {10, 9}, {5, 4}, /* power and concat (right associative) */ - {3, 3}, {3, 3}, /* equality and inequality */ - {3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */ - {2, 2}, {1, 1} /* logical (and/or) */ -}; - -#define UNARY_PRIORITY 8 /* priority for unary operators */ - - -/* -** subexpr -> (simpleexp | unop subexpr) { binop subexpr } -** where `binop' is any binary operator with a priority higher than `limit' -*/ -static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) { - BinOpr op; - UnOpr uop; - enterlevel(ls); - uop = getunopr(ls->t.token); - if (uop != OPR_NOUNOPR) { - luaX_next(ls); - subexpr(ls, v, UNARY_PRIORITY); - luaK_prefix(ls->fs, uop, v); - } - else simpleexp(ls, v); - /* expand while operators have priorities higher than `limit' */ - op = getbinopr(ls->t.token); - while (op != OPR_NOBINOPR && priority[op].left > limit) { - expdesc v2; - BinOpr nextop; - luaX_next(ls); - luaK_infix(ls->fs, op, v); - /* read sub-expression with higher priority */ - nextop = subexpr(ls, &v2, priority[op].right); - luaK_posfix(ls->fs, op, v, &v2); - op = nextop; - } - leavelevel(ls); - return op; /* return first untreated operator */ -} - - -static void expr (LexState *ls, expdesc *v) { - subexpr(ls, v, 0); -} - -/* }==================================================================== */ - - - -/* -** {====================================================================== -** Rules for Statements -** ======================================================================= -*/ - - -static int block_follow (int token) { - switch (token) { - case TK_ELSE: case TK_ELSEIF: case TK_END: - case TK_UNTIL: case TK_EOS: - return 1; - default: return 0; - } -} - - -static void block (LexState *ls) { - /* block -> chunk */ - FuncState *fs = ls->fs; - BlockCnt bl; - enterblock(fs, &bl, 0); - chunk(ls); - lua_assert(bl.breaklist == NO_JUMP); - leaveblock(fs); -} - - -/* -** structure to chain all variables in the left-hand side of an -** assignment -*/ -struct LHS_assign { - struct LHS_assign *prev; - expdesc v; /* variable (global, local, upvalue, or indexed) */ -}; - - -/* -** check whether, in an assignment to a local variable, the local variable -** is needed in a previous assignment (to a table). If so, save original -** local value in a safe place and use this safe copy in the previous -** assignment. -*/ -static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { - FuncState *fs = ls->fs; - int extra = fs->freereg; /* eventual position to save local variable */ - int conflict = 0; - for (; lh; lh = lh->prev) { - if (lh->v.k == VINDEXED) { - if (lh->v.u.s.info == v->u.s.info) { /* conflict? */ - conflict = 1; - lh->v.u.s.info = extra; /* previous assignment will use safe copy */ - } - if (lh->v.u.s.aux == v->u.s.info) { /* conflict? */ - conflict = 1; - lh->v.u.s.aux = extra; /* previous assignment will use safe copy */ - } - } - } - if (conflict) { - luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0); /* make copy */ - luaK_reserveregs(fs, 1); - } -} - - -static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) { - expdesc e; - check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED, - "syntax error"); - if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */ - struct LHS_assign nv; - nv.prev = lh; - primaryexp(ls, &nv.v); - if (nv.v.k == VLOCAL) - check_conflict(ls, lh, &nv.v); - luaY_checklimit(ls->fs, nvars, LUAI_MAXCCALLS - ls->L->nCcalls, - "variables in assignment"); - assignment(ls, &nv, nvars+1); - } - else { /* assignment -> `=' explist1 */ - int nexps; - checknext(ls, '='); - nexps = explist1(ls, &e); - if (nexps != nvars) { - adjust_assign(ls, nvars, nexps, &e); - if (nexps > nvars) - ls->fs->freereg -= nexps - nvars; /* remove extra values */ - } - else { - luaK_setoneret(ls->fs, &e); /* close last expression */ - luaK_storevar(ls->fs, &lh->v, &e); - return; /* avoid default */ - } - } - init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */ - luaK_storevar(ls->fs, &lh->v, &e); -} - - -static int cond (LexState *ls) { - /* cond -> exp */ - expdesc v; - expr(ls, &v); /* read condition */ - if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */ - luaK_goiftrue(ls->fs, &v); - return v.f; -} - - -static void breakstat (LexState *ls) { - FuncState *fs = ls->fs; - BlockCnt *bl = fs->bl; - int upval = 0; - while (bl && !bl->isbreakable) { - upval |= bl->upval; - bl = bl->previous; - } - if (!bl) - luaX_syntaxerror(ls, "no loop to break"); - if (upval) - luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0); - luaK_concat(fs, &bl->breaklist, luaK_jump(fs)); -} - - -static void whilestat (LexState *ls, int line) { - /* whilestat -> WHILE cond DO block END */ - FuncState *fs = ls->fs; - int whileinit; - int condexit; - BlockCnt bl; - luaX_next(ls); /* skip WHILE */ - whileinit = luaK_getlabel(fs); - condexit = cond(ls); - enterblock(fs, &bl, 1); - checknext(ls, TK_DO); - block(ls); - luaK_patchlist(fs, luaK_jump(fs), whileinit); - check_match(ls, TK_END, TK_WHILE, line); - leaveblock(fs); - luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ -} - - -static void repeatstat (LexState *ls, int line) { - /* repeatstat -> REPEAT block UNTIL cond */ - int condexit; - FuncState *fs = ls->fs; - int repeat_init = luaK_getlabel(fs); - BlockCnt bl1, bl2; - enterblock(fs, &bl1, 1); /* loop block */ - enterblock(fs, &bl2, 0); /* scope block */ - luaX_next(ls); /* skip REPEAT */ - chunk(ls); - check_match(ls, TK_UNTIL, TK_REPEAT, line); - condexit = cond(ls); /* read condition (inside scope block) */ - if (!bl2.upval) { /* no upvalues? */ - leaveblock(fs); /* finish scope */ - luaK_patchlist(ls->fs, condexit, repeat_init); /* close the loop */ - } - else { /* complete semantics when there are upvalues */ - breakstat(ls); /* if condition then break */ - luaK_patchtohere(ls->fs, condexit); /* else... */ - leaveblock(fs); /* finish scope... */ - luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init); /* and repeat */ - } - leaveblock(fs); /* finish loop */ -} - - -static int exp1 (LexState *ls) { - expdesc e; - int k; - expr(ls, &e); - k = e.k; - luaK_exp2nextreg(ls->fs, &e); - return k; -} - - -static void forbody (LexState *ls, int base, int line, int nvars, int isnum) { - /* forbody -> DO block */ - BlockCnt bl; - FuncState *fs = ls->fs; - int prep, endfor; - adjustlocalvars(ls, 3); /* control variables */ - checknext(ls, TK_DO); - prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs); - enterblock(fs, &bl, 0); /* scope for declared variables */ - adjustlocalvars(ls, nvars); - luaK_reserveregs(fs, nvars); - block(ls); - leaveblock(fs); /* end of scope for declared variables */ - luaK_patchtohere(fs, prep); - endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) : - luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars); - luaK_fixline(fs, line); /* pretend that `OP_FOR' starts the loop */ - luaK_patchlist(fs, (isnum ? endfor : luaK_jump(fs)), prep + 1); -} - - -static void fornum (LexState *ls, TString *varname, int line) { - /* fornum -> NAME = exp1,exp1[,exp1] forbody */ - FuncState *fs = ls->fs; - int base = fs->freereg; - new_localvarliteral(ls, "(for index)", 0); - new_localvarliteral(ls, "(for limit)", 1); - new_localvarliteral(ls, "(for step)", 2); - new_localvar(ls, varname, 3); - checknext(ls, '='); - exp1(ls); /* initial value */ - checknext(ls, ','); - exp1(ls); /* limit */ - if (testnext(ls, ',')) - exp1(ls); /* optional step */ - else { /* default step = 1 */ - luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1)); - luaK_reserveregs(fs, 1); - } - forbody(ls, base, line, 1, 1); -} - - -static void forlist (LexState *ls, TString *indexname) { - /* forlist -> NAME {,NAME} IN explist1 forbody */ - FuncState *fs = ls->fs; - expdesc e; - int nvars = 0; - int line; - int base = fs->freereg; - /* create control variables */ - new_localvarliteral(ls, "(for generator)", nvars++); - new_localvarliteral(ls, "(for state)", nvars++); - new_localvarliteral(ls, "(for control)", nvars++); - /* create declared variables */ - new_localvar(ls, indexname, nvars++); - while (testnext(ls, ',')) - new_localvar(ls, str_checkname(ls), nvars++); - checknext(ls, TK_IN); - line = ls->linenumber; - adjust_assign(ls, 3, explist1(ls, &e), &e); - luaK_checkstack(fs, 3); /* extra space to call generator */ - forbody(ls, base, line, nvars - 3, 0); -} - - -static void forstat (LexState *ls, int line) { - /* forstat -> FOR (fornum | forlist) END */ - FuncState *fs = ls->fs; - TString *varname; - BlockCnt bl; - enterblock(fs, &bl, 1); /* scope for loop and control variables */ - luaX_next(ls); /* skip `for' */ - varname = str_checkname(ls); /* first variable name */ - switch (ls->t.token) { - case '=': fornum(ls, varname, line); break; - case ',': case TK_IN: forlist(ls, varname); break; - default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected"); - } - check_match(ls, TK_END, TK_FOR, line); - leaveblock(fs); /* loop scope (`break' jumps to this point) */ -} - - -static int test_then_block (LexState *ls) { - /* test_then_block -> [IF | ELSEIF] cond THEN block */ - int condexit; - luaX_next(ls); /* skip IF or ELSEIF */ - condexit = cond(ls); - checknext(ls, TK_THEN); - block(ls); /* `then' part */ - return condexit; -} - - -static void ifstat (LexState *ls, int line) { - /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ - FuncState *fs = ls->fs; - int flist; - int escapelist = NO_JUMP; - flist = test_then_block(ls); /* IF cond THEN block */ - while (ls->t.token == TK_ELSEIF) { - luaK_concat(fs, &escapelist, luaK_jump(fs)); - luaK_patchtohere(fs, flist); - flist = test_then_block(ls); /* ELSEIF cond THEN block */ - } - if (ls->t.token == TK_ELSE) { - luaK_concat(fs, &escapelist, luaK_jump(fs)); - luaK_patchtohere(fs, flist); - luaX_next(ls); /* skip ELSE (after patch, for correct line info) */ - block(ls); /* `else' part */ - } - else - luaK_concat(fs, &escapelist, flist); - luaK_patchtohere(fs, escapelist); - check_match(ls, TK_END, TK_IF, line); -} - - -static void localfunc (LexState *ls) { - expdesc v, b; - FuncState *fs = ls->fs; - new_localvar(ls, str_checkname(ls), 0); - init_exp(&v, VLOCAL, fs->freereg); - luaK_reserveregs(fs, 1); - adjustlocalvars(ls, 1); - body(ls, &b, 0, ls->linenumber); - luaK_storevar(fs, &v, &b); - /* debug information will only see the variable after this point! */ - getlocvar(fs, fs->nactvar - 1).startpc = fs->pc; -} - - -static void localstat (LexState *ls) { - /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */ - int nvars = 0; - int nexps; - expdesc e; - do { - new_localvar(ls, str_checkname(ls), nvars++); - } while (testnext(ls, ',')); - if (testnext(ls, '=')) - nexps = explist1(ls, &e); - else { - e.k = VVOID; - nexps = 0; - } - adjust_assign(ls, nvars, nexps, &e); - adjustlocalvars(ls, nvars); -} - - -static int funcname (LexState *ls, expdesc *v) { - /* funcname -> NAME {field} [`:' NAME] */ - int needself = 0; - singlevar(ls, v); - while (ls->t.token == '.') - field(ls, v); - if (ls->t.token == ':') { - needself = 1; - field(ls, v); - } - return needself; -} - - -static void funcstat (LexState *ls, int line) { - /* funcstat -> FUNCTION funcname body */ - int needself; - expdesc v, b; - luaX_next(ls); /* skip FUNCTION */ - needself = funcname(ls, &v); - body(ls, &b, needself, line); - luaK_storevar(ls->fs, &v, &b); - luaK_fixline(ls->fs, line); /* definition `happens' in the first line */ -} - - -static void exprstat (LexState *ls) { - /* stat -> func | assignment */ - FuncState *fs = ls->fs; - struct LHS_assign v; - primaryexp(ls, &v.v); - if (v.v.k == VCALL) /* stat -> func */ - SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */ - else { /* stat -> assignment */ - v.prev = NULL; - assignment(ls, &v, 1); - } -} - - -static void retstat (LexState *ls) { - /* stat -> RETURN explist */ - FuncState *fs = ls->fs; - expdesc e; - int first, nret; /* registers with returned values */ - luaX_next(ls); /* skip RETURN */ - if (block_follow(ls->t.token) || ls->t.token == ';') - first = nret = 0; /* return no values */ - else { - nret = explist1(ls, &e); /* optional return values */ - if (hasmultret(e.k)) { - luaK_setmultret(fs, &e); - if (e.k == VCALL && nret == 1) { /* tail call? */ - SET_OPCODE(getcode(fs,&e), OP_TAILCALL); - lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar); - } - first = fs->nactvar; - nret = LUA_MULTRET; /* return all values */ - } - else { - if (nret == 1) /* only one single value? */ - first = luaK_exp2anyreg(fs, &e); - else { - luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */ - first = fs->nactvar; /* return all `active' values */ - lua_assert(nret == fs->freereg - first); - } - } - } - luaK_ret(fs, first, nret); -} - - -static int statement (LexState *ls) { - int line = ls->linenumber; /* may be needed for error messages */ - switch (ls->t.token) { - case TK_IF: { /* stat -> ifstat */ - ifstat(ls, line); - return 0; - } - case TK_WHILE: { /* stat -> whilestat */ - whilestat(ls, line); - return 0; - } - case TK_DO: { /* stat -> DO block END */ - luaX_next(ls); /* skip DO */ - block(ls); - check_match(ls, TK_END, TK_DO, line); - return 0; - } - case TK_FOR: { /* stat -> forstat */ - forstat(ls, line); - return 0; - } - case TK_REPEAT: { /* stat -> repeatstat */ - repeatstat(ls, line); - return 0; - } - case TK_FUNCTION: { - funcstat(ls, line); /* stat -> funcstat */ - return 0; - } - case TK_LOCAL: { /* stat -> localstat */ - luaX_next(ls); /* skip LOCAL */ - if (testnext(ls, TK_FUNCTION)) /* local function? */ - localfunc(ls); - else - localstat(ls); - return 0; - } - case TK_RETURN: { /* stat -> retstat */ - retstat(ls); - return 1; /* must be last statement */ - } - case TK_BREAK: { /* stat -> breakstat */ - luaX_next(ls); /* skip BREAK */ - breakstat(ls); - return 1; /* must be last statement */ - } - default: { - exprstat(ls); - return 0; /* to avoid warnings */ - } - } -} - - -static void chunk (LexState *ls) { - /* chunk -> { stat [`;'] } */ - int islast = 0; - enterlevel(ls); - while (!islast && !block_follow(ls->t.token)) { - islast = statement(ls); - testnext(ls, ';'); - lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && - ls->fs->freereg >= ls->fs->nactvar); - ls->fs->freereg = ls->fs->nactvar; /* free registers */ - } - leavelevel(ls); -} - -/* }====================================================================== */ diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lparser.h b/desmume/src/windows/lua/lua-5.1.4/src/lparser.h deleted file mode 100644 index 18836afd1..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lparser.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -** $Id: lparser.h,v 1.57.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lua Parser -** See Copyright Notice in lua.h -*/ - -#ifndef lparser_h -#define lparser_h - -#include "llimits.h" -#include "lobject.h" -#include "lzio.h" - - -/* -** Expression descriptor -*/ - -typedef enum { - VVOID, /* no value */ - VNIL, - VTRUE, - VFALSE, - VK, /* info = index of constant in `k' */ - VKNUM, /* nval = numerical value */ - VLOCAL, /* info = local register */ - VUPVAL, /* info = index of upvalue in `upvalues' */ - VGLOBAL, /* info = index of table; aux = index of global name in `k' */ - VINDEXED, /* info = table register; aux = index register (or `k') */ - VJMP, /* info = instruction pc */ - VRELOCABLE, /* info = instruction pc */ - VNONRELOC, /* info = result register */ - VCALL, /* info = instruction pc */ - VVARARG /* info = instruction pc */ -} expkind; - -typedef struct expdesc { - expkind k; - union { - struct { int info, aux; } s; - lua_Number nval; - } u; - int t; /* patch list of `exit when true' */ - int f; /* patch list of `exit when false' */ -} expdesc; - - -typedef struct upvaldesc { - lu_byte k; - lu_byte info; -} upvaldesc; - - -struct BlockCnt; /* defined in lparser.c */ - - -/* state needed to generate code for a given function */ -typedef struct FuncState { - Proto *f; /* current function header */ - Table *h; /* table to find (and reuse) elements in `k' */ - struct FuncState *prev; /* enclosing function */ - struct LexState *ls; /* lexical state */ - struct lua_State *L; /* copy of the Lua state */ - struct BlockCnt *bl; /* chain of current blocks */ - int pc; /* next position to code (equivalent to `ncode') */ - int lasttarget; /* `pc' of last `jump target' */ - int jpc; /* list of pending jumps to `pc' */ - int freereg; /* first free register */ - int nk; /* number of elements in `k' */ - int np; /* number of elements in `p' */ - short nlocvars; /* number of elements in `locvars' */ - lu_byte nactvar; /* number of active local variables */ - upvaldesc upvalues[LUAI_MAXUPVALUES]; /* upvalues */ - unsigned short actvar[LUAI_MAXVARS]; /* declared-variable stack */ -} FuncState; - - -LUAI_FUNC Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, - const char *name); - - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lstate.c b/desmume/src/windows/lua/lua-5.1.4/src/lstate.c deleted file mode 100644 index 4313b83a0..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lstate.c +++ /dev/null @@ -1,214 +0,0 @@ -/* -** $Id: lstate.c,v 2.36.1.2 2008/01/03 15:20:39 roberto Exp $ -** Global State -** See Copyright Notice in lua.h -*/ - - -#include - -#define lstate_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lgc.h" -#include "llex.h" -#include "lmem.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" - - -#define state_size(x) (sizeof(x) + LUAI_EXTRASPACE) -#define fromstate(l) (cast(lu_byte *, (l)) - LUAI_EXTRASPACE) -#define tostate(l) (cast(lua_State *, cast(lu_byte *, l) + LUAI_EXTRASPACE)) - - -/* -** Main thread combines a thread state and the global state -*/ -typedef struct LG { - lua_State l; - global_State g; -} LG; - - - -static void stack_init (lua_State *L1, lua_State *L) { - /* initialize CallInfo array */ - L1->base_ci = luaM_newvector(L, BASIC_CI_SIZE, CallInfo); - L1->ci = L1->base_ci; - L1->size_ci = BASIC_CI_SIZE; - L1->end_ci = L1->base_ci + L1->size_ci - 1; - /* initialize stack array */ - L1->stack = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, TValue); - L1->stacksize = BASIC_STACK_SIZE + EXTRA_STACK; - L1->top = L1->stack; - L1->stack_last = L1->stack+(L1->stacksize - EXTRA_STACK)-1; - /* initialize first ci */ - L1->ci->func = L1->top; - setnilvalue(L1->top++); /* `function' entry for this `ci' */ - L1->base = L1->ci->base = L1->top; - L1->ci->top = L1->top + LUA_MINSTACK; -} - - -static void freestack (lua_State *L, lua_State *L1) { - luaM_freearray(L, L1->base_ci, L1->size_ci, CallInfo); - luaM_freearray(L, L1->stack, L1->stacksize, TValue); -} - - -/* -** open parts that may cause memory-allocation errors -*/ -static void f_luaopen (lua_State *L, void *ud) { - global_State *g = G(L); - UNUSED(ud); - stack_init(L, L); /* init stack */ - sethvalue(L, gt(L), luaH_new(L, 0, 2)); /* table of globals */ - sethvalue(L, registry(L), luaH_new(L, 0, 2)); /* registry */ - luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */ - luaT_init(L); - luaX_init(L); - luaS_fix(luaS_newliteral(L, MEMERRMSG)); - g->GCthreshold = 4*g->totalbytes; -} - - -static void preinit_state (lua_State *L, global_State *g) { - G(L) = g; - L->stack = NULL; - L->stacksize = 0; - L->errorJmp = NULL; - L->hook = NULL; - L->hookmask = 0; - L->basehookcount = 0; - L->allowhook = 1; - resethookcount(L); - L->openupval = NULL; - L->size_ci = 0; - L->nCcalls = L->baseCcalls = 0; - L->status = 0; - L->base_ci = L->ci = NULL; - L->savedpc = NULL; - L->errfunc = 0; - setnilvalue(gt(L)); -} - - -static void close_state (lua_State *L) { - global_State *g = G(L); - luaF_close(L, L->stack); /* close all upvalues for this thread */ - luaC_freeall(L); /* collect all objects */ - lua_assert(g->rootgc == obj2gco(L)); - lua_assert(g->strt.nuse == 0); - luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size, TString *); - luaZ_freebuffer(L, &g->buff); - freestack(L, L); - lua_assert(g->totalbytes == sizeof(LG)); - (*g->frealloc)(g->ud, fromstate(L), state_size(LG), 0); -} - - -lua_State *luaE_newthread (lua_State *L) { - lua_State *L1 = tostate(luaM_malloc(L, state_size(lua_State))); - luaC_link(L, obj2gco(L1), LUA_TTHREAD); - preinit_state(L1, G(L)); - stack_init(L1, L); /* init stack */ - setobj2n(L, gt(L1), gt(L)); /* share table of globals */ - L1->hookmask = L->hookmask; - L1->basehookcount = L->basehookcount; - L1->hook = L->hook; - resethookcount(L1); - lua_assert(iswhite(obj2gco(L1))); - return L1; -} - - -void luaE_freethread (lua_State *L, lua_State *L1) { - luaF_close(L1, L1->stack); /* close all upvalues for this thread */ - lua_assert(L1->openupval == NULL); - luai_userstatefree(L1); - freestack(L, L1); - luaM_freemem(L, fromstate(L1), state_size(lua_State)); -} - - -LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { - int i; - lua_State *L; - global_State *g; - void *l = (*f)(ud, NULL, 0, state_size(LG)); - if (l == NULL) return NULL; - L = tostate(l); - g = &((LG *)L)->g; - L->next = NULL; - L->tt = LUA_TTHREAD; - g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT); - L->marked = luaC_white(g); - set2bits(L->marked, FIXEDBIT, SFIXEDBIT); - preinit_state(L, g); - g->frealloc = f; - g->ud = ud; - g->mainthread = L; - g->uvhead.u.l.prev = &g->uvhead; - g->uvhead.u.l.next = &g->uvhead; - g->GCthreshold = 0; /* mark it as unfinished state */ - g->strt.size = 0; - g->strt.nuse = 0; - g->strt.hash = NULL; - setnilvalue(registry(L)); - luaZ_initbuffer(L, &g->buff); - g->panic = NULL; - g->gcstate = GCSpause; - g->rootgc = obj2gco(L); - g->sweepstrgc = 0; - g->sweepgc = &g->rootgc; - g->gray = NULL; - g->grayagain = NULL; - g->weak = NULL; - g->tmudata = NULL; - g->totalbytes = sizeof(LG); - g->gcpause = LUAI_GCPAUSE; - g->gcstepmul = LUAI_GCMUL; - g->gcdept = 0; - for (i=0; imt[i] = NULL; - if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) { - /* memory allocation error: free partial state */ - close_state(L); - L = NULL; - } - else - luai_userstateopen(L); - return L; -} - - -static void callallgcTM (lua_State *L, void *ud) { - UNUSED(ud); - luaC_callGCTM(L); /* call GC metamethods for all udata */ -} - - -LUA_API void lua_close (lua_State *L) { - L = G(L)->mainthread; /* only the main thread can be closed */ - lua_lock(L); - luaF_close(L, L->stack); /* close all upvalues for this thread */ - luaC_separateudata(L, 1); /* separate udata that have GC metamethods */ - L->errfunc = 0; /* no error function during GC metamethods */ - do { /* repeat until no more errors */ - L->ci = L->base_ci; - L->base = L->top = L->ci->base; - L->nCcalls = L->baseCcalls = 0; - } while (luaD_rawrunprotected(L, callallgcTM, NULL) != 0); - lua_assert(G(L)->tmudata == NULL); - luai_userstateclose(L); - close_state(L); -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lstate.h b/desmume/src/windows/lua/lua-5.1.4/src/lstate.h deleted file mode 100644 index 3bc575b6b..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lstate.h +++ /dev/null @@ -1,169 +0,0 @@ -/* -** $Id: lstate.h,v 2.24.1.2 2008/01/03 15:20:39 roberto Exp $ -** Global State -** See Copyright Notice in lua.h -*/ - -#ifndef lstate_h -#define lstate_h - -#include "lua.h" - -#include "lobject.h" -#include "ltm.h" -#include "lzio.h" - - - -struct lua_longjmp; /* defined in ldo.c */ - - -/* table of globals */ -#define gt(L) (&L->l_gt) - -/* registry */ -#define registry(L) (&G(L)->l_registry) - - -/* extra stack space to handle TM calls and some other extras */ -#define EXTRA_STACK 5 - - -#define BASIC_CI_SIZE 8 - -#define BASIC_STACK_SIZE (2*LUA_MINSTACK) - - - -typedef struct stringtable { - GCObject **hash; - lu_int32 nuse; /* number of elements */ - int size; -} stringtable; - - -/* -** informations about a call -*/ -typedef struct CallInfo { - StkId base; /* base for this function */ - StkId func; /* function index in the stack */ - StkId top; /* top for this function */ - const Instruction *savedpc; - int nresults; /* expected number of results from this function */ - int tailcalls; /* number of tail calls lost under this entry */ -} CallInfo; - - - -#define curr_func(L) (clvalue(L->ci->func)) -#define ci_func(ci) (clvalue((ci)->func)) -#define f_isLua(ci) (!ci_func(ci)->c.isC) -#define isLua(ci) (ttisfunction((ci)->func) && f_isLua(ci)) - - -/* -** `global state', shared by all threads of this state -*/ -typedef struct global_State { - stringtable strt; /* hash table for strings */ - lua_Alloc frealloc; /* function to reallocate memory */ - void *ud; /* auxiliary data to `frealloc' */ - lu_byte currentwhite; - lu_byte gcstate; /* state of garbage collector */ - int sweepstrgc; /* position of sweep in `strt' */ - GCObject *rootgc; /* list of all collectable objects */ - GCObject **sweepgc; /* position of sweep in `rootgc' */ - GCObject *gray; /* list of gray objects */ - GCObject *grayagain; /* list of objects to be traversed atomically */ - GCObject *weak; /* list of weak tables (to be cleared) */ - GCObject *tmudata; /* last element of list of userdata to be GC */ - Mbuffer buff; /* temporary buffer for string concatentation */ - lu_mem GCthreshold; - lu_mem totalbytes; /* number of bytes currently allocated */ - lu_mem estimate; /* an estimate of number of bytes actually in use */ - lu_mem gcdept; /* how much GC is `behind schedule' */ - int gcpause; /* size of pause between successive GCs */ - int gcstepmul; /* GC `granularity' */ - lua_CFunction panic; /* to be called in unprotected errors */ - TValue l_registry; - struct lua_State *mainthread; - UpVal uvhead; /* head of double-linked list of all open upvalues */ - struct Table *mt[NUM_TAGS]; /* metatables for basic types */ - TString *tmname[TM_N]; /* array with tag-method names */ -} global_State; - - -/* -** `per thread' state -*/ -struct lua_State { - CommonHeader; - lu_byte status; - StkId top; /* first free slot in the stack */ - StkId base; /* base of current function */ - global_State *l_G; - CallInfo *ci; /* call info for current function */ - const Instruction *savedpc; /* `savedpc' of current function */ - StkId stack_last; /* last free slot in the stack */ - StkId stack; /* stack base */ - CallInfo *end_ci; /* points after end of ci array*/ - CallInfo *base_ci; /* array of CallInfo's */ - int stacksize; - int size_ci; /* size of array `base_ci' */ - unsigned short nCcalls; /* number of nested C calls */ - unsigned short baseCcalls; /* nested C calls when resuming coroutine */ - lu_byte hookmask; - lu_byte allowhook; - int basehookcount; - int hookcount; - lua_Hook hook; - TValue l_gt; /* table of globals */ - TValue env; /* temporary place for environments */ - GCObject *openupval; /* list of open upvalues in this stack */ - GCObject *gclist; - struct lua_longjmp *errorJmp; /* current error recover point */ - ptrdiff_t errfunc; /* current error handling function (stack index) */ -}; - - -#define G(L) (L->l_G) - - -/* -** Union of all collectable objects -*/ -union GCObject { - GCheader gch; - union TString ts; - union Udata u; - union Closure cl; - struct Table h; - struct Proto p; - struct UpVal uv; - struct lua_State th; /* thread */ -}; - - -/* macros to convert a GCObject into a specific value */ -#define rawgco2ts(o) check_exp((o)->gch.tt == LUA_TSTRING, &((o)->ts)) -#define gco2ts(o) (&rawgco2ts(o)->tsv) -#define rawgco2u(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u)) -#define gco2u(o) (&rawgco2u(o)->uv) -#define gco2cl(o) check_exp((o)->gch.tt == LUA_TFUNCTION, &((o)->cl)) -#define gco2h(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h)) -#define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p)) -#define gco2uv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv)) -#define ngcotouv(o) \ - check_exp((o) == NULL || (o)->gch.tt == LUA_TUPVAL, &((o)->uv)) -#define gco2th(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th)) - -/* macro to convert any Lua object into a GCObject */ -#define obj2gco(v) (cast(GCObject *, (v))) - - -LUAI_FUNC lua_State *luaE_newthread (lua_State *L); -LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); - -#endif - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lstring.c b/desmume/src/windows/lua/lua-5.1.4/src/lstring.c deleted file mode 100644 index 49113151c..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lstring.c +++ /dev/null @@ -1,111 +0,0 @@ -/* -** $Id: lstring.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $ -** String table (keeps all strings handled by Lua) -** See Copyright Notice in lua.h -*/ - - -#include - -#define lstring_c -#define LUA_CORE - -#include "lua.h" - -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" -#include "lstring.h" - - - -void luaS_resize (lua_State *L, int newsize) { - GCObject **newhash; - stringtable *tb; - int i; - if (G(L)->gcstate == GCSsweepstring) - return; /* cannot resize during GC traverse */ - newhash = luaM_newvector(L, newsize, GCObject *); - tb = &G(L)->strt; - for (i=0; isize; i++) { - GCObject *p = tb->hash[i]; - while (p) { /* for each node in the list */ - GCObject *next = p->gch.next; /* save next */ - unsigned int h = gco2ts(p)->hash; - int h1 = lmod(h, newsize); /* new position */ - lua_assert(cast_int(h%newsize) == lmod(h, newsize)); - p->gch.next = newhash[h1]; /* chain it */ - newhash[h1] = p; - p = next; - } - } - luaM_freearray(L, tb->hash, tb->size, TString *); - tb->size = newsize; - tb->hash = newhash; -} - - -static TString *newlstr (lua_State *L, const char *str, size_t l, - unsigned int h) { - TString *ts; - stringtable *tb; - if (l+1 > (MAX_SIZET - sizeof(TString))/sizeof(char)) - luaM_toobig(L); - ts = cast(TString *, luaM_malloc(L, (l+1)*sizeof(char)+sizeof(TString))); - ts->tsv.len = l; - ts->tsv.hash = h; - ts->tsv.marked = luaC_white(G(L)); - ts->tsv.tt = LUA_TSTRING; - ts->tsv.reserved = 0; - memcpy(ts+1, str, l*sizeof(char)); - ((char *)(ts+1))[l] = '\0'; /* ending 0 */ - tb = &G(L)->strt; - h = lmod(h, tb->size); - ts->tsv.next = tb->hash[h]; /* chain new entry */ - tb->hash[h] = obj2gco(ts); - tb->nuse++; - if (tb->nuse > cast(lu_int32, tb->size) && tb->size <= MAX_INT/2) - luaS_resize(L, tb->size*2); /* too crowded */ - return ts; -} - - -TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { - GCObject *o; - unsigned int h = cast(unsigned int, l); /* seed */ - size_t step = (l>>5)+1; /* if string is too long, don't hash all its chars */ - size_t l1; - for (l1=l; l1>=step; l1-=step) /* compute hash */ - h = h ^ ((h<<5)+(h>>2)+cast(unsigned char, str[l1-1])); - for (o = G(L)->strt.hash[lmod(h, G(L)->strt.size)]; - o != NULL; - o = o->gch.next) { - TString *ts = rawgco2ts(o); - if (ts->tsv.len == l && (memcmp(str, getstr(ts), l) == 0)) { - /* string may be dead */ - if (isdead(G(L), o)) changewhite(o); - return ts; - } - } - return newlstr(L, str, l, h); /* not found */ -} - - -Udata *luaS_newudata (lua_State *L, size_t s, Table *e) { - Udata *u; - if (s > MAX_SIZET - sizeof(Udata)) - luaM_toobig(L); - u = cast(Udata *, luaM_malloc(L, s + sizeof(Udata))); - u->uv.marked = luaC_white(G(L)); /* is not finalized */ - u->uv.tt = LUA_TUSERDATA; - u->uv.len = s; - u->uv.metatable = NULL; - u->uv.env = e; - /* chain it on udata list (after main thread) */ - u->uv.next = G(L)->mainthread->next; - G(L)->mainthread->next = obj2gco(u); - return u; -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lstring.h b/desmume/src/windows/lua/lua-5.1.4/src/lstring.h deleted file mode 100644 index 73a2ff8b3..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lstring.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -** $Id: lstring.h,v 1.43.1.1 2007/12/27 13:02:25 roberto Exp $ -** String table (keep all strings handled by Lua) -** See Copyright Notice in lua.h -*/ - -#ifndef lstring_h -#define lstring_h - - -#include "lgc.h" -#include "lobject.h" -#include "lstate.h" - - -#define sizestring(s) (sizeof(union TString)+((s)->len+1)*sizeof(char)) - -#define sizeudata(u) (sizeof(union Udata)+(u)->len) - -#define luaS_new(L, s) (luaS_newlstr(L, s, strlen(s))) -#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \ - (sizeof(s)/sizeof(char))-1)) - -#define luaS_fix(s) l_setbit((s)->tsv.marked, FIXEDBIT) - -LUAI_FUNC void luaS_resize (lua_State *L, int newsize); -LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e); -LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l); - - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lstrlib.c b/desmume/src/windows/lua/lua-5.1.4/src/lstrlib.c deleted file mode 100644 index 1b4763d4e..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lstrlib.c +++ /dev/null @@ -1,869 +0,0 @@ -/* -** $Id: lstrlib.c,v 1.132.1.4 2008/07/11 17:27:21 roberto Exp $ -** Standard library for string operations and pattern-matching -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include -#include - -#define lstrlib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - -/* macro to `unsign' a character */ -#define uchar(c) ((unsigned char)(c)) - - - -static int str_len (lua_State *L) { - size_t l; - luaL_checklstring(L, 1, &l); - lua_pushinteger(L, l); - return 1; -} - - -static ptrdiff_t posrelat (ptrdiff_t pos, size_t len) { - /* relative string position: negative means back from end */ - if (pos < 0) pos += (ptrdiff_t)len + 1; - return (pos >= 0) ? pos : 0; -} - - -static int str_sub (lua_State *L) { - size_t l; - const char *s = luaL_checklstring(L, 1, &l); - ptrdiff_t start = posrelat(luaL_checkinteger(L, 2), l); - ptrdiff_t end = posrelat(luaL_optinteger(L, 3, -1), l); - if (start < 1) start = 1; - if (end > (ptrdiff_t)l) end = (ptrdiff_t)l; - if (start <= end) - lua_pushlstring(L, s+start-1, end-start+1); - else lua_pushliteral(L, ""); - return 1; -} - - -static int str_reverse (lua_State *L) { - size_t l; - luaL_Buffer b; - const char *s = luaL_checklstring(L, 1, &l); - luaL_buffinit(L, &b); - while (l--) luaL_addchar(&b, s[l]); - luaL_pushresult(&b); - return 1; -} - - -static int str_lower (lua_State *L) { - size_t l; - size_t i; - luaL_Buffer b; - const char *s = luaL_checklstring(L, 1, &l); - luaL_buffinit(L, &b); - for (i=0; i 0) - luaL_addlstring(&b, s, l); - luaL_pushresult(&b); - return 1; -} - - -static int str_byte (lua_State *L) { - size_t l; - const char *s = luaL_checklstring(L, 1, &l); - ptrdiff_t posi = posrelat(luaL_optinteger(L, 2, 1), l); - ptrdiff_t pose = posrelat(luaL_optinteger(L, 3, posi), l); - int n, i; - if (posi <= 0) posi = 1; - if ((size_t)pose > l) pose = l; - if (posi > pose) return 0; /* empty interval; return no values */ - n = (int)(pose - posi + 1); - if (posi + n <= pose) /* overflow? */ - luaL_error(L, "string slice too long"); - luaL_checkstack(L, n, "string slice too long"); - for (i=0; i= ms->level || ms->capture[l].len == CAP_UNFINISHED) - return luaL_error(ms->L, "invalid capture index"); - return l; -} - - -static int capture_to_close (MatchState *ms) { - int level = ms->level; - for (level--; level>=0; level--) - if (ms->capture[level].len == CAP_UNFINISHED) return level; - return luaL_error(ms->L, "invalid pattern capture"); -} - - -static const char *classend (MatchState *ms, const char *p) { - switch (*p++) { - case L_ESC: { - if (*p == '\0') - luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")"); - return p+1; - } - case '[': { - if (*p == '^') p++; - do { /* look for a `]' */ - if (*p == '\0') - luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")"); - if (*(p++) == L_ESC && *p != '\0') - p++; /* skip escapes (e.g. `%]') */ - } while (*p != ']'); - return p+1; - } - default: { - return p; - } - } -} - - -static int match_class (int c, int cl) { - int res; - switch (tolower(cl)) { - case 'a' : res = isalpha(c); break; - case 'c' : res = iscntrl(c); break; - case 'd' : res = isdigit(c); break; - case 'l' : res = islower(c); break; - case 'p' : res = ispunct(c); break; - case 's' : res = isspace(c); break; - case 'u' : res = isupper(c); break; - case 'w' : res = isalnum(c); break; - case 'x' : res = isxdigit(c); break; - case 'z' : res = (c == 0); break; - default: return (cl == c); - } - return (islower(cl) ? res : !res); -} - - -static int matchbracketclass (int c, const char *p, const char *ec) { - int sig = 1; - if (*(p+1) == '^') { - sig = 0; - p++; /* skip the `^' */ - } - while (++p < ec) { - if (*p == L_ESC) { - p++; - if (match_class(c, uchar(*p))) - return sig; - } - else if ((*(p+1) == '-') && (p+2 < ec)) { - p+=2; - if (uchar(*(p-2)) <= c && c <= uchar(*p)) - return sig; - } - else if (uchar(*p) == c) return sig; - } - return !sig; -} - - -static int singlematch (int c, const char *p, const char *ep) { - switch (*p) { - case '.': return 1; /* matches any char */ - case L_ESC: return match_class(c, uchar(*(p+1))); - case '[': return matchbracketclass(c, p, ep-1); - default: return (uchar(*p) == c); - } -} - - -static const char *match (MatchState *ms, const char *s, const char *p); - - -static const char *matchbalance (MatchState *ms, const char *s, - const char *p) { - if (*p == 0 || *(p+1) == 0) - luaL_error(ms->L, "unbalanced pattern"); - if (*s != *p) return NULL; - else { - int b = *p; - int e = *(p+1); - int cont = 1; - while (++s < ms->src_end) { - if (*s == e) { - if (--cont == 0) return s+1; - } - else if (*s == b) cont++; - } - } - return NULL; /* string ends out of balance */ -} - - -static const char *max_expand (MatchState *ms, const char *s, - const char *p, const char *ep) { - ptrdiff_t i = 0; /* counts maximum expand for item */ - while ((s+i)src_end && singlematch(uchar(*(s+i)), p, ep)) - i++; - /* keeps trying to match with the maximum repetitions */ - while (i>=0) { - const char *res = match(ms, (s+i), ep+1); - if (res) return res; - i--; /* else didn't match; reduce 1 repetition to try again */ - } - return NULL; -} - - -static const char *min_expand (MatchState *ms, const char *s, - const char *p, const char *ep) { - for (;;) { - const char *res = match(ms, s, ep+1); - if (res != NULL) - return res; - else if (ssrc_end && singlematch(uchar(*s), p, ep)) - s++; /* try with one more repetition */ - else return NULL; - } -} - - -static const char *start_capture (MatchState *ms, const char *s, - const char *p, int what) { - const char *res; - int level = ms->level; - if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); - ms->capture[level].init = s; - ms->capture[level].len = what; - ms->level = level+1; - if ((res=match(ms, s, p)) == NULL) /* match failed? */ - ms->level--; /* undo capture */ - return res; -} - - -static const char *end_capture (MatchState *ms, const char *s, - const char *p) { - int l = capture_to_close(ms); - const char *res; - ms->capture[l].len = s - ms->capture[l].init; /* close capture */ - if ((res = match(ms, s, p)) == NULL) /* match failed? */ - ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ - return res; -} - - -static const char *match_capture (MatchState *ms, const char *s, int l) { - size_t len; - l = check_capture(ms, l); - len = ms->capture[l].len; - if ((size_t)(ms->src_end-s) >= len && - memcmp(ms->capture[l].init, s, len) == 0) - return s+len; - else return NULL; -} - - -static const char *match (MatchState *ms, const char *s, const char *p) { - init: /* using goto's to optimize tail recursion */ - switch (*p) { - case '(': { /* start capture */ - if (*(p+1) == ')') /* position capture? */ - return start_capture(ms, s, p+2, CAP_POSITION); - else - return start_capture(ms, s, p+1, CAP_UNFINISHED); - } - case ')': { /* end capture */ - return end_capture(ms, s, p+1); - } - case L_ESC: { - switch (*(p+1)) { - case 'b': { /* balanced string? */ - s = matchbalance(ms, s, p+2); - if (s == NULL) return NULL; - p+=4; goto init; /* else return match(ms, s, p+4); */ - } - case 'f': { /* frontier? */ - const char *ep; char previous; - p += 2; - if (*p != '[') - luaL_error(ms->L, "missing " LUA_QL("[") " after " - LUA_QL("%%f") " in pattern"); - ep = classend(ms, p); /* points to what is next */ - previous = (s == ms->src_init) ? '\0' : *(s-1); - if (matchbracketclass(uchar(previous), p, ep-1) || - !matchbracketclass(uchar(*s), p, ep-1)) return NULL; - p=ep; goto init; /* else return match(ms, s, ep); */ - } - default: { - if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */ - s = match_capture(ms, s, uchar(*(p+1))); - if (s == NULL) return NULL; - p+=2; goto init; /* else return match(ms, s, p+2) */ - } - goto dflt; /* case default */ - } - } - } - case '\0': { /* end of pattern */ - return s; /* match succeeded */ - } - case '$': { - if (*(p+1) == '\0') /* is the `$' the last char in pattern? */ - return (s == ms->src_end) ? s : NULL; /* check end of string */ - else goto dflt; - } - default: dflt: { /* it is a pattern item */ - const char *ep = classend(ms, p); /* points to what is next */ - int m = ssrc_end && singlematch(uchar(*s), p, ep); - switch (*ep) { - case '?': { /* optional */ - const char *res; - if (m && ((res=match(ms, s+1, ep+1)) != NULL)) - return res; - p=ep+1; goto init; /* else return match(ms, s, ep+1); */ - } - case '*': { /* 0 or more repetitions */ - return max_expand(ms, s, p, ep); - } - case '+': { /* 1 or more repetitions */ - return (m ? max_expand(ms, s+1, p, ep) : NULL); - } - case '-': { /* 0 or more repetitions (minimum) */ - return min_expand(ms, s, p, ep); - } - default: { - if (!m) return NULL; - s++; p=ep; goto init; /* else return match(ms, s+1, ep); */ - } - } - } - } -} - - - -static const char *lmemfind (const char *s1, size_t l1, - const char *s2, size_t l2) { - if (l2 == 0) return s1; /* empty strings are everywhere */ - else if (l2 > l1) return NULL; /* avoids a negative `l1' */ - else { - const char *init; /* to search for a `*s2' inside `s1' */ - l2--; /* 1st char will be checked by `memchr' */ - l1 = l1-l2; /* `s2' cannot be found after that */ - while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { - init++; /* 1st char is already checked */ - if (memcmp(init, s2+1, l2) == 0) - return init-1; - else { /* correct `l1' and `s1' to try again */ - l1 -= init-s1; - s1 = init; - } - } - return NULL; /* not found */ - } -} - - -static void push_onecapture (MatchState *ms, int i, const char *s, - const char *e) { - if (i >= ms->level) { - if (i == 0) /* ms->level == 0, too */ - lua_pushlstring(ms->L, s, e - s); /* add whole match */ - else - luaL_error(ms->L, "invalid capture index"); - } - else { - ptrdiff_t l = ms->capture[i].len; - if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture"); - if (l == CAP_POSITION) - lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1); - else - lua_pushlstring(ms->L, ms->capture[i].init, l); - } -} - - -static int push_captures (MatchState *ms, const char *s, const char *e) { - int i; - int nlevels = (ms->level == 0 && s) ? 1 : ms->level; - luaL_checkstack(ms->L, nlevels, "too many captures"); - for (i = 0; i < nlevels; i++) - push_onecapture(ms, i, s, e); - return nlevels; /* number of strings pushed */ -} - - -static int str_find_aux (lua_State *L, int find) { - size_t l1, l2; - const char *s = luaL_checklstring(L, 1, &l1); - const char *p = luaL_checklstring(L, 2, &l2); - ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1; - if (init < 0) init = 0; - else if ((size_t)(init) > l1) init = (ptrdiff_t)l1; - if (find && (lua_toboolean(L, 4) || /* explicit request? */ - strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */ - /* do a plain search */ - const char *s2 = lmemfind(s+init, l1-init, p, l2); - if (s2) { - lua_pushinteger(L, s2-s+1); - lua_pushinteger(L, s2-s+l2); - return 2; - } - } - else { - MatchState ms; - int anchor = (*p == '^') ? (p++, 1) : 0; - const char *s1=s+init; - ms.L = L; - ms.src_init = s; - ms.src_end = s+l1; - do { - const char *res; - ms.level = 0; - if ((res=match(&ms, s1, p)) != NULL) { - if (find) { - lua_pushinteger(L, s1-s+1); /* start */ - lua_pushinteger(L, res-s); /* end */ - return push_captures(&ms, NULL, 0) + 2; - } - else - return push_captures(&ms, s1, res); - } - } while (s1++ < ms.src_end && !anchor); - } - lua_pushnil(L); /* not found */ - return 1; -} - - -static int str_find (lua_State *L) { - return str_find_aux(L, 1); -} - - -static int str_match (lua_State *L) { - return str_find_aux(L, 0); -} - - -static int gmatch_aux (lua_State *L) { - MatchState ms; - size_t ls; - const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls); - const char *p = lua_tostring(L, lua_upvalueindex(2)); - const char *src; - ms.L = L; - ms.src_init = s; - ms.src_end = s+ls; - for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3)); - src <= ms.src_end; - src++) { - const char *e; - ms.level = 0; - if ((e = match(&ms, src, p)) != NULL) { - lua_Integer newstart = e-s; - if (e == src) newstart++; /* empty match? go at least one position */ - lua_pushinteger(L, newstart); - lua_replace(L, lua_upvalueindex(3)); - return push_captures(&ms, src, e); - } - } - return 0; /* not found */ -} - - -static int gmatch (lua_State *L) { - luaL_checkstring(L, 1); - luaL_checkstring(L, 2); - lua_settop(L, 2); - lua_pushinteger(L, 0); - lua_pushcclosure(L, gmatch_aux, 3); - return 1; -} - - -static int gfind_nodef (lua_State *L) { - return luaL_error(L, LUA_QL("string.gfind") " was renamed to " - LUA_QL("string.gmatch")); -} - - -static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, - const char *e) { - size_t l, i; - const char *news = lua_tolstring(ms->L, 3, &l); - for (i = 0; i < l; i++) { - if (news[i] != L_ESC) - luaL_addchar(b, news[i]); - else { - i++; /* skip ESC */ - if (!isdigit(uchar(news[i]))) - luaL_addchar(b, news[i]); - else if (news[i] == '0') - luaL_addlstring(b, s, e - s); - else { - push_onecapture(ms, news[i] - '1', s, e); - luaL_addvalue(b); /* add capture to accumulated result */ - } - } - } -} - - -static void add_value (MatchState *ms, luaL_Buffer *b, const char *s, - const char *e) { - lua_State *L = ms->L; - switch (lua_type(L, 3)) { - case LUA_TNUMBER: - case LUA_TSTRING: { - add_s(ms, b, s, e); - return; - } - case LUA_TFUNCTION: { - int n; - lua_pushvalue(L, 3); - n = push_captures(ms, s, e); - lua_call(L, n, 1); - break; - } - case LUA_TTABLE: { - push_onecapture(ms, 0, s, e); - lua_gettable(L, 3); - break; - } - } - if (!lua_toboolean(L, -1)) { /* nil or false? */ - lua_pop(L, 1); - lua_pushlstring(L, s, e - s); /* keep original text */ - } - else if (!lua_isstring(L, -1)) - luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); - luaL_addvalue(b); /* add result to accumulator */ -} - - -static int str_gsub (lua_State *L) { - size_t srcl; - const char *src = luaL_checklstring(L, 1, &srcl); - const char *p = luaL_checkstring(L, 2); - int tr = lua_type(L, 3); - int max_s = luaL_optint(L, 4, srcl+1); - int anchor = (*p == '^') ? (p++, 1) : 0; - int n = 0; - MatchState ms; - luaL_Buffer b; - luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || - tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, - "string/function/table expected"); - luaL_buffinit(L, &b); - ms.L = L; - ms.src_init = src; - ms.src_end = src+srcl; - while (n < max_s) { - const char *e; - ms.level = 0; - e = match(&ms, src, p); - if (e) { - n++; - add_value(&ms, &b, src, e); - } - if (e && e>src) /* non empty match? */ - src = e; /* skip it */ - else if (src < ms.src_end) - luaL_addchar(&b, *src++); - else break; - if (anchor) break; - } - luaL_addlstring(&b, src, ms.src_end-src); - luaL_pushresult(&b); - lua_pushinteger(L, n); /* number of substitutions */ - return 2; -} - -/* }====================================================== */ - - -/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */ -#define MAX_ITEM 512 -/* valid flags in a format specification */ -#define FLAGS "-+ #0" -/* -** maximum size of each format specification (such as '%-099.99d') -** (+10 accounts for %99.99x plus margin of error) -*/ -#define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10) - - -static void addquoted (lua_State *L, luaL_Buffer *b, int arg) { - size_t l; - const char *s = luaL_checklstring(L, arg, &l); - luaL_addchar(b, '"'); - while (l--) { - switch (*s) { - case '"': case '\\': case '\n': { - luaL_addchar(b, '\\'); - luaL_addchar(b, *s); - break; - } - case '\r': { - luaL_addlstring(b, "\\r", 2); - break; - } - case '\0': { - luaL_addlstring(b, "\\000", 4); - break; - } - default: { - luaL_addchar(b, *s); - break; - } - } - s++; - } - luaL_addchar(b, '"'); -} - -static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { - const char *p = strfrmt; - while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */ - if ((size_t)(p - strfrmt) >= sizeof(FLAGS)) - luaL_error(L, "invalid format (repeated flags)"); - if (isdigit(uchar(*p))) p++; /* skip width */ - if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ - if (*p == '.') { - p++; - if (isdigit(uchar(*p))) p++; /* skip precision */ - if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ - } - if (isdigit(uchar(*p))) - luaL_error(L, "invalid format (width or precision too long)"); - *(form++) = '%'; - strncpy(form, strfrmt, p - strfrmt + 1); - form += p - strfrmt + 1; - *form = '\0'; - return p; -} - - -static void addintlen (char *form) { - size_t l = strlen(form); - char spec = form[l - 1]; - strcpy(form + l - 1, LUA_INTFRMLEN); - form[l + sizeof(LUA_INTFRMLEN) - 2] = spec; - form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0'; -} - - -static int str_format (lua_State *L) { - int arg = 1; - size_t sfl; - const char *strfrmt = luaL_checklstring(L, arg, &sfl); - const char *strfrmt_end = strfrmt+sfl; - luaL_Buffer b; - luaL_buffinit(L, &b); - while (strfrmt < strfrmt_end) { - if (*strfrmt != L_ESC) - luaL_addchar(&b, *strfrmt++); - else if (*++strfrmt == L_ESC) - luaL_addchar(&b, *strfrmt++); /* %% */ - else { /* format item */ - char form[MAX_FORMAT]; /* to store the format (`%...') */ - char buff[MAX_ITEM]; /* to store the formatted item */ - arg++; - strfrmt = scanformat(L, strfrmt, form); - switch (*strfrmt++) { - case 'c': { - sprintf(buff, form, (int)luaL_checknumber(L, arg)); - break; - } - case 'd': case 'i': { - addintlen(form); - sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg)); - break; - } - case 'o': case 'u': case 'x': case 'X': { - addintlen(form); - sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg)); - break; - } - case 'e': case 'E': case 'f': - case 'g': case 'G': { - sprintf(buff, form, (double)luaL_checknumber(L, arg)); - break; - } - case 'q': { - addquoted(L, &b, arg); - continue; /* skip the 'addsize' at the end */ - } - case 's': { - size_t l; - const char *s = luaL_checklstring(L, arg, &l); - if (!strchr(form, '.') && l >= 100) { - /* no precision and string is too long to be formatted; - keep original string */ - lua_pushvalue(L, arg); - luaL_addvalue(&b); - continue; /* skip the `addsize' at the end */ - } - else { - sprintf(buff, form, s); - break; - } - } - default: { /* also treat cases `pnLlh' */ - return luaL_error(L, "invalid option " LUA_QL("%%%c") " to " - LUA_QL("format"), *(strfrmt - 1)); - } - } - luaL_addlstring(&b, buff, strlen(buff)); - } - } - luaL_pushresult(&b); - return 1; -} - - -static const luaL_Reg strlib[] = { - {"byte", str_byte}, - {"char", str_char}, - {"dump", str_dump}, - {"find", str_find}, - {"format", str_format}, - {"gfind", gfind_nodef}, - {"gmatch", gmatch}, - {"gsub", str_gsub}, - {"len", str_len}, - {"lower", str_lower}, - {"match", str_match}, - {"rep", str_rep}, - {"reverse", str_reverse}, - {"sub", str_sub}, - {"upper", str_upper}, - {NULL, NULL} -}; - - -static void createmetatable (lua_State *L) { - lua_createtable(L, 0, 1); /* create metatable for strings */ - lua_pushliteral(L, ""); /* dummy string */ - lua_pushvalue(L, -2); - lua_setmetatable(L, -2); /* set string metatable */ - lua_pop(L, 1); /* pop dummy string */ - lua_pushvalue(L, -2); /* string library... */ - lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */ - lua_pop(L, 1); /* pop metatable */ -} - - -/* -** Open string library -*/ -LUALIB_API int luaopen_string (lua_State *L) { - luaL_register(L, LUA_STRLIBNAME, strlib); -#if defined(LUA_COMPAT_GFIND) - lua_getfield(L, -1, "gmatch"); - lua_setfield(L, -2, "gfind"); -#endif - createmetatable(L); - return 1; -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/ltable.c b/desmume/src/windows/lua/lua-5.1.4/src/ltable.c deleted file mode 100644 index ec84f4fab..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/ltable.c +++ /dev/null @@ -1,588 +0,0 @@ -/* -** $Id: ltable.c,v 2.32.1.2 2007/12/28 15:32:23 roberto Exp $ -** Lua tables (hash) -** See Copyright Notice in lua.h -*/ - - -/* -** Implementation of tables (aka arrays, objects, or hash tables). -** Tables keep its elements in two parts: an array part and a hash part. -** Non-negative integer keys are all candidates to be kept in the array -** part. The actual size of the array is the largest `n' such that at -** least half the slots between 0 and n are in use. -** Hash uses a mix of chained scatter table with Brent's variation. -** A main invariant of these tables is that, if an element is not -** in its main position (i.e. the `original' position that its hash gives -** to it), then the colliding element is in its own main position. -** Hence even when the load factor reaches 100%, performance remains good. -*/ - -#include -#include - -#define ltable_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lgc.h" -#include "lmem.h" -#include "lobject.h" -#include "lstate.h" -#include "ltable.h" - - -/* -** max size of array part is 2^MAXBITS -*/ -#if LUAI_BITSINT > 26 -#define MAXBITS 26 -#else -#define MAXBITS (LUAI_BITSINT-2) -#endif - -#define MAXASIZE (1 << MAXBITS) - - -#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) - -#define hashstr(t,str) hashpow2(t, (str)->tsv.hash) -#define hashboolean(t,p) hashpow2(t, p) - - -/* -** for some types, it is better to avoid modulus by power of 2, as -** they tend to have many 2 factors. -*/ -#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) - - -#define hashpointer(t,p) hashmod(t, IntPoint(p)) - - -/* -** number of ints inside a lua_Number -*/ -#define numints cast_int(sizeof(lua_Number)/sizeof(int)) - - - -#define dummynode (&dummynode_) - -static const Node dummynode_ = { - {{NULL}, LUA_TNIL}, /* value */ - {{{NULL}, LUA_TNIL, NULL}} /* key */ -}; - - -/* -** hash for lua_Numbers -*/ -static Node *hashnum (const Table *t, lua_Number n) { - unsigned int a[numints]; - int i; - if (luai_numeq(n, 0)) /* avoid problems with -0 */ - return gnode(t, 0); - memcpy(a, &n, sizeof(a)); - for (i = 1; i < numints; i++) a[0] += a[i]; - return hashmod(t, a[0]); -} - - - -/* -** returns the `main' position of an element in a table (that is, the index -** of its hash value) -*/ -static Node *mainposition (const Table *t, const TValue *key) { - switch (ttype(key)) { - case LUA_TNUMBER: - return hashnum(t, nvalue(key)); - case LUA_TSTRING: - return hashstr(t, rawtsvalue(key)); - case LUA_TBOOLEAN: - return hashboolean(t, bvalue(key)); - case LUA_TLIGHTUSERDATA: - return hashpointer(t, pvalue(key)); - default: - return hashpointer(t, gcvalue(key)); - } -} - - -/* -** returns the index for `key' if `key' is an appropriate key to live in -** the array part of the table, -1 otherwise. -*/ -static int arrayindex (const TValue *key) { - if (ttisnumber(key)) { - lua_Number n = nvalue(key); - int k; - lua_number2int(k, n); - if (luai_numeq(cast_num(k), n)) - return k; - } - return -1; /* `key' did not match some condition */ -} - - -/* -** returns the index of a `key' for table traversals. First goes all -** elements in the array part, then elements in the hash part. The -** beginning of a traversal is signalled by -1. -*/ -static int findindex (lua_State *L, Table *t, StkId key) { - int i; - if (ttisnil(key)) return -1; /* first iteration */ - i = arrayindex(key); - if (0 < i && i <= t->sizearray) /* is `key' inside array part? */ - return i-1; /* yes; that's the index (corrected to C) */ - else { - Node *n = mainposition(t, key); - do { /* check whether `key' is somewhere in the chain */ - /* key may be dead already, but it is ok to use it in `next' */ - if (luaO_rawequalObj(key2tval(n), key) || - (ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) && - gcvalue(gkey(n)) == gcvalue(key))) { - i = cast_int(n - gnode(t, 0)); /* key index in hash table */ - /* hash elements are numbered after array ones */ - return i + t->sizearray; - } - else n = gnext(n); - } while (n); - luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */ - return 0; /* to avoid warnings */ - } -} - - -int luaH_next (lua_State *L, Table *t, StkId key) { - int i = findindex(L, t, key); /* find original element */ - for (i++; i < t->sizearray; i++) { /* try first array part */ - if (!ttisnil(&t->array[i])) { /* a non-nil value? */ - setnvalue(key, cast_num(i+1)); - setobj2s(L, key+1, &t->array[i]); - return 1; - } - } - for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */ - if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ - setobj2s(L, key, key2tval(gnode(t, i))); - setobj2s(L, key+1, gval(gnode(t, i))); - return 1; - } - } - return 0; /* no more elements */ -} - - -/* -** {============================================================= -** Rehash -** ============================================================== -*/ - - -static int computesizes (int nums[], int *narray) { - int i; - int twotoi; /* 2^i */ - int a = 0; /* number of elements smaller than 2^i */ - int na = 0; /* number of elements to go to array part */ - int n = 0; /* optimal size for array part */ - for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) { - if (nums[i] > 0) { - a += nums[i]; - if (a > twotoi/2) { /* more than half elements present? */ - n = twotoi; /* optimal size (till now) */ - na = a; /* all elements smaller than n will go to array part */ - } - } - if (a == *narray) break; /* all elements already counted */ - } - *narray = n; - lua_assert(*narray/2 <= na && na <= *narray); - return na; -} - - -static int countint (const TValue *key, int *nums) { - int k = arrayindex(key); - if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */ - nums[ceillog2(k)]++; /* count as such */ - return 1; - } - else - return 0; -} - - -static int numusearray (const Table *t, int *nums) { - int lg; - int ttlg; /* 2^lg */ - int ause = 0; /* summation of `nums' */ - int i = 1; /* count to traverse all array keys */ - for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */ - int lc = 0; /* counter */ - int lim = ttlg; - if (lim > t->sizearray) { - lim = t->sizearray; /* adjust upper limit */ - if (i > lim) - break; /* no more elements to count */ - } - /* count elements in range (2^(lg-1), 2^lg] */ - for (; i <= lim; i++) { - if (!ttisnil(&t->array[i-1])) - lc++; - } - nums[lg] += lc; - ause += lc; - } - return ause; -} - - -static int numusehash (const Table *t, int *nums, int *pnasize) { - int totaluse = 0; /* total number of elements */ - int ause = 0; /* summation of `nums' */ - int i = sizenode(t); - while (i--) { - Node *n = &t->node[i]; - if (!ttisnil(gval(n))) { - ause += countint(key2tval(n), nums); - totaluse++; - } - } - *pnasize += ause; - return totaluse; -} - - -static void setarrayvector (lua_State *L, Table *t, int size) { - int i; - luaM_reallocvector(L, t->array, t->sizearray, size, TValue); - for (i=t->sizearray; iarray[i]); - t->sizearray = size; -} - - -static void setnodevector (lua_State *L, Table *t, int size) { - int lsize; - if (size == 0) { /* no elements to hash part? */ - t->node = cast(Node *, dummynode); /* use common `dummynode' */ - lsize = 0; - } - else { - int i; - lsize = ceillog2(size); - if (lsize > MAXBITS) - luaG_runerror(L, "table overflow"); - size = twoto(lsize); - t->node = luaM_newvector(L, size, Node); - for (i=0; ilsizenode = cast_byte(lsize); - t->lastfree = gnode(t, size); /* all positions are free */ -} - - -static void resize (lua_State *L, Table *t, int nasize, int nhsize) { - int i; - int oldasize = t->sizearray; - int oldhsize = t->lsizenode; - Node *nold = t->node; /* save old hash ... */ - if (nasize > oldasize) /* array part must grow? */ - setarrayvector(L, t, nasize); - /* create new hash part with appropriate size */ - setnodevector(L, t, nhsize); - if (nasize < oldasize) { /* array part must shrink? */ - t->sizearray = nasize; - /* re-insert elements from vanishing slice */ - for (i=nasize; iarray[i])) - setobjt2t(L, luaH_setnum(L, t, i+1), &t->array[i]); - } - /* shrink array */ - luaM_reallocvector(L, t->array, oldasize, nasize, TValue); - } - /* re-insert elements from hash part */ - for (i = twoto(oldhsize) - 1; i >= 0; i--) { - Node *old = nold+i; - if (!ttisnil(gval(old))) - setobjt2t(L, luaH_set(L, t, key2tval(old)), gval(old)); - } - if (nold != dummynode) - luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */ -} - - -void luaH_resizearray (lua_State *L, Table *t, int nasize) { - int nsize = (t->node == dummynode) ? 0 : sizenode(t); - resize(L, t, nasize, nsize); -} - - -static void rehash (lua_State *L, Table *t, const TValue *ek) { - int nasize, na; - int nums[MAXBITS+1]; /* nums[i] = number of keys between 2^(i-1) and 2^i */ - int i; - int totaluse; - for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */ - nasize = numusearray(t, nums); /* count keys in array part */ - totaluse = nasize; /* all those keys are integer keys */ - totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */ - /* count extra key */ - nasize += countint(ek, nums); - totaluse++; - /* compute new size for array part */ - na = computesizes(nums, &nasize); - /* resize the table to new computed sizes */ - resize(L, t, nasize, totaluse - na); -} - - - -/* -** }============================================================= -*/ - - -Table *luaH_new (lua_State *L, int narray, int nhash) { - Table *t = luaM_new(L, Table); - luaC_link(L, obj2gco(t), LUA_TTABLE); - t->metatable = NULL; - t->flags = cast_byte(~0); - /* temporary values (kept only if some malloc fails) */ - t->array = NULL; - t->sizearray = 0; - t->lsizenode = 0; - t->node = cast(Node *, dummynode); - setarrayvector(L, t, narray); - setnodevector(L, t, nhash); - return t; -} - - -void luaH_free (lua_State *L, Table *t) { - if (t->node != dummynode) - luaM_freearray(L, t->node, sizenode(t), Node); - luaM_freearray(L, t->array, t->sizearray, TValue); - luaM_free(L, t); -} - - -static Node *getfreepos (Table *t) { - while (t->lastfree-- > t->node) { - if (ttisnil(gkey(t->lastfree))) - return t->lastfree; - } - return NULL; /* could not find a free place */ -} - - - -/* -** inserts a new key into a hash table; first, check whether key's main -** position is free. If not, check whether colliding node is in its main -** position or not: if it is not, move colliding node to an empty place and -** put new key in its main position; otherwise (colliding node is in its main -** position), new key goes to an empty position. -*/ -static TValue *newkey (lua_State *L, Table *t, const TValue *key) { - Node *mp = mainposition(t, key); - if (!ttisnil(gval(mp)) || mp == dummynode) { - Node *othern; - Node *n = getfreepos(t); /* get a free place */ - if (n == NULL) { /* cannot find a free place? */ - rehash(L, t, key); /* grow table */ - return luaH_set(L, t, key); /* re-insert key into grown table */ - } - lua_assert(n != dummynode); - othern = mainposition(t, key2tval(mp)); - if (othern != mp) { /* is colliding node out of its main position? */ - /* yes; move colliding node into free position */ - while (gnext(othern) != mp) othern = gnext(othern); /* find previous */ - gnext(othern) = n; /* redo the chain with `n' in place of `mp' */ - *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */ - gnext(mp) = NULL; /* now `mp' is free */ - setnilvalue(gval(mp)); - } - else { /* colliding node is in its own main position */ - /* new node will go into free position */ - gnext(n) = gnext(mp); /* chain new position */ - gnext(mp) = n; - mp = n; - } - } - gkey(mp)->value = key->value; gkey(mp)->tt = key->tt; - luaC_barriert(L, t, key); - lua_assert(ttisnil(gval(mp))); - return gval(mp); -} - - -/* -** search function for integers -*/ -const TValue *luaH_getnum (Table *t, int key) { - /* (1 <= key && key <= t->sizearray) */ - if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray)) - return &t->array[key-1]; - else { - lua_Number nk = cast_num(key); - Node *n = hashnum(t, nk); - do { /* check whether `key' is somewhere in the chain */ - if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk)) - return gval(n); /* that's it */ - else n = gnext(n); - } while (n); - return luaO_nilobject; - } -} - - -/* -** search function for strings -*/ -const TValue *luaH_getstr (Table *t, TString *key) { - Node *n = hashstr(t, key); - do { /* check whether `key' is somewhere in the chain */ - if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key) - return gval(n); /* that's it */ - else n = gnext(n); - } while (n); - return luaO_nilobject; -} - - -/* -** main search function -*/ -const TValue *luaH_get (Table *t, const TValue *key) { - switch (ttype(key)) { - case LUA_TNIL: return luaO_nilobject; - case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key)); - case LUA_TNUMBER: { - int k; - lua_Number n = nvalue(key); - lua_number2int(k, n); - if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */ - return luaH_getnum(t, k); /* use specialized version */ - /* else go through */ - } - default: { - Node *n = mainposition(t, key); - do { /* check whether `key' is somewhere in the chain */ - if (luaO_rawequalObj(key2tval(n), key)) - return gval(n); /* that's it */ - else n = gnext(n); - } while (n); - return luaO_nilobject; - } - } -} - - -TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { - const TValue *p = luaH_get(t, key); - t->flags = 0; - if (p != luaO_nilobject) - return cast(TValue *, p); - else { - if (ttisnil(key)) luaG_runerror(L, "table index is nil"); - else if (ttisnumber(key) && luai_numisnan(nvalue(key))) - luaG_runerror(L, "table index is NaN"); - return newkey(L, t, key); - } -} - - -TValue *luaH_setnum (lua_State *L, Table *t, int key) { - const TValue *p = luaH_getnum(t, key); - if (p != luaO_nilobject) - return cast(TValue *, p); - else { - TValue k; - setnvalue(&k, cast_num(key)); - return newkey(L, t, &k); - } -} - - -TValue *luaH_setstr (lua_State *L, Table *t, TString *key) { - const TValue *p = luaH_getstr(t, key); - if (p != luaO_nilobject) - return cast(TValue *, p); - else { - TValue k; - setsvalue(L, &k, key); - return newkey(L, t, &k); - } -} - - -static int unbound_search (Table *t, unsigned int j) { - unsigned int i = j; /* i is zero or a present index */ - j++; - /* find `i' and `j' such that i is present and j is not */ - while (!ttisnil(luaH_getnum(t, j))) { - i = j; - j *= 2; - if (j > cast(unsigned int, MAX_INT)) { /* overflow? */ - /* table was built with bad purposes: resort to linear search */ - i = 1; - while (!ttisnil(luaH_getnum(t, i))) i++; - return i - 1; - } - } - /* now do a binary search between them */ - while (j - i > 1) { - unsigned int m = (i+j)/2; - if (ttisnil(luaH_getnum(t, m))) j = m; - else i = m; - } - return i; -} - - -/* -** Try to find a boundary in table `t'. A `boundary' is an integer index -** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil). -*/ -int luaH_getn (Table *t) { - unsigned int j = t->sizearray; - if (j > 0 && ttisnil(&t->array[j - 1])) { - /* there is a boundary in the array part: (binary) search for it */ - unsigned int i = 0; - while (j - i > 1) { - unsigned int m = (i+j)/2; - if (ttisnil(&t->array[m - 1])) j = m; - else i = m; - } - return i; - } - /* else must find a boundary in hash part */ - else if (t->node == dummynode) /* hash part is empty? */ - return j; /* that is easy... */ - else return unbound_search(t, j); -} - - - -#if defined(LUA_DEBUG) - -Node *luaH_mainposition (const Table *t, const TValue *key) { - return mainposition(t, key); -} - -int luaH_isdummy (Node *n) { return n == dummynode; } - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/ltable.h b/desmume/src/windows/lua/lua-5.1.4/src/ltable.h deleted file mode 100644 index f5b9d5ead..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/ltable.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** $Id: ltable.h,v 2.10.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lua tables (hash) -** See Copyright Notice in lua.h -*/ - -#ifndef ltable_h -#define ltable_h - -#include "lobject.h" - - -#define gnode(t,i) (&(t)->node[i]) -#define gkey(n) (&(n)->i_key.nk) -#define gval(n) (&(n)->i_val) -#define gnext(n) ((n)->i_key.nk.next) - -#define key2tval(n) (&(n)->i_key.tvk) - - -LUAI_FUNC const TValue *luaH_getnum (Table *t, int key); -LUAI_FUNC TValue *luaH_setnum (lua_State *L, Table *t, int key); -LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); -LUAI_FUNC TValue *luaH_setstr (lua_State *L, Table *t, TString *key); -LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); -LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key); -LUAI_FUNC Table *luaH_new (lua_State *L, int narray, int lnhash); -LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, int nasize); -LUAI_FUNC void luaH_free (lua_State *L, Table *t); -LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key); -LUAI_FUNC int luaH_getn (Table *t); - - -#if defined(LUA_DEBUG) -LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); -LUAI_FUNC int luaH_isdummy (Node *n); -#endif - - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/ltablib.c b/desmume/src/windows/lua/lua-5.1.4/src/ltablib.c deleted file mode 100644 index b6d9cb4ac..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/ltablib.c +++ /dev/null @@ -1,287 +0,0 @@ -/* -** $Id: ltablib.c,v 1.38.1.3 2008/02/14 16:46:58 roberto Exp $ -** Library for Table Manipulation -** See Copyright Notice in lua.h -*/ - - -#include - -#define ltablib_c -#define LUA_LIB - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - -#define aux_getn(L,n) (luaL_checktype(L, n, LUA_TTABLE), luaL_getn(L, n)) - - -static int foreachi (lua_State *L) { - int i; - int n = aux_getn(L, 1); - luaL_checktype(L, 2, LUA_TFUNCTION); - for (i=1; i <= n; i++) { - lua_pushvalue(L, 2); /* function */ - lua_pushinteger(L, i); /* 1st argument */ - lua_rawgeti(L, 1, i); /* 2nd argument */ - lua_call(L, 2, 1); - if (!lua_isnil(L, -1)) - return 1; - lua_pop(L, 1); /* remove nil result */ - } - return 0; -} - - -static int foreach (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); - luaL_checktype(L, 2, LUA_TFUNCTION); - lua_pushnil(L); /* first key */ - while (lua_next(L, 1)) { - lua_pushvalue(L, 2); /* function */ - lua_pushvalue(L, -3); /* key */ - lua_pushvalue(L, -3); /* value */ - lua_call(L, 2, 1); - if (!lua_isnil(L, -1)) - return 1; - lua_pop(L, 2); /* remove value and result */ - } - return 0; -} - - -static int maxn (lua_State *L) { - lua_Number max = 0; - luaL_checktype(L, 1, LUA_TTABLE); - lua_pushnil(L); /* first key */ - while (lua_next(L, 1)) { - lua_pop(L, 1); /* remove value */ - if (lua_type(L, -1) == LUA_TNUMBER) { - lua_Number v = lua_tonumber(L, -1); - if (v > max) max = v; - } - } - lua_pushnumber(L, max); - return 1; -} - - -static int getn (lua_State *L) { - lua_pushinteger(L, aux_getn(L, 1)); - return 1; -} - - -static int setn (lua_State *L) { - luaL_checktype(L, 1, LUA_TTABLE); -#ifndef luaL_setn - luaL_setn(L, 1, luaL_checkint(L, 2)); -#else - luaL_error(L, LUA_QL("setn") " is obsolete"); -#endif - lua_pushvalue(L, 1); - return 1; -} - - -static int tinsert (lua_State *L) { - int e = aux_getn(L, 1) + 1; /* first empty element */ - int pos; /* where to insert new element */ - switch (lua_gettop(L)) { - case 2: { /* called with only 2 arguments */ - pos = e; /* insert new element at the end */ - break; - } - case 3: { - int i; - pos = luaL_checkint(L, 2); /* 2nd argument is the position */ - if (pos > e) e = pos; /* `grow' array if necessary */ - for (i = e; i > pos; i--) { /* move up elements */ - lua_rawgeti(L, 1, i-1); - lua_rawseti(L, 1, i); /* t[i] = t[i-1] */ - } - break; - } - default: { - return luaL_error(L, "wrong number of arguments to " LUA_QL("insert")); - } - } - luaL_setn(L, 1, e); /* new size */ - lua_rawseti(L, 1, pos); /* t[pos] = v */ - return 0; -} - - -static int tremove (lua_State *L) { - int e = aux_getn(L, 1); - int pos = luaL_optint(L, 2, e); - if (!(1 <= pos && pos <= e)) /* position is outside bounds? */ - return 0; /* nothing to remove */ - luaL_setn(L, 1, e - 1); /* t.n = n-1 */ - lua_rawgeti(L, 1, pos); /* result = t[pos] */ - for ( ;pos= P */ - while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) { - if (i>u) luaL_error(L, "invalid order function for sorting"); - lua_pop(L, 1); /* remove a[i] */ - } - /* repeat --j until a[j] <= P */ - while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) { - if (j - -#define ltm_c -#define LUA_CORE - -#include "lua.h" - -#include "lobject.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" - - - -const char *const luaT_typenames[] = { - "nil", "boolean", "userdata", "number", - "string", "table", "function", "userdata", "thread", - "proto", "upval" -}; - - -void luaT_init (lua_State *L) { - static const char *const luaT_eventname[] = { /* ORDER TM */ - "__index", "__newindex", - "__gc", "__mode", "__eq", - "__add", "__sub", "__mul", "__div", "__mod", - "__pow", "__unm", "__len", "__lt", "__le", - "__concat", "__call" - }; - int i; - for (i=0; itmname[i] = luaS_new(L, luaT_eventname[i]); - luaS_fix(G(L)->tmname[i]); /* never collect these names */ - } -} - - -/* -** function to be used with macro "fasttm": optimized for absence of -** tag methods -*/ -const TValue *luaT_gettm (Table *events, TMS event, TString *ename) { - const TValue *tm = luaH_getstr(events, ename); - lua_assert(event <= TM_EQ); - if (ttisnil(tm)) { /* no tag method? */ - events->flags |= cast_byte(1u<metatable; - break; - case LUA_TUSERDATA: - mt = uvalue(o)->metatable; - break; - default: - mt = G(L)->mt[ttype(o)]; - } - return (mt ? luaH_getstr(mt, G(L)->tmname[event]) : luaO_nilobject); -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/ltm.h b/desmume/src/windows/lua/lua-5.1.4/src/ltm.h deleted file mode 100644 index 64343b781..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/ltm.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -** $Id: ltm.h,v 2.6.1.1 2007/12/27 13:02:25 roberto Exp $ -** Tag methods -** See Copyright Notice in lua.h -*/ - -#ifndef ltm_h -#define ltm_h - - -#include "lobject.h" - - -/* -* WARNING: if you change the order of this enumeration, -* grep "ORDER TM" -*/ -typedef enum { - TM_INDEX, - TM_NEWINDEX, - TM_GC, - TM_MODE, - TM_EQ, /* last tag method with `fast' access */ - TM_ADD, - TM_SUB, - TM_MUL, - TM_DIV, - TM_MOD, - TM_POW, - TM_UNM, - TM_LEN, - TM_LT, - TM_LE, - TM_CONCAT, - TM_CALL, - TM_N /* number of elements in the enum */ -} TMS; - - - -#define gfasttm(g,et,e) ((et) == NULL ? NULL : \ - ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e])) - -#define fasttm(l,et,e) gfasttm(G(l), et, e) - -LUAI_DATA const char *const luaT_typenames[]; - - -LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename); -LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, - TMS event); -LUAI_FUNC void luaT_init (lua_State *L); - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lua.c b/desmume/src/windows/lua/lua-5.1.4/src/lua.c deleted file mode 100644 index 3a4660932..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lua.c +++ /dev/null @@ -1,392 +0,0 @@ -/* -** $Id: lua.c,v 1.160.1.2 2007/12/28 15:32:23 roberto Exp $ -** Lua stand-alone interpreter -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include -#include - -#define lua_c - -#include "lua.h" - -#include "lauxlib.h" -#include "lualib.h" - - - -static lua_State *globalL = NULL; - -static const char *progname = LUA_PROGNAME; - - - -static void lstop (lua_State *L, lua_Debug *ar) { - (void)ar; /* unused arg. */ - lua_sethook(L, NULL, 0, 0); - luaL_error(L, "interrupted!"); -} - - -static void laction (int i) { - signal(i, SIG_DFL); /* if another SIGINT happens before lstop, - terminate process (default action) */ - lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1); -} - - -static void print_usage (void) { - fprintf(stderr, - "usage: %s [options] [script [args]].\n" - "Available options are:\n" - " -e stat execute string " LUA_QL("stat") "\n" - " -l name require library " LUA_QL("name") "\n" - " -i enter interactive mode after executing " LUA_QL("script") "\n" - " -v show version information\n" - " -- stop handling options\n" - " - execute stdin and stop handling options\n" - , - progname); - fflush(stderr); -} - - -static void l_message (const char *pname, const char *msg) { - if (pname) fprintf(stderr, "%s: ", pname); - fprintf(stderr, "%s\n", msg); - fflush(stderr); -} - - -static int report (lua_State *L, int status) { - if (status && !lua_isnil(L, -1)) { - const char *msg = lua_tostring(L, -1); - if (msg == NULL) msg = "(error object is not a string)"; - l_message(progname, msg); - lua_pop(L, 1); - } - return status; -} - - -static int traceback (lua_State *L) { - if (!lua_isstring(L, 1)) /* 'message' not a string? */ - return 1; /* keep it intact */ - lua_getfield(L, LUA_GLOBALSINDEX, "debug"); - if (!lua_istable(L, -1)) { - lua_pop(L, 1); - return 1; - } - lua_getfield(L, -1, "traceback"); - if (!lua_isfunction(L, -1)) { - lua_pop(L, 2); - return 1; - } - lua_pushvalue(L, 1); /* pass error message */ - lua_pushinteger(L, 2); /* skip this function and traceback */ - lua_call(L, 2, 1); /* call debug.traceback */ - return 1; -} - - -static int docall (lua_State *L, int narg, int clear) { - int status; - int base = lua_gettop(L) - narg; /* function index */ - lua_pushcfunction(L, traceback); /* push traceback function */ - lua_insert(L, base); /* put it under chunk and args */ - signal(SIGINT, laction); - status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base); - signal(SIGINT, SIG_DFL); - lua_remove(L, base); /* remove traceback function */ - /* force a complete garbage collection in case of errors */ - if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0); - return status; -} - - -static void print_version (void) { - l_message(NULL, LUA_RELEASE " " LUA_COPYRIGHT); -} - - -static int getargs (lua_State *L, char **argv, int n) { - int narg; - int i; - int argc = 0; - while (argv[argc]) argc++; /* count total number of arguments */ - narg = argc - (n + 1); /* number of arguments to the script */ - luaL_checkstack(L, narg + 3, "too many arguments to script"); - for (i=n+1; i < argc; i++) - lua_pushstring(L, argv[i]); - lua_createtable(L, narg, n + 1); - for (i=0; i < argc; i++) { - lua_pushstring(L, argv[i]); - lua_rawseti(L, -2, i - n); - } - return narg; -} - - -static int dofile (lua_State *L, const char *name) { - int status = luaL_loadfile(L, name) || docall(L, 0, 1); - return report(L, status); -} - - -static int dostring (lua_State *L, const char *s, const char *name) { - int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1); - return report(L, status); -} - - -static int dolibrary (lua_State *L, const char *name) { - lua_getglobal(L, "require"); - lua_pushstring(L, name); - return report(L, docall(L, 1, 1)); -} - - -static const char *get_prompt (lua_State *L, int firstline) { - const char *p; - lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2"); - p = lua_tostring(L, -1); - if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2); - lua_pop(L, 1); /* remove global */ - return p; -} - - -static int incomplete (lua_State *L, int status) { - if (status == LUA_ERRSYNTAX) { - size_t lmsg; - const char *msg = lua_tolstring(L, -1, &lmsg); - const char *tp = msg + lmsg - (sizeof(LUA_QL("")) - 1); - if (strstr(msg, LUA_QL("")) == tp) { - lua_pop(L, 1); - return 1; - } - } - return 0; /* else... */ -} - - -static int pushline (lua_State *L, int firstline) { - char buffer[LUA_MAXINPUT]; - char *b = buffer; - size_t l; - const char *prmt = get_prompt(L, firstline); - if (lua_readline(L, b, prmt) == 0) - return 0; /* no input */ - l = strlen(b); - if (l > 0 && b[l-1] == '\n') /* line ends with newline? */ - b[l-1] = '\0'; /* remove it */ - if (firstline && b[0] == '=') /* first line starts with `=' ? */ - lua_pushfstring(L, "return %s", b+1); /* change it to `return' */ - else - lua_pushstring(L, b); - lua_freeline(L, b); - return 1; -} - - -static int loadline (lua_State *L) { - int status; - lua_settop(L, 0); - if (!pushline(L, 1)) - return -1; /* no input */ - for (;;) { /* repeat until gets a complete line */ - status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin"); - if (!incomplete(L, status)) break; /* cannot try to add lines? */ - if (!pushline(L, 0)) /* no more input? */ - return -1; - lua_pushliteral(L, "\n"); /* add a new line... */ - lua_insert(L, -2); /* ...between the two lines */ - lua_concat(L, 3); /* join them */ - } - lua_saveline(L, 1); - lua_remove(L, 1); /* remove line */ - return status; -} - - -static void dotty (lua_State *L) { - int status; - const char *oldprogname = progname; - progname = NULL; - while ((status = loadline(L)) != -1) { - if (status == 0) status = docall(L, 0, 0); - report(L, status); - if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */ - lua_getglobal(L, "print"); - lua_insert(L, 1); - if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) - l_message(progname, lua_pushfstring(L, - "error calling " LUA_QL("print") " (%s)", - lua_tostring(L, -1))); - } - } - lua_settop(L, 0); /* clear stack */ - fputs("\n", stdout); - fflush(stdout); - progname = oldprogname; -} - - -static int handle_script (lua_State *L, char **argv, int n) { - int status; - const char *fname; - int narg = getargs(L, argv, n); /* collect arguments */ - lua_setglobal(L, "arg"); - fname = argv[n]; - if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0) - fname = NULL; /* stdin */ - status = luaL_loadfile(L, fname); - lua_insert(L, -(narg+1)); - if (status == 0) - status = docall(L, narg, 0); - else - lua_pop(L, narg); - return report(L, status); -} - - -/* check that argument has no extra characters at the end */ -#define notail(x) {if ((x)[2] != '\0') return -1;} - - -static int collectargs (char **argv, int *pi, int *pv, int *pe) { - int i; - for (i = 1; argv[i] != NULL; i++) { - if (argv[i][0] != '-') /* not an option? */ - return i; - switch (argv[i][1]) { /* option */ - case '-': - notail(argv[i]); - return (argv[i+1] != NULL ? i+1 : 0); - case '\0': - return i; - case 'i': - notail(argv[i]); - *pi = 1; /* go through */ - case 'v': - notail(argv[i]); - *pv = 1; - break; - case 'e': - *pe = 1; /* go through */ - case 'l': - if (argv[i][2] == '\0') { - i++; - if (argv[i] == NULL) return -1; - } - break; - default: return -1; /* invalid option */ - } - } - return 0; -} - - -static int runargs (lua_State *L, char **argv, int n) { - int i; - for (i = 1; i < n; i++) { - if (argv[i] == NULL) continue; - lua_assert(argv[i][0] == '-'); - switch (argv[i][1]) { /* option */ - case 'e': { - const char *chunk = argv[i] + 2; - if (*chunk == '\0') chunk = argv[++i]; - lua_assert(chunk != NULL); - if (dostring(L, chunk, "=(command line)") != 0) - return 1; - break; - } - case 'l': { - const char *filename = argv[i] + 2; - if (*filename == '\0') filename = argv[++i]; - lua_assert(filename != NULL); - if (dolibrary(L, filename)) - return 1; /* stop if file fails */ - break; - } - default: break; - } - } - return 0; -} - - -static int handle_luainit (lua_State *L) { - const char *init = getenv(LUA_INIT); - if (init == NULL) return 0; /* status OK */ - else if (init[0] == '@') - return dofile(L, init+1); - else - return dostring(L, init, "=" LUA_INIT); -} - - -struct Smain { - int argc; - char **argv; - int status; -}; - - -static int pmain (lua_State *L) { - struct Smain *s = (struct Smain *)lua_touserdata(L, 1); - char **argv = s->argv; - int script; - int has_i = 0, has_v = 0, has_e = 0; - globalL = L; - if (argv[0] && argv[0][0]) progname = argv[0]; - lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */ - luaL_openlibs(L); /* open libraries */ - lua_gc(L, LUA_GCRESTART, 0); - s->status = handle_luainit(L); - if (s->status != 0) return 0; - script = collectargs(argv, &has_i, &has_v, &has_e); - if (script < 0) { /* invalid args? */ - print_usage(); - s->status = 1; - return 0; - } - if (has_v) print_version(); - s->status = runargs(L, argv, (script > 0) ? script : s->argc); - if (s->status != 0) return 0; - if (script) - s->status = handle_script(L, argv, script); - if (s->status != 0) return 0; - if (has_i) - dotty(L); - else if (script == 0 && !has_e && !has_v) { - if (lua_stdin_is_tty()) { - print_version(); - dotty(L); - } - else dofile(L, NULL); /* executes stdin as a file */ - } - return 0; -} - - -int main (int argc, char **argv) { - int status; - struct Smain s; - lua_State *L = lua_open(); /* create state */ - if (L == NULL) { - l_message(argv[0], "cannot create state: not enough memory"); - return EXIT_FAILURE; - } - s.argc = argc; - s.argv = argv; - status = lua_cpcall(L, &pmain, &s); - report(L, status); - lua_close(L); - return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS; -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lua.h b/desmume/src/windows/lua/lua-5.1.4/src/lua.h deleted file mode 100644 index 41b2ea808..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lua.h +++ /dev/null @@ -1,388 +0,0 @@ -/* -** $Id: lua.h,v 1.218.1.5 2008/08/06 13:30:12 roberto Exp $ -** Lua - An Extensible Extension Language -** Lua.org, PUC-Rio, Brazil (http://www.lua.org) -** See Copyright Notice at the end of this file -*/ - - -#ifndef lua_h -#define lua_h - -#include -#include - - -#include "luaconf.h" - - -#define LUA_VERSION "Lua 5.1" -#define LUA_RELEASE "Lua 5.1.4" -#define LUA_VERSION_NUM 501 -#define LUA_COPYRIGHT "Copyright (C) 1994-2008 Lua.org, PUC-Rio" -#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes" - - -/* mark for precompiled code (`Lua') */ -#define LUA_SIGNATURE "\033Lua" - -/* option for multiple returns in `lua_pcall' and `lua_call' */ -#define LUA_MULTRET (-1) - - -/* -** pseudo-indices -*/ -#define LUA_REGISTRYINDEX (-10000) -#define LUA_ENVIRONINDEX (-10001) -#define LUA_GLOBALSINDEX (-10002) -#define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i)) - - -/* thread status; 0 is OK */ -#define LUA_YIELD 1 -#define LUA_ERRRUN 2 -#define LUA_ERRSYNTAX 3 -#define LUA_ERRMEM 4 -#define LUA_ERRERR 5 - - -typedef struct lua_State lua_State; - -typedef int (*lua_CFunction) (lua_State *L); - - -/* -** functions that read/write blocks when loading/dumping Lua chunks -*/ -typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); - -typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); - - -/* -** prototype for memory-allocation functions -*/ -typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); - - -/* -** basic types -*/ -#define LUA_TNONE (-1) - -#define LUA_TNIL 0 -#define LUA_TBOOLEAN 1 -#define LUA_TLIGHTUSERDATA 2 -#define LUA_TNUMBER 3 -#define LUA_TSTRING 4 -#define LUA_TTABLE 5 -#define LUA_TFUNCTION 6 -#define LUA_TUSERDATA 7 -#define LUA_TTHREAD 8 - - - -/* minimum Lua stack available to a C function */ -#define LUA_MINSTACK 20 - - -/* -** generic extra include file -*/ -#if defined(LUA_USER_H) -#include LUA_USER_H -#endif - - -/* type of numbers in Lua */ -typedef LUA_NUMBER lua_Number; - - -/* type for integer functions */ -typedef LUA_INTEGER lua_Integer; - - - -/* -** state manipulation -*/ -LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); -LUA_API void lua_close (lua_State *L); -LUA_API lua_State *(lua_newthread) (lua_State *L); - -LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); - - -/* -** basic stack manipulation -*/ -LUA_API int (lua_gettop) (lua_State *L); -LUA_API void (lua_settop) (lua_State *L, int idx); -LUA_API void (lua_pushvalue) (lua_State *L, int idx); -LUA_API void (lua_remove) (lua_State *L, int idx); -LUA_API void (lua_insert) (lua_State *L, int idx); -LUA_API void (lua_replace) (lua_State *L, int idx); -LUA_API int (lua_checkstack) (lua_State *L, int sz); - -LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); - - -/* -** access functions (stack -> C) -*/ - -LUA_API int (lua_isnumber) (lua_State *L, int idx); -LUA_API int (lua_isstring) (lua_State *L, int idx); -LUA_API int (lua_iscfunction) (lua_State *L, int idx); -LUA_API int (lua_isuserdata) (lua_State *L, int idx); -LUA_API int (lua_type) (lua_State *L, int idx); -LUA_API const char *(lua_typename) (lua_State *L, int tp); - -LUA_API int (lua_equal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); -LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2); - -LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx); -LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx); -LUA_API int (lua_toboolean) (lua_State *L, int idx); -LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); -LUA_API size_t (lua_objlen) (lua_State *L, int idx); -LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); -LUA_API void *(lua_touserdata) (lua_State *L, int idx); -LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); -LUA_API const void *(lua_topointer) (lua_State *L, int idx); - - -/* -** push functions (C -> stack) -*/ -LUA_API void (lua_pushnil) (lua_State *L); -LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); -LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); -LUA_API void (lua_pushlstring) (lua_State *L, const char *s, size_t l); -LUA_API void (lua_pushstring) (lua_State *L, const char *s); -LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, - va_list argp); -LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); -LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); -LUA_API void (lua_pushboolean) (lua_State *L, int b); -LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); -LUA_API int (lua_pushthread) (lua_State *L); - - -/* -** get functions (Lua -> stack) -*/ -LUA_API void (lua_gettable) (lua_State *L, int idx); -LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_rawget) (lua_State *L, int idx); -LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n); -LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); -LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); -LUA_API int (lua_getmetatable) (lua_State *L, int objindex); -LUA_API void (lua_getfenv) (lua_State *L, int idx); - - -/* -** set functions (stack -> Lua) -*/ -LUA_API void (lua_settable) (lua_State *L, int idx); -LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); -LUA_API void (lua_rawset) (lua_State *L, int idx); -LUA_API void (lua_rawseti) (lua_State *L, int idx, int n); -LUA_API int (lua_setmetatable) (lua_State *L, int objindex); -LUA_API int (lua_setfenv) (lua_State *L, int idx); - - -/* -** `load' and `call' functions (load and run Lua code) -*/ -LUA_API void (lua_call) (lua_State *L, int nargs, int nresults); -LUA_API int (lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc); -LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud); -LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, - const char *chunkname); - -LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data); - - -/* -** coroutine functions -*/ -LUA_API int (lua_yield) (lua_State *L, int nresults); -LUA_API int (lua_resume) (lua_State *L, int narg); -LUA_API int (lua_status) (lua_State *L); - -/* -** garbage-collection function and options -*/ - -#define LUA_GCSTOP 0 -#define LUA_GCRESTART 1 -#define LUA_GCCOLLECT 2 -#define LUA_GCCOUNT 3 -#define LUA_GCCOUNTB 4 -#define LUA_GCSTEP 5 -#define LUA_GCSETPAUSE 6 -#define LUA_GCSETSTEPMUL 7 - -LUA_API int (lua_gc) (lua_State *L, int what, int data); - - -/* -** miscellaneous functions -*/ - -LUA_API int (lua_error) (lua_State *L); - -LUA_API int (lua_next) (lua_State *L, int idx); - -LUA_API void (lua_concat) (lua_State *L, int n); - -LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); -LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); - - - -/* -** =============================================================== -** some useful macros -** =============================================================== -*/ - -#define lua_pop(L,n) lua_settop(L, -(n)-1) - -#define lua_newtable(L) lua_createtable(L, 0, 0) - -#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) - -#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) - -#define lua_strlen(L,i) lua_objlen(L, (i)) - -#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) -#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) -#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) -#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) -#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) -#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) -#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) -#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) - -#define lua_pushliteral(L, s) \ - lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) - -#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, (s)) -#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, (s)) - -#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) - - - -/* -** compatibility macros and functions -*/ - -#define lua_open() luaL_newstate() - -#define lua_getregistry(L) lua_pushvalue(L, LUA_REGISTRYINDEX) - -#define lua_getgccount(L) lua_gc(L, LUA_GCCOUNT, 0) - -#define lua_Chunkreader lua_Reader -#define lua_Chunkwriter lua_Writer - - -/* hack */ -LUA_API void lua_setlevel (lua_State *from, lua_State *to); - - -/* -** {====================================================================== -** Debug API -** ======================================================================= -*/ - - -/* -** Event codes -*/ -#define LUA_HOOKCALL 0 -#define LUA_HOOKRET 1 -#define LUA_HOOKLINE 2 -#define LUA_HOOKCOUNT 3 -#define LUA_HOOKTAILRET 4 - - -/* -** Event masks -*/ -#define LUA_MASKCALL (1 << LUA_HOOKCALL) -#define LUA_MASKRET (1 << LUA_HOOKRET) -#define LUA_MASKLINE (1 << LUA_HOOKLINE) -#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) - -typedef struct lua_Debug lua_Debug; /* activation record */ - - -/* Functions to be called by the debuger in specific events */ -typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); - - -LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar); -LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); -LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); -LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n); -LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n); - -LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count); -LUA_API lua_Hook lua_gethook (lua_State *L); -LUA_API int lua_gethookmask (lua_State *L); -LUA_API int lua_gethookcount (lua_State *L); - - -struct lua_Debug { - int event; - const char *name; /* (n) */ - const char *namewhat; /* (n) `global', `local', `field', `method' */ - const char *what; /* (S) `Lua', `C', `main', `tail' */ - const char *source; /* (S) */ - int currentline; /* (l) */ - int nups; /* (u) number of upvalues */ - int linedefined; /* (S) */ - int lastlinedefined; /* (S) */ - char short_src[LUA_IDSIZE]; /* (S) */ - /* private part */ - int i_ci; /* active function */ -}; - -/* }====================================================================== */ - - -/****************************************************************************** -* Copyright (C) 1994-2008 Lua.org, PUC-Rio. All rights reserved. -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ - - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/luac.c b/desmume/src/windows/lua/lua-5.1.4/src/luac.c deleted file mode 100644 index d07017391..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/luac.c +++ /dev/null @@ -1,200 +0,0 @@ -/* -** $Id: luac.c,v 1.54 2006/06/02 17:37:11 lhf Exp $ -** Lua compiler (saves bytecodes to files; also list bytecodes) -** See Copyright Notice in lua.h -*/ - -#include -#include -#include -#include - -#define luac_c -#define LUA_CORE - -#include "lua.h" -#include "lauxlib.h" - -#include "ldo.h" -#include "lfunc.h" -#include "lmem.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lstring.h" -#include "lundump.h" - -#define PROGNAME "luac" /* default program name */ -#define OUTPUT PROGNAME ".out" /* default output file */ - -static int listing=0; /* list bytecodes? */ -static int dumping=1; /* dump bytecodes? */ -static int stripping=0; /* strip debug information? */ -static char Output[]={ OUTPUT }; /* default output file name */ -static const char* output=Output; /* actual output file name */ -static const char* progname=PROGNAME; /* actual program name */ - -static void fatal(const char* message) -{ - fprintf(stderr,"%s: %s\n",progname,message); - exit(EXIT_FAILURE); -} - -static void cannot(const char* what) -{ - fprintf(stderr,"%s: cannot %s %s: %s\n",progname,what,output,strerror(errno)); - exit(EXIT_FAILURE); -} - -static void usage(const char* message) -{ - if (*message=='-') - fprintf(stderr,"%s: unrecognized option " LUA_QS "\n",progname,message); - else - fprintf(stderr,"%s: %s\n",progname,message); - fprintf(stderr, - "usage: %s [options] [filenames].\n" - "Available options are:\n" - " - process stdin\n" - " -l list\n" - " -o name output to file " LUA_QL("name") " (default is \"%s\")\n" - " -p parse only\n" - " -s strip debug information\n" - " -v show version information\n" - " -- stop handling options\n", - progname,Output); - exit(EXIT_FAILURE); -} - -#define IS(s) (strcmp(argv[i],s)==0) - -static int doargs(int argc, char* argv[]) -{ - int i; - int version=0; - if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0]; - for (i=1; itop+(i))->l.p) - -static const Proto* combine(lua_State* L, int n) -{ - if (n==1) - return toproto(L,-1); - else - { - int i,pc; - Proto* f=luaF_newproto(L); - setptvalue2s(L,L->top,f); incr_top(L); - f->source=luaS_newliteral(L,"=(" PROGNAME ")"); - f->maxstacksize=1; - pc=2*n+1; - f->code=luaM_newvector(L,pc,Instruction); - f->sizecode=pc; - f->p=luaM_newvector(L,n,Proto*); - f->sizep=n; - pc=0; - for (i=0; ip[i]=toproto(L,i-n-1); - f->code[pc++]=CREATE_ABx(OP_CLOSURE,0,i); - f->code[pc++]=CREATE_ABC(OP_CALL,0,1,1); - } - f->code[pc++]=CREATE_ABC(OP_RETURN,0,1,0); - return f; - } -} - -static int writer(lua_State* L, const void* p, size_t size, void* u) -{ - UNUSED(L); - return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0); -} - -struct Smain { - int argc; - char** argv; -}; - -static int pmain(lua_State* L) -{ - struct Smain* s = (struct Smain*)lua_touserdata(L, 1); - int argc=s->argc; - char** argv=s->argv; - const Proto* f; - int i; - if (!lua_checkstack(L,argc)) fatal("too many input files"); - for (i=0; i1); - if (dumping) - { - FILE* D= (output==NULL) ? stdout : fopen(output,"wb"); - if (D==NULL) cannot("open"); - lua_lock(L); - luaU_dump(L,f,writer,D,stripping); - lua_unlock(L); - if (ferror(D)) cannot("write"); - if (fclose(D)) cannot("close"); - } - return 0; -} - -int main(int argc, char* argv[]) -{ - lua_State* L; - struct Smain s; - int i=doargs(argc,argv); - argc-=i; argv+=i; - if (argc<=0) usage("no input files given"); - L=lua_open(); - if (L==NULL) fatal("not enough memory for state"); - s.argc=argc; - s.argv=argv; - if (lua_cpcall(L,pmain,&s)!=0) fatal(lua_tostring(L,-1)); - lua_close(L); - return EXIT_SUCCESS; -} diff --git a/desmume/src/windows/lua/lua-5.1.4/src/luaconf.h b/desmume/src/windows/lua/lua-5.1.4/src/luaconf.h deleted file mode 100644 index 0ccb4fe7d..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/luaconf.h +++ /dev/null @@ -1,765 +0,0 @@ -/* -** $Id: luaconf.h,v 1.82.1.7 2008/02/11 16:25:08 roberto Exp $ -** Configuration file for Lua -** See Copyright Notice in lua.h -*/ - - -#ifndef lconfig_h -#define lconfig_h - -#include -#include - - -/* -** ================================================================== -** Search for "@@" to find all configurable definitions. -** =================================================================== -*/ - - -/* -@@ LUA_ANSI controls the use of non-ansi features. -** CHANGE it (define it) if you want Lua to avoid the use of any -** non-ansi feature or library. -*/ -#if defined(__STRICT_ANSI__) -#define LUA_ANSI -#endif - - -#if !defined(LUA_ANSI) && defined(_WIN32) -#define LUA_WIN -#endif - -#if defined(LUA_USE_LINUX) -#define LUA_USE_POSIX -#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ -#define LUA_USE_READLINE /* needs some extra libraries */ -#endif - -#if defined(LUA_USE_MACOSX) -#define LUA_USE_POSIX -#define LUA_DL_DYLD /* does not need extra library */ -#endif - - - -/* -@@ LUA_USE_POSIX includes all functionallity listed as X/Open System -@* Interfaces Extension (XSI). -** CHANGE it (define it) if your system is XSI compatible. -*/ -#if defined(LUA_USE_POSIX) -#define LUA_USE_MKSTEMP -#define LUA_USE_ISATTY -#define LUA_USE_POPEN -#define LUA_USE_ULONGJMP -#endif - - -/* -@@ LUA_PATH and LUA_CPATH are the names of the environment variables that -@* Lua check to set its paths. -@@ LUA_INIT is the name of the environment variable that Lua -@* checks for initialization code. -** CHANGE them if you want different names. -*/ -#define LUA_PATH "LUA_PATH" -#define LUA_CPATH "LUA_CPATH" -#define LUA_INIT "LUA_INIT" - - -/* -@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for -@* Lua libraries. -@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for -@* C libraries. -** CHANGE them if your machine has a non-conventional directory -** hierarchy or if you want to install your libraries in -** non-conventional directories. -*/ -#if defined(_WIN32) -/* -** In Windows, any exclamation mark ('!') in the path is replaced by the -** path of the directory of the executable file of the current process. -*/ -#define LUA_LDIR "!\\lua\\" -#define LUA_CDIR "!\\" -#define LUA_PATH_DEFAULT \ - ".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua" -#define LUA_CPATH_DEFAULT \ - ".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll" - -#else -#define LUA_ROOT "/usr/local/" -#define LUA_LDIR LUA_ROOT "share/lua/5.1/" -#define LUA_CDIR LUA_ROOT "lib/lua/5.1/" -#define LUA_PATH_DEFAULT \ - "./?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ - LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua" -#define LUA_CPATH_DEFAULT \ - "./?.so;" LUA_CDIR"?.so;" LUA_CDIR"loadall.so" -#endif - - -/* -@@ LUA_DIRSEP is the directory separator (for submodules). -** CHANGE it if your machine does not use "/" as the directory separator -** and is not Windows. (On Windows Lua automatically uses "\".) -*/ -#if defined(_WIN32) -#define LUA_DIRSEP "\\" -#else -#define LUA_DIRSEP "/" -#endif - - -/* -@@ LUA_PATHSEP is the character that separates templates in a path. -@@ LUA_PATH_MARK is the string that marks the substitution points in a -@* template. -@@ LUA_EXECDIR in a Windows path is replaced by the executable's -@* directory. -@@ LUA_IGMARK is a mark to ignore all before it when bulding the -@* luaopen_ function name. -** CHANGE them if for some reason your system cannot use those -** characters. (E.g., if one of those characters is a common character -** in file/directory names.) Probably you do not need to change them. -*/ -#define LUA_PATHSEP ";" -#define LUA_PATH_MARK "?" -#define LUA_EXECDIR "!" -#define LUA_IGMARK "-" - - -/* -@@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger. -** CHANGE that if ptrdiff_t is not adequate on your machine. (On most -** machines, ptrdiff_t gives a good choice between int or long.) -*/ -#define LUA_INTEGER ptrdiff_t - - -/* -@@ LUA_API is a mark for all core API functions. -@@ LUALIB_API is a mark for all standard library functions. -** CHANGE them if you need to define those functions in some special way. -** For instance, if you want to create one Windows DLL with the core and -** the libraries, you may want to use the following definition (define -** LUA_BUILD_AS_DLL to get it). -*/ -#if defined(LUA_BUILD_AS_DLL) - -#if defined(LUA_CORE) || defined(LUA_LIB) -#define LUA_API __declspec(dllexport) -#else -#define LUA_API __declspec(dllimport) -#endif - -#else - -//#define LUA_API extern -//desmume: dont want this junk -#define LUA_API - -#endif - -/* more often than not the libs go together with the core */ -#define LUALIB_API LUA_API - - -/* -@@ LUAI_FUNC is a mark for all extern functions that are not to be -@* exported to outside modules. -@@ LUAI_DATA is a mark for all extern (const) variables that are not to -@* be exported to outside modules. -** CHANGE them if you need to mark them in some special way. Elf/gcc -** (versions 3.2 and later) mark them as "hidden" to optimize access -** when Lua is compiled as a shared library. -*/ -#if defined(luaall_c) -#define LUAI_FUNC static -#define LUAI_DATA /* empty */ - -#elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ - defined(__ELF__) -#define LUAI_FUNC __attribute__((visibility("hidden"))) extern -#define LUAI_DATA LUAI_FUNC - -#else -#define LUAI_FUNC extern -#define LUAI_DATA extern -#endif - - - -/* -@@ LUA_QL describes how error messages quote program elements. -** CHANGE it if you want a different appearance. -*/ -#define LUA_QL(x) "'" x "'" -#define LUA_QS LUA_QL("%s") - - -/* -@@ LUA_IDSIZE gives the maximum size for the description of the source -@* of a function in debug information. -** CHANGE it if you want a different size. -*/ -#define LUA_IDSIZE 60 - - -/* -** {================================================================== -** Stand-alone configuration -** =================================================================== -*/ - -#if defined(lua_c) || defined(luaall_c) - -/* -@@ lua_stdin_is_tty detects whether the standard input is a 'tty' (that -@* is, whether we're running lua interactively). -** CHANGE it if you have a better definition for non-POSIX/non-Windows -** systems. -*/ -#if defined(LUA_USE_ISATTY) -#include -#define lua_stdin_is_tty() isatty(0) -#elif defined(LUA_WIN) -#include -#include -#define lua_stdin_is_tty() _isatty(_fileno(stdin)) -#else -#define lua_stdin_is_tty() 1 /* assume stdin is a tty */ -#endif - - -/* -@@ LUA_PROMPT is the default prompt used by stand-alone Lua. -@@ LUA_PROMPT2 is the default continuation prompt used by stand-alone Lua. -** CHANGE them if you want different prompts. (You can also change the -** prompts dynamically, assigning to globals _PROMPT/_PROMPT2.) -*/ -#define LUA_PROMPT "> " -#define LUA_PROMPT2 ">> " - - -/* -@@ LUA_PROGNAME is the default name for the stand-alone Lua program. -** CHANGE it if your stand-alone interpreter has a different name and -** your system is not able to detect that name automatically. -*/ -#define LUA_PROGNAME "lua" - - -/* -@@ LUA_MAXINPUT is the maximum length for an input line in the -@* stand-alone interpreter. -** CHANGE it if you need longer lines. -*/ -#define LUA_MAXINPUT 512 - - -/* -@@ lua_readline defines how to show a prompt and then read a line from -@* the standard input. -@@ lua_saveline defines how to "save" a read line in a "history". -@@ lua_freeline defines how to free a line read by lua_readline. -** CHANGE them if you want to improve this functionality (e.g., by using -** GNU readline and history facilities). -*/ -#if defined(LUA_USE_READLINE) -#include -#include -#include -#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL) -#define lua_saveline(L,idx) \ - if (lua_strlen(L,idx) > 0) /* non-empty line? */ \ - add_history(lua_tostring(L, idx)); /* add it to history */ -#define lua_freeline(L,b) ((void)L, free(b)) -#else -#define lua_readline(L,b,p) \ - ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \ - fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */ -#define lua_saveline(L,idx) { (void)L; (void)idx; } -#define lua_freeline(L,b) { (void)L; (void)b; } -#endif - -#endif - -/* }================================================================== */ - - -/* -@@ LUAI_GCPAUSE defines the default pause between garbage-collector cycles -@* as a percentage. -** CHANGE it if you want the GC to run faster or slower (higher values -** mean larger pauses which mean slower collection.) You can also change -** this value dynamically. -*/ -#define LUAI_GCPAUSE 200 /* 200% (wait memory to double before next GC) */ - - -/* -@@ LUAI_GCMUL defines the default speed of garbage collection relative to -@* memory allocation as a percentage. -** CHANGE it if you want to change the granularity of the garbage -** collection. (Higher values mean coarser collections. 0 represents -** infinity, where each step performs a full collection.) You can also -** change this value dynamically. -*/ -#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */ - - - -/* -@@ LUA_COMPAT_GETN controls compatibility with old getn behavior. -** CHANGE it (define it) if you want exact compatibility with the -** behavior of setn/getn in Lua 5.0. -*/ -#undef LUA_COMPAT_GETN - -/* -@@ LUA_COMPAT_LOADLIB controls compatibility about global loadlib. -** CHANGE it to undefined as soon as you do not need a global 'loadlib' -** function (the function is still available as 'package.loadlib'). -*/ -#undef LUA_COMPAT_LOADLIB - -/* -@@ LUA_COMPAT_VARARG controls compatibility with old vararg feature. -** CHANGE it to undefined as soon as your programs use only '...' to -** access vararg parameters (instead of the old 'arg' table). -*/ -#define LUA_COMPAT_VARARG - -/* -@@ LUA_COMPAT_MOD controls compatibility with old math.mod function. -** CHANGE it to undefined as soon as your programs use 'math.fmod' or -** the new '%' operator instead of 'math.mod'. -*/ -#define LUA_COMPAT_MOD - -/* -@@ LUA_COMPAT_LSTR controls compatibility with old long string nesting -@* facility. -** CHANGE it to 2 if you want the old behaviour, or undefine it to turn -** off the advisory error when nesting [[...]]. -*/ -#define LUA_COMPAT_LSTR 1 - -/* -@@ LUA_COMPAT_GFIND controls compatibility with old 'string.gfind' name. -** CHANGE it to undefined as soon as you rename 'string.gfind' to -** 'string.gmatch'. -*/ -#define LUA_COMPAT_GFIND - -/* -@@ LUA_COMPAT_OPENLIB controls compatibility with old 'luaL_openlib' -@* behavior. -** CHANGE it to undefined as soon as you replace to 'luaL_register' -** your uses of 'luaL_openlib' -*/ -#define LUA_COMPAT_OPENLIB - - - -/* -@@ luai_apicheck is the assert macro used by the Lua-C API. -** CHANGE luai_apicheck if you want Lua to perform some checks in the -** parameters it gets from API calls. This may slow down the interpreter -** a bit, but may be quite useful when debugging C code that interfaces -** with Lua. A useful redefinition is to use assert.h. -*/ -#if defined(LUA_USE_APICHECK) -#include -#define luai_apicheck(L,o) { (void)L; assert(o); } -#else -#define luai_apicheck(L,o) { (void)L; } -#endif - - -/* -@@ LUAI_BITSINT defines the number of bits in an int. -** CHANGE here if Lua cannot automatically detect the number of bits of -** your machine. Probably you do not need to change this. -*/ -/* avoid overflows in comparison */ -#if INT_MAX-20 < 32760 -#define LUAI_BITSINT 16 -#elif INT_MAX > 2147483640L -/* int has at least 32 bits */ -#define LUAI_BITSINT 32 -#else -#error "you must define LUA_BITSINT with number of bits in an integer" -#endif - - -/* -@@ LUAI_UINT32 is an unsigned integer with at least 32 bits. -@@ LUAI_INT32 is an signed integer with at least 32 bits. -@@ LUAI_UMEM is an unsigned integer big enough to count the total -@* memory used by Lua. -@@ LUAI_MEM is a signed integer big enough to count the total memory -@* used by Lua. -** CHANGE here if for some weird reason the default definitions are not -** good enough for your machine. (The definitions in the 'else' -** part always works, but may waste space on machines with 64-bit -** longs.) Probably you do not need to change this. -*/ -#if LUAI_BITSINT >= 32 -#define LUAI_UINT32 unsigned int -#define LUAI_INT32 int -#define LUAI_MAXINT32 INT_MAX -#define LUAI_UMEM size_t -#define LUAI_MEM ptrdiff_t -#else -/* 16-bit ints */ -#define LUAI_UINT32 unsigned long -#define LUAI_INT32 long -#define LUAI_MAXINT32 LONG_MAX -#define LUAI_UMEM unsigned long -#define LUAI_MEM long -#endif - - -/* -@@ LUAI_MAXCALLS limits the number of nested calls. -** CHANGE it if you need really deep recursive calls. This limit is -** arbitrary; its only purpose is to stop infinite recursion before -** exhausting memory. -*/ -#define LUAI_MAXCALLS 20000 - - -/* -@@ LUAI_MAXCSTACK limits the number of Lua stack slots that a C function -@* can use. -** CHANGE it if you need lots of (Lua) stack space for your C -** functions. This limit is arbitrary; its only purpose is to stop C -** functions to consume unlimited stack space. (must be smaller than -** -LUA_REGISTRYINDEX) -*/ -#define LUAI_MAXCSTACK 8000 - - - -/* -** {================================================================== -** CHANGE (to smaller values) the following definitions if your system -** has a small C stack. (Or you may want to change them to larger -** values if your system has a large C stack and these limits are -** too rigid for you.) Some of these constants control the size of -** stack-allocated arrays used by the compiler or the interpreter, while -** others limit the maximum number of recursive calls that the compiler -** or the interpreter can perform. Values too large may cause a C stack -** overflow for some forms of deep constructs. -** =================================================================== -*/ - - -/* -@@ LUAI_MAXCCALLS is the maximum depth for nested C calls (short) and -@* syntactical nested non-terminals in a program. -*/ -#define LUAI_MAXCCALLS 200 - - -/* -@@ LUAI_MAXVARS is the maximum number of local variables per function -@* (must be smaller than 250). -*/ -#define LUAI_MAXVARS 200 - - -/* -@@ LUAI_MAXUPVALUES is the maximum number of upvalues per function -@* (must be smaller than 250). -*/ -#define LUAI_MAXUPVALUES 60 - - -/* -@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. -*/ -#define LUAL_BUFFERSIZE BUFSIZ - -/* }================================================================== */ - - - - -/* -** {================================================================== -@@ LUA_NUMBER is the type of numbers in Lua. -** CHANGE the following definitions only if you want to build Lua -** with a number type different from double. You may also need to -** change lua_number2int & lua_number2integer. -** =================================================================== -*/ - -#define LUA_NUMBER_DOUBLE -#define LUA_NUMBER double - -/* -@@ LUAI_UACNUMBER is the result of an 'usual argument conversion' -@* over a number. -*/ -#define LUAI_UACNUMBER double - - -/* -@@ LUA_NUMBER_SCAN is the format for reading numbers. -@@ LUA_NUMBER_FMT is the format for writing numbers. -@@ lua_number2str converts a number to a string. -@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion. -@@ lua_str2number converts a string to a number. -*/ -#define LUA_NUMBER_SCAN "%lf" -#define LUA_NUMBER_FMT "%.14g" -#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) -#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */ -#define lua_str2number(s,p) strtod((s), (p)) - - -/* -@@ The luai_num* macros define the primitive operations over numbers. -*/ -#if defined(LUA_CORE) -#include -#define luai_numadd(a,b) ((a)+(b)) -#define luai_numsub(a,b) ((a)-(b)) -#define luai_nummul(a,b) ((a)*(b)) -#define luai_numdiv(a,b) ((a)/(b)) -#define luai_nummod(a,b) ((a) - floor((a)/(b))*(b)) -#define luai_numpow(a,b) (pow(a,b)) -#define luai_numunm(a) (-(a)) -#define luai_numeq(a,b) ((a)==(b)) -#define luai_numlt(a,b) ((a)<(b)) -#define luai_numle(a,b) ((a)<=(b)) -#define luai_numisnan(a) (!luai_numeq((a), (a))) -#endif - - -/* -@@ lua_number2int is a macro to convert lua_Number to int. -@@ lua_number2integer is a macro to convert lua_Number to lua_Integer. -** CHANGE them if you know a faster way to convert a lua_Number to -** int (with any rounding method and without throwing errors) in your -** system. In Pentium machines, a naive typecast from double to int -** in C is extremely slow, so any alternative is worth trying. -*/ - -/* On a Pentium, resort to a trick */ -#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) && !defined(__SSE2__) && \ - (defined(__i386) || defined (_M_IX86) || defined(__i386__)) - -/* On a Microsoft compiler, use assembler */ -#if defined(_MSC_VER) - -#define lua_number2int(i,d) __asm fld d __asm fistp i -#define lua_number2integer(i,n) lua_number2int(i, n) - -/* the next trick should work on any Pentium, but sometimes clashes - with a DirectX idiosyncrasy */ -#else - -union luai_Cast { double l_d; long l_l; }; -#define lua_number2int(i,d) \ - { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; } -#define lua_number2integer(i,n) lua_number2int(i, n) - -#endif - - -/* this option always works, but may be slow */ -#else -#define lua_number2int(i,d) ((i)=(int)(d)) -#define lua_number2integer(i,d) ((i)=(lua_Integer)(d)) - -#endif - -/* }================================================================== */ - - -/* -@@ LUAI_USER_ALIGNMENT_T is a type that requires maximum alignment. -** CHANGE it if your system requires alignments larger than double. (For -** instance, if your system supports long doubles and they must be -** aligned in 16-byte boundaries, then you should add long double in the -** union.) Probably you do not need to change this. -*/ -#define LUAI_USER_ALIGNMENT_T union { double u; void *s; long l; } - - -/* -@@ LUAI_THROW/LUAI_TRY define how Lua does exception handling. -** CHANGE them if you prefer to use longjmp/setjmp even with C++ -** or if want/don't to use _longjmp/_setjmp instead of regular -** longjmp/setjmp. By default, Lua handles errors with exceptions when -** compiling as C++ code, with _longjmp/_setjmp when asked to use them, -** and with longjmp/setjmp otherwise. -*/ -#if defined(__cplusplus) -/* C++ exceptions */ -#define LUAI_THROW(L,c) throw(c) -#define LUAI_TRY(L,c,a) try { a } catch(...) \ - { if ((c)->status == 0) (c)->status = -1; } -#define luai_jmpbuf int /* dummy variable */ - -#elif defined(LUA_USE_ULONGJMP) -/* in Unix, try _longjmp/_setjmp (more efficient) */ -#define LUAI_THROW(L,c) _longjmp((c)->b, 1) -#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a } -#define luai_jmpbuf jmp_buf - -#else -/* default handling with long jumps */ -#define LUAI_THROW(L,c) longjmp((c)->b, 1) -#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } -#define luai_jmpbuf jmp_buf - -#endif - - -/* -@@ LUA_MAXCAPTURES is the maximum number of captures that a pattern -@* can do during pattern-matching. -** CHANGE it if you need more captures. This limit is arbitrary. -*/ -#define LUA_MAXCAPTURES 32 - - -/* -@@ lua_tmpnam is the function that the OS library uses to create a -@* temporary name. -@@ LUA_TMPNAMBUFSIZE is the maximum size of a name created by lua_tmpnam. -** CHANGE them if you have an alternative to tmpnam (which is considered -** insecure) or if you want the original tmpnam anyway. By default, Lua -** uses tmpnam except when POSIX is available, where it uses mkstemp. -*/ -#if defined(loslib_c) || defined(luaall_c) - -#if defined(LUA_USE_MKSTEMP) -#include -#define LUA_TMPNAMBUFSIZE 32 -#define lua_tmpnam(b,e) { \ - strcpy(b, "/tmp/lua_XXXXXX"); \ - e = mkstemp(b); \ - if (e != -1) close(e); \ - e = (e == -1); } - -#else -#define LUA_TMPNAMBUFSIZE L_tmpnam -#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } -#endif - -#endif - - -/* -@@ lua_popen spawns a new process connected to the current one through -@* the file streams. -** CHANGE it if you have a way to implement it in your system. -*/ -#if defined(LUA_USE_POPEN) - -#define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m)) -#define lua_pclose(L,file) ((void)L, (pclose(file) != -1)) - -#elif defined(LUA_WIN) - -#define lua_popen(L,c,m) ((void)L, _popen(c,m)) -#define lua_pclose(L,file) ((void)L, (_pclose(file) != -1)) - -#else - -#define lua_popen(L,c,m) ((void)((void)c, m), \ - luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0) -#define lua_pclose(L,file) ((void)((void)L, file), 0) - -#endif - -/* -@@ LUA_DL_* define which dynamic-library system Lua should use. -** CHANGE here if Lua has problems choosing the appropriate -** dynamic-library system for your platform (either Windows' DLL, Mac's -** dyld, or Unix's dlopen). If your system is some kind of Unix, there -** is a good chance that it has dlopen, so LUA_DL_DLOPEN will work for -** it. To use dlopen you also need to adapt the src/Makefile (probably -** adding -ldl to the linker options), so Lua does not select it -** automatically. (When you change the makefile to add -ldl, you must -** also add -DLUA_USE_DLOPEN.) -** If you do not want any kind of dynamic library, undefine all these -** options. -** By default, _WIN32 gets LUA_DL_DLL and MAC OS X gets LUA_DL_DYLD. -*/ -#if defined(LUA_USE_DLOPEN) -#define LUA_DL_DLOPEN -#endif - -#if defined(LUA_WIN) -#define LUA_DL_DLL -#endif - - -/* -@@ LUAI_EXTRASPACE allows you to add user-specific data in a lua_State -@* (the data goes just *before* the lua_State pointer). -** CHANGE (define) this if you really need that. This value must be -** a multiple of the maximum alignment required for your machine. -*/ -#define LUAI_EXTRASPACE 0 - - -/* -@@ luai_userstate* allow user-specific actions on threads. -** CHANGE them if you defined LUAI_EXTRASPACE and need to do something -** extra when a thread is created/deleted/resumed/yielded. -*/ -#define luai_userstateopen(L) ((void)L) -#define luai_userstateclose(L) ((void)L) -#define luai_userstatethread(L,L1) ((void)L) -#define luai_userstatefree(L) ((void)L) -#define luai_userstateresume(L,n) ((void)L) -#define luai_userstateyield(L,n) ((void)L) - - -/* -@@ LUA_INTFRMLEN is the length modifier for integer conversions -@* in 'string.format'. -@@ LUA_INTFRM_T is the integer type correspoding to the previous length -@* modifier. -** CHANGE them if your system supports long long or does not support long. -*/ - -#if defined(LUA_USELONGLONG) - -#define LUA_INTFRMLEN "ll" -#define LUA_INTFRM_T long long - -#else - -#define LUA_INTFRMLEN "l" -#define LUA_INTFRM_T long - -#endif - - - -/* =================================================================== */ - -/* -** Local configuration. You can use this space to add your redefinitions -** without modifying the main part of the file. -*/ - - - -#endif - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lualib.h b/desmume/src/windows/lua/lua-5.1.4/src/lualib.h deleted file mode 100644 index 469417f67..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lualib.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -** $Id: lualib.h,v 1.36.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lua standard libraries -** See Copyright Notice in lua.h -*/ - - -#ifndef lualib_h -#define lualib_h - -#include "lua.h" - - -/* Key to file-handle type */ -#define LUA_FILEHANDLE "FILE*" - - -#define LUA_COLIBNAME "coroutine" -LUALIB_API int (luaopen_base) (lua_State *L); - -#define LUA_TABLIBNAME "table" -LUALIB_API int (luaopen_table) (lua_State *L); - -#define LUA_IOLIBNAME "io" -LUALIB_API int (luaopen_io) (lua_State *L); - -#define LUA_OSLIBNAME "os" -LUALIB_API int (luaopen_os) (lua_State *L); - -#define LUA_STRLIBNAME "string" -LUALIB_API int (luaopen_string) (lua_State *L); - -#define LUA_MATHLIBNAME "math" -LUALIB_API int (luaopen_math) (lua_State *L); - -#define LUA_DBLIBNAME "debug" -LUALIB_API int (luaopen_debug) (lua_State *L); - -#define LUA_LOADLIBNAME "package" -LUALIB_API int (luaopen_package) (lua_State *L); - - -/* open all previous libraries */ -LUALIB_API void (luaL_openlibs) (lua_State *L); - - - -#ifndef lua_assert -#define lua_assert(x) ((void)0) -#endif - - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lundump.c b/desmume/src/windows/lua/lua-5.1.4/src/lundump.c deleted file mode 100644 index 8010a4579..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lundump.c +++ /dev/null @@ -1,227 +0,0 @@ -/* -** $Id: lundump.c,v 2.7.1.4 2008/04/04 19:51:41 roberto Exp $ -** load precompiled Lua chunks -** See Copyright Notice in lua.h -*/ - -#include - -#define lundump_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lmem.h" -#include "lobject.h" -#include "lstring.h" -#include "lundump.h" -#include "lzio.h" - -typedef struct { - lua_State* L; - ZIO* Z; - Mbuffer* b; - const char* name; -} LoadState; - -#ifdef LUAC_TRUST_BINARIES -#define IF(c,s) -#define error(S,s) -#else -#define IF(c,s) if (c) error(S,s) - -static void error(LoadState* S, const char* why) -{ - luaO_pushfstring(S->L,"%s: %s in precompiled chunk",S->name,why); - luaD_throw(S->L,LUA_ERRSYNTAX); -} -#endif - -#define LoadMem(S,b,n,size) LoadBlock(S,b,(n)*(size)) -#define LoadByte(S) (lu_byte)LoadChar(S) -#define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x)) -#define LoadVector(S,b,n,size) LoadMem(S,b,n,size) - -static void LoadBlock(LoadState* S, void* b, size_t size) -{ - size_t r=luaZ_read(S->Z,b,size); - IF (r!=0, "unexpected end"); -} - -static int LoadChar(LoadState* S) -{ - char x; - LoadVar(S,x); - return x; -} - -static int LoadInt(LoadState* S) -{ - int x; - LoadVar(S,x); - IF (x<0, "bad integer"); - return x; -} - -static lua_Number LoadNumber(LoadState* S) -{ - lua_Number x; - LoadVar(S,x); - return x; -} - -static TString* LoadString(LoadState* S) -{ - size_t size; - LoadVar(S,size); - if (size==0) - return NULL; - else - { - char* s=luaZ_openspace(S->L,S->b,size); - LoadBlock(S,s,size); - return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */ - } -} - -static void LoadCode(LoadState* S, Proto* f) -{ - int n=LoadInt(S); - f->code=luaM_newvector(S->L,n,Instruction); - f->sizecode=n; - LoadVector(S,f->code,n,sizeof(Instruction)); -} - -static Proto* LoadFunction(LoadState* S, TString* p); - -static void LoadConstants(LoadState* S, Proto* f) -{ - int i,n; - n=LoadInt(S); - f->k=luaM_newvector(S->L,n,TValue); - f->sizek=n; - for (i=0; ik[i]); - for (i=0; ik[i]; - int t=LoadChar(S); - switch (t) - { - case LUA_TNIL: - setnilvalue(o); - break; - case LUA_TBOOLEAN: - setbvalue(o,LoadChar(S)!=0); - break; - case LUA_TNUMBER: - setnvalue(o,LoadNumber(S)); - break; - case LUA_TSTRING: - setsvalue2n(S->L,o,LoadString(S)); - break; - default: - error(S,"bad constant"); - break; - } - } - n=LoadInt(S); - f->p=luaM_newvector(S->L,n,Proto*); - f->sizep=n; - for (i=0; ip[i]=NULL; - for (i=0; ip[i]=LoadFunction(S,f->source); -} - -static void LoadDebug(LoadState* S, Proto* f) -{ - int i,n; - n=LoadInt(S); - f->lineinfo=luaM_newvector(S->L,n,int); - f->sizelineinfo=n; - LoadVector(S,f->lineinfo,n,sizeof(int)); - n=LoadInt(S); - f->locvars=luaM_newvector(S->L,n,LocVar); - f->sizelocvars=n; - for (i=0; ilocvars[i].varname=NULL; - for (i=0; ilocvars[i].varname=LoadString(S); - f->locvars[i].startpc=LoadInt(S); - f->locvars[i].endpc=LoadInt(S); - } - n=LoadInt(S); - f->upvalues=luaM_newvector(S->L,n,TString*); - f->sizeupvalues=n; - for (i=0; iupvalues[i]=NULL; - for (i=0; iupvalues[i]=LoadString(S); -} - -static Proto* LoadFunction(LoadState* S, TString* p) -{ - Proto* f; - if (++S->L->nCcalls > LUAI_MAXCCALLS) error(S,"code too deep"); - f=luaF_newproto(S->L); - setptvalue2s(S->L,S->L->top,f); incr_top(S->L); - f->source=LoadString(S); if (f->source==NULL) f->source=p; - f->linedefined=LoadInt(S); - f->lastlinedefined=LoadInt(S); - f->nups=LoadByte(S); - f->numparams=LoadByte(S); - f->is_vararg=LoadByte(S); - f->maxstacksize=LoadByte(S); - LoadCode(S,f); - LoadConstants(S,f); - LoadDebug(S,f); - IF (!luaG_checkcode(f), "bad code"); - S->L->top--; - S->L->nCcalls--; - return f; -} - -static void LoadHeader(LoadState* S) -{ - char h[LUAC_HEADERSIZE]; - char s[LUAC_HEADERSIZE]; - luaU_header(h); - LoadBlock(S,s,LUAC_HEADERSIZE); - IF (memcmp(h,s,LUAC_HEADERSIZE)!=0, "bad header"); -} - -/* -** load precompiled chunk -*/ -Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name) -{ - LoadState S; - if (*name=='@' || *name=='=') - S.name=name+1; - else if (*name==LUA_SIGNATURE[0]) - S.name="binary string"; - else - S.name=name; - S.L=L; - S.Z=Z; - S.b=buff; - LoadHeader(&S); - return LoadFunction(&S,luaS_newliteral(L,"=?")); -} - -/* -* make header -*/ -void luaU_header (char* h) -{ - int x=1; - memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-1); - h+=sizeof(LUA_SIGNATURE)-1; - *h++=(char)LUAC_VERSION; - *h++=(char)LUAC_FORMAT; - *h++=(char)*(char*)&x; /* endianness */ - *h++=(char)sizeof(int); - *h++=(char)sizeof(size_t); - *h++=(char)sizeof(Instruction); - *h++=(char)sizeof(lua_Number); - *h++=(char)(((lua_Number)0.5)==0); /* is lua_Number integral? */ -} diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lundump.h b/desmume/src/windows/lua/lua-5.1.4/src/lundump.h deleted file mode 100644 index c80189dbf..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lundump.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -** $Id: lundump.h,v 1.37.1.1 2007/12/27 13:02:25 roberto Exp $ -** load precompiled Lua chunks -** See Copyright Notice in lua.h -*/ - -#ifndef lundump_h -#define lundump_h - -#include "lobject.h" -#include "lzio.h" - -/* load one chunk; from lundump.c */ -LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name); - -/* make header; from lundump.c */ -LUAI_FUNC void luaU_header (char* h); - -/* dump one chunk; from ldump.c */ -LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip); - -#ifdef luac_c -/* print one chunk; from print.c */ -LUAI_FUNC void luaU_print (const Proto* f, int full); -#endif - -/* for header of binary files -- this is Lua 5.1 */ -#define LUAC_VERSION 0x51 - -/* for header of binary files -- this is the official format */ -#define LUAC_FORMAT 0 - -/* size of header of binary files */ -#define LUAC_HEADERSIZE 12 - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lvm.c b/desmume/src/windows/lua/lua-5.1.4/src/lvm.c deleted file mode 100644 index ee3256ab9..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lvm.c +++ /dev/null @@ -1,763 +0,0 @@ -/* -** $Id: lvm.c,v 2.63.1.3 2007/12/28 15:32:23 roberto Exp $ -** Lua virtual machine -** See Copyright Notice in lua.h -*/ - - -#include -#include -#include - -#define lvm_c -#define LUA_CORE - -#include "lua.h" - -#include "ldebug.h" -#include "ldo.h" -#include "lfunc.h" -#include "lgc.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lstate.h" -#include "lstring.h" -#include "ltable.h" -#include "ltm.h" -#include "lvm.h" - - - -/* limit for table tag-method chains (to avoid loops) */ -#define MAXTAGLOOP 100 - - -const TValue *luaV_tonumber (const TValue *obj, TValue *n) { - lua_Number num; - if (ttisnumber(obj)) return obj; - if (ttisstring(obj) && luaO_str2d(svalue(obj), &num)) { - setnvalue(n, num); - return n; - } - else - return NULL; -} - - -int luaV_tostring (lua_State *L, StkId obj) { - if (!ttisnumber(obj)) - return 0; - else { - char s[LUAI_MAXNUMBER2STR]; - lua_Number n = nvalue(obj); - lua_number2str(s, n); - setsvalue2s(L, obj, luaS_new(L, s)); - return 1; - } -} - - -static void traceexec (lua_State *L, const Instruction *pc) { - lu_byte mask = L->hookmask; - const Instruction *oldpc = L->savedpc; - L->savedpc = pc; - if ((mask & LUA_MASKCOUNT) && L->hookcount == 0) { - resethookcount(L); - luaD_callhook(L, LUA_HOOKCOUNT, -1); - } - if (mask & LUA_MASKLINE) { - Proto *p = ci_func(L->ci)->l.p; - int npc = pcRel(pc, p); - int newline = getline(p, npc); - /* call linehook when enter a new function, when jump back (loop), - or when enter a new line */ - if (npc == 0 || pc <= oldpc || newline != getline(p, pcRel(oldpc, p))) - luaD_callhook(L, LUA_HOOKLINE, newline); - } -} - - -static void callTMres (lua_State *L, StkId res, const TValue *f, - const TValue *p1, const TValue *p2) { - ptrdiff_t result = savestack(L, res); - setobj2s(L, L->top, f); /* push function */ - setobj2s(L, L->top+1, p1); /* 1st argument */ - setobj2s(L, L->top+2, p2); /* 2nd argument */ - luaD_checkstack(L, 3); - L->top += 3; - luaD_call(L, L->top - 3, 1); - res = restorestack(L, result); - L->top--; - setobjs2s(L, res, L->top); -} - - - -static void callTM (lua_State *L, const TValue *f, const TValue *p1, - const TValue *p2, const TValue *p3) { - setobj2s(L, L->top, f); /* push function */ - setobj2s(L, L->top+1, p1); /* 1st argument */ - setobj2s(L, L->top+2, p2); /* 2nd argument */ - setobj2s(L, L->top+3, p3); /* 3th argument */ - luaD_checkstack(L, 4); - L->top += 4; - luaD_call(L, L->top - 4, 0); -} - - -void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { - int loop; - for (loop = 0; loop < MAXTAGLOOP; loop++) { - const TValue *tm; - if (ttistable(t)) { /* `t' is a table? */ - Table *h = hvalue(t); - const TValue *res = luaH_get(h, key); /* do a primitive get */ - if (!ttisnil(res) || /* result is no nil? */ - (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */ - setobj2s(L, val, res); - return; - } - /* else will try the tag method */ - } - else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX))) - luaG_typeerror(L, t, "index"); - if (ttisfunction(tm)) { - callTMres(L, val, tm, t, key); - return; - } - t = tm; /* else repeat with `tm' */ - } - luaG_runerror(L, "loop in gettable"); -} - - -void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { - int loop; - for (loop = 0; loop < MAXTAGLOOP; loop++) { - const TValue *tm; - if (ttistable(t)) { /* `t' is a table? */ - Table *h = hvalue(t); - TValue *oldval = luaH_set(L, h, key); /* do a primitive set */ - if (!ttisnil(oldval) || /* result is no nil? */ - (tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL) { /* or no TM? */ - setobj2t(L, oldval, val); - luaC_barriert(L, h, val); - return; - } - /* else will try the tag method */ - } - else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX))) - luaG_typeerror(L, t, "index"); - if (ttisfunction(tm)) { - callTM(L, tm, t, key, val); - return; - } - t = tm; /* else repeat with `tm' */ - } - luaG_runerror(L, "loop in settable"); -} - - -static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2, - StkId res, TMS event) { - const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ - if (ttisnil(tm)) - tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ - if (ttisnil(tm)) return 0; - callTMres(L, res, tm, p1, p2); - return 1; -} - - -static const TValue *get_compTM (lua_State *L, Table *mt1, Table *mt2, - TMS event) { - const TValue *tm1 = fasttm(L, mt1, event); - const TValue *tm2; - if (tm1 == NULL) return NULL; /* no metamethod */ - if (mt1 == mt2) return tm1; /* same metatables => same metamethods */ - tm2 = fasttm(L, mt2, event); - if (tm2 == NULL) return NULL; /* no metamethod */ - if (luaO_rawequalObj(tm1, tm2)) /* same metamethods? */ - return tm1; - return NULL; -} - - -static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2, - TMS event) { - const TValue *tm1 = luaT_gettmbyobj(L, p1, event); - const TValue *tm2; - if (ttisnil(tm1)) return -1; /* no metamethod? */ - tm2 = luaT_gettmbyobj(L, p2, event); - if (!luaO_rawequalObj(tm1, tm2)) /* different metamethods? */ - return -1; - callTMres(L, L->top, tm1, p1, p2); - return !l_isfalse(L->top); -} - - -static int l_strcmp (const TString *ls, const TString *rs) { - const char *l = getstr(ls); - size_t ll = ls->tsv.len; - const char *r = getstr(rs); - size_t lr = rs->tsv.len; - for (;;) { - int temp = strcoll(l, r); - if (temp != 0) return temp; - else { /* strings are equal up to a `\0' */ - size_t len = strlen(l); /* index of first `\0' in both strings */ - if (len == lr) /* r is finished? */ - return (len == ll) ? 0 : 1; - else if (len == ll) /* l is finished? */ - return -1; /* l is smaller than r (because r is not finished) */ - /* both strings longer than `len'; go on comparing (after the `\0') */ - len++; - l += len; ll -= len; r += len; lr -= len; - } - } -} - - -int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { - int res; - if (ttype(l) != ttype(r)) - return luaG_ordererror(L, l, r); - else if (ttisnumber(l)) - return luai_numlt(nvalue(l), nvalue(r)); - else if (ttisstring(l)) - return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0; - else if ((res = call_orderTM(L, l, r, TM_LT)) != -1) - return res; - return luaG_ordererror(L, l, r); -} - - -static int lessequal (lua_State *L, const TValue *l, const TValue *r) { - int res; - if (ttype(l) != ttype(r)) - return luaG_ordererror(L, l, r); - else if (ttisnumber(l)) - return luai_numle(nvalue(l), nvalue(r)); - else if (ttisstring(l)) - return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0; - else if ((res = call_orderTM(L, l, r, TM_LE)) != -1) /* first try `le' */ - return res; - else if ((res = call_orderTM(L, r, l, TM_LT)) != -1) /* else try `lt' */ - return !res; - return luaG_ordererror(L, l, r); -} - - -int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) { - const TValue *tm; - lua_assert(ttype(t1) == ttype(t2)); - switch (ttype(t1)) { - case LUA_TNIL: return 1; - case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); - case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */ - case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); - case LUA_TUSERDATA: { - if (uvalue(t1) == uvalue(t2)) return 1; - tm = get_compTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, - TM_EQ); - break; /* will try TM */ - } - case LUA_TTABLE: { - if (hvalue(t1) == hvalue(t2)) return 1; - tm = get_compTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ); - break; /* will try TM */ - } - default: return gcvalue(t1) == gcvalue(t2); - } - if (tm == NULL) return 0; /* no TM? */ - callTMres(L, L->top, tm, t1, t2); /* call TM */ - return !l_isfalse(L->top); -} - - -void luaV_concat (lua_State *L, int total, int last) { - do { - StkId top = L->base + last + 1; - int n = 2; /* number of elements handled in this pass (at least 2) */ - if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) { - if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT)) - luaG_concaterror(L, top-2, top-1); - } else if (tsvalue(top-1)->len == 0) /* second op is empty? */ - (void)tostring(L, top - 2); /* result is first op (as string) */ - else { - /* at least two string values; get as many as possible */ - size_t tl = tsvalue(top-1)->len; - char *buffer; - int i; - /* collect total length */ - for (n = 1; n < total && tostring(L, top-n-1); n++) { - size_t l = tsvalue(top-n-1)->len; - if (l >= MAX_SIZET - tl) luaG_runerror(L, "string length overflow"); - tl += l; - } - buffer = luaZ_openspace(L, &G(L)->buff, tl); - tl = 0; - for (i=n; i>0; i--) { /* concat all strings */ - size_t l = tsvalue(top-i)->len; - memcpy(buffer+tl, svalue(top-i), l); - tl += l; - } - setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl)); - } - total -= n-1; /* got `n' strings to create 1 new */ - last -= n-1; - } while (total > 1); /* repeat until only 1 result left */ -} - - -static void Arith (lua_State *L, StkId ra, const TValue *rb, - const TValue *rc, TMS op) { - TValue tempb, tempc; - const TValue *b, *c; - if ((b = luaV_tonumber(rb, &tempb)) != NULL && - (c = luaV_tonumber(rc, &tempc)) != NULL) { - lua_Number nb = nvalue(b), nc = nvalue(c); - switch (op) { - case TM_ADD: setnvalue(ra, luai_numadd(nb, nc)); break; - case TM_SUB: setnvalue(ra, luai_numsub(nb, nc)); break; - case TM_MUL: setnvalue(ra, luai_nummul(nb, nc)); break; - case TM_DIV: setnvalue(ra, luai_numdiv(nb, nc)); break; - case TM_MOD: setnvalue(ra, luai_nummod(nb, nc)); break; - case TM_POW: setnvalue(ra, luai_numpow(nb, nc)); break; - case TM_UNM: setnvalue(ra, luai_numunm(nb)); break; - default: lua_assert(0); break; - } - } - else if (!call_binTM(L, rb, rc, ra, op)) - luaG_aritherror(L, rb, rc); -} - - - -/* -** some macros for common tasks in `luaV_execute' -*/ - -#define runtime_check(L, c) { if (!(c)) break; } - -#define RA(i) (base+GETARG_A(i)) -/* to be used after possible stack reallocation */ -#define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i)) -#define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i)) -#define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \ - ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i)) -#define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \ - ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i)) -#define KBx(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, k+GETARG_Bx(i)) - - -#define dojump(L,pc,i) {(pc) += (i); luai_threadyield(L);} - - -#define Protect(x) { L->savedpc = pc; {x;}; base = L->base; } - - -#define arith_op(op,tm) { \ - TValue *rb = RKB(i); \ - TValue *rc = RKC(i); \ - if (ttisnumber(rb) && ttisnumber(rc)) { \ - lua_Number nb = nvalue(rb), nc = nvalue(rc); \ - setnvalue(ra, op(nb, nc)); \ - } \ - else \ - Protect(Arith(L, ra, rb, rc, tm)); \ - } - - - -void luaV_execute (lua_State *L, int nexeccalls) { - LClosure *cl; - StkId base; - TValue *k; - const Instruction *pc; - reentry: /* entry point */ - lua_assert(isLua(L->ci)); - pc = L->savedpc; - cl = &clvalue(L->ci->func)->l; - base = L->base; - k = cl->p->k; - /* main loop of interpreter */ - for (;;) { - const Instruction i = *pc++; - StkId ra; - if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) && - (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) { - traceexec(L, pc); - if (L->status == LUA_YIELD) { /* did hook yield? */ - L->savedpc = pc - 1; - return; - } - base = L->base; - } - /* warning!! several calls may realloc the stack and invalidate `ra' */ - ra = RA(i); - lua_assert(base == L->base && L->base == L->ci->base); - lua_assert(base <= L->top && L->top <= L->stack + L->stacksize); - lua_assert(L->top == L->ci->top || luaG_checkopenop(i)); - switch (GET_OPCODE(i)) { - case OP_MOVE: { - setobjs2s(L, ra, RB(i)); - continue; - } - case OP_LOADK: { - setobj2s(L, ra, KBx(i)); - continue; - } - case OP_LOADBOOL: { - setbvalue(ra, GETARG_B(i)); - if (GETARG_C(i)) pc++; /* skip next instruction (if C) */ - continue; - } - case OP_LOADNIL: { - TValue *rb = RB(i); - do { - setnilvalue(rb--); - } while (rb >= ra); - continue; - } - case OP_GETUPVAL: { - int b = GETARG_B(i); - setobj2s(L, ra, cl->upvals[b]->v); - continue; - } - case OP_GETGLOBAL: { - TValue g; - TValue *rb = KBx(i); - sethvalue(L, &g, cl->env); - lua_assert(ttisstring(rb)); - Protect(luaV_gettable(L, &g, rb, ra)); - continue; - } - case OP_GETTABLE: { - Protect(luaV_gettable(L, RB(i), RKC(i), ra)); - continue; - } - case OP_SETGLOBAL: { - TValue g; - sethvalue(L, &g, cl->env); - lua_assert(ttisstring(KBx(i))); - Protect(luaV_settable(L, &g, KBx(i), ra)); - continue; - } - case OP_SETUPVAL: { - UpVal *uv = cl->upvals[GETARG_B(i)]; - setobj(L, uv->v, ra); - luaC_barrier(L, uv, ra); - continue; - } - case OP_SETTABLE: { - Protect(luaV_settable(L, ra, RKB(i), RKC(i))); - continue; - } - case OP_NEWTABLE: { - int b = GETARG_B(i); - int c = GETARG_C(i); - sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c))); - Protect(luaC_checkGC(L)); - continue; - } - case OP_SELF: { - StkId rb = RB(i); - setobjs2s(L, ra+1, rb); - Protect(luaV_gettable(L, rb, RKC(i), ra)); - continue; - } - case OP_ADD: { - arith_op(luai_numadd, TM_ADD); - continue; - } - case OP_SUB: { - arith_op(luai_numsub, TM_SUB); - continue; - } - case OP_MUL: { - arith_op(luai_nummul, TM_MUL); - continue; - } - case OP_DIV: { - arith_op(luai_numdiv, TM_DIV); - continue; - } - case OP_MOD: { - arith_op(luai_nummod, TM_MOD); - continue; - } - case OP_POW: { - arith_op(luai_numpow, TM_POW); - continue; - } - case OP_UNM: { - TValue *rb = RB(i); - if (ttisnumber(rb)) { - lua_Number nb = nvalue(rb); - setnvalue(ra, luai_numunm(nb)); - } - else { - Protect(Arith(L, ra, rb, rb, TM_UNM)); - } - continue; - } - case OP_NOT: { - int res = l_isfalse(RB(i)); /* next assignment may change this value */ - setbvalue(ra, res); - continue; - } - case OP_LEN: { - const TValue *rb = RB(i); - switch (ttype(rb)) { - case LUA_TTABLE: { - setnvalue(ra, cast_num(luaH_getn(hvalue(rb)))); - break; - } - case LUA_TSTRING: { - setnvalue(ra, cast_num(tsvalue(rb)->len)); - break; - } - default: { /* try metamethod */ - Protect( - if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN)) - luaG_typeerror(L, rb, "get length of"); - ) - } - } - continue; - } - case OP_CONCAT: { - int b = GETARG_B(i); - int c = GETARG_C(i); - Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L)); - setobjs2s(L, RA(i), base+b); - continue; - } - case OP_JMP: { - dojump(L, pc, GETARG_sBx(i)); - continue; - } - case OP_EQ: { - TValue *rb = RKB(i); - TValue *rc = RKC(i); - Protect( - if (equalobj(L, rb, rc) == GETARG_A(i)) - dojump(L, pc, GETARG_sBx(*pc)); - ) - pc++; - continue; - } - case OP_LT: { - Protect( - if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i)) - dojump(L, pc, GETARG_sBx(*pc)); - ) - pc++; - continue; - } - case OP_LE: { - Protect( - if (lessequal(L, RKB(i), RKC(i)) == GETARG_A(i)) - dojump(L, pc, GETARG_sBx(*pc)); - ) - pc++; - continue; - } - case OP_TEST: { - if (l_isfalse(ra) != GETARG_C(i)) - dojump(L, pc, GETARG_sBx(*pc)); - pc++; - continue; - } - case OP_TESTSET: { - TValue *rb = RB(i); - if (l_isfalse(rb) != GETARG_C(i)) { - setobjs2s(L, ra, rb); - dojump(L, pc, GETARG_sBx(*pc)); - } - pc++; - continue; - } - case OP_CALL: { - int b = GETARG_B(i); - int nresults = GETARG_C(i) - 1; - if (b != 0) L->top = ra+b; /* else previous instruction set top */ - L->savedpc = pc; - switch (luaD_precall(L, ra, nresults)) { - case PCRLUA: { - nexeccalls++; - goto reentry; /* restart luaV_execute over new Lua function */ - } - case PCRC: { - /* it was a C function (`precall' called it); adjust results */ - if (nresults >= 0) L->top = L->ci->top; - base = L->base; - continue; - } - default: { - return; /* yield */ - } - } - } - case OP_TAILCALL: { - int b = GETARG_B(i); - if (b != 0) L->top = ra+b; /* else previous instruction set top */ - L->savedpc = pc; - lua_assert(GETARG_C(i) - 1 == LUA_MULTRET); - switch (luaD_precall(L, ra, LUA_MULTRET)) { - case PCRLUA: { - /* tail call: put new frame in place of previous one */ - CallInfo *ci = L->ci - 1; /* previous frame */ - int aux; - StkId func = ci->func; - StkId pfunc = (ci+1)->func; /* previous function index */ - if (L->openupval) luaF_close(L, ci->base); - L->base = ci->base = ci->func + ((ci+1)->base - pfunc); - for (aux = 0; pfunc+aux < L->top; aux++) /* move frame down */ - setobjs2s(L, func+aux, pfunc+aux); - ci->top = L->top = func+aux; /* correct top */ - lua_assert(L->top == L->base + clvalue(func)->l.p->maxstacksize); - ci->savedpc = L->savedpc; - ci->tailcalls++; /* one more call lost */ - L->ci--; /* remove new frame */ - goto reentry; - } - case PCRC: { /* it was a C function (`precall' called it) */ - base = L->base; - continue; - } - default: { - return; /* yield */ - } - } - } - case OP_RETURN: { - int b = GETARG_B(i); - if (b != 0) L->top = ra+b-1; - if (L->openupval) luaF_close(L, base); - L->savedpc = pc; - b = luaD_poscall(L, ra); - if (--nexeccalls == 0) /* was previous function running `here'? */ - return; /* no: return */ - else { /* yes: continue its execution */ - if (b) L->top = L->ci->top; - lua_assert(isLua(L->ci)); - lua_assert(GET_OPCODE(*((L->ci)->savedpc - 1)) == OP_CALL); - goto reentry; - } - } - case OP_FORLOOP: { - lua_Number step = nvalue(ra+2); - lua_Number idx = luai_numadd(nvalue(ra), step); /* increment index */ - lua_Number limit = nvalue(ra+1); - if (luai_numlt(0, step) ? luai_numle(idx, limit) - : luai_numle(limit, idx)) { - dojump(L, pc, GETARG_sBx(i)); /* jump back */ - setnvalue(ra, idx); /* update internal index... */ - setnvalue(ra+3, idx); /* ...and external index */ - } - continue; - } - case OP_FORPREP: { - const TValue *init = ra; - const TValue *plimit = ra+1; - const TValue *pstep = ra+2; - L->savedpc = pc; /* next steps may throw errors */ - if (!tonumber(init, ra)) - luaG_runerror(L, LUA_QL("for") " initial value must be a number"); - else if (!tonumber(plimit, ra+1)) - luaG_runerror(L, LUA_QL("for") " limit must be a number"); - else if (!tonumber(pstep, ra+2)) - luaG_runerror(L, LUA_QL("for") " step must be a number"); - setnvalue(ra, luai_numsub(nvalue(ra), nvalue(pstep))); - dojump(L, pc, GETARG_sBx(i)); - continue; - } - case OP_TFORLOOP: { - StkId cb = ra + 3; /* call base */ - setobjs2s(L, cb+2, ra+2); - setobjs2s(L, cb+1, ra+1); - setobjs2s(L, cb, ra); - L->top = cb+3; /* func. + 2 args (state and index) */ - Protect(luaD_call(L, cb, GETARG_C(i))); - L->top = L->ci->top; - cb = RA(i) + 3; /* previous call may change the stack */ - if (!ttisnil(cb)) { /* continue loop? */ - setobjs2s(L, cb-1, cb); /* save control variable */ - dojump(L, pc, GETARG_sBx(*pc)); /* jump back */ - } - pc++; - continue; - } - case OP_SETLIST: { - int n = GETARG_B(i); - int c = GETARG_C(i); - int last; - Table *h; - if (n == 0) { - n = cast_int(L->top - ra) - 1; - L->top = L->ci->top; - } - if (c == 0) c = cast_int(*pc++); - runtime_check(L, ttistable(ra)); - h = hvalue(ra); - last = ((c-1)*LFIELDS_PER_FLUSH) + n; - if (last > h->sizearray) /* needs more space? */ - luaH_resizearray(L, h, last); /* pre-alloc it at once */ - for (; n > 0; n--) { - TValue *val = ra+n; - setobj2t(L, luaH_setnum(L, h, last--), val); - luaC_barriert(L, h, val); - } - continue; - } - case OP_CLOSE: { - luaF_close(L, ra); - continue; - } - case OP_CLOSURE: { - Proto *p; - Closure *ncl; - int nup, j; - p = cl->p->p[GETARG_Bx(i)]; - nup = p->nups; - ncl = luaF_newLclosure(L, nup, cl->env); - ncl->l.p = p; - for (j=0; jl.upvals[j] = cl->upvals[GETARG_B(*pc)]; - else { - lua_assert(GET_OPCODE(*pc) == OP_MOVE); - ncl->l.upvals[j] = luaF_findupval(L, base + GETARG_B(*pc)); - } - } - setclvalue(L, ra, ncl); - Protect(luaC_checkGC(L)); - continue; - } - case OP_VARARG: { - int b = GETARG_B(i) - 1; - int j; - CallInfo *ci = L->ci; - int n = cast_int(ci->base - ci->func) - cl->p->numparams - 1; - if (b == LUA_MULTRET) { - Protect(luaD_checkstack(L, n)); - ra = RA(i); /* previous call may change the stack */ - b = n; - L->top = ra + n; - } - for (j = 0; j < b; j++) { - if (j < n) { - setobjs2s(L, ra + j, ci->base - n + j); - } - else { - setnilvalue(ra + j); - } - } - continue; - } - } - } -} - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lvm.h b/desmume/src/windows/lua/lua-5.1.4/src/lvm.h deleted file mode 100644 index bfe4f5678..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lvm.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -** $Id: lvm.h,v 2.5.1.1 2007/12/27 13:02:25 roberto Exp $ -** Lua virtual machine -** See Copyright Notice in lua.h -*/ - -#ifndef lvm_h -#define lvm_h - - -#include "ldo.h" -#include "lobject.h" -#include "ltm.h" - - -#define tostring(L,o) ((ttype(o) == LUA_TSTRING) || (luaV_tostring(L, o))) - -#define tonumber(o,n) (ttype(o) == LUA_TNUMBER || \ - (((o) = luaV_tonumber(o,n)) != NULL)) - -#define equalobj(L,o1,o2) \ - (ttype(o1) == ttype(o2) && luaV_equalval(L, o1, o2)) - - -LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); -LUAI_FUNC int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2); -LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n); -LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj); -LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key, - StkId val); -LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key, - StkId val); -LUAI_FUNC void luaV_execute (lua_State *L, int nexeccalls); -LUAI_FUNC void luaV_concat (lua_State *L, int total, int last); - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lzio.c b/desmume/src/windows/lua/lua-5.1.4/src/lzio.c deleted file mode 100644 index 293edd59b..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lzio.c +++ /dev/null @@ -1,82 +0,0 @@ -/* -** $Id: lzio.c,v 1.31.1.1 2007/12/27 13:02:25 roberto Exp $ -** a generic input stream interface -** See Copyright Notice in lua.h -*/ - - -#include - -#define lzio_c -#define LUA_CORE - -#include "lua.h" - -#include "llimits.h" -#include "lmem.h" -#include "lstate.h" -#include "lzio.h" - - -int luaZ_fill (ZIO *z) { - size_t size; - lua_State *L = z->L; - const char *buff; - lua_unlock(L); - buff = z->reader(L, z->data, &size); - lua_lock(L); - if (buff == NULL || size == 0) return EOZ; - z->n = size - 1; - z->p = buff; - return char2int(*(z->p++)); -} - - -int luaZ_lookahead (ZIO *z) { - if (z->n == 0) { - if (luaZ_fill(z) == EOZ) - return EOZ; - else { - z->n++; /* luaZ_fill removed first byte; put back it */ - z->p--; - } - } - return char2int(*z->p); -} - - -void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { - z->L = L; - z->reader = reader; - z->data = data; - z->n = 0; - z->p = NULL; -} - - -/* --------------------------------------------------------------- read --- */ -size_t luaZ_read (ZIO *z, void *b, size_t n) { - while (n) { - size_t m; - if (luaZ_lookahead(z) == EOZ) - return n; /* return number of missing bytes */ - m = (n <= z->n) ? n : z->n; /* min. between n and z->n */ - memcpy(b, z->p, m); - z->n -= m; - z->p += m; - b = (char *)b + m; - n -= m; - } - return 0; -} - -/* ------------------------------------------------------------------------ */ -char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) { - if (n > buff->buffsize) { - if (n < LUA_MINBUFFER) n = LUA_MINBUFFER; - luaZ_resizebuffer(L, buff, n); - } - return buff->buffer; -} - - diff --git a/desmume/src/windows/lua/lua-5.1.4/src/lzio.h b/desmume/src/windows/lua/lua-5.1.4/src/lzio.h deleted file mode 100644 index 51d695d8c..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/lzio.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -** $Id: lzio.h,v 1.21.1.1 2007/12/27 13:02:25 roberto Exp $ -** Buffered streams -** See Copyright Notice in lua.h -*/ - - -#ifndef lzio_h -#define lzio_h - -#include "lua.h" - -#include "lmem.h" - - -#define EOZ (-1) /* end of stream */ - -typedef struct Zio ZIO; - -#define char2int(c) cast(int, cast(unsigned char, (c))) - -#define zgetc(z) (((z)->n--)>0 ? char2int(*(z)->p++) : luaZ_fill(z)) - -typedef struct Mbuffer { - char *buffer; - size_t n; - size_t buffsize; -} Mbuffer; - -#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0) - -#define luaZ_buffer(buff) ((buff)->buffer) -#define luaZ_sizebuffer(buff) ((buff)->buffsize) -#define luaZ_bufflen(buff) ((buff)->n) - -#define luaZ_resetbuffer(buff) ((buff)->n = 0) - - -#define luaZ_resizebuffer(L, buff, size) \ - (luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \ - (buff)->buffsize = size) - -#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) - - -LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n); -LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, - void *data); -LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n bytes */ -LUAI_FUNC int luaZ_lookahead (ZIO *z); - - - -/* --------- Private Part ------------------ */ - -struct Zio { - size_t n; /* bytes still unread */ - const char *p; /* current position in buffer */ - lua_Reader reader; - void* data; /* additional data */ - lua_State *L; /* Lua state (for reader) */ -}; - - -LUAI_FUNC int luaZ_fill (ZIO *z); - -#endif diff --git a/desmume/src/windows/lua/lua-5.1.4/src/print.c b/desmume/src/windows/lua/lua-5.1.4/src/print.c deleted file mode 100644 index e240cfc3c..000000000 --- a/desmume/src/windows/lua/lua-5.1.4/src/print.c +++ /dev/null @@ -1,227 +0,0 @@ -/* -** $Id: print.c,v 1.55a 2006/05/31 13:30:05 lhf Exp $ -** print bytecodes -** See Copyright Notice in lua.h -*/ - -#include -#include - -#define luac_c -#define LUA_CORE - -#include "ldebug.h" -#include "lobject.h" -#include "lopcodes.h" -#include "lundump.h" - -#define PrintFunction luaU_print - -#define Sizeof(x) ((int)sizeof(x)) -#define VOID(p) ((const void*)(p)) - -static void PrintString(const TString* ts) -{ - const char* s=getstr(ts); - size_t i,n=ts->tsv.len; - putchar('"'); - for (i=0; ik[i]; - switch (ttype(o)) - { - case LUA_TNIL: - printf("nil"); - break; - case LUA_TBOOLEAN: - printf(bvalue(o) ? "true" : "false"); - break; - case LUA_TNUMBER: - printf(LUA_NUMBER_FMT,nvalue(o)); - break; - case LUA_TSTRING: - PrintString(rawtsvalue(o)); - break; - default: /* cannot happen */ - printf("? type=%d",ttype(o)); - break; - } -} - -static void PrintCode(const Proto* f) -{ - const Instruction* code=f->code; - int pc,n=f->sizecode; - for (pc=0; pc0) printf("[%d]\t",line); else printf("[-]\t"); - printf("%-9s\t",luaP_opnames[o]); - switch (getOpMode(o)) - { - case iABC: - printf("%d",a); - if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (-1-INDEXK(b)) : b); - if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (-1-INDEXK(c)) : c); - break; - case iABx: - if (getBMode(o)==OpArgK) printf("%d %d",a,-1-bx); else printf("%d %d",a,bx); - break; - case iAsBx: - if (o==OP_JMP) printf("%d",sbx); else printf("%d %d",a,sbx); - break; - } - switch (o) - { - case OP_LOADK: - printf("\t; "); PrintConstant(f,bx); - break; - case OP_GETUPVAL: - case OP_SETUPVAL: - printf("\t; %s", (f->sizeupvalues>0) ? getstr(f->upvalues[b]) : "-"); - break; - case OP_GETGLOBAL: - case OP_SETGLOBAL: - printf("\t; %s",svalue(&f->k[bx])); - break; - case OP_GETTABLE: - case OP_SELF: - if (ISK(c)) { printf("\t; "); PrintConstant(f,INDEXK(c)); } - break; - case OP_SETTABLE: - case OP_ADD: - case OP_SUB: - case OP_MUL: - case OP_DIV: - case OP_POW: - case OP_EQ: - case OP_LT: - case OP_LE: - if (ISK(b) || ISK(c)) - { - printf("\t; "); - if (ISK(b)) PrintConstant(f,INDEXK(b)); else printf("-"); - printf(" "); - if (ISK(c)) PrintConstant(f,INDEXK(c)); else printf("-"); - } - break; - case OP_JMP: - case OP_FORLOOP: - case OP_FORPREP: - printf("\t; to %d",sbx+pc+2); - break; - case OP_CLOSURE: - printf("\t; %p",VOID(f->p[bx])); - break; - case OP_SETLIST: - if (c==0) printf("\t; %d",(int)code[++pc]); - else printf("\t; %d",c); - break; - default: - break; - } - printf("\n"); - } -} - -#define SS(x) (x==1)?"":"s" -#define S(x) x,SS(x) - -static void PrintHeader(const Proto* f) -{ - const char* s=getstr(f->source); - if (*s=='@' || *s=='=') - s++; - else if (*s==LUA_SIGNATURE[0]) - s="(bstring)"; - else - s="(string)"; - printf("\n%s <%s:%d,%d> (%d instruction%s, %d bytes at %p)\n", - (f->linedefined==0)?"main":"function",s, - f->linedefined,f->lastlinedefined, - S(f->sizecode),f->sizecode*Sizeof(Instruction),VOID(f)); - printf("%d%s param%s, %d slot%s, %d upvalue%s, ", - f->numparams,f->is_vararg?"+":"",SS(f->numparams), - S(f->maxstacksize),S(f->nups)); - printf("%d local%s, %d constant%s, %d function%s\n", - S(f->sizelocvars),S(f->sizek),S(f->sizep)); -} - -static void PrintConstants(const Proto* f) -{ - int i,n=f->sizek; - printf("constants (%d) for %p:\n",n,VOID(f)); - for (i=0; isizelocvars; - printf("locals (%d) for %p:\n",n,VOID(f)); - for (i=0; ilocvars[i].varname),f->locvars[i].startpc+1,f->locvars[i].endpc+1); - } -} - -static void PrintUpvalues(const Proto* f) -{ - int i,n=f->sizeupvalues; - printf("upvalues (%d) for %p:\n",n,VOID(f)); - if (f->upvalues==NULL) return; - for (i=0; iupvalues[i])); - } -} - -void PrintFunction(const Proto* f, int full) -{ - int i,n=f->sizep; - PrintHeader(f); - PrintCode(f); - if (full) - { - PrintConstants(f); - PrintLocals(f); - PrintUpvalues(f); - } - for (i=0; ip[i],full); -} diff --git a/desmume/src/windows/lua/vs8/lua.sln b/desmume/src/windows/lua/vs8/lua.sln deleted file mode 100644 index aeb2437f0..000000000 --- a/desmume/src/windows/lua/vs8/lua.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual Studio 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lua", "lua.vcproj", "{650C0DB9-F95F-4283-8778-2DE8FA3CCED8}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {650C0DB9-F95F-4283-8778-2DE8FA3CCED8}.Debug|Win32.ActiveCfg = Debug|Win32 - {650C0DB9-F95F-4283-8778-2DE8FA3CCED8}.Debug|Win32.Build.0 = Debug|Win32 - {650C0DB9-F95F-4283-8778-2DE8FA3CCED8}.Release|Win32.ActiveCfg = Release|Win32 - {650C0DB9-F95F-4283-8778-2DE8FA3CCED8}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/desmume/src/windows/lua/vs8/lua.vcproj b/desmume/src/windows/lua/vs8/lua.vcproj deleted file mode 100644 index 8c7d5af6b..000000000 --- a/desmume/src/windows/lua/vs8/lua.vcproj +++ /dev/null @@ -1,375 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/desmume/src/windows/luaconsole.cpp b/desmume/src/windows/luaconsole.cpp deleted file mode 100644 index 8daa2429a..000000000 --- a/desmume/src/windows/luaconsole.cpp +++ /dev/null @@ -1,710 +0,0 @@ -#include "resource.h" -#include -#include -#include -#include -#include -#include - -#include "OpenArchive.h" - -#ifdef WIN32 -#include "common.h" -#include "main.h" -#include "driver.h" -#endif -#include "..\lua-engine.h" - -#define MAX_RECENT_SCRIPTS 15 - -static char Str_Tmp [1024]; // shadow added because the global one is completely unreliable - -char Recent_Scripts[MAX_RECENT_SCRIPTS][1024]; - -struct ControlLayoutInfo -{ - int controlID; - - enum LayoutType // what to do when the containing window resizes - { - NONE, // leave the control where it was - RESIZE_END, // resize the control - MOVE_START, // move the control - }; - LayoutType horizontalLayout; - LayoutType verticalLayout; -}; -struct ControlLayoutState -{ - int x,y,width,height; - bool valid; - ControlLayoutState() : valid(false) {} -}; - -static ControlLayoutInfo controlLayoutInfos [] = { - {IDC_LUACONSOLE, ControlLayoutInfo::RESIZE_END, ControlLayoutInfo::RESIZE_END}, - {IDC_EDIT_LUAPATH, ControlLayoutInfo::RESIZE_END, ControlLayoutInfo::NONE}, - {IDC_BUTTON_LUARUN, ControlLayoutInfo::MOVE_START, ControlLayoutInfo::NONE}, - {IDC_BUTTON_LUASTOP, ControlLayoutInfo::MOVE_START, ControlLayoutInfo::NONE}, -}; -static const int numControlLayoutInfos = sizeof(controlLayoutInfos)/sizeof(*controlLayoutInfos); - - -extern std::vector LuaScriptHWnds; -struct LuaPerWindowInfo { - std::string filename; - HANDLE fileWatcherThread; - bool started; - bool closeOnStop; - bool subservient; - int width; int height; - ControlLayoutState layoutState [numControlLayoutInfos]; - LuaPerWindowInfo() : fileWatcherThread(NULL), started(false), closeOnStop(false), subservient(false), width(405), height(244) {} -}; -std::map LuaWindowInfo; -static char Lua_Dir[1024]=""; - -int WINAPI FileSysWatcher (LPVOID arg) -{ - HWND hDlg = (HWND)arg; - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - - while(true) - { - char filename [1024], directory [1024]; - - strncpy(filename, info.filename.c_str(), 1024); - filename[1023] = 0; - strcpy(directory, filename); - char* slash = strrchr(directory, '/'); - slash = std::max(slash, strrchr(directory, '\\')); - if(slash) - *slash = 0; - - char* bar = strchr(filename, '|'); - if(bar) *bar = '\0'; - - WIN32_FILE_ATTRIBUTE_DATA origData; - GetFileAttributesEx (filename, GetFileExInfoStandard, (LPVOID)&origData); - - HANDLE hNotify = FindFirstChangeNotification(directory, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE); - - if(hNotify) - { - DWORD dwWaitResult = WaitForSingleObject(hNotify, 500); - - if(dwWaitResult != STATUS_TIMEOUT) - { - if(dwWaitResult == WAIT_ABANDONED) - return dwWaitResult; - - WIN32_FILE_ATTRIBUTE_DATA data; - GetFileAttributesEx (filename, GetFileExInfoStandard, (LPVOID)&data); - - // at this point it could be any file in the directory that changed - // so check to make sure it was the file we care about - if(memcmp(&origData.ftLastWriteTime, &data.ftLastWriteTime, sizeof(FILETIME))) - { - RequestAbortLuaScript((int)hDlg, "terminated to reload the script"); - PostMessage(hDlg, WM_COMMAND, IDC_BUTTON_LUARUN, 0); - } - } - - //FindNextChangeNotification(hNotify); // let's not try to reuse it... - FindCloseChangeNotification(hNotify); // but let's at least make sure to release it! - } - else - { - Sleep(500); - } - } - - return 0; -} - -void RegisterWatcherThread (HWND hDlg) -{ - HANDLE thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) FileSysWatcher, (LPVOID) hDlg, CREATE_SUSPENDED, NULL); - SetThreadPriority(thread, THREAD_PRIORITY_LOWEST); - - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - info.fileWatcherThread = thread; - - ResumeThread(thread); -} -void KillWatcherThread (HWND hDlg) -{ - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - TerminateThread(info.fileWatcherThread, 0); - info.fileWatcherThread = NULL; -} - - -// some extensions that might commonly be near lua files that almost certainly aren't lua files. -static const char* s_nonLuaExtensions [] = {"txt", "nfo", "htm", "html", "jpg", "jpeg", "png", "bmp", "gif", "mp3", "wav", "lnk", "exe", "bat", "gmv", "gm2", "luasav", "sav", "srm", "brm", "cfg", "wch", "gs*", "bin","smd","gen","32x","cue","iso","raw"}; - - -void Update_Recent_Script(const char* Path, bool dontPutAtTop) -{ - char LogicalName[1024], PhysicalName[1024]; - bool exists = ObtainFile(Path, LogicalName, PhysicalName, "luacheck", s_nonLuaExtensions, sizeof(s_nonLuaExtensions)/sizeof(*s_nonLuaExtensions)); - ReleaseTempFileCategory("luacheck"); // delete the temporary (physical) file if any - - if(!exists) - return; - - int i; - - for(i = 0; i < MAX_RECENT_SCRIPTS; i++) - { - if (!(strcmp(Recent_Scripts[i], Path))) - { - // move recent item to the top of the list - if(i == 0 || dontPutAtTop) - return; - char temp [1024]; - strcpy(temp, Recent_Scripts[i]); - int j; - for(j = i; j > 0; j--) - strcpy(Recent_Scripts[j], Recent_Scripts[j-1]); - strcpy(Recent_Scripts[0], temp); -// MustUpdateMenu = 1; - return; - } - } - - if(!dontPutAtTop) - { - // add to start of recent list - for(i = MAX_RECENT_SCRIPTS-1; i > 0; i--) - strcpy(Recent_Scripts[i], Recent_Scripts[i - 1]); - - strcpy(Recent_Scripts[0], Path); - } - else - { - // add to end of recent list - for(i = 0; i < MAX_RECENT_SCRIPTS; i++) - { - if(!*Recent_Scripts[i]) - { - strcpy(Recent_Scripts[i], Path); - break; - } - } - } - -// MustUpdateMenu = 1; -} - -HWND IsScriptFileOpen(const char* Path) -{ - for(std::map::iterator iter = LuaWindowInfo.begin(); iter != LuaWindowInfo.end(); ++iter) - { - LuaPerWindowInfo& info = iter->second; - const char* filename = info.filename.c_str(); - const char* pathPtr = Path; - - // case-insensitive slash-direction-insensitive compare - bool same = true; - while(*filename || *pathPtr) - { - if((*filename == '/' || *filename == '\\') && (*pathPtr == '/' || *pathPtr == '\\')) - { - do {filename++;} while(*filename == '/' || *filename == '\\'); - do {pathPtr++;} while(*pathPtr == '/' || *pathPtr == '\\'); - } - else if(tolower(*filename) != tolower(*pathPtr)) - { - same = false; - break; - } - else - { - filename++; - pathPtr++; - } - } - - if(same) - return iter->first; - } - return NULL; -} - - -void PrintToWindowConsole(int hDlgAsInt, const char* str) -{ - HWND hDlg = (HWND)hDlgAsInt; - HWND hConsole = GetDlgItem(hDlg, IDC_LUACONSOLE); - - int length = GetWindowTextLength(hConsole); - if(length >= 250000) - { - // discard first half of text if it's getting too long - SendMessage(hConsole, EM_SETSEL, 0, length/2); - SendMessage(hConsole, EM_REPLACESEL, false, (LPARAM)""); - length = GetWindowTextLength(hConsole); - } - SendMessage(hConsole, EM_SETSEL, length, length); - - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - - { - SendMessage(hConsole, EM_REPLACESEL, false, (LPARAM)str); - } -} - -extern int Show_Genesis_Screen(HWND hWnd); -void OnStart(int hDlgAsInt) -{ - HWND hDlg = (HWND)hDlgAsInt; - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - info.started = true; - EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_LUABROWSE), false); // disable browse while running because it misbehaves if clicked in a frameadvance loop - EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_LUASTOP), true); - SetWindowText(GetDlgItem(hDlg, IDC_BUTTON_LUARUN), "Restart"); - SetWindowText(GetDlgItem(hDlg, IDC_LUACONSOLE), ""); // clear the console -// Show_Genesis_Screen(HWnd); // otherwise we might never show the first thing the script draws -} - -void OnStop(int hDlgAsInt, bool statusOK) -{ - HWND hDlg = (HWND)hDlgAsInt; - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - - HWND prevWindow = GetActiveWindow(); - SetActiveWindow(hDlg); // bring to front among other script/secondary windows, since a stopped script will have some message for the user that would be easier to miss otherwise - if(prevWindow == MainWindow->getHWnd()) SetActiveWindow(prevWindow); - - info.started = false; - EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_LUABROWSE), true); - EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_LUASTOP), false); - SetWindowText(GetDlgItem(hDlg, IDC_BUTTON_LUARUN), "Run"); -// if(statusOK) -// Show_Genesis_Screen(MainWindow->getHWnd()); // otherwise we might never show the last thing the script draws - if(info.closeOnStop) - PostMessage(hDlg, WM_CLOSE, 0, 0); -} - -const char* MakeScriptPathAbsolute(const char* filename, const char* extraDirToCheck); - -void UpdateFileEntered(HWND hDlg) -{ - char local_str_tmp [1024]; - SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,WM_GETTEXT,(WPARAM)512,(LPARAM)local_str_tmp); - - // if it exists, make sure we're using an absolute path to it - const char* filename = local_str_tmp; - FILE* file = fopen(filename, "rb"); - if(file) - { - fclose(file); - filename = MakeScriptPathAbsolute(local_str_tmp, NULL); - if(filename != local_str_tmp && stricmp(filename, local_str_tmp)) - { - SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,WM_SETTEXT,(WPARAM)512,(LPARAM)filename); - SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,EM_SETSEL,0,-1); - SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,EM_SETSEL,-1,-1); - return; - } - } - - // use ObtainFile to support opening files within archives - char LogicalName[1024], PhysicalName[1024]; - bool exists = ObtainFile(filename, LogicalName, PhysicalName, "luacheck", s_nonLuaExtensions, sizeof(s_nonLuaExtensions)/sizeof(*s_nonLuaExtensions)); - bool readonly = exists ? ((GetFileAttributes(PhysicalName) & FILE_ATTRIBUTE_READONLY) != 0) : (strchr(LogicalName, '|') != NULL || strchr(filename, '|') != NULL); - ReleaseTempFileCategory("luacheck"); // delete the temporary (physical) file if any - - if(exists) - { - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - info.filename = LogicalName; - - char* slash = strrchr(LogicalName, '/'); - slash = std::max(slash, strrchr(LogicalName, '\\')); - if(slash) - slash++; - else - slash = LogicalName; - SetWindowText(hDlg, slash); -// Build_Main_Menu(); - - PostMessage(hDlg, WM_COMMAND, IDC_BUTTON_LUARUN, 0); - } - - const char* ext = strrchr(LogicalName, '.'); - bool isLuaFile = ext && !_stricmp(ext, ".lua"); - if(exists) - { - SetWindowText(GetDlgItem(hDlg, IDC_BUTTON_LUAEDIT), isLuaFile ? (readonly ? "View" : "Edit") : "Open"); - EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_LUAEDIT), true); - } - else - { - SetWindowText(GetDlgItem(hDlg, IDC_BUTTON_LUAEDIT), "Create"); - EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_LUAEDIT), isLuaFile && !readonly); - } -} - -//extern "C" int Clear_Sound_Buffer(void); - -static int Change_File_L(char *Dest, char *Dir, char *Titre, char *Filter, char *Ext, HWND hwnd) -{ - OPENFILENAME ofn; - -// SetCurrentDirectory(Desmume_Path); - - if (!strcmp(Dest, "")) - { - strcpy(Dest, "default."); - strcat(Dest, Ext); - } - - memset(&ofn, 0, sizeof(OPENFILENAME)); - - ofn.lStructSize = sizeof(OPENFILENAME); - ofn.hwndOwner = hwnd; - ofn.hInstance = hAppInst; - ofn.lpstrFile = Dest; - ofn.nMaxFile = 2047; - ofn.lpstrFilter = Filter; - ofn.nFilterIndex = 1; - ofn.lpstrInitialDir = Dir; - ofn.lpstrTitle = Titre; - ofn.lpstrDefExt = Ext; - ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; - - if (GetOpenFileName(&ofn)) return 1; - - return 0; -} - -LRESULT CALLBACK LuaScriptProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - RECT r; - RECT r2; - int dx1, dy1, dx2, dy2; - - switch(uMsg) - { - case WM_INITDIALOG: { - if(std::find(LuaScriptHWnds.begin(), LuaScriptHWnds.end(), hDlg) == LuaScriptHWnds.end()) - { - LuaScriptHWnds.push_back(hDlg); -// Build_Main_Menu(); - } -// if (Full_Screen) -// { -// while (ShowCursor(false) >= 0); -// while (ShowCursor(true) < 0); -// } - -// HANDLE hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_LUA)); -// SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon); - - // remove the 30000 character limit from the console control - SendMessage(GetDlgItem(hDlg, IDC_LUACONSOLE),EM_LIMITTEXT,0,0); - - GetWindowRect(MainWindow->getHWnd(), &r); - dx1 = (r.right - r.left) / 2; - dy1 = (r.bottom - r.top) / 2; - - GetWindowRect(hDlg, &r2); - dx2 = (r2.right - r2.left) / 2; - dy2 = (r2.bottom - r2.top) / 2; - - int windowIndex = std::find(LuaScriptHWnds.begin(), LuaScriptHWnds.end(), hDlg) - LuaScriptHWnds.begin(); - int staggerOffset = windowIndex * 24; - r.left += staggerOffset; - r.right += staggerOffset; - r.top += staggerOffset; - r.bottom += staggerOffset; - - // push it away from the main window if we can - const int width = (r.right-r.left); - const int width2 = (r2.right-r2.left); - if(r.left+width2 + width < GetSystemMetrics(SM_CXSCREEN)) - { - r.right += width; - r.left += width; - } - else if((int)r.left - (int)width2 > 0) - { - r.right -= width2; - r.left -= width2; - } - - SetWindowPos(hDlg, NULL, r.left, r.top, NULL, NULL, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW); - - LuaPerWindowInfo info; - { - RECT r3; - GetClientRect(hDlg, &r3); - info.width = r3.right - r3.left; - info.height = r3.bottom - r3.top; - } - LuaWindowInfo[hDlg] = info; - RegisterWatcherThread(hDlg); - - OpenLuaContext((int)hDlg, PrintToWindowConsole, OnStart, OnStop); - - DragAcceptFiles(hDlg, TRUE); - - return true; - } break; - - case WM_MENUSELECT: - case WM_ENTERSIZEMOVE: -// Clear_Sound_Buffer(); - break; - - case WM_SIZING: - { - // enforce a minimum window size - - LPRECT r = (LPRECT) lParam; - int minimumWidth = 333; - int minimumHeight = 117; - if(r->right - r->left < minimumWidth) - if(wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT) - r->left = r->right - minimumWidth; - else - r->right = r->left + minimumWidth; - if(r->bottom - r->top < minimumHeight) - if(wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT) - r->top = r->bottom - minimumHeight; - else - r->bottom = r->top + minimumHeight; - } - return TRUE; - - case WM_SIZE: - { - // resize or move controls in the window as necessary when the window is resized - - LuaPerWindowInfo& windowInfo = LuaWindowInfo[hDlg]; - int prevDlgWidth = windowInfo.width; - int prevDlgHeight = windowInfo.height; - - int dlgWidth = LOWORD(lParam); - int dlgHeight = HIWORD(lParam); - - int deltaWidth = dlgWidth - prevDlgWidth; - int deltaHeight = dlgHeight - prevDlgHeight; - - for(int i = 0; i < numControlLayoutInfos; i++) - { - ControlLayoutInfo layoutInfo = controlLayoutInfos[i]; - ControlLayoutState& layoutState = windowInfo.layoutState[i]; - - HWND hCtrl = GetDlgItem(hDlg,layoutInfo.controlID); - - int x,y,width,height; - if(layoutState.valid) - { - x = layoutState.x; - y = layoutState.y; - width = layoutState.width; - height = layoutState.height; - } - else - { - RECT r; - GetWindowRect(hCtrl, &r); - POINT p = {r.left, r.top}; - ScreenToClient(hDlg, &p); - x = p.x; - y = p.y; - width = r.right - r.left; - height = r.bottom - r.top; - } - - switch(layoutInfo.horizontalLayout) - { - case ControlLayoutInfo::RESIZE_END: width += deltaWidth; break; - case ControlLayoutInfo::MOVE_START: x += deltaWidth; break; - default: break; - } - switch(layoutInfo.verticalLayout) - { - case ControlLayoutInfo::RESIZE_END: height += deltaHeight; break; - case ControlLayoutInfo::MOVE_START: y += deltaHeight; break; - default: break; - } - - SetWindowPos(hCtrl, 0, x,y, width,height, 0); - - layoutState.x = x; - layoutState.y = y; - layoutState.width = width; - layoutState.height = height; - layoutState.valid = true; - } - - windowInfo.width = dlgWidth; - windowInfo.height = dlgHeight; - - RedrawWindow(hDlg, NULL, NULL, RDW_INVALIDATE); - } - break; - - case WM_COMMAND: - { - switch(LOWORD(wParam)) - { - case IDC_BUTTON_LUABROWSE: - { - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - char Str_Tmp [1024]; // shadow added because the global one is unreliable - strcpy(Str_Tmp,info.filename.c_str()); - SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,WM_GETTEXT,(WPARAM)512,(LPARAM)Str_Tmp); - char* bar = strchr(Str_Tmp, '|'); - if(bar) *bar = '\0'; -// DialogsOpen++; -// Clear_Sound_Buffer(); - if(Change_File_L(Str_Tmp, Lua_Dir, "Load Lua Script", "Lua Script\0*.lua*\0All Files\0*.*\0\0", "lua", hDlg)) - { - SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,WM_SETTEXT,0,(LPARAM)Str_Tmp); - } -// DialogsOpen--; - - } break; - case IDC_BUTTON_LUAEDIT: - { - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - char Str_Tmp [1024]; // shadow added because the global one is unreliable - strcpy(Str_Tmp,info.filename.c_str()); - SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,WM_GETTEXT,(WPARAM)512,(LPARAM)Str_Tmp); - char LogicalName[1024], PhysicalName[1024]; - bool exists = ObtainFile(Str_Tmp, LogicalName, PhysicalName, "luaview", s_nonLuaExtensions, sizeof(s_nonLuaExtensions)/sizeof(*s_nonLuaExtensions)); - bool created = false; - if(!exists) - { - FILE* file = fopen(Str_Tmp, "r"); - if(!file) - { - file = fopen(Str_Tmp, "w"); - if(file) - { - created = true; - exists = true; - strcpy(PhysicalName, Str_Tmp); - } - } - if(file) - fclose(file); - } - if(exists) - { - // tell the OS to open the file with its associated editor, - // without blocking on it or leaving a command window open. - ShellExecute(NULL, "open", PhysicalName, NULL, NULL, SW_SHOWNORMAL); - } - if(created) - { - UpdateFileEntered(hDlg); - } - } break; - case IDC_EDIT_LUAPATH: - { - switch(HIWORD(wParam)) - { - case EN_CHANGE: - { - UpdateFileEntered(hDlg); - } break; - } - } break; - case IDC_BUTTON_LUARUN: - { - HWND focus = GetFocus(); - HWND textbox = GetDlgItem(hDlg, IDC_EDIT_LUAPATH); - if(focus != textbox) - SetActiveWindow(MainWindow->getHWnd()); - - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - strcpy(Str_Tmp,info.filename.c_str()); - char LogicalName[1024], PhysicalName[1024]; - bool exists = ObtainFile(Str_Tmp, LogicalName, PhysicalName, "luarun", s_nonLuaExtensions, sizeof(s_nonLuaExtensions)/sizeof(*s_nonLuaExtensions)); - Update_Recent_Script(LogicalName, info.subservient); - RunLuaScriptFile((int)hDlg, PhysicalName); - } break; - case IDC_BUTTON_LUASTOP: - { - PrintToWindowConsole((int)hDlg, "user clicked stop button\r\n"); - SetActiveWindow(MainWindow->getHWnd()); - StopLuaScript((int)hDlg); - } break; - case IDC_NOTIFY_SUBSERVIENT: - { - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - info.subservient = lParam ? true : false; - } break; - //case IDOK: - case IDCANCEL: - { LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - if(info.filename.empty()) - { -// if (Full_Screen) -// { -// while (ShowCursor(true) < 0); -// while (ShowCursor(false) >= 0); -// } -// DialogsOpen--; - DragAcceptFiles(hDlg, FALSE); - KillWatcherThread(hDlg); - LuaScriptHWnds.erase(remove(LuaScriptHWnds.begin(), LuaScriptHWnds.end(), hDlg), LuaScriptHWnds.end()); - LuaWindowInfo.erase(hDlg); - CloseLuaContext((int)hDlg); -// Build_Main_Menu(); - EndDialog(hDlg, true); - } - } return true; - } - - return false; - } break; - - case WM_CLOSE: - { - LuaPerWindowInfo& info = LuaWindowInfo[hDlg]; - - PrintToWindowConsole((int)hDlg, "user closed script window\r\n"); - StopLuaScript((int)hDlg); - if(info.started) - { - // not stopped yet, wait to close until we are, otherwise we'll crash - info.closeOnStop = true; - return false; - } - -// if (Full_Screen) -// { -// while (ShowCursor(true) < 0); -// while (ShowCursor(false) >= 0); -// } -// DialogsOpen--; - DragAcceptFiles(hDlg, FALSE); - KillWatcherThread(hDlg); - LuaScriptHWnds.erase(remove(LuaScriptHWnds.begin(), LuaScriptHWnds.end(), hDlg), LuaScriptHWnds.end()); - LuaWindowInfo.erase(hDlg); - CloseLuaContext((int)hDlg); -// Build_Main_Menu(); - EndDialog(hDlg, true); - } return true; - - case WM_DROPFILES: - { - HDROP hDrop = (HDROP)wParam; - DragQueryFile(hDrop, 0, Str_Tmp, 1024); - DragFinish(hDrop); - SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,WM_SETTEXT,0,(LPARAM)Str_Tmp ); - UpdateFileEntered(hDlg); - } return true; - - } - - return false; -} - diff --git a/desmume/src/windows/pathsettings.cpp b/desmume/src/windows/pathsettings.cpp deleted file mode 100644 index eda860c05..000000000 --- a/desmume/src/windows/pathsettings.cpp +++ /dev/null @@ -1,613 +0,0 @@ -/* - Copyright (C) 2007 Hicoder - - This file is part of DeSmuME - - DeSmuME is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - DeSmuME is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with DeSmuME; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/* notes: will not save paths for current session if IDCANCEL is sent it -will only change paths for that session - -the only way paths will be saved is if IDOK is sent - -the default paths are saved on first load -*/ - -#include "../common.h" -#include -#include -#include -#include -#include -#include "main.h" -#include "NDSSystem.h" -#include "pathSettings.h" -#include "../debug.h" -#include "common.h" - -/*macros to forward messages -the dialog procedure was getting long and confusing for me -*/ -#define HANDLE_DLGMSG(hwnd, message, fn) \ - case (message): return (SetDlgMsgResult(hDlg, uMsg, \ - HANDLE_##message( (hwnd), (wParam), (lParam), (fn) ) ) ) - - -/*variable declaration*/ - -char pathToRoms[MAX_PATH]; -char pathToBattery[MAX_PATH]; -char pathToStates[MAX_PATH]; -char pathToScreenshots[MAX_PATH]; -char pathToAviFiles[MAX_PATH]; -char pathToCheats[MAX_PATH]; -char pathToSounds[MAX_PATH]; -char pathToFirmware[MAX_PATH]; -char pathToModule[MAX_PATH]; -char pathToLua[MAX_PATH]; -char screenshotFormat[MAX_FORMAT]; - -char *currentSelection = 0; -char *currentKey = 0; - -BOOL romsLastVisit = FALSE; -BOOL needsSaving = FALSE; - -ImageFormat defaultFormat = PNG; - -/* end variable declaration*/ - -/*private functions*/ - -void ReadKey(char *pathToRead, const char *key) -{ - ZeroMemory(pathToRead, sizeof(pathToRead)); - GetPrivateProfileString(SECTION, key, key, pathToRead, MAX_PATH, IniName); - if(strcmp(pathToRead, key) == 0) - //since the variables are all intialized in this file they all use MAX_PATH - GetDefaultPath(pathToRead, key, MAX_PATH); -} - -int InitialFolder(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData) -{ - if(uMsg == BFFM_INITIALIZED) - { - SendMessage(hwnd, BFFM_SETSELECTION, (WPARAM)TRUE, lpData); - } - return 0; -} - -BOOL BrowseForPath(char *pathToBrowse) -{ - LPMALLOC shMalloc; - BOOL changed = false; - LPITEMIDLIST idList; - BROWSEINFO bi; - - //stupid shell - if(SHGetMalloc( &shMalloc) != S_OK) - return FALSE; - - ZeroMemory(&idList, sizeof(idList)); - ZeroMemory(&bi, sizeof(bi)); - - char tmp[MAX_PATH]; - strncpy(tmp, pathToBrowse, MAX_PATH); - - bi.hwndOwner = MainWindow->getHWnd(); - bi.lpszTitle = "Choose a Folder"; - bi.ulFlags = BIF_NONEWFOLDERBUTTON; - - /*wanted to add a callback function for the folder initialization but it crashes everytime i do - bi.lpfn = (BFFCALLBACK)InitialFolder; - bi.lParam = (LPARAM)pathToBrowse; - */ - - if( (idList = SHBrowseForFolder(&bi)) ) - { - changed = true; - SHGetPathFromIDList(idList, pathToBrowse); -// shMalloc->Free(&idList); - } - - return changed; -} - -void LoadModulePath() -{ - //stolen from common.cpp GetINIPath - char *p; - ZeroMemory(pathToModule, sizeof(pathToModule)); - GetModuleFileName(NULL, pathToModule, sizeof(pathToModule)); - p = pathToModule + lstrlen(pathToModule); - while (p >= pathToModule && *p != '\\') p--; - if (++p >= pathToModule) *p = 0; -} - -void SwitchPath(Action action, KnownPath path, char * buffer, int maxCount) -{ - char *pathToCopy = 0; - switch(path) - { - case ROMS: - pathToCopy = pathToRoms; - break; - case BATTERY: - pathToCopy = pathToBattery; - break; - case STATES: - pathToCopy = pathToStates; - break; - case SCREENSHOTS: - pathToCopy = pathToScreenshots; - break; - case AVI_FILES: - pathToCopy = pathToAviFiles; - break; - case CHEATS: - pathToCopy = pathToCheats; - break; - case SOUNDS: - pathToCopy = pathToSounds; - break; - case FIRMWARE: - pathToCopy = pathToFirmware; - break; - case MODULE: - pathToCopy = pathToModule; - break; - } - - if(action == GET) - { - strncpy(buffer, pathToCopy, maxCount); - strcat(buffer, "\\"); - } - else if(action == SET) - { - int len = strlen(buffer)-1; - if(buffer[len] == '\\') - buffer[len] = '\0'; - - strncpy(pathToCopy, buffer, MAX_PATH); - } -} - -/* end private functions */ - -/* public functions */ - -//returns "filename" -void GetFilename(char *buffer, int maxCount) -{ - strcpy(buffer,GetRomNameWithoutExtension().c_str()); -} - -void GetFullPathNoExt(KnownPath path, char *buffer, int maxCount) -{ - GetPathFor(path, buffer, maxCount); - char filename[MAX_PATH]; - ZeroMemory(filename, sizeof(filename)); - GetFilename(filename, MAX_PATH); - strcat(buffer, filename); -} - -void GetPathFor(KnownPath path, char *buffer, int maxCount) -{ - SwitchPath(GET, path, buffer, maxCount); -} - -void SetPathFor(KnownPath path, char *buffer) -{ - SwitchPath(SET, path, buffer, 0); -} - -void GetDefaultPath(char *pathToDefault, const char *key, int maxCount) -{ - strncpy(pathToDefault, pathToModule, maxCount); -// strcat(pathToDefault, key); - -// if(GetFileAttributes(pathToDefault) == INVALID_FILE_ATTRIBUTES) -// CreateDirectory(pathToDefault, NULL); -} - -void WritePathSettings() -{ - WritePrivateProfileString(SECTION, ROMKEY, pathToRoms, IniName); - WritePrivateProfileString(SECTION, BATTERYKEY, pathToBattery, IniName); - WritePrivateProfileString(SECTION, STATEKEY, pathToStates, IniName); - WritePrivateProfileString(SECTION, SCREENSHOTKEY, pathToScreenshots, IniName); - WritePrivateProfileString(SECTION, AVIKEY, pathToAviFiles, IniName); - WritePrivateProfileString(SECTION, CHEATKEY, pathToCheats, IniName); - WritePrivateProfileString(SECTION, SOUNDKEY, pathToSounds, IniName); - WritePrivateProfileString(SECTION, FIRMWAREKEY, pathToFirmware, IniName); - WritePrivateProfileString(SECTION, LUAKEY, pathToLua, IniName); - - WritePrivateProfileString(SECTION, FORMATKEY, screenshotFormat, IniName); - - WritePrivateProfileInt(SECTION, LASTVISITKEY, romsLastVisit, IniName); - WritePrivateProfileInt(SECTION, DEFAULTFORMATKEY, defaultFormat, IniName); - WritePrivateProfileInt(SECTION, NEEDSSAVINGKEY, needsSaving, IniName); -} - -void ReadPathSettings() -{ - if( ( strcmp(pathToModule, "") == 0) || !pathToModule) - LoadModulePath(); - - ReadKey(pathToRoms, ROMKEY); - ReadKey(pathToBattery, BATTERYKEY); - ReadKey(pathToStates, STATEKEY); - ReadKey(pathToScreenshots, SCREENSHOTKEY); - ReadKey(pathToAviFiles, AVIKEY); - ReadKey(pathToCheats, CHEATKEY); - ReadKey(pathToSounds, SOUNDKEY); - ReadKey(pathToFirmware, FIRMWAREKEY); - ReadKey(pathToLua, LUAKEY); - - GetPrivateProfileString(SECTION, FORMATKEY, "%f_%s_%r", screenshotFormat, MAX_FORMAT, IniName); - - romsLastVisit = GetPrivateProfileInt(SECTION, LASTVISITKEY, TRUE, IniName); - defaultFormat = (ImageFormat)GetPrivateProfileInt(SECTION, DEFAULTFORMATKEY, PNG, IniName); - - needsSaving = GetPrivateProfileInt(SECTION, NEEDSSAVINGKEY, TRUE, IniName); - if(needsSaving) - { - needsSaving = FALSE; - WritePathSettings(); - } -} - -ImageFormat GetImageFormatType() -{ - return defaultFormat; -} - -void FormatName(char *output, int maxCount) -{ - char file[MAX_PATH]; - ZeroMemory(file, sizeof(file)); - time_t now = time(NULL); - tm *time_struct = localtime(&now); - srand(now); - - for(int i = 0; i < MAX_FORMAT;i++) - { - char *c = &screenshotFormat[i]; - char tmp[MAX_PATH]; - ZeroMemory(tmp, sizeof(tmp)); - - if(*c == '%') - { - c = &screenshotFormat[++i]; - switch(*c) - { - case 'f': - GetFilename(tmp, MAX_PATH); - break; - case 'D': - strftime(tmp, MAX_PATH, "%d", time_struct); - break; - case 'M': - strftime(tmp, MAX_PATH, "%m", time_struct); - break; - case 'Y': - strftime(tmp, MAX_PATH, "%Y", time_struct); - break; - case 'h': - strftime(tmp, MAX_PATH, "%H", time_struct); - break; - case 'm': - strftime(tmp, MAX_PATH, "%M", time_struct); - break; - case 's': - strftime(tmp, MAX_PATH, "%S", time_struct); - break; - case 'r': - sprintf(tmp, "%d", rand() % RAND_MAX); - break; - } - } - else - { - int j; - for(j=i;j 256) + gxFIFO.tail = 256; -#ifdef USE_GEOMETRY_FIFO_EMULATION - gxstat |= 0x08000000; // set busy flag -#endif - - gxstat |= (gxFIFO.tail << 16); - + // TODO: irq handle if (gxFIFO.tail < 128) gxstat |= 0x02000000; + gxstat |= (gxFIFO.tail << 16); -#ifndef USE_GEOMETRY_FIFO_EMULATION +#ifdef USE_GEOMETRY_FIFO_EMULATION + gxstat |= 0x08000000; // busy +#else gxstat |= 0x02000000; // this is hack (must be removed later) #endif @@ -179,19 +179,14 @@ void GFX_FIFOsend(u8 cmd, u32 param) BOOL GFX_FIFOrecv(u8 *cmd, u32 *param) { u32 gxstat = T1ReadLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600); - if (gxstat & 0xC0000000) - { - setIF(0, (1<<21)); - } gxstat &= 0xF000FFFF; - if (gxFIFO.tail == 0) // empty + if (!gxFIFO.tail) // empty { //gxstat |= (0x01FF << 16); gxstat |= 0x06000000; T1WriteLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600, gxstat); return FALSE; } - *cmd = gxFIFO.cmd[0]; *param = gxFIFO.param[0]; gxFIFO.tail--; @@ -201,11 +196,16 @@ BOOL GFX_FIFOrecv(u8 *cmd, u32 *param) gxFIFO.param[i] = gxFIFO.param[i+1]; } -#ifdef USE_GEOMETRY_FIFO_EMULATION - gxstat |= 0x08000000; // set busy flag -#endif - - gxstat |= (gxFIFO.tail << 16); + if (gxFIFO.tail) // not empty + { + gxstat |= (gxFIFO.tail << 16); + gxstat |= 0x08000000; + } + else + { + gxstat |= 0x04000000; + return FALSE; + } if (gxFIFO.tail < 128) gxstat |= 0x02000000; @@ -218,9 +218,10 @@ BOOL GFX_FIFOrecv(u8 *cmd, u32 *param) void GFX_FIFOcnt(u32 val) { u32 gxstat = T1ReadLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600); - //INFO("GFX FIFO: write context 0x%08X (prev 0x%08X) tail %i\n", val, gxstat, gxFIFO.tail); + //INFO("GFX FIFO: write context 0x%08X (prev 0x%08X)\n", val, gxstat); if (val & (1<<29)) // clear? (homebrew) { + // need to flush before??? GFX_FIFOclear(); return; } diff --git a/desmume/src/FIFO.h b/src/FIFO.h similarity index 96% rename from desmume/src/FIFO.h rename to src/FIFO.h index d98db4df9..21a281398 100644 --- a/desmume/src/FIFO.h +++ b/src/FIFO.h @@ -26,7 +26,7 @@ #ifndef FIFO_H #define FIFO_H -//#define USE_GEOMETRY_FIFO_EMULATION //enables new experimental gxFIFO +//#define USE_GEOMETRY_FIFO_EMULATION #include "types.h" diff --git a/desmume/src/GPU.cpp b/src/GPU.cpp similarity index 89% rename from desmume/src/GPU.cpp rename to src/GPU.cpp index ac7b77713..f4092b08f 100644 --- a/desmume/src/GPU.cpp +++ b/src/GPU.cpp @@ -22,6 +22,24 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ +// CONTENTS +// INITIALIZATION +// ENABLING / DISABLING LAYERS +// PARAMETERS OF BACKGROUNDS +// PARAMETERS OF ROTOSCALE +// PARAMETERS OF EFFECTS +// PARAMETERS OF WINDOWS +// ROUTINES FOR INSIDE / OUTSIDE WINDOW CHECKS +// PIXEL RENDERING +// BACKGROUND RENDERING -TEXT- +// BACKGROUND RENDERING -ROTOSCALE- +// BACKGROUND RENDERING -HELPER FUNCTIONS- +// SPRITE RENDERING -HELPER FUNCTIONS- +// SPRITE RENDERING +// SCREEN FUNCTIONS +// GRAPHICS CORE +// GPU_ligne + #include #include #include @@ -71,7 +89,7 @@ const size sprSizeTab[4][4] = -const BGType GPU_mode2type[8][4] = +static const BGType mode2type[8][4] = { {BGType_Text, BGType_Text, BGType_Text, BGType_Text}, {BGType_Text, BGType_Text, BGType_Text, BGType_Affine}, @@ -494,27 +512,25 @@ FORCEINLINE void GPU::setFinal3DColorSpecialDecreaseWnd(int dstX, int srcX) } -enum OBJFunc -{ - None, Blend, Increase, Decrease -}; -template -static void _master_setFinalOBJColor(GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x); - +static void setFinalOBJColorSpecialNone (GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x); +static void setFinalOBJColorSpecialBlend (GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x); +static void setFinalOBJColorSpecialIncrease (GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x); +static void setFinalOBJColorSpecialDecrease (GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x); static void setFinalOBJColorSpecialNoneWnd (GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x); static void setFinalOBJColorSpecialBlendWnd (GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x); static void setFinalOBJColorSpecialIncreaseWnd (GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x); static void setFinalOBJColorSpecialDecreaseWnd (GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x); const GPU::FinalOBJColFunct pixelBlittersOBJ[8] = { - _master_setFinalOBJColor, - _master_setFinalOBJColor, - _master_setFinalOBJColor, - _master_setFinalOBJColor, - _master_setFinalOBJColor, - _master_setFinalOBJColor, - _master_setFinalOBJColor, - _master_setFinalOBJColor }; + setFinalOBJColorSpecialNone, + setFinalOBJColorSpecialBlend, + setFinalOBJColorSpecialIncrease, + setFinalOBJColorSpecialDecrease, + setFinalOBJColorSpecialNoneWnd, + setFinalOBJColorSpecialBlendWnd, + setFinalOBJColorSpecialIncreaseWnd, + setFinalOBJColorSpecialDecreaseWnd,}; + /*****************************************************************************/ // INITIALIZATION @@ -551,14 +567,12 @@ static void GPU_InitFadeColors() cur.bits.red = (cur.bits.red + ((31 - cur.bits.red) * i / 16)); cur.bits.green = (cur.bits.green + ((31 - cur.bits.green) * i / 16)); cur.bits.blue = (cur.bits.blue + ((31 - cur.bits.blue) * i / 16)); - cur.bits.alpha = 0; fadeInColors[i][j & 0x7FFF] = cur.val; cur.val = j; cur.bits.red = (cur.bits.red - (cur.bits.red * i / 16)); cur.bits.green = (cur.bits.green - (cur.bits.green * i / 16)); cur.bits.blue = (cur.bits.blue - (cur.bits.blue * i / 16)); - cur.bits.alpha = 0; fadeOutColors[i][j & 0x7FFF] = cur.val; } } @@ -591,7 +605,7 @@ GPU * GPU_Init(u8 l) g->need_update_winh[1] = true; g->setFinalColorBck_funcNum = 0; g->setFinalColor3d_funcNum = 0; - g->setFinalColorSpr = _master_setFinalOBJColor; + g->setFinalColorSpr = setFinalOBJColorSpecialNone; @@ -604,7 +618,7 @@ void GPU_Reset(GPU *g, u8 l) g->setFinalColorBck_funcNum = 0; g->setFinalColor3d_funcNum = 0; - g->setFinalColorSpr = _master_setFinalOBJColor; + g->setFinalColorSpr = setFinalOBJColorSpecialNone; g->core = l; g->BGSize[0][0] = g->BGSize[1][0] = g->BGSize[2][0] = g->BGSize[3][0] = 256; g->BGSize[0][1] = g->BGSize[1][1] = g->BGSize[2][1] = g->BGSize[3][1] = 256; @@ -734,7 +748,7 @@ void SetupFinalPixelBlitter (GPU *gpu) } -//Sets up LCD control variables for Display Engines A and B for quick reading +/* Sets up LCD control variables for Display Engines A and B for quick reading */ void GPU_setVideoProp(GPU * gpu, u32 p) { struct _DISPCNT * cnt; @@ -842,7 +856,7 @@ void GPU_setBGProp(GPU * gpu, u16 num, u16 p) break; } - BGType mode = GPU_mode2type[dispCnt->BG_Mode][num]; + BGType mode = mode2type[dispCnt->BG_Mode][num]; //clarify affine ext modes if(mode == BGType_AffineExt) @@ -1075,51 +1089,256 @@ FORCEINLINE bool GPU::setFinalBGColorSpecialDecreaseWnd(u16 &color, const u8 x) // PIXEL RENDERING - OBJS /*****************************************************************************/ -template -static void _master_setFinalOBJColor(GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x) +static void setFinalOBJColorSpecialNone(GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x) +{ + if(type == 1) + { + int bg_under = gpu->bgPixels[x]; + u16 final = color; + + // If the layer we are drawing on is selected as 2nd source, we can blend + if((bg_under != 4) && (gpu->BLDCNT & (0x100 << bg_under))) + final = gpu->blend(color,T2ReadWord(dst, passing)); + + T2WriteWord(dst, passing, (final | 0x8000)); + gpu->bgPixels[x] = 4; + } + else + { + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } +} + +static FORCEINLINE u16 blendSprite(GPU* gpu, u8 alpha, u16 sprColor, u16 backColor, u8 type) +{ + if(type == 3) + //handle translucent bitmap sprite + return _blend(sprColor,backColor,&gpuBlendTable555[alpha+1][15-alpha]); + else + return gpu->blend(sprColor,backColor); +} + +static void setFinalOBJColorSpecialBlend(GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x) +{ + if((gpu->BLDCNT & 0x10) || (type == 1)) + { + int bg_under = gpu->bgPixels[x]; + u16 final = color; + + //If the layer we are drawing on is selected as 2nd source, we can blend + if((bg_under != 4) && (gpu->BLDCNT & (0x100 << bg_under))) + { + //bmp translucent handling tested by disgaea clock hud + final = blendSprite(gpu, alpha, color, T2ReadWord(dst, passing), type); + } + + T2WriteWord(dst, passing, (final | 0x8000)); + gpu->bgPixels[x] = 4; + } + else + { + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } +} + +static void setFinalOBJColorSpecialIncrease(GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x) +{ + if(type == 1) + { + int bg_under = gpu->bgPixels[x]; + u16 final = color; + + //If the layer we are drawing on is selected as 2nd source, we can blend + if((bg_under != 4) && (gpu->BLDCNT & (0x100 << bg_under))) + final = gpu->blend(color,T2ReadWord(dst, passing)); + + T2WriteWord(dst, passing, (final | 0x8000)); + gpu->bgPixels[x] = 4; + } + else if(gpu->BLDCNT & 0x10) + { + if (gpu->BLDY_EVY != 0x0) + { + color = fadeInColors[gpu->BLDY_EVY][color&0x7FFF]; + } + + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } + else + { + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } + +} + +static void setFinalOBJColorSpecialDecrease(GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x) +{ + if(type == 1) + { + int bg_under = gpu->bgPixels[x]; + u16 final = color; + + //If the layer we are drawing on is selected as 2nd source, we can blend + if((bg_under != 4) && (gpu->BLDCNT & (0x100 << bg_under))) + final = gpu->blend(color,T2ReadWord(dst, passing)); + + T2WriteWord(dst, passing, (final | 0x8000)); + gpu->bgPixels[x] = 4; + } + else if(gpu->BLDCNT & 0x10) + { + if (gpu->BLDY_EVY != 0x0) + { + color = fadeOutColors[gpu->BLDY_EVY][color&0x7FFF]; + } + + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } + else + { + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } +} + +static void setFinalOBJColorSpecialNoneWnd(GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x) { bool windowDraw = true, windowEffect = true; - if(WINDOW) + gpu->renderline_checkWindows(x, windowDraw, windowEffect); + + if(windowDraw) { - gpu->renderline_checkWindows(x, windowDraw, windowEffect); - if(!windowDraw) - return; - } - - //this inspects the layer beneath the sprite to see if the current blend flags make it a candidate for blending - int bg_under = gpu->bgPixels[x]; - bool allowBlend = ((bg_under != 4) && (gpu->BLDCNT & (0x100 << bg_under))); - - bool sourceEffectSelected = (gpu->BLDCNT & 0x10)!=0; - - //note that the fadein and fadeout is done here before blending, - //so that a fade and blending can be applied at the same time - bool forceBlendingForNormal = false; - if(windowEffect && sourceEffectSelected) - switch(FUNC) + if((type == 1) && windowEffect) { - case Increase: if(!allowBlend) color = fadeInColors[gpu->BLDY_EVY][color&0x7FFF]; break; - case Decrease: if(!allowBlend) color = fadeOutColors[gpu->BLDY_EVY][color&0x7FFF]; break; + int bg_under = gpu->bgPixels[x]; + u16 final = color; - //only when blend color effect is selected, ordinarily opaque sprites are blended with the color effect params - case Blend: forceBlendingForNormal = true; break; + // If the layer we are drawing on is selected as 2nd source, we can blend + if((bg_under != 4) && (gpu->BLDCNT & (0x100 << bg_under))) + final = gpu->blend(color,T2ReadWord(dst, passing)); + + T2WriteWord(dst, passing, (final | 0x8000)); + gpu->bgPixels[x] = 4; } + else + { + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } + } +} +static void setFinalOBJColorSpecialBlendWnd(GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x) +{ + bool windowDraw = true, windowEffect = true; - if(allowBlend) + gpu->renderline_checkWindows(x, windowDraw, windowEffect); + + if(windowDraw) { - u16 backColor = T2ReadWord(dst,passing); - //this hasn't been tested: this blending occurs without regard to the color effect, - //but rather purely from the sprite's alpha - if(type == GPU_OBJ_MODE_Bitmap) - color = _blend(color,backColor,&gpuBlendTable555[alpha+1][15-alpha]); - else if(type == GPU_OBJ_MODE_Transparent || forceBlendingForNormal) - color = gpu->blend(color,backColor); + if(((gpu->BLDCNT & 0x10) || (type == 1)) && windowEffect) + { + int bg_under = gpu->bgPixels[x]; + u16 final = color; + + // If the layer we are drawing on is selected as 2nd source, we can blend + if((bg_under != 4) && (gpu->BLDCNT & (0x100 << bg_under))) + { + final = gpu->blend(color,T2ReadWord(dst, passing)); + } + + T2WriteWord(dst, passing, (final | 0x8000)); + gpu->bgPixels[x] = 4; + } + else + { + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } + } +} + +static void setFinalOBJColorSpecialIncreaseWnd(GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x) +{ + bool windowDraw = true, windowEffect = true; + + gpu->renderline_checkWindows(x, windowDraw,windowEffect); + + if(windowDraw) + { + if((type == 1) && windowEffect) + { + int bg_under = gpu->bgPixels[x]; + u16 final = color; + + // If the layer we are drawing on is selected as 2nd source, we can blend + if((bg_under != 4) && (gpu->BLDCNT & (0x100 << bg_under))) + final = gpu->blend(color,T2ReadWord(dst, passing)); + + T2WriteWord(dst, passing, (final | 0x8000)); + gpu->bgPixels[x] = 4; + } + else if((gpu->BLDCNT & 0x10) && windowEffect) + { + if (gpu->BLDY_EVY != 0x0) + { + color = fadeInColors[gpu->BLDY_EVY][color&0x7FFF]; + } + + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } + else + { + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } } - T2WriteWord(dst, passing, (color | 0x8000)); - gpu->bgPixels[x] = 4; +} + +static void setFinalOBJColorSpecialDecreaseWnd(GPU *gpu, u32 passing, u8 *dst, u16 color, u8 alpha, u8 type, u16 x) +{ + bool windowDraw = true, windowEffect = true; + + gpu->renderline_checkWindows(x, windowDraw, windowEffect); + + if(windowDraw) + { + if((type == 1) && windowEffect) + { + int bg_under = gpu->bgPixels[x]; + u16 final = color; + + // If the layer we are drawing on is selected as 2nd source, we can blend + if((bg_under != 4) && (gpu->BLDCNT & (0x100 << bg_under))) + final = gpu->blend(color,T2ReadWord(dst, passing)); + + T2WriteWord(dst, passing, (final | 0x8000)); + gpu->bgPixels[x] = 4; + } + else if((gpu->BLDCNT & 0x10) && windowEffect) + { + if (gpu->BLDY_EVY != 0x0) + { + color = fadeOutColors[gpu->BLDY_EVY][color&0x7FFF]; + } + + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } + else + { + T2WriteWord(dst, passing, (color | 0x8000)); + gpu->bgPixels[x] = 4; + } + } } FORCEINLINE void GPU::setFinalColorBG(u16 color, u8 x) @@ -1367,6 +1586,12 @@ template INLINE void renderline_textBG(GPU * gpu, u16 XBG, u16 YBG, { color = T1ReadWord(pal, ((currLine&0xF) + tilePalette) << 1); gpu->__setFinalColorBck(color,x,currLine&0xF); + + extern int currFrameCounter; + if(currFrameCounter == 0x20 && nds.VCount == 0x48) { + int zzz=9; + } + x++; xoff++; } @@ -1590,21 +1815,16 @@ template void lineRot(GPU * gpu) } else { parms = &(gpu->dispx_st)->dispx_BG3PARMS; } - if(gpu->debug) - rotBG2(gpu, 0, (s16)gpu->currLine*256, 256,0, -1,-1, 256); - else - { - rotBG2(gpu, - parms->BGxX, - parms->BGxY, - parms->BGxPA, - parms->BGxPB, - parms->BGxPC, - parms->BGxPD, - 256); - parms->BGxX += parms->BGxPB; - parms->BGxY += parms->BGxPD; - } + rotBG2(gpu, + parms->BGxX, + parms->BGxY, + parms->BGxPA, + parms->BGxPB, + parms->BGxPC, + parms->BGxPD, + 256); + parms->BGxX += parms->BGxPB; + parms->BGxY += parms->BGxPD; } template void lineExtRot(GPU * gpu) @@ -1615,12 +1835,7 @@ template void lineExtRot(GPU * gpu) } else { parms = &(gpu->dispx_st)->dispx_BG3PARMS; } - - if(gpu->debug) - extRotBG2(gpu, 0, (s16)gpu->currLine*256, 256,0, -1,-1, 256); - else - { - extRotBG2(gpu, + extRotBG2(gpu, parms->BGxX, parms->BGxY, parms->BGxPA, @@ -1628,8 +1843,41 @@ template void lineExtRot(GPU * gpu) parms->BGxPC, parms->BGxPD, 256); - parms->BGxX += parms->BGxPB; - parms->BGxY += parms->BGxPD; + parms->BGxX += parms->BGxPB; + parms->BGxY += parms->BGxPD; +} + +namespace GPU_EXT { + void textBG(GPU * gpu, u8 num, u8 * DST) + { + gpu->currBgNum = num; + for(u32 i = 0; i < gpu->BGSize[num][1]; ++i) + { + gpu->currDst = DST + i*gpu->BGSize[num][0]*2; + gpu->currLine = i; + renderline_textBG(gpu, 0, i, gpu->BGSize[num][0]); + } + } + + void rotBG(GPU * gpu, u8 num, u8 * DST) + { + gpu->currBgNum = num; + for(u32 i = 0; i < gpu->BGSize[num][1]; ++i) + { + gpu->currDst = DST + i*gpu->BGSize[num][0]*2; + gpu->currLine = i; + rotBG2(gpu, 0, 0, 256, 0, 0, 256, gpu->BGSize[num][0]); + } + } + + void extRotBG(GPU * gpu, u8 num, u8 * DST) + { + for(u32 i = 0; i < gpu->BGSize[num][1]; ++i) + { + gpu->currDst = DST + i*gpu->BGSize[num][0]*2; + gpu->currLine = i; + extRotBG2(gpu, 0, 0, 256, 0, 0, 256, gpu->BGSize[num][0]); + } } } @@ -2116,14 +2364,15 @@ void GPU::_spriteRender(u8 * dst, u8 * dst_alpha, u8 * typeTab, u8 * prioTab) } else { - //2d mapping: + //NOT TESTED: - if (dispCnt->OBJ_BMP_2D_dim) - //256*256, verified by heroes of mana FMV intro + if (dispCnt->OBJ_BMP_2D_dim) // 256*256 + { + //verified by heroes of mana FMV intro src = (u8 *)MMU_RenderMapToLCD(gpu->sprMem + (((spriteInfo->TileIndex&0x3E0) * 64 + (spriteInfo->TileIndex&0x1F) *8 + ( y << 8)) << 1)); - else - //128*512, verified by harry potter and the order of the phoenix conversation portraits - src = (u8 *)MMU_RenderMapToLCD(gpu->sprMem + (((spriteInfo->TileIndex&0x3F0) * 64 + (spriteInfo->TileIndex&0x0F) *8 + ( y << 7)) << 1)); + } + else // 128 * 512 + src = (u8 *)MMU_RenderMapToLCD(gpu->sprMem + (((spriteInfo->TileIndex&0x3F0) * 64 + (spriteInfo->TileIndex&0x0F) *8 + ( y << 8)) << 1)); } if (!src) { @@ -3010,7 +3259,7 @@ void GPU::refreshAffineStartRegs(const int num, const int xy) template void GPU::modeRender(int layer) { - switch(GPU_mode2type[dispCnt().BG_Mode][layer]) + switch(mode2type[dispCnt().BG_Mode][layer]) { case BGType_Text: lineText(this); break; case BGType_Affine: lineRot(this); break; diff --git a/desmume/src/GPU.h b/src/GPU.h similarity index 98% rename from desmume/src/GPU.h rename to src/GPU.h index b535a27c7..0c4da93e8 100644 --- a/desmume/src/GPU.h +++ b/src/GPU.h @@ -505,14 +505,8 @@ typedef union - // (00: Normal, 01: Transparent, 10: Object window, 11: Bitmap) -enum GPU_OBJ_MODE -{ - GPU_OBJ_MODE_Normal = 0, - GPU_OBJ_MODE_Transparent = 1, - GPU_OBJ_MODE_Window = 2, - GPU_OBJ_MODE_Bitmap = 3 -}; + + /* this structure is for Sprite description, @@ -521,7 +515,7 @@ enum GPU_OBJ_MODE ref: http://www.bottledlight.com/ds/index.php/Video/Sprites */ -struct _OAM_ +typedef struct { #ifdef WORDS_BIGENDIAN // attr0 @@ -564,7 +558,7 @@ struct _OAM_ // attr3 unsigned attr3:16; #endif -}; +} _OAM_; typedef struct { @@ -622,21 +616,12 @@ enum BGType { BGType_AffineExt=4, BGType_AffineExt_256x16=5, BGType_AffineExt_256x1=6, BGType_AffineExt_Direct=7 }; -extern const BGType GPU_mode2type[8][4]; - struct GPU { - GPU() - : debug(false) - {} - // some structs are becoming redundant // some functions too (no need to recopy some vars as it is done by MMU) REG_DISPx * dispx_st; - //this indicates whether this gpu is handling debug tools - bool debug; - _BGxCNT & bgcnt(int num) { return (dispx_st)->dispx_BGxCNT[num].bits; } _DISPCNT & dispCnt() { return dispx_st->dispx_DISPCNT.bits; } template void modeRender(int layer); diff --git a/desmume/src/GPU_osd.cpp b/src/GPU_osd.cpp similarity index 100% rename from desmume/src/GPU_osd.cpp rename to src/GPU_osd.cpp diff --git a/desmume/src/GPU_osd.h b/src/GPU_osd.h similarity index 100% rename from desmume/src/GPU_osd.h rename to src/GPU_osd.h diff --git a/desmume/src/MMU.cpp b/src/MMU.cpp similarity index 97% rename from desmume/src/MMU.cpp rename to src/MMU.cpp index 348329daa..25251e9ab 100644 --- a/desmume/src/MMU.cpp +++ b/src/MMU.cpp @@ -33,6 +33,9 @@ #include "common.h" #include "debug.h" #include "NDSSystem.h" +#ifndef EXPERIMENTAL_GBASLOT +#include "cflash.h" +#endif #include "cp15.h" #include "wifi.h" #include "registers.h" @@ -468,7 +471,7 @@ struct VramConfiguration { std::string describe() { std::stringstream ret; for(int i=0;i>26)&1) for(; i < taille; ++i) { - _MMU_write32(dst, _MMU_read32(src)); + _MMU_write32(dst, _MMU_read32(src)); dst += dstinc; src += srcinc; } else for(; i < taille; ++i) { - _MMU_write16(dst, _MMU_read16(src)); + _MMU_write16(dst, _MMU_read16(src)); dst += dstinc; src += srcinc; } + //this is necessary for repeating DMA such as to scroll registers for NSMB level backdrop scrolling effect +//#if 0 //write back the addresses DMASrc[PROCNUM][num] = src; if((u & 0x3)!=3) //but dont write back dst if we were supposed to reload DMADst[PROCNUM][num] = dst; - - //this is probably not the best place to do it, but the dma code in ndssystem is so bad i didnt want to touch it - //until it all gets rewritten. so this is here as a reminder, at least. - //(there is no proof for this code, but it is reasonable) - T1WriteLong(MMU.MMU_MEM[PROCNUM][0x40], 0xB0+12*num, DMASrc[PROCNUM][num]); - T1WriteLong(MMU.MMU_MEM[PROCNUM][0x40], 0xB4+12*num, DMADst[PROCNUM][num]); +//#endif } } @@ -1315,28 +1314,6 @@ static INLINE void MMU_IPCSync(u8 proc, u32 val) setIF(proc^1, ( 1 << 16 )); } -static INLINE void write_auxspicnt(const int proc, const int size, const int adr, const int val) -{ - //why val==0 to reset? is it a particular bit? its not bit 6... - switch(size) { - case 16: - MMU.AUX_SPI_CNT = val; - if (val == 0) MMU_new.backupDevice.reset_command(); - break; - case 8: - switch(adr) { - case 0: - T1WriteByte((u8*)&MMU.AUX_SPI_CNT,0,val); - if (val == 0) MMU_new.backupDevice.reset_command(); - break; - case 1: - T1WriteByte((u8*)&MMU.AUX_SPI_CNT,1,val); - break; - } - } -} - - //================================================================================================== ARM9 * //========================================================================================================= //========================================================================================================= @@ -1351,11 +1328,19 @@ void FASTCALL _MMU_ARM9_write08(u32 adr, u8 val) return; } +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) { addon.write08(adr, val); return; } +#else + // CFlash writing, Mic + if ((adr>=0x9000000)&&(adr<0x9900000)) { + cflash_write(adr,val); + return; + } +#endif adr &= 0x0FFFFFFF; @@ -1491,14 +1476,6 @@ void FASTCALL _MMU_ARM9_write08(u32 adr, u8 val) GPU_setBLDY_EVY(SubScreen.gpu,val) ; break; - case REG_AUXSPICNT: - write_auxspicnt(9,8,0,val); - return; - case REG_AUXSPICNT+1: - write_auxspicnt(9,8,1,val); - return; - - case 0x4000247: /* Update WRAMSTAT at the ARM7 side */ T1WriteByte(MMU.MMU_MEM[ARMCPU_ARM7][0x40], 0x241, val); @@ -1559,11 +1536,20 @@ void FASTCALL _MMU_ARM9_write16(u32 adr, u16 val) return; } +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) { addon.write16(adr, val); return; } +#else + // CFlash writing, Mic + if ((adr>=0x08800000)&&(adr<0x09900000)) + { + cflash_write(adr,val); + return; + } +#endif adr &= 0x0FFFFFFF; @@ -1799,12 +1785,17 @@ void FASTCALL _MMU_ARM9_write16(u32 adr, u16 val) } case REG_AUXSPICNT: - write_auxspicnt(9,16,0,val); + T1WriteWord(MMU.MMU_MEM[ARMCPU_ARM7][(REG_AUXSPICNT >> 20) & 0xff], REG_AUXSPICNT & 0xfff, val); + AUX_SPI_CNT = val; + + if (val == 0) + //mc_reset_com(&MMU.bupmem); // reset backup memory device communication + MMU_new.backupDevice.reset_command(); return; case REG_AUXSPIDATA: if(val!=0) - MMU.AUX_SPI_CMD = val & 0xFF; + AUX_SPI_CMD = val & 0xFF; //T1WriteWord(MMU.MMU_MEM[ARMCPU_ARM7][(REG_AUXSPIDATA >> 20) & 0xff], REG_AUXSPIDATA & 0xfff, bm_transfer(&MMU.bupmem, val)); T1WriteWord(MMU.MMU_MEM[ARMCPU_ARM7][(REG_AUXSPIDATA >> 20) & 0xff], REG_AUXSPIDATA & 0xfff, MMU_new.backupDevice.data_command(val)); @@ -2144,11 +2135,19 @@ void FASTCALL _MMU_ARM9_write32(u32 adr, u32 val) //int zzz=9; } +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) { addon.write32(adr, val); return; } +#else + // CFlash writing, Mic + if ((adr>=0x9000000) && (adr<0x9900000)) { + cflash_write(adr,val); + return; + } +#endif adr &= 0x0FFFFFFF; @@ -2191,10 +2190,8 @@ void FASTCALL _MMU_ARM9_write32(u32 adr, u32 val) case 0x400041: case 0x400042: case 0x400043: // FIFO Commands - ((u32 *)(MMU.MMU_MEM[ARMCPU_ARM9][0x40]))[(adr & 0xFFF) >> 2] = val; gfx3d_sendCommandToFIFO(val); return; - case 0x400044: case 0x400045: case 0x400046: @@ -2220,7 +2217,6 @@ void FASTCALL _MMU_ARM9_write32(u32 adr, u32 val) case 0x40005A: case 0x40005B: case 0x40005C: // Individual Commands - ((u32 *)(MMU.MMU_MEM[ARMCPU_ARM9][0x40]))[(adr & 0xFFF) >> 2] = val; gfx3d_sendCommand(adr, val); return; default: @@ -2713,8 +2709,14 @@ u8 FASTCALL _MMU_ARM9_read08(u32 adr) if(adr<0x02000000) return T1ReadByte(ARM9Mem.ARM9_ITCM, adr&0x7FFF); +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) return addon.read08(adr); +#else + // CFlash reading, Mic + if ((adr>=0x9000000)&&(adr<0x9900000)) + return (unsigned char)cflash_read(adr); +#endif bool unmapped; adr = MMU_LCDmap(adr, unmapped); @@ -2731,8 +2733,14 @@ u16 FASTCALL _MMU_ARM9_read16(u32 adr) if(adr<0x02000000) return T1ReadWord(ARM9Mem.ARM9_ITCM, adr & 0x7FFF); +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) return addon.read16(adr); +#else + // CFlash reading, Mic + if ((adr>=0x08800000) && (adr<0x09900000)) + return (unsigned short)cflash_read(adr); +#endif adr &= 0x0FFFFFFF; @@ -2743,9 +2751,9 @@ u16 FASTCALL _MMU_ARM9_read16(u32 adr) { // ============================================= 3D case 0x04000604: - return (gfx3d_GetNumPolys()); + return (gfx3d_GetNumPolys()&2047); case 0x04000606: - return (gfx3d_GetNumVertex()); + return (gfx3d_GetNumVertex()&8191); case 0x04000630: case 0x04000632: case 0x04000634: @@ -2770,9 +2778,6 @@ u16 FASTCALL _MMU_ARM9_read16(u32 adr) case REG_TM3CNTL : return MMU.timer[ARMCPU_ARM9][(adr&0xF)>>2]; - case REG_AUXSPICNT: - return MMU.AUX_SPI_CNT; - case 0x04000130: case 0x04000136: //not sure whether these should trigger from byte reads @@ -2801,8 +2806,14 @@ u32 FASTCALL _MMU_ARM9_read32(u32 adr) if(adr<0x02000000) return T1ReadLong(ARM9Mem.ARM9_ITCM, adr&0x7FFF); +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) return addon.read32(adr); +#else + // CFlash reading, Mic + if ((adr>=0x9000000) && (adr<0x9900000)) + return (u32)cflash_read(adr); +#endif adr &= 0x0FFFFFFF; @@ -2847,7 +2858,7 @@ u32 FASTCALL _MMU_ARM9_read32(u32 adr) case 0x4000604: { - return (gfx3d_GetNumPolys()) & ((gfx3d_GetNumVertex()) << 16); + return (gfx3d_GetNumPolys()&2047) & ((gfx3d_GetNumVertex()&8191) << 16); //LOG ("read32 - RAM_COUNT -> 0x%X", ((u32 *)(MMU.MMU_MEM[ARMCPU_ARM9][(adr>>20)&0xFF]))[(adr&MMU.MMU_MASK[ARMCPU_ARM9][(adr>>20)&0xFF])>>2]); } @@ -2957,7 +2968,7 @@ u32 FASTCALL _MMU_ARM9_read32(u32 adr) T1ReadLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x1A4) & 0x7F7FFFFF); // if needed, throw irq for the end of transfer - if(MMU.AUX_SPI_CNT & 0x4000) + if(T1ReadWord(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x1A0) & 0x4000) NDS_makeInt(ARMCPU_ARM9, 19); return val; @@ -2981,11 +2992,20 @@ void FASTCALL _MMU_ARM7_write08(u32 adr, u8 val) { mmu_log_debug_ARM7(adr, "(write08) %0x%X", val); +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) { addon.write08(adr, val); return; } +#else + // CFlash writing, Mic + if ((adr>=0x9000000)&&(adr<0x9900000)) + { + cflash_write(adr,val); + return; + } +#endif adr &= 0x0FFFFFFF; // This is bad, remove it @@ -2995,8 +3015,6 @@ void FASTCALL _MMU_ARM7_write08(u32 adr, u8 val) return; } - adr &= 0x0FFFFFFF; - if(adr == 0x04000301) { switch(val) @@ -3015,22 +3033,7 @@ void FASTCALL _MMU_ARM7_write08(u32 adr, u8 val) } #endif - if (adr >> 24 == 4) - { - switch(adr) - { - case REG_RTC: - rtcWrite(val); - return; - - case REG_AUXSPICNT: - write_auxspicnt(9,8,0,val); - return; - case REG_AUXSPICNT+1: - write_auxspicnt(9,8,1,val); - return; - } - } + if ( adr == REG_RTC ) rtcWrite(val); bool unmapped; adr = MMU_LCDmap(adr,unmapped); @@ -3045,11 +3048,20 @@ void FASTCALL _MMU_ARM7_write16(u32 adr, u16 val) { mmu_log_debug_ARM7(adr, "(write16) %0x%X", val); +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) { addon.write16(adr, val); return; } +#else + // CFlash writing, Mic + if ((adr>=0x08800000)&&(adr<0x09900000)) + { + cflash_write(adr,val); + return; + } +#endif #ifdef EXPERIMENTAL_WIFI @@ -3090,12 +3102,17 @@ void FASTCALL _MMU_ARM7_write16(u32 adr, u16 val) return; case REG_AUXSPICNT: - write_auxspicnt(7,16,0,val); + T1WriteWord(MMU.MMU_MEM[ARMCPU_ARM7][(REG_AUXSPICNT >> 20) & 0xff], REG_AUXSPICNT & 0xfff, val); + AUX_SPI_CNT = val; + + if (val == 0) + //mc_reset_com(&MMU.bupmem); // reset backup memory device communication + MMU_new.backupDevice.reset_command(); return; case REG_AUXSPIDATA: if(val!=0) - MMU.AUX_SPI_CMD = val & 0xFF; + AUX_SPI_CMD = val & 0xFF; //T1WriteWord(MMU.MMU_MEM[ARMCPU_ARM7][(REG_AUXSPIDATA >> 20) & 0xff], REG_AUXSPIDATA & 0xfff, bm_transfer(&MMU.bupmem, val)); T1WriteWord(MMU.MMU_MEM[ARMCPU_ARM7][(REG_AUXSPIDATA >> 20) & 0xff], REG_AUXSPIDATA & 0xfff, MMU_new.backupDevice.data_command(val)); @@ -3105,11 +3122,11 @@ void FASTCALL _MMU_ARM7_write16(u32 adr, u16 val) { int reset_firmware = 1; - if ( ((MMU.SPI_CNT >> 8) & 0x3) == 1) + if ( ((SPI_CNT >> 8) & 0x3) == 1) { if ( ((val >> 8) & 0x3) == 1) { - if ( BIT11(MMU.SPI_CNT)) + if ( BIT11(SPI_CNT)) { // select held reset_firmware = 0; @@ -3123,7 +3140,7 @@ void FASTCALL _MMU_ARM7_write16(u32 adr, u16 val) // reset fw device communication fw_reset_com(&MMU.fw); } - MMU.SPI_CNT = val; + SPI_CNT = val; T1WriteWord(MMU.MMU_MEM[ARMCPU_ARM7][(REG_SPICNT >> 20) & 0xff], REG_SPICNT & 0xfff, val); } @@ -3134,7 +3151,7 @@ void FASTCALL _MMU_ARM7_write16(u32 adr, u16 val) u16 spicnt; if(val!=0) - MMU.SPI_CMD = val; + SPI_CMD = val; spicnt = T1ReadWord(MMU.MMU_MEM[ARMCPU_ARM7][(REG_SPICNT >> 20) & 0xff], REG_SPICNT & 0xfff); @@ -3173,14 +3190,14 @@ void FASTCALL _MMU_ARM7_write16(u32 adr, u16 val) return; case 2 : - switch(MMU.SPI_CMD & 0x70) + switch(SPI_CMD & 0x70) { case 0x00 : val = 0; break; case 0x10 : //emu_halt(); - if(MMU.SPI_CNT&(1<<11)) + if(SPI_CNT&(1<<11)) { if(partie) { @@ -3460,11 +3477,21 @@ void FASTCALL _MMU_ARM7_write32(u32 adr, u32 val) { mmu_log_debug_ARM7(adr, "(write32) %0x%X", val); +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) { addon.write32(adr, val); return; } +#else + // CFlash writing, Mic + if ((adr>=0x9000000)&&(adr<0x9900000)) { + cflash_write(adr,val); + return; + } +#endif + + #ifdef EXPERIMENTAL_WIFI if ((adr & 0xFF800000) == 0x04800000) @@ -3751,8 +3778,14 @@ u8 FASTCALL _MMU_ARM7_read08(u32 adr) } #endif +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) return addon.read08(adr); +#else + // CFlash reading, Mic + if ((adr>=0x9000000)&&(adr<0x9900000)) + return (unsigned char)cflash_read(adr); +#endif if (adr == REG_RTC) return (u8)rtcRead(); @@ -3773,8 +3806,14 @@ u16 FASTCALL _MMU_ARM7_read16(u32 adr) return WIFI_read16(&wifiMac,adr) ; #endif +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) return addon.read16(adr); +#else + // CFlash reading, Mic + if ((adr>=0x08800000)&&(adr<0x09900000)) + return (unsigned short)cflash_read(adr); +#endif adr &= 0x0FFFFFFF; @@ -3805,8 +3844,6 @@ u16 FASTCALL _MMU_ARM7_read16(u32 adr) case REG_TM3CNTL : return MMU.timer[ARMCPU_ARM7][(adr&0xF)>>2]; - case REG_AUXSPICNT: - return MMU.AUX_SPI_CNT; case 0x04000130: case 0x04000136: @@ -3839,8 +3876,14 @@ u32 FASTCALL _MMU_ARM7_read32(u32 adr) return (WIFI_read16(&wifiMac,adr) | (WIFI_read16(&wifiMac,adr+2) << 16)); #endif +#ifdef EXPERIMENTAL_GBASLOT if ( (adr >= 0x08000000) && (adr < 0x0A010000) ) return addon.read32(adr); +#else + // CFlash reading, Mic + if ((adr>=0x9000000)&&(adr<0x9900000)) + return (u32)cflash_read(adr); +#endif adr &= 0x0FFFFFFF; @@ -3924,7 +3967,7 @@ u32 FASTCALL _MMU_ARM7_read32(u32 adr) T1ReadLong(MMU.MMU_MEM[ARMCPU_ARM7][0x40], 0x1A4) & 0x7F7FFFFF); // if needed, throw irq for the end of transfer - if(MMU.AUX_SPI_CNT & 0x4000) + if(T1ReadWord(MMU.MMU_MEM[ARMCPU_ARM7][0x40], 0x1A0) & 0x4000) NDS_makeInt(ARMCPU_ARM7, 19); return val; diff --git a/desmume/src/MMU.h b/src/MMU.h similarity index 90% rename from desmume/src/MMU.h rename to src/MMU.h index 1c6d4c901..9b1e6ca87 100644 --- a/desmume/src/MMU.h +++ b/src/MMU.h @@ -112,15 +112,6 @@ struct MMU_struct { u32 sqrtCnt; s32 sqrtCycles; - u16 SPI_CNT; - u16 SPI_CMD; - u16 AUX_SPI_CNT; - u16 AUX_SPI_CMD; - -#ifdef USE_GEOMETRY_FIFO_EMULATION - s32 gfx3dCycles; -#endif - u8 powerMan_CntReg; BOOL powerMan_CntRegWritten; u8 powerMan_Reg[4]; @@ -222,7 +213,7 @@ FORCEINLINE void* MMU_gpu_map(u32 vram_addr) enum MMU_ACCESS_TYPE { - MMU_AT_CODE, MMU_AT_DATA, MMU_AT_GPU, MMU_AT_DMA + MMU_AT_CODE, MMU_AT_DATA, MMU_AT_GPU }; template u8 _MMU_read08(u32 addr); @@ -265,15 +256,7 @@ inline void SetupMMU(bool debugConsole) { //T1ReadWord(MMU.MMU_MEM[ARMCPU_ARM7][(adr >> 20) & 0xFF], // adr & MMU.MMU_MASK[ARMCPU_ARM7][(adr >> 20) & 0xFF]); -FORCEINLINE u8 _MMU_read08(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr) -{ - //special handling for DMA: read 0 from TCM - if(PROCNUM==ARMCPU_ARM9 && AT == MMU_AT_DMA) - { - if(addr<0x02000000) return 0; //itcm - if((addr&(~0x3FFF)) == MMU.DTCMRegion) return 0; //dtcm - } - +FORCEINLINE u8 _MMU_read08(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr) { if(PROCNUM==ARMCPU_ARM9) if((addr&(~0x3FFF)) == MMU.DTCMRegion) { @@ -288,14 +271,7 @@ FORCEINLINE u8 _MMU_read08(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u3 else return _MMU_ARM7_read08(addr); } -FORCEINLINE u16 _MMU_read16(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr) -{ - //special handling for DMA: read 0 from TCM - if(PROCNUM==ARMCPU_ARM9 && AT == MMU_AT_DMA) - { - if(addr<0x02000000) return 0; //itcm - if((addr&(~0x3FFF)) == MMU.DTCMRegion) return 0; //dtcm - } +FORCEINLINE u16 _MMU_read16(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr) { //special handling for execution from arm9, since we spend so much time in there if(PROCNUM==ARMCPU_ARM9 && AT == MMU_AT_CODE) @@ -324,14 +300,7 @@ dunno: else return _MMU_ARM7_read16(addr); } -FORCEINLINE u32 _MMU_read32(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr) -{ - //special handling for DMA: read 0 from TCM - if(PROCNUM==ARMCPU_ARM9 && AT == MMU_AT_DMA) - { - if(addr<0x02000000) return 0; //itcm - if((addr&(~0x3FFF)) == MMU.DTCMRegion) return 0; //dtcm - } +FORCEINLINE u32 _MMU_read32(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr) { //special handling for execution from arm9, since we spend so much time in there if(PROCNUM==ARMCPU_ARM9 && AT == MMU_AT_CODE) @@ -375,15 +344,7 @@ dunno: else return _MMU_ARM7_read32(addr); } -FORCEINLINE void _MMU_write08(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr, u8 val) -{ - //special handling for DMA: discard writes to TCM - if(PROCNUM==ARMCPU_ARM9 && AT == MMU_AT_DMA) - { - if(addr<0x02000000) return; //itcm - if((addr&(~0x3FFF)) == MMU.DTCMRegion) return; //dtcm - } - +FORCEINLINE void _MMU_write08(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr, u8 val) { if(PROCNUM==ARMCPU_ARM9) if((addr&(~0x3FFF)) == MMU.DTCMRegion) { @@ -400,15 +361,7 @@ FORCEINLINE void _MMU_write08(const int PROCNUM, const MMU_ACCESS_TYPE AT, const else _MMU_ARM7_write08(addr,val); } -FORCEINLINE void _MMU_write16(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr, u16 val) -{ - //special handling for DMA: discard writes to TCM - if(PROCNUM==ARMCPU_ARM9 && AT == MMU_AT_DMA) - { - if(addr<0x02000000) return; //itcm - if((addr&(~0x3FFF)) == MMU.DTCMRegion) return; //dtcm - } - +FORCEINLINE void _MMU_write16(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr, u16 val) { if(PROCNUM==ARMCPU_ARM9) if((addr&(~0x3FFF)) == MMU.DTCMRegion) { @@ -425,15 +378,7 @@ FORCEINLINE void _MMU_write16(const int PROCNUM, const MMU_ACCESS_TYPE AT, const else _MMU_ARM7_write16(addr,val); } -FORCEINLINE void _MMU_write32(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr, u32 val) -{ - //special handling for DMA: discard writes to TCM - if(PROCNUM==ARMCPU_ARM9 && AT == MMU_AT_DMA) - { - if(addr<0x02000000) return; //itcm - if((addr&(~0x3FFF)) == MMU.DTCMRegion) return; //dtcm - } - +FORCEINLINE void _MMU_write32(const int PROCNUM, const MMU_ACCESS_TYPE AT, const u32 addr, u32 val) { if(PROCNUM==ARMCPU_ARM9) if((addr&(~0x3FFF)) == MMU.DTCMRegion) { diff --git a/desmume/src/Makefile.am b/src/Makefile.am similarity index 95% rename from desmume/src/Makefile.am rename to src/Makefile.am index c3dcfb956..67a1d90f7 100644 --- a/desmume/src/Makefile.am +++ b/src/Makefile.am @@ -1,6 +1,6 @@ include $(top_srcdir)/src/desmume.mk -AM_CPPFLAGS += $(SDL_CFLAGS) $(GTK_CFLAGS) $(GTHREAD_CFLAGS) $(X_CFLAGS) $(LUA_CFLAGS) +AM_CPPFLAGS += $(SDL_CFLAGS) $(GTK_CFLAGS) $(GTHREAD_CFLAGS) $(X_CFLAGS) EXTRA_DIST = build.bat instruction_tabdef.inc thumb_tabdef.inc fs-linux.cpp fs-windows.cpp \ matrix_sse2-x64.asm matrix_sse2-x86.asm @@ -15,6 +15,7 @@ libdesmume_a_SOURCES = \ armcpu.cpp armcpu.h ARM9.h \ arm_instructions.cpp arm_instructions.h \ bios.cpp bios.h bits.h cp15.cpp cp15.h \ + cflash.cpp cflash.h fs.h \ common.cpp common.h \ debug.cpp debug.h driver.h \ Disassembler.cpp Disassembler.h \ @@ -47,7 +48,7 @@ libdesmume_a_SOURCES = \ utils/decrypt/crc.cpp utils/decrypt/crc.h utils/decrypt/decrypt.cpp \ utils/decrypt/decrypt.h utils/decrypt/header.cpp utils/decrypt/header.h \ addons.cpp addons.h \ - addons/compactFlash.cpp addons/gbagame.cpp addons/none.cpp addons/rumblepak.cpp fs.h \ + addons/compactFlash.cpp addons/gbagame.cpp addons/none.cpp addons/rumblepak.cpp \ mic.cpp mic.h \ cheatSystem.cpp cheatSystem.h \ texcache.cpp texcache.h rasterize.cpp rasterize.h \ @@ -55,9 +56,6 @@ libdesmume_a_SOURCES = \ if HAVE_GLIB libdesmume_a_SOURCES += commandline.h commandline.cpp endif -if HAVE_LUA -libdesmume_a_SOURCES += lua-engine.cpp -endif if HAVE_GDB_STUB libdesmume_a_SOURCES += gdbstub.h endif diff --git a/desmume/src/NDSSystem.cpp b/src/NDSSystem.cpp similarity index 97% rename from desmume/src/NDSSystem.cpp rename to src/NDSSystem.cpp index 2ac9c0fd7..e0ea08fa6 100644 --- a/desmume/src/NDSSystem.cpp +++ b/src/NDSSystem.cpp @@ -31,6 +31,9 @@ #include "NDSSystem.h" #include "render3D.h" #include "MMU.h" +#ifndef EXPERIMENTAL_GBASLOT +#include "cflash.h" +#endif #include "ROMReader.h" #include "gfx3d.h" #include "utils/decrypt/decrypt.h" @@ -709,7 +712,12 @@ void GameInfo::populate() } } -int NDS_LoadROM( const char *filename, const char *logicalFilename) +#ifdef EXPERIMENTAL_GBASLOT +int NDS_LoadROM( const char *filename) +#else +int NDS_LoadROM( const char *filename, + const char *cflash_disk_image_file) +#endif { int ret; int type; @@ -733,24 +741,12 @@ int NDS_LoadROM( const char *filename, const char *logicalFilename) noext = strdup(filename); reader = ROMReaderInit(&noext); - if(logicalFilename) - { - for (int t = strlen(logicalFilename); t>0; t--) - if ( (logicalFilename[t] == '\\') || (logicalFilename[t] == '/') ) - { - strncpy(pathToROM, logicalFilename, t+1); - break; - } - } - else - { - for (int t = strlen(filename); t>0; t--) - if ( (filename[t] == '\\') || (filename[t] == '/') ) - { - strncpy(pathToROM, filename, t+1); - break; - } - } + for (int t = strlen(filename); t>0; t--) + if ( (filename[t] == '\\') || (filename[t] == '/') ) + { + strncpy(pathToROM, filename, t+1); + break; + } for (int t = strlen(filename); t>0; t--) if ( (filename[t] == '\\') || (filename[t] == '/') || (filename[t] == '.') ) @@ -837,28 +833,20 @@ int NDS_LoadROM( const char *filename, const char *logicalFilename) NDS_SetROM(data, mask); NDS_Reset(); +#ifndef EXPERIMENTAL_GBASLOT + cflash_close(); + cflash_init(cflash_disk_image_file); +#endif free(noext); memset(buf, 0, MAX_PATH); - - #ifdef WIN32 - GetFullPathNoExt(BATTERY, buf, MAX_PATH); - #else strcpy(buf, pathFilenameToROMwithoutExt); - #endif - strcat(buf, ".dsv"); // DeSmuME memory card :) MMU_new.backupDevice.load_rom(buf); memset(buf, 0, MAX_PATH); - - #ifdef WIN32 - GetFullPathNoExt(CHEATS, buf, MAX_PATH); - #else strcpy(buf, pathFilenameToROMwithoutExt); - #endif - strcat(buf, ".dct"); // DeSmuME cheat :) cheatsInit(buf); @@ -894,14 +882,6 @@ void NDS_Reset() if(movieMode != MOVIEMODE_INACTIVE && !_HACK_DONT_STOPMOVIE) movie_reset_command = true; - if(movieMode == MOVIEMODE_INACTIVE) { - currFrameCounter = 0; - lagframecounter = 0; - LagFrameFlag = 0; - lastLag = 0; - TotalLagFrames = 0; - } - MMU_clearMem(); MMU_new.backupDevice.reset(); @@ -1050,9 +1030,7 @@ void NDS_Reset() // Copy the whole header to Main RAM 0x27FFE00 on startup. // Reference: http://nocash.emubase.de/gbatek.htm#dscartridgeheader - //zero 27-jun-09 : why did this copy 0x90 more? gbatek says its not stored in ram. - //for (i = 0; i < ((0x170+0x90)/4); i++) { - for (i = 0; i < ((0x170)/4); i++) { + for (i = 0; i < ((0x170+0x90)/4); i++) { _MMU_write32(0x027FFE00+i*4, LE_TO_LOCAL_32(((u32*)MMU.CART_ROM)[i])); } @@ -1654,7 +1632,7 @@ void NDS_exec(s32 nb) else des_arm_instructions_set[INDEX(NDS_ARM9.instruction)](NDS_ARM9.instruct_adr, NDS_ARM9.instruction, dasmbuf); - printf("%05d %08d 9:%08X %08X %-30s R00:%08X R01:%08X R02:%08X R03:%08X R04:%08X R05:%08X R06:%08X R07:%08X R08:%08X R09:%08X R10:%08X R11:%08X R12:%08X R13:%08X R14:%08X R15:%08X\n", + printf("%05d %08d 9:%08X %08X %-30s %08X R00:%08X R01:%08X R02:%08X R03:%08X R04:%08X R05:%08X R06:%08X R07:%08X R08:%08X R09:%08X R10:%08X R11:%08X R12:%08X R13:%08X R14:%08X R15:%08X\n", currFrameCounter, nds.cycles, NDS_ARM9.instruct_adr,NDS_ARM9.instruction, dasmbuf, NDS_ARM9.R[0], NDS_ARM9.R[1], NDS_ARM9.R[2], NDS_ARM9.R[3], NDS_ARM9.R[4], NDS_ARM9.R[5], NDS_ARM9.R[6], NDS_ARM9.R[7], @@ -1712,7 +1690,7 @@ void NDS_exec(s32 nb) des_thumb_instructions_set[((NDS_ARM7.instruction)>>6)&1023](NDS_ARM7.instruct_adr, NDS_ARM7.instruction, dasmbuf); else des_arm_instructions_set[INDEX(NDS_ARM7.instruction)](NDS_ARM7.instruct_adr, NDS_ARM7.instruction, dasmbuf); - printf("%05d %08d 7:%08X %08X %-30s R00:%08X R01:%08X R02:%08X R03:%08X R04:%08X R05:%08X R06:%08X R07:%08X R08:%08X R09:%08X R10:%08X R11:%08X R12:%08X R13:%08X R14:%08X R15:%08X\n", + printf("%05d %08d 7:%08X %08X %-30s %08X R00:%08X R01:%08X R02:%08X R03:%08X R04:%08X R05:%08X R06:%08X R07:%08X R08:%08X R09:%08X R10:%08X R11:%08X R12:%08X R13:%08X R14:%08X R15:%08X\n", currFrameCounter, nds.cycles, NDS_ARM7.instruct_adr,NDS_ARM7.instruction, dasmbuf, NDS_ARM7.R[0], NDS_ARM7.R[1], NDS_ARM7.R[2], NDS_ARM7.R[3], NDS_ARM7.R[4], NDS_ARM7.R[5], NDS_ARM7.R[6], NDS_ARM7.R[7], @@ -1891,6 +1869,7 @@ void NDS_exec(s32 nb) T1WriteWord(MMU.ARM7_REG, 4, T1ReadWord(MMU.ARM7_REG, 4) | 1); NDS_ARM9VBlankInt(); NDS_ARM7VBlankInt(); + cheatsProcess(); nds.runCycleCollector[nds.idleFrameCounter] = 1120380-nds.idleCycles; nds.idleFrameCounter++; @@ -1937,10 +1916,6 @@ void NDS_exec(s32 nb) nds.ARM7Cycle -= (560190<<1); nb -= (560190<<1); -#ifdef USE_GEOMETRY_FIFO_EMULATION - MMU.gfx3dCycles -= (560190 << 1); -#endif - if(MMU.divRunning) { MMU.divCycles -= (560190 << 1); @@ -2014,11 +1989,6 @@ void NDS_exec(s32 nb) if(!nds.sleeping) {*/ -#ifdef USE_GEOMETRY_FIFO_EMULATION - if (nds.cycles > MMU.gfx3dCycles) - gfx3d_execute3D(); -#endif - if(MMU.divRunning) { if(nds.cycles > MMU.divCycles) @@ -2441,10 +2411,8 @@ void NDS_exec(s32 nb) } } -#ifndef USE_GEOMETRY_FIFO_EMULATION if(MMU.reg_IE[ARMCPU_ARM9]&(1<<21)) NDS_makeARM9Int(21); // GX geometry -#endif if((MMU.reg_IF[0]&MMU.reg_IE[0]) && (MMU.reg_IME[0])) { @@ -2494,7 +2462,6 @@ void NDS_exec(s32 nb) } currFrameCounter++; - cheatsProcess(); } static std::string MakeInputDisplayString(u16 pad, const std::string* Buttons, int count) { diff --git a/desmume/src/NDSSystem.h b/src/NDSSystem.h similarity index 98% rename from desmume/src/NDSSystem.h rename to src/NDSSystem.h index 2caef8424..73b8dba1f 100644 --- a/desmume/src/NDSSystem.h +++ b/src/NDSSystem.h @@ -35,17 +35,13 @@ #include -#ifdef WIN32 -#include "pathsettings.h" -#endif - struct turbo { bool Right; bool Left; bool Down; bool Up; - bool Start; bool Select; + bool Start; bool B; bool A; bool Y; @@ -63,8 +59,8 @@ struct turbotime { int Left; int Down; int Up; - int Start; int Select; + int Start; int B; int A; int Y; @@ -82,8 +78,8 @@ struct autohold { bool Left; bool Down; bool Up; - bool Start; bool Select; + bool Start; bool B; bool A; bool Y; @@ -289,7 +285,12 @@ void NDS_releaseTouch(void); void NDS_setPad(bool R,bool L,bool D,bool U,bool T,bool S,bool B,bool A,bool Y,bool X,bool W,bool E,bool G, bool F); void NDS_setPadFromMovie(u16 pad); -int NDS_LoadROM(const char *filename, const char* logicalFilename=0); +#ifdef EXPERIMENTAL_GBASLOT +int NDS_LoadROM(const char *filename); +#else +int NDS_LoadROM(const char *filename, + const char *cflash_disk_image_file); +#endif void NDS_FreeROM(void); void NDS_Reset(); int NDS_ImportSave(const char *filename); diff --git a/desmume/src/OGLRender.cpp b/src/OGLRender.cpp similarity index 100% rename from desmume/src/OGLRender.cpp rename to src/OGLRender.cpp diff --git a/desmume/src/OGLRender.h b/src/OGLRender.h similarity index 100% rename from desmume/src/OGLRender.h rename to src/OGLRender.h diff --git a/desmume/src/PACKED.h b/src/PACKED.h similarity index 100% rename from desmume/src/PACKED.h rename to src/PACKED.h diff --git a/src/PACKED_END.h b/src/PACKED_END.h new file mode 100644 index 000000000..9d407a236 --- /dev/null +++ b/src/PACKED_END.h @@ -0,0 +1,3 @@ +#if defined(_MSC_VER) || defined(__INTEL_COMPILER) +#pragma pack(pop) +#endif diff --git a/desmume/src/ROMReader.cpp b/src/ROMReader.cpp similarity index 100% rename from desmume/src/ROMReader.cpp rename to src/ROMReader.cpp diff --git a/desmume/src/ROMReader.h b/src/ROMReader.h similarity index 100% rename from desmume/src/ROMReader.h rename to src/ROMReader.h diff --git a/desmume/src/SPU.cpp b/src/SPU.cpp similarity index 98% rename from desmume/src/SPU.cpp rename to src/SPU.cpp index eb4f3f407..fd3a42556 100644 --- a/desmume/src/SPU.cpp +++ b/src/SPU.cpp @@ -52,6 +52,18 @@ int SPU_currentCoreNum = SNDCORE_DUMMY; static SoundInterface_struct *SNDCore=NULL; extern SoundInterface_struct *SNDCoreList[]; +#define CHANSTAT_STOPPED 0 +#define CHANSTAT_PLAY 1 + + + +static FORCEINLINE u32 sputrunc(float f) { return u32floor(f); } +static FORCEINLINE u32 sputrunc(double d) { return u32floor(d); } +static FORCEINLINE s32 spumuldiv7(s32 val, u8 multiplier) { + assert(multiplier <= 127); + return (multiplier == 127) ? val : ((val * multiplier) >> 7); +} + //const int shift = (FORMAT == 0 ? 2 : 1); static const int format_shift[] = { 2, 1, 3, 0 }; diff --git a/desmume/src/SPU.h b/src/SPU.h similarity index 89% rename from desmume/src/SPU.h rename to src/SPU.h index 493f62bfd..36532c982 100644 --- a/desmume/src/SPU.h +++ b/src/SPU.h @@ -24,24 +24,12 @@ #define SPU_H #include "types.h" -#include "matrix.h" #include #include -#include #define SNDCORE_DEFAULT -1 #define SNDCORE_DUMMY 0 -#define CHANSTAT_STOPPED 0 -#define CHANSTAT_PLAY 1 - -static FORCEINLINE u32 sputrunc(float f) { return u32floor(f); } -static FORCEINLINE u32 sputrunc(double d) { return u32floor(d); } -static FORCEINLINE s32 spumuldiv7(s32 val, u8 multiplier) { - assert(multiplier <= 127); - return (multiplier == 127) ? val : ((val * multiplier) >> 7); -} - enum SPUInterpolationMode { SPUInterpolation_None = 0, diff --git a/desmume/src/addons.cpp b/src/addons.cpp similarity index 87% rename from desmume/src/addons.cpp rename to src/addons.cpp index 3aadbc369..d1abe9826 100644 --- a/desmume/src/addons.cpp +++ b/src/addons.cpp @@ -23,16 +23,11 @@ */ #include "addons.h" -#include -std::string CFlash_Path; -ADDON_CFLASH_MODE CFlash_Mode; - - -//char CFlashName[MAX_PATH]; -//char CFlashPath[MAX_PATH]; -//u8 CFlashUseRomPath = TRUE; -//u8 CFlashUsePath = TRUE; +char CFlashName[MAX_PATH]; +char CFlashPath[MAX_PATH]; +u8 CFlashUseRomPath = TRUE; +u8 CFlashUsePath = TRUE; char GBAgameName[MAX_PATH]; @@ -68,7 +63,6 @@ void addonsReset() BOOL addonsChangePak(u8 type) { - printf("addonsChangePak\n"); if (type > NDS_ADDON_COUNT) return FALSE; addon.close(); addon = addonList[type]; diff --git a/desmume/src/addons.h b/src/addons.h similarity index 88% rename from desmume/src/addons.h rename to src/addons.h index d011d2aee..0d14402bf 100644 --- a/desmume/src/addons.h +++ b/src/addons.h @@ -69,19 +69,14 @@ enum { NDS_ADDON_COUNT // use for counter addons - MUST TO BE LAST!!! }; -enum ADDON_CFLASH_MODE -{ - ADDON_CFLASH_MODE_Path, ADDON_CFLASH_MODE_File, ADDON_CFLASH_MODE_RomPath -}; - -extern ADDON_CFLASH_MODE CFlash_Mode; -extern std::string CFlash_Path; -inline bool CFlash_IsUsingPath() { return CFlash_Mode==ADDON_CFLASH_MODE_Path || CFlash_Mode==ADDON_CFLASH_MODE_RomPath; } - extern ADDONINTERFACE addon; // current pak extern ADDONINTERFACE addonList[NDS_ADDON_COUNT]; // lists pointer on paks extern u8 addon_type; // current type pak +extern char CFlashName[MAX_PATH]; // path to compact flash img file +extern char CFlashPath[MAX_PATH]; // path to compact flash directory +extern u8 CFlashUsePath; // true is used path from CFlashPath for cflash folder +extern u8 CFlashUseRomPath; // true is used path to rom file for cflash folder extern char GBAgameName[MAX_PATH]; // file name for GBA game (rom) extern void (*FeedbackON)(BOOL enable); // feedback on/off diff --git a/desmume/src/addons/compactFlash.cpp b/src/addons/compactFlash.cpp similarity index 93% rename from desmume/src/addons/compactFlash.cpp rename to src/addons/compactFlash.cpp index d65d6c757..094f8a170 100644 --- a/desmume/src/addons/compactFlash.cpp +++ b/src/addons/compactFlash.cpp @@ -24,8 +24,9 @@ */ #include "../addons.h" -#include #include +#ifdef EXPERIMENTAL_GBASLOT + #include "debug.h" #include #include @@ -101,7 +102,7 @@ static const int lfnPos[13] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; #define BYTESPERCLUS (512*SECPERCLUS) #define DIRENTSPERCLUS ((BYTESPERCLUS)/32) -BOOT_RECORD MBR; +static BOOT_RECORD MBR; static DIR_ENT *files,*dirEntries,**dirEntryPtr; static FILE_INFO *fileLink,*dirEntryLink; static u32 filesysFAT,filesysRootDir,filesysData; @@ -111,6 +112,7 @@ static DIR_ENT *extraDirEntries[SECPERFAT*256]; static int numFiles,maxLevel,numRootFiles; static int *dirEntriesInCluster, clusterNum, firstDirEntCluster, lastDirEntCluster, lastFileDataCluster; +static char *sRomPath; static int activeDirEnt=-1; static u32 bufferStart; static u32 fileStartLBA,fileEndLBA; @@ -119,8 +121,6 @@ static FILE * hFile; static char fpath[255+1]; static BOOL cflashDeviceEnabled = FALSE; -static std::string sFlashPath; - // =========================== BOOL inited; @@ -273,7 +273,6 @@ static void list_files(const char *filepath) { fname = (strlen(entry.cAlternateFileName)>0) ? entry.cAlternateFileName : entry.cFileName; add_file(fname, &entry, fileLevel); - CFLASHLOG("cflash added %s\n",fname); if (numFiles==MAXFILES-1) break; @@ -282,7 +281,7 @@ static void list_files(const char *filepath) if (strlen(fname)+strlen(filepath)+2 < 256) { sprintf(SubDir, "%s%c%s", filepath, FS_SEPARATOR, fname); - list_files(SubDir); + list_files(SubDir); } } } @@ -299,7 +298,7 @@ static void list_files(const char *filepath) } // Set up the MBR, FAT and DIR_ENTs -static BOOL cflash_build_fat() +static BOOL cflash_build_fat( void) { int i,j,k,l, clust,numClusters, @@ -310,6 +309,12 @@ static BOOL cflash_build_fat() fileLevel = -1; maxLevel = -1; + if (CFlashUseRomPath) + sRomPath = pathToROM; + else + sRomPath = CFlashPath; + + files = (DIR_ENT *) malloc(MAXFILES*sizeof(DIR_ENT)); if (files == NULL) return FALSE; fileLink = (FILE_INFO *) malloc(MAXFILES*sizeof(FILE_INFO)); @@ -331,7 +336,8 @@ static BOOL cflash_build_fat() numExtraEntries[i] = 0; } - list_files(sFlashPath.c_str()); + //COMMENT OUT THIS LINE TO STOP THE IRRITATING FILESYSTEM SCANNING BEHAVIOR + list_files(sRomPath); k = 0; clusterNum = rootCluster = (SECRESV + SECPERFAT)/SECPERCLUS; @@ -506,21 +512,11 @@ static BOOL cflash_init() if (inited) return FALSE; BOOL init_good = FALSE; - CFLASHLOG("CFlash_Mode: %d\n",CFlash_Mode); - - if (CFlash_Mode == ADDON_CFLASH_MODE_RomPath) - { - sFlashPath = pathToROM; - INFO("Using CFlash directory of rom: %s\n", sFlashPath.c_str()); - } - else if(CFlash_Mode == ADDON_CFLASH_MODE_Path) - { - sFlashPath = CFlash_Path; - INFO("Using CFlash directory: %s\n", sFlashPath.c_str()); - } - - if(CFlash_IsUsingPath()) + if (CFlashUsePath) { + if (!strlen(CFlashPath)) CFlashUseRomPath = TRUE; + if (CFlashUseRomPath) + CFLASHLOG("Using CFlash directory of rom: %s\n", pathToROM); cflashDeviceEnabled = FALSE; currLBA = 0; @@ -528,10 +524,8 @@ static BOOL cflash_init() fclose(hFile); activeDirEnt = -1; fileStartLBA = fileEndLBA = 0xFFFFFFFF; - if (!cflash_build_fat()) { - CFLASHLOG("FAILED cflash_build_fat\n"); + if (!cflash_build_fat()) return FALSE; - } cf_reg_sts = 0x58; // READY cflashDeviceEnabled = TRUE; @@ -539,9 +533,9 @@ static BOOL cflash_init() } else { - sFlashPath = CFlash_Path; - INFO("Using CFlash disk image file %s\n", sFlashPath.c_str()); - disk_image = OPEN_FN( sFlashPath.c_str(), OPEN_MODE); + if (!strlen(CFlashName)) return FALSE; + CFLASHLOG("Using CFlash disk image file %s\n", CFlashName); + disk_image = OPEN_FN( CFlashName, OPEN_MODE); if ( disk_image != -1) { @@ -559,7 +553,7 @@ static BOOL cflash_init() } else // TODO: create image if not exist - CFLASHLOG("Failed to open file %s: \"%s\"\n", sFlashPath.c_str(), strerror( errno)); + CFLASHLOG("Failed to open file %s: \"%s\"\n", CFlashName, strerror( errno)); } // READY @@ -651,7 +645,7 @@ static u16 fread_buffered(int dirent,u32 cluster,u32 offset) if (activeDirEnt != -1) fclose(hFile); - strncpy(fpath,sFlashPath.c_str(),ARRAY_SIZE(fpath)); + strncpy(fpath,sRomPath,ARRAY_SIZE(fpath)); strncat(fpath,DIR_SEP,ARRAY_SIZE(fpath)-strlen(fpath)); resolve_path(dirent); @@ -659,7 +653,6 @@ static u16 fread_buffered(int dirent,u32 cluster,u32 offset) fatstring_to_asciiz(dirent,fname,NULL); strncat(fpath,fname,ARRAY_SIZE(fpath)-strlen(fpath)); - CFLASHLOG("CFLASH Opening %s\n",fpath); hFile = fopen(fpath, "rb"); if (!hFile) return 0; bufferStart = offset; @@ -693,7 +686,7 @@ static unsigned int cflash_read(unsigned int address) case CF_REG_DATA: if (cf_reg_cmd == CF_CMD_READ) { - if (!CFlash_IsUsingPath()) + if (!CFlashUsePath) { if ( disk_image != -1) { @@ -839,7 +832,7 @@ static void cflash_write(unsigned int address,unsigned int data) case CF_REG_DATA: if (cf_reg_cmd == CF_CMD_WRITE) { - if (!CFlash_IsUsingPath()) + if (!CFlashUsePath) { sector_data[sector_write_index] = (data >> 0) & 0xff; sector_data[sector_write_index + 1] = (data >> 8) & 0xff; @@ -915,11 +908,11 @@ static void cflash_write(unsigned int address,unsigned int data) static void cflash_close( void) { if (!inited) return; - if (!CFlash_IsUsingPath()) + if (!CFlashUsePath) { - if (disk_image != -1) + if ( disk_image != -1) { - CLOSE_FN(disk_image); + CLOSE_FN( disk_image); disk_image = -1; } } @@ -954,6 +947,8 @@ static void cflash_close( void) static BOOL CFlash_init(void) { + CFlashUseRomPath = TRUE; + CFlashUsePath = TRUE; return TRUE; } @@ -1006,6 +1001,23 @@ static void CFlash_info(char *info) { strcpy(info, "Compact Flash memory in slot"); } +#else +static BOOL CFlash_init(void) { return TRUE; } +static void CFlash_reset(void) {} +static void CFlash_close(void) {} +static void CFlash_config(void){} +static void CFlash_write08(u32 adr, u8 val){} +static void CFlash_write16(u32 adr, u16 val){} +static void CFlash_write32(u32 adr, u32 val){} +static u8 CFlash_read08(u32 adr){return (0);} +static u16 CFlash_read16(u32 adr){return (0);} +static u32 CFlash_read32(u32 adr){return (0);} + +static void CFlash_info(char *info) +{ + strcpy(info, "Compact Flash memory in slot"); +} +#endif ADDONINTERFACE addonCFlash = { "Compact Flash", diff --git a/desmume/src/addons/gbagame.cpp b/src/addons/gbagame.cpp similarity index 100% rename from desmume/src/addons/gbagame.cpp rename to src/addons/gbagame.cpp diff --git a/desmume/src/addons/none.cpp b/src/addons/none.cpp similarity index 100% rename from desmume/src/addons/none.cpp rename to src/addons/none.cpp diff --git a/desmume/src/addons/rumblepak.cpp b/src/addons/rumblepak.cpp similarity index 100% rename from desmume/src/addons/rumblepak.cpp rename to src/addons/rumblepak.cpp diff --git a/desmume/src/arm_instructions.cpp b/src/arm_instructions.cpp similarity index 99% rename from desmume/src/arm_instructions.cpp rename to src/arm_instructions.cpp index a0b19d056..a377189e7 100644 --- a/desmume/src/arm_instructions.cpp +++ b/src/arm_instructions.cpp @@ -7726,16 +7726,8 @@ TEMPLATE static u32 FASTCALL OP_MRC() //--------------SWI------------------------------- TEMPLATE static u32 FASTCALL OP_SWI() { - u32 swinum = (cpu->instruction>>16)&0xFF; - - //ideas-style debug prints - if(swinum==0xFC) { - IdeasLog(cpu); - return 0; - } - if(cpu->swi_tab) { - swinum &= 0x1F; + u32 swinum = (cpu->instruction>>16)&0x1F; return cpu->swi_tab[swinum]() + 3; } else { /* TODO (#1#): translocated SWI vectors */ diff --git a/desmume/src/arm_instructions.h b/src/arm_instructions.h similarity index 100% rename from desmume/src/arm_instructions.h rename to src/arm_instructions.h diff --git a/desmume/src/armcpu.cpp b/src/armcpu.cpp similarity index 100% rename from desmume/src/armcpu.cpp rename to src/armcpu.cpp diff --git a/desmume/src/armcpu.h b/src/armcpu.h similarity index 100% rename from desmume/src/armcpu.h rename to src/armcpu.h diff --git a/desmume/src/bios.cpp b/src/bios.cpp similarity index 100% rename from desmume/src/bios.cpp rename to src/bios.cpp diff --git a/desmume/src/bios.h b/src/bios.h similarity index 100% rename from desmume/src/bios.h rename to src/bios.h diff --git a/desmume/src/bits.h b/src/bits.h similarity index 100% rename from desmume/src/bits.h rename to src/bits.h diff --git a/desmume/src/build.bat b/src/build.bat similarity index 100% rename from desmume/src/build.bat rename to src/build.bat diff --git a/src/cflash.cpp b/src/cflash.cpp new file mode 100644 index 000000000..a5bb8697f --- /dev/null +++ b/src/cflash.cpp @@ -0,0 +1,880 @@ +/* Copyright (C) 2006 yopyop + yopyop156@ifrance.com + yopyop156.ifrance.com + + Copyright (C) 2006-2008 The DeSmuME Team + + This file is part of DeSmuME + + DeSmuME is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + DeSmuME is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with DeSmuME; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +/* + CFLASH.C + CompactFlash/FAT emulation routines for DeSmuME + /Mic, 2006 + + Logical memory layout: + + ---------------------- + | MBR | + ---------------------- + | FAT | + ---------------------- + | Root entries | + ---------------------- + | Subdirectories | + ---------------------- + | File data | + ---------------------- + +*/ +#include "common.h" + +#ifndef EXPERIMENTAL_GBASLOT + +#include +#include +#include +#include + +#include +#include +#ifdef WIN32 +#include +#define OPEN_MODE _O_RDWR | _O_BINARY + +#define OPEN_FN _open +#define CLOSE_FN _close +#define LSEEK_FN _lseek +#define WRITE_FN _write +#define READ_FN _read +#else +#include +#define OPEN_MODE O_RDWR + +#define OPEN_FN open +#define CLOSE_FN close +#define LSEEK_FN lseek +#define WRITE_FN write +#define READ_FN read +#endif + +#include "types.h" +#include "fs.h" +#include "MMU.h" +#include "cflash.h" +#include "NDSSystem.h" +#include "debug.h" + +static int use_disk_image_file = 0; + +/* Set up addresses for GBAMP */ +#define CF_REG_DATA 0x9000000 +#define CF_REG_ERR 0x9020000 +#define CF_REG_SEC 0x9040000 +#define CF_REG_LBA1 0x9060000 +#define CF_REG_LBA2 0x9080000 +#define CF_REG_LBA3 0x90A0000 +#define CF_REG_LBA4 0x90C0000 +#define CF_REG_CMD 0x90E0000 +#define CF_REG_STS 0x98C0000 + +// CF Card commands +#define CF_CMD_LBA 0xE0 +#define CF_CMD_READ 0x20 +#define CF_CMD_WRITE 0x30 + + +static int disk_image = -1; +static off_t file_size; + +static u16 cf_reg_sts, cf_reg_lba1, cf_reg_lba2, + cf_reg_lba3, cf_reg_lba4, cf_reg_cmd; +static off_t currLBA; + +#define SECPERFAT 128 +#define SECPERCLUS 16 +#define MAXFILES 32768 +#define SECRESV 2 +#define NUMSECTORS 0x80000 +#define NUMCLUSTERS (NUMSECTORS/SECPERCLUS) +#define BYTESPERCLUS (512*SECPERCLUS) +#define DIRENTSPERCLUS ((BYTESPERCLUS)/32) + + +static BOOT_RECORD MBR; +static DIR_ENT *files,*dirEntries,**dirEntryPtr; +static FILE_INFO *fileLink,*dirEntryLink; +static u32 filesysFAT,filesysRootDir,filesysData; +static u16 FAT16[SECPERFAT*256]; +static u16 numExtraEntries[SECPERFAT*256]; +static DIR_ENT *extraDirEntries[SECPERFAT*256]; +static int numFiles,maxLevel,numRootFiles; +static int *dirEntriesInCluster, clusterNum, firstDirEntCluster, + lastDirEntCluster, lastFileDataCluster; +static char *sRomPath; +static int activeDirEnt=-1; +static u32 bufferStart; +static u32 fileStartLBA,fileEndLBA; +static u16 freadBuffer[256]; +static FILE * hFile; +static char fpath[255+1]; +static BOOL cflashDeviceEnabled = FALSE; + +static int lfn_checksum( void) { + int i; + u8 chk; + + chk = 0; + for (i=0; i < (NAME_LEN + EXT_LEN); i++) { + chk = ((chk & 1) ? 0x80 : 0) + (chk >> 1) + (i < NAME_LEN ? files[numFiles].name[i] : files[numFiles].ext[i - NAME_LEN]); + } + return chk; +} + + +static const int lfnPos[13] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; + + +/* Add a DIR_ENT for the files */ +static void add_file(char *fname, FsEntry * entry, int fileLevel) { + int i,j,k,n; + u8 chk; + + if (numFiles < MAXFILES-1) { + if (strcmp(fname,"..") != 0) { + for (i=strlen(fname)-1; i>=0; i--) + if (fname[i]=='.') break; + if ((i==0)&&(strcmp(fname,".")==0)) i = 1; + if (i<0) i = strlen(fname); + for (j=0; j=strlen(fname)) break; + files[numFiles].ext[j] = fname[j+i+1]; + } + for (; j<3; j++) + files[numFiles].ext[j] = 0x20; + + fileLink[fileLevel].filesInDir += 1; + + // See if LFN entries need to be added + if (strlen(entry->cAlternateFileName)>0) { + char *p = NULL; + + chk = lfn_checksum(); + k = (strlen(entry->cFileName)/13) + (((strlen(entry->cFileName)%13)!=0)?1:0); + numFiles += k; + + fileLink[fileLevel].filesInDir += k; + + n = 0; + j = 13; + for (i=0; (size_t)icFileName); i++) { + if (j == 13) { + n++; + p = (char*)&files[numFiles-n].name[0]; + fileLink[numFiles-n].parent = fileLevel; + p[0] = n; + ((DIR_ENT*)p)->attrib = ATTRIB_LFN; + p[0xD] = chk; + j = 0; + } + *(p + lfnPos[j]) = entry->cFileName[i]; + *(p + lfnPos[j]+1) = 0; + j++; + } + for (; j<13; j++) { + *(p + lfnPos[j]) = entry->cFileName[i]; + *(p + lfnPos[j]+1) = 0; + } + if (p != NULL) + p[0] |= 0x40; // END + for (i=strlen(fname)-1; i>=0; i--) + if (fname[i]=='.') break; + if ((i==0)&&(strcmp(fname,".")==0)) i = 1; + if (i<0) i = strlen(fname); + for (j=0; j=strlen(fname)) break; + files[numFiles].ext[j] = fname[j+i+1]; + } + for (; j<3; j++) + files[numFiles].ext[j] = 0x20; + } + + files[numFiles].fileSize = entry->fileSize; + + if (entry->flags & FS_IS_DIR) { + if (strcmp(fname,".")==0) + fileLink[numFiles].level = maxLevel; + else + fileLink[numFiles].level = maxLevel+1; + files[numFiles].attrib = ATTRIB_DIR; + } else { + files[numFiles].attrib = 0; + } + + fileLink[numFiles].parent = fileLevel; + + numFiles++; + } else if (fileLevel > 0) { + fileLink[fileLevel].filesInDir += 1; + strncpy((char*)&files[numFiles].name[0],".. ",NAME_LEN); + strncpy((char*)&files[numFiles].ext[0]," ",EXT_LEN); + fileLink[numFiles].parent = fileLevel; + files[numFiles].attrib = 0x10; + numFiles++; + } + } +} + + +/* List all files and subdirectories recursively */ +static void list_files(const char *filepath) { + char DirSpec[255+1], SubDir[255+1]; + FsEntry entry; + void * hFind; + char *fname; + u32 dwError; + int fileLevel; + + maxLevel++; + fileLevel = maxLevel; + + strncpy(DirSpec, filepath, ARRAY_SIZE(DirSpec)); + DirSpec[255] = 0 ; /* hard limit the string here */ + + hFind = FsReadFirst(DirSpec, &entry); + if (hFind == NULL) + return; + + fname = (strlen(entry.cAlternateFileName)>0) ? entry.cAlternateFileName : entry.cFileName; + add_file(fname, &entry, fileLevel); + + while (FsReadNext(hFind, &entry) != 0) { + fname = (strlen(entry.cAlternateFileName)>0) ? entry.cAlternateFileName : entry.cFileName; + add_file(fname, &entry, fileLevel); + + if (numFiles==MAXFILES-1) + break; + + if ((entry.flags & FS_IS_DIR) && (strcmp(fname, ".")) && (strcmp(fname, ".."))) { + if (strlen(fname)+strlen(filepath)+2 < 256) { + sprintf(SubDir, "%s%c%s", filepath, FS_SEPARATOR, fname); + list_files(SubDir); + } + } + } + + dwError = FsError(); + FsClose(hFind); + if (dwError != FS_ERR_NO_MORE_FILES) + return; + + if (numFiles < MAXFILES) { + fileLink[numFiles].parent = fileLevel; + files[numFiles++].name[0] = 0; + } +} + + + +/* Set up the MBR, FAT and DIR_ENTs */ +static BOOL cflash_build_fat( void) { + int i,j,k,l, + clust,numClusters, + clusterNum2,rootCluster; + int fileLevel; + + numFiles = 0; + fileLevel = -1; + maxLevel = -1; + + sRomPath = pathToROM; + files = (DIR_ENT *) malloc(MAXFILES*sizeof(DIR_ENT)); + if (files == NULL) + return FALSE; + fileLink = (FILE_INFO *) malloc(MAXFILES*sizeof(FILE_INFO)); + if (fileLink == NULL) { + free(files); + return FALSE; + } + + for (i=0; i>8; + clust += l; + numClusters += l; + } + } else { + dirEntries[k-1].startCluster = clusterNum; + } + } + if (i==0) numRootFiles++; + dirEntriesInCluster[clusterNum]++; + if (dirEntriesInCluster[clusterNum]==256) { + clusterNum++; + } + } + } + clusterNum = clusterNum2 + ((fileLink[i].filesInDir)>>8) + 1; + numClusters++; + } + + // Free the file indexing buffer + free(files); + free(fileLink); + + // Set up the MBR + MBR.bytesPerSector = 512; + MBR.numFATs = 1; + /* replaced strcpy with strncpy. It doesnt matter here, as the strings are constant */ + /* but we should extingish all unrestricted strcpy,strcat from the project */ + strncpy((char*)&MBR.OEMName[0],"DESMUM",8); + strncpy((char*)&MBR.fat16.fileSysType[0],"FAT16 ",8); + MBR.reservedSectors = SECRESV; + MBR.numSectors = 524288; + MBR.numSectorsSmall = 0; + MBR.sectorsPerCluster = SECPERCLUS; + MBR.sectorsPerFAT = SECPERFAT; + MBR.rootEntries = 512; + MBR.fat16.signature = 0xAA55; + MBR.mediaDesc = 1; + + filesysFAT = 0 + MBR.reservedSectors; + filesysRootDir = filesysFAT + (MBR.numFATs * MBR.sectorsPerFAT); + filesysData = filesysRootDir + ((MBR.rootEntries * sizeof(DIR_ENT)) / 512); + + // Set up the cluster values for all subdirectories + clust = filesysData / SECPERCLUS; + firstDirEntCluster = clust; + for (i=1; i rootCluster) + dirEntries[i].startCluster += clust-rootCluster; + } + } + lastDirEntCluster = clust+numClusters-1; + + // Set up the cluster values for all files + clust += numClusters; //clusterNum; + for (i=0; i 0) { + if (dirEntries[i].startCluster+j < MAXFILES) + FAT16[dirEntries[i].startCluster+j] = dirEntries[i].startCluster+j+1; + j++; + l -= (512*16); + } + if ((dirEntries[i].attrib & ATTRIB_DIR)==0) { + if (dirEntries[i].startCluster+j < MAXFILES) + FAT16[dirEntries[i].startCluster+j] = 0xFFFF; + } + k = dirEntries[i].startCluster+j; + } + } + + for (i=(filesysData/SECPERCLUS); iname[i] == ' ') break; + out[i] = pd->name[i]; + } + if ((pd->attrib & 0x10)==0) { + out[i++] = '.'; + for (j=0; jext[j] == ' ') break; + out[i++] = pd->ext[j]; + } + } + out[i] = '\0'; +} + + + +/* Resolve the path of a files by working backwards through the directory entries */ +static void resolve_path(int dirent) { + int i; + char dirname[128]; + + while (dirEntryLink[dirent].parent > 0) { + for (i=0; i= bufferStart + 512)) { + if (!hFile) { + CFLASHLOG("fread_buffered with hFile null with" + "offset %lu and bufferStart %lu\n", + offset, bufferStart); + return 0; + } + fseek(hFile, offset, SEEK_SET); + elems_read += fread(&freadBuffer, 1, 512, hFile); + bufferStart = offset; + } + + return freadBuffer[(offset-bufferStart)>>1]; + } + if (activeDirEnt != -1) + fclose(hFile); + + strncpy(fpath,sRomPath,ARRAY_SIZE(fpath)); + strncat(fpath,DIR_SEP,ARRAY_SIZE(fpath)-strlen(fpath)); + + resolve_path(dirent); + + fatstring_to_asciiz(dirent,fname,NULL); + strncat(fpath,fname,ARRAY_SIZE(fpath)-strlen(fpath)); + + hFile = fopen(fpath, "rb"); + if (!hFile) return 0; + bufferStart = offset; + fseek(hFile, offset, SEEK_SET); + elems_read += fread(&freadBuffer, 1, 512, hFile); + + bufferStart = offset; + activeDirEnt = dirent; + fileStartLBA = (dirEntries[dirent].startCluster*512*SECPERCLUS); + fileEndLBA = fileStartLBA + dirEntries[dirent].fileSize; + + return freadBuffer[(offset-bufferStart)>>1]; +} + +unsigned int +cflash_read(unsigned int address) { + unsigned int ret_value = 0; + size_t elems_read = 0; +#if 0 /* used by next if 0 block */ +#define BUFFERED_BLOCK_SIZE 512 + static u8 block_buffer[BUFFERED_BLOCK_SIZE]; + static s32 buffered_start_index = -1; +#endif + + switch ( address) { + case CF_REG_STS: + ret_value = cf_reg_sts; + break; + + case CF_REG_DATA: + if (cf_reg_cmd == CF_CMD_READ) { + if ( use_disk_image_file) { + if ( disk_image != -1) { + u8 data[2]; +#if 0 + if ( currLBA < buffered_start_index || + currLBA >= (buffered_start_index + BUFFERED_BLOCK_SIZE)) { + size_t read_bytes = 0; + LSEEK_FN( disk_image, currLBA, SEEK_SET); + + while ( read_bytes < BUFFERED_BLOCK_SIZE) { + size_t cur_read = + READ_FN( disk_image, &block_buffer[read_bytes], + BUFFERED_BLOCK_SIZE - read_bytes); + + if ( cur_read == -1) { + CFLASHLOG( "Error during read: %s\n", strerror(errno) ); + break; + } + read_bytes += cur_read; + } + + CFLASHLOG( "Read %d bytes\n", read_bytes); + + buffered_start_index = currLBA; + } + data[0] = block_buffer[currLBA - buffered_start_index]; + data[1] = block_buffer[currLBA + 1 - buffered_start_index]; +#else + LSEEK_FN( disk_image, currLBA, SEEK_SET); + elems_read += READ_FN( disk_image, data, 2); +#endif + ret_value = data[1] << 8 | + data[0]; + } + currLBA += 2; + } + else { + unsigned char *p; + int i; + u32 cluster,cluster2,cluster3,fileLBA; + cluster = (currLBA / (512 * SECPERCLUS)); + cluster2 = (((currLBA/512) - filesysData) / SECPERCLUS) + 2; + + // Reading from the MBR + if (currLBA < 512) { + p = (unsigned char*)&MBR; + ret_value = T1ReadWord(p, currLBA); + + // Reading the FAT + } else if (((u32)currLBA >= filesysFAT*512) && ((u32)currLBA < filesysRootDir*512)) { + p = (unsigned char*)&FAT16[0]; + ret_value = T1ReadWord(p, currLBA - filesysFAT * 512); + + // Reading directory entries + } else if (((u32)currLBA >= filesysRootDir*512) && + (cluster <= (u32)lastDirEntCluster)) { + cluster3 = ((currLBA - (SECRESV * 512)) / (512 * SECPERCLUS)); + i = (currLBA-(((cluster3-(filesysRootDir/SECPERCLUS))*SECPERCLUS+filesysRootDir)*512)); //(currLBA - cluster*BYTESPERCLUS); + if (i < (dirEntriesInCluster[cluster3]*32)) { + + p = (unsigned char*)dirEntryPtr[cluster3]; + ret_value = T1ReadWord(p, i); + } else { + i /= 32; + i -= dirEntriesInCluster[cluster3]; + if ((i>=0)&&(i (u32)lastDirEntCluster) && (cluster2 <= (u32)lastFileDataCluster)) { //else if ((cluster>lastDirEntCluster)&&(cluster<=lastFileDataCluster)) { + fileLBA = currLBA - (filesysData-32)*512; // 32 = # sectors used for the root entries + + // Check if the read is from the currently opened file + if ((fileLBA >= fileStartLBA) && (fileLBA < fileEndLBA)) { + cluster = (fileLBA / (512 * SECPERCLUS)); + ret_value = fread_buffered(activeDirEnt,cluster-dirEntries[activeDirEnt].startCluster,(fileLBA-fileStartLBA)&(BYTESPERCLUS-1)); + } else { + for (i=0; i=(u32)(dirEntries[i].startCluster*512*SECPERCLUS)) && + (fileLBA <(dirEntries[i].startCluster*512*SECPERCLUS)+dirEntries[i].fileSize) && + ((dirEntries[i].attrib & (ATTRIB_DIR|ATTRIB_LFN))==0)) { + cluster = (fileLBA / (512 * SECPERCLUS)); + ret_value = fread_buffered(i,cluster-dirEntries[i].startCluster,fileLBA&(BYTESPERCLUS-1)); + break; + } + } + } + } + currLBA += 2; + } + } + break; + + case CF_REG_CMD: + break; + + case CF_REG_LBA1: + ret_value = cf_reg_lba1; + break; + } + + return ret_value; +} + +void +cflash_write(unsigned int address,unsigned int data) { + static u8 sector_data[512]; + static u32 sector_write_index = 0; + + switch ( address) { + case CF_REG_STS: + cf_reg_sts = data&0xFFFF; + break; + + case CF_REG_DATA: + if ( use_disk_image_file) { + if (cf_reg_cmd == CF_CMD_WRITE) { + sector_data[sector_write_index] = (data >> 0) & 0xff; + sector_data[sector_write_index + 1] = (data >> 8) & 0xff; + + sector_write_index += 2; + + if ( sector_write_index == 512) { + CFLASHLOG( "Write sector to %ld\n", currLBA); + + if ( currLBA + 512 < file_size) { + size_t written = 0; + + if ( disk_image != -1) { + LSEEK_FN( disk_image, currLBA, SEEK_SET); + + while( written < 512) { + size_t cur_write = + WRITE_FN( disk_image, §or_data[written], 512 - written); + written += cur_write; + + if ( cur_write == (size_t)-1) { + break; + } + } + } + + CFLASHLOG("Wrote %u bytes\n", written); + } + currLBA += 512; + sector_write_index = 0; + } + } + } + break; + + case CF_REG_CMD: + cf_reg_cmd = data&0xFF; + cf_reg_sts = 0x58; // READY + break; + + case CF_REG_LBA1: + cf_reg_lba1 = data&0xFF; + currLBA = (currLBA&0xFFFFFF00)| cf_reg_lba1; + break; + + case CF_REG_LBA2: + cf_reg_lba2 = data&0xFF; + currLBA = (currLBA&0xFFFF00FF)|(cf_reg_lba2<<8); + break; + + case CF_REG_LBA3: + cf_reg_lba3 = data&0xFF; + currLBA = (currLBA&0xFF00FFFF)|(cf_reg_lba3<<16); + break; + + case CF_REG_LBA4: + cf_reg_lba4 = data&0xFF; + + if ( (cf_reg_lba4 & 0xf0) == CF_CMD_LBA) { + currLBA = (currLBA&0x00FFFFFF)|((cf_reg_lba4&0x0F)<<24); + currLBA *= 512; + sector_write_index = 0; + } + break; + } +} + +void +cflash_close( void) { + if ( use_disk_image_file) { + if ( disk_image != -1) { + CLOSE_FN( disk_image); + disk_image = -1; + } + } + else { + int i; + + if (cflashDeviceEnabled) { + cflashDeviceEnabled = FALSE; + + for (i=0; i 0) - return RomName.substr(0,x); - else return RomName; } \ No newline at end of file diff --git a/desmume/src/common.h b/src/common.h similarity index 97% rename from desmume/src/common.h rename to src/common.h index 084a39aec..1a0fa1ca2 100644 --- a/desmume/src/common.h +++ b/src/common.h @@ -26,11 +26,9 @@ #include #include "types.h" -#include extern u8 gba_header_data_0x04[156]; const char* GetRomName(); //adelikat: return the name of the Rom currently loaded -std::string GetRomNameWithoutExtension(); void SetRomName(const char *filename); @@ -77,6 +75,7 @@ void SetRomName(const char *filename); extern void GetINIPath(); extern void WritePrivateProfileInt(char* appname, char* keyname, int val, char* file); + #define EXPERIMENTAL_GBASLOT 1 #else // non Windows #define sscanf_s sscanf diff --git a/desmume/src/cp15.cpp b/src/cp15.cpp similarity index 100% rename from desmume/src/cp15.cpp rename to src/cp15.cpp diff --git a/desmume/src/cp15.h b/src/cp15.h similarity index 100% rename from desmume/src/cp15.h rename to src/cp15.h diff --git a/desmume/src/ctrlssdl.cpp b/src/ctrlssdl.cpp similarity index 100% rename from desmume/src/ctrlssdl.cpp rename to src/ctrlssdl.cpp diff --git a/desmume/src/ctrlssdl.h b/src/ctrlssdl.h similarity index 100% rename from desmume/src/ctrlssdl.h rename to src/ctrlssdl.h diff --git a/desmume/src/debug.cpp b/src/debug.cpp similarity index 91% rename from desmume/src/debug.cpp rename to src/debug.cpp index 36b6bc820..93f3625a6 100644 --- a/desmume/src/debug.cpp +++ b/src/debug.cpp @@ -21,8 +21,6 @@ #include #include -#include "MMU.h" -#include "armcpu.h" std::vector Logger::channels; @@ -101,17 +99,3 @@ void Logger::log(unsigned int channel, const char * file, unsigned int line, voi channels[channel]->setCallback(callback); } - -void IdeasLog(armcpu_t* cpu) -{ - u32 adr = cpu->R[0]; - printf("EMULOG%c: ",cpu->proc_ID==0?'9':'7'); - for(;;) { - u8 c = MMU_read8(cpu->proc_ID,adr); - adr++; - if(!c) break; - printf("%c",c); - } - printf("\n"); -} - diff --git a/desmume/src/debug.h b/src/debug.h similarity index 98% rename from desmume/src/debug.h rename to src/debug.h index 71a74d4fc..99dea52fc 100644 --- a/desmume/src/debug.h +++ b/src/debug.h @@ -24,8 +24,6 @@ #include #include -struct armcpu_t; - class Logger { protected: void (*callback)(const Logger& logger, const char * format); @@ -114,6 +112,4 @@ public: #define INFOC(channel, ...) Logger::log(channel, __FILE__, __LINE__, __VA_ARGS__) #define INFO(...) INFOC(10, __VA_ARGS__) -void IdeasLog(armcpu_t* cpu); - #endif diff --git a/desmume/src/desmume.mk b/src/desmume.mk similarity index 100% rename from desmume/src/desmume.mk rename to src/desmume.mk diff --git a/desmume/src/driver.h b/src/driver.h similarity index 100% rename from desmume/src/driver.h rename to src/driver.h diff --git a/desmume/src/dscard.h b/src/dscard.h similarity index 100% rename from desmume/src/dscard.h rename to src/dscard.h diff --git a/src/fat.h b/src/fat.h new file mode 100644 index 000000000..046c1a593 --- /dev/null +++ b/src/fat.h @@ -0,0 +1,131 @@ +/* + FAT.H + Mic, 2006 + Structures taken from Michael Chisholm's FAT library +*/ + +#ifndef __FAT_H__ +#define __FAT_H__ + +#include "types.h" +#include "PACKED.h" +#include "PACKED_END.h" + +#define ATTRIB_DIR 0x10 +#define ATTRIB_LFN 0x0F + +#define FILE_FREE 0xE5 +/* Name and extension maximum length */ +#define NAME_LEN 8 +#define EXT_LEN 3 + +// Boot Sector - must be packed +#if defined(_MSC_VER) || defined(__INTEL_COMPILER) +#pragma pack(push, 1) +#define DIR_SEP "\\" +typedef struct +{ + u8 jmpBoot[3]; + u8 OEMName[8]; + // BIOS Parameter Block + u16 bytesPerSector; + u8 sectorsPerCluster; + u16 reservedSectors; + u8 numFATs; + u16 rootEntries; + u16 numSectorsSmall; + u8 mediaDesc; + u16 sectorsPerFAT; + u16 sectorsPerTrk; + u16 numHeads; + u32 numHiddenSectors; + u32 numSectors; + struct + { + // Ext BIOS Parameter Block for FAT16 + u8 driveNumber; + u8 reserved1; + u8 extBootSig; + u32 volumeID; + u8 volumeLabel[11]; + u8 fileSysType[8]; + // Bootcode + u8 bootCode[448]; + u16 signature; + } fat16; +} __PACKED BOOT_RECORD; +#pragma pack(pop) + +// Directory entry - must be packed +#pragma pack(push, 1) +typedef struct +{ + u8 name[NAME_LEN]; + u8 ext[EXT_LEN]; + u8 attrib; + u8 reserved; + u8 cTime_ms; + u16 cTime; + u16 cDate; + u16 aDate; + u16 startClusterHigh; + u16 mTime; + u16 mDate; + u16 startCluster; + u32 fileSize; +} __PACKED DIR_ENT; +#pragma pack(pop) +#else +#define DIR_SEP "/" +typedef struct +{ + u8 jmpBoot[3]; + u8 OEMName[8]; + // BIOS Parameter Block + u16 bytesPerSector; + u8 sectorsPerCluster; + u16 reservedSectors; + u8 numFATs; + u16 rootEntries; + u16 numSectorsSmall; + u8 mediaDesc; + u16 sectorsPerFAT; + u16 sectorsPerTrk; + u16 numHeads; + u32 numHiddenSectors; + u32 numSectors; + struct + { + // Ext BIOS Parameter Block for FAT16 + u8 driveNumber; + u8 reserved1; + u8 extBootSig; + u32 volumeID; + u8 volumeLabel[11]; + u8 fileSysType[8]; + // Bootcode + u8 bootCode[448]; + u16 signature; + } fat16; +} __PACKED BOOT_RECORD; + +// Directory entry - must be packed +typedef struct +{ + u8 name[NAME_LEN]; + u8 ext[EXT_LEN]; + u8 attrib; + u8 reserved; + u8 cTime_ms; + u16 cTime; + u16 cDate; + u16 aDate; + u16 startClusterHigh; + u16 mTime; + u16 mDate; + u16 startCluster; + u32 fileSize; +} __PACKED DIR_ENT; +#endif + +#endif diff --git a/desmume/src/fs-linux.cpp b/src/fs-linux.cpp similarity index 100% rename from desmume/src/fs-linux.cpp rename to src/fs-linux.cpp diff --git a/desmume/src/fs-windows.cpp b/src/fs-windows.cpp similarity index 100% rename from desmume/src/fs-windows.cpp rename to src/fs-windows.cpp diff --git a/desmume/src/fs.h b/src/fs.h similarity index 100% rename from desmume/src/fs.h rename to src/fs.h diff --git a/desmume/src/gdbstub.h b/src/gdbstub.h similarity index 100% rename from desmume/src/gdbstub.h rename to src/gdbstub.h diff --git a/desmume/src/gdbstub/Makefile.am b/src/gdbstub/Makefile.am similarity index 100% rename from desmume/src/gdbstub/Makefile.am rename to src/gdbstub/Makefile.am diff --git a/desmume/src/gdbstub/gdbstub.cpp b/src/gdbstub/gdbstub.cpp similarity index 100% rename from desmume/src/gdbstub/gdbstub.cpp rename to src/gdbstub/gdbstub.cpp diff --git a/desmume/src/gdbstub/gdbstub_internal.h b/src/gdbstub/gdbstub_internal.h similarity index 100% rename from desmume/src/gdbstub/gdbstub_internal.h rename to src/gdbstub/gdbstub_internal.h diff --git a/desmume/src/gfx3d.cpp b/src/gfx3d.cpp similarity index 89% rename from desmume/src/gfx3d.cpp rename to src/gfx3d.cpp index 17cb28688..1a8bf3387 100644 --- a/desmume/src/gfx3d.cpp +++ b/src/gfx3d.cpp @@ -60,13 +60,6 @@ But since we're not sure how we'll eventually want this, I am leaving it sort of in this function: */ static void gfx3d_doFlush(); -#ifdef USE_GEOMETRY_FIFO_EMULATION -#define GFX_DELAY(x) MMU.gfx3dCycles = nds.cycles + (2*x) -#define GFX_DELAY_M2(x) MMU.gfx3dCycles += (2*x) -#else -#define GFX_DELAY(x) -#define GFX_DELAY_M2(x) -#endif using std::max; using std::min; @@ -146,11 +139,6 @@ static float float10Table[1024]; static float float10RelTable[1024]; static float normalTable[1024]; -#ifndef NOSSE2 -float ALIGN(16) _fix2float_divizor_mask[4] = { 4096.f, 4096.f, 4096.f, 4096.f }; -float ALIGN(16) _fix10_2float_divizor_mask[4] = { 512.f, 512.f, 512.f, 512.f }; -#endif - #define fix2float(v) (((float)((s32)(v))) / (float)(1<<12)) #define fix10_2float(v) (((float)((s32)(v))) / (float)(1<<9)) @@ -196,14 +184,9 @@ static float _t=0, _s=0; static float last_t, last_s; static u32 clCmd = 0; static u32 clInd = 0; - #ifdef USE_GEOMETRY_FIFO_EMULATION static u32 clInd2 = 0; -static bool isSwapBuffers = false; -bool isVBlank = false; -bool bWaitForPolys = false; #endif - static u32 BTind = 0; static u32 PTind = 0; //static CACHE_ALIGN float BTcoords[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; @@ -249,7 +232,6 @@ POLYLIST* polylists = NULL; POLYLIST* polylist = NULL; VERTLIST* vertlists = NULL; VERTLIST* vertlist = NULL; -int polygonListCompleted = 0; int listTwiddle = 1; int triStripToggle; @@ -365,19 +347,11 @@ void gfx3d_reset() gfx3d.clearDepth = gfx3d_extendDepth_15_to_24(0x7FFF); GFX_FIFOclear(); - -#ifdef USE_GEOMETRY_FIFO_EMULATION - clInd2 = 0; - isSwapBuffers = false; - isVBlank = false; - bWaitForPolys = false; -#endif } void gfx3d_glViewPort(u32 v) { viewport = v; - GFX_DELAY(1); } void VIEWPORT::decode(u32 v) @@ -417,8 +391,6 @@ void gfx3d_glClearDepth(u32 v) void gfx3d_glMatrixMode(u32 v) { mode = (v&3); - - GFX_DELAY(1); } @@ -426,57 +398,36 @@ void gfx3d_glLoadIdentity() { MatrixIdentity (mtxCurrent[mode]); - GFX_DELAY(19); - if (mode == 2) MatrixIdentity (mtxCurrent[1]); } BOOL gfx3d_glLoadMatrix4x4(s32 v) { -#ifdef NOSSE2 mtxCurrent[mode][ML4x4ind] = fix2float(v); -#else - mtxCurrent[mode][ML4x4ind] = v; -#endif ++ML4x4ind; if(ML4x4ind<16) return FALSE; ML4x4ind = 0; - GFX_DELAY(19); - -#ifndef NOSSE2 - _sse2_fix2float_16(mtxCurrent[mode], _fix2float_divizor_mask); -#endif - if (mode == 2) MatrixCopy (mtxCurrent[1], mtxCurrent[2]); + return TRUE; } BOOL gfx3d_glLoadMatrix4x3(s32 v) { -#ifdef NOSSE2 mtxCurrent[mode][ML4x3ind] = fix2float(v); -#else - mtxCurrent[mode][ML4x3ind] = v; -#endif ML4x3ind++; if((ML4x3ind & 0x03) == 3) ML4x3ind++; if(ML4x3ind<16) return FALSE; ML4x3ind = 0; -#ifndef NOSSE2 - _sse2_fix2float_16(mtxCurrent[mode], _fix2float_divizor_mask); -#endif - //fill in the unusued matrix values - mtxCurrent[mode][3] = mtxCurrent[mode][7] = mtxCurrent[mode][11] = 0.f; - mtxCurrent[mode][15] = 1.f; - - GFX_DELAY(30); + mtxCurrent[mode][3] = mtxCurrent[mode][7] = mtxCurrent[mode][11] = 0; + mtxCurrent[mode][15] = 1; if (mode == 2) MatrixCopy (mtxCurrent[1], mtxCurrent[2]); @@ -496,9 +447,6 @@ void gfx3d_glStoreMatrix(u32 v) if(v==31) v=30; //? what should happen in this case? MatrixStackLoadMatrix (&mtxStack[mymode], v&31, mtxCurrent[mymode]); - - GFX_DELAY(17); - if(mymode==2) MatrixStackLoadMatrix (&mtxStack[1], v&31, mtxCurrent[1]); } @@ -516,9 +464,6 @@ void gfx3d_glRestoreMatrix(u32 v) if(v==31) v=30; //? what should happen in this case? MatrixCopy (mtxCurrent[mymode], MatrixStackGetPos(&mtxStack[mymode], v&31)); - - GFX_DELAY(36); - if (mymode == 2) MatrixCopy (mtxCurrent[1], MatrixStackGetPos(&mtxStack[1], v&31)); } @@ -539,16 +484,11 @@ void gfx3d_glPushMatrix() gxstat &= 0xFFFF00FF; MatrixStackPushMatrix(&mtxStack[mymode], mtxCurrent[mymode]); - - GFX_DELAY(17); - if(mymode==2) MatrixStackPushMatrix (&mtxStack[1], mtxCurrent[1]); gxstat |= ((mtxStack[0].position << 13) | (mtxStack[1].position << 8)); T1WriteLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600, gxstat); - - } void gfx3d_glPopMatrix(s32 i) @@ -570,15 +510,11 @@ void gfx3d_glPopMatrix(s32 i) MatrixCopy(mtxCurrent[mymode], MatrixStackPopMatrix (&mtxStack[mymode], i)); - GFX_DELAY(36); - if (mymode == 2) MatrixCopy(mtxCurrent[1], MatrixStackPopMatrix (&mtxStack[1], i)); gxstat |= ((mtxStack[0].position << 13) | (mtxStack[1].position << 8)); T1WriteLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600, gxstat); - - } BOOL gfx3d_glTranslate(s32 v) @@ -592,18 +528,15 @@ BOOL gfx3d_glTranslate(s32 v) MatrixTranslate (mtxCurrent[mode], trans); - GFX_DELAY(22); - if (mode == 2) - { MatrixTranslate (mtxCurrent[1], trans); - GFX_DELAY_M2(30); - } return TRUE; } BOOL gfx3d_glScale(s32 v) { + short mymode = (mode==2?1:mode); + scale[scaleind] = fix2float(v); ++scaleind; @@ -611,9 +544,7 @@ BOOL gfx3d_glScale(s32 v) if(scaleind<3) return FALSE; scaleind = 0; - MatrixScale (mtxCurrent[(mode==2?1:mode)], scale); - - GFX_DELAY(22); + MatrixScale (mtxCurrent[mymode], scale); //note: pos-vector mode should not cause both matrices to scale. //the whole purpose is to keep the vector matrix orthogonal @@ -625,24 +556,13 @@ BOOL gfx3d_glScale(s32 v) BOOL gfx3d_glMultMatrix3x3(s32 v) { -#ifdef NOSSE2 mtxTemporal[MM3x3ind] = fix2float(v); -#else - mtxTemporal[MM3x3ind] = v; -#endif - MM3x3ind++; if((MM3x3ind & 0x03) == 3) MM3x3ind++; if(MM3x3ind<12) return FALSE; MM3x3ind = 0; - GFX_DELAY(28); - -#ifndef NOSSE2 - _sse2_fix2float_12(mtxTemporal, _fix2float_divizor_mask); -#endif - //fill in the unusued matrix values mtxTemporal[3] = mtxTemporal[7] = mtxTemporal[11] = 0; mtxTemporal[15] = 1; @@ -651,10 +571,7 @@ BOOL gfx3d_glMultMatrix3x3(s32 v) MatrixMultiply (mtxCurrent[mode], mtxTemporal); if (mode == 2) - { MatrixMultiply (mtxCurrent[1], mtxTemporal); - GFX_DELAY_M2(30); - } //does this really need to be done? MatrixIdentity (mtxTemporal); @@ -663,34 +580,20 @@ BOOL gfx3d_glMultMatrix3x3(s32 v) BOOL gfx3d_glMultMatrix4x3(s32 v) { -#ifdef NOSSE2 mtxTemporal[MM4x3ind] = fix2float(v); -#else - mtxTemporal[MM4x3ind] = v; -#endif MM4x3ind++; if((MM4x3ind & 0x03) == 3) MM4x3ind++; if(MM4x3ind<16) return FALSE; MM4x3ind = 0; - GFX_DELAY(31); - -#ifndef NOSSE2 - _sse2_fix2float_16(mtxTemporal, _fix2float_divizor_mask); -#endif - //fill in the unusued matrix values - mtxTemporal[3] = mtxTemporal[7] = mtxTemporal[11] = 0.f; - mtxTemporal[15] = 1.f; + mtxTemporal[3] = mtxTemporal[7] = mtxTemporal[11] = 0; + mtxTemporal[15] = 1; MatrixMultiply (mtxCurrent[mode], mtxTemporal); - if (mode == 2) - { MatrixMultiply (mtxCurrent[1], mtxTemporal); - GFX_DELAY_M2(30); - } //does this really need to be done? MatrixIdentity (mtxTemporal); @@ -699,29 +602,15 @@ BOOL gfx3d_glMultMatrix4x3(s32 v) BOOL gfx3d_glMultMatrix4x4(s32 v) { -#ifdef NOSSE2 mtxTemporal[MM4x4ind] = fix2float(v); -#else - mtxTemporal[MM4x4ind] = v; -#endif MM4x4ind++; if(MM4x4ind<16) return FALSE; MM4x4ind = 0; - GFX_DELAY(35); - -#ifndef NOSSE2 - _sse2_fix2float_16(mtxTemporal, _fix2float_divizor_mask); -#endif - MatrixMultiply (mtxCurrent[mode], mtxTemporal); - if (mode == 2) - { MatrixMultiply (mtxCurrent[1], mtxTemporal); - GFX_DELAY_M2(30); - } MatrixIdentity (mtxTemporal); return TRUE; @@ -751,14 +640,12 @@ void gfx3d_glBegin(u32 v) tempVertInfo.first = true; polyAttr = polyAttrPending; gfx3d_glPolygonAttrib_cache(); - GFX_DELAY(1); } void gfx3d_glEnd(void) { inBegin = FALSE; tempVertInfo.count = 0; - GFX_DELAY(1); } void gfx3d_glColor3b(u32 v) @@ -766,15 +653,18 @@ void gfx3d_glColor3b(u32 v) colorRGB[0] = (v&0x1F); colorRGB[1] = ((v>>5)&0x1F); colorRGB[2] = ((v>>10)&0x1F); - GFX_DELAY(1); } -#define SUBMITVERTEX(ii, nn) polylist->list[polylist->count].vertIndexes[ii] = tempVertInfo.map[nn]; +static void SUBMITVERTEX(int i, int n) +{ + polylist->list[polylist->count].vertIndexes[i] = tempVertInfo.map[n]; +} + + //Submit a vertex to the GE static void SetVertex() { - ALIGN(16) float coordTransformed[4] = { coord[0], coord[1], coord[2], 1.f }; - + ALIGN(16) float coordTransformed[4] = { coord[0], coord[1], coord[2], 1 }; if (texCoordinateTransform == 3) { last_s =((coord[0]*mtxCurrent[3][0] + @@ -785,23 +675,17 @@ static void SetVertex() coord[2]*mtxCurrent[3][9]) + _t * 16.0f) / 16.0f; } - //refuse to do anything if we have too many verts or polys - polygonListCompleted = 0; - if(vertlist->count >= VERTLIST_SIZE) - return; - if(polylist->count >= POLYLIST_SIZE) - return; - -#ifdef NOSSE2 + if(vertlist->count >= VERTLIST_SIZE) + return; + if(polylist->count >= POLYLIST_SIZE) + return; + //apply modelview matrix MatrixMultVec4x4 (mtxCurrent[1], coordTransformed); //apply projection matrix MatrixMultVec4x4 (mtxCurrent[0], coordTransformed); -#else - _sse2_MatrixMultVec4x4_M2(mtxCurrent[0], coordTransformed); -#endif //TODO - culling should be done here. //TODO - viewport transform? @@ -831,12 +715,12 @@ static void SetVertex() //possibly complete a polygon { - polygonListCompleted = 2; + int completed=0; switch(vtxFormat) { case 0: //GL_TRIANGLES if(tempVertInfo.count!=3) break; - polygonListCompleted = 1; + completed = 1; //vertlist->list[polylist->list[polylist->count].vertIndexes[i] = vertlist->count++] = tempVertList.list[n]; SUBMITVERTEX(0,0); SUBMITVERTEX(1,1); @@ -848,7 +732,7 @@ static void SetVertex() case 1: //GL_QUADS if(tempVertInfo.count!=4) break; - polygonListCompleted = 1; + completed = 1; SUBMITVERTEX(0,0); SUBMITVERTEX(1,1); SUBMITVERTEX(2,2); @@ -860,7 +744,7 @@ static void SetVertex() case 2: //GL_TRIANGLE_STRIP if(tempVertInfo.count!=3) break; - polygonListCompleted = 1; + completed = 1; SUBMITVERTEX(0,0); SUBMITVERTEX(1,1); SUBMITVERTEX(2,2); @@ -883,7 +767,7 @@ static void SetVertex() case 3: //GL_QUAD_STRIP if(tempVertInfo.count!=4) break; - polygonListCompleted = 1; + completed = 1; SUBMITVERTEX(0,0); SUBMITVERTEX(1,1); SUBMITVERTEX(2,3); @@ -897,11 +781,9 @@ static void SetVertex() tempVertInfo.first = false; tempVertInfo.count = 2; break; - default: - return; } - if(polygonListCompleted == 1) + if(completed) { POLY &poly = polylist->list[polylist->count]; @@ -929,8 +811,6 @@ BOOL gfx3d_glVertex16b(unsigned int v) coordind = 0; SetVertex (); - - GFX_DELAY(9); return TRUE; } @@ -940,7 +820,6 @@ void gfx3d_glVertex10b(u32 v) coord[1] = float10Table[(v>>10)&1023]; coord[2] = float10Table[(v>>20)&1023]; - GFX_DELAY(8); SetVertex (); } @@ -950,8 +829,6 @@ void gfx3d_glVertex3_cord(unsigned int one, unsigned int two, unsigned int v) coord[two] = float16table[v>>16]; SetVertex (); - - GFX_DELAY(8); } void gfx3d_glVertex_rel(u32 v) @@ -961,8 +838,6 @@ void gfx3d_glVertex_rel(u32 v) coord[2] += float10RelTable[(v>>20)&1023]; SetVertex (); - - GFX_DELAY(8); } // Ignored for now @@ -974,13 +849,13 @@ void gfx3d_glSwapScreen(unsigned int screen) int gfx3d_GetNumPolys() { //so is this in the currently-displayed or currently-built list? - return (polylists[listTwiddle].count); + return 0; } int gfx3d_GetNumVertex() { //so is this in the currently-displayed or currently-built list? - return (vertlists[listTwiddle].count); + return 0; } @@ -992,7 +867,6 @@ void gfx3d_glPolygonAttrib (u32 val) //TODO - we need some some similar checking for teximageparam etc. } polyAttrPending = val; - GFX_DELAY(1); } /* @@ -1015,14 +889,12 @@ void gfx3d_glMaterial0(u32 val) colorRGB[1] = (val>>5)&0x1F; colorRGB[2] = (val>>10)&0x1F; } - GFX_DELAY(4); } void gfx3d_glMaterial1(u32 val) { dsSpecular = val&0xFFFF; dsEmission = val>>16; - GFX_DELAY(4); } BOOL gfx3d_glShininess (u32 val) @@ -1034,7 +906,6 @@ BOOL gfx3d_glShininess (u32 val) if (shininessInd < 128) return FALSE; shininessInd = 0; - GFX_DELAY(32); return TRUE; } @@ -1057,13 +928,11 @@ void gfx3d_glTexImage(u32 val) { textureFormat = val; gfx3d_glTexImage_cache(); - GFX_DELAY(1); } void gfx3d_glTexPalette(u32 val) { texturePalette = val; - GFX_DELAY(1); } void gfx3d_glTexCoord(u32 val) @@ -1086,7 +955,6 @@ void gfx3d_glTexCoord(u32 val) last_s=_s; last_t=_t; } - GFX_DELAY(1); } #define vec3dot(a, b) (((a[0]) * (b[0])) + ((a[1]) * (b[1])) + ((a[2]) * (b[2]))) @@ -1134,56 +1002,52 @@ void gfx3d_glNormal(u32 v) int vertexColor[3] = { emission[0], emission[1], emission[2] }; - for(i=0; i<4; i++) - { - if(!((lightMask>>i)&1)) continue; + for(i=0;i<4;i++) { + if(!((lightMask>>i)&1)) + continue; - u8 _lightColor[3] = { - (lightColor[i])&0x1F, - (lightColor[i]>>5)&0x1F, - (lightColor[i]>>10)&0x1F }; - - /* This formula is the one used by the DS */ - /* Reference : http://nocash.emubase.de/gbatek.htm#ds3dpolygonlightparameters */ - - float diffuseLevel = std::max(0.0f, -vec3dot(cacheLightDirection[i], normal)); - float shininessLevel = pow(std::max(0.0f, vec3dot(-cacheHalfVector[i], normal)), 2); - - if(dsSpecular & 0x8000) { - int shininessIndex = (int)(shininessLevel * 128); - if(shininessIndex >= (int)ARRAY_SIZE(shininessTable)) { - //we can't print this right now, because when a game triggers this it triggers it _A_LOT_ - //so wait until we have per-frame diagnostics. - //this was tested using Princess Debut (US) after proceeding through the intro and getting the tiara. - //After much research, I determined that this was caused by the game feeding in a totally jacked matrix - //to mult4x4 from 0x02129B80 (after feeding two other valid matrices) - //the game seems to internally index these as: ?, 0x37, 0x2B <-- error - //but, man... this is seriously messed up. there must be something going wrong. - //maybe it has something to do with what looks like a mirror room effect that is going on during this time? - //PROGINFO("ERROR: shininess table out of bounds.\n maybe an emulator error; maybe a non-unit normal; setting to 0\n"); - shininessIndex = 0; + u8 _lightColor[3] = { + (lightColor[i])&0x1F, + (lightColor[i]>>5)&0x1F, + (lightColor[i]>>10)&0x1F }; + + /* This formula is the one used by the DS */ + /* Reference : http://nocash.emubase.de/gbatek.htm#ds3dpolygonlightparameters */ + + float diffuseLevel = std::max(0.0f, -vec3dot(cacheLightDirection[i], normal)); + float shininessLevel = pow(std::max(0.0f, vec3dot(-cacheHalfVector[i], normal)), 2); + + if(dsSpecular & 0x8000) + { + int shininessIndex = (int)(shininessLevel * 128); + if(shininessIndex >= (int)ARRAY_SIZE(shininessTable)) { + //we can't print this right now, because when a game triggers this it triggers it _A_LOT_ + //so wait until we have per-frame diagnostics. + //this was tested using Princess Debut (US) after proceeding through the intro and getting the tiara. + //After much research, I determined that this was caused by the game feeding in a totally jacked matrix + //to mult4x4 from 0x02129B80 (after feeding two other valid matrices) + //the game seems to internally index these as: ?, 0x37, 0x2B <-- error + //but, man... this is seriously messed up. there must be something going wrong. + //maybe it has something to do with what looks like a mirror room effect that is going on during this time? + //PROGINFO("ERROR: shininess table out of bounds.\n maybe an emulator error; maybe a non-unit normal; setting to 0\n"); + shininessIndex = 0; + } + shininessLevel = shininessTable[shininessIndex]; } - shininessLevel = shininessTable[shininessIndex]; - } - for(c = 0; c < 3; c++) - { - vertexColor[c] += (int)(((specular[c] * _lightColor[c] * shininessLevel) - + (diffuse[c] * _lightColor[c] * diffuseLevel) - + (ambient[c] * _lightColor[c])) / 31.0f); + for(c = 0; c < 3; c++) + { + vertexColor[c] += (int)(((specular[c] * _lightColor[c] * shininessLevel) + + (diffuse[c] * _lightColor[c] * diffuseLevel) + + (ambient[c] * _lightColor[c])) / 31.0f); + } } } for(c=0;c<3;c++) colorRGB[c] = std::min(31,vertexColor[c]); } - - GFX_DELAY(9); - GFX_DELAY_M2((lightMask) & 0x01); - GFX_DELAY_M2((lightMask>>1) & 0x01); - GFX_DELAY_M2((lightMask>>2) & 0x01); - GFX_DELAY_M2((lightMask>>3) & 0x01); } @@ -1236,14 +1100,12 @@ void gfx3d_glLightDirection (u32 v) lightDirection[index] = v; gfx3d_glLightDirection_cache(index); - GFX_DELAY(6); } void gfx3d_glLightColor (u32 v) { int index = v>>30; lightColor[index] = v; - GFX_DELAY(1); } void gfx3d_glAlphaFunc(u32 v) @@ -1276,8 +1138,6 @@ BOOL gfx3d_glBoxTest(u32 v) } BTind = 0; - GFX_DELAY(103); - /* BTcoords[4] = float16table[v & 0xFFFF]; BTcoords[5] = float16table[v >> 16]; @@ -1376,8 +1236,6 @@ BOOL gfx3d_glPosTest(u32 v) gxstat &= 0xFFFFFFFE; T1WriteLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600, gxstat); - GFX_DELAY(9); - return TRUE; } @@ -1387,7 +1245,6 @@ void gfx3d_glVecTest(u32 v) gxstat &= 0xFFFFFFFE; T1WriteLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600, gxstat); - GFX_DELAY(5); //INFO("NDS_glVecTest\n"); } @@ -1404,13 +1261,8 @@ unsigned short gfx3d_glGetVecRes(unsigned int index) #ifdef USE_GEOMETRY_FIFO_EMULATION -//#define _3D_LOG_EXEC void gfx3d_execute(u8 cmd, u32 param) { -#ifdef _3D_LOG_EXEC - u32 gxstat2 = T1ReadLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600); - INFO("*** gxFIFO: exec 0x%02X, tail %03i, gxstat 0x%08X\n", cmd, gxFIFO.tail, gxstat2); -#endif switch (cmd) { case 0x10: // MTX_MODE - Set Matrix Mode (W) @@ -1529,44 +1381,21 @@ void gfx3d_execute(u8 cmd, u32 param) break; } } +#endif -void gfx3d_execute3D() +static void gfx3d_FlushFIFO() { - u8 cmd = 0; - u32 param = 0; + if (!gxFIFO.tail) return; - //if (isSwapBuffers) return; - - if (GFX_FIFOrecv(&cmd, ¶m)) +#ifdef USE_GEOMETRY_FIFO_EMULATION + for (int i=0; i < gxFIFO.tail; i++) { - gfx3d_execute(cmd, param); -#if 0 - for ( ;;) - { - if ( (cmd == 0x11) || (cmd==0x15) || (cmd==41) ) - { - if (!GFX_FIFOrecv(&cmd, ¶m)) return; - gfx3d_execute(cmd, param); - continue; - } - break; - } -#endif -#if 0 - if (bWaitForPolys) - { - //INFO("Error: incompleted polylist\n"); - if (polygonListCompleted == 1) - { - gfx3d_doFlush(); - isSwapBuffers = true; - bWaitForPolys = false; - } - } -#endif + //INFO("3D execute command 0x%02X with param 0x%08X (pos %03i)\n", gxFIFO.cmd[i], gxFIFO.param[i], i); + gfx3d_execute(gxFIFO.cmd[i], gxFIFO.param[i]); } -} #endif + GFX_FIFOclear(); +} void gfx3d_glFlush(u32 v) { @@ -1574,31 +1403,9 @@ void gfx3d_glFlush(u32 v) gfx3d.sortmode = BIT0(v); gfx3d.wbuffer = BIT1(v); -#ifdef USE_GEOMETRY_FIFO_EMULATION - -#if 0 - if (polygonListCompleted == 2) - { - //u32 gxstat = T1ReadLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600); - //gxstat |= 0x08000000; // set busy flag - //T1WriteLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600, gxstat); - bWaitForPolys = true; - return; - } -#endif - - gfx3d_doFlush(); - isSwapBuffers = true; - - //u32 gxstat = T1ReadLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600); - //gxstat |= 0x08000000; // set busy flag - //T1WriteLong(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x600, gxstat); -#else //see discussion at top of file if(CommonSettings.gfx3d_flushMode == 0) gfx3d_doFlush(); -#endif - } static bool gfx3d_ysort_compare(int num1, int num2) @@ -1623,12 +1430,11 @@ static void gfx3d_doFlush() { gfx3d.frameCtr++; -#ifndef USE_GEOMETRY_FIFO_EMULATION - GFX_FIFOclear(); + gfx3d_FlushFIFO(); + // reset clInd = 0; clCmd = 0; -#endif //the renderer wil lget the lists we just built gfx3d.polylist = polylist; @@ -1683,59 +1489,27 @@ static void gfx3d_doFlush() //switch to the new lists twiddleLists(); -#ifndef USE_GEOMETRY_FIFO_EMULATION flushPending = FALSE; drawPending = TRUE; -#else - drawPending = TRUE; -#endif } void gfx3d_VBlankSignal() { -#ifdef USE_GEOMETRY_FIFO_EMULATION - isVBlank = true; - if (isSwapBuffers) - { - isSwapBuffers = false; - GFX_DELAY(392); - } -#else //the 3d buffers are swapped when a vblank begins. //so, if we have a redraw pending, now is a safe time to do it if(!flushPending) { - GFX_FIFOclear(); + gfx3d_FlushFIFO(); return; } //see discussion at top of file if(CommonSettings.gfx3d_flushMode == 1) gfx3d_doFlush(); -#endif } void gfx3d_VBlankEndSignal(bool skipFrame) { -#ifdef USE_GEOMETRY_FIFO_EMULATION - isVBlank = false; - if (drawPending) - { - drawPending = FALSE; - - //if the null 3d core is chosen, then we need to clear out the 3d buffers to keep old data from being rendered - if(gpu3D == &gpu3DNull || !CommonSettings.showGpu.main) - { - memset(gfx3d_convertedScreen,0,sizeof(gfx3d_convertedScreen)); - memset(gfx3d_convertedScreen,0,sizeof(gfx3d_convertedAlpha)); - } - else - { - if(CommonSettings.showGpu.main) - gpu3D->NDS_3D_Render(); - } - } -#else //if we are skipping 3d frames then the 3d rendering will get held up here. //but, as soon as we quit skipping frames, the held-up 3d frame will render if(skipFrame) return; @@ -1752,30 +1526,37 @@ void gfx3d_VBlankEndSignal(bool skipFrame) memset(gfx3d_convertedScreen,0,sizeof(gfx3d_convertedScreen)); memset(gfx3d_convertedScreen,0,sizeof(gfx3d_convertedAlpha)); } -#endif } #ifdef USE_GEOMETRY_FIFO_EMULATION //#define _3D_LOG - static void NOPARAMS() { for (;;) { - if (clCmd == 0) return; + if (!clInd) return; switch (clCmd & 0xFF) { case 0x00: { clCmd >>= 8; + clInd--; +#ifdef _3D_LOG + INFO("GX FIFO !!!ZERO!!! (%03i) (without params)\n", gxFIFO.tail); +#endif + //gfx3d_FlushFIFO(); continue; } - case 0x11: - case 0x15: - case 0x41: + case 0x11: // MTX_PUSH - Push Current Matrix on Stack (W) + case 0x15: // MTX_IDENTITY - Load Unit Matrix to Current Matrix (W) + case 0x41: // END_VTXS - End of Vertex List (W) { +#ifdef _3D_LOG + INFO("GX FIFO cmd 0x%02X (without params)\n", clCmd, gxFIFO.tail); +#endif GFX_FIFOsend(clCmd & 0xFF, 0); clCmd >>= 8; + clInd--; continue; } } @@ -1785,20 +1566,29 @@ static void NOPARAMS() void gfx3d_sendCommandToFIFO(u32 val) { - if (clCmd == 0) + if (!clInd) { - clCmd = val; - return; - } + if (val == 0) + { + //gfx3d_FlushFIFO(); + return; + } #ifdef _3D_LOG - INFO("GFX FIFO: Send GFX 3D cmd 0x%02X to FIFO (0x%08X)\n", clCmd & 0xFF, val); + INFO("GX FIFO cmd 0x%02X, gxstat 0x%08X (%03i)\n", val, gxstat, gxFIFO.tail); #endif - - NOPARAMS(); - if (clCmd == 0) - { - if (val == 0) return; clCmd = val; + + if (!(clCmd & 0xFFFFFF00)) // unpacked command + clInd = 1; + else + if (!(clCmd & 0xFFFF0000)) // packed command + clInd = 2; + else + if (!(clCmd & 0xFF000000)) // packed command + clInd = 3; + else + clInd = 4; + NOPARAMS(); return; } @@ -1811,6 +1601,7 @@ void gfx3d_sendCommandToFIFO(u32 val) if (clInd2 < 32) return; clInd2 = 0; clCmd >>= 8; + clInd--; break; case 0x16: // MTX_LOAD_4x4 - Load 4x4 Matrix to Current Matrix (W) @@ -1821,6 +1612,7 @@ void gfx3d_sendCommandToFIFO(u32 val) if (clInd2 < 16) return; clInd2 = 0; clCmd >>= 8; + clInd--; break; case 0x17: // MTX_LOAD_4x3 - Load 4x3 Matrix to Current Matrix (W) @@ -1831,6 +1623,7 @@ void gfx3d_sendCommandToFIFO(u32 val) if (clInd2 < 12) return; clInd2 = 0; clCmd >>= 8; + clInd--; break; case 0x1A: // MTX_MULT_3x3 - Multiply Current Matrix by 3x3 Matrix (W) @@ -1840,6 +1633,7 @@ void gfx3d_sendCommandToFIFO(u32 val) if (clInd2 < 9) return; clInd2 = 0; clCmd >>= 8; + clInd--; break; case 0x1B: // MTX_SCALE - Multiply Current Matrix by Scale Matrix (W) @@ -1851,6 +1645,7 @@ void gfx3d_sendCommandToFIFO(u32 val) if (clInd2 < 3) return; clInd2 = 0; clCmd >>= 8; + clInd--; break; case 0x23: // VTX_16 - Set Vertex XYZ Coordinates (W) @@ -1861,6 +1656,7 @@ void gfx3d_sendCommandToFIFO(u32 val) if (clInd2 < 2) return; clInd2 = 0; clCmd >>= 8; + clInd--; break; case 0x10: // MTX_MODE - Set Matrix Mode (W) @@ -1886,25 +1682,29 @@ void gfx3d_sendCommandToFIFO(u32 val) case 0x60: // VIEWPORT - Set Viewport (W) case 0x72: // VEC_TEST - Set Directional Vector for Test (W) GFX_FIFOsend(clCmd & 0xFF, val); + clCmd >>= 8; + clInd--; break; case 0x50: // SWAP_BUFFERS - Swap Rendering Engine Buffer (W) - GFX_FIFOsend(clCmd & 0xFF, val); - clCmd >>= 8; + gfx3d_glFlush(val); break; default: INFO("Unknown FIFO 3D command 0x%02X (0x%08X)\n", clCmd&0xFF, clCmd); clCmd >>= 8; + clInd--; return; } + NOPARAMS(); } void gfx3d_sendCommand(u32 cmd, u32 param) { cmd = (cmd & 0x01FF) >> 2; + #ifdef _3D_LOG - INFO("GFX FIFO: Send GFX 3D cmd 0x%02X to FIFO (0x%08X) - DIRECT (%i)\n", cmd, param, nds.cycles); + INFO("GX (dir) cmd 0x%02X = 0x%08X, gxstat 0x%08X (%02i)\n", cmd, param, gxstat, gxFIFO.tail); #endif switch (cmd) @@ -1948,48 +1748,53 @@ void gfx3d_sendCommand(u32 cmd, u32 param) GFX_FIFOsend(cmd, param); break; case 0x50: // SWAP_BUFFERS - Swap Rendering Engine Buffer (W) - GFX_FIFOsend(cmd, param); + gfx3d_glFlush(param); break; default: INFO("Unknown 3D command %03X with param 0x%08X (directport)\n", cmd, param); break; } } - #else -//#define _3D_LOG static void NOPARAMS() { for (;;) { - if (clCmd == 0) return; + if (!clInd) return; switch (clCmd & 0xFF) { case 0x00: { clCmd >>= 8; + clInd--; continue; } case 0x11: { + *(u32 *)(ARM9Mem.ARM9_REG + 0x444) = 0; gfx3d_glPushMatrix(); GFX_FIFOsend(clCmd & 0xFF, 0); clCmd >>= 8; + clInd--; continue; } case 0x15: { + *(u32 *)(ARM9Mem.ARM9_REG + 0x454) = 0; gfx3d_glLoadIdentity(); GFX_FIFOsend(clCmd & 0xFF, 0); clCmd >>= 8; + clInd--; continue; } case 0x41: { + *(u32 *)(ARM9Mem.ARM9_REG + 0x504) = 0; gfx3d_glEnd(); GFX_FIFOsend(clCmd & 0xFF, 0); clCmd >>= 8; + clInd--; continue; } } @@ -1999,195 +1804,269 @@ static void NOPARAMS() void gfx3d_sendCommandToFIFO(u32 val) { - if (clCmd == 0) + if (!clInd) { - clCmd = val; - return; - } -#ifdef _3D_LOG - INFO("GFX FIFO: Send GFX 3D cmd 0x%02X to FIFO (0x%08X)\n", clCmd & 0xFF, val); -#endif + if (val == 0) return; - NOPARAMS(); - if (clCmd == 0) - { +#ifdef _3D_LOG + INFO("GFX FIFO: Send GFX 3D cmd 0x%02X to FIFO (0x%08X)\n", clCmd, val); +#endif clCmd = val; + if (!(clCmd & 0xFFFFFF00)) // unpacked command + clInd = 1; + else + if (!(clCmd & 0xFFFF0000)) // packed command + clInd = 2; + else + if (!(clCmd & 0xFF000000)) // packed command + clInd = 3; + else + clInd = 4; + NOPARAMS(); return; } switch (clCmd & 0xFF) { case 0x10: // MTX_MODE - Set Matrix Mode (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x440) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glMatrixMode(val); clCmd >>= 8; + clInd--; break; case 0x12: // MTX_POP - Pop Current Matrix from Stack (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x448) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glPopMatrix(val); clCmd >>= 8; + clInd--; break; case 0x13: // MTX_STORE - Store Current Matrix on Stack (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x44C) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glStoreMatrix(val); clCmd >>= 8; + clInd--; break; case 0x14: // MTX_RESTORE - Restore Current Matrix from Stack (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x450) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glRestoreMatrix(val); clCmd >>= 8; + clInd--; break; case 0x16: // MTX_LOAD_4x4 - Load 4x4 Matrix to Current Matrix (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x458) = val; GFX_FIFOsend(clCmd & 0xFF, val); if (!gfx3d_glLoadMatrix4x4(val)) break; clCmd >>= 8; + clInd--; break; case 0x17: // MTX_LOAD_4x3 - Load 4x3 Matrix to Current Matrix (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x45C) = val; GFX_FIFOsend(clCmd & 0xFF, val); if (!gfx3d_glLoadMatrix4x3(val)) break; clCmd >>= 8; + clInd--; break; case 0x18: // MTX_MULT_4x4 - Multiply Current Matrix by 4x4 Matrix (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x460) = val; GFX_FIFOsend(clCmd & 0xFF, val); if (!gfx3d_glMultMatrix4x4(val)) break; clCmd >>= 8; + clInd--; break; case 0x19: // MTX_MULT_4x3 - Multiply Current Matrix by 4x3 Matrix (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x464) = val; GFX_FIFOsend(clCmd & 0xFF, val); if (!gfx3d_glMultMatrix4x3(val)) break; clCmd >>= 8; + clInd--; break; case 0x1A: // MTX_MULT_3x3 - Multiply Current Matrix by 3x3 Matrix (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x468) = val; GFX_FIFOsend(clCmd & 0xFF, val); if (!gfx3d_glMultMatrix3x3(val)) break; clCmd >>= 8; + clInd--; break; case 0x1B: // MTX_SCALE - Multiply Current Matrix by Scale Matrix (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x46C) = val; GFX_FIFOsend(clCmd & 0xFF, val); if (!gfx3d_glScale(val)) break; clCmd >>= 8; + clInd--; break; case 0x1C: // MTX_TRANS - Mult. Curr. Matrix by Translation Matrix (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x470) = val; GFX_FIFOsend(clCmd & 0xFF, val); if (!gfx3d_glTranslate(val)) break; clCmd >>= 8; + clInd--; break; case 0x20: // COLOR - Directly Set Vertex Color (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x480) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glColor3b(val); clCmd >>= 8; + clInd--; break; case 0x21: // NORMAL - Set Normal Vector (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x484) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glNormal(val); clCmd >>= 8; + clInd--; break; case 0x22: // TEXCOORD - Set Texture Coordinates (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x488) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glTexCoord(val); clCmd >>= 8; + clInd--; break; case 0x23: // VTX_16 - Set Vertex XYZ Coordinates (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x48C) = val; GFX_FIFOsend(clCmd & 0xFF, val); if (!gfx3d_glVertex16b(val)) break; clCmd >>= 8; + clInd--; break; case 0x24: // VTX_10 - Set Vertex XYZ Coordinates (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x490) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glVertex10b(val); clCmd >>= 8; + clInd--; break; case 0x25: // VTX_XY - Set Vertex XY Coordinates (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x494) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glVertex3_cord(0, 1, val); clCmd >>= 8; + clInd--; break; case 0x26: // VTX_XZ - Set Vertex XZ Coordinates (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x498) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glVertex3_cord(0, 2, val); clCmd >>= 8; + clInd--; break; case 0x27: // VTX_YZ - Set Vertex YZ Coordinates (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x49C) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glVertex3_cord(1, 2, val); clCmd >>= 8; + clInd--; break; case 0x28: // VTX_DIFF - Set Relative Vertex Coordinates (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x4A0) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glVertex_rel(val); clCmd >>= 8; + clInd--; break; case 0x29: // POLYGON_ATTR - Set Polygon Attributes (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x4A4) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glPolygonAttrib(val); clCmd >>= 8; + clInd--; break; case 0x2A: // TEXIMAGE_PARAM - Set Texture Parameters (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x4A8) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glTexImage(val); clCmd >>= 8; + clInd--; break; case 0x2B: // PLTT_BASE - Set Texture Palette Base Address (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x4AC) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glTexPalette(val); clCmd >>= 8; + clInd--; break; case 0x30: // DIF_AMB - MaterialColor0 - Diffuse/Ambient Reflect. (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x4C0) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glMaterial0(val); clCmd >>= 8; + clInd--; break; case 0x31: // SPE_EMI - MaterialColor1 - Specular Ref. & Emission (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x4C4) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glMaterial1(val); clCmd >>= 8; + clInd--; break; case 0x32: // LIGHT_VECTOR - Set Light's Directional Vector (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x4C8) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glLightDirection(val); clCmd >>= 8; + clInd--; break; case 0x33: // LIGHT_COLOR - Set Light Color (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x4CC) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glLightColor(val); clCmd >>= 8; + clInd--; break; case 0x34: // SHININESS - Specular Reflection Shininess Table (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x4D0) = val; GFX_FIFOsend(clCmd & 0xFF, val); if (!gfx3d_glShininess(val)) break; clCmd >>= 8; + clInd--; break; case 0x40: // BEGIN_VTXS - Start of Vertex List (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x500) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glBegin(val); clCmd >>= 8; + clInd--; break; case 0x50: // SWAP_BUFFERS - Swap Rendering Engine Buffer (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x540) = val; gfx3d_glFlush(val); break; case 0x60: // VIEWPORT - Set Viewport (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x580) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glViewPort(val); clCmd >>= 8; + clInd--; break; case 0x70: // BOX_TEST - Test if Cuboid Sits inside View Volume (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x5C0) = val; GFX_FIFOsend(clCmd & 0xFF, val); if (!gfx3d_glBoxTest(val)) break; clCmd >>= 8; + clInd--; break; case 0x71: // POS_TEST - Set Position Coordinates for Test (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x5C4) = val; GFX_FIFOsend(clCmd & 0xFF, val); if (!gfx3d_glPosTest(val)) break; clCmd >>= 8; + clInd--; break; case 0x72: // VEC_TEST - Set Directional Vector for Test (W) + *(u32 *)(ARM9Mem.ARM9_REG + 0x5C8) = val; GFX_FIFOsend(clCmd & 0xFF, val); gfx3d_glVecTest(val); clCmd >>= 8; + clInd--; break; default: LOG("Unknown FIFO 3D command 0x%02X in cmd=0x%02X\n", clCmd&0xFF, val); clCmd >>= 8; + clInd--; break; } NOPARAMS(); @@ -2350,6 +2229,12 @@ static void gfx3d_Control_cache() gfx3d.enableAntialiasing = BIT4(v); gfx3d.enableEdgeMarking = BIT5(v); gfx3d.enableClearImage = BIT14(v); + + //other junk + if (v&(1<<14)) + { + LOG("Enabled BITMAP background mode\n"); + } } void gfx3d_Control(u32 v) diff --git a/desmume/src/gfx3d.h b/src/gfx3d.h similarity index 99% rename from desmume/src/gfx3d.h rename to src/gfx3d.h index 09eb1c54a..34304ce2f 100644 --- a/desmume/src/gfx3d.h +++ b/src/gfx3d.h @@ -298,9 +298,6 @@ void gfx3d_VBlankSignal(); void gfx3d_VBlankEndSignal(bool skipFrame); void gfx3d_Control(u32 v); u32 gfx3d_GetGXstatus(); -#ifdef USE_GEOMETRY_FIFO_EMULATION -void gfx3d_execute3D(); -#endif void gfx3d_sendCommandToFIFO(u32 val); void gfx3d_sendCommand(u32 cmd, u32 param); diff --git a/desmume/src/gtk-glade/Makefile.am b/src/gtk-glade/Makefile.am similarity index 100% rename from desmume/src/gtk-glade/Makefile.am rename to src/gtk-glade/Makefile.am diff --git a/desmume/src/gtk-glade/callbacks.cpp b/src/gtk-glade/callbacks.cpp similarity index 98% rename from desmume/src/gtk-glade/callbacks.cpp rename to src/gtk-glade/callbacks.cpp index bd5f5ee7a..a879a2a1d 100755 --- a/desmume/src/gtk-glade/callbacks.cpp +++ b/src/gtk-glade/callbacks.cpp @@ -478,16 +478,10 @@ void on_menu_palview_activate (GtkMenuItem *menuitem, gpointer user_data) GtkWidget * dlg = glade_xml_get_widget(xml_tools, "wtools_3_PalView"); gtk_widget_show(dlg); } -#ifdef GTKGLEXT_AVAILABLE void on_menu_tileview_activate (GtkMenuItem *menuitem, gpointer user_data) { GtkWidget * dlg = glade_xml_get_widget(xml_tools, "wtools_4_TileView"); gtk_widget_show(dlg); } -#else -void on_menu_tileview_activate (GtkMenuItem *menuitem, gpointer user_data) { - g_printerr("You need gtkglext for the tile viewer\n"); -} -#endif void on_menu_wtoolsXX_activate (GtkMenuItem *menuitem, gpointer user_data) { GtkWidget * w = (GtkWidget *) user_data; gtk_widget_show(w); diff --git a/desmume/src/gtk-glade/callbacks.h b/src/gtk-glade/callbacks.h similarity index 100% rename from desmume/src/gtk-glade/callbacks.h rename to src/gtk-glade/callbacks.h diff --git a/desmume/src/gtk-glade/callbacks_IO.cpp b/src/gtk-glade/callbacks_IO.cpp similarity index 100% rename from desmume/src/gtk-glade/callbacks_IO.cpp rename to src/gtk-glade/callbacks_IO.cpp diff --git a/desmume/src/gtk-glade/callbacks_IO.h b/src/gtk-glade/callbacks_IO.h similarity index 100% rename from desmume/src/gtk-glade/callbacks_IO.h rename to src/gtk-glade/callbacks_IO.h diff --git a/desmume/src/gtk-glade/dTools/callbacks_1_ioregs.cpp b/src/gtk-glade/dTools/callbacks_1_ioregs.cpp similarity index 100% rename from desmume/src/gtk-glade/dTools/callbacks_1_ioregs.cpp rename to src/gtk-glade/dTools/callbacks_1_ioregs.cpp diff --git a/desmume/src/gtk-glade/dTools/callbacks_2_memview.cpp b/src/gtk-glade/dTools/callbacks_2_memview.cpp similarity index 100% rename from desmume/src/gtk-glade/dTools/callbacks_2_memview.cpp rename to src/gtk-glade/dTools/callbacks_2_memview.cpp diff --git a/desmume/src/gtk-glade/dTools/callbacks_3_palview.cpp b/src/gtk-glade/dTools/callbacks_3_palview.cpp similarity index 100% rename from desmume/src/gtk-glade/dTools/callbacks_3_palview.cpp rename to src/gtk-glade/dTools/callbacks_3_palview.cpp diff --git a/desmume/src/gtk-glade/dTools/callbacks_4_tileview.cpp b/src/gtk-glade/dTools/callbacks_4_tileview.cpp similarity index 69% rename from desmume/src/gtk-glade/dTools/callbacks_4_tileview.cpp rename to src/gtk-glade/dTools/callbacks_4_tileview.cpp index dbf979c09..46b059c26 100755 --- a/desmume/src/gtk-glade/dTools/callbacks_4_tileview.cpp +++ b/src/gtk-glade/dTools/callbacks_4_tileview.cpp @@ -19,8 +19,8 @@ * Boston, MA 02111-1307, USA. */ -#include "callbacks_dtools.h" #ifdef GTKGLEXT_AVAILABLE +#include "callbacks_dtools.h" #include "../gdk_gl.h" void init_combo_memory(GtkComboBox *combo, u8 ** addresses) { @@ -309,21 +309,157 @@ gboolean on_wDraw_Tile_expose_event (GtkWidget * w, GdkEventExpose * e, gp refresh(); return TRUE; } -#else -void on_wtools_4_TileView_show (GtkWidget *widget, gpointer data) { -} -gboolean on_wtools_4_TileView_close (GtkWidget *widget, ...) { - return FALSE; -} -void on_wtools_4_palette_changed (GtkComboBox *combo, gpointer user_data) { -} -void on_wtools_4_palnum_value_changed (GtkSpinButton *spin, gpointer user_data) { -} -void on_wtools_4_memory_changed (GtkComboBox *combo, gpointer user_data) { -} -void on_wtools_4_rXX_toggled (GtkToggleButton *togglebutton, gpointer user_data) { -} -gboolean on_wDraw_Tile_expose_event (GtkWidget * w, GdkEventExpose * e, gpointer user_data) { - return FALSE; + + + +#if 0 + +void other_screen (GtkWidget * widget, int screen) { + if (!my_gl_Begin(screen)) return; + + my_gl_Identity(); + glClear( GL_COLOR_BUFFER_BIT ); + + GPU * gpu = &SubScreen; + struct _DISPCNT * dispCnt = &(gpu->dispx_st)->dispx_DISPCNT.bits; + _OAM_ * spriteInfo = (_OAM_*)(gpu->oam + 127);// + 127; + u16 i; int mode; + u8 prioTab[256]; + +#define MODE_IDX_16 1 +#define MODE_IDX_256 2 +#define MODE_BMP 3 + + for(i = 0; i<127; ++i, --spriteInfo) + { + size sprSize; + s32 sprX, sprY, x, y, lg; + int xdir; + u8 prio, * src; + u16 * pal; + u16 i,j; + u16 rotScaleA,rotScaleB,rotScaleC,rotScaleD; + int block; + + prio = spriteInfo->Priority; + + // get sprite location and size + sprX = (spriteInfo->X<<23)>>23; + sprY = spriteInfo->Y; + sprSize = sprSizeTab[spriteInfo->Size][spriteInfo->Shape]; + + lg = sprSize.x; + + if (spriteInfo->RotScale == 2) continue; +#if 0 + // switch TOP<-->BOTTOM + if (spriteInfo->VFlip); + // switch LEFT<-->RIGHT + if (spriteInfo->HFlip); + + { + u16 rotScaleIndex; + // index from 0 to 31 + rotScaleIndex = spriteInfo->RotScalIndex + (spriteInfo->HFlip<<1) + (spriteInfo->VFlip << 2); + rotScaleA = T1ReadWord((u8*)(gpu->oam + rotScaleIndex*0x20 + 0x06),0) ; + rotScaleB = T1ReadWord((u8*)(gpu->oam + rotScaleIndex*0x20 + 0x0E),0) ; + rotScaleC = T1ReadWord((u8*)(gpu->oam + rotScaleIndex*0x20 + 0x16),0) ; + rotScaleD = T1ReadWord((u8*)(gpu->oam + rotScaleIndex*0x20 + 0x1E),0) ; + } + + if (spriteInfo->Mode == 2) { + src = gpu->sprMem + ((spriteInfo->TileIndex)<<5) + ((y>>3)<<10); + continue; + } + + if (spriteInfo->Mode == 3) /* sprite is in BMP format */ + { + src = (gpu->sprMem) + (spriteInfo->TileIndex<<4) + (y<sprBMPBoundary); + + if (dispCnt->OBJ_BMP_2D_dim) // 256*256 + src = (gpu->sprMem) + (((spriteInfo->TileIndex&0x3F0) * 64 + (spriteInfo->TileIndex&0x0F) *8) << 1); + else // 128 * 512 + src = (gpu->sprMem) + (((spriteInfo->TileIndex&0x3E0) * 64 + (spriteInfo->TileIndex&0x1F) *8) << 1); + continue; + } + + + if(dispCnt->OBJ_Tile_mapping) + + if (spriteInfo->Depth) { + //256 colors + glColorTable(GL_TEXTURE_COLOR_TABLE_EXT, + GL_RGBA, 256, GL_RGBA, + GL_UNSIGNED_SHORT_1_5_5_5_REV, pal); + } else { + pal += (spriteInfo->PaletteIndex<<4); + glColorTable(GL_TEXTURE_COLOR_TABLE_EXT, + GL_RGBA, 16, GL_RGBA, + GL_UNSIGNED_SHORT_1_5_5_5_REV, pal); + } + glTexImage2D(GL_TEXTURE_2D, 0, COLOR_INDEX4_EXT, + 16, 16, 0, + GL_COLOR_INDEX, GL_UNSIGNED_BYTE, src); + src = gpu->sprMem + ((spriteInfo->TileIndex)<<5) + ((y>>3)<<10); + pal = (u16*)(ARM9Mem.ARM9_VMEM + 0x200 + gpu->core *0x400); +#endif + } + + int boundary = 32; + if (dispCnt->OBJ_Tile_mapping) + boundary <<= dispCnt->OBJ_Tile_mapping_Bound; + + int bmpboundary = 128; + bmpboundary <<= (dispCnt->OBJ_BMP_mapping & dispCnt->OBJ_BMP_1D_Bound); + + guint Textures[3]; + glGenTextures(3, Textures); + glBindTexture(GL_TEXTURE_2D, Textures[0]); + //proxy + glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA, + 256, 256, 0, + GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV, NULL); + + u16 * pal = (u16*)(ARM9Mem.ARM9_VMEM + 0x200 + gpu->core *0x400); + + u8 palette_16[1024][64]; + u8 palette_256[1024][64]; +// u16 tile_BMP[1024][64]; + u8 * index16 = gpu->sprMem; + u8 * index256 = gpu->sprMem; + u16 * indexBMP = gpu->sprMem; + int tile_n, index; + if (gpu->sprMem != NULL) + for (tile_n=0; tile_n<1024; tile_n++) { + for (index=0; index<64; index++) { +// tile_BMP[tile_n][index]=*indexBMP; +// indexBMP++; + palette_256[tile_n][index]=pal[*index256]; + index256++; + + if (index & 1) continue; + palette_16[tile_n][index] =pal[*index16 & 15]; + palette_16[tile_n][index+1]=pal[*index16 >> 4]; + index16++; + } + glBindTexture(GL_TEXTURE_2D, Textures[0]); + glTexSubImage2D(GL_TEXTURE_2D, 0, + (tile_n & 0x1F)<<3, (tile_n >> 5)<<3, + 8, 8, GL_RGBA, + GL_UNSIGNED_SHORT_1_5_5_5_REV, indexBMP); + } + + glBegin(GL_QUADS); + glTexCoord2f(0.0, 0.0); glVertex2d(-1.0, 1.0); + glTexCoord2f(0.0, 1.0); glVertex2d(-1.0,-1.0); + glTexCoord2f(1.0, 1.0); glVertex2d( 1.0,-1.0); + glTexCoord2f(1.0, 0.0); glVertex2d( 1.0, 1.0); + glEnd(); + + my_gl_End(screen); + glDeleteTextures(3, &Textures); } + +#endif + #endif diff --git a/desmume/src/gtk-glade/dTools/callbacks_dtools.h b/src/gtk-glade/dTools/callbacks_dtools.h similarity index 100% rename from desmume/src/gtk-glade/dTools/callbacks_dtools.h rename to src/gtk-glade/dTools/callbacks_dtools.h diff --git a/desmume/src/gtk-glade/dTools/dTools_display.h b/src/gtk-glade/dTools/dTools_display.h similarity index 100% rename from desmume/src/gtk-glade/dTools/dTools_display.h rename to src/gtk-glade/dTools/dTools_display.h diff --git a/desmume/src/gtk-glade/desmume-glade.desktop b/src/gtk-glade/desmume-glade.desktop similarity index 100% rename from desmume/src/gtk-glade/desmume-glade.desktop rename to src/gtk-glade/desmume-glade.desktop diff --git a/desmume/src/gtk-glade/desmume.cpp b/src/gtk-glade/desmume.cpp similarity index 98% rename from desmume/src/gtk-glade/desmume.cpp rename to src/gtk-glade/desmume.cpp index 3d692781d..be83830e9 100755 --- a/desmume/src/gtk-glade/desmume.cpp +++ b/src/gtk-glade/desmume.cpp @@ -63,7 +63,11 @@ int desmume_open(const char *filename) int i; noticed_3D=FALSE; clear_savestates(); +#ifdef EXPERIMENTAL_GBASLOT i = NDS_LoadROM(filename); +#else + i = NDS_LoadROM(filename, NULL); +#endif return i; } diff --git a/desmume/src/gtk-glade/desmume.h b/src/gtk-glade/desmume.h similarity index 100% rename from desmume/src/gtk-glade/desmume.h rename to src/gtk-glade/desmume.h diff --git a/desmume/src/gtk-glade/doc/Makefile.am b/src/gtk-glade/doc/Makefile.am similarity index 100% rename from desmume/src/gtk-glade/doc/Makefile.am rename to src/gtk-glade/doc/Makefile.am diff --git a/desmume/src/gtk-glade/doc/desmume-glade.1 b/src/gtk-glade/doc/desmume-glade.1 similarity index 100% rename from desmume/src/gtk-glade/doc/desmume-glade.1 rename to src/gtk-glade/doc/desmume-glade.1 diff --git a/desmume/src/gtk-glade/gdk_3Demu.cpp b/src/gtk-glade/gdk_3Demu.cpp similarity index 100% rename from desmume/src/gtk-glade/gdk_3Demu.cpp rename to src/gtk-glade/gdk_3Demu.cpp diff --git a/desmume/src/gtk-glade/gdk_3Demu.h b/src/gtk-glade/gdk_3Demu.h similarity index 100% rename from desmume/src/gtk-glade/gdk_3Demu.h rename to src/gtk-glade/gdk_3Demu.h diff --git a/desmume/src/gtk-glade/gdk_gl.cpp b/src/gtk-glade/gdk_gl.cpp similarity index 100% rename from desmume/src/gtk-glade/gdk_gl.cpp rename to src/gtk-glade/gdk_gl.cpp diff --git a/desmume/src/gtk-glade/gdk_gl.h b/src/gtk-glade/gdk_gl.h similarity index 100% rename from desmume/src/gtk-glade/gdk_gl.h rename to src/gtk-glade/gdk_gl.h diff --git a/desmume/src/gtk-glade/glade-xml.cpp b/src/gtk-glade/glade-xml.cpp similarity index 100% rename from desmume/src/gtk-glade/glade-xml.cpp rename to src/gtk-glade/glade-xml.cpp diff --git a/desmume/src/gtk-glade/glade/DeSmuME.xpm b/src/gtk-glade/glade/DeSmuME.xpm similarity index 100% rename from desmume/src/gtk-glade/glade/DeSmuME.xpm rename to src/gtk-glade/glade/DeSmuME.xpm diff --git a/desmume/src/gtk-glade/glade/DeSmuMe.glade b/src/gtk-glade/glade/DeSmuMe.glade similarity index 100% rename from desmume/src/gtk-glade/glade/DeSmuMe.glade rename to src/gtk-glade/glade/DeSmuMe.glade diff --git a/desmume/src/gtk-glade/glade/DeSmuMe_Dtools.glade b/src/gtk-glade/glade/DeSmuMe_Dtools.glade similarity index 100% rename from desmume/src/gtk-glade/glade/DeSmuMe_Dtools.glade rename to src/gtk-glade/glade/DeSmuMe_Dtools.glade diff --git a/desmume/src/gtk-glade/globals.h b/src/gtk-glade/globals.h similarity index 99% rename from desmume/src/gtk-glade/globals.h rename to src/gtk-glade/globals.h index fe6d3f7cd..658c409d0 100755 --- a/desmume/src/gtk-glade/globals.h +++ b/src/gtk-glade/globals.h @@ -86,6 +86,7 @@ typedef union _callback_arg{ #include "../registers.h" #include "../armcpu.h" #include "../NDSSystem.h" +#include "../cflash.h" #include "../sndsdl.h" #include "../ctrlssdl.h" #include "../types.h" diff --git a/desmume/src/gtk-glade/keyval_names.cpp b/src/gtk-glade/keyval_names.cpp similarity index 100% rename from desmume/src/gtk-glade/keyval_names.cpp rename to src/gtk-glade/keyval_names.cpp diff --git a/desmume/src/gtk-glade/keyval_names.h b/src/gtk-glade/keyval_names.h similarity index 100% rename from desmume/src/gtk-glade/keyval_names.h rename to src/gtk-glade/keyval_names.h diff --git a/desmume/src/gtk-glade/main.cpp b/src/gtk-glade/main.cpp similarity index 100% rename from desmume/src/gtk-glade/main.cpp rename to src/gtk-glade/main.cpp diff --git a/desmume/src/gtk/DeSmuME.xpm b/src/gtk/DeSmuME.xpm similarity index 100% rename from desmume/src/gtk/DeSmuME.xpm rename to src/gtk/DeSmuME.xpm diff --git a/desmume/src/gtk/Makefile.am b/src/gtk/Makefile.am similarity index 100% rename from desmume/src/gtk/Makefile.am rename to src/gtk/Makefile.am diff --git a/desmume/src/gtk/cheatsGTK.cpp b/src/gtk/cheatsGTK.cpp similarity index 100% rename from desmume/src/gtk/cheatsGTK.cpp rename to src/gtk/cheatsGTK.cpp diff --git a/desmume/src/gtk/cheatsGTK.h b/src/gtk/cheatsGTK.h similarity index 100% rename from desmume/src/gtk/cheatsGTK.h rename to src/gtk/cheatsGTK.h diff --git a/desmume/src/gtk/dTool.h b/src/gtk/dTool.h similarity index 75% rename from desmume/src/gtk/dTool.h rename to src/gtk/dTool.h index 82685b3f7..e758f8aa5 100644 --- a/desmume/src/gtk/dTool.h +++ b/src/gtk/dTool.h @@ -10,9 +10,7 @@ typedef void (*dTool_closeFn)(); typedef struct { - /* this should be the same name of the action in the gui xml */ - const char shortname[16]; - const char name[32]; + const char name[64]; dTool_openFn open; dTool_updateFn update; dTool_closeFn close; diff --git a/desmume/src/gtk/dToolsList.cpp b/src/gtk/dToolsList.cpp similarity index 94% rename from desmume/src/gtk/dToolsList.cpp rename to src/gtk/dToolsList.cpp index 1b7e24d16..1438d1d0c 100644 --- a/desmume/src/gtk/dToolsList.cpp +++ b/src/gtk/dToolsList.cpp @@ -27,5 +27,5 @@ dTool_t *dTools_list[] = &dTool_ioregsView }; -int dTools_list_size = ARRAY_SIZE(dTools_list); +int dTools_list_size = 1; diff --git a/desmume/src/gtk/desmume.cpp b/src/gtk/desmume.cpp similarity index 100% rename from desmume/src/gtk/desmume.cpp rename to src/gtk/desmume.cpp diff --git a/desmume/src/gtk/desmume.desktop b/src/gtk/desmume.desktop similarity index 100% rename from desmume/src/gtk/desmume.desktop rename to src/gtk/desmume.desktop diff --git a/desmume/src/gtk/desmume.h b/src/gtk/desmume.h similarity index 100% rename from desmume/src/gtk/desmume.h rename to src/gtk/desmume.h diff --git a/desmume/src/gtk/desmume_config.cpp b/src/gtk/desmume_config.cpp similarity index 100% rename from desmume/src/gtk/desmume_config.cpp rename to src/gtk/desmume_config.cpp diff --git a/desmume/src/gtk/desmume_config.h b/src/gtk/desmume_config.h similarity index 100% rename from desmume/src/gtk/desmume_config.h rename to src/gtk/desmume_config.h diff --git a/desmume/src/gtk/doc/Makefile.am b/src/gtk/doc/Makefile.am similarity index 100% rename from desmume/src/gtk/doc/Makefile.am rename to src/gtk/doc/Makefile.am diff --git a/desmume/src/gtk/doc/desmume.1 b/src/gtk/doc/desmume.1 similarity index 100% rename from desmume/src/gtk/doc/desmume.1 rename to src/gtk/doc/desmume.1 diff --git a/desmume/src/gtk/main.cpp b/src/gtk/main.cpp similarity index 98% rename from desmume/src/gtk/main.cpp rename to src/gtk/main.cpp index 600feb80e..1da1a0a19 100644 --- a/desmume/src/gtk/main.cpp +++ b/src/gtk/main.cpp @@ -49,8 +49,6 @@ #include "commandline.h" -#include "addons.h" - #ifdef GDB_STUB #include "gdbstub.h" #endif @@ -70,6 +68,8 @@ #define HAVE_TIMEOUT 1 #endif +static const char *bad_glob_cflash_disk_image_file; + #define SCREENS_PIXEL_SIZE (256*192*2) #define SCREEN_BYTES_PER_PIXEL 3 #define GAP_SIZE 50 @@ -226,7 +226,7 @@ static const char *ui_description = " " " " "

" -" " +" " " " " " " " @@ -421,6 +421,7 @@ fill_configured_features( struct configured_features *config, "\t\t\t\t 4 = Italian\n" "\t\t\t\t 5 = Spanish\n", "LANG"}, + { "cflash", 0, 0, G_OPTION_ARG_FILENAME, &config->cflash_disk_image_file, "Enable disk image GBAMP compact flash emulation", "PATH_TO_DISK_IMAGE"}, #ifdef HAVE_TIMEOUT { "timeout", 0, 0, G_OPTION_ARG_INT, &config->timeout, "Quit desmume after the specified seconds for testing purpose.", "SECONDS"}, #endif @@ -573,10 +574,14 @@ static void ToggleStatusbarVisible(GtkToggleAction *action) -static int Open(const char *filename) +static int Open(const char *filename, const char *cflash_disk_image) { int res; +#ifdef EXPERIMENTAL_GBASLOT res = NDS_LoadROM( filename ); +#else + res = NDS_LoadROM( filename, cflash_disk_image ); +#endif if(res > 0) gtk_action_set_sensitive(gtk_action_group_get_action(action_group, "cheatlist"), TRUE); return res; @@ -888,7 +893,7 @@ static void OpenNdsDialog() switch(gtk_dialog_run(GTK_DIALOG(pFileSelection))) { case GTK_RESPONSE_OK: sPath = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(pFileSelection)); - if(Open((const char*)sPath) < 0) { + if(Open((const char*)sPath, bad_glob_cflash_disk_image_file) < 0) { GtkWidget *pDialog = gtk_message_dialog_new(GTK_WINDOW(pFileSelection), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, @@ -1682,7 +1687,8 @@ static void desmume_gtk_menu_tools (GtkActionGroup *ag) gint i; for(i = 0; i < dTools_list_size; i++) { GtkAction *act; - act = gtk_action_new(dTools_list[i]->shortname, dTools_list[i]->name, NULL, NULL); + //FIXME: remove hardcoded 'ioregtool' from here and in ui_description + act = gtk_action_new("ioregtool", dTools_list[i]->name, NULL, NULL); g_signal_connect(G_OBJECT(act), "activate", G_CALLBACK(Start_dTool), GINT_TO_POINTER(i)); gtk_action_group_add_action(ag, GTK_ACTION(act)); } @@ -1730,23 +1736,7 @@ common_gtk_main( struct configured_features *my_config) fw_config.language = my_config->firmware_language; } - //------------------addons---------- - my_config->process_addonCommands(); - addon_type = NDS_ADDON_NONE; - if (my_config->is_cflash_configured) - addon_type = NDS_ADDON_CFLASH; - - switch (addon_type) { - case NDS_ADDON_CFLASH: - case NDS_ADDON_RUMBLEPAK: - case NDS_ADDON_NONE: - case NDS_ADDON_GBAGAME: - break; - default: - addon_type = NDS_ADDON_NONE; - break; - } - addonsChangePak (addon_type); + bad_glob_cflash_disk_image_file = my_config->cflash_disk_image_file; #ifdef GDB_STUB if ( my_config->arm9_gdb_port != 0) { @@ -1907,9 +1897,11 @@ common_gtk_main( struct configured_features *my_config) } } - //Set the 3D emulation to use + /* + * Set the 3D emulation to use + */ unsigned core = my_config->engine_3d; - // setup the gdk 3D emulation; + /* setup the gdk 3D emulation; */ #if defined(HAVE_LIBOSMESA) if(my_config->engine_3d == 2){ core = init_osmesa_3Demu() ? 2 : GPU3D_NULL; @@ -1923,9 +1915,9 @@ common_gtk_main( struct configured_features *my_config) backup_setManualBackupType(my_config->savetype); - // Command line arg + /* Command line arg */ if( my_config->nds_file != "") { - if(Open( my_config->nds_file.c_str()) >= 0) { + if(Open( my_config->nds_file.c_str(), bad_glob_cflash_disk_image_file) >= 0) { my_config->process_movieCommands(); if(my_config->load_slot){ diff --git a/desmume/src/gtk/main.h b/src/gtk/main.h similarity index 100% rename from desmume/src/gtk/main.h rename to src/gtk/main.h diff --git a/desmume/src/gtk/osmesa_3Demu.cpp b/src/gtk/osmesa_3Demu.cpp similarity index 100% rename from desmume/src/gtk/osmesa_3Demu.cpp rename to src/gtk/osmesa_3Demu.cpp diff --git a/desmume/src/gtk/osmesa_3Demu.h b/src/gtk/osmesa_3Demu.h similarity index 100% rename from desmume/src/gtk/osmesa_3Demu.h rename to src/gtk/osmesa_3Demu.h diff --git a/desmume/src/gtk/tools/ioregsView.cpp b/src/gtk/tools/ioregsView.cpp similarity index 99% rename from desmume/src/gtk/tools/ioregsView.cpp rename to src/gtk/tools/ioregsView.cpp index cf75b1530..c701b4791 100644 --- a/desmume/src/gtk/tools/ioregsView.cpp +++ b/src/gtk/tools/ioregsView.cpp @@ -25,7 +25,6 @@ #include "../MMU.h" -#define SHORTNAME "ioregs" #define TOOL_NAME "IO regs view" BOOL CPUS [2] = {TRUE, TRUE}; @@ -473,7 +472,6 @@ static void open(int ID) dTool_t dTool_ioregsView = { - SHORTNAME, TOOL_NAME, &open, &update, diff --git a/desmume/src/gtk/tools/ioregsView.h b/src/gtk/tools/ioregsView.h similarity index 100% rename from desmume/src/gtk/tools/ioregsView.h rename to src/gtk/tools/ioregsView.h diff --git a/desmume/src/instruction_tabdef.inc b/src/instruction_tabdef.inc similarity index 100% rename from desmume/src/instruction_tabdef.inc rename to src/instruction_tabdef.inc diff --git a/desmume/src/matrix.cpp b/src/matrix.cpp similarity index 92% rename from desmume/src/matrix.cpp rename to src/matrix.cpp index f611473c6..b298cb4fe 100644 --- a/desmume/src/matrix.cpp +++ b/src/matrix.cpp @@ -127,11 +127,16 @@ void MatrixTranspose(float *matrix) #undef swap } -void MATRIXFASTCALL MatrixIdentity (float *matrix) +void MATRIXFASTCALL MatrixIdentity (float *matrix) //============== TODO { - matrix[1] = matrix[2] = matrix[3] = matrix[4] = 0.0f; - matrix[6] = matrix[7] = matrix[8] = matrix[9] = 0.0f; - matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0.0f; + //memset (matrix, 0, sizeof(float)*16); + //this is fastest for SSE2 i think. + //study code generation and split into sse2 specific module later + for(int i=0;i<16;i++) + matrix[i] = 0.0f; + //matrix[1] = matrix[2] = matrix[3] = matrix[4] = 0.0f; + //matrix[6] = matrix[7] = matrix[8] = matrix[9] = 0.0f; + //matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0.0f; matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1.f; } @@ -150,23 +155,7 @@ void MATRIXFASTCALL MatrixSet (float *matrix, int x, int y, float value) // TODO void MATRIXFASTCALL MatrixCopy (float* matrixDST, const float* matrixSRC) { - matrixDST[0] = matrixSRC[0]; - matrixDST[1] = matrixSRC[1]; - matrixDST[2] = matrixSRC[2]; - matrixDST[3] = matrixSRC[3]; - matrixDST[4] = matrixSRC[4]; - matrixDST[5] = matrixSRC[5]; - matrixDST[6] = matrixSRC[6]; - matrixDST[7] = matrixSRC[7]; - matrixDST[8] = matrixSRC[8]; - matrixDST[9] = matrixSRC[9]; - matrixDST[10] = matrixSRC[10]; - matrixDST[11] = matrixSRC[11]; - matrixDST[12] = matrixSRC[12]; - matrixDST[13] = matrixSRC[13]; - matrixDST[14] = matrixSRC[14]; - matrixDST[15] = matrixSRC[15]; - + memcpy ((void*)matrixDST, matrixSRC, sizeof(float)*16); } int MATRIXFASTCALL MatrixCompare (const float* matrixDST, const float* matrixSRC) diff --git a/desmume/src/matrix.h b/src/matrix.h similarity index 94% rename from desmume/src/matrix.h rename to src/matrix.h index f87ed8ec2..a0687691f 100644 --- a/desmume/src/matrix.h +++ b/src/matrix.h @@ -53,9 +53,6 @@ void MatrixInit (float *matrix); #define MatrixMultiply _sse2_MatrixMultiply #define MatrixTranslate _sse2_MatrixTranslate #define MatrixScale _sse2_MatrixScale -void MATRIXFASTCALL _sse2_fix2float_16 (float* matrix, float* divizor_mask); -void MATRIXFASTCALL _sse2_fix2float_12 (float* matrix, float* divizor_mask); -void MATRIXFASTCALL _sse2_MatrixMultVec4x4_M2 (const float * matrix, float * vecPtr); // mode 2 #else #define SSE2_FUNC(X) X #endif diff --git a/desmume/src/matrix_sse2-x64.asm b/src/matrix_sse2-x64.asm similarity index 100% rename from desmume/src/matrix_sse2-x64.asm rename to src/matrix_sse2-x64.asm diff --git a/desmume/src/matrix_sse2-x86.asm b/src/matrix_sse2-x86.asm similarity index 68% rename from desmume/src/matrix_sse2-x86.asm rename to src/matrix_sse2-x86.asm index 4f2ddf30e..550bbe515 100644 --- a/desmume/src/matrix_sse2-x86.asm +++ b/src/matrix_sse2-x86.asm @@ -41,35 +41,6 @@ ret 0 @_sse2_MatrixMultVec4x4@8 ENDP -@_sse2_MatrixMultVec4x4_M2@8 PROC PUBLIC - movaps xmm4, XMMWORD PTR [edx] - pshufd xmm5, xmm4, 01010101b - pshufd xmm6, xmm4, 10101010b - pshufd xmm7, xmm4, 11111111b - shufps xmm4, xmm4, 00000000b - mulps xmm4, XMMWORD PTR [ecx+64] - mulps xmm5, XMMWORD PTR [ecx+80] - mulps xmm6, XMMWORD PTR [ecx+96] - mulps xmm7, XMMWORD PTR [ecx+112] - addps xmm4, xmm5 - addps xmm4, xmm6 - addps xmm4, xmm7 - pshufd xmm5, xmm4, 01010101b - pshufd xmm6, xmm4, 10101010b - pshufd xmm7, xmm4, 11111111b - shufps xmm4, xmm4, 00000000b - mulps xmm4, XMMWORD PTR [ecx] - mulps xmm5, XMMWORD PTR [ecx+16] - mulps xmm6, XMMWORD PTR [ecx+32] - mulps xmm7, XMMWORD PTR [ecx+48] - addps xmm4, xmm5 - addps xmm4, xmm6 - addps xmm4, xmm7 - movaps XMMWORD PTR [edx], xmm4 - ret 0 -@_sse2_MatrixMultVec4x4_M2@8 ENDP - - @_sse2_MatrixMultVec3x3@8 PROC PUBLIC movaps xmm4, XMMWORD PTR [edx] pshufd xmm5, xmm4, 01010101b @@ -177,38 +148,5 @@ ret 0 @_sse2_MatrixScale@8 ENDP -@_sse2_fix2float_12@8 PROC PUBLIC - movaps xmm0, XMMWORD PTR[ecx] - movaps xmm1, XMMWORD PTR[ecx+16] - movaps xmm2, XMMWORD PTR[ecx+32] - movaps xmm4, XMMWORD PTR [edx] - ;prefetchnta [ecx+64] - divps xmm0, xmm4 - divps xmm1, xmm4 - divps xmm2, xmm4 - movaps XMMWORD PTR[ecx], xmm0 - movaps XMMWORD PTR[ecx+16],xmm1 - movaps XMMWORD PTR[ecx+32],xmm2 - ret 0 -@_sse2_fix2float_12@8 ENDP - -@_sse2_fix2float_16@8 PROC PUBLIC - movaps xmm0, XMMWORD PTR[ecx] - movaps xmm1, XMMWORD PTR[ecx+16] - movaps xmm2, XMMWORD PTR[ecx+32] - movaps xmm3, XMMWORD PTR[ecx+48] - movaps xmm4, XMMWORD PTR [edx] - ;prefetchnta [ecx+64] - divps xmm0, xmm4 - divps xmm1, xmm4 - divps xmm2, xmm4 - divps xmm3, xmm4 - movaps XMMWORD PTR[ecx], xmm0 - movaps XMMWORD PTR[ecx+16],xmm1 - movaps XMMWORD PTR[ecx+32],xmm2 - movaps XMMWORD PTR[ecx+48],xmm3 - ret 0 -@_sse2_fix2float_16@8 ENDP - end diff --git a/desmume/src/mc.cpp b/src/mc.cpp similarity index 100% rename from desmume/src/mc.cpp rename to src/mc.cpp diff --git a/desmume/src/mc.h b/src/mc.h similarity index 100% rename from desmume/src/mc.h rename to src/mc.h diff --git a/desmume/src/mem.h b/src/mem.h similarity index 100% rename from desmume/src/mem.h rename to src/mem.h diff --git a/desmume/src/memorystream.h b/src/memorystream.h similarity index 100% rename from desmume/src/memorystream.h rename to src/memorystream.h diff --git a/desmume/src/mic.cpp b/src/mic.cpp similarity index 100% rename from desmume/src/mic.cpp rename to src/mic.cpp diff --git a/desmume/src/mic.h b/src/mic.h similarity index 100% rename from desmume/src/mic.h rename to src/mic.h diff --git a/desmume/src/movie.cpp b/src/movie.cpp similarity index 100% rename from desmume/src/movie.cpp rename to src/movie.cpp diff --git a/desmume/src/movie.h b/src/movie.h similarity index 100% rename from desmume/src/movie.h rename to src/movie.h diff --git a/desmume/src/rasterize.cpp b/src/rasterize.cpp similarity index 94% rename from desmume/src/rasterize.cpp rename to src/rasterize.cpp index 2ebd066a7..1e6a48c59 100644 --- a/desmume/src/rasterize.cpp +++ b/src/rasterize.cpp @@ -191,7 +191,6 @@ struct PolyAttr u8 polyid; u8 alpha; bool backfacing; - bool translucent; bool isVisible(bool backfacing) { @@ -237,7 +236,7 @@ struct Fragment u8 stencil; - u8 isTranslucentPoly; + u8 pad; }; static VERT* verts[MAX_CLIPPED_VERTS]; @@ -441,12 +440,16 @@ struct Shader static FORCEINLINE void alphaBlend(FragmentColor & dst, const FragmentColor & src) { - u8 dstAlpha = dst.a; if(gfx3d.enableAlphaBlending) { if(src.a == 0) + { + dst.a = max(src.a,dst.a); + } + else if(src.a == 31 || dst.a == 0) { dst = src; + dst.a = max(src.a,dst.a); } else { @@ -455,9 +458,8 @@ static FORCEINLINE void alphaBlend(FragmentColor & dst, const FragmentColor & sr dst.r = (alpha*src.r + invAlpha*dst.r)>>5; dst.g = (alpha*src.g + invAlpha*dst.g)>>5; dst.b = (alpha*src.b + invAlpha*dst.b)>>5; + dst.a = max(src.a,dst.a); } - - dst.a = max(src.a,dst.a); } else { @@ -574,8 +576,6 @@ static FORCEINLINE void pixel(int adr,float r, float g, float b, float invu, flo if(isOpaquePixel) { destFragment.polyid.opaque = polyAttr.polyid; - destFragment.isTranslucentPoly = polyAttr.translucent?1:0; - destFragmentColor = shaderOutput; } else { @@ -597,11 +597,11 @@ static FORCEINLINE void pixel(int adr,float r, float g, float b, float invu, flo //but, it looks bad in that game. this is actually correct //if this isnt correct, then complex shape cart shadows in mario kart don't work right destFragment.polyid.translucent = polyAttr.polyid; - - //alpha blending and write color - alphaBlend(destFragmentColor, shaderOutput); } + //alpha blending and write color + alphaBlend(destFragmentColor, shaderOutput); + //depth writing if(isOpaquePixel || polyAttr.translucentDepthWrite) destFragment.depth = depth; @@ -979,55 +979,6 @@ static void SoftRastVramReconfigureSignal() { TexCache_Invalidate(); } -static void SoftRastFramebufferProcess() -{ - //this is not very accurate, but it works roughly - if(gfx3d.enableEdgeMarking) - { - u8 clearPolyid = ((gfx3d.clearColor>>24)&0x3F)>>3; - - //TODO - need to test and find out whether these get grabbed at flush time, or at render time - //we can do this by rendering a 3d frame and then freezing the system, but only changing the edge mark colors - - //now, I am not entirely sure about this. I can't find any documentation about the high bit here but - //it doesnt seem plausible to me that its all or nothing. I think that only polyid groups with a color - //with the high bit set get edge marked. - u16 edgeMarkColors[8]; - bool edgeMarkEnables[8]; - for(int i=0;i<8;i++) - { - edgeMarkColors[i] = T1ReadWord(MMU.MMU_MEM[ARMCPU_ARM9][0x40], 0x330+i*2); - edgeMarkEnables[i] = (edgeMarkColors[i]&0x8000)!=0; - } - - for(int i=0,y=0;y<192;y++) - { - for(int x=0;x<256;x++,i++) - { - Fragment &destFragment = screen[i]; - FragmentColor &destFragmentColor = screenColor[i]; - u8 self = destFragment.polyid.opaque>>3; - if(!edgeMarkEnables[self]) continue; - if(destFragment.isTranslucentPoly) continue; - - u8 left = x==0?clearPolyid:(screen[i-1].polyid.opaque>>3); - u8 right = x==255?clearPolyid:(screen[i+1].polyid.opaque>>3); - u8 top = y==0?clearPolyid:(screen[i-256].polyid.opaque>>3); - u8 bottom = y==191?clearPolyid:(screen[i+256].polyid.opaque>>3); - - if(left != self || right != self || top != self || bottom != self) - { - destFragmentColor.color = edgeMarkColors[self]; - } - - - } - } - - } - -} - static void SoftRastConvertFramebuffer() { FragmentColor* src = screenColor; @@ -1224,7 +1175,7 @@ static void SoftRastRender() { Fragment clearFragment; FragmentColor clearFragmentColor; - clearFragment.isTranslucentPoly = 0; + clearFragment.pad = 0; clearFragmentColor.r = gfx3d.clearColor&0x1F; clearFragmentColor.g = (gfx3d.clearColor>>5)&0x1F; clearFragmentColor.b = (gfx3d.clearColor>>10)&0x1F; @@ -1257,11 +1208,11 @@ static void SoftRastRender() for(int y=0;y<192;y++) for(int x=0;x<256;x++) { - //this is tested by harry potter and the order of the phoenix. - //TODO (optimization) dont do this if we are mapped to blank memory (such as in sonic chronicles) + //this hasnt been tested + //TODO - dont do this if we are mapped to blank memory (such as in sonic chronicles) //(or use a special zero fill in the bulk clearing above) u16 col = *clearImage; - dstColor->color = RGB15TO5555(col,31*(col>>15)); + dstColor->color = RGB15TO32(255*(col>>15),col); //this is tested quite well in the sonic chronicles main map mode //where depth values are used for trees etc you can walk behind @@ -1363,7 +1314,6 @@ static void SoftRastRender() if(i == 0 || lastPolyAttr != poly->polyAttr) { polyAttr.setup(poly->polyAttr); - polyAttr.translucent = poly->isTranslucent(); lastPolyAttr = poly->polyAttr; } @@ -1410,8 +1360,6 @@ static void SoftRastRender() shape_engine(type,!polyAttr.backfacing); } - SoftRastFramebufferProcess(); - // printf("rendered %d of %d polys after backface culling\n",gfx3d.polylist->count-culled,gfx3d.polylist->count); SoftRastConvertFramebuffer(); } diff --git a/desmume/src/rasterize.h b/src/rasterize.h similarity index 100% rename from desmume/src/rasterize.h rename to src/rasterize.h diff --git a/desmume/src/readwrite.cpp b/src/readwrite.cpp similarity index 100% rename from desmume/src/readwrite.cpp rename to src/readwrite.cpp diff --git a/desmume/src/readwrite.h b/src/readwrite.h similarity index 100% rename from desmume/src/readwrite.h rename to src/readwrite.h diff --git a/desmume/src/registers.h b/src/registers.h similarity index 100% rename from desmume/src/registers.h rename to src/registers.h diff --git a/desmume/src/render3D.cpp b/src/render3D.cpp similarity index 100% rename from desmume/src/render3D.cpp rename to src/render3D.cpp diff --git a/desmume/src/render3D.h b/src/render3D.h similarity index 100% rename from desmume/src/render3D.h rename to src/render3D.h diff --git a/desmume/src/rtc.cpp b/src/rtc.cpp similarity index 100% rename from desmume/src/rtc.cpp rename to src/rtc.cpp diff --git a/desmume/src/rtc.h b/src/rtc.h similarity index 100% rename from desmume/src/rtc.h rename to src/rtc.h diff --git a/desmume/src/saves.cpp b/src/saves.cpp similarity index 97% rename from desmume/src/saves.cpp rename to src/saves.cpp index 90b011c10..9c553f335 100644 --- a/desmume/src/saves.cpp +++ b/src/saves.cpp @@ -198,11 +198,6 @@ SFORMAT SF_MMU[]={ { "MIME", 4, 2, MMU.reg_IME}, { "MIE_", 4, 2, MMU.reg_IE}, { "MIF_", 4, 2, MMU.reg_IF}, - - { "M_SX", 1, 2, &MMU.SPI_CNT}, - { "M_SC", 1, 2, &MMU.SPI_CMD}, - { "MASX", 1, 2, &MMU.AUX_SPI_CNT}, - { "MASC", 1, 2, &MMU.AUX_SPI_CMD}, { "MDST", 4, 8, MMU.DMAStartTime}, { "MDCY", 4, 8, MMU.DMACycle}, @@ -460,12 +455,7 @@ void scan_savestates() for( i = 1; i <= NB_STATES; i++ ) { - #ifdef WIN32 - GetFullPathNoExt(STATES, filename, MAX_PATH); - #else - strncpy(filename, pathFilenameToROMwithoutExt, MAX_PATH); - #endif - + strncpy(filename, pathFilenameToROMwithoutExt, MAX_PATH); if (strlen(filename) + strlen(".dst") + strlen("-2147483648") /* = biggest string for i */ >MAX_PATH) return ; sprintf(filename+strlen(filename), ".ds%d", i); if( stat(filename,&sbuf) == -1 ) continue; @@ -481,12 +471,7 @@ void savestate_slot(int num) struct stat sbuf; char filename[MAX_PATH]; - #ifdef WIN32 - GetFullPathNoExt(STATES, filename, MAX_PATH); - #else - strncpy(filename, pathFilenameToROMwithoutExt, MAX_PATH); - #endif - + strncpy(filename, pathFilenameToROMwithoutExt, MAX_PATH); if (strlen(filename) + strlen(".dsx") + strlen("-2147483648") /* = biggest string for num */ >MAX_PATH) return ; sprintf(filename+strlen(filename), ".ds%d", num); @@ -510,13 +495,7 @@ void savestate_slot(int num) void loadstate_slot(int num) { char filename[MAX_PATH]; - - #ifdef WIN32 - GetFullPathNoExt(STATES, filename, MAX_PATH); - #else - strncpy(filename, pathFilenameToROMwithoutExt, MAX_PATH); - #endif - + strncpy(filename, pathFilenameToROMwithoutExt, MAX_PATH); if (strlen(filename) + strlen(".dsx") + strlen("-2147483648") /* = biggest string for num */ >MAX_PATH) return ; sprintf(filename+strlen(filename), ".ds%d", num); if (savestate_load(filename)) diff --git a/desmume/src/saves.h b/src/saves.h similarity index 100% rename from desmume/src/saves.h rename to src/saves.h diff --git a/desmume/src/shaders.h b/src/shaders.h similarity index 100% rename from desmume/src/shaders.h rename to src/shaders.h diff --git a/desmume/src/sndsdl.cpp b/src/sndsdl.cpp similarity index 100% rename from desmume/src/sndsdl.cpp rename to src/sndsdl.cpp diff --git a/desmume/src/sndsdl.h b/src/sndsdl.h similarity index 100% rename from desmume/src/sndsdl.h rename to src/sndsdl.h diff --git a/desmume/src/softrender.cpp b/src/softrender.cpp similarity index 100% rename from desmume/src/softrender.cpp rename to src/softrender.cpp diff --git a/desmume/src/softrender.h b/src/softrender.h similarity index 100% rename from desmume/src/softrender.h rename to src/softrender.h diff --git a/desmume/src/softrender_config.h b/src/softrender_config.h similarity index 100% rename from desmume/src/softrender_config.h rename to src/softrender_config.h diff --git a/desmume/src/softrender_desmumefont.h b/src/softrender_desmumefont.h similarity index 100% rename from desmume/src/softrender_desmumefont.h rename to src/softrender_desmumefont.h diff --git a/desmume/src/softrender_v3sysfont.h b/src/softrender_v3sysfont.h similarity index 100% rename from desmume/src/softrender_v3sysfont.h rename to src/softrender_v3sysfont.h diff --git a/desmume/src/texcache.cpp b/src/texcache.cpp similarity index 100% rename from desmume/src/texcache.cpp rename to src/texcache.cpp diff --git a/desmume/src/texcache.h b/src/texcache.h similarity index 96% rename from desmume/src/texcache.h rename to src/texcache.h index 8d7f2c48a..3d6671871 100644 --- a/desmume/src/texcache.h +++ b/src/texcache.h @@ -43,7 +43,7 @@ extern void (*TexCache_BindTextureData)(u32 texnum, u8* data); void TexCache_Reset(); -template +template void TexCache_SetTexture(u32 format, u32 texpal); void TexCache_Invalidate(); diff --git a/desmume/src/thumb_instructions.cpp b/src/thumb_instructions.cpp similarity index 99% rename from desmume/src/thumb_instructions.cpp rename to src/thumb_instructions.cpp index 0113ce115..dfea7e859 100644 --- a/desmume/src/thumb_instructions.cpp +++ b/src/thumb_instructions.cpp @@ -893,20 +893,11 @@ TEMPLATE static u32 FASTCALL OP_B_COND() TEMPLATE static u32 FASTCALL OP_SWI_THUMB() { - u32 swinum = cpu->instruction & 0xFF; - - //ideas-style debug prints - if(swinum==0xFC) { - IdeasLog(cpu); - return 0; - } - if(cpu->swi_tab) { //zero 25-dec-2008 - in arm, we were masking to 0x1F. //this is probably safer since an invalid opcode could crash the emu - //zero 30-jun-2009 - but they say that the ideas 0xFF should crash the device... //u32 swinum = cpu->instruction & 0xFF; - swinum &= 0x1F; + u32 swinum = cpu->instruction & 0x1F; return cpu->swi_tab[swinum]() + 3; } else { diff --git a/desmume/src/thumb_instructions.h b/src/thumb_instructions.h similarity index 100% rename from desmume/src/thumb_instructions.h rename to src/thumb_instructions.h diff --git a/desmume/src/thumb_tabdef.inc b/src/thumb_tabdef.inc similarity index 100% rename from desmume/src/thumb_tabdef.inc rename to src/thumb_tabdef.inc diff --git a/desmume/src/types.h b/src/types.h similarity index 100% rename from desmume/src/types.h rename to src/types.h diff --git a/desmume/src/utils/ConvertUTF.c b/src/utils/ConvertUTF.c similarity index 100% rename from desmume/src/utils/ConvertUTF.c rename to src/utils/ConvertUTF.c diff --git a/desmume/src/utils/ConvertUTF.h b/src/utils/ConvertUTF.h similarity index 100% rename from desmume/src/utils/ConvertUTF.h rename to src/utils/ConvertUTF.h diff --git a/desmume/src/utils/decrypt/crc.cpp b/src/utils/decrypt/crc.cpp similarity index 100% rename from desmume/src/utils/decrypt/crc.cpp rename to src/utils/decrypt/crc.cpp diff --git a/desmume/src/utils/decrypt/crc.h b/src/utils/decrypt/crc.h similarity index 100% rename from desmume/src/utils/decrypt/crc.h rename to src/utils/decrypt/crc.h diff --git a/desmume/src/utils/decrypt/decrypt.cpp b/src/utils/decrypt/decrypt.cpp similarity index 100% rename from desmume/src/utils/decrypt/decrypt.cpp rename to src/utils/decrypt/decrypt.cpp diff --git a/desmume/src/utils/decrypt/decrypt.h b/src/utils/decrypt/decrypt.h similarity index 100% rename from desmume/src/utils/decrypt/decrypt.h rename to src/utils/decrypt/decrypt.h diff --git a/desmume/src/utils/decrypt/header.cpp b/src/utils/decrypt/header.cpp similarity index 99% rename from desmume/src/utils/decrypt/header.cpp rename to src/utils/decrypt/header.cpp index 484e7e0e8..7b8559108 100644 --- a/desmume/src/utils/decrypt/header.cpp +++ b/src/utils/decrypt/header.cpp @@ -71,7 +71,7 @@ int DetectRomType(const Header& header, char* romdata) unsigned int * data = (unsigned int*)(romdata + 0x4000); //this is attempting to check for an utterly invalid nds header - if(header.unitcode != 0 && header.unitcode != 2) return ROMTYPE_INVALID; + if(header.unitcode != 0) return ROMTYPE_INVALID; if (header.arm9_rom_offset < 0x4000) return ROMTYPE_HOMEBREW; if (data[0] == 0x00000000 && data[1] == 0x00000000) return ROMTYPE_MULTIBOOT; diff --git a/desmume/src/utils/decrypt/header.h b/src/utils/decrypt/header.h similarity index 100% rename from desmume/src/utils/decrypt/header.h rename to src/utils/decrypt/header.h diff --git a/desmume/src/utils/guid.cpp b/src/utils/guid.cpp similarity index 100% rename from desmume/src/utils/guid.cpp rename to src/utils/guid.cpp diff --git a/desmume/src/utils/guid.h b/src/utils/guid.h similarity index 100% rename from desmume/src/utils/guid.h rename to src/utils/guid.h diff --git a/desmume/src/utils/md5.cpp b/src/utils/md5.cpp similarity index 100% rename from desmume/src/utils/md5.cpp rename to src/utils/md5.cpp diff --git a/desmume/src/utils/md5.h b/src/utils/md5.h similarity index 100% rename from desmume/src/utils/md5.h rename to src/utils/md5.h diff --git a/desmume/src/utils/valuearray.h b/src/utils/valuearray.h similarity index 100% rename from desmume/src/utils/valuearray.h rename to src/utils/valuearray.h diff --git a/desmume/src/utils/xstring.cpp b/src/utils/xstring.cpp similarity index 100% rename from desmume/src/utils/xstring.cpp rename to src/utils/xstring.cpp diff --git a/desmume/src/utils/xstring.h b/src/utils/xstring.h similarity index 100% rename from desmume/src/utils/xstring.h rename to src/utils/xstring.h diff --git a/desmume/src/version.h b/src/version.h similarity index 92% rename from desmume/src/version.h rename to src/version.h index 32e6f6de2..cdfc21f16 100644 --- a/desmume/src/version.h +++ b/src/version.h @@ -77,6 +77,6 @@ #define DESMUME_COMPILER_DETAIL "" #endif -#define DESMUME_VERSION_NUMERIC 90500 -#define DESMUME_VERSION_STRING " " "0.9.5" DESMUME_SUBVERSION_STRING DESMUME_FEATURE_STRING DESMUME_PLATFORM_STRING DESMUME_CPUEXT_STRING DESMUME_COMPILER +#define DESMUME_VERSION_NUMERIC 90400 +#define DESMUME_VERSION_STRING " " "0.9.4" DESMUME_SUBVERSION_STRING DESMUME_FEATURE_STRING DESMUME_PLATFORM_STRING DESMUME_CPUEXT_STRING DESMUME_COMPILER #define DESMUME_NAME_AND_VERSION " " DESMUME_NAME DESMUME_VERSION_STRING diff --git a/desmume/src/wifi.cpp b/src/wifi.cpp similarity index 100% rename from desmume/src/wifi.cpp rename to src/wifi.cpp diff --git a/desmume/src/wifi.h b/src/wifi.h similarity index 100% rename from desmume/src/wifi.h rename to src/wifi.h diff --git a/desmume/src/windows/AboutBox.cpp b/src/windows/AboutBox.cpp similarity index 100% rename from desmume/src/windows/AboutBox.cpp rename to src/windows/AboutBox.cpp diff --git a/desmume/src/windows/AboutBox.h b/src/windows/AboutBox.h similarity index 100% rename from desmume/src/windows/AboutBox.h rename to src/windows/AboutBox.h diff --git a/desmume/src/windows/CWindow.cpp b/src/windows/CWindow.cpp similarity index 100% rename from desmume/src/windows/CWindow.cpp rename to src/windows/CWindow.cpp diff --git a/desmume/src/windows/CWindow.h b/src/windows/CWindow.h similarity index 100% rename from desmume/src/windows/CWindow.h rename to src/windows/CWindow.h diff --git a/desmume/src/windows/DeSmuME.ico b/src/windows/DeSmuME.ico similarity index 100% rename from desmume/src/windows/DeSmuME.ico rename to src/windows/DeSmuME.ico diff --git a/desmume/src/windows/DeSmuME_2005.sln b/src/windows/DeSmuME_2005.sln similarity index 100% rename from desmume/src/windows/DeSmuME_2005.sln rename to src/windows/DeSmuME_2005.sln diff --git a/desmume/src/windows/DeSmuME_2005.vcproj b/src/windows/DeSmuME_2005.vcproj similarity index 84% rename from desmume/src/windows/DeSmuME_2005.vcproj rename to src/windows/DeSmuME_2005.vcproj index 74d43851e..59ec38ca2 100644 --- a/desmume/src/windows/DeSmuME_2005.vcproj +++ b/src/windows/DeSmuME_2005.vcproj @@ -51,7 +51,7 @@ FavorSizeOrSpeed="0" EnableFiberSafeOptimizations="false" WholeProgramOptimization="false" - AdditionalIncludeDirectories=".;..;"lua\lua-5.1.4\src";"glib-2.20.1\build";"glib-2.20.1\build\glib";.\zlib123;.\zziplib;.\winpcap;userconfig;defaultconfig" + AdditionalIncludeDirectories=".;..;"glib-2.20.1\build";"glib-2.20.1\build\glib";.\zlib123;.\zziplib;.\winpcap;userconfig;defaultconfig" PreprocessorDefinitions="DEBUG;_CRT_SECURE_NO_DEPRECATE;WIN32;SPU_INTERPOLATE;HAVE_LIBZ;HAVE_LIBZZIP;NOMINMAX;DEBUG;EXPERIMENTAL_WIFI" ExceptionHandling="1" BasicRuntimeChecks="0" @@ -75,9 +75,9 @@ /> - - - - - - @@ -458,10 +446,6 @@ RelativePath=".\lightView.h" > - - @@ -510,14 +494,6 @@ RelativePath=".\ogl.cpp" > - - - - @@ -798,6 +774,14 @@ RelativePath="..\bits.h" > + + + + @@ -930,14 +914,6 @@ RelativePath="..\GPU_osd.h" > - - - - @@ -998,14 +974,6 @@ RelativePath="..\OGLRender.h" > - - - - @@ -1037,6 +1005,22 @@ + + + + + + + + + + + + + + + @@ -381,10 +385,6 @@ RelativePath="..\GPU_OSD.cpp" > - - @@ -689,18 +689,6 @@ - - - - - - @@ -757,10 +745,6 @@ RelativePath=".\lightView.cpp" > - - @@ -789,22 +773,10 @@ RelativePath=".\ogl.cpp" > - - - - - - @@ -931,10 +903,6 @@ RelativePath=".\palView.h" > - - @@ -1003,6 +971,10 @@ RelativePath="..\bits.h" > + + @@ -1067,10 +1039,6 @@ RelativePath="..\GPU_osd.h" > - - diff --git a/desmume/src/windows/DeSmuME_2010.sln b/src/windows/DeSmuME_2010.sln similarity index 92% rename from desmume/src/windows/DeSmuME_2010.sln rename to src/windows/DeSmuME_2010.sln index fad4cb2e8..e04b49ff4 100644 --- a/desmume/src/windows/DeSmuME_2010.sln +++ b/src/windows/DeSmuME_2010.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 10 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DeSmuME_VS2010", "DeSmuME_2010.vcxproj", "{9F5F72A1-D3A5-4918-B460-E076B16D10A9}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DeSmuME_VS2008", "DeSmuME_2010.vcxproj", "{9F5F72A1-D3A5-4918-B460-E076B16D10A9}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/desmume/src/windows/DeSmuME_2010.vcxproj b/src/windows/DeSmuME_2010.vcxproj similarity index 83% rename from desmume/src/windows/DeSmuME_2010.vcxproj rename to src/windows/DeSmuME_2010.vcxproj index 6adf08494..855e62d9f 100644 --- a/desmume/src/windows/DeSmuME_2010.vcxproj +++ b/src/windows/DeSmuME_2010.vcxproj @@ -55,17 +55,14 @@ .exe $(SolutionDir)\__bins\ $(SolutionDir)\.VS2010\$(Configuration)\$(Platform)\ - $(ProjectName)_release + $(ProjectName)_sse2 .exe $(SolutionDir)\__bins\ $(SolutionDir)\.VS2010\$(Configuration)\$(Platform)\ - $(ProjectName)_releaseFastBuild + $(ProjectName)_sse2 .exe - - defaultconfig\SubWCRev.bat - Disabled Disabled @@ -73,7 +70,7 @@ Neither false false - .;..;lua\lua-5.1.4\src;glib-2.20.1\build;glib-2.20.1\build\glib;.\zlib123;.\zziplib;.\winpcap;userconfig;defaultconfig;.\7z;%(AdditionalIncludeDirectories) + .;..;glib-2.20.1\build;glib-2.20.1\build\glib;.\zlib123;.\zziplib;.\winpcap;userconfig;defaultconfig;%(AdditionalIncludeDirectories) DEBUG;_CRT_SECURE_NO_DEPRECATE;WIN32;BETA_VERSION;SPU_INTERPOLATE;NOMINMAX;EXPERIMENTAL_WIFI;HAVE_LIBZ;HAVE_LIBZZIP;%(PreprocessorDefinitions) Sync EnableFastChecks @@ -85,8 +82,8 @@ Default - lua-5.1.4-x86.lib;glib-2.20.1-x86.lib;vfw32.lib;winmm.lib;opengl32.lib;glu32.lib;ws2_32.lib;user32.lib;gdi32.lib;directx\dxguid.lib;shell32.lib;comdlg32.lib;directx\dxerr8.lib;directx\dsound.lib;directx\dinput8.lib;directx\ddraw.lib;zlib-2005-x32.lib;zziplib-2005-x32.lib;shlwapi.lib;winpcap\wpcap.lib;7zip.lib;%(AdditionalDependencies) - .\zlib123;.\zziplib;glib-2.20.1\lib;lua\lib;.\7z;%(AdditionalLibraryDirectories) + glib-2.20.1-x86.lib;vfw32.lib;winmm.lib;comctl32.lib;opengl32.lib;glu32.lib;ws2_32.lib;user32.lib;gdi32.lib;directx\dxguid.lib;shell32.lib;comdlg32.lib;directx\dxerr8.lib;directx\dsound.lib;directx\dinput8.lib;directx\ddraw.lib;shlwapi.lib;winpcap\wpcap.lib;zlib-2008-x32.lib;zziplib-2008-x32.lib;%(AdditionalDependencies) + .\zlib123;.\zziplib;.\winpcap;glib-2.20.1\lib;%(AdditionalLibraryDirectories) wpcap.dll;%(DelayLoadDLLs) true true @@ -99,9 +96,6 @@ - - defaultconfig\SubWCRev.bat - MaxSpeed AnySuitable @@ -110,7 +104,7 @@ true true true - .;..;lua\lua-5.1.4\src;glib-2.20.1\build;glib-2.20.1\build\glib;.\zlib123;.\zziplib;.\winpcap;userconfig;defaultconfig;%(AdditionalIncludeDirectories) + .;..;glib-2.20.1\build;glib-2.20.1\build\glib;.\zlib123;.\zziplib;.\winpcap;userconfig;defaultconfig;%(AdditionalIncludeDirectories) _CRT_SECURE_NO_DEPRECATE;WIN32;HAVE_LIBZ;HAVE_LIBZZIP;SSE2;SPU_INTERPOLATE;NOMINMAX;RELEASE;EXPERIMENTAL_WIFI;NDEBUG;%(PreprocessorDefinitions) true Sync @@ -120,12 +114,12 @@ Fast Level1 ProgramDatabase - Cdecl + FastCall Default - lua-5.1.4-x86.lib;glib-2.20.1-x86.lib;vfw32.lib;winmm.lib;opengl32.lib;glu32.lib;ws2_32.lib;user32.lib;gdi32.lib;directx\dxguid.lib;shell32.lib;comdlg32.lib;directx\dxerr8.lib;directx\dsound.lib;directx\dinput8.lib;directx\ddraw.lib;zlib-2005-x32.lib;zziplib-2005-x32.lib;shlwapi.lib;winpcap\wpcap.lib;7zip.lib;%(AdditionalDependencies) - .\zlib123;.\zziplib;glib-2.20.1\lib;lua\lib;.\7z;%(AdditionalLibraryDirectories) + glib-2.20.1-x86.lib;vfw32.lib;winmm.lib;comctl32.lib;opengl32.lib;glu32.lib;ws2_32.lib;user32.lib;gdi32.lib;directx\dxguid.lib;shell32.lib;comdlg32.lib;directx\dxerr8.lib;directx\dsound.lib;directx\dinput8.lib;directx\ddraw.lib;shlwapi.lib;winpcap\wpcap.lib;zlib-2008-x32.lib;zziplib-2008-x32.lib;%(AdditionalDependencies) + .\zlib123;.\zziplib;.\winpcap;glib-2.20.1\lib;%(AdditionalLibraryDirectories) wpcap.dll;%(DelayLoadDLLs) true true @@ -139,9 +133,6 @@ - - defaultconfig\SubWCRev.bat - MaxSpeed AnySuitable @@ -150,7 +141,7 @@ true true false - .;..;lua\lua-5.1.4\src;glib-2.20.1\build;glib-2.20.1\build\glib;.\zlib123;.\zziplib;.\winpcap;userconfig;defaultconfig;.\7z;%(AdditionalIncludeDirectories) + .;..;glib-2.20.1\build;glib-2.20.1\build\glib;.\zlib123;.\zziplib;.\winpcap;userconfig;defaultconfig;%(AdditionalIncludeDirectories) _CRT_SECURE_NO_DEPRECATE;WIN32;HAVE_LIBZ;HAVE_LIBZZIP;SSE2;SPU_INTERPOLATE;NOMINMAX;RELEASE;EXPERIMENTAL_WIFI;NDEBUG;%(PreprocessorDefinitions) true Sync @@ -160,12 +151,12 @@ Fast Level1 ProgramDatabase - Cdecl + FastCall Default - lua-5.1.4-x86.lib;glib-2.20.1-x86.lib;vfw32.lib;winmm.lib;opengl32.lib;glu32.lib;ws2_32.lib;user32.lib;gdi32.lib;directx\dxguid.lib;shell32.lib;comdlg32.lib;directx\dxerr8.lib;directx\dsound.lib;directx\dinput8.lib;directx\ddraw.lib;zlib-2005-x32.lib;zziplib-2005-x32.lib;shlwapi.lib;winpcap\wpcap.lib;7zip.lib;%(AdditionalDependencies) - .\zlib123;.\zziplib;glib-2.20.1\lib;lua\lib;.\7z;%(AdditionalLibraryDirectories) + glib-2.20.1-x86.lib;vfw32.lib;winmm.lib;comctl32.lib;opengl32.lib;glu32.lib;ws2_32.lib;user32.lib;gdi32.lib;directx\dxguid.lib;shell32.lib;comdlg32.lib;directx\dxerr8.lib;directx\dsound.lib;directx\dinput8.lib;directx\ddraw.lib;shlwapi.lib;winpcap\wpcap.lib;zlib-2008-x32.lib;zziplib-2008-x32.lib;%(AdditionalDependencies) + .\zlib123;.\zziplib;.\winpcap;glib-2.20.1\lib;%(AdditionalLibraryDirectories) wpcap.dll;%(DelayLoadDLLs) true true @@ -189,6 +180,7 @@ + Cdecl @@ -200,11 +192,9 @@ - - @@ -229,7 +219,6 @@ - @@ -244,7 +233,6 @@ - @@ -252,9 +240,7 @@ - - @@ -284,15 +270,15 @@ - - - + + + @@ -300,6 +286,7 @@ + @@ -316,7 +303,6 @@ - @@ -352,8 +338,6 @@ - - @@ -373,9 +357,7 @@ - - diff --git a/desmume/src/windows/DeSmuME_Intel.icproj b/src/windows/DeSmuME_Intel.icproj similarity index 100% rename from desmume/src/windows/DeSmuME_Intel.icproj rename to src/windows/DeSmuME_Intel.icproj diff --git a/desmume/src/windows/DeSmuME_Intel.sln b/src/windows/DeSmuME_Intel.sln similarity index 100% rename from desmume/src/windows/DeSmuME_Intel.sln rename to src/windows/DeSmuME_Intel.sln diff --git a/desmume/src/windows/DeSmuME_Intel.vcproj b/src/windows/DeSmuME_Intel.vcproj similarity index 100% rename from desmume/src/windows/DeSmuME_Intel.vcproj rename to src/windows/DeSmuME_Intel.vcproj diff --git a/desmume/src/windows/DeSmuME_x64.manifest b/src/windows/DeSmuME_x64.manifest similarity index 100% rename from desmume/src/windows/DeSmuME_x64.manifest rename to src/windows/DeSmuME_x64.manifest diff --git a/desmume/src/windows/DeSmuME_x86.manifest b/src/windows/DeSmuME_x86.manifest similarity index 100% rename from desmume/src/windows/DeSmuME_x86.manifest rename to src/windows/DeSmuME_x86.manifest diff --git a/desmume/src/windows/FirmConfig.cpp b/src/windows/FirmConfig.cpp similarity index 100% rename from desmume/src/windows/FirmConfig.cpp rename to src/windows/FirmConfig.cpp diff --git a/desmume/src/windows/FirmConfig.h b/src/windows/FirmConfig.h similarity index 100% rename from desmume/src/windows/FirmConfig.h rename to src/windows/FirmConfig.h diff --git a/desmume/src/windows/GL/glext.h b/src/windows/GL/glext.h similarity index 100% rename from desmume/src/windows/GL/glext.h rename to src/windows/GL/glext.h diff --git a/desmume/src/windows/IORegView.cpp b/src/windows/IORegView.cpp similarity index 97% rename from desmume/src/windows/IORegView.cpp rename to src/windows/IORegView.cpp index 25e213a6b..fc6a5a0a7 100644 --- a/desmume/src/windows/IORegView.cpp +++ b/src/windows/IORegView.cpp @@ -52,7 +52,7 @@ LRESULT Ioreg_OnPaint(HWND hwnd, WPARAM wParam, LPARAM lParam) sprintf(text, "0x%08X", (int)MMU.reg_IF[ARMCPU_ARM9]); SetWindowText(GetDlgItem(hwnd, IDC_IF9), text); - sprintf(text, "%s", ((int)(MMU.reg_IME[ARMCPU_ARM9]) & 0x01)?"enabled":"disabled"); + sprintf(text, "0x%08X", (int)MMU.reg_IME[ARMCPU_ARM9]); SetWindowText(GetDlgItem(hwnd, IDC_IME9), text); sprintf(text, "0x%08X", ((u16 *)ARM9Mem.ARM9_REG)[0x0000>>1]); @@ -83,7 +83,7 @@ LRESULT Ioreg_OnPaint(HWND hwnd, WPARAM wParam, LPARAM lParam) sprintf(text, "0x%08X", (int)MMU.reg_IF[ARMCPU_ARM7]); SetWindowText(GetDlgItem(hwnd, IDC_IF7), text); - sprintf(text, "%s", ((int)(MMU.reg_IME[ARMCPU_ARM7]) & 0x01)?"enabled":"disabled"); + sprintf(text, "0x%08X", (int)MMU.reg_IME[ARMCPU_ARM7]); SetWindowText(GetDlgItem(hwnd, IDC_IME7), text); sprintf(text, "0x%08X", (int)((u32 *)MMU.ARM7_REG)[0x180>>2]); diff --git a/desmume/src/windows/IORegView.h b/src/windows/IORegView.h similarity index 100% rename from desmume/src/windows/IORegView.h rename to src/windows/IORegView.h diff --git a/desmume/src/windows/Makefile.am b/src/windows/Makefile.am similarity index 100% rename from desmume/src/windows/Makefile.am rename to src/windows/Makefile.am diff --git a/desmume/src/windows/Makefile.win b/src/windows/Makefile.win similarity index 100% rename from desmume/src/windows/Makefile.win rename to src/windows/Makefile.win diff --git a/desmume/src/windows/afxres.h b/src/windows/afxres.h similarity index 100% rename from desmume/src/windows/afxres.h rename to src/windows/afxres.h diff --git a/desmume/src/windows/aviout.cpp b/src/windows/aviout.cpp similarity index 100% rename from desmume/src/windows/aviout.cpp rename to src/windows/aviout.cpp diff --git a/desmume/src/windows/aviout.h b/src/windows/aviout.h similarity index 100% rename from desmume/src/windows/aviout.h rename to src/windows/aviout.h diff --git a/desmume/src/windows/bitmap1.bmp b/src/windows/bitmap1.bmp similarity index 100% rename from desmume/src/windows/bitmap1.bmp rename to src/windows/bitmap1.bmp diff --git a/desmume/src/windows/cheatsWin.cpp b/src/windows/cheatsWin.cpp similarity index 100% rename from desmume/src/windows/cheatsWin.cpp rename to src/windows/cheatsWin.cpp diff --git a/desmume/src/windows/cheatsWin.h b/src/windows/cheatsWin.h similarity index 100% rename from desmume/src/windows/cheatsWin.h rename to src/windows/cheatsWin.h diff --git a/desmume/src/windows/colorctrl.cpp b/src/windows/colorctrl.cpp similarity index 100% rename from desmume/src/windows/colorctrl.cpp rename to src/windows/colorctrl.cpp diff --git a/desmume/src/windows/colorctrl.h b/src/windows/colorctrl.h similarity index 100% rename from desmume/src/windows/colorctrl.h rename to src/windows/colorctrl.h diff --git a/desmume/src/windows/config.h b/src/windows/config.h similarity index 100% rename from desmume/src/windows/config.h rename to src/windows/config.h diff --git a/desmume/src/windows/console.cpp b/src/windows/console.cpp similarity index 100% rename from desmume/src/windows/console.cpp rename to src/windows/console.cpp diff --git a/desmume/src/windows/console.h b/src/windows/console.h similarity index 100% rename from desmume/src/windows/console.h rename to src/windows/console.h diff --git a/desmume/src/windows/defaultconfig/SubWCRev.bat b/src/windows/defaultconfig/SubWCRev.bat similarity index 100% rename from desmume/src/windows/defaultconfig/SubWCRev.bat rename to src/windows/defaultconfig/SubWCRev.bat diff --git a/desmume/src/windows/defaultconfig/SubWCRev.exe b/src/windows/defaultconfig/SubWCRev.exe similarity index 100% rename from desmume/src/windows/defaultconfig/SubWCRev.exe rename to src/windows/defaultconfig/SubWCRev.exe diff --git a/desmume/src/windows/defaultconfig/svnrev.h b/src/windows/defaultconfig/svnrev.h similarity index 100% rename from desmume/src/windows/defaultconfig/svnrev.h rename to src/windows/defaultconfig/svnrev.h diff --git a/desmume/src/windows/defaultconfig/svnrev_template.h b/src/windows/defaultconfig/svnrev_template.h similarity index 100% rename from desmume/src/windows/defaultconfig/svnrev_template.h rename to src/windows/defaultconfig/svnrev_template.h diff --git a/desmume/src/windows/defaultconfig/userconfig.h b/src/windows/defaultconfig/userconfig.h similarity index 100% rename from desmume/src/windows/defaultconfig/userconfig.h rename to src/windows/defaultconfig/userconfig.h diff --git a/desmume/src/windows/directx/DxErr8.lib b/src/windows/directx/DxErr8.lib similarity index 100% rename from desmume/src/windows/directx/DxErr8.lib rename to src/windows/directx/DxErr8.lib diff --git a/desmume/src/windows/directx/ddraw.h b/src/windows/directx/ddraw.h similarity index 100% rename from desmume/src/windows/directx/ddraw.h rename to src/windows/directx/ddraw.h diff --git a/desmume/src/windows/directx/ddraw.lib b/src/windows/directx/ddraw.lib similarity index 100% rename from desmume/src/windows/directx/ddraw.lib rename to src/windows/directx/ddraw.lib diff --git a/desmume/src/windows/directx/dinput.h b/src/windows/directx/dinput.h similarity index 100% rename from desmume/src/windows/directx/dinput.h rename to src/windows/directx/dinput.h diff --git a/desmume/src/windows/directx/dinput8.lib b/src/windows/directx/dinput8.lib similarity index 100% rename from desmume/src/windows/directx/dinput8.lib rename to src/windows/directx/dinput8.lib diff --git a/desmume/src/windows/directx/dsound.h b/src/windows/directx/dsound.h similarity index 100% rename from desmume/src/windows/directx/dsound.h rename to src/windows/directx/dsound.h diff --git a/desmume/src/windows/directx/dsound.lib b/src/windows/directx/dsound.lib similarity index 100% rename from desmume/src/windows/directx/dsound.lib rename to src/windows/directx/dsound.lib diff --git a/desmume/src/windows/directx/dxerr8.h b/src/windows/directx/dxerr8.h similarity index 100% rename from desmume/src/windows/directx/dxerr8.h rename to src/windows/directx/dxerr8.h diff --git a/desmume/src/windows/directx/dxguid.lib b/src/windows/directx/dxguid.lib similarity index 100% rename from desmume/src/windows/directx/dxguid.lib rename to src/windows/directx/dxguid.lib diff --git a/desmume/src/windows/disView.cpp b/src/windows/disView.cpp similarity index 100% rename from desmume/src/windows/disView.cpp rename to src/windows/disView.cpp diff --git a/desmume/src/windows/disView.h b/src/windows/disView.h similarity index 100% rename from desmume/src/windows/disView.h rename to src/windows/disView.h diff --git a/desmume/src/windows/gbaslot_config.cpp b/src/windows/gbaslot_config.cpp similarity index 81% rename from desmume/src/windows/gbaslot_config.cpp rename to src/windows/gbaslot_config.cpp index 863488e26..e170cb276 100644 --- a/desmume/src/windows/gbaslot_config.cpp +++ b/src/windows/gbaslot_config.cpp @@ -30,18 +30,17 @@ #include WNDCLASSEX wc; -HWND wndConfig = NULL; +HWND wndConfig; u8 temp_type = 0; -u8 last_type = 0; -char tmp_cflash_filename[MAX_PATH] = { 0 }; -char tmp_cflash_path[MAX_PATH] = { 0 }; -char tmp_gbagame_filename[MAX_PATH] = { 0 }; -ADDON_CFLASH_MODE tmp_CFlashMode = ADDON_CFLASH_MODE_RomPath; +u8 last_type; +char tmp_cflash_filename[MAX_PATH]; +char tmp_cflash_path[MAX_PATH]; +char tmp_gbagame_filename[MAX_PATH]; +u8 tmp_CFlashUsePath; +u8 tmp_CFlashUseRomPath; HWND OKbutton = NULL; bool _OKbutton = false; -std::string CFlashPath, CFlashName; - BOOL CALLBACK GbaSlotNone(HWND dialog, UINT msg,WPARAM wparam,LPARAM lparam) { switch(msg) @@ -63,37 +62,32 @@ BOOL CALLBACK GbaSlotCFlash(HWND dialog, UINT msg,WPARAM wparam,LPARAM lparam) { SetWindowText(GetDlgItem(dialog, IDC_PATHIMG), tmp_cflash_filename); SetWindowText(GetDlgItem(dialog, IDC_PATH), tmp_cflash_path); - switch (tmp_CFlashMode) + if (tmp_CFlashUsePath) { - case ADDON_CFLASH_MODE_Path: - CheckDlgButton(dialog, IDC_RFOLDER, BST_CHECKED); - EnableWindow(GetDlgItem(dialog, IDC_PATH), TRUE); - EnableWindow(GetDlgItem(dialog, IDC_BBROWSE2), TRUE); - EnableWindow(GetDlgItem(dialog, IDC_PATHIMG), FALSE); - EnableWindow(GetDlgItem(dialog, IDC_BBROWSE), FALSE); - if (strlen(tmp_cflash_path)) _OKbutton = TRUE; - break; - - case ADDON_CFLASH_MODE_File: - CheckDlgButton(dialog, IDC_RFILE, BST_CHECKED); - EnableWindow(GetDlgItem(dialog, IDC_PATHIMG), TRUE); - EnableWindow(GetDlgItem(dialog, IDC_BBROWSE), TRUE); - EnableWindow(GetDlgItem(dialog, IDC_BBROWSE2), FALSE); - EnableWindow(GetDlgItem(dialog, IDC_PATH), FALSE); - if (strlen(tmp_cflash_filename)) _OKbutton = TRUE; - break; - - case ADDON_CFLASH_MODE_RomPath: + if (tmp_CFlashUseRomPath) + { CheckDlgButton(dialog, IDC_PATHDESMUME, BST_CHECKED); EnableWindow(GetDlgItem(dialog, IDC_PATH), FALSE); EnableWindow(GetDlgItem(dialog, IDC_BBROWSE2), FALSE); - EnableWindow(GetDlgItem(dialog, IDC_PATHIMG), FALSE); - EnableWindow(GetDlgItem(dialog, IDC_BBROWSE), FALSE); _OKbutton = TRUE; - break; - default: - return FALSE; - + } + else + { + EnableWindow(GetDlgItem(dialog, IDC_PATH), TRUE); + EnableWindow(GetDlgItem(dialog, IDC_BBROWSE2), TRUE); + if (strlen(tmp_cflash_path)) _OKbutton = TRUE; + } + EnableWindow(GetDlgItem(dialog, IDC_PATHIMG), FALSE); + EnableWindow(GetDlgItem(dialog, IDC_BBROWSE), FALSE); + CheckDlgButton(dialog, IDC_RFOLDER, BST_CHECKED); + } + else + { + EnableWindow(GetDlgItem(dialog, IDC_BBROWSE2), FALSE); + EnableWindow(GetDlgItem(dialog, IDC_PATHDESMUME), FALSE); + EnableWindow(GetDlgItem(dialog, IDC_PATH), FALSE); + if (strlen(tmp_cflash_filename)) _OKbutton = TRUE; + CheckDlgButton(dialog, IDC_RFILE, BST_CHECKED); } return TRUE; } @@ -168,11 +162,12 @@ BOOL CALLBACK GbaSlotCFlash(HWND dialog, UINT msg,WPARAM wparam,LPARAM lparam) { if (HIWORD(wparam) == BN_CLICKED) { - tmp_CFlashMode = ADDON_CFLASH_MODE_File; + tmp_CFlashUsePath = FALSE; EnableWindow(GetDlgItem(dialog, IDC_PATHIMG), TRUE); EnableWindow(GetDlgItem(dialog, IDC_BBROWSE), TRUE); EnableWindow(GetDlgItem(dialog, IDC_BBROWSE2), FALSE); + EnableWindow(GetDlgItem(dialog, IDC_PATHDESMUME), FALSE); EnableWindow(GetDlgItem(dialog, IDC_PATH), FALSE); if (!strlen(tmp_cflash_filename)) @@ -185,30 +180,48 @@ BOOL CALLBACK GbaSlotCFlash(HWND dialog, UINT msg,WPARAM wparam,LPARAM lparam) { if (HIWORD(wparam) == BN_CLICKED) { - tmp_CFlashMode = ADDON_CFLASH_MODE_Path; + tmp_CFlashUsePath = TRUE; EnableWindow(GetDlgItem(dialog, IDC_PATHIMG), FALSE); EnableWindow(GetDlgItem(dialog, IDC_BBROWSE), FALSE); - EnableWindow(GetDlgItem(dialog, IDC_BBROWSE2), TRUE); - EnableWindow(GetDlgItem(dialog, IDC_PATH), TRUE); - if (!strlen(tmp_cflash_path)) - EnableWindow(OKbutton, FALSE); + if (IsDlgButtonChecked(dialog, IDC_PATHDESMUME)) + { + tmp_CFlashUseRomPath = TRUE; + EnableWindow(GetDlgItem(dialog, IDC_BBROWSE2), FALSE); + EnableWindow(GetDlgItem(dialog, IDC_PATH), FALSE); + EnableWindow(OKbutton, TRUE); + } + else + { + tmp_CFlashUseRomPath = FALSE; + EnableWindow(GetDlgItem(dialog, IDC_BBROWSE2), TRUE); + EnableWindow(GetDlgItem(dialog, IDC_PATH), TRUE); + } + + EnableWindow(GetDlgItem(dialog, IDC_PATHDESMUME), TRUE); } break; } case IDC_PATHDESMUME: { - if (HIWORD(wparam) == BN_CLICKED) + if (IsDlgButtonChecked(dialog, IDC_PATHDESMUME)) { - tmp_CFlashMode = ADDON_CFLASH_MODE_RomPath; - EnableWindow(GetDlgItem(dialog, IDC_PATHIMG), FALSE); - EnableWindow(GetDlgItem(dialog, IDC_BBROWSE), FALSE); - + tmp_CFlashUseRomPath = TRUE; EnableWindow(GetDlgItem(dialog, IDC_BBROWSE2), FALSE); EnableWindow(GetDlgItem(dialog, IDC_PATH), FALSE); EnableWindow(OKbutton, TRUE); } + else + { + tmp_CFlashUseRomPath = FALSE; + EnableWindow(GetDlgItem(dialog, IDC_BBROWSE2), TRUE); + EnableWindow(GetDlgItem(dialog, IDC_PATH), TRUE); + if (strlen(tmp_cflash_path)) + EnableWindow(OKbutton, TRUE); + else + EnableWindow(OKbutton, FALSE); + } break; } } @@ -385,10 +398,11 @@ void GBAslotDialog(HWND hwnd) { temp_type = addon_type; last_type = temp_type; - strcpy(tmp_cflash_filename, CFlashName.c_str()); - strcpy(tmp_cflash_path, CFlashPath.c_str()); + strcpy(tmp_cflash_filename, CFlashName); + strcpy(tmp_cflash_path, CFlashPath); strcpy(tmp_gbagame_filename, GBAgameName); - tmp_CFlashMode = CFlash_Mode; + tmp_CFlashUseRomPath = CFlashUseRomPath; + tmp_CFlashUsePath = CFlashUsePath; _OKbutton = false; u32 res=DialogBox(hAppInst, MAKEINTRESOURCE(IDD_GBASLOT), hwnd, (DLGPROC) GbaSlotBox_Proc); if (res) @@ -398,17 +412,22 @@ void GBAslotDialog(HWND hwnd) case NDS_ADDON_NONE: break; case NDS_ADDON_CFLASH: - CFlash_Mode = tmp_CFlashMode; - WritePrivateProfileInt("GBAslot.CFlash","fileMode",CFlash_Mode,IniName); - WritePrivateProfileString("GBAslot.CFlash","path",tmp_cflash_path,IniName); - WritePrivateProfileString("GBAslot.CFlash","filename",tmp_cflash_filename,IniName); - if(CFlash_Mode == ADDON_CFLASH_MODE_Path) - CFlash_Path = tmp_cflash_path; - else if(CFlash_Mode == ADDON_CFLASH_MODE_RomPath) - CFlash_Path = ""; - else - CFlash_Path = tmp_cflash_filename; - + CFlashUsePath = tmp_CFlashUsePath; + WritePrivateProfileInt("GBAslot.CFlash","usePath",CFlashUsePath,IniName); + if (tmp_CFlashUsePath) + { + if (tmp_CFlashUseRomPath) + { + CFlashUseRomPath = tmp_CFlashUseRomPath; + WritePrivateProfileInt("GBAslot.CFlash","useRomPath",CFlashUseRomPath,IniName); + break; + } + strcpy(CFlashPath, tmp_cflash_path); + WritePrivateProfileString("GBAslot.CFlash","path",CFlashPath,IniName); + break; + } + strcpy(CFlashName, tmp_cflash_filename); + WritePrivateProfileString("GBAslot.CFlash","filename",CFlashName,IniName); break; case NDS_ADDON_RUMBLEPAK: break; @@ -420,7 +439,6 @@ void GBAslotDialog(HWND hwnd) return; } WritePrivateProfileInt("GBAslot","type",temp_type,IniName); - addon_type = temp_type; addonsChangePak(addon_type); if (romloaded) diff --git a/desmume/src/windows/gbaslot_config.h b/src/windows/gbaslot_config.h similarity index 93% rename from desmume/src/windows/gbaslot_config.h rename to src/windows/gbaslot_config.h index 59f1092a0..9d9de875a 100644 --- a/desmume/src/windows/gbaslot_config.h +++ b/src/windows/gbaslot_config.h @@ -21,10 +21,6 @@ #ifndef __GBASLOT_CONFIG_H_ #define __GBASLOT_CONFIG_H_ #include "../common.h" -#include - -extern std::string CFlashPath, CFlashName; extern void GBAslotDialog(HWND hwnd); - #endif diff --git a/desmume/src/windows/ginfo.cpp b/src/windows/ginfo.cpp similarity index 100% rename from desmume/src/windows/ginfo.cpp rename to src/windows/ginfo.cpp diff --git a/desmume/src/windows/ginfo.h b/src/windows/ginfo.h similarity index 100% rename from desmume/src/windows/ginfo.h rename to src/windows/ginfo.h diff --git a/desmume/src/windows/glib-2.20.1/build/dependencies/proxy-libintl-20080918/include/libintl.h b/src/windows/glib-2.20.1/build/dependencies/proxy-libintl-20080918/include/libintl.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/dependencies/proxy-libintl-20080918/include/libintl.h rename to src/windows/glib-2.20.1/build/dependencies/proxy-libintl-20080918/include/libintl.h diff --git a/desmume/src/windows/glib-2.20.1/build/dirent/README b/src/windows/glib-2.20.1/build/dirent/README similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/dirent/README rename to src/windows/glib-2.20.1/build/dirent/README diff --git a/desmume/src/windows/glib-2.20.1/build/dirent/dirent.c b/src/windows/glib-2.20.1/build/dirent/dirent.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/dirent/dirent.c rename to src/windows/glib-2.20.1/build/dirent/dirent.c diff --git a/desmume/src/windows/glib-2.20.1/build/dirent/dirent.h b/src/windows/glib-2.20.1/build/dirent/dirent.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/dirent/dirent.h rename to src/windows/glib-2.20.1/build/dirent/dirent.h diff --git a/desmume/src/windows/glib-2.20.1/build/dirent/wdirent.c b/src/windows/glib-2.20.1/build/dirent/wdirent.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/dirent/wdirent.c rename to src/windows/glib-2.20.1/build/dirent/wdirent.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/config.h b/src/windows/glib-2.20.1/build/glib/config.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/config.h rename to src/windows/glib-2.20.1/build/glib/config.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/galias.h b/src/windows/glib-2.20.1/build/glib/galias.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/galias.h rename to src/windows/glib-2.20.1/build/glib/galias.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/galiasdef.c b/src/windows/glib-2.20.1/build/glib/galiasdef.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/galiasdef.c rename to src/windows/glib-2.20.1/build/glib/galiasdef.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/galloca.h b/src/windows/glib-2.20.1/build/glib/galloca.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/galloca.h rename to src/windows/glib-2.20.1/build/glib/galloca.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/garray.c b/src/windows/glib-2.20.1/build/glib/garray.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/garray.c rename to src/windows/glib-2.20.1/build/glib/garray.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/garray.h b/src/windows/glib-2.20.1/build/glib/garray.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/garray.h rename to src/windows/glib-2.20.1/build/glib/garray.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gasyncqueue.c b/src/windows/glib-2.20.1/build/glib/gasyncqueue.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gasyncqueue.c rename to src/windows/glib-2.20.1/build/glib/gasyncqueue.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gasyncqueue.h b/src/windows/glib-2.20.1/build/glib/gasyncqueue.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gasyncqueue.h rename to src/windows/glib-2.20.1/build/glib/gasyncqueue.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gatomic.c b/src/windows/glib-2.20.1/build/glib/gatomic.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gatomic.c rename to src/windows/glib-2.20.1/build/glib/gatomic.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gatomic.h b/src/windows/glib-2.20.1/build/glib/gatomic.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gatomic.h rename to src/windows/glib-2.20.1/build/glib/gatomic.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gbacktrace.c b/src/windows/glib-2.20.1/build/glib/gbacktrace.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gbacktrace.c rename to src/windows/glib-2.20.1/build/glib/gbacktrace.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gbacktrace.h b/src/windows/glib-2.20.1/build/glib/gbacktrace.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gbacktrace.h rename to src/windows/glib-2.20.1/build/glib/gbacktrace.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gbase64.c b/src/windows/glib-2.20.1/build/glib/gbase64.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gbase64.c rename to src/windows/glib-2.20.1/build/glib/gbase64.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gbase64.h b/src/windows/glib-2.20.1/build/glib/gbase64.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gbase64.h rename to src/windows/glib-2.20.1/build/glib/gbase64.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gbookmarkfile.c b/src/windows/glib-2.20.1/build/glib/gbookmarkfile.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gbookmarkfile.c rename to src/windows/glib-2.20.1/build/glib/gbookmarkfile.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gbookmarkfile.h b/src/windows/glib-2.20.1/build/glib/gbookmarkfile.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gbookmarkfile.h rename to src/windows/glib-2.20.1/build/glib/gbookmarkfile.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gbsearcharray.h b/src/windows/glib-2.20.1/build/glib/gbsearcharray.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gbsearcharray.h rename to src/windows/glib-2.20.1/build/glib/gbsearcharray.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gcache.c b/src/windows/glib-2.20.1/build/glib/gcache.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gcache.c rename to src/windows/glib-2.20.1/build/glib/gcache.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gcache.h b/src/windows/glib-2.20.1/build/glib/gcache.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gcache.h rename to src/windows/glib-2.20.1/build/glib/gcache.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gchecksum.c b/src/windows/glib-2.20.1/build/glib/gchecksum.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gchecksum.c rename to src/windows/glib-2.20.1/build/glib/gchecksum.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gchecksum.h b/src/windows/glib-2.20.1/build/glib/gchecksum.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gchecksum.h rename to src/windows/glib-2.20.1/build/glib/gchecksum.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gcompletion.c b/src/windows/glib-2.20.1/build/glib/gcompletion.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gcompletion.c rename to src/windows/glib-2.20.1/build/glib/gcompletion.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gcompletion.h b/src/windows/glib-2.20.1/build/glib/gcompletion.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gcompletion.h rename to src/windows/glib-2.20.1/build/glib/gcompletion.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gconvert.c b/src/windows/glib-2.20.1/build/glib/gconvert.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gconvert.c rename to src/windows/glib-2.20.1/build/glib/gconvert.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gconvert.h b/src/windows/glib-2.20.1/build/glib/gconvert.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gconvert.h rename to src/windows/glib-2.20.1/build/glib/gconvert.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gdataset.c b/src/windows/glib-2.20.1/build/glib/gdataset.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gdataset.c rename to src/windows/glib-2.20.1/build/glib/gdataset.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gdataset.h b/src/windows/glib-2.20.1/build/glib/gdataset.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gdataset.h rename to src/windows/glib-2.20.1/build/glib/gdataset.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gdatasetprivate.h b/src/windows/glib-2.20.1/build/glib/gdatasetprivate.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gdatasetprivate.h rename to src/windows/glib-2.20.1/build/glib/gdatasetprivate.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gdate.c b/src/windows/glib-2.20.1/build/glib/gdate.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gdate.c rename to src/windows/glib-2.20.1/build/glib/gdate.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gdate.h b/src/windows/glib-2.20.1/build/glib/gdate.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gdate.h rename to src/windows/glib-2.20.1/build/glib/gdate.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gdebug.h b/src/windows/glib-2.20.1/build/glib/gdebug.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gdebug.h rename to src/windows/glib-2.20.1/build/glib/gdebug.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gdir.c b/src/windows/glib-2.20.1/build/glib/gdir.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gdir.c rename to src/windows/glib-2.20.1/build/glib/gdir.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gdir.h b/src/windows/glib-2.20.1/build/glib/gdir.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gdir.h rename to src/windows/glib-2.20.1/build/glib/gdir.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gerror.c b/src/windows/glib-2.20.1/build/glib/gerror.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gerror.c rename to src/windows/glib-2.20.1/build/glib/gerror.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gerror.h b/src/windows/glib-2.20.1/build/glib/gerror.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gerror.h rename to src/windows/glib-2.20.1/build/glib/gerror.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gfileutils.c b/src/windows/glib-2.20.1/build/glib/gfileutils.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gfileutils.c rename to src/windows/glib-2.20.1/build/glib/gfileutils.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gfileutils.h b/src/windows/glib-2.20.1/build/glib/gfileutils.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gfileutils.h rename to src/windows/glib-2.20.1/build/glib/gfileutils.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/ghash.c b/src/windows/glib-2.20.1/build/glib/ghash.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/ghash.c rename to src/windows/glib-2.20.1/build/glib/ghash.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/ghash.h b/src/windows/glib-2.20.1/build/glib/ghash.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/ghash.h rename to src/windows/glib-2.20.1/build/glib/ghash.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/ghook.c b/src/windows/glib-2.20.1/build/glib/ghook.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/ghook.c rename to src/windows/glib-2.20.1/build/glib/ghook.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/ghook.h b/src/windows/glib-2.20.1/build/glib/ghook.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/ghook.h rename to src/windows/glib-2.20.1/build/glib/ghook.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gi18n-lib.h b/src/windows/glib-2.20.1/build/glib/gi18n-lib.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gi18n-lib.h rename to src/windows/glib-2.20.1/build/glib/gi18n-lib.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gi18n.h b/src/windows/glib-2.20.1/build/glib/gi18n.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gi18n.h rename to src/windows/glib-2.20.1/build/glib/gi18n.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/giochannel.c b/src/windows/glib-2.20.1/build/glib/giochannel.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/giochannel.c rename to src/windows/glib-2.20.1/build/glib/giochannel.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/giochannel.h b/src/windows/glib-2.20.1/build/glib/giochannel.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/giochannel.h rename to src/windows/glib-2.20.1/build/glib/giochannel.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/giounix.c b/src/windows/glib-2.20.1/build/glib/giounix.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/giounix.c rename to src/windows/glib-2.20.1/build/glib/giounix.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/giowin32.c b/src/windows/glib-2.20.1/build/glib/giowin32.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/giowin32.c rename to src/windows/glib-2.20.1/build/glib/giowin32.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gkeyfile.c b/src/windows/glib-2.20.1/build/glib/gkeyfile.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gkeyfile.c rename to src/windows/glib-2.20.1/build/glib/gkeyfile.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gkeyfile.h b/src/windows/glib-2.20.1/build/glib/gkeyfile.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gkeyfile.h rename to src/windows/glib-2.20.1/build/glib/gkeyfile.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/glib-object.h b/src/windows/glib-2.20.1/build/glib/glib-object.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/glib-object.h rename to src/windows/glib-2.20.1/build/glib/glib-object.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/glib.h b/src/windows/glib-2.20.1/build/glib/glib.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/glib.h rename to src/windows/glib-2.20.1/build/glib/glib.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/glibintl.h b/src/windows/glib-2.20.1/build/glib/glibintl.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/glibintl.h rename to src/windows/glib-2.20.1/build/glib/glibintl.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/glist.c b/src/windows/glib-2.20.1/build/glib/glist.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/glist.c rename to src/windows/glib-2.20.1/build/glib/glist.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/glist.h b/src/windows/glib-2.20.1/build/glib/glist.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/glist.h rename to src/windows/glib-2.20.1/build/glib/glist.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmacros.h b/src/windows/glib-2.20.1/build/glib/gmacros.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmacros.h rename to src/windows/glib-2.20.1/build/glib/gmacros.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmain.c b/src/windows/glib-2.20.1/build/glib/gmain.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmain.c rename to src/windows/glib-2.20.1/build/glib/gmain.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmain.h b/src/windows/glib-2.20.1/build/glib/gmain.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmain.h rename to src/windows/glib-2.20.1/build/glib/gmain.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmappedfile.c b/src/windows/glib-2.20.1/build/glib/gmappedfile.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmappedfile.c rename to src/windows/glib-2.20.1/build/glib/gmappedfile.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmappedfile.h b/src/windows/glib-2.20.1/build/glib/gmappedfile.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmappedfile.h rename to src/windows/glib-2.20.1/build/glib/gmappedfile.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmarkup.c b/src/windows/glib-2.20.1/build/glib/gmarkup.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmarkup.c rename to src/windows/glib-2.20.1/build/glib/gmarkup.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmarkup.h b/src/windows/glib-2.20.1/build/glib/gmarkup.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmarkup.h rename to src/windows/glib-2.20.1/build/glib/gmarkup.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmem.c b/src/windows/glib-2.20.1/build/glib/gmem.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmem.c rename to src/windows/glib-2.20.1/build/glib/gmem.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmem.h b/src/windows/glib-2.20.1/build/glib/gmem.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmem.h rename to src/windows/glib-2.20.1/build/glib/gmem.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmessages.c b/src/windows/glib-2.20.1/build/glib/gmessages.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmessages.c rename to src/windows/glib-2.20.1/build/glib/gmessages.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmessages.h b/src/windows/glib-2.20.1/build/glib/gmessages.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmessages.h rename to src/windows/glib-2.20.1/build/glib/gmessages.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gmirroringtable.h b/src/windows/glib-2.20.1/build/glib/gmirroringtable.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gmirroringtable.h rename to src/windows/glib-2.20.1/build/glib/gmirroringtable.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnode.c b/src/windows/glib-2.20.1/build/glib/gnode.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnode.c rename to src/windows/glib-2.20.1/build/glib/gnode.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnode.h b/src/windows/glib-2.20.1/build/glib/gnode.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnode.h rename to src/windows/glib-2.20.1/build/glib/gnode.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnulib/README b/src/windows/glib-2.20.1/build/glib/gnulib/README similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnulib/README rename to src/windows/glib-2.20.1/build/glib/gnulib/README diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnulib/asnprintf.c b/src/windows/glib-2.20.1/build/glib/gnulib/asnprintf.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnulib/asnprintf.c rename to src/windows/glib-2.20.1/build/glib/gnulib/asnprintf.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnulib/g-gnulib.h b/src/windows/glib-2.20.1/build/glib/gnulib/g-gnulib.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnulib/g-gnulib.h rename to src/windows/glib-2.20.1/build/glib/gnulib/g-gnulib.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf-args.c b/src/windows/glib-2.20.1/build/glib/gnulib/printf-args.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf-args.c rename to src/windows/glib-2.20.1/build/glib/gnulib/printf-args.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf-args.h b/src/windows/glib-2.20.1/build/glib/gnulib/printf-args.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf-args.h rename to src/windows/glib-2.20.1/build/glib/gnulib/printf-args.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf-parse.c b/src/windows/glib-2.20.1/build/glib/gnulib/printf-parse.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf-parse.c rename to src/windows/glib-2.20.1/build/glib/gnulib/printf-parse.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf-parse.h b/src/windows/glib-2.20.1/build/glib/gnulib/printf-parse.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf-parse.h rename to src/windows/glib-2.20.1/build/glib/gnulib/printf-parse.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf.c b/src/windows/glib-2.20.1/build/glib/gnulib/printf.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf.c rename to src/windows/glib-2.20.1/build/glib/gnulib/printf.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf.h b/src/windows/glib-2.20.1/build/glib/gnulib/printf.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnulib/printf.h rename to src/windows/glib-2.20.1/build/glib/gnulib/printf.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnulib/vasnprintf.c b/src/windows/glib-2.20.1/build/glib/gnulib/vasnprintf.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnulib/vasnprintf.c rename to src/windows/glib-2.20.1/build/glib/gnulib/vasnprintf.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gnulib/vasnprintf.h b/src/windows/glib-2.20.1/build/glib/gnulib/vasnprintf.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gnulib/vasnprintf.h rename to src/windows/glib-2.20.1/build/glib/gnulib/vasnprintf.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/goption.c b/src/windows/glib-2.20.1/build/glib/goption.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/goption.c rename to src/windows/glib-2.20.1/build/glib/goption.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/goption.h b/src/windows/glib-2.20.1/build/glib/goption.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/goption.h rename to src/windows/glib-2.20.1/build/glib/goption.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gpattern.c b/src/windows/glib-2.20.1/build/glib/gpattern.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gpattern.c rename to src/windows/glib-2.20.1/build/glib/gpattern.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gpattern.h b/src/windows/glib-2.20.1/build/glib/gpattern.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gpattern.h rename to src/windows/glib-2.20.1/build/glib/gpattern.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gpoll.c b/src/windows/glib-2.20.1/build/glib/gpoll.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gpoll.c rename to src/windows/glib-2.20.1/build/glib/gpoll.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gpoll.h b/src/windows/glib-2.20.1/build/glib/gpoll.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gpoll.h rename to src/windows/glib-2.20.1/build/glib/gpoll.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gprimes.c b/src/windows/glib-2.20.1/build/glib/gprimes.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gprimes.c rename to src/windows/glib-2.20.1/build/glib/gprimes.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gprimes.h b/src/windows/glib-2.20.1/build/glib/gprimes.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gprimes.h rename to src/windows/glib-2.20.1/build/glib/gprimes.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gprintf.c b/src/windows/glib-2.20.1/build/glib/gprintf.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gprintf.c rename to src/windows/glib-2.20.1/build/glib/gprintf.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gprintf.h b/src/windows/glib-2.20.1/build/glib/gprintf.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gprintf.h rename to src/windows/glib-2.20.1/build/glib/gprintf.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gprintfint.h b/src/windows/glib-2.20.1/build/glib/gprintfint.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gprintfint.h rename to src/windows/glib-2.20.1/build/glib/gprintfint.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gqsort.c b/src/windows/glib-2.20.1/build/glib/gqsort.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gqsort.c rename to src/windows/glib-2.20.1/build/glib/gqsort.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gqsort.h b/src/windows/glib-2.20.1/build/glib/gqsort.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gqsort.h rename to src/windows/glib-2.20.1/build/glib/gqsort.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gquark.h b/src/windows/glib-2.20.1/build/glib/gquark.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gquark.h rename to src/windows/glib-2.20.1/build/glib/gquark.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gqueue.c b/src/windows/glib-2.20.1/build/glib/gqueue.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gqueue.c rename to src/windows/glib-2.20.1/build/glib/gqueue.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gqueue.h b/src/windows/glib-2.20.1/build/glib/gqueue.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gqueue.h rename to src/windows/glib-2.20.1/build/glib/gqueue.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/grand.c b/src/windows/glib-2.20.1/build/glib/grand.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/grand.c rename to src/windows/glib-2.20.1/build/glib/grand.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/grand.h b/src/windows/glib-2.20.1/build/glib/grand.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/grand.h rename to src/windows/glib-2.20.1/build/glib/grand.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gregex.c b/src/windows/glib-2.20.1/build/glib/gregex.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gregex.c rename to src/windows/glib-2.20.1/build/glib/gregex.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gregex.h b/src/windows/glib-2.20.1/build/glib/gregex.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gregex.h rename to src/windows/glib-2.20.1/build/glib/gregex.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/grel.c b/src/windows/glib-2.20.1/build/glib/grel.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/grel.c rename to src/windows/glib-2.20.1/build/glib/grel.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/grel.h b/src/windows/glib-2.20.1/build/glib/grel.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/grel.h rename to src/windows/glib-2.20.1/build/glib/grel.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gscanner.c b/src/windows/glib-2.20.1/build/glib/gscanner.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gscanner.c rename to src/windows/glib-2.20.1/build/glib/gscanner.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gscanner.h b/src/windows/glib-2.20.1/build/glib/gscanner.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gscanner.h rename to src/windows/glib-2.20.1/build/glib/gscanner.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gscripttable.h b/src/windows/glib-2.20.1/build/glib/gscripttable.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gscripttable.h rename to src/windows/glib-2.20.1/build/glib/gscripttable.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gsequence.c b/src/windows/glib-2.20.1/build/glib/gsequence.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gsequence.c rename to src/windows/glib-2.20.1/build/glib/gsequence.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gsequence.h b/src/windows/glib-2.20.1/build/glib/gsequence.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gsequence.h rename to src/windows/glib-2.20.1/build/glib/gsequence.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gshell.c b/src/windows/glib-2.20.1/build/glib/gshell.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gshell.c rename to src/windows/glib-2.20.1/build/glib/gshell.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gshell.h b/src/windows/glib-2.20.1/build/glib/gshell.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gshell.h rename to src/windows/glib-2.20.1/build/glib/gshell.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gslice.c b/src/windows/glib-2.20.1/build/glib/gslice.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gslice.c rename to src/windows/glib-2.20.1/build/glib/gslice.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gslice.h b/src/windows/glib-2.20.1/build/glib/gslice.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gslice.h rename to src/windows/glib-2.20.1/build/glib/gslice.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gslist.c b/src/windows/glib-2.20.1/build/glib/gslist.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gslist.c rename to src/windows/glib-2.20.1/build/glib/gslist.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gslist.h b/src/windows/glib-2.20.1/build/glib/gslist.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gslist.h rename to src/windows/glib-2.20.1/build/glib/gslist.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gspawn-win32-helper-console.c b/src/windows/glib-2.20.1/build/glib/gspawn-win32-helper-console.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gspawn-win32-helper-console.c rename to src/windows/glib-2.20.1/build/glib/gspawn-win32-helper-console.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gspawn-win32-helper.c b/src/windows/glib-2.20.1/build/glib/gspawn-win32-helper.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gspawn-win32-helper.c rename to src/windows/glib-2.20.1/build/glib/gspawn-win32-helper.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gspawn-win32.c b/src/windows/glib-2.20.1/build/glib/gspawn-win32.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gspawn-win32.c rename to src/windows/glib-2.20.1/build/glib/gspawn-win32.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gspawn-win64-helper-console.c b/src/windows/glib-2.20.1/build/glib/gspawn-win64-helper-console.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gspawn-win64-helper-console.c rename to src/windows/glib-2.20.1/build/glib/gspawn-win64-helper-console.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gspawn-win64-helper.c b/src/windows/glib-2.20.1/build/glib/gspawn-win64-helper.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gspawn-win64-helper.c rename to src/windows/glib-2.20.1/build/glib/gspawn-win64-helper.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gspawn.c b/src/windows/glib-2.20.1/build/glib/gspawn.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gspawn.c rename to src/windows/glib-2.20.1/build/glib/gspawn.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gspawn.h b/src/windows/glib-2.20.1/build/glib/gspawn.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gspawn.h rename to src/windows/glib-2.20.1/build/glib/gspawn.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gstdio.c b/src/windows/glib-2.20.1/build/glib/gstdio.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gstdio.c rename to src/windows/glib-2.20.1/build/glib/gstdio.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gstdio.h b/src/windows/glib-2.20.1/build/glib/gstdio.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gstdio.h rename to src/windows/glib-2.20.1/build/glib/gstdio.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gstrfuncs.c b/src/windows/glib-2.20.1/build/glib/gstrfuncs.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gstrfuncs.c rename to src/windows/glib-2.20.1/build/glib/gstrfuncs.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gstrfuncs.h b/src/windows/glib-2.20.1/build/glib/gstrfuncs.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gstrfuncs.h rename to src/windows/glib-2.20.1/build/glib/gstrfuncs.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gstring.c b/src/windows/glib-2.20.1/build/glib/gstring.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gstring.c rename to src/windows/glib-2.20.1/build/glib/gstring.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gstring.h b/src/windows/glib-2.20.1/build/glib/gstring.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gstring.h rename to src/windows/glib-2.20.1/build/glib/gstring.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gtester.c b/src/windows/glib-2.20.1/build/glib/gtester.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gtester.c rename to src/windows/glib-2.20.1/build/glib/gtester.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gtestutils.c b/src/windows/glib-2.20.1/build/glib/gtestutils.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gtestutils.c rename to src/windows/glib-2.20.1/build/glib/gtestutils.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gtestutils.h b/src/windows/glib-2.20.1/build/glib/gtestutils.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gtestutils.h rename to src/windows/glib-2.20.1/build/glib/gtestutils.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gthread.c b/src/windows/glib-2.20.1/build/glib/gthread.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gthread.c rename to src/windows/glib-2.20.1/build/glib/gthread.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gthread.h b/src/windows/glib-2.20.1/build/glib/gthread.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gthread.h rename to src/windows/glib-2.20.1/build/glib/gthread.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gthreadpool.c b/src/windows/glib-2.20.1/build/glib/gthreadpool.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gthreadpool.c rename to src/windows/glib-2.20.1/build/glib/gthreadpool.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gthreadpool.h b/src/windows/glib-2.20.1/build/glib/gthreadpool.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gthreadpool.h rename to src/windows/glib-2.20.1/build/glib/gthreadpool.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gthreadprivate.h b/src/windows/glib-2.20.1/build/glib/gthreadprivate.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gthreadprivate.h rename to src/windows/glib-2.20.1/build/glib/gthreadprivate.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gtimer.c b/src/windows/glib-2.20.1/build/glib/gtimer.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gtimer.c rename to src/windows/glib-2.20.1/build/glib/gtimer.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gtimer.h b/src/windows/glib-2.20.1/build/glib/gtimer.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gtimer.h rename to src/windows/glib-2.20.1/build/glib/gtimer.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gtree.c b/src/windows/glib-2.20.1/build/glib/gtree.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gtree.c rename to src/windows/glib-2.20.1/build/glib/gtree.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gtree.h b/src/windows/glib-2.20.1/build/glib/gtree.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gtree.h rename to src/windows/glib-2.20.1/build/glib/gtree.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gtypes.h b/src/windows/glib-2.20.1/build/glib/gtypes.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gtypes.h rename to src/windows/glib-2.20.1/build/glib/gtypes.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gunibreak.c b/src/windows/glib-2.20.1/build/glib/gunibreak.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gunibreak.c rename to src/windows/glib-2.20.1/build/glib/gunibreak.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gunibreak.h b/src/windows/glib-2.20.1/build/glib/gunibreak.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gunibreak.h rename to src/windows/glib-2.20.1/build/glib/gunibreak.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gunichartables.h b/src/windows/glib-2.20.1/build/glib/gunichartables.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gunichartables.h rename to src/windows/glib-2.20.1/build/glib/gunichartables.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gunicode.h b/src/windows/glib-2.20.1/build/glib/gunicode.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gunicode.h rename to src/windows/glib-2.20.1/build/glib/gunicode.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gunicodeprivate.h b/src/windows/glib-2.20.1/build/glib/gunicodeprivate.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gunicodeprivate.h rename to src/windows/glib-2.20.1/build/glib/gunicodeprivate.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gunicollate.c b/src/windows/glib-2.20.1/build/glib/gunicollate.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gunicollate.c rename to src/windows/glib-2.20.1/build/glib/gunicollate.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gunicomp.h b/src/windows/glib-2.20.1/build/glib/gunicomp.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gunicomp.h rename to src/windows/glib-2.20.1/build/glib/gunicomp.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gunidecomp.c b/src/windows/glib-2.20.1/build/glib/gunidecomp.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gunidecomp.c rename to src/windows/glib-2.20.1/build/glib/gunidecomp.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gunidecomp.h b/src/windows/glib-2.20.1/build/glib/gunidecomp.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gunidecomp.h rename to src/windows/glib-2.20.1/build/glib/gunidecomp.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/guniprop.c b/src/windows/glib-2.20.1/build/glib/guniprop.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/guniprop.c rename to src/windows/glib-2.20.1/build/glib/guniprop.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gurifuncs.c b/src/windows/glib-2.20.1/build/glib/gurifuncs.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gurifuncs.c rename to src/windows/glib-2.20.1/build/glib/gurifuncs.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gurifuncs.h b/src/windows/glib-2.20.1/build/glib/gurifuncs.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gurifuncs.h rename to src/windows/glib-2.20.1/build/glib/gurifuncs.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gutf8.c b/src/windows/glib-2.20.1/build/glib/gutf8.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gutf8.c rename to src/windows/glib-2.20.1/build/glib/gutf8.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gutils.c b/src/windows/glib-2.20.1/build/glib/gutils.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gutils.c rename to src/windows/glib-2.20.1/build/glib/gutils.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gutils.h b/src/windows/glib-2.20.1/build/glib/gutils.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gutils.h rename to src/windows/glib-2.20.1/build/glib/gutils.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gwin32.c b/src/windows/glib-2.20.1/build/glib/gwin32.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gwin32.c rename to src/windows/glib-2.20.1/build/glib/gwin32.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/gwin32.h b/src/windows/glib-2.20.1/build/glib/gwin32.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/gwin32.h rename to src/windows/glib-2.20.1/build/glib/gwin32.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/libcharset/README b/src/windows/glib-2.20.1/build/glib/libcharset/README similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/libcharset/README rename to src/windows/glib-2.20.1/build/glib/libcharset/README diff --git a/desmume/src/windows/glib-2.20.1/build/glib/libcharset/libcharset.h b/src/windows/glib-2.20.1/build/glib/libcharset/libcharset.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/libcharset/libcharset.h rename to src/windows/glib-2.20.1/build/glib/libcharset/libcharset.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/libcharset/localcharset.c b/src/windows/glib-2.20.1/build/glib/libcharset/localcharset.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/libcharset/localcharset.c rename to src/windows/glib-2.20.1/build/glib/libcharset/localcharset.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/libcharset/localcharset.h b/src/windows/glib-2.20.1/build/glib/libcharset/localcharset.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/libcharset/localcharset.h rename to src/windows/glib-2.20.1/build/glib/libcharset/localcharset.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/libintl.h b/src/windows/glib-2.20.1/build/glib/libintl.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/libintl.h rename to src/windows/glib-2.20.1/build/glib/libintl.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/msvc_recommended_pragmas.h b/src/windows/glib-2.20.1/build/glib/msvc_recommended_pragmas.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/msvc_recommended_pragmas.h rename to src/windows/glib-2.20.1/build/glib/msvc_recommended_pragmas.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/COPYING b/src/windows/glib-2.20.1/build/glib/pcre/COPYING similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/COPYING rename to src/windows/glib-2.20.1/build/glib/pcre/COPYING diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre.h b/src/windows/glib-2.20.1/build/glib/pcre/pcre.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre.h rename to src/windows/glib-2.20.1/build/glib/pcre/pcre.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_chartables.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_chartables.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_chartables.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_chartables.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_compile.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_compile.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_compile.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_compile.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_config.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_config.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_config.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_config.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_dfa_exec.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_dfa_exec.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_dfa_exec.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_dfa_exec.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_exec.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_exec.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_exec.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_exec.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_fullinfo.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_fullinfo.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_fullinfo.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_fullinfo.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_get.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_get.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_get.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_get.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_globals.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_globals.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_globals.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_globals.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_info.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_info.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_info.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_info.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_internal.h b/src/windows/glib-2.20.1/build/glib/pcre/pcre_internal.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_internal.h rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_internal.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_maketables.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_maketables.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_maketables.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_maketables.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_newline.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_newline.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_newline.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_newline.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_ord2utf8.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_ord2utf8.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_ord2utf8.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_ord2utf8.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_refcount.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_refcount.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_refcount.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_refcount.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_study.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_study.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_study.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_study.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_tables.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_tables.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_tables.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_tables.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_try_flipped.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_try_flipped.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_try_flipped.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_try_flipped.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_ucp_searchfuncs.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_ucp_searchfuncs.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_ucp_searchfuncs.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_ucp_searchfuncs.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_valid_utf8.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_valid_utf8.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_valid_utf8.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_valid_utf8.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_version.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_version.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_version.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_version.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_xclass.c b/src/windows/glib-2.20.1/build/glib/pcre/pcre_xclass.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/pcre_xclass.c rename to src/windows/glib-2.20.1/build/glib/pcre/pcre_xclass.c diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/ucp.h b/src/windows/glib-2.20.1/build/glib/pcre/ucp.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/ucp.h rename to src/windows/glib-2.20.1/build/glib/pcre/ucp.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/pcre/ucpinternal.h b/src/windows/glib-2.20.1/build/glib/pcre/ucpinternal.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/pcre/ucpinternal.h rename to src/windows/glib-2.20.1/build/glib/pcre/ucpinternal.h diff --git a/desmume/src/windows/glib-2.20.1/build/glib/win_iconv.c b/src/windows/glib-2.20.1/build/glib/win_iconv.c similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glib/win_iconv.c rename to src/windows/glib-2.20.1/build/glib/win_iconv.c diff --git a/desmume/src/windows/glib-2.20.1/build/glibconfig.h b/src/windows/glib-2.20.1/build/glibconfig.h similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/glibconfig.h rename to src/windows/glib-2.20.1/build/glibconfig.h diff --git a/desmume/src/windows/glib-2.20.1/build/vs8/README b/src/windows/glib-2.20.1/build/vs8/README similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/vs8/README rename to src/windows/glib-2.20.1/build/vs8/README diff --git a/desmume/src/windows/glib-2.20.1/build/vs8/gio.vcproj b/src/windows/glib-2.20.1/build/vs8/gio.vcproj similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/vs8/gio.vcproj rename to src/windows/glib-2.20.1/build/vs8/gio.vcproj diff --git a/desmume/src/windows/glib-2.20.1/build/vs8/glib.sln b/src/windows/glib-2.20.1/build/vs8/glib.sln similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/vs8/glib.sln rename to src/windows/glib-2.20.1/build/vs8/glib.sln diff --git a/desmume/src/windows/glib-2.20.1/build/vs8/glib.vcproj b/src/windows/glib-2.20.1/build/vs8/glib.vcproj similarity index 100% rename from desmume/src/windows/glib-2.20.1/build/vs8/glib.vcproj rename to src/windows/glib-2.20.1/build/vs8/glib.vcproj diff --git a/desmume/src/windows/glib-2.20.1/lib/glib-2.20.1-x86.lib b/src/windows/glib-2.20.1/lib/glib-2.20.1-x86.lib similarity index 100% rename from desmume/src/windows/glib-2.20.1/lib/glib-2.20.1-x86.lib rename to src/windows/glib-2.20.1/lib/glib-2.20.1-x86.lib diff --git a/desmume/src/windows/glib-2.20.1/modified_for_desmume.txt b/src/windows/glib-2.20.1/modified_for_desmume.txt similarity index 100% rename from desmume/src/windows/glib-2.20.1/modified_for_desmume.txt rename to src/windows/glib-2.20.1/modified_for_desmume.txt diff --git a/desmume/src/windows/hotkey.cpp b/src/windows/hotkey.cpp similarity index 95% rename from desmume/src/windows/hotkey.cpp rename to src/windows/hotkey.cpp index 1d7cb60f2..52b5b0372 100644 --- a/desmume/src/windows/hotkey.cpp +++ b/src/windows/hotkey.cpp @@ -34,7 +34,6 @@ #include "aviout.h" #include "spu.h" #include "../GPU.h" -#include "pathsettings.h" extern LRESULT OpenFile(); //adelikat: Made this an extern here instead of main.h Seemed icky not to limit the scope of this function @@ -82,58 +81,32 @@ void HK_OpenROM(int) {OpenFile();} void HK_PrintScreen(int param) { OPENFILENAME ofn; + char * ptr; + char filename[MAX_PATH] = ""; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = MainWindow->getHWnd(); ofn.lpstrFilter = "png file (*.png)\0*.png\0Bmp file (*.bmp)\0*.bmp\0Any file (*.*)\0*.*\0\0"; ofn.nFilterIndex = 1; + ofn.lpstrFile = filename; ofn.lpstrTitle = "Print Screen Save As"; ofn.nMaxFile = MAX_PATH; ofn.lpstrDefExt = "png"; ofn.Flags = OFN_OVERWRITEPROMPT; GetSaveFileName(&ofn); - char folder[MAX_PATH]; - ZeroMemory(folder, sizeof(folder)); - GetPathFor(SCREENSHOTS, folder, MAX_PATH); - - char file[MAX_PATH]; - ZeroMemory(file, sizeof(file)); - FormatName(file, MAX_PATH); - - strcat(folder, file); - int len = strlen(folder); - if(len > MAX_PATH - 4) - folder[MAX_PATH - 4] = '\0'; - - ImageFormat format = GetImageFormatType(); - if(format == PNG) - { - strcat(folder, ".png"); - ofn.lpstrDefExt = "png"; - ofn.nFilterIndex = 1; - } - else if(format == BMP) - { - strcat(folder, ".bmp"); - ofn.lpstrDefExt = "bmp"; - ofn.nFilterIndex = 2; - } - ofn.lpstrFile = folder; - GetSaveFileName(&ofn); - - char *ptr = strrchr(folder,'.');//look for the last . in the filename + ptr = strrchr(filename,'.');//look for the last . in the filename if ( ptr != 0 ) { if (( strcmp ( ptr, ".BMP" ) == 0 ) || ( strcmp ( ptr, ".bmp" ) == 0 )) { - NDS_WriteBMP(folder); + NDS_WriteBMP(filename); } if (( strcmp ( ptr, ".PNG" ) == 0 ) || ( strcmp ( ptr, ".png" ) == 0 )) { - NDS_WritePNG(folder); + NDS_WritePNG(filename); } } } @@ -211,12 +184,6 @@ void HK_ToggleFrame(int) {frameCounterDisplay ^= true;} void HK_ToggleFPS(int) {FpsDisplay ^= true;} void HK_ToggleInput(int) {ShowInputDisplay ^= true;} void HK_ToggleLag(int) {ShowLagFrameCounter ^= true;} -void HK_ResetLagCounter(int) { - lagframecounter=0; - LagFrameFlag=0; - lastLag=0; - TotalLagFrames=0; -} void HK_ToggleReadOnly(int) { movie_readonly ^= true; if(movie_readonly) @@ -454,12 +421,6 @@ void InitCustomKeys (SCustomKeys *keys) keys->ToggleLag.page = HOTKEY_PAGE_MAIN; keys->ToggleLag.key = NULL; - keys->ResetLagCounter.handleKeyDown = HK_ResetLagCounter; - keys->ResetLagCounter.code = "ResetLagCounter"; - keys->ResetLagCounter.name = L"Reset Lag Counter"; - keys->ResetLagCounter.page = HOTKEY_PAGE_MAIN; - keys->ResetLagCounter.key = NULL; - keys->ToggleReadOnly.handleKeyDown = HK_ToggleReadOnly; keys->ToggleReadOnly.code = "ToggleReadOnly"; keys->ToggleReadOnly.name = L"Toggle Read Only"; diff --git a/desmume/src/windows/hotkey.h b/src/windows/hotkey.h similarity index 99% rename from desmume/src/windows/hotkey.h rename to src/windows/hotkey.h index 1b4a836fc..9951d38ca 100644 --- a/desmume/src/windows/hotkey.h +++ b/src/windows/hotkey.h @@ -84,7 +84,6 @@ struct SCustomKeys SCustomKey ToggleFPS; SCustomKey ToggleInput; SCustomKey ToggleLag; - SCustomKey ResetLagCounter; SCustomKey LastItem; // dummy, must be last //--methods-- diff --git a/desmume/src/windows/inputdx.cpp b/src/windows/inputdx.cpp similarity index 100% rename from desmume/src/windows/inputdx.cpp rename to src/windows/inputdx.cpp diff --git a/desmume/src/windows/inputdx.h b/src/windows/inputdx.h similarity index 100% rename from desmume/src/windows/inputdx.h rename to src/windows/inputdx.h diff --git a/desmume/src/windows/langs/build_utils/gettextlib.dll b/src/windows/langs/build_utils/gettextlib.dll similarity index 100% rename from desmume/src/windows/langs/build_utils/gettextlib.dll rename to src/windows/langs/build_utils/gettextlib.dll diff --git a/desmume/src/windows/langs/build_utils/gettextpo.dll b/src/windows/langs/build_utils/gettextpo.dll similarity index 100% rename from desmume/src/windows/langs/build_utils/gettextpo.dll rename to src/windows/langs/build_utils/gettextpo.dll diff --git a/desmume/src/windows/langs/build_utils/gettextsrc.dll b/src/windows/langs/build_utils/gettextsrc.dll similarity index 100% rename from desmume/src/windows/langs/build_utils/gettextsrc.dll rename to src/windows/langs/build_utils/gettextsrc.dll diff --git a/desmume/src/windows/langs/build_utils/iconv.dll b/src/windows/langs/build_utils/iconv.dll similarity index 100% rename from desmume/src/windows/langs/build_utils/iconv.dll rename to src/windows/langs/build_utils/iconv.dll diff --git a/desmume/src/windows/langs/build_utils/intl.dll b/src/windows/langs/build_utils/intl.dll similarity index 100% rename from desmume/src/windows/langs/build_utils/intl.dll rename to src/windows/langs/build_utils/intl.dll diff --git a/desmume/src/windows/langs/build_utils/libiconv-2.dll b/src/windows/langs/build_utils/libiconv-2.dll similarity index 100% rename from desmume/src/windows/langs/build_utils/libiconv-2.dll rename to src/windows/langs/build_utils/libiconv-2.dll diff --git a/desmume/src/windows/langs/build_utils/msgfmt.exe b/src/windows/langs/build_utils/msgfmt.exe similarity index 100% rename from desmume/src/windows/langs/build_utils/msgfmt.exe rename to src/windows/langs/build_utils/msgfmt.exe diff --git a/desmume/src/windows/langs/fr_FR.mo b/src/windows/langs/fr_FR.mo similarity index 100% rename from desmume/src/windows/langs/fr_FR.mo rename to src/windows/langs/fr_FR.mo diff --git a/desmume/src/windows/lightView.cpp b/src/windows/lightView.cpp similarity index 100% rename from desmume/src/windows/lightView.cpp rename to src/windows/lightView.cpp diff --git a/desmume/src/windows/lightView.h b/src/windows/lightView.h similarity index 100% rename from desmume/src/windows/lightView.h rename to src/windows/lightView.h diff --git a/desmume/src/windows/main.cpp b/src/windows/main.cpp similarity index 93% rename from desmume/src/windows/main.cpp rename to src/windows/main.cpp index cd96bb7c5..875471958 100644 --- a/desmume/src/windows/main.cpp +++ b/src/windows/main.cpp @@ -41,7 +41,11 @@ #include "../NDSSystem.h" #include "../debug.h" #include "../saves.h" +#ifndef EXPERIMENTAL_GBASLOT +#include "../cflash.h" +#else #include "../addons.h" +#endif #include "resource.h" #include "memView.h" #include "disView.h" @@ -79,10 +83,6 @@ #include "aviout.h" #include "soundView.h" #include "commandline.h" -#include "../lua-engine.h" -#include "7zip.h" -#include "pathsettings.h" -#include "utils/xstring.h" #include "directx/ddraw.h" @@ -132,8 +132,6 @@ void wxTest() { #endif -static BOOL OpenCore(const char* filename); - unsigned int lastSaveState = 0; //Keeps track of last savestate used for quick save/load functions //----Recent ROMs menu globals---------- vector RecentRoms; //The list of recent ROM filenames @@ -171,6 +169,12 @@ LPDIRECTDRAWCLIPPER lpDDClipBack=NULL; #define WM_CUSTKEYDOWN (WM_USER+50) #define WM_CUSTKEYUP (WM_USER+51) +#ifndef EXPERIMENTAL_GBASLOT +/* The compact flash disk image file */ +static const char *bad_glob_cflash_disk_image_file; +static char cflash_filename_buffer[512]; +#endif + /* Declare Windows procedure */ LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM); @@ -199,9 +203,6 @@ static BOOL lostFocusPause = TRUE; static BOOL lastPauseFromLostFocus = FALSE; static int FrameLimit = 1; -std::vector LuaScriptHWnds; -LRESULT CALLBACK LuaScriptProc(HWND, UINT, WPARAM, LPARAM); - //=========================== view tools TOOLSCLASS *ViewDisasm_ARM7 = NULL; TOOLSCLASS *ViewDisasm_ARM9 = NULL; @@ -488,6 +489,100 @@ VOID CALLBACK KeyInputTimer( UINT idEvent, UINT uMsg, DWORD_PTR dwUser, DWORD_PT // } } +//static void +//init_configured_features( struct configured_features *config) { +// config->arm9_gdb_port = 0; +// config->arm7_gdb_port = 0; +// +// config->cflash_disk_image_file = NULL; +//} +// +// +//static int +//fill_configured_features( struct configured_features *config, LPSTR lpszArgument) { +// int good_args = 0; +// LPTSTR cmd_line; +// LPWSTR *argv; +// int argc; +// +// argv = CommandLineToArgvW( GetCommandLineW(), &argc); +// +// if ( argv != NULL) { +// int i; +// good_args = 1; +// for ( i = 1; i < argc && good_args; i++) { +// if ( wcsncmp( argv[i], L"--arm9gdb=", 10) == 0) { +// wchar_t *end_char; +// unsigned long port_num = wcstoul( &argv[i][10], &end_char, 10); +// +// if ( port_num > 0 && port_num < 65536) { +// config->arm9_gdb_port = port_num; +// } +// else { +// MessageBox(NULL,"ARM9 GDB stub port must be in the range 1 to 65535","Error",MB_OK); +// good_args = 0; +// } +// } +// else if ( wcsncmp( argv[i], L"--arm7gdb=", 10) == 0) { +// wchar_t *end_char; +// unsigned long port_num = wcstoul( &argv[i][10], &end_char, 10); +// +// if ( port_num > 0 && port_num < 65536) { +// config->arm7_gdb_port = port_num; +// } +// else { +// MessageBox(NULL,"ARM9 GDB stub port must be in the range 1 to 65535","Error",MB_OK); +// good_args = 0; +// } +// } +// +//#ifdef EXPERIMENTAL_GBASLOT +// else if ( wcsncmp( argv[i], L"--cflash=", 9) == 0) +// { +// char buf[512]; +// size_t convert_count = wcstombs(&buf[0], &argv[i][9], 512); +// if (convert_count > 0) +// { +// addon_type = NDS_ADDON_CFLASH; +// CFlashUsePath = FALSE; +// strcpy(CFlashName, buf); +// } +// } +// else if ( wcsncmp( argv[i], L"--gbagame=", 10) == 0) +// { +// char buf[512]; +// size_t convert_count = wcstombs(&buf[0], &argv[i][9], 512); +// if (convert_count > 0) +// { +// addon_type = NDS_ADDON_GBAGAME; +// strcpy(GBAgameName, buf); +// } +// } +// else if ( wcsncmp( argv[i], L"--rumble", 8) == 0) +// { +// addon_type = NDS_ADDON_RUMBLEPAK; +// } +//#else +// else if ( wcsncmp( argv[i], L"--cflash=", 9) == 0) { +// if ( config->cflash_disk_image_file == NULL) { +// size_t convert_count = wcstombs( &cflash_filename_buffer[0], &argv[i][9], 512); +// if ( convert_count > 0) { +// config->cflash_disk_image_file = cflash_filename_buffer; +// } +// } +// else { +// MessageBox(NULL,"CFlash disk image file already set","Error",MB_OK); +// good_args = 0; +// } +// } +//#endif +// } +// LocalFree( argv); +// } +// +// return good_args; +//} + // Rotation definitions short GPU_rotation = 0; DWORD GPU_width = 256; @@ -1019,7 +1114,6 @@ DWORD WINAPI run() while(execute) { input_process(); - CallRegisteredLuaFunctions(LUACALL_BEFOREEMULATION); FCEUMOV_AddInputState(); if (ShowInputDisplay) osd->addFixed(Hud.InputDisplay.x, Hud.InputDisplay.y, "%s",InputDisplayString.c_str()); @@ -1031,8 +1125,6 @@ DWORD WINAPI run() } DRV_AviVideoUpdate((u16*)GPU_screen); - CallRegisteredLuaFunctions(LUACALL_AFTEREMULATION); - static int fps3d = 0; if (FpsDisplay) osd->addFixed(Hud.FpsDisplay.x, Hud.FpsDisplay.y, "Fps:%02d/%02d", fps, fps3d); @@ -1045,8 +1137,6 @@ DWORD WINAPI run() else osd->addFixed(Hud.FrameCounter.x, Hud.FrameCounter.y, "%d (no movie)",currFrameCounter); } - if (ShowLagFrameCounter) osd->addFixed(Hud.LagFrameCounter.x, Hud.LagFrameCounter.y, "%d",TotalLagFrames); - if (ShowMicrophone) osd->addFixed(Hud.Microphone.x, Hud.Microphone.y, "%d",MicDisplay); if(!AVI_IsRecording()) osd->update(); Display(); @@ -1168,6 +1258,8 @@ DWORD WINAPI run() emu_halt(); SPU_Pause(1); } + if (ShowLagFrameCounter) osd->addFixed(Hud.LagFrameCounter.x, Hud.LagFrameCounter.y, "%d",TotalLagFrames); + if (ShowMicrophone) osd->addFixed(Hud.Microphone.x, Hud.Microphone.y, "%d",MicDisplay); // DisplayMessage(); CheckMessages(); @@ -1265,22 +1357,28 @@ void LoadSaveStateInfo() } } -static BOOL LoadROM(const char * filename, const char * logicalName) + + +#ifdef EXPERIMENTAL_GBASLOT +static BOOL LoadROM(const char * filename) +#else +static BOOL LoadROM(const char * filename, const char *cflash_disk_image) +#endif { ResetSaveStateTimes(); NDS_Pause(); //if (strcmp(filename,"")!=0) INFO("Attempting to load ROM: %s\n",filename); - //extract the internal part of the logical rom name - std::vector parts = tokenize_str(logicalName,"|"); - SetRomName(parts[parts.size()-1].c_str()); - - if (NDS_LoadROM(filename, logicalName) > 0) +#ifdef EXPERIMENTAL_GBASLOT + if (NDS_LoadROM(filename) > 0) +#else + if (NDS_LoadROM(filename, cflash_disk_image) > 0) +#endif { - INFO("Loading %s was successful\n",logicalName); + INFO("Loading %s was successful\n",filename); LoadSaveStateInfo(); lagframecounter=0; - UpdateRecentRoms(logicalName); + UpdateRecentRoms(filename); osd->setRotate(GPU_rotation); if (AutoRWLoad) { @@ -1288,10 +1386,10 @@ static BOOL LoadROM(const char * filename, const char * logicalName) OpenRWRecentFile(0); RamWatchHWnd = CreateDialog(hAppInst, MAKEINTRESOURCE(IDD_RAMWATCH), MainWindow->getHWnd(), (DLGPROC) RamWatchProc); } - + SetRomName(filename); return TRUE; } - INFO("Loading %s FAILED.\n",logicalName); + INFO("Loading %s FAILED.\n",filename); return FALSE; } @@ -1460,16 +1558,9 @@ class WinDriver : public BaseDriver } }; -std::string GetPrivateProfileStdString(LPCSTR lpAppName,LPCSTR lpKeyName,LPCSTR lpDefault) -{ - static char buf[65536]; - GetPrivateProfileString(lpAppName, lpKeyName, lpDefault, buf, 65536, IniName); - return buf; -} int _main() { - InitDecoder(); #ifdef WX_STUB wxInitialize(); @@ -1496,32 +1587,39 @@ int _main() char text[80]; GetINIPath(); - +#ifdef EXPERIMENTAL_GBASLOT addon_type = GetPrivateProfileInt("GBAslot", "type", NDS_ADDON_NONE, IniName); - UINT CFlashFileMode = GetPrivateProfileInt("GBAslot.CFlash", "fileMode", 2, IniName); - - CFlashPath = GetPrivateProfileStdString("GBAslot.CFlash", "path", ""); - CFlashName = GetPrivateProfileStdString("GBAslot.CFlash", "filename", ""); + CFlashUsePath = GetPrivateProfileInt("GBAslot.CFlash", "usePath", 1, IniName); + CFlashUseRomPath = GetPrivateProfileInt("GBAslot.CFlash", "useRomPath", 1, IniName); + GetPrivateProfileString("GBAslot.CFlash", "path", "", CFlashPath, MAX_PATH, IniName); + GetPrivateProfileString("GBAslot.CFlash", "filename", "", CFlashName, MAX_PATH, IniName); GetPrivateProfileString("GBAslot.GBAgame", "filename", "", GBAgameName, MAX_PATH, IniName); - if(CFlashFileMode==ADDON_CFLASH_MODE_Path) + switch (addon_type) { - CFlash_Mode = ADDON_CFLASH_MODE_Path; - } - else - if(CFlashFileMode==ADDON_CFLASH_MODE_File) + case NDS_ADDON_NONE: + break; + case NDS_ADDON_CFLASH: + if (!strlen(CFlashPath)) CFlashUseRomPath = TRUE; + if (!strlen(CFlashName)) CFlashUsePath = TRUE; + // TODO: check for file exist + break; + case NDS_ADDON_RUMBLEPAK: + break; + case NDS_ADDON_GBAGAME: + if (!strlen(GBAgameName)) { - CFlash_Path = CFlashName; - CFlash_Mode = ADDON_CFLASH_MODE_File; + addon_type = NDS_ADDON_NONE; + break; } - else - { - CFlash_Path = ""; - CFlash_Mode = ADDON_CFLASH_MODE_RomPath; - } - - - + // TODO: check for file exist + break; + default: + addon_type = NDS_ADDON_NONE; + break; + } + addonsChangePak(addon_type); +#endif //init_configured_features( &my_config); /*if ( !fill_configured_features( &my_config, lpszArgument)) { @@ -1593,8 +1691,14 @@ int _main() GetPrivateProfileString("General", "Language", "0", text, 80, IniName); SetLanguage(atoi(text)); +#ifndef EXPERIMENTAL_GBASLOT + bad_glob_cflash_disk_image_file = my_config.cflash_disk_image_file; +#endif + //hAccel = LoadAccelerators(hAppInst, MAKEINTRESOURCE(IDR_MAIN_ACCEL)); //Now that we have a hotkey system we down need the Accel table. Not deleting just yet though + + if(MenuInit() == 0) { MessageBox(NULL, "Error creating main menu", "DeSmuME", MB_OK); @@ -1626,6 +1730,10 @@ int _main() DragAcceptFiles(MainWindow->getHWnd(), TRUE); +#ifndef EXPERIMENTAL_GBASLOT + EnableMenuItem(mainMenu, IDM_GBASLOT, MF_GRAYED); +#endif + #ifdef EXPERIMENTAL_WIFI EnableMenuItem(mainMenu, IDM_WIFISETTINGS, MF_ENABLED); #endif @@ -1656,41 +1764,6 @@ int _main() ViewMatrices = new TOOLSCLASS(hAppInst, IDD_MATRIX_VIEWER, (DLGPROC) ViewMatricesProc); ViewLights = new TOOLSCLASS(hAppInst, IDD_LIGHT_VIEWER, (DLGPROC) ViewLightsProc); - - cmdline.process_addonCommands(); - if(cmdline.is_cflash_configured) - { - addon_type = NDS_ADDON_CFLASH; - //push the commandline-provided options into the current config slots - if(CFlash_Mode == ADDON_CFLASH_MODE_Path) - CFlashPath = CFlash_Path; - else - CFlashName = CFlash_Path; - } - - - switch (addon_type) - { - case NDS_ADDON_NONE: - break; - case NDS_ADDON_CFLASH: - break; - case NDS_ADDON_RUMBLEPAK: - break; - case NDS_ADDON_GBAGAME: - if (!strlen(GBAgameName)) - { - addon_type = NDS_ADDON_NONE; - break; - } - // TODO: check for file exist - break; - default: - addon_type = NDS_ADDON_NONE; - break; - } - addonsChangePak(addon_type); - #ifdef GDB_STUB if ( cmdline.arm9_gdb_port != 0) { arm9_gdb_stub = createStub_gdb( cmdline.arm9_gdb_port, @@ -1730,8 +1803,7 @@ int _main() activateStub_gdb( arm7_gdb_stub, arm7_ctrl_iface); } #endif - - GetPrivateProfileString("General", "Language", "0", text, 80, IniName); + GetPrivateProfileString("General", "Language", "0", text, 80, IniName); //================================================== ??? CheckLanguage(IDC_LANGENGLISH+atoi(text)); GetPrivateProfileString("Video", "FrameSkip", "0", text, 80, IniName); @@ -1829,7 +1901,11 @@ int _main() if (cmdline.nds_file != "") { - if(OpenCore(cmdline.nds_file.c_str())) +#ifdef EXPERIMENTAL_GBASLOT + if(LoadROM(cmdline.nds_file.c_str())) +#else + if(LoadROM(cmdline.nds_file.c_str(), bad_glob_cflash_disk_image_file)) +#endif { romloaded = TRUE; if(!cmdline.start_paused) @@ -2177,6 +2253,7 @@ void AviRecordTo() NDS_Pause(); OPENFILENAME ofn; + char szChoice[MAX_PATH] = {0}; ////if we are playing a movie, construct the filename from the current movie. ////else construct it from the filename. @@ -2204,32 +2281,16 @@ void AviRecordTo() ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = MainWindow->getHWnd(); ofn.lpstrFilter = "AVI Files (*.avi)\0*.avi\0\0"; + ofn.lpstrFile = szChoice; ofn.lpstrDefExt = "avi"; ofn.lpstrTitle = "Save AVI as"; - char folder[MAX_PATH]; - ZeroMemory(folder, sizeof(folder)); - GetPathFor(AVI_FILES, folder, MAX_PATH); - - char file[MAX_PATH]; - ZeroMemory(file, sizeof(file)); - FormatName(file, MAX_PATH); - - strcat(folder, file); - int len = strlen(folder); - if(len > MAX_PATH - 4) - folder[MAX_PATH - 4] = '\0'; - - strcat(folder, ".avi"); - ofn.lpstrFile = folder; - - ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT; if(GetSaveFileName(&ofn)) { - DRV_AviBegin(folder); + DRV_AviBegin(szChoice); } NDS_UnPause(); @@ -2297,7 +2358,11 @@ void OpenRecentROM(int listNum) char filename[MAX_PATH]; strcpy(filename, RecentRoms[listNum].c_str()); //LOG("Attempting to load %s\n",filename); - if(OpenCore(filename)) +#ifdef EXPERIMENTAL_GBASLOT + if(LoadROM(filename)) +#else + if(LoadROM(filename, bad_glob_cflash_disk_image_file)) +#endif { romloaded = TRUE; } @@ -2316,34 +2381,6 @@ void OpenRecentROM(int listNum) NDS_UnPause(); } -#include "OpenArchive.h" -#include "utils/xstring.h" - -static BOOL OpenCore(const char* filename) -{ - if(!strcmp(getExtension(filename).c_str(), "gz") || !strcmp(getExtension(filename).c_str(), "nds.gz")) { - if(LoadROM(filename,filename)) { - NDS_UnPause(); - return FALSE; - } - } - - char LogicalName[1024], PhysicalName[1024]; - - const char* s_nonRomExtensions [] = {"txt", "nfo", "htm", "html", "jpg", "jpeg", "png", "bmp", "gif", "mp3", "wav", "lnk", "exe", "bat", "gmv", "gm2", "lua", "luasav", "sav", "srm", "brm", "cfg", "wch", "gs*"}; - - if(!ObtainFile(filename, LogicalName, PhysicalName, "rom", s_nonRomExtensions, ARRAY_SIZE(s_nonRomExtensions))) - return FALSE; - - if(LoadROM(PhysicalName, LogicalName)) - { - romloaded = TRUE; - NDS_UnPause(); - return TRUE; - } - else return FALSE; -} - LRESULT OpenFile() { HWND hwnd = MainWindow->getHWnd(); @@ -2364,7 +2401,7 @@ LRESULT OpenFile() // should be, and later transform prior assigning to the OPENFILENAME structure strncpy (fileFilter, "NDS ROM file (*.nds)|*.nds|NDS/GBA ROM File (*.ds.gba)|*.ds.gba|",512); #ifdef HAVE_LIBZZIP - strncpy (fileFilter, "All Usable Files (*.nds, *.ds.gba, *.zip, *.gz, *.7z, *.rar, *.bz2)|*.nds;*.ds.gba;*.zip;*.gz;*.7z;*.rar;*.bz2|",512); + strncpy (fileFilter, "All Usable Files (*.nds, *.ds.gba, *.zip, *.gz)|*.nds;*.ds.gba;*.zip;*.gz|",512); #endif #ifdef HAVE_LIBZZIP @@ -2373,10 +2410,6 @@ LRESULT OpenFile() #ifdef HAVE_LIBZ strncat (fileFilter, "GZipped NDS ROM file (*.gz)|*.gz|",512 - strlen(fileFilter)); #endif - strncat (fileFilter, "7Zipped NDS ROM file (*.7z)|*.7z|",512 - strlen(fileFilter)); - strncat (fileFilter, "RARed NDS ROM file (*.rar)|*.rar|",512 - strlen(fileFilter)); - strncat (fileFilter, "BZipped NDS ROM file (*.bz2)|*.bz2|",512 - strlen(fileFilter)); - strncat (fileFilter, "Any file (*.*)|*.*||",512 - strlen(fileFilter)); filterSize = strlen(fileFilter); @@ -2391,44 +2424,26 @@ LRESULT OpenFile() ofn.lpstrDefExt = "nds"; ofn.Flags = OFN_NOCHANGEDIR; - char buffer[MAX_PATH]; - ZeroMemory(buffer, sizeof(buffer)); - GetPathFor(ROMS, buffer, MAX_PATH); - ofn.lpstrInitialDir = buffer; - - - if (GetOpenFileName(&ofn) == NULL) { - NDS_UnPause(); - return 0; - } - else { - if(SavePathForRomVisit()) + if(!GetOpenFileName(&ofn)) { - char *lchr, buffer[MAX_PATH]; - ZeroMemory(buffer, sizeof(buffer)); - - lchr = strrchr(filename, '\\'); - strncpy(buffer, filename, strlen(filename) - strlen(lchr)); - - SetPathFor(ROMS, buffer); - WritePathSettings(); - } - } - - if(!OpenCore(filename)) + if (romloaded) + { + CheatsSearchReset(); + NDS_UnPause(); //Restart emulation if no new rom chosen + } return 0; + } -// if(!GetOpenFileName(&ofn)) -// { -// if (romloaded) -// { -// CheatsSearchReset(); -// NDS_UnPause(); //Restart emulation if no new rom chosen -// } -// return 0; -// } - - + //LOG("%s\r\n", filename); +#ifdef EXPERIMENTAL_GBASLOT + if(LoadROM(filename)) +#else + if(LoadROM(filename, bad_glob_cflash_disk_image_file)) +#endif + { + romloaded = TRUE; + NDS_UnPause(); + } return 0; } @@ -2531,8 +2546,7 @@ enum CONFIGSCREEN CONFIGSCREEN_WIFI, CONFIGSCREEN_SOUND, CONFIGSCREEN_EMULATION, - CONFIGSCREEN_MICROPHONE, - CONFIGSCREEN_PATHSETTINGS + CONFIGSCREEN_MICROPHONE }; void RunConfig(CONFIGSCREEN which) @@ -2565,9 +2579,6 @@ void RunConfig(CONFIGSCREEN which) case CONFIGSCREEN_MICROPHONE: DialogBox(hAppInst, MAKEINTRESOURCE(IDD_MICROPHONE), hwnd, (DLGPROC)MicrophoneSettingsDlgProc); break; - case CONFIGSCREEN_PATHSETTINGS: - DialogBox(hAppInst, MAKEINTRESOURCE(IDD_PATHSETTINGS), hwnd, (DLGPROC)PathSettingsDlgProc); - break; case CONFIGSCREEN_WIFI: #ifdef EXPERIMENTAL_WIFI if(wifiMac.netEnabled) @@ -2714,7 +2725,6 @@ LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM case WM_CREATE: { - ReadPathSettings(); pausedByMinimize = FALSE; UpdateScreenRects(); return 0; @@ -2875,7 +2885,11 @@ LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM char filename[MAX_PATH] = ""; DragQueryFile((HDROP)wParam,0,filename,MAX_PATH); DragFinish((HDROP)wParam); - if(OpenCore(filename)) +#ifdef EXPERIMENTAL_GBASLOT + if(LoadROM(filename)) +#else + if(LoadROM(filename, bad_glob_cflash_disk_image_file)) +#endif { romloaded = TRUE; } @@ -2976,33 +2990,7 @@ LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM return 0; case IDM_QUICK_PRINTSCREEN: { - char buffer[MAX_PATH]; - ZeroMemory(buffer, sizeof(buffer)); - GetPathFor(SCREENSHOTS, buffer, MAX_PATH); - - char file[MAX_PATH]; - ZeroMemory(file, sizeof(file)); - FormatName(file, MAX_PATH); - - strcat(buffer, file); - if( strlen(buffer) > (MAX_PATH - 4)) - buffer[MAX_PATH - 4] = '\0'; - - switch(GetImageFormatType()) - { - case PNG: - { - strcat(buffer, ".png"); - NDS_WritePNG(buffer); - } - break; - case BMP: - { - strcat(buffer, ".bmp"); - NDS_WriteBMP(buffer); - } - break; - } + NDS_WriteBMP("./printscreen.bmp"); } return 0; case IDM_FILE_RECORDAVI: @@ -3030,11 +3018,6 @@ LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM ofn.nMaxFile = MAX_PATH; ofn.lpstrDefExt = "dst"; - char buffer[MAX_PATH]; - ZeroMemory(buffer, sizeof(buffer)); - GetPathFor(STATES, buffer, MAX_PATH); - ofn.lpstrInitialDir = buffer; - if(!GetOpenFileName(&ofn)) { NDS_UnPause(); @@ -3060,11 +3043,6 @@ LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM ofn.nMaxFile = MAX_PATH; ofn.lpstrDefExt = "dst"; - char buffer[MAX_PATH]; - ZeroMemory(buffer, sizeof(buffer)); - GetPathFor(STATES, buffer, MAX_PATH); - ofn.lpstrInitialDir = buffer; - if(!GetSaveFileName(&ofn)) { return 0; @@ -3131,11 +3109,6 @@ LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM ofn.nMaxFile = MAX_PATH; ofn.lpstrDefExt = "duc"; - char buffer[MAX_PATH]; - ZeroMemory(buffer, sizeof(buffer)); - GetPathFor(BATTERY, buffer, MAX_PATH); - ofn.lpstrInitialDir = buffer; - if(!GetOpenFileName(&ofn)) { NDS_UnPause(); @@ -3194,9 +3167,6 @@ LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM case IDM_MICROPHONESETTINGS: RunConfig(CONFIGSCREEN_MICROPHONE); return 0; - case IDM_PATHSETTINGS: - RunConfig(CONFIGSCREEN_PATHSETTINGS); - return 0; case IDM_GAME_INFO: { @@ -3483,6 +3453,7 @@ LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM if(tpaused) NDS_UnPause(); } return 0; + case IDC_FRAMESKIPAUTO: case IDC_FRAMESKIP0: case IDC_FRAMESKIP1: @@ -3510,13 +3481,6 @@ LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM } } return 0; - case IDC_NEW_LUA_SCRIPT: - if(LuaScriptHWnds.size() < 16) - { - CreateDialog(hAppInst, MAKEINTRESOURCE(IDD_LUA), MainWindow->getHWnd(), (DLGPROC) LuaScriptProc); - // DialogsOpen++; - } - break; case IDC_LANGENGLISH: SaveLanguage(0); ChangeLanguage(0); @@ -3901,11 +3865,6 @@ LRESULT CALLBACK EmulationSettingsDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, L ofn.lpstrDefExt = "bin"; ofn.Flags = OFN_NOCHANGEDIR; - char buffer[MAX_PATH]; - ZeroMemory(buffer, sizeof(buffer)); - GetPathFor(FIRMWARE, buffer, MAX_PATH); - ofn.lpstrInitialDir = buffer; - if(GetOpenFileName(&ofn)) { HWND cur; @@ -4006,11 +3965,6 @@ LRESULT CALLBACK MicrophoneSettingsDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, ofn.lpstrDefExt = "bin"; ofn.Flags = OFN_NOCHANGEDIR; - char buffer[MAX_PATH]; - ZeroMemory(buffer, sizeof(buffer)); - GetPathFor(SOUNDS, buffer, MAX_PATH); - ofn.lpstrInitialDir = buffer; - if(GetOpenFileName(&ofn)) { HWND cur; @@ -4405,80 +4359,3 @@ void UpdateHotkeyAssignments() } -static char Lua_Dir [1024]; -char Desmume_Path [1024]; - -static const char* PathWithoutPrefixDotOrSlash(const char* path) -{ - while(*path && - ((*path == '.' && (path[1] == '\\' || path[1] == '/')) || - *path == '\\' || *path == '/' || *path == ' ')) - path++; - return path; -} - -const char* MakeScriptPathAbsolute(const char* filename, const char* extraDirToCheck) -{ - static char filename2 [1024]; - if(filename[0] && filename[1] != ':') - { - char tempFile [1024], curDir [1024]; - strncpy(tempFile, filename, 1024); - tempFile[1023] = 0; - const char* tempFilePtr = PathWithoutPrefixDotOrSlash(tempFile); - for(int i=0; i<=4; i++) - { - if((!*tempFilePtr || tempFilePtr[1] != ':') && i != 2) - strcpy(curDir, i!=1 ? ((i!=3||!extraDirToCheck) ? Lua_Dir : extraDirToCheck) : Desmume_Path); - else - curDir[0] = 0; - _snprintf(filename2, 1024, "%s%s", curDir, tempFilePtr); - char* bar = strchr(filename2, '|'); - if(bar) *bar = 0; - FILE* file = fopen(filename2, "rb"); - if(bar) *bar = '|'; - if(file || i==4) - filename = filename2; - if(file) - { - fclose(file); - break; - } - } - } - return filename; -} - -extern void RequestAbortLuaScript(int uid, const char* message); - -const char* OpenLuaScript(const char* filename, const char* extraDirToCheck, bool makeSubservient) -{ - if(LuaScriptHWnds.size() < 16) - { - // make the filename absolute before loading - filename = MakeScriptPathAbsolute(filename, extraDirToCheck); - - // now check if it's already open and load it if it isn't - HWND IsScriptFileOpen(const char* Path); - HWND scriptHWnd = IsScriptFileOpen(filename); - if(!scriptHWnd) - { - HWND prevWindow = GetActiveWindow(); - - HWND hDlg = CreateDialog(hAppInst, MAKEINTRESOURCE(IDD_LUA), MainWindow->getHWnd(), (DLGPROC) LuaScriptProc); - SendMessage(hDlg,WM_COMMAND,IDC_NOTIFY_SUBSERVIENT,TRUE); - SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,WM_SETTEXT,0,(LPARAM)filename); -// DialogsOpen++; - - SetActiveWindow(prevWindow); - } - else - { - RequestAbortLuaScript((int)scriptHWnd, "terminated to restart because of a call to gens.openscript"); - SendMessage(scriptHWnd, WM_COMMAND, IDC_BUTTON_LUARUN, 0); - } - } - else return "Too many script windows are already open."; - - return NULL; -} diff --git a/desmume/src/windows/main.h b/src/windows/main.h similarity index 100% rename from desmume/src/windows/main.h rename to src/windows/main.h diff --git a/desmume/src/windows/mapView.cpp b/src/windows/mapView.cpp similarity index 80% rename from desmume/src/windows/mapView.cpp rename to src/windows/mapView.cpp index 55f499047..c84c507f1 100644 --- a/desmume/src/windows/mapView.cpp +++ b/src/windows/mapView.cpp @@ -30,7 +30,7 @@ using namespace GPU_EXT; -struct mapview_struct +typedef struct { u32 autoup_secs; bool autoup; @@ -38,36 +38,10 @@ struct mapview_struct u16 map; u16 lcd; u16 bitmap[1024*1024]; - - void render() - { - //we're going to make a copy of the gpu so that we don't wreck affine scroll params - //hopefully we won't mess up anything else - GPU *realGpu; - if(lcd) realGpu = SubScreen.gpu; - else realGpu = MainScreen.gpu; - GPU &gpu = *realGpu; - - //forgive the gyrations, some of this junk in here is to remind us of gyrations we might have to go - //through to avoid breaking the gpu struct - - gpu.currBgNum = map; - gpu.debug = true; - - for(u32 i = 0; i < gpu.BGSize[map][1]; ++i) - { - gpu.currDst = (u8 *)bitmap + i*gpu.BGSize[map][0]*2; - gpu.currLine = i; - gpu.modeRender(map); - } - gpu.debug = false; - - } -}; +} mapview_struct; mapview_struct *MapView = NULL; - LRESULT MapView_OnPaint(mapview_struct * win, HWND hwnd, WPARAM wParam, LPARAM lParam) { Lock lock; @@ -161,12 +135,94 @@ LRESULT MapView_OnPaint(mapview_struct * win, HWND hwnd, WPARAM wParam, LPARAM l sprintf(text, "%d x %d", parms->BGxPC, parms->BGxPD); SetWindowText(GetDlgItem(hwnd, IDC_SCROLL), text); + // memset(win->bitmap, 0, sizeof(win->bitmap)); for(int i = 0; i < (1024*1024); i++) win->bitmap[i] = 0x7C1F; - - win->render(); - + if(win->lcd) + { + switch(dispcnt & 7) + { + case 0: + textBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + break; + case 1: + if (win->map < 3) + textBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + else + rotBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + break; + case 2: + if (win->map < 2) + textBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + else + rotBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + break; + case 3: + if (win->map < 3) + textBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + else + extRotBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + break; + case 4: + if (win->map < 2) + textBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + else if (win->map < 3) + rotBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + else + extRotBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + break; + case 5: + if (win->map < 2) + textBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + else + extRotBG(SubScreen.gpu, win->map, (u8 *)win->bitmap); + break; + } + } + else + { + switch(dispcnt & 7) + { + case 0: + textBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + break; + case 1: + if (win->map < 3) + textBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + else + rotBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + break; + case 2: + if (win->map < 2) + textBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + else + rotBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + break; + case 3: + if (win->map < 3) + textBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + else + extRotBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + break; + case 4: + if (win->map < 2) + textBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + else if (win->map < 3) + rotBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + else + extRotBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + break; + case 5: + if (win->map < 2) + textBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + else + extRotBG(MainScreen.gpu, win->map, (u8 *)win->bitmap); + break; + } + } + SetDIBitsToDevice(hdc, 200, 4, lg, ht, 0, 0, 0, ht, win->bitmap, (BITMAPINFO*)&bmi, DIB_RGB_COLORS); + //SetDIBitsToDevice(hdc, 200, 4, 256, 192, 0, 0, 0, 192, win->bitmap, (BITMAPINFO*)&bmi, DIB_RGB_COLORS); EndPaint(hwnd, &ps); diff --git a/desmume/src/windows/mapView.h b/src/windows/mapView.h similarity index 100% rename from desmume/src/windows/mapView.h rename to src/windows/mapView.h diff --git a/desmume/src/windows/matrixView.cpp b/src/windows/matrixView.cpp similarity index 100% rename from desmume/src/windows/matrixView.cpp rename to src/windows/matrixView.cpp diff --git a/desmume/src/windows/matrixView.h b/src/windows/matrixView.h similarity index 100% rename from desmume/src/windows/matrixView.h rename to src/windows/matrixView.h diff --git a/desmume/src/windows/memView.cpp b/src/windows/memView.cpp similarity index 100% rename from desmume/src/windows/memView.cpp rename to src/windows/memView.cpp diff --git a/desmume/src/windows/memView.h b/src/windows/memView.h similarity index 100% rename from desmume/src/windows/memView.h rename to src/windows/memView.h diff --git a/desmume/src/windows/mic.cpp b/src/windows/mic.cpp similarity index 100% rename from desmume/src/windows/mic.cpp rename to src/windows/mic.cpp diff --git a/desmume/src/windows/oamView.cpp b/src/windows/oamView.cpp similarity index 100% rename from desmume/src/windows/oamView.cpp rename to src/windows/oamView.cpp diff --git a/desmume/src/windows/oamView.h b/src/windows/oamView.h similarity index 100% rename from desmume/src/windows/oamView.h rename to src/windows/oamView.h diff --git a/desmume/src/windows/ogl.cpp b/src/windows/ogl.cpp similarity index 100% rename from desmume/src/windows/ogl.cpp rename to src/windows/ogl.cpp diff --git a/desmume/src/windows/palView.cpp b/src/windows/palView.cpp similarity index 100% rename from desmume/src/windows/palView.cpp rename to src/windows/palView.cpp diff --git a/desmume/src/windows/palView.h b/src/windows/palView.h similarity index 100% rename from desmume/src/windows/palView.h rename to src/windows/palView.h diff --git a/desmume/src/windows/ram_search.cpp b/src/windows/ram_search.cpp similarity index 99% rename from desmume/src/windows/ram_search.cpp rename to src/windows/ram_search.cpp index e07d7099e..57dd662d0 100644 --- a/desmume/src/windows/ram_search.cpp +++ b/src/windows/ram_search.cpp @@ -51,7 +51,7 @@ HWND RamSearchHWnd = NULL; extern HWND RamWatchHWnd; -static char Str_Tmp[1024]; +extern char Str_Tmp[1024]; int Rom_Size; //TODO unsigned char* Rom_Data; //TODO diff --git a/desmume/src/windows/ram_search.h b/src/windows/ram_search.h similarity index 100% rename from desmume/src/windows/ram_search.h rename to src/windows/ram_search.h diff --git a/desmume/src/windows/ramwatch.cpp b/src/windows/ramwatch.cpp similarity index 99% rename from desmume/src/windows/ramwatch.cpp rename to src/windows/ramwatch.cpp index ca0244602..35f373f12 100644 --- a/desmume/src/windows/ramwatch.cpp +++ b/src/windows/ramwatch.cpp @@ -16,7 +16,7 @@ HWND RamWatchHWnd = NULL; #define MESSAGEBOXPARENT (RamWatchHWnd ? RamWatchHWnd : MainWindow->getHWnd()) -static char Str_Tmp[1024]; +char Str_Tmp[1024]; std::string Rom_Name; static HMENU ramwatchmenu; @@ -552,7 +552,7 @@ bool Load_Watches(bool clear, const char* filename) -static int Change_File_L(char *Dest, char *Dir, char *Titre, char *Filter, char *Ext, HWND hwnd) +int Change_File_L(char *Dest, char *Dir, char *Titre, char *Filter, char *Ext, HWND hwnd) { OPENFILENAME ofn; diff --git a/desmume/src/windows/ramwatch.h b/src/windows/ramwatch.h similarity index 100% rename from desmume/src/windows/ramwatch.h rename to src/windows/ramwatch.h diff --git a/desmume/src/windows/replay.cpp b/src/windows/replay.cpp similarity index 100% rename from desmume/src/windows/replay.cpp rename to src/windows/replay.cpp diff --git a/desmume/src/windows/replay.h b/src/windows/replay.h similarity index 100% rename from desmume/src/windows/replay.h rename to src/windows/replay.h diff --git a/desmume/src/windows/resource.h b/src/windows/resource.h similarity index 95% rename from desmume/src/windows/resource.h rename to src/windows/resource.h index 7900b6090..6a8fbdae5 100644 --- a/desmume/src/windows/resource.h +++ b/src/windows/resource.h @@ -101,42 +101,6 @@ #define IDC_16_BIT 303 #define IDC_32_BIT 304 #define IDC_BACKGROUNDPAUSE 305 -#define IDC_LUACONSOLE 309 -#define IDC_EDIT_LUAPATH 310 -#define IDC_BUTTON_LUARUN 311 -#define IDC_BUTTON_LUASTOP 312 -#define IDC_BUTTON_LUABROWSE 313 -#define IDC_BUTTON_LUAEDIT 314 -#define IDC_NOTIFY_SUBSERVIENT 315 -#define IDD_ARCHIVEFILECHOOSER 316 -#define IDD_LUA 317 -#define IDC_NEW_LUA_SCRIPT 318 -#define IDC_PATHEDIT 319 -#define IDC_BROWSE 320 -#define IDC_USELASTVISIT 321 -#define IDC_FORMATEDIT 322 -#define IDC_PATHLIST 323 -#define IDC_SAVEAS 324 -#define IDC_PNG 325 -#define IDC_BMP 326 -#define IDC_FORMATSTATIC 327 -#define IDM_PATHSETTINGS 350 -#define IDC_ROMPATHEDIT 351 -#define IDC_BROWSEROMS 352 -#define IDC_PATHDEFAULTS 353 -#define IDC_SAVERAMPATHEDIT 354 -#define IDC_BROWSESRAM 355 -#define IDC_STATEPATHEDIT 356 -#define IDC_BROWSESTATES 357 -#define IDC_SCREENSHOTPATHEDIT 358 -#define IDC_BROWSESCREENSHOTS 359 -#define IDC_AVIPATHEDIT 360 -#define IDC_BROWSEAVI 361 -#define IDC_CHEATPATHEDIT 362 -#define IDC_BROWSECHEATS 363 -#define IDC_LUAPATHEDIT 364 -#define IDC_BROWSELUA 365 -#define IDD_PATHSETTINGS 366 #define IDC_DES_BOX 402 #define IDC_R0 403 #define IDC_R1 404 @@ -285,14 +249,12 @@ #define IDC_GI_GAMETITLE 1003 #define IDC_MFRAMES 1003 #define IDC_ROTATE0 1003 -#define IDC_BUTTON2 1003 #define IDC_ARM9BIOSBROWSE 1004 #define IDC_EDIT11 1004 #define IDC_GI_GAMECODE 1004 #define IDC_MRERECORDCOUNT 1004 #define IDC_ROTATE90 1004 #define IDC_SPU_INTERPOLATION_CB 1004 -#define IDC_BUTTON_VOLMODE 1004 #define IDC_ARM7BIOS 1005 #define IDC_EDIT07 1005 #define IDC_MROM 1005 @@ -768,7 +730,7 @@ #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 105 #define _APS_NEXT_COMMAND_VALUE 40008 -#define _APS_NEXT_CONTROL_VALUE 1005 +#define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif diff --git a/desmume/src/windows/resources.rc b/src/windows/resources.rc similarity index 96% rename from desmume/src/windows/resources.rc rename to src/windows/resources.rc index 9a28d2684..30896884a 100644 Binary files a/desmume/src/windows/resources.rc and b/src/windows/resources.rc differ diff --git a/desmume/src/windows/snddx.cpp b/src/windows/snddx.cpp similarity index 100% rename from desmume/src/windows/snddx.cpp rename to src/windows/snddx.cpp diff --git a/desmume/src/windows/snddx.h b/src/windows/snddx.h similarity index 100% rename from desmume/src/windows/snddx.h rename to src/windows/snddx.h diff --git a/desmume/src/windows/soundView.cpp b/src/windows/soundView.cpp similarity index 90% rename from desmume/src/windows/soundView.cpp rename to src/windows/soundView.cpp index f71543a9a..15dff852b 100644 --- a/desmume/src/windows/soundView.cpp +++ b/src/windows/soundView.cpp @@ -39,16 +39,13 @@ using namespace std; typedef struct SoundView_DataStruct { - SoundView_DataStruct() - : viewFirst8Channels(TRUE) - , volModeAlternate(FALSE) + SoundView_DataStruct() : viewFirst8Channels(TRUE) { } HWND hDlg; BOOL viewFirst8Channels; - BOOL volModeAlternate; } SoundView_DataStruct; SoundView_DataStruct * SoundView_Data = NULL; @@ -110,6 +107,14 @@ HWND SoundView_GetHWnd() return SoundView_Data ? SoundView_Data->hDlg : NULL; } +#define CHANSTAT_STOPPED 0 +#define CHANSTAT_PLAY 1 +static u32 sputrunc(float f) { return u32floor(f); } +static u32 sputrunc(double d) { return u32floor(d); } +static FORCEINLINE s32 spumuldiv7(s32 val, u8 multiplier) { + assert(multiplier <= 127); + return (multiplier == 127) ? val : ((val * multiplier) >> 7); +} void SoundView_Refresh() { if(SoundView_Data == NULL || SPU_core == NULL) @@ -127,14 +132,10 @@ void SoundView_Refresh() SendDlgItemMessage(hDlg, IDC_SOUND0PANBAR+chanId, PBM_SETPOS, (WPARAM)spumuldiv7(128, thischan.pan), (LPARAM)0); if(thischan.status != CHANSTAT_STOPPED) { - s32 vol = spumuldiv7(128, thischan.vol) >> thischan.datashift; SendDlgItemMessage(hDlg, IDC_SOUND0VOLBAR+chanId, PBM_SETPOS, - (WPARAM)vol, (LPARAM)0); + (WPARAM)(spumuldiv7(128, thischan.vol) >> thischan.datashift), (LPARAM)0); - if(SoundView_Data->volModeAlternate) - sprintf(buf, "%d/%d", thischan.vol, 1 << thischan.datashift); - else - sprintf(buf, "%d", vol); + sprintf(buf, "%d/%d", thischan.vol, 1 << thischan.datashift); SetDlgItemText(hDlg, IDC_SOUND0VOL+chanId, buf); if (thischan.pan == 0) @@ -266,9 +267,6 @@ BOOL CALLBACK SoundView_DlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lPar case IDCANCEL: SoundView_DlgClose(); return 1; - case IDC_BUTTON_VOLMODE: - data->volModeAlternate = IsDlgButtonChecked(hDlg, IDC_BUTTON_VOLMODE); - return 1; case IDC_SOUNDVIEW_CHANSWITCH: { diff --git a/desmume/src/windows/soundView.h b/src/windows/soundView.h similarity index 100% rename from desmume/src/windows/soundView.h rename to src/windows/soundView.h diff --git a/desmume/src/windows/throttle.cpp b/src/windows/throttle.cpp similarity index 100% rename from desmume/src/windows/throttle.cpp rename to src/windows/throttle.cpp diff --git a/desmume/src/windows/throttle.h b/src/windows/throttle.h similarity index 100% rename from desmume/src/windows/throttle.h rename to src/windows/throttle.h diff --git a/desmume/src/windows/tileView.cpp b/src/windows/tileView.cpp similarity index 100% rename from desmume/src/windows/tileView.cpp rename to src/windows/tileView.cpp diff --git a/desmume/src/windows/tileView.h b/src/windows/tileView.h similarity index 100% rename from desmume/src/windows/tileView.h rename to src/windows/tileView.h diff --git a/desmume/src/windows/userconfig/readme.txt b/src/windows/userconfig/readme.txt similarity index 100% rename from desmume/src/windows/userconfig/readme.txt rename to src/windows/userconfig/readme.txt diff --git a/desmume/src/windows/windriver.h b/src/windows/windriver.h similarity index 100% rename from desmume/src/windows/windriver.h rename to src/windows/windriver.h diff --git a/desmume/src/windows/winpcap/Devioctl.h b/src/windows/winpcap/Devioctl.h similarity index 100% rename from desmume/src/windows/winpcap/Devioctl.h rename to src/windows/winpcap/Devioctl.h diff --git a/desmume/src/windows/winpcap/Gnuc.h b/src/windows/winpcap/Gnuc.h similarity index 100% rename from desmume/src/windows/winpcap/Gnuc.h rename to src/windows/winpcap/Gnuc.h diff --git a/desmume/src/windows/winpcap/Ntddndis.h b/src/windows/winpcap/Ntddndis.h similarity index 100% rename from desmume/src/windows/winpcap/Ntddndis.h rename to src/windows/winpcap/Ntddndis.h diff --git a/desmume/src/windows/winpcap/Ntddpack.h b/src/windows/winpcap/Ntddpack.h similarity index 100% rename from desmume/src/windows/winpcap/Ntddpack.h rename to src/windows/winpcap/Ntddpack.h diff --git a/desmume/src/windows/winpcap/Packet.lib b/src/windows/winpcap/Packet.lib similarity index 100% rename from desmume/src/windows/winpcap/Packet.lib rename to src/windows/winpcap/Packet.lib diff --git a/desmume/src/windows/winpcap/Packet32.h b/src/windows/winpcap/Packet32.h similarity index 100% rename from desmume/src/windows/winpcap/Packet32.h rename to src/windows/winpcap/Packet32.h diff --git a/desmume/src/windows/winpcap/Win32-Extensions.h b/src/windows/winpcap/Win32-Extensions.h similarity index 100% rename from desmume/src/windows/winpcap/Win32-Extensions.h rename to src/windows/winpcap/Win32-Extensions.h diff --git a/desmume/src/windows/winpcap/bittypes.h b/src/windows/winpcap/bittypes.h similarity index 100% rename from desmume/src/windows/winpcap/bittypes.h rename to src/windows/winpcap/bittypes.h diff --git a/desmume/src/windows/winpcap/bucket_lookup.h b/src/windows/winpcap/bucket_lookup.h similarity index 100% rename from desmume/src/windows/winpcap/bucket_lookup.h rename to src/windows/winpcap/bucket_lookup.h diff --git a/desmume/src/windows/winpcap/count_packets.h b/src/windows/winpcap/count_packets.h similarity index 100% rename from desmume/src/windows/winpcap/count_packets.h rename to src/windows/winpcap/count_packets.h diff --git a/desmume/src/windows/winpcap/ip6_misc.h b/src/windows/winpcap/ip6_misc.h similarity index 100% rename from desmume/src/windows/winpcap/ip6_misc.h rename to src/windows/winpcap/ip6_misc.h diff --git a/desmume/src/windows/winpcap/memory_t.h b/src/windows/winpcap/memory_t.h similarity index 100% rename from desmume/src/windows/winpcap/memory_t.h rename to src/windows/winpcap/memory_t.h diff --git a/desmume/src/windows/winpcap/normal_lookup.h b/src/windows/winpcap/normal_lookup.h similarity index 100% rename from desmume/src/windows/winpcap/normal_lookup.h rename to src/windows/winpcap/normal_lookup.h diff --git a/desmume/src/windows/winpcap/pcap-bpf.h b/src/windows/winpcap/pcap-bpf.h similarity index 100% rename from desmume/src/windows/winpcap/pcap-bpf.h rename to src/windows/winpcap/pcap-bpf.h diff --git a/desmume/src/windows/winpcap/pcap-int.h b/src/windows/winpcap/pcap-int.h similarity index 100% rename from desmume/src/windows/winpcap/pcap-int.h rename to src/windows/winpcap/pcap-int.h diff --git a/desmume/src/windows/winpcap/pcap-stdinc.h b/src/windows/winpcap/pcap-stdinc.h similarity index 100% rename from desmume/src/windows/winpcap/pcap-stdinc.h rename to src/windows/winpcap/pcap-stdinc.h diff --git a/desmume/src/windows/winpcap/pcap.h b/src/windows/winpcap/pcap.h similarity index 100% rename from desmume/src/windows/winpcap/pcap.h rename to src/windows/winpcap/pcap.h diff --git a/desmume/src/windows/winpcap/remote-ext.h b/src/windows/winpcap/remote-ext.h similarity index 100% rename from desmume/src/windows/winpcap/remote-ext.h rename to src/windows/winpcap/remote-ext.h diff --git a/desmume/src/windows/winpcap/tcp_session.h b/src/windows/winpcap/tcp_session.h similarity index 100% rename from desmume/src/windows/winpcap/tcp_session.h rename to src/windows/winpcap/tcp_session.h diff --git a/desmume/src/windows/winpcap/time_calls.h b/src/windows/winpcap/time_calls.h similarity index 100% rename from desmume/src/windows/winpcap/time_calls.h rename to src/windows/winpcap/time_calls.h diff --git a/desmume/src/windows/winpcap/tme.h b/src/windows/winpcap/tme.h similarity index 100% rename from desmume/src/windows/winpcap/tme.h rename to src/windows/winpcap/tme.h diff --git a/desmume/src/windows/winpcap/wpcap.lib b/src/windows/winpcap/wpcap.lib similarity index 100% rename from desmume/src/windows/winpcap/wpcap.lib rename to src/windows/winpcap/wpcap.lib diff --git a/desmume/src/windows/winres.h b/src/windows/winres.h similarity index 100% rename from desmume/src/windows/winres.h rename to src/windows/winres.h diff --git a/desmume/src/windows/zlib123/README b/src/windows/zlib123/README similarity index 100% rename from desmume/src/windows/zlib123/README rename to src/windows/zlib123/README diff --git a/desmume/src/windows/zlib123/zconf.h b/src/windows/zlib123/zconf.h similarity index 100% rename from desmume/src/windows/zlib123/zconf.h rename to src/windows/zlib123/zconf.h diff --git a/desmume/src/windows/zlib123/zlib-2005-x32.lib b/src/windows/zlib123/zlib-2005-x32.lib similarity index 100% rename from desmume/src/windows/zlib123/zlib-2005-x32.lib rename to src/windows/zlib123/zlib-2005-x32.lib diff --git a/desmume/src/windows/zlib123/zlib-2005-x64.lib b/src/windows/zlib123/zlib-2005-x64.lib similarity index 100% rename from desmume/src/windows/zlib123/zlib-2005-x64.lib rename to src/windows/zlib123/zlib-2005-x64.lib diff --git a/desmume/src/windows/zlib123/zlib-2008-x32.lib b/src/windows/zlib123/zlib-2008-x32.lib similarity index 100% rename from desmume/src/windows/zlib123/zlib-2008-x32.lib rename to src/windows/zlib123/zlib-2008-x32.lib diff --git a/desmume/src/windows/zlib123/zlib-2008-x64.lib b/src/windows/zlib123/zlib-2008-x64.lib similarity index 100% rename from desmume/src/windows/zlib123/zlib-2008-x64.lib rename to src/windows/zlib123/zlib-2008-x64.lib diff --git a/desmume/src/windows/zlib123/zlib.h b/src/windows/zlib123/zlib.h similarity index 100% rename from desmume/src/windows/zlib123/zlib.h rename to src/windows/zlib123/zlib.h diff --git a/desmume/src/windows/zlib123/zutil.h b/src/windows/zlib123/zutil.h similarity index 100% rename from desmume/src/windows/zlib123/zutil.h rename to src/windows/zlib123/zutil.h diff --git a/desmume/src/windows/zziplib/README b/src/windows/zziplib/README similarity index 100% rename from desmume/src/windows/zziplib/README rename to src/windows/zziplib/README diff --git a/desmume/src/windows/zziplib/zzip/_msvc.h b/src/windows/zziplib/zzip/_msvc.h similarity index 100% rename from desmume/src/windows/zziplib/zzip/_msvc.h rename to src/windows/zziplib/zzip/_msvc.h diff --git a/desmume/src/windows/zziplib/zzip/conf.h b/src/windows/zziplib/zzip/conf.h similarity index 100% rename from desmume/src/windows/zziplib/zzip/conf.h rename to src/windows/zziplib/zzip/conf.h diff --git a/desmume/src/windows/zziplib/zzip/types.h b/src/windows/zziplib/zzip/types.h similarity index 100% rename from desmume/src/windows/zziplib/zzip/types.h rename to src/windows/zziplib/zzip/types.h diff --git a/desmume/src/windows/zziplib/zzip/zzip.h b/src/windows/zziplib/zzip/zzip.h similarity index 100% rename from desmume/src/windows/zziplib/zzip/zzip.h rename to src/windows/zziplib/zzip/zzip.h diff --git a/desmume/src/windows/zziplib/zziplib-2005-x32.lib b/src/windows/zziplib/zziplib-2005-x32.lib similarity index 100% rename from desmume/src/windows/zziplib/zziplib-2005-x32.lib rename to src/windows/zziplib/zziplib-2005-x32.lib diff --git a/desmume/src/windows/zziplib/zziplib-2005-x64.lib b/src/windows/zziplib/zziplib-2005-x64.lib similarity index 100% rename from desmume/src/windows/zziplib/zziplib-2005-x64.lib rename to src/windows/zziplib/zziplib-2005-x64.lib diff --git a/desmume/src/windows/zziplib/zziplib-2008-x32.lib b/src/windows/zziplib/zziplib-2008-x32.lib similarity index 100% rename from desmume/src/windows/zziplib/zziplib-2008-x32.lib rename to src/windows/zziplib/zziplib-2008-x32.lib diff --git a/desmume/src/windows/zziplib/zziplib-2008-x64.lib b/src/windows/zziplib/zziplib-2008-x64.lib similarity index 100% rename from desmume/src/windows/zziplib/zziplib-2008-x64.lib rename to src/windows/zziplib/zziplib-2008-x64.lib