diff --git a/.gitignore b/.gitignore index 3b1e7690ef..71e7b81344 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,6 @@ Logs *.dll *.rar *.exe -*.bin *.ini *.map *.lib @@ -25,6 +24,11 @@ gen libs obj *.exp +.pspsh.hist +GameLogNotes.txt Windows/x64 +Windows/ipch Memstick android/ui_atlas.zim +__testoutput.txt +__testerror.txt diff --git a/.gitmodules b/.gitmodules index 51f908e2a1..cc59b8f98a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ [submodule "native"] path = native - url = git@github.com:hrydgard/native.git + url = https://github.com/hrydgard/native.git +[submodule "pspautotests"] + path = pspautotests + url = https://github.com/hrydgard/pspautotests.git diff --git a/Common/ABI.cpp b/Common/ABI.cpp index 63a8e76934..3bf8dc41c7 100644 --- a/Common/ABI.cpp +++ b/Common/ABI.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/ABI.h b/Common/ABI.h index c5c1419fd6..e86da83e4d 100644 --- a/Common/ABI.h +++ b/Common/ABI.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/ArmABI.cpp b/Common/ArmABI.cpp index 6792edb977..63824d808f 100644 --- a/Common/ArmABI.cpp +++ b/Common/ArmABI.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/ArmABI.h b/Common/ArmABI.h index 5f27879700..1646d10682 100644 --- a/Common/ArmABI.h +++ b/Common/ArmABI.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/ArmEmitter.cpp b/Common/ArmEmitter.cpp index 219595471b..0928b3d8f8 100644 --- a/Common/ArmEmitter.cpp +++ b/Common/ArmEmitter.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/ArmEmitter.h b/Common/ArmEmitter.h index c3eb8d6510..0af0e636aa 100644 --- a/Common/ArmEmitter.h +++ b/Common/ArmEmitter.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -23,6 +23,8 @@ #include "Common.h" #include "MemoryUtil.h" +#undef _SP + namespace ArmGen { diff --git a/Common/Atomic.h b/Common/Atomic.h index 5b37b79c3d..86b400b065 100644 --- a/Common/Atomic.h +++ b/Common/Atomic.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Atomic_GCC.h b/Common/Atomic_GCC.h index 8eb2f5d818..e8c39c63bb 100644 --- a/Common/Atomic_GCC.h +++ b/Common/Atomic_GCC.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Atomic_Win32.h b/Common/Atomic_Win32.h index 70d2f1c4a2..541aa203e7 100644 --- a/Common/Atomic_Win32.h +++ b/Common/Atomic_Win32.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/CMakeLists.txt b/Common/CMakeLists.txt index c12b4a51ba..bec85d7347 100644 --- a/Common/CMakeLists.txt +++ b/Common/CMakeLists.txt @@ -1,7 +1,5 @@ set(SRCS - ABI.cpp Action.cpp - CPUDetect.cpp ColorUtil.cpp ConsoleListener.cpp ExtendedTrace.cpp @@ -11,23 +9,20 @@ set(SRCS Hash.cpp IniFile.cpp LogManager.cpp - MathUtil.cpp MemArena.cpp MemoryUtil.cpp Misc.cpp MsgHandler.cpp StringUtil.cpp Thread.cpp - Thunk.cpp Timer.cpp - x64Analyzer.cpp - x64Emitter.cpp - x86Disasm.cpp ) # TODO if (ARM) set(SRCS ${SRCS} ArmEmitter.cpp ArmABI.cpp) +else() + set(SRCS ${SRCS} CPUDetect.cpp MathUtil.cpp Thunk.cpp x64Analyzer.cpp x64Emitter.cpp x86Disasm.cpp ABI.cpp) endif (ARM) set(SRCS ${SRCS}) @@ -35,6 +30,6 @@ set(SRCS ${SRCS}) add_library(common STATIC ${SRCS}) if(UNIX) - add_definitions(-fPIC) + add_definitions(-fPIC) endif(UNIX) diff --git a/Common/CPUDetect.cpp b/Common/CPUDetect.cpp index 93e9d25087..8222117669 100644 --- a/Common/CPUDetect.cpp +++ b/Common/CPUDetect.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/CPUDetect.h b/Common/CPUDetect.h index 928b34c109..5b98ab4805 100644 --- a/Common/CPUDetect.h +++ b/Common/CPUDetect.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/ChunkFile.h b/Common/ChunkFile.h index 5935b7f53a..7228365ccd 100644 --- a/Common/ChunkFile.h +++ b/Common/ChunkFile.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/ColorUtil.cpp b/Common/ColorUtil.cpp index 52ffec0803..79e17357b0 100644 --- a/Common/ColorUtil.cpp +++ b/Common/ColorUtil.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/ColorUtil.h b/Common/ColorUtil.h index 93a16d24e6..c99961d1f9 100644 --- a/Common/ColorUtil.h +++ b/Common/ColorUtil.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Common.h b/Common/Common.h index 0570902253..696a6bbcc2 100644 --- a/Common/Common.h +++ b/Common/Common.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -25,7 +25,7 @@ #include #include -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #define _M_ARM32 #endif diff --git a/Common/CommonFuncs.h b/Common/CommonFuncs.h index c81bab01dc..832256a083 100644 --- a/Common/CommonFuncs.h +++ b/Common/CommonFuncs.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -36,7 +36,7 @@ template<> struct CompileTimeAssert {}; #define ROUND_UP_POW2(x) (b32(x - 1) + 1) #if defined __GNUC__ && !defined __SSSE3__ -#ifndef ANDROID +#if !defined(ANDROID) && !defined(BLACKBERRY) #include static __inline __m128i __attribute__((__always_inline__)) _mm_shuffle_epi8(__m128i a, __m128i mask) @@ -63,7 +63,7 @@ _mm_shuffle_epi8(__m128i a, __m128i mask) #ifdef GEKKO #define Crash() #else -#ifndef ANDROID +#if !defined(ANDROID) && !defined(BLACKBERRY) #define Crash() {asm ("int $3");} #else #define Crash() {kill( getpid(), SIGINT ) ; } diff --git a/Common/CommonPaths.h b/Common/CommonPaths.h index b28474dfb5..cdc0304d7f 100644 --- a/Common/CommonPaths.h +++ b/Common/CommonPaths.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/CommonTypes.h b/Common/CommonTypes.h index 5dfd5e97eb..8b31eea6e7 100644 --- a/Common/CommonTypes.h +++ b/Common/CommonTypes.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/ConsoleListener.cpp b/Common/ConsoleListener.cpp index 94a4d01a45..04729985d0 100644 --- a/Common/ConsoleListener.cpp +++ b/Common/ConsoleListener.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/ConsoleListener.h b/Common/ConsoleListener.h index d497a42636..832822b76a 100644 --- a/Common/ConsoleListener.h +++ b/Common/ConsoleListener.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/FileSearch.cpp b/Common/FileSearch.cpp index c60ce9beda..4c6a1b4105 100644 --- a/Common/FileSearch.cpp +++ b/Common/FileSearch.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/FileSearch.h b/Common/FileSearch.h index 6a73f92f99..5dd6236fc2 100644 --- a/Common/FileSearch.h +++ b/Common/FileSearch.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/FileUtil.cpp b/Common/FileUtil.cpp index 2b2ef081a3..e2eb22a3ff 100644 --- a/Common/FileUtil.cpp +++ b/Common/FileUtil.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -417,14 +417,16 @@ u32 ScanDirectoryTree(const std::string &directory, FSTEntry& parentEntry) FSTEntry entry; const std::string virtualName(ffd.cFileName); #else - struct dirent dirent, *result = NULL; + struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; }; + struct dirent_large diren; + struct dirent *result = NULL; DIR *dirp = opendir(directory.c_str()); if (!dirp) return 0; // non windows loop - while (!readdir_r(dirp, &dirent, &result) && result) + while (!readdir_r(dirp, (dirent*)&diren, &result) && result) { FSTEntry entry; const std::string virtualName(result->d_name); @@ -534,11 +536,13 @@ void CopyDir(const std::string &source_path, const std::string &dest_path) if (!File::Exists(source_path)) return; if (!File::Exists(dest_path)) File::CreateFullPath(dest_path); - struct dirent dirent, *result = NULL; + struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; }; + struct dirent_large diren; + struct dirent *result = NULL; DIR *dirp = opendir(source_path.c_str()); if (!dirp) return; - while (!readdir_r(dirp, &dirent, &result) && result) + while (!readdir_r(dirp, (dirent*) &diren, &result) && result) { const std::string virtualName(result->d_name); // check for "." and ".." diff --git a/Common/FileUtil.h b/Common/FileUtil.h index 3c175dd1ef..0c9e464fbb 100644 --- a/Common/FileUtil.h +++ b/Common/FileUtil.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/FixedSizeQueue.h b/Common/FixedSizeQueue.h index 260503baf0..fbfd94c415 100644 --- a/Common/FixedSizeQueue.h +++ b/Common/FixedSizeQueue.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -25,68 +25,84 @@ // Not fully featured, no safety checking yet. Add features as needed. -// TODO: "inline" storage? - template -class FixedSizeQueue -{ - T *storage; - int head; - int tail; - int count; // sacrifice 4 bytes for a simpler implementation. may optimize away in the future. - - // Make copy constructor private for now. - FixedSizeQueue(FixedSizeQueue &other) { } - +class FixedSizeQueue { public: - FixedSizeQueue() - { - storage = new T[N]; + FixedSizeQueue() { + storage_ = new T[N]; clear(); } - ~FixedSizeQueue() - { - delete [] storage; + ~FixedSizeQueue() { + delete [] storage_; } void clear() { - head = 0; - tail = 0; - count = 0; + head_ = 0; + tail_ = 0; + count_ = 0; } void push(T t) { - storage[tail] = t; - tail++; - if (tail == N) - tail = 0; - count++; + storage_[tail_] = t; + tail_++; + if (tail_ == N) + tail_ = 0; + count_++; } void pop() { - head++; - if (head == N) - head = 0; - count--; + head_++; + if (head_ == N) + head_ = 0; + count_--; } + /* + void push_array(const T *ptr, size_t num) { + // TODO: memcpy + for (size_t i = 0; i < num; i++) { + push(ptr[i]); + } + } + + void pop_array(T *outptr, size_t num) { + for (size_t i = 0; i < num; i++) { + outptr[i] = front(); + pop(); + } + }*/ + T pop_front() { - const T &temp = storage[head]; + const T &temp = storage_[head_]; pop(); return temp; } - T &front() { return storage[head]; } - const T &front() const { return storage[head]; } + T &front() { return storage_[head_]; } + + const T &front() const { return storage_[head_]; } size_t size() const { - return count; + return count_; + } + + int room() const { + return N - count_; } bool empty() { - return count; + return count_; } + +private: + T *storage_; + int head_; + int tail_; + int count_; // sacrifice 4 bytes for a simpler implementation. may optimize away in the future. + + // Make copy constructor private for now. + FixedSizeQueue(FixedSizeQueue &other) { } }; #endif // _FIXED_SIZE_QUEUE_H_ diff --git a/Common/Hash.cpp b/Common/Hash.cpp index 8e8d6f85bd..fae83fa8fe 100644 --- a/Common/Hash.cpp +++ b/Common/Hash.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Hash.h b/Common/Hash.h index 0e385d4270..542ea9a73f 100644 --- a/Common/Hash.h +++ b/Common/Hash.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/IniFile.cpp b/Common/IniFile.cpp index 89b3edbbce..e8408f0dac 100644 --- a/Common/IniFile.cpp +++ b/Common/IniFile.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/IniFile.h b/Common/IniFile.h index 31d410e44c..14c3bfeb31 100644 --- a/Common/IniFile.h +++ b/Common/IniFile.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/LinearDiskCache.h b/Common/LinearDiskCache.h index 9755c996bd..066b319a84 100644 --- a/Common/LinearDiskCache.h +++ b/Common/LinearDiskCache.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Log.h b/Common/Log.h index 73775eace6..742a96d912 100644 --- a/Common/Log.h +++ b/Common/Log.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/LogManager.cpp b/Common/LogManager.cpp index 71a53e256e..060ab25905 100644 --- a/Common/LogManager.cpp +++ b/Common/LogManager.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/LogManager.h b/Common/LogManager.h index f269d1d4fe..9b6614e696 100644 --- a/Common/LogManager.h +++ b/Common/LogManager.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/MathUtil.cpp b/Common/MathUtil.cpp index 5c7181bd8c..f088c7fbc0 100644 --- a/Common/MathUtil.cpp +++ b/Common/MathUtil.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/MathUtil.h b/Common/MathUtil.h index a6290ff602..a9e9f0c0a2 100644 --- a/Common/MathUtil.h +++ b/Common/MathUtil.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/MemArena.cpp b/Common/MemArena.cpp index fc0c43414e..8a3a8b67f3 100644 --- a/Common/MemArena.cpp +++ b/Common/MemArena.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -226,13 +226,13 @@ u8* MemArena::Find4GBBase() } return base; #else - void* base = mmap(0, 0x31000000, PROT_READ | PROT_WRITE, + void* base = mmap(0, 0x5000000, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0); if (base == MAP_FAILED) { - PanicAlert("Failed to map 1 GB of memory space: %s", strerror(errno)); + PanicAlert("Failed to map 100 MB of memory space: %s", strerror(errno)); return 0; } - munmap(base, 0x31000000); + munmap(base, 0x5000000); return static_cast(base); #endif #endif diff --git a/Common/MemArena.h b/Common/MemArena.h index 4a1f9838d3..75dd738b0e 100644 --- a/Common/MemArena.h +++ b/Common/MemArena.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/MemoryUtil.cpp b/Common/MemoryUtil.cpp index 51343def1c..2a8008f226 100644 --- a/Common/MemoryUtil.cpp +++ b/Common/MemoryUtil.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/MemoryUtil.h b/Common/MemoryUtil.h index 9df44169c0..bafa7e4e88 100644 --- a/Common/MemoryUtil.h +++ b/Common/MemoryUtil.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Misc.cpp b/Common/Misc.cpp index aafe37886f..ea749d1a7b 100644 --- a/Common/Misc.cpp +++ b/Common/Misc.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/MsgHandler.cpp b/Common/MsgHandler.cpp index 7c666227aa..fcc48e7c2d 100644 --- a/Common/MsgHandler.cpp +++ b/Common/MsgHandler.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/MsgHandler.h b/Common/MsgHandler.h index 38ee246b4b..b3ac8e4bef 100644 --- a/Common/MsgHandler.h +++ b/Common/MsgHandler.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Setup.h b/Common/Setup.h index c0faec3059..89ddbd25c9 100644 --- a/Common/Setup.h +++ b/Common/Setup.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/StringUtil.cpp b/Common/StringUtil.cpp index 664987d350..5dae0a5d7f 100644 --- a/Common/StringUtil.cpp +++ b/Common/StringUtil.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -138,6 +138,9 @@ bool TryParse(const std::string &str, u32 *const output) return false; if (ULONG_MAX > UINT_MAX) { +#ifdef _MSC_VER +#pragma warning (disable:4309) +#endif // Note: The typecasts avoid GCC warnings when long is 32 bits wide. if (value >= static_cast(0x100000000ull) && value <= static_cast(0xFFFFFFFF00000000ull)) diff --git a/Common/StringUtil.h b/Common/StringUtil.h index 102ae2d5fb..a5477a3996 100644 --- a/Common/StringUtil.h +++ b/Common/StringUtil.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -27,6 +27,38 @@ #include "Common.h" +#ifdef BLACKBERRY +// QNX Does not have an implementation of vasprintf +static inline int vasprintf(char **rResult, const char *aFormat, va_list aAp) +{ + int rVal; + char *result; + va_list ap; + + result = (char *) malloc(16); + if (result == NULL) return -1; + + va_copy(ap, aAp); + rVal = vsnprintf(result, 16, aFormat, ap); + va_end(ap); + + if (rVal == -1) return rVal; + else if (rVal >= 16) + { + free(result); + result = (char *) malloc(rVal + 1); + if (result == NULL) return -1; + + va_copy(ap, aAp); + rVal = vsnprintf(result, rVal + 1, aFormat, aAp); + va_end(ap); + } + + *rResult = result; + return rVal; +} +#endif + std::string StringFromFormat(const char* format, ...); // Cheap! bool CharArrayFromFormatV(char* out, int outsize, const char* format, va_list args); diff --git a/Common/Thread.cpp b/Common/Thread.cpp index 8e42f8884e..f3dc162574 100644 --- a/Common/Thread.cpp +++ b/Common/Thread.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Thread.h b/Common/Thread.h index 96e08a54d4..65395db065 100644 --- a/Common/Thread.h +++ b/Common/Thread.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -33,7 +33,7 @@ #define INFINITE 0xffffffff #endif -#ifndef ANDROID +#if !defined(ANDROID) && !defined(BLACKBERRY) #include #endif diff --git a/Common/Thunk.cpp b/Common/Thunk.cpp index 1792df3e77..70dc351b9d 100644 --- a/Common/Thunk.cpp +++ b/Common/Thunk.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Thunk.h b/Common/Thunk.h index 68bbfa82f0..66fe703943 100644 --- a/Common/Thunk.h +++ b/Common/Thunk.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -21,7 +21,7 @@ #include #include "Common.h" -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include "ArmEmitter.h" #else #include "x64Emitter.h" @@ -38,7 +38,7 @@ // we don't want to pollute the stack, so we store away regs somewhere global. // NOT THREAD SAFE. This may only be used from the CPU thread. // Any other thread using this stuff will be FATAL. -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) class ThunkManager : public ArmGen::ARMXCodeBlock #else class ThunkManager : public Gen::XCodeBlock diff --git a/Common/ThunkArm.cpp b/Common/ThunkArm.cpp index 98cee1683d..b470f868e8 100644 --- a/Common/ThunkArm.cpp +++ b/Common/ThunkArm.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Timer.cpp b/Common/Timer.cpp index 022a8c0127..278816e21f 100644 --- a/Common/Timer.cpp +++ b/Common/Timer.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Timer.h b/Common/Timer.h index 8ef683c415..5ccfb69aa5 100644 --- a/Common/Timer.h +++ b/Common/Timer.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/Version.cpp b/Common/Version.cpp index 97e232785d..85ff3a95a7 100644 --- a/Common/Version.cpp +++ b/Common/Version.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/stdafx.h b/Common/stdafx.h index 80ce15136d..993286e03b 100644 --- a/Common/stdafx.h +++ b/Common/stdafx.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/x64Analyzer.cpp b/Common/x64Analyzer.cpp index 2ea3e9a512..1940416d6a 100644 --- a/Common/x64Analyzer.cpp +++ b/Common/x64Analyzer.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/x64Analyzer.h b/Common/x64Analyzer.h index 8b13ca94aa..bddde399b0 100644 --- a/Common/x64Analyzer.h +++ b/Common/x64Analyzer.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/x64Emitter.cpp b/Common/x64Emitter.cpp index 19e96478d1..7c0d88320c 100644 --- a/Common/x64Emitter.cpp +++ b/Common/x64Emitter.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/x64Emitter.h b/Common/x64Emitter.h index 0d6c94c6fe..9e9c39f110 100644 --- a/Common/x64Emitter.h +++ b/Common/x64Emitter.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Common/x86Disasm.cpp b/Common/x86Disasm.cpp index 42a8499c41..535218c7a4 100644 --- a/Common/x86Disasm.cpp +++ b/Common/x86Disasm.cpp @@ -1,7 +1,7 @@ // X86 disassembler - 95% ripped from some GNU source if I remember // correctly, probably GCC or some GCC tool -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #error DO NOT COMPILE THIS INTO ANDROID BUILDS #endif diff --git a/Common/x86Disasm.h b/Common/x86Disasm.h index fcbebd1801..e6de2c54bc 100644 --- a/Common/x86Disasm.h +++ b/Common/x86Disasm.h @@ -1,6 +1,6 @@ #pragma once -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #error DO NOT COMPILE THIS INTO ANDROID BUILDS #endif diff --git a/Core/CMakeLists.txt b/Core/CMakeLists.txt index dc1a37e687..bbf5e38704 100644 --- a/Core/CMakeLists.txt +++ b/Core/CMakeLists.txt @@ -12,15 +12,8 @@ set(SRCS MIPS/MIPSTables.cpp MIPS/MIPSVFPUUtils.cpp MIPS/JitCommon/JitCommon.cpp - MIPS/x86/Asm.cpp - MIPS/x86/CompALU.cpp - MIPS/x86/CompBranch.cpp - MIPS/x86/CompLoadStore.cpp - MIPS/x86/CompFPU.cpp - MIPS/x86/Jit.cpp - MIPS/x86/JitCache.cpp - MIPS/x86/RegCache.cpp ELF/ElfReader.cpp + ELF/PrxDecrypter.cpp HLE/HLE.cpp HLE/HLETables.cpp HLE/sceAtrac.cpp @@ -32,10 +25,10 @@ set(SRCS HLE/sceGe.cpp HLE/sceHprm.cpp HLE/sceHttp.cpp + HLE/sceImpose.cpp HLE/sceIo.cpp HLE/sceKernel.cpp HLE/sceKernelAlarm.cpp - HLE/sceKernelCallback.cpp HLE/sceKernelEventFlag.cpp HLE/sceKernelInterrupt.cpp HLE/sceKernelMemory.cpp @@ -55,6 +48,7 @@ set(SRCS HLE/sceSas.cpp HLE/sceUmd.cpp HLE/sceUtility.cpp + HW/MemoryStick.cpp FileSystems/BlockDevices.cpp FileSystems/ISOFileSystem.cpp FileSystems/DirectoryFileSystem.cpp @@ -73,6 +67,28 @@ set(SRCS Core.cpp ) +if(ARM) + set(SRCS ${SRCS} MIPS/ARM/Asm.cpp + MIPS/ARM/CompALU.cpp + MIPS/ARM/CompBranch.cpp + MIPS/ARM/CompLoadStore.cpp + MIPS/ARM/CompFPU.cpp + MIPS/ARM/Jit.cpp + MIPS/ARM/JitCache.cpp + MIPS/ARM/RegCache.cpp + ) +else() + set(SRCS ${SRCS} MIPS/x86/Asm.cpp + MIPS/x86/CompALU.cpp + MIPS/x86/CompBranch.cpp + MIPS/x86/CompLoadStore.cpp + MIPS/x86/CompFPU.cpp + MIPS/x86/Jit.cpp + MIPS/x86/JitCache.cpp + MIPS/x86/RegCache.cpp + ) +endif(ARM) + set(SRCS ${SRCS}) add_library(core STATIC ${SRCS}) @@ -83,4 +99,3 @@ if(UNIX) add_definitions(-fPIC) add_definitions(-std=gnu++0x) endif(UNIX) - diff --git a/Core/CPU.cpp b/Core/CPU.cpp index c71c94e08b..a0abe65ff6 100644 --- a/Core/CPU.cpp +++ b/Core/CPU.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/CPU.h b/Core/CPU.h index 7137e3bd30..aac897f270 100644 --- a/Core/CPU.h +++ b/Core/CPU.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/Config.cpp b/Core/Config.cpp index 6209dbc765..d04466bee4 100644 --- a/Core/Config.cpp +++ b/Core/Config.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -51,6 +51,7 @@ void CConfig::Load(const char *iniFileName) general->Get("DisplayFramebuffer", &bDisplayFramebuffer, false); general->Get("CurrentDirectory", ¤tDirectory, ""); general->Get("ShowFPSCounter", &bShowFPSCounter, false); + general->Get("WindowZoom", &iWindowZoom, 1); IniFile::Section *sound = iniFile.GetOrCreateSection("Sound"); sound->Get("Enable", &bEnableSound, true); @@ -76,6 +77,7 @@ void CConfig::Save() general->Set("DisplayFramebuffer", bDisplayFramebuffer); general->Set("CurrentDirectory", currentDirectory); general->Set("ShowFPSCounter", bShowFPSCounter); + general->Set("WindowZoom", iWindowZoom); IniFile::Section *sound = iniFile.GetOrCreateSection("Sound"); sound->Set("Enable", bEnableSound); diff --git a/Core/Config.h b/Core/Config.h index 617346c0c5..4c4e4b4fdc 100644 --- a/Core/Config.h +++ b/Core/Config.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -46,6 +46,7 @@ public: bool bShowAnalogStick; bool bShowFPSCounter; + int iWindowZoom; // for Windows std::string currentDirectory; diff --git a/Core/Core.cpp b/Core/Core.cpp index a29fed118d..e1c553eff2 100644 --- a/Core/Core.cpp +++ b/Core/Core.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/Core.h b/Core/Core.h index d101eee84a..564701ef52 100644 --- a/Core/Core.h +++ b/Core/Core.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/Core.vcxproj b/Core/Core.vcxproj index df60b82fd2..426a12c298 100644 --- a/Core/Core.vcxproj +++ b/Core/Core.vcxproj @@ -66,7 +66,7 @@ Level3 Disabled - ../common;..;../native;../native/ext/glew;../zlib + ../common;..;../native;../native/ext/glew;../ext/zlib WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) @@ -77,7 +77,7 @@ Level3 Disabled - ../common;..;../native;../native/ext/glew;../zlib + ../common;..;../native;../native/ext/glew;../ext/zlib WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) @@ -90,7 +90,7 @@ MaxSpeed true true - ../common;..;../native;../native/ext/glew;../zlib + ../common;..;../native;../native/ext/glew;../ext/zlib true @@ -104,7 +104,7 @@ MaxSpeed true true - ../common;..;../native;../native/ext/glew;../zlib + ../common;..;../native;../native/ext/glew;../ext/zlib true @@ -120,6 +120,7 @@ + @@ -134,10 +135,10 @@ + - @@ -159,6 +160,7 @@ + @@ -246,6 +248,7 @@ + @@ -262,10 +265,10 @@ + - @@ -287,6 +290,7 @@ + @@ -336,9 +340,9 @@ - + @@ -350,7 +354,7 @@ {e8b58922-9827-493d-81e0-4b6e6bd77171} - + {f761046e-6c38-4428-a5f1-38391a37bb34} diff --git a/Core/Core.vcxproj.filters b/Core/Core.vcxproj.filters index 160903d172..a29237c2a8 100644 --- a/Core/Core.vcxproj.filters +++ b/Core/Core.vcxproj.filters @@ -37,6 +37,9 @@ {75f0ee2b-1397-4cf3-9960-94ccd7d4d803} + + {9696662f-7398-489a-a358-5ebbf4ad4d97} + @@ -147,9 +150,6 @@ HLE\Kernel - - HLE\Kernel - HLE\Kernel @@ -282,6 +282,15 @@ Core + + ELF + + + HW + + + HLE\Libraries + @@ -374,9 +383,6 @@ HLE\Kernel - - HLE\Kernel - HLE\Kernel @@ -515,11 +521,20 @@ Core + + ELF + + + HW + + + HLE\Libraries + - + \ No newline at end of file diff --git a/Core/CoreParameter.h b/Core/CoreParameter.h index f285ceebb5..1e44cd8398 100644 --- a/Core/CoreParameter.h +++ b/Core/CoreParameter.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/CoreTiming.cpp b/Core/CoreTiming.cpp index 86a089fd7f..db686e885f 100644 --- a/Core/CoreTiming.cpp +++ b/Core/CoreTiming.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -23,6 +23,7 @@ #include "StdMutex.h" #include "CoreTiming.h" #include "Core.h" +#include "HLE/sceKernelThread.h" int CPU_HZ = 222000000; @@ -169,7 +170,7 @@ void Shutdown() u64 GetTicks() { - return (u64)globalTimer; + return (u64)globalTimer + slicelength - downcount; } u64 GetIdleTicks() diff --git a/Core/CoreTiming.h b/Core/CoreTiming.h index 7bf63f803c..a442af20ca 100644 --- a/Core/CoreTiming.h +++ b/Core/CoreTiming.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/Debugger/Breakpoints.cpp b/Core/Debugger/Breakpoints.cpp index 52b7ddca17..f682b96727 100644 --- a/Core/Debugger/Breakpoints.cpp +++ b/Core/Debugger/Breakpoints.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/Debugger/Breakpoints.h b/Core/Debugger/Breakpoints.h index 4fc9dab27e..16103017c3 100644 --- a/Core/Debugger/Breakpoints.h +++ b/Core/Debugger/Breakpoints.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/Debugger/DebugInterface.h b/Core/Debugger/DebugInterface.h index 951e0055b2..9e1c5df1cc 100644 --- a/Core/Debugger/DebugInterface.h +++ b/Core/Debugger/DebugInterface.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/Debugger/SymbolMap.cpp b/Core/Debugger/SymbolMap.cpp index 32105e3964..b4f454b32f 100644 --- a/Core/Debugger/SymbolMap.cpp +++ b/Core/Debugger/SymbolMap.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/Debugger/SymbolMap.h b/Core/Debugger/SymbolMap.h index 788f4afaf5..07116afe05 100644 --- a/Core/Debugger/SymbolMap.h +++ b/Core/Debugger/SymbolMap.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/ELF/ElfReader.cpp b/Core/ELF/ElfReader.cpp index b5e60bdb77..36f5d08899 100644 --- a/Core/ELF/ElfReader.cpp +++ b/Core/ELF/ElfReader.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -51,7 +51,7 @@ void addrToHiLo(u32 addr, u16 &hi, s16 &lo) } -bool ElfReader::LoadInto(u32 vaddr) +bool ElfReader::LoadInto(u32 loadAddress) { DEBUG_LOG(LOADER,"String section: %i", header->e_shstrndx); @@ -77,13 +77,32 @@ bool ElfReader::LoadInto(u32 vaddr) bRelocate = (header->e_type != ET_EXEC); entryPoint = header->e_entry; - if (bRelocate) - { + u32 totalStart = 0xFFFFFFFF; + u32 totalEnd = 0; + for (int i = 0; i < header->e_phnum; i++) { + Elf32_Phdr *p = &segments[i]; + if (p->p_type == PT_LOAD) { + if (p->p_vaddr < totalStart) + totalStart = p->p_vaddr; + if (p->p_vaddr + p->p_memsz > totalEnd) + totalEnd = p->p_vaddr + p->p_memsz; + } + } + u32 totalSize = totalEnd - totalStart; + if (loadAddress) + vaddr = userMemory.AllocAt(loadAddress, totalSize, "ELF"); + else + vaddr = userMemory.Alloc(totalSize, false, "ELF"); + + if (vaddr == -1) { + ERROR_LOG(LOADER, "Failed to allocate memory for ELF!"); + return false; + } + + if (bRelocate) { DEBUG_LOG(LOADER,"Relocatable module"); entryPoint += vaddr; - } - else - { + } else { DEBUG_LOG(LOADER,"Prerelocated executable"); } @@ -96,7 +115,6 @@ bool ElfReader::LoadInto(u32 vaddr) for (int i=0; ie_phnum; i++) { Elf32_Phdr *p = segments + i; - INFO_LOG(LOADER, "p = %p", p); DEBUG_LOG(LOADER, "Type: %i Vaddr: %08x Filesz: %i Memsz: %i ", (int)p->p_type, (u32)p->p_vaddr, (int)p->p_filesz, (int)p->p_memsz); if (p->p_type == PT_LOAD) @@ -109,14 +127,12 @@ bool ElfReader::LoadInto(u32 vaddr) u32 srcSize = p->p_filesz; u32 dstSize = p->p_memsz; - userMemory.AllocAt(writeAddr, dstSize, "ELF"); - - memcpy(dst, src, srcSize); if (srcSize < dstSize) { - //memset(dst + srcSize, 0, dstSize-srcSize); //zero out bss + memset(dst + srcSize, 0, dstSize - srcSize); //zero out bss } + memcpy(dst, src, srcSize); DEBUG_LOG(LOADER,"Loadable Segment Copied to %08x, size %08x", writeAddr, (u32)p->p_memsz); } } @@ -185,7 +201,7 @@ bool ElfReader::LoadInto(u32 vaddr) addr += segmentVAddr[readwrite]; u32 op = Memory::ReadUnchecked_U32(addr); - + const bool log = false; //log=true; if (log) diff --git a/Core/ELF/ElfReader.h b/Core/ELF/ElfReader.h index 722fd95ab3..9290cc22b5 100644 --- a/Core/ELF/ElfReader.h +++ b/Core/ELF/ElfReader.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -41,6 +41,7 @@ class ElfReader u32 *sectionAddrs; bool bRelocate; u32 entryPoint; + u32 vaddr; public: ElfReader(void *ptr) { @@ -95,9 +96,24 @@ public: } SectionID GetSectionByName(const char *name, int firstSection=0); //-1 for not found + u32 GetSegmentPaddr(int segment) + { + return segments[segment].p_paddr; + } + u32 GetSegmentOffset(int segment) + { + return segments[segment].p_offset; + } + bool DidRelocate() { return bRelocate; } + + u32 GetVaddr() + { + return vaddr; + } + // More indepth stuff:) bool LoadInto(u32 vaddr); bool LoadSymbols(); diff --git a/Core/ELF/ElfTypes.h b/Core/ELF/ElfTypes.h index f62f4e793f..1bfdf03019 100644 --- a/Core/ELF/ElfTypes.h +++ b/Core/ELF/ElfTypes.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/ELF/PrxDecrypter.cpp b/Core/ELF/PrxDecrypter.cpp new file mode 100644 index 0000000000..4419dcd665 --- /dev/null +++ b/Core/ELF/PrxDecrypter.cpp @@ -0,0 +1,737 @@ +#include + +extern "C" +{ +#include "ext/libkirk/kirk_engine.h" +} + +#include "../../Globals.h" + +// Thank you PSARDUMPER & JPCSP keys + +// PRXDecrypter 16-byte tag keys. +u8 keys260_0[] = {0xC3, 0x24, 0x89, 0xD3, 0x80, 0x87, 0xB2, 0x4E, 0x4C, 0xD7, 0x49, 0xE4, 0x9D, 0x1D, 0x34, 0xD1}; +u8 keys260_1[] = {0xF3, 0xAC, 0x6E, 0x7C, 0x04, 0x0A, 0x23, 0xE7, 0x0D, 0x33, 0xD8, 0x24, 0x73, 0x39, 0x2B, 0x4A}; +u8 keys260_2[] = {0x72, 0xB4, 0x39, 0xFF, 0x34, 0x9B, 0xAE, 0x82, 0x30, 0x34, 0x4A, 0x1D, 0xA2, 0xD8, 0xB4, 0x3C}; +u8 keys280_0[] = {0xCA, 0xFB, 0xBF, 0xC7, 0x50, 0xEA, 0xB4, 0x40, 0x8E, 0x44, 0x5C, 0x63, 0x53, 0xCE, 0x80, 0xB1}; +u8 keys280_1[] = {0x40, 0x9B, 0xC6, 0x9B, 0xA9, 0xFB, 0x84, 0x7F, 0x72, 0x21, 0xD2, 0x36, 0x96, 0x55, 0x09, 0x74}; +u8 keys280_2[] = {0x03, 0xA7, 0xCC, 0x4A, 0x5B, 0x91, 0xC2, 0x07, 0xFF, 0xFC, 0x26, 0x25, 0x1E, 0x42, 0x4B, 0xB5}; +u8 keys300_0[] = {0x9F, 0x67, 0x1A, 0x7A, 0x22, 0xF3, 0x59, 0x0B, 0xAA, 0x6D, 0xA4, 0xC6, 0x8B, 0xD0, 0x03, 0x77}; +u8 keys300_1[] = {0x15, 0x07, 0x63, 0x26, 0xDB, 0xE2, 0x69, 0x34, 0x56, 0x08, 0x2A, 0x93, 0x4E, 0x4B, 0x8A, 0xB2}; +u8 keys300_2[] = {0x56, 0x3B, 0x69, 0xF7, 0x29, 0x88, 0x2F, 0x4C, 0xDB, 0xD5, 0xDE, 0x80, 0xC6, 0x5C, 0xC8, 0x73}; +u8 keys303_0[] = {0x7b, 0xa1, 0xe2, 0x5a, 0x91, 0xb9, 0xd3, 0x13, 0x77, 0x65, 0x4a, 0xb7, 0xc2, 0x8a, 0x10, 0xaf}; +u8 keys310_0[] = {0xa2, 0x41, 0xe8, 0x39, 0x66, 0x5b, 0xfa, 0xbb, 0x1b, 0x2d, 0x6e, 0x0e, 0x33, 0xe5, 0xd7, 0x3f}; +u8 keys310_1[] = {0xA4, 0x60, 0x8F, 0xAB, 0xAB, 0xDE, 0xA5, 0x65, 0x5D, 0x43, 0x3A, 0xD1, 0x5E, 0xC3, 0xFF, 0xEA}; +u8 keys310_2[] = {0xE7, 0x5C, 0x85, 0x7A, 0x59, 0xB4, 0xE3, 0x1D, 0xD0, 0x9E, 0xCE, 0xC2, 0xD6, 0xD4, 0xBD, 0x2B}; +u8 keys310_3[] = {0x2E, 0x00, 0xF6, 0xF7, 0x52, 0xCF, 0x95, 0x5A, 0xA1, 0x26, 0xB4, 0x84, 0x9B, 0x58, 0x76, 0x2F}; +u8 keys330_0[] = {0x3B, 0x9B, 0x1A, 0x56, 0x21, 0x80, 0x14, 0xED, 0x8E, 0x8B, 0x08, 0x42, 0xFA, 0x2C, 0xDC, 0x3A}; +u8 keys330_1[] = {0xE8, 0xBE, 0x2F, 0x06, 0xB1, 0x05, 0x2A, 0xB9, 0x18, 0x18, 0x03, 0xE3, 0xEB, 0x64, 0x7D, 0x26}; +u8 keys330_2[] = {0xAB, 0x82, 0x25, 0xD7, 0x43, 0x6F, 0x6C, 0xC1, 0x95, 0xC5, 0xF7, 0xF0, 0x63, 0x73, 0x3F, 0xE7}; +u8 keys330_3[] = {0xA8, 0xB1, 0x47, 0x77, 0xDC, 0x49, 0x6A, 0x6F, 0x38, 0x4C, 0x4D, 0x96, 0xBD, 0x49, 0xEC, 0x9B}; +u8 keys330_4[] = {0xEC, 0x3B, 0xD2, 0xC0, 0xFA, 0xC1, 0xEE, 0xB9, 0x9A, 0xBC, 0xFF, 0xA3, 0x89, 0xF2, 0x60, 0x1F}; +u8 keys360_0[] = {0x3C, 0x2B, 0x51, 0xD4, 0x2D, 0x85, 0x47, 0xDA, 0x2D, 0xCA, 0x18, 0xDF, 0xFE, 0x54, 0x09, 0xED}; +u8 keys360_1[] = {0x31, 0x1F, 0x98, 0xD5, 0x7B, 0x58, 0x95, 0x45, 0x32, 0xAB, 0x3A, 0xE3, 0x89, 0x32, 0x4B, 0x34}; +u8 keys370_0[] = {0x26, 0x38, 0x0A, 0xAC, 0xA5, 0xD8, 0x74, 0xD1, 0x32, 0xB7, 0x2A, 0xBF, 0x79, 0x9E, 0x6D, 0xDB}; +u8 keys370_1[] = {0x53, 0xE7, 0xAB, 0xB9, 0xC6, 0x4A, 0x4B, 0x77, 0x92, 0x17, 0xB5, 0x74, 0x0A, 0xDA, 0xA9, 0xEA}; +u8 keys370_2[] = {0x71, 0x10, 0xF0, 0xA4, 0x16, 0x14, 0xD5, 0x93, 0x12, 0xFF, 0x74, 0x96, 0xDF, 0x1F, 0xDA, 0x89}; +u8 keys390_0[] = {0x45, 0xEF, 0x5C, 0x5D, 0xED, 0x81, 0x99, 0x84, 0x12, 0x94, 0x8F, 0xAB, 0xE8, 0x05, 0x6D, 0x7D}; +u8 keys390_1[] = {0x70, 0x1B, 0x08, 0x25, 0x22, 0xA1, 0x4D, 0x3B, 0x69, 0x21, 0xF9, 0x71, 0x0A, 0xA8, 0x41, 0xA9}; +u8 keys500_0[] = {0xEB, 0x1B, 0x53, 0x0B, 0x62, 0x49, 0x32, 0x58, 0x1F, 0x83, 0x0A, 0xF4, 0x99, 0x3D, 0x75, 0xD0}; +u8 keys500_1[] = {0xBA, 0xE2, 0xA3, 0x12, 0x07, 0xFF, 0x04, 0x1B, 0x64, 0xA5, 0x11, 0x85, 0xF7, 0x2F, 0x99, 0x5B}; +u8 keys500_2[] = {0x2C, 0x8E, 0xAF, 0x1D, 0xFF, 0x79, 0x73, 0x1A, 0xAD, 0x96, 0xAB, 0x09, 0xEA, 0x35, 0x59, 0x8B}; +u8 keys500_c[] = {0xA3, 0x5D, 0x51, 0xE6, 0x56, 0xC8, 0x01, 0xCA, 0xE3, 0x77, 0xBF, 0xCD, 0xFF, 0x24, 0xDA, 0x4D}; +u8 keys505_a[] = {0x7B, 0x94, 0x72, 0x27, 0x4C, 0xCC, 0x54, 0x3B, 0xAE, 0xDF, 0x46, 0x37, 0xAC, 0x01, 0x4D, 0x87}; +u8 keys505_0[] = {0x2E, 0x8E, 0x97, 0xA2, 0x85, 0x42, 0x70, 0x73, 0x18, 0xDA, 0xA0, 0x8A, 0xF8, 0x62, 0xA2, 0xB0}; +u8 keys505_1[] = {0x58, 0x2A, 0x4C, 0x69, 0x19, 0x7B, 0x83, 0x3D, 0xD2, 0x61, 0x61, 0xFE, 0x14, 0xEE, 0xAA, 0x11}; +u8 keys570_5k[] = {0x6D, 0x72, 0xA4, 0xBA, 0x7F, 0xBF, 0xD1, 0xF1, 0xA9, 0xF3, 0xBB, 0x07, 0x1B, 0xC0, 0xB3, 0x66}; +u8 keys600_1[] = {0xE3, 0x52, 0x39, 0x97, 0x3B, 0x84, 0x41, 0x1C, 0xC3, 0x23, 0xF1, 0xB8, 0xA9, 0x09, 0x4B, 0xF0}; +u8 keys600_2[] = {0xE1, 0x45, 0x93, 0x2C, 0x53, 0xE2, 0xAB, 0x06, 0x6F, 0xB6, 0x8F, 0x0B, 0x66, 0x91, 0xE7, 0x1E}; +u8 keys620_0[] = {0xD6, 0xBD, 0xCE, 0x1E, 0x12, 0xAF, 0x9A, 0xE6, 0x69, 0x30, 0xDE, 0xDA, 0x88, 0xB8, 0xFF, 0xFB}; +u8 keys620_1[] = {0x1D, 0x13, 0xE9, 0x50, 0x04, 0x73, 0x3D, 0xD2, 0xE1, 0xDA, 0xB9, 0xC1, 0xE6, 0x7B, 0x25, 0xA7}; +u8 keys620_a[] = {0xAC, 0x34, 0xBA, 0xB1, 0x97, 0x8D, 0xAE, 0x6F, 0xBA, 0xE8, 0xB1, 0xD6, 0xDF, 0xDF, 0xF1, 0xA2}; +u8 keys620_e[] = {0xB1, 0xB3, 0x7F, 0x76, 0xC3, 0xFB, 0x88, 0xE6, 0xF8, 0x60, 0xD3, 0x35, 0x3C, 0xA3, 0x4E, 0xF3}; +u8 keys620_5[] = {0xF1, 0xBC, 0x17, 0x07, 0xAE, 0xB7, 0xC8, 0x30, 0xD8, 0x34, 0x9D, 0x40, 0x6A, 0x8E, 0xDF, 0x4E}; +u8 keys620_5k[] = {0x41, 0x8A, 0x35, 0x4F, 0x69, 0x3A, 0xDF, 0x04, 0xFD, 0x39, 0x46, 0xA2, 0x5C, 0x2D, 0xF2, 0x21}; +u8 keys620_5v[] = {0xF2, 0x8F, 0x75, 0xA7, 0x31, 0x91, 0xCE, 0x9E, 0x75, 0xBD, 0x27, 0x26, 0xB4, 0xB4, 0x0C, 0x32}; +u8 keys630_k1[] = {0x36, 0xB0, 0xDC, 0xFC, 0x59, 0x2A, 0x95, 0x1D, 0x80, 0x2D, 0x80, 0x3F, 0xCD, 0x30, 0xA0, 0x1B}; +u8 keys630_k2[] = {0xd4, 0x35, 0x18, 0x02, 0x29, 0x68, 0xfb, 0xa0, 0x6a, 0xa9, 0xa5, 0xed, 0x78, 0xfd, 0x2e, 0x9d}; +u8 keys630_k3[] = {0x23, 0x8D, 0x3D, 0xAE, 0x41, 0x50, 0xA0, 0xFA, 0xF3, 0x2F, 0x32, 0xCE, 0xC7, 0x27, 0xCD, 0x50}; +u8 keys630_k4[] = {0xAA, 0xA1, 0xB5, 0x7C, 0x93, 0x5A, 0x95, 0xBD, 0xEF, 0x69, 0x16, 0xFC, 0x2B, 0x92, 0x31, 0xDD}; +u8 keys630_k5[] = {0x87, 0x37, 0x21, 0xCC, 0x65, 0xAE, 0xAA, 0x5F, 0x40, 0xF6, 0x6F, 0x2A, 0x86, 0xC7, 0xA1, 0xC8}; +u8 keys630_k6[] = {0x8D, 0xDB, 0xDC, 0x5C, 0xF2, 0x70, 0x2B, 0x40, 0xB2, 0x3D, 0x00, 0x09, 0x61, 0x7C, 0x10, 0x60}; +u8 keys630_k7[] = {0x77, 0x1C, 0x06, 0x5F, 0x53, 0xEC, 0x3F, 0xFC, 0x22, 0xCE, 0x5A, 0x27, 0xFF, 0x78, 0xA8, 0x48}; +u8 keys630_k8[] = {0x81, 0xD1, 0x12, 0x89, 0x35, 0xC8, 0xEA, 0x8B, 0xE0, 0x02, 0x2D, 0x2D, 0x6A, 0x18, 0x67, 0xB8}; +u8 keys636_k1[] = {0x07, 0xE3, 0x08, 0x64, 0x7F, 0x60, 0xA3, 0x36, 0x6A, 0x76, 0x21, 0x44, 0xC9, 0xD7, 0x06, 0x83}; +u8 keys636_k2[] = {0x91, 0xF2, 0x02, 0x9E, 0x63, 0x32, 0x30, 0xA9, 0x1D, 0xDA, 0x0B, 0xA8, 0xB7, 0x41, 0xA3, 0xCC}; +u8 keys638_k4[] = {0x98, 0x43, 0xFF, 0x85, 0x68, 0xB2, 0xDB, 0x3B, 0xD4, 0x22, 0xD0, 0x4F, 0xAB, 0x5F, 0x0A, 0x31}; +u8 keys639_k3[] = {0x01, 0x7B, 0xF0, 0xE9, 0xBE, 0x9A, 0xDD, 0x54, 0x37, 0xEA, 0x0E, 0xC4, 0xD6, 0x4D, 0x8E, 0x9E}; +u8 keys660_k1[] = {0x76, 0xF2, 0x6C, 0x0A, 0xCA, 0x3A, 0xBA, 0x4E, 0xAC, 0x76, 0xD2, 0x40, 0xF5, 0xC3, 0xBF, 0xF9}; +u8 keys660_k2[] = {0x7A, 0x3E, 0x55, 0x75, 0xB9, 0x6A, 0xFC, 0x4F, 0x3E, 0xE3, 0xDF, 0xB3, 0x6C, 0xE8, 0x2A, 0x82}; +u8 keys660_k3[] = {0xFA, 0x79, 0x09, 0x36, 0xE6, 0x19, 0xE8, 0xA4, 0xA9, 0x41, 0x37, 0x18, 0x81, 0x02, 0xE9, 0xB3}; +u8 keys660_v1[] = {0xBA, 0x76, 0x61, 0x47, 0x8B, 0x55, 0xA8, 0x72, 0x89, 0x15, 0x79, 0x6D, 0xD7, 0x2F, 0x78, 0x0E}; +u8 keys660_v2[] = {0xF9, 0x4A, 0x6B, 0x96, 0x79, 0x3F, 0xEE, 0x0A, 0x04, 0xC8, 0x8D, 0x7E, 0x5F, 0x38, 0x3A, 0xCF}; +u8 keys660_v3[] = {0x88, 0xAF, 0x18, 0xE9, 0xC3, 0xAA, 0x6B, 0x56, 0xF7, 0xC5, 0xA8, 0xBF, 0x1A, 0x84, 0xE9, 0xF3}; +u8 keys660_v4[] = {0xD1, 0xB0, 0xAE, 0xC3, 0x24, 0x36, 0x13, 0x49, 0xD6, 0x49, 0xD7, 0x88, 0xEA, 0xA4, 0x99, 0x86}; +u8 keys660_v5[] = {0xCB, 0x93, 0x12, 0x38, 0x31, 0xC0, 0x2D, 0x2E, 0x7A, 0x18, 0x5C, 0xAC, 0x92, 0x93, 0xAB, 0x32}; +u8 keys660_v6[] = {0x92, 0x8C, 0xA4, 0x12, 0xD6, 0x5C, 0x55, 0x31, 0x5B, 0x94, 0x23, 0x9B, 0x62, 0xB3, 0xDB, 0x47}; +u8 keys660_k4[] = {0xC8, 0xA0, 0x70, 0x98, 0xAE, 0xE6, 0x2B, 0x80, 0xD7, 0x91, 0xE6, 0xCA, 0x4C, 0xA9, 0x78, 0x4E}; +u8 keys660_k5[] = {0xBF, 0xF8, 0x34, 0x02, 0x84, 0x47, 0xBD, 0x87, 0x1C, 0x52, 0x03, 0x23, 0x79, 0xBB, 0x59, 0x81}; +u8 keys660_k6[] = {0xD2, 0x83, 0xCC, 0x63, 0xBB, 0x10, 0x15, 0xE7, 0x7B, 0xC0, 0x6D, 0xEE, 0x34, 0x9E, 0x4A, 0xFA}; +u8 keys660_k7[] = {0xEB, 0xD9, 0x1E, 0x05, 0x3C, 0xAE, 0xAB, 0x62, 0xE3, 0xB7, 0x1F, 0x37, 0xE5, 0xCD, 0x68, 0xC3}; +u8 keys660_v7[] = {0xC5, 0x9C, 0x77, 0x9C, 0x41, 0x01, 0xE4, 0x85, 0x79, 0xC8, 0x71, 0x63, 0xA5, 0x7D, 0x4F, 0xFB}; +u8 keys660_v8[] = {0x86, 0xA0, 0x7D, 0x4D, 0xB3, 0x6B, 0xA2, 0xFD, 0xF4, 0x15, 0x85, 0x70, 0x2D, 0x6A, 0x0D, 0x3A}; +u8 keys660_k8[] = {0x85, 0x93, 0x1F, 0xED, 0x2C, 0x4D, 0xA4, 0x53, 0x59, 0x9C, 0x3F, 0x16, 0xF3, 0x50, 0xDE, 0x46}; +u8 key_21C0[] = {0x6A, 0x19, 0x71, 0xF3, 0x18, 0xDE, 0xD3, 0xA2, 0x6D, 0x3B, 0xDE, 0xC7, 0xBE, 0x98, 0xE2, 0x4C}; +u8 key_2250[] = {0x50, 0xCC, 0x03, 0xAC, 0x3F, 0x53, 0x1A, 0xFA, 0x0A, 0xA4, 0x34, 0x23, 0x86, 0x61, 0x7F, 0x97}; +u8 key_22E0[] = {0x66, 0x0F, 0xCB, 0x3B, 0x30, 0x75, 0xE3, 0x10, 0x0A, 0x95, 0x65, 0xC7, 0x3C, 0x93, 0x87, 0x22}; +u8 key_2D80[] = {0x40, 0x02, 0xC0, 0xBF, 0x20, 0x02, 0xC0, 0xBF, 0x5C, 0x68, 0x2B, 0x95, 0x5F, 0x40, 0x7B, 0xB8}; +u8 key_2D90[] = {0x55, 0x19, 0x35, 0x10, 0x48, 0xD8, 0x2E, 0x46, 0xA8, 0xB1, 0x47, 0x77, 0xDC, 0x49, 0x6A, 0x6F}; +u8 key_2DA8[] = {0x80, 0x02, 0xC0, 0xBF, 0x00, 0x0A, 0xC0, 0xBF, 0x40, 0x03, 0xC0, 0xBF, 0x40, 0x00, 0x00, 0x00}; +u8 key_2DB8[] = {0x4C, 0x2D, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xB8, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +u8 key_D91605F0[] = {0xB8, 0x8C, 0x45, 0x8B, 0xB6, 0xE7, 0x6E, 0xB8, 0x51, 0x59, 0xA6, 0x53, 0x7C, 0x5E, 0x86, 0x31}; +u8 key_D91606F0[] = {0xED, 0x10, 0xE0, 0x36, 0xC4, 0xFE, 0x83, 0xF3, 0x75, 0x70, 0x5E, 0xF6, 0xA4, 0x40, 0x05, 0xF7}; +u8 key_D91608F0[] = {0x5C, 0x77, 0x0C, 0xBB, 0xB4, 0xC2, 0x4F, 0xA2, 0x7E, 0x3B, 0x4E, 0xB4, 0xB4, 0xC8, 0x70, 0xAF}; +u8 key_D91609F0[] = {0xD0, 0x36, 0x12, 0x75, 0x80, 0x56, 0x20, 0x43, 0xC4, 0x30, 0x94, 0x3E, 0x1C, 0x75, 0xD1, 0xBF}; +u8 key_D9160AF0[] = {0x10, 0xA9, 0xAC, 0x16, 0xAE, 0x19, 0xC0, 0x7E, 0x3B, 0x60, 0x77, 0x86, 0x01, 0x6F, 0xF2, 0x63}; +u8 key_D9160BF0[] = {0x83, 0x83, 0xF1, 0x37, 0x53, 0xD0, 0xBE, 0xFC, 0x8D, 0xA7, 0x32, 0x52, 0x46, 0x0A, 0xC2, 0xC2}; +u8 key_D91611F0[] = {0x61, 0xB0, 0xC0, 0x58, 0x71, 0x57, 0xD9, 0xFA, 0x74, 0x67, 0x0E, 0x5C, 0x7E, 0x6E, 0x95, 0xB9}; +u8 key_D91612F0[] = {0x9E, 0x20, 0xE1, 0xCD, 0xD7, 0x88, 0xDE, 0xC0, 0x31, 0x9B, 0x10, 0xAF, 0xC5, 0xB8, 0x73, 0x23}; +u8 key_D91613F0[] = {0xEB, 0xFF, 0x40, 0xD8, 0xB4, 0x1A, 0xE1, 0x66, 0x91, 0x3B, 0x8F, 0x64, 0xB6, 0xFC, 0xB7, 0x12}; +u8 key_D91614F0[] = {0xFD, 0xF7, 0xB7, 0x3C, 0x9F, 0xD1, 0x33, 0x95, 0x11, 0xB8, 0xB5, 0xBB, 0x54, 0x23, 0x73, 0x85}; +u8 key_D91615F0[] = {0xC8, 0x03, 0xE3, 0x44, 0x50, 0xF1, 0xE7, 0x2A, 0x6A, 0x0D, 0xC3, 0x61, 0xB6, 0x8E, 0x5F, 0x51}; +u8 key_D91616F0[] = {0x53, 0x03, 0xB8, 0x6A, 0x10, 0x19, 0x98, 0x49, 0x1C, 0xAF, 0x30, 0xE4, 0x25, 0x1B, 0x6B, 0x28}; +u8 key_D91617F0[] = {0x02, 0xFA, 0x48, 0x73, 0x75, 0xAF, 0xAE, 0x0A, 0x67, 0x89, 0x2B, 0x95, 0x4B, 0x09, 0x87, 0xA3}; +u8 key_D91618F0[] = {0x96, 0x96, 0x7C, 0xC3, 0xF7, 0x12, 0xDA, 0x62, 0x1B, 0xF6, 0x9A, 0x9A, 0x44, 0x44, 0xBC, 0x48}; +u8 key_D91619F0[] = {0xE0, 0x32, 0xA7, 0x08, 0x6B, 0x2B, 0x29, 0x2C, 0xD1, 0x4D, 0x5B, 0xEE, 0xA8, 0xC8, 0xB4, 0xE9}; +u8 key_D9161AF0[] = {0x27, 0xE5, 0xA7, 0x49, 0x52, 0xE1, 0x94, 0x67, 0x35, 0x66, 0x91, 0x0C, 0xE8, 0x9A, 0x25, 0x24}; +u8 key_D91620F0[] = {0x52, 0x1C, 0xB4, 0x5F, 0x40, 0x3B, 0x9A, 0xDD, 0xAC, 0xFC, 0xEA, 0x92, 0xFD, 0xDD, 0xF5, 0x90}; +u8 key_D91621F0[] = {0xD1, 0x91, 0x2E, 0xA6, 0x21, 0x14, 0x29, 0x62, 0xF6, 0xED, 0xAE, 0xCB, 0xDD, 0xA3, 0xBA, 0xFE}; +u8 key_D91622F0[] = {0x59, 0x5D, 0x78, 0x4D, 0x21, 0xB2, 0x01, 0x17, 0x6C, 0x9A, 0xB5, 0x1B, 0xDA, 0xB7, 0xF9, 0xE6}; +u8 key_D91623F0[] = {0xAA, 0x45, 0xEB, 0x4F, 0x62, 0xFB, 0xD1, 0x0D, 0x71, 0xD5, 0x62, 0xD2, 0xF5, 0xBF, 0xA5, 0x2F}; +u8 key_D91624F0[] = {0x61, 0xB7, 0x26, 0xAF, 0x8B, 0xF1, 0x41, 0x58, 0x83, 0x6A, 0xC4, 0x92, 0x12, 0xCB, 0xB1, 0xE9}; +u8 key_D91628F0[] = {0x49, 0xA4, 0xFC, 0x66, 0xDC, 0xE7, 0x62, 0x21, 0xDB, 0x18, 0xA7, 0x50, 0xD6, 0xA8, 0xC1, 0xB6}; +u8 key_D91680F0[] = {0x2C, 0x22, 0x9B, 0x12, 0x36, 0x74, 0x11, 0x67, 0x49, 0xD1, 0xD1, 0x88, 0x92, 0xF6, 0xA1, 0xD8}; +u8 key_D91681F0[] = {0x52, 0xB6, 0x36, 0x6C, 0x8C, 0x46, 0x7F, 0x7A, 0xCC, 0x11, 0x62, 0x99, 0xC1, 0x99, 0xBE, 0x98}; +u8 key_2E5E10F0[] = {0x9D, 0x5C, 0x5B, 0xAF, 0x8C, 0xD8, 0x69, 0x7E, 0x51, 0x9F, 0x70, 0x96, 0xE6, 0xD5, 0xC4, 0xE8}; +u8 key_2E5E12F0[] = {0x8A, 0x7B, 0xC9, 0xD6, 0x52, 0x58, 0x88, 0xEA, 0x51, 0x83, 0x60, 0xCA, 0x16, 0x79, 0xE2, 0x07}; +u8 key_2E5E13F0[] = {0xFF, 0xA4, 0x68, 0xC3, 0x31, 0xCA, 0xB7, 0x4C, 0xF1, 0x23, 0xFF, 0x01, 0x65, 0x3D, 0x26, 0x36}; +u8 key_2FD30BF0[] = {0xD8, 0x58, 0x79, 0xF9, 0xA4, 0x22, 0xAF, 0x86, 0x90, 0xAC, 0xDA, 0x45, 0xCE, 0x60, 0x40, 0x3F}; +u8 key_2FD311F0[] = {0x3A, 0x6B, 0x48, 0x96, 0x86, 0xA5, 0xC8, 0x80, 0x69, 0x6C, 0xE6, 0x4B, 0xF6, 0x04, 0x17, 0x44}; +u8 key_2FD312F0[] = {0xC5, 0xFB, 0x69, 0x03, 0x20, 0x7A, 0xCF, 0xBA, 0x2C, 0x90, 0xF8, 0xB8, 0x4D, 0xD2, 0xF1, 0xDE}; +u8 keys02G_E[] = {0x9D, 0x09, 0xFD, 0x20, 0xF3, 0x8F, 0x10, 0x69, 0x0D, 0xB2, 0x6F, 0x00, 0xCC, 0xC5, 0x51, 0x2E}; +u8 keys03G_E[] = {0x4F, 0x44, 0x5C, 0x62, 0xB3, 0x53, 0xC4, 0x30, 0xFC, 0x3A, 0xA4, 0x5B, 0xEC, 0xFE, 0x51, 0xEA}; +u8 keys05G_E[] = {0x5D, 0xAA, 0x72, 0xF2, 0x26, 0x60, 0x4D, 0x1C, 0xE7, 0x2D, 0xC8, 0xA3, 0x2F, 0x79, 0xC5, 0x54}; +u8 oneseg_310[] = {0xC7, 0x27, 0x72, 0x85, 0xAB, 0xA7, 0xF7, 0xF0, 0x4C, 0xC1, 0x86, 0xCC, 0xE3, 0x7F, 0x17, 0xCA}; +u8 oneseg_300[] = {0x76, 0x40, 0x9E, 0x08, 0xDB, 0x9B, 0x3B, 0xA1, 0x47, 0x8A, 0x96, 0x8E, 0xF3, 0xF7, 0x62, 0x92}; +u8 oneseg_280[] = {0x23, 0xDC, 0x3B, 0xB5, 0xA9, 0x82, 0xD6, 0xEA, 0x63, 0xA3, 0x6E, 0x2B, 0x2B, 0xE9, 0xE1, 0x54}; +u8 oneseg_260_271[] = {0x22, 0x43, 0x57, 0x68, 0x2F, 0x41, 0xCE, 0x65, 0x4C, 0xA3, 0x7C, 0xC6, 0xC4, 0xAC, 0xF3, 0x60}; +u8 oneseg_slim[] = {0x12, 0x57, 0x0D, 0x8A, 0x16, 0x6D, 0x87, 0x06, 0x03, 0x7D, 0xC8, 0x8B, 0x62, 0xA3, 0x32, 0xA9}; +u8 ms_app_main[] = {0x1E, 0x2E, 0x38, 0x49, 0xDA, 0xD4, 0x16, 0x08, 0x27, 0x2E, 0xF3, 0xBC, 0x37, 0x75, 0x80, 0x93}; +u8 demokeys_280[] = {0x12, 0x99, 0x70, 0x5E, 0x24, 0x07, 0x6C, 0xD0, 0x2D, 0x06, 0xFE, 0x7E, 0xB3, 0x0C, 0x11, 0x26}; +u8 demokeys_3XX_1[] = {0x47, 0x05, 0xD5, 0xE3, 0x56, 0x1E, 0x81, 0x9B, 0x09, 0x2F, 0x06, 0xDB, 0x6B, 0x12, 0x92, 0xE0}; +u8 demokeys_3XX_2[] = {0xF6, 0x62, 0x39, 0x6E, 0x26, 0x22, 0x4D, 0xCA, 0x02, 0x64, 0x16, 0x99, 0x7B, 0x9A, 0xE7, 0xB8}; +u8 ebootbin_271_new[] = {0xF4, 0xAE, 0xF4, 0xE1, 0x86, 0xDD, 0xD2, 0x9C, 0x7C, 0xC5, 0x42, 0xA6, 0x95, 0xA0, 0x83, 0x88}; +u8 ebootbin_280_new[] = {0xB8, 0x8C, 0x45, 0x8B, 0xB6, 0xE7, 0x6E, 0xB8, 0x51, 0x59, 0xA6, 0x53, 0x7C, 0x5E, 0x86, 0x31}; +u8 ebootbin_300_new[] = {0xED, 0x10, 0xE0, 0x36, 0xC4, 0xFE, 0x83, 0xF3, 0x75, 0x70, 0x5E, 0xF6, 0xA4, 0x40, 0x05, 0xF7}; +u8 ebootbin_310_new[] = {0x5C, 0x77, 0x0C, 0xBB, 0xB4, 0xC2, 0x4F, 0xA2, 0x7E, 0x3B, 0x4E, 0xB4, 0xB4, 0xC8, 0x70, 0xAF}; +u8 gameshare_260_271[] = {0xF9, 0x48, 0x38, 0x0C, 0x96, 0x88, 0xA7, 0x74, 0x4F, 0x65, 0xA0, 0x54, 0xC2, 0x76, 0xD9, 0xB8}; +u8 gameshare_280[] = {0x2D, 0x86, 0x77, 0x3A, 0x56, 0xA4, 0x4F, 0xDD, 0x3C, 0x16, 0x71, 0x93, 0xAA, 0x8E, 0x11, 0x43}; +u8 gameshare_300[] = {0x78, 0x1A, 0xD2, 0x87, 0x24, 0xBD, 0xA2, 0x96, 0x18, 0x3F, 0x89, 0x36, 0x72, 0x90, 0x92, 0x85}; +u8 gameshare_310[] = {0xC9, 0x7D, 0x3E, 0x0A, 0x54, 0x81, 0x6E, 0xC7, 0x13, 0x74, 0x99, 0x74, 0x62, 0x18, 0xE7, 0xDD}; +u8 key_380210F0[] = {0x32, 0x2C, 0xFA, 0x75, 0xE4, 0x7E, 0x93, 0xEB, 0x9F, 0x22, 0x80, 0x85, 0x57, 0x08, 0x98, 0x48}; +u8 key_380280F0[] = {0x97, 0x09, 0x12, 0xD3, 0xDB, 0x02, 0xBD, 0xD8, 0xE7, 0x74, 0x51, 0xFE, 0xF0, 0xEA, 0x6C, 0x5C}; +u8 key_380283F0[] = {0x34, 0x20, 0x0C, 0x8E, 0xA1, 0x86, 0x79, 0x84, 0xAF, 0x13, 0xAE, 0x34, 0x77, 0x6F, 0xEA, 0x89}; +u8 key_407810F0[] = {0xAF, 0xAD, 0xCA, 0xF1, 0x95, 0x59, 0x91, 0xEC, 0x1B, 0x27, 0xD0, 0x4E, 0x8A, 0xF3, 0x3D, 0xE7}; +u8 drmkeys_6XX_1[] = {0x36, 0xEF, 0x82, 0x4E, 0x74, 0xFB, 0x17, 0x5B, 0x14, 0x14, 0x05, 0xF3, 0xB3, 0x8A, 0x76, 0x18}; +u8 drmkeys_6XX_2[] = {0x21, 0x52, 0x5D, 0x76, 0xF6, 0x81, 0x0F, 0x15, 0x2F, 0x4A, 0x40, 0x89, 0x63, 0xA0, 0x10, 0x55}; + +// PRXDecrypter 144-byte tag keys. +u32 g_key0[] = { + 0x7b21f3be, 0x299c5e1d, 0x1c9c5e71, 0x96cb4645, 0x3c9b1be0, 0xeb85de3d, + 0x4a7f2022, 0xc2206eaa, 0xd50b3265, 0x55770567, 0x3c080840, 0x981d55f2, + 0x5fd8f6f3, 0xee8eb0c5, 0x944d8152, 0xf8278651, 0x2705bafa, 0x8420e533, + 0x27154ae9, 0x4819aa32, 0x59a3aa40, 0x2cb3cf65, 0xf274466d, 0x3a655605, + 0x21b0f88f, 0xc5b18d26, 0x64c19051, 0xd669c94e, 0xe87035f2, 0x9d3a5909, + 0x6f4e7102, 0xdca946ce, 0x8416881b, 0xbab097a5, 0x249125c6, 0xb34c0872}; +u32 g_key2[] = { + 0xccfda932, 0x51c06f76, 0x046dcccf, 0x49e1821e, 0x7d3b024c, 0x9dda5865, + 0xcc8c9825, 0xd1e97db5, 0x6874d8cb, 0x3471c987, 0x72edb3fc, 0x81c8365d, + 0xe161e33a, 0xfc92db59, 0x2009b1ec, 0xb1a94ce4, 0x2f03696b, 0x87e236d8, + 0x3b2b8ce9, 0x0305e784, 0xf9710883, 0xb039db39, 0x893bea37, 0xe74d6805, + 0x2a5c38bd, 0xb08dc813, 0x15b32375, 0x46be4525, 0x0103fd90, 0xa90e87a2, + 0x52aba66a, 0x85bf7b80, 0x45e8ce63, 0x4dd716d3, 0xf5e30d2d, 0xaf3ae456}; +u32 g_key3[] = { + 0xa6c8f5ca, 0x6d67c080, 0x924f4d3a, 0x047ca06a, 0x08640297, 0x4fd4a758, + 0xbd685a87, 0x9b2701c2, 0x83b62a35, 0x726b533c, 0xe522fa0c, 0xc24b06b4, + 0x459d1cac, 0xa8c5417b, 0x4fea62a2, 0x0615d742, 0x30628d09, 0xc44fab14, + 0x69ff715e, 0xd2d8837d, 0xbeed0b8b, 0x1e6e57ae, 0x61e8c402, 0xbe367a06, + 0x543f2b5e, 0xdb3ec058, 0xbe852075, 0x1e7e4dcc, 0x1564ea55, 0xec7825b4, + 0xc0538cad, 0x70f72c7f, 0x49e8c3d0, 0xeda97ec5, 0xf492b0a4, 0xe05eb02a}; +u32 g_key44[] = { + 0xef80e005, 0x3a54689f, 0x43c99ccd, 0x1b7727be, 0x5cb80038, 0xdd2efe62, + 0xf369f92c, 0x160f94c5, 0x29560019, 0xbf3c10c5, 0xf2ce5566, 0xcea2c626, + 0xb601816f, 0x64e7481e, 0x0c34debd, 0x98f29cb0, 0x3fc504d7, 0xc8fb39f0, + 0x0221b3d8, 0x63f936a2, 0x9a3a4800, 0x6ecc32e3, 0x8e120cfd, 0xb0361623, + 0xaee1e689, 0x745502eb, 0xe4a6c61c, 0x74f23eb4, 0xd7fa5813, 0xb01916eb, + 0x12328457, 0xd2bc97d2, 0x646425d8, 0x328380a5, 0x43da8ab1, 0x4b122ac9}; +u32 g_key20[] = { + 0x33b50800, 0xf32f5fcd, 0x3c14881f, 0x6e8a2a95, 0x29feefd5, 0x1394eae3, + 0xbd6bd443, 0x0821c083, 0xfab379d3, 0xe613e165, 0xf5a754d3, 0x108b2952, + 0x0a4b1e15, 0x61eadeba, 0x557565df, 0x3b465301, 0xae54ecc3, 0x61423309, + 0x70c9ff19, 0x5b0ae5ec, 0x989df126, 0x9d987a5f, 0x55bc750e, 0xc66eba27, + 0x2de988e8, 0xf76600da, 0x0382dccb, 0x5569f5f2, 0x8e431262, 0x288fe3d3, + 0x656f2187, 0x37d12e9c, 0x2f539eb4, 0xa492998e, 0xed3958f7, 0x39e96523}; +u32 g_key3A[] = { + 0x67877069, 0x3abd5617, 0xc23ab1dc, 0xab57507d, 0x066a7f40, 0x24def9b9, + 0x06f759e4, 0xdcf524b1, 0x13793e5e, 0x0359022d, 0xaae7e1a2, 0x76b9b2fa, + 0x9a160340, 0x87822fba, 0x19e28fbb, 0x9e338a02, 0xd8007e9a, 0xea317af1, + 0x630671de, 0x0b67ca7c, 0x865192af, 0xea3c3526, 0x2b448c8e, 0x8b599254, + 0x4602e9cb, 0x4de16cda, 0xe164d5bb, 0x07ecd88e, 0x99ffe5f8, 0x768800c1, + 0x53b091ed, 0x84047434, 0xb426dbbc, 0x36f948bb, 0x46142158, 0x749bb492}; +u32 g_keyEBOOT1xx[] = { + 0x18CB69EF, 0x158E8912, 0xDEF90EBB, 0x4CB0FB23, 0x3687EE18, 0x868D4A6E, + 0x19B5C756, 0xEE16551D, 0xE7CB2D6C, 0x9747C660, 0xCE95143F, 0x2956F477, + 0x03824ADE, 0x210C9DF1, 0x5029EB24, 0x81DFE69F, 0x39C89B00, 0xB00C8B91, + 0xEF2DF9C2, 0xE13A93FC, 0x8B94A4A8, 0x491DD09D, 0x686A400D, 0xCED4C7E4, + 0x96C8B7C9, 0x1EAADC28, 0xA4170B84, 0x505D5DDC, 0x5DA6C3CF, 0x0E5DFA2D, + 0x6E7919B5, 0xCE5E29C7, 0xAAACDB94, 0x45F70CDD, 0x62A73725, 0xCCE6563D}; +u32 g_keyEBOOT2xx[] = { + 0xDA8E36FA, 0x5DD97447, 0x76C19874, 0x97E57EAF, 0x1CAB09BD, 0x9835BAC6, + 0x03D39281, 0x03B205CF, 0x2882E734, 0xE714F663, 0xB96E2775, 0xBD8AAFC7, + 0x1DD3EC29, 0xECA4A16C, 0x5F69EC87, 0x85981E92, 0x7CFCAE21, 0xBAE9DD16, + 0xE6A97804, 0x2EEE02FC, 0x61DF8A3D, 0xDD310564, 0x9697E149, 0xC2453F3B, + 0xF91D8456, 0x39DA6BC8, 0xB3E5FEF5, 0x89C593A3, 0xFB5C8ABC, 0x6C0B7212, + 0xE10DD3CB, 0x98D0B2A8, 0x5FD61847, 0xF0DC2357, 0x7701166A, 0x0F5C3B68}; +u32 g_keyUPDATER[] = { + 0xA5603CBF, 0xD7482441, 0xF65764CC, 0x1F90060B, 0x4EA73E45, 0xE551D192, + 0xE7B75D8A, 0x465A506E, 0x40FB1022, 0x2C273350, 0x8096DA44, 0x9947198E, + 0x278DEE77, 0x745D062E, 0xC148FA45, 0x832582AF, 0x5FDB86DA, 0xCB15C4CE, + 0x2524C62F, 0x6C2EC3B1, 0x369BE39E, 0xF7EB1FC4, 0x1E51CE1A, 0xD70536F4, + 0xC34D39D8, 0x7418FB13, 0xE3C84DE1, 0xB118F03C, 0xA2018D4E, 0xE6D8770D, + 0x5720F390, 0x17F96341, 0x60A4A68F, 0x1327DD28, 0x05944C64, 0x0C2C4C12}; +u32 g_keyMEIMG250[] = { + 0xA381FEBC, 0x99B9D5C9, 0x6C560A8D, 0x30309F95, 0x792646CC, 0x82B64E5E, + 0x1A3951AD, 0x0A182EC4, 0xC46131B4, 0x77C50C8A, 0x325F16C6, 0x02D1942E, + 0x0AA38AC4, 0x2A940AC6, 0x67034726, 0xE52DB133, 0xD2EF2107, 0x85C81E90, + 0xC8D164BA, 0xC38DCE1D, 0x948BA275, 0x0DB84603, 0xE2473637, 0xCD74FCDA, + 0x588E3D66, 0x6D28E822, 0x891E548B, 0xF53CF56D, 0x0BBDDB66, 0xC4B286AA, + 0x2BEBBC4B, 0xFC261FF4, 0x92B8E705, 0xDCEE6952, 0x5E0442E5, 0x8BEB7F21}; +u32 g_keyMEIMG260[] = { + 0x11BFD698, 0xD7F9B324, 0xDD524927, 0x16215B86, 0x504AC36D, 0x5843B217, + 0xE5A0DA47, 0xBB73A1E7, 0x2915DB35, 0x375CFD3A, 0xBB70A905, 0x272BEFCA, + 0x2E960791, 0xEA0799BB, 0xB85AE6C8, 0xC9CAF773, 0x250EE641, 0x06E74A9E, + 0x5244895D, 0x466755A5, 0x9A84AF53, 0xE1024174, 0xEEBA031E, 0xED80B9CE, + 0xBC315F72, 0x5821067F, 0xE8313058, 0xD2D0E706, 0xE6D8933E, 0xD7D17FB4, + 0x505096C4, 0xFDA50B3B, 0x4635AE3D, 0xEB489C8A, 0x422D762D, 0x5A8B3231}; +u32 g_keyDEMOS27X[] = { + 0x1ABF102F, 0xD596D071, 0x6FC552B2, 0xD4F2531F, 0xF025CDD9, 0xAF9AAF03, + 0xE0CF57CF, 0x255494C4, 0x7003675E, 0x907BC884, 0x002D4EE4, 0x0B687A0D, + 0x9E3AA44F, 0xF58FDA81, 0xEC26AC8C, 0x3AC9B49D, 0x3471C037, 0xB0F3834D, + 0x10DC4411, 0xA232EA31, 0xE2E5FA6B, 0x45594B03, 0xE43A1C87, 0x31DAD9D1, + 0x08CD7003, 0xFA9C2FDF, 0x5A891D25, 0x9B5C1934, 0x22F366E5, 0x5F084A32, + 0x695516D5, 0x2245BE9F, 0x4F6DD705, 0xC4B8B8A1, 0xBC13A600, 0x77B7FC3B}; +u32 g_keyUNK1[] = { + 0x33B50800, 0xF32F5FCD, 0x3C14881F, 0x6E8A2A95, 0x29FEEFD5, 0x1394EAE3, + 0xBD6BD443, 0x0821C083, 0xFAB379D3, 0xE613E165, 0xF5A754D3, 0x108B2952, + 0x0A4B1E15, 0x61EADEBA, 0x557565DF, 0x3B465301, 0xAE54ECC3, 0x61423309, + 0x70C9FF19, 0x5B0AE5EC, 0x989DF126, 0x9D987A5F, 0x55BC750E, 0xC66EBA27, + 0x2DE988E8, 0xF76600DA, 0x0382DCCB, 0x5569F5F2, 0x8E431262, 0x288FE3D3, + 0x656F2187, 0x37D12E9C, 0x2F539EB4, 0xA492998E, 0xED3958F7, 0x39E96523}; +u32 g_key_GAMESHARE1xx[] = { + 0x721B53E8, 0xFC3E31C6, 0xF85BA2A2, 0x3CF0AC72, 0x54EEA7AB, 0x5959BFCB, + 0x54B8836B, 0xBC431313, 0x989EF2CF, 0xF0CE36B2, 0x98BA4CF8, 0xE971C931, + 0xA0375DC8, 0x08E52FA0, 0xAC0DD426, 0x57E4D601, 0xC56E61C7, 0xEF1AB98A, + 0xD1D9F8F4, 0x5FE9A708, 0x3EF09D07, 0xFA0C1A8C, 0xA91EEA5C, 0x58F482C5, + 0x2C800302, 0x7EE6F6C3, 0xFF6ABBBB, 0x2110D0D0, 0xD3297A88, 0x980012D3, + 0xDC59C87B, 0x7FDC5792, 0xDB3F5DA6, 0xFC23B787, 0x22698ED3, 0xB680E812}; +u32 g_key_GAMESHARE2xx[] = { + 0x94A757C7, 0x9FD39833, 0xF8508371, 0x328B0B29, 0x2CBCB9DA, 0x2918B9C6, + 0x944C50BA, 0xF1DCE7D0, 0x640C3966, 0xC90B3D08, 0xF4AD17BA, 0x6CA0F84B, + 0xF7767C67, 0xA4D3A55A, 0x4A085C6A, 0x6BB27071, 0xFA8B38FB, 0x3FDB31B8, + 0x8B7196F2, 0xDB9BED4A, 0x51625B84, 0x4C1481B4, 0xF684F508, 0x30B44770, + 0x93AA8E74, 0x90C579BC, 0x246EC88D, 0x2E051202, 0xC774842E, 0xA185D997, + 0x7A2B3ADD, 0xFE835B6D, 0x508F184D, 0xEB4C4F13, 0x0E1993D3, 0xBA96DFD2}; +u32 g_key_INDEXDAT1xx[] = { + 0x76CB00AF, 0x111CE62F, 0xB7B27E36, 0x6D8DE8F9, 0xD54BF16A, 0xD9E90373, + 0x7599D982, 0x51F82B0E, 0x636103AD, 0x8E40BC35, 0x2F332C94, 0xF513AAE9, + 0xD22AFEE9, 0x04343987, 0xFC5BB80C, 0x12349D89, 0x14A481BB, 0x25ED3AE8, + 0x7D500E4F, 0x43D1B757, 0x7B59FDAD, 0x4CFBBF34, 0xC3D17436, 0xC1DA21DB, + 0xA34D8C80, 0x962B235D, 0x3E420548, 0x09CF9FFE, 0xD4883F5C, 0xD90E9CB5, + 0x00AEF4E9, 0xF0886DE9, 0x62A58A5B, 0x52A55546, 0x971941B5, 0xF5B79FAC}; + +typedef struct +{ + u32 tag; // 4 byte value at offset 0xD0 in the PRX file + u32* key; // "step1_result" use for XOR step + u8 code; + u8 codeExtra; +} TAG_INFO; + +static const TAG_INFO g_tagInfo[] = +{ + { 0x00000000, g_key0, 0x42 }, + { 0x02000000, g_key2, 0x45 }, + { 0x03000000, g_key3, 0x46 }, + { 0x4467415d, g_key44, 0x59, 0x59 }, + { 0x207bbf2f, g_key20, 0x5A, 0x5A }, + { 0x3ace4dce, g_key3A, 0x5B, 0x5B }, + { 0x07000000, g_key_INDEXDAT1xx, 0x4A }, + { 0x08000000, g_keyEBOOT1xx, 0x4B }, + { 0xC0CB167C, g_keyEBOOT2xx, 0x5D, 0x5D }, + { 0x0B000000, g_keyUPDATER, 0x4E }, + { 0x0C000000, g_keyDEMOS27X, 0x4F }, + { 0x0F000000, g_keyMEIMG250, 0x52 }, + { 0x862648D1, g_keyMEIMG260, 0x52, 0x52 }, + { 0x207BBF2F, g_keyUNK1, 0x5A, 0x5A }, + { 0x09000000, g_key_GAMESHARE1xx, 0x4C }, + { 0xBB67C59F, g_key_GAMESHARE2xx, 0x5E, 0x5E } +}; + +static TAG_INFO const* GetTagInfo(u32 tagFind) +{ + for (u32 iTag = 0; iTag < sizeof(g_tagInfo)/sizeof(TAG_INFO); iTag++) + if (g_tagInfo[iTag].tag == tagFind) + return &g_tagInfo[iTag]; + return NULL; // not found +} + +static void ExtraV2Mangle(u8* buffer1, u8 codeExtra) +{ +#ifdef _MSC_VER + static u8 __declspec(align(64)) g_dataTmp[20+0xA0]; +#else + static u8 g_dataTmp[20+0xA0] __attribute__((aligned(0x40))); +#endif + u8* buffer2 = g_dataTmp; // aligned + + memcpy(buffer2+20, buffer1, 0xA0); + u32* pl2 = (u32*)buffer2; + pl2[0] = 5; + pl2[1] = pl2[2] = 0; + pl2[3] = codeExtra; + pl2[4] = 0xA0; + + sceUtilsBufferCopyWithRange(buffer2, 20+0xA0, buffer2, 20+0xA0, 7); + // copy result back + memcpy(buffer1, buffer2, 0xA0); +} + +static int Scramble(u32 *buf, u32 size, u32 code) +{ + buf[0] = 5; + buf[1] = buf[2] = 0; + buf[3] = code; + buf[4] = size; + + if (sceUtilsBufferCopyWithRange((u8*)buf, size+0x14, (u8*)buf, size+0x14, 7) < 0) + { + return -1; + } + + return 0; +} + +static int DecryptPRX1(const u8* pbIn, u8* pbOut, int cbTotal, u32 tag) +{ + int i, retsize; + u8 bD0[0x80], b80[0x50], b00[0x80], bB0[0x20]; + + TAG_INFO const* pti = GetTagInfo(tag); + if (pti == NULL) + { + return -1; + } + + retsize = *(u32*)&pbIn[0xB0]; + + for (i = 0; i < 0x14; i++) + { + if (pti->key[i] != 0) + break; + } + + if (i == 0x14) + { + Scramble(pti->key, 0x90, pti->code); + } + + // build conversion into pbOut + + if (pbIn != pbOut) + memcpy(pbOut, pbIn, cbTotal); + + memcpy(bD0, pbIn+0xD0, 0x80); + memcpy(b80, pbIn+0x80, 0x50); + memcpy(b00, pbIn+0x00, 0x80); + memcpy(bB0, pbIn+0xB0, 0x20); + + memset(pbOut, 0, 0x150); + memset(pbOut, 0x55, 0x40); // first $40 bytes ignored + + // step3 demangle in place + u32* pl = (u32*)(pbOut+0x2C); + pl[0] = 5; // number of ulongs in the header + pl[1] = pl[2] = 0; + pl[3] = pti->code; // initial seed for PRX + pl[4] = 0x70; // size + + // redo part of the SIG check (step2) + u8 buffer1[0x150]; + memcpy(buffer1+0x00, bD0, 0x80); + memcpy(buffer1+0x80, b80, 0x50); + memcpy(buffer1+0xD0, b00, 0x80); + if (pti->codeExtra != 0) + ExtraV2Mangle(buffer1+0x10, pti->codeExtra); + memcpy(pbOut+0x40, buffer1+0x40, 0x40); + + int ret; + int iXOR; + for (iXOR = 0; iXOR < 0x70; iXOR++) + pbOut[0x40+iXOR] = pbOut[0x40+iXOR] ^ ((u8*)pti->key)[0x14+iXOR]; + + ret = sceUtilsBufferCopyWithRange(pbOut+0x2C, 20+0x70, pbOut+0x2C, 20+0x70, 7); + if (ret != 0) + { + return -1; + } + + for (iXOR = 0x6F; iXOR >= 0; iXOR--) + pbOut[0x40+iXOR] = pbOut[0x2C+iXOR] ^ ((u8*)pti->key)[0x20+iXOR]; + + memset(pbOut+0x80, 0, 0x30); // $40 bytes kept, clean up + pbOut[0xA0] = 1; + // copy unscrambled parts from header + memcpy(pbOut+0xB0, bB0, 0x20); // file size + lots of zeros + memcpy(pbOut+0xD0, b00, 0x80); // ~PSP header + + // step4: do the actual decryption of code block + // point 0x40 bytes into the buffer to key info + ret = sceUtilsBufferCopyWithRange(pbOut, cbTotal, pbOut+0x40, cbTotal-0x40, 0x1); + if (ret != 0) + { + return -1; + } + + // return cbTotal - 0x150; // rounded up size + return retsize; +} + +////////// Decryption 2 ////////// + +typedef struct +{ + u32 tag; // 4 byte value at offset 0xD0 in the PRX file + u8 *key; // 16 bytes keys + u8 code; // code for scramble + u8 type; +} TAG_INFO2; + +static TAG_INFO2 g_tagInfo2[] = +{ + { 0x4C9494F0, keys660_k1, 0x43 }, + { 0x4C9495F0, keys660_k2, 0x43 }, + { 0x4C9490F0, keys660_k3, 0x43 }, + { 0x4C9491F0, keys660_k8, 0x43 }, + { 0x4C9493F0, keys660_k4, 0x43 }, + { 0x4C9497F0, keys660_k5, 0x43 }, + { 0x4C9492F0, keys660_k6, 0x43 }, + { 0x4C9496F0, keys660_k7, 0x43 }, + { 0x457B90F0, keys660_v1, 0x5B }, + { 0x457B91F0, keys660_v7, 0x5B }, + { 0x457B92F0, keys660_v6, 0x5B }, + { 0x457B93F0, keys660_v3, 0x5B }, + { 0x380290F0, keys660_v2, 0x5A }, + { 0x380291F0, keys660_v8, 0x5A }, + { 0x380292F0, keys660_v4, 0x5A }, + { 0x380293F0, keys660_v5, 0x5A }, + { 0x4C948CF0, keys639_k3, 0x43 }, + { 0x4C948DF0, keys638_k4, 0x43 }, + { 0x4C948BF0, keys636_k2, 0x43 }, + { 0x4C948AF0, keys636_k1, 0x43 }, + { 0x4C9487F0, keys630_k8, 0x43 }, + { 0x457B83F0, keys630_k7, 0x5B }, + { 0x4C9486F0, keys630_k6, 0x43 }, + { 0x457B82F0, keys630_k5, 0x5B }, + { 0x457B81F0, keys630_k4, 0x5B }, + { 0x4C9485F0, keys630_k3, 0x43 }, + { 0x457B80F0, keys630_k2, 0x5B }, + { 0x4C9484F0, keys630_k1, 0x43 }, + { 0x457B28F0, keys620_e, 0x5B }, + { 0x457B0CF0, keys620_a, 0x5B }, + { 0x380228F0, keys620_5v, 0x5A }, + { 0x4C942AF0, keys620_5k, 0x43 }, + { 0x4C9428F0, keys620_5, 0x43 }, + { 0x4C941DF0, keys620_1, 0x43 }, + { 0x4C941CF0, keys620_0, 0x43 }, + { 0x4C9422F0, keys600_2, 0x43 }, + { 0x4C941EF0, keys600_1, 0x43 }, + { 0x4C9429F0, keys570_5k, 0x43 }, + { 0x457B0BF0, keys505_a, 0x5B }, + { 0x4C9419F0, keys505_1, 0x43 }, + { 0x4C9418F0, keys505_0, 0x43 }, + { 0x457B1EF0, keys500_c, 0x5B }, + { 0x4C941FF0, keys500_2, 0x43 }, + { 0x4C9417F0, keys500_1, 0x43 }, + { 0x4C9416F0, keys500_0, 0x43 }, + { 0x4C9414F0, keys390_0, 0x43 }, + { 0x4C9415F0, keys390_1, 0x43 }, + { 0x4C9412F0, keys370_0, 0x43 }, + { 0x4C9413F0, keys370_1, 0x43 }, + { 0x457B10F0, keys370_2, 0x5B }, + { 0x4C940DF0, keys360_0, 0x43 }, + { 0x4C9410F0, keys360_1, 0x43 }, + { 0x4C940BF0, keys330_0, 0x43 }, + { 0x457B0AF0, keys330_1, 0x5B }, + { 0x38020AF0, keys330_2, 0x5A }, + { 0x4C940AF0, keys330_3, 0x43 }, + { 0x4C940CF0, keys330_4, 0x43 }, + { 0xcfef09f0, keys310_0, 0x62 }, + { 0x457b08f0, keys310_1, 0x5B }, + { 0x380208F0, keys310_2, 0x5A }, + { 0xcfef08f0, keys310_3, 0x62 }, + { 0xCFEF07F0, keys303_0, 0x62 }, + { 0xCFEF06F0, keys300_0, 0x62 }, + { 0x457B06F0, keys300_1, 0x5B }, + { 0x380206F0, keys300_2, 0x5A }, + { 0xCFEF05F0, keys280_0, 0x62 }, + { 0x457B05F0, keys280_1, 0x5B }, + { 0x380205F0, keys280_2, 0x5A }, + { 0x16D59E03, keys260_0, 0x62 }, + { 0x76202403, keys260_1, 0x5B }, + { 0x0F037303, keys260_2, 0x5A }, + { 0x4C940FF0, key_2DA8, 0x43 }, + { 0x4467415D, key_22E0, 0x59 }, + { 0x00000000, key_21C0, 0x42 }, + { 0x01000000, key_2250, 0x43 }, + { 0x2E5E10F0, key_2E5E10F0, 0x48 }, + { 0x2E5E12F0, key_2E5E12F0, 0x48 }, + { 0x2E5E13F0, key_2E5E13F0, 0x48 }, + { 0x2FD30BF0, key_2FD30BF0, 0x47 }, + { 0x2FD311F0, key_2FD311F0, 0x47 }, + { 0x2FD312F0, key_2FD312F0, 0x47 }, + { 0xD91605F0, key_D91605F0, 0x5D }, + { 0xD91606F0, key_D91606F0, 0x5D }, + { 0xD91608F0, key_D91608F0, 0x5D }, + { 0xD91609F0, key_D91609F0, 0x5D }, + { 0xD9160AF0, key_D9160AF0, 0x5D }, + { 0xD9160BF0, key_D9160BF0, 0x5D }, + { 0xD91611F0, key_D91611F0, 0x5D }, + { 0xD91612F0, key_D91612F0, 0x5D }, + { 0xD91613F0, key_D91613F0, 0x5D }, + { 0xD91614F0, key_D91614F0, 0x5D }, + { 0xD91615F0, key_D91615F0, 0x5D }, + { 0xD91616F0, key_D91616F0, 0x5D }, + { 0xD91617F0, key_D91617F0, 0x5D }, + { 0xD91618F0, key_D91618F0, 0x5D }, + { 0xD91619F0, key_D91619F0, 0x5D }, + { 0xD9161AF0, key_D9161AF0, 0x5D }, + { 0xD91620F0, key_D91620F0, 0x5D }, + { 0xD91621F0, key_D91621F0, 0x5D }, + { 0xD91622F0, key_D91622F0, 0x5D }, + { 0xD91623F0, key_D91623F0, 0x5D }, + { 0xD91624F0, key_D91624F0, 0x5D }, + { 0xD91628F0, key_D91628F0, 0x5D }, + { 0xD91680F0, key_D91680F0, 0x5D }, + { 0xD91681F0, key_D91681F0, 0x5D }, + { 0xD82310F0, keys02G_E, 0x51 }, + { 0xD8231EF0, keys03G_E, 0x51 }, + { 0xD82328F0, keys05G_E, 0x51 }, + { 0x279D08F0, oneseg_310, 0x61 }, + { 0x279D06F0, oneseg_300, 0x61 }, + { 0x279D05F0, oneseg_280, 0x61 }, + { 0xD66DF703, oneseg_260_271, 0x61 }, + { 0x279D10F0, oneseg_slim, 0x61 }, + { 0x3C2A08F0, ms_app_main, 0x67 }, + { 0xADF305F0, demokeys_280, 0x60 }, + { 0xADF306F0, demokeys_3XX_1, 0x60 }, + { 0xADF308F0, demokeys_3XX_2, 0x60 }, + { 0x8004FD03, ebootbin_271_new, 0x5D }, + { 0xD91605F0, ebootbin_280_new, 0x5D }, + { 0xD91606F0, ebootbin_300_new, 0x5D }, + { 0xD91608F0, ebootbin_310_new, 0x5D }, + { 0x0A35EA03, gameshare_260_271, 0x5E }, + { 0x7B0505F0, gameshare_280, 0x5E }, + { 0x7B0506F0, gameshare_300, 0x5E }, + { 0x7B0508F0, gameshare_310, 0x5E }, + { 0x380210F0, key_380210F0, 0x5A }, + { 0x380280F0, key_380280F0, 0x5A }, + { 0x380283F0, key_380283F0, 0x5A }, + { 0x407810F0, key_407810F0, 0x6A }, + { 0xE92410F0, drmkeys_6XX_1, 0x40 }, + { 0x692810F0, drmkeys_6XX_2, 0x40 } +}; + + +static TAG_INFO2 *GetTagInfo2(u32 tagFind) +{ + for (u32 iTag = 0; iTag < sizeof(g_tagInfo2) / sizeof(TAG_INFO2); iTag++) + { + if (g_tagInfo2[iTag].tag == tagFind) + { + return &g_tagInfo2[iTag]; + } + } + + return NULL; // not found +} + +// Moving these out here is a really ugly hack to avoid a stack corruption warning, warranted or not +static u8 padding1[0x100]; +static u8 tmp1[0x150], tmp2[0x90+0x14], tmp3[0x60+0x14], tmp4[0x20]; +static u8 padding2[0x100]; + +static int DecryptPRX2(const u8 *inbuf, u8 *outbuf, u32 size, u32 tag) +{ + TAG_INFO2 * pti = GetTagInfo2(tag); + + if (!pti) + { + return -1; + } + + int retsize = *(int *)&inbuf[0xB0]; + + memset(tmp1, 0, 0x150); + memset(tmp2, 0, 0x90+0x14); + memset(tmp3, 0, 0x60+0x14); + memset(tmp4, 0, 0x20); + + if (inbuf != outbuf) + memcpy(outbuf, inbuf, size); + + if (size < 0x160) + { + return -2; + } + + if ((size - 0x150) < retsize) + { + return -4; + } + + memcpy(tmp1, outbuf, 0x150); + + int i, j; + u8 *p = tmp2+0x14; + + for (i = 0; i < 9; i++) + { + for (j = 0; j < 0x10; j++) + { + p[(i << 4) + j] = pti->key[j]; + + } + + p[(i << 4)] = i; + } + + if (Scramble((u32 *)tmp2, 0x90, pti->code) < 0) + { + return -5; + } + + memcpy(outbuf, tmp1+0xD0, 0x5C); + memcpy(outbuf+0x5C, tmp1+0x140, 0x10); + memcpy(outbuf+0x6C, tmp1+0x12C, 0x14); + memcpy(outbuf+0x80, tmp1+0x080, 0x30); + memcpy(outbuf+0xB0, tmp1+0x0C0, 0x10); + memcpy(outbuf+0xC0, tmp1+0x0B0, 0x10); + memcpy(outbuf+0xD0, tmp1+0x000, 0x80); + + memcpy(tmp3+0x14, outbuf+0x5C, 0x60); + + if (Scramble((u32 *)tmp3, 0x60, pti->code) < 0) + { + return -6; + } + + memcpy(outbuf+0x5C, tmp3, 0x60); + memcpy(tmp3, outbuf+0x6C, 0x14); + memcpy(outbuf+0x70, outbuf+0x5C, 0x10); + + if(pti->type == 3) + { + memcpy(tmp4, outbuf+0x3C, 0x20); + memcpy(outbuf+0x50, tmp4, 0x20); + memset(outbuf+0x18, 0, 0x38); + }else + memset(outbuf+0x18, 0, 0x58); + + memcpy(outbuf+0x04, outbuf, 0x04); + *((u32 *)outbuf) = 0x014C; + memcpy(outbuf+0x08, tmp2, 0x10); + + /* sha-1 */ + + if (sceUtilsBufferCopyWithRange(outbuf, 3000000, outbuf, 3000000, 0x0B) != 0) + { + return -7; + } + + if (memcmp(outbuf, tmp3, 0x14) != 0) + { + return -8; + } + + int iXOR; + + for (iXOR = 0; iXOR < 0x40; iXOR++) + { + tmp3[iXOR+0x14] = outbuf[iXOR+0x80] ^ tmp2[iXOR+0x10]; + } + + if (Scramble((u32 *)tmp3, 0x40, pti->code) != 0) + { + return -9; + } + + for (iXOR = 0x3F; iXOR >= 0; iXOR--) + { + outbuf[iXOR+0x40] = tmp3[iXOR] ^ tmp2[iXOR+0x50]; // uns 8 + } + + if (pti->type == 3) + { + memcpy(outbuf+0x80, tmp4, 0x20); + memset(outbuf+0xA0, 0, 0x10); + *(u32*)&outbuf[0xA4] = 1; + *(u32*)&outbuf[0xA0] = 1; + } + else + { + memset(outbuf+0x80, 0, 0x30); + *(u32*)&outbuf[0xA0] = 1; + } + + memcpy(outbuf+0xB0, outbuf+0xC0, 0x10); + memset(outbuf+0xC0, 0, 0x10); + memcpy(outbuf+0xD0, outbuf+0xD0, 0x80); + + // The real decryption + if (sceUtilsBufferCopyWithRange(outbuf, size, outbuf+0x40, size-0x40, 0x1) != 0) + { + return -1; + } + + if (retsize < 0x150) + { + // Fill with 0 + memset(outbuf+retsize, 0, 0x150-retsize); + } + + return retsize; +} + +int pspDecryptPRX(const u8 *inbuf, u8 *outbuf, u32 size) +{ + kirk_init(); + int retsize = DecryptPRX1(inbuf, outbuf, size, *(u32 *)&inbuf[0xD0]); + + if (retsize <= 0) + { + retsize = DecryptPRX2(inbuf, outbuf, size, *(u32 *)&inbuf[0xD0]); + } + + return retsize; +} + diff --git a/Core/ELF/PrxDecrypter.h b/Core/ELF/PrxDecrypter.h new file mode 100644 index 0000000000..23cbedbc1a --- /dev/null +++ b/Core/ELF/PrxDecrypter.h @@ -0,0 +1,67 @@ +// Copyright (c) 2012- PPSSPP Project. + +// 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, version 2.0. + +// 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 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "../../Globals.h" + +#ifdef _MSC_VER +#pragma pack(push, 1) +#endif +typedef struct +{ + u32 signature; // 0 + u16 attribute; // 4 modinfo + u16 comp_attribute; // 6 + u8 module_ver_lo; // 8 + u8 module_ver_hi; // 9 + char modname[28]; // 0A + u8 version; // 26 + u8 nsegments; // 27 + u32 elf_size; // 28 + u32 psp_size; // 2C + u32 entry; // 30 + u32 modinfo_offset; // 34 + int bss_size; // 38 + u16 seg_align[4]; // 3C + u32 seg_address[4]; // 44 + int seg_size[4]; // 54 + u32 reserved[5]; // 64 + u32 devkitversion; // 78 + u32 decrypt_mode; // 7C + u8 key_data0[0x30]; // 80 + int comp_size; // B0 + int _80; // B4 + int reserved2[2]; // B8 + u8 key_data1[0x10]; // C0 + u32 tag; // D0 + u8 scheck[0x58]; // D4 + u32 key_data2; // 12C + u32 oe_tag; // 130 + u8 key_data3[0x1C]; // 134 +#ifdef _MSC_VER +} PSP_Header; +#else +} __attribute__((packed)) PSP_Header; +#endif + +#ifdef _MSC_VER +#pragma pack(pop) +#endif + +int pspDecryptPRX(const u8 *inbuf, u8 *outbuf, u32 size); + diff --git a/Core/FileSystems/BlockDevices.cpp b/Core/FileSystems/BlockDevices.cpp index 01bbff2364..cd743741f5 100644 --- a/Core/FileSystems/BlockDevices.cpp +++ b/Core/FileSystems/BlockDevices.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/FileSystems/BlockDevices.h b/Core/FileSystems/BlockDevices.h index 9272c88a7a..626c11e6ed 100644 --- a/Core/FileSystems/BlockDevices.h +++ b/Core/FileSystems/BlockDevices.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/FileSystems/DirectoryFileSystem.cpp b/Core/FileSystems/DirectoryFileSystem.cpp index 074572b669..d1a4e02091 100644 --- a/Core/FileSystems/DirectoryFileSystem.cpp +++ b/Core/FileSystems/DirectoryFileSystem.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -32,6 +32,9 @@ DirectoryFileSystem::DirectoryFileSystem(IHandleAllocator *_hAlloc, std::string std::string DirectoryFileSystem::GetLocalPath(std::string localpath) { + if (localpath.empty()) + return basePath; + if (localpath[0] == '/') localpath.erase(0,1); //Convert slashes @@ -81,7 +84,7 @@ bool DirectoryFileSystem::DeleteFile(const std::string &filename) u32 DirectoryFileSystem::OpenFile(std::string filename, FileAccess access) { std::string fullName = GetLocalPath(filename); - INFO_LOG(HLE,"Actually opening %s",fullName.c_str()); + INFO_LOG(HLE,"Actually opening %s (%s)", fullName.c_str(), filename.c_str()); OpenFileEntry entry; @@ -237,9 +240,15 @@ size_t DirectoryFileSystem::SeekFile(u32 handle, s32 position, FileMove type) PSPFileInfo DirectoryFileSystem::GetFileInfo(std::string filename) { PSPFileInfo x; - x.size=0; + x.name = filename; + std::string fullName = GetLocalPath(filename); + if (!File::Exists(fullName)) { + return x; + } + x.type = File::IsDirectory(fullName) ? FILETYPE_NORMAL : FILETYPE_DIRECTORY; + x.exists = true; #ifdef _WIN32 @@ -280,7 +289,10 @@ std::vector DirectoryFileSystem::GetDirListing(std::string path) else entry.type = FILETYPE_NORMAL; - entry.size = findData.nFileSizeLow | ((u64)findData.nFileSizeHigh<<32); + if (!strcmp(findData.cFileName, "..") )// TODO: is this just for .. or all sub directories? Need to add a directory to the test to find out. Also why so different than the old test results? + entry.size = 4096; + else + entry.size = findData.nFileSizeLow | ((u64)findData.nFileSizeHigh<<32); entry.name = findData.cFileName; myVector.push_back(entry); diff --git a/Core/FileSystems/DirectoryFileSystem.h b/Core/FileSystems/DirectoryFileSystem.h index d18e0cdc7d..e0598cbde7 100644 --- a/Core/FileSystems/DirectoryFileSystem.h +++ b/Core/FileSystems/DirectoryFileSystem.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/FileSystems/FileSystem.h b/Core/FileSystems/FileSystem.h index 9b5ce794a5..8024461d1c 100644 --- a/Core/FileSystems/FileSystem.h +++ b/Core/FileSystems/FileSystem.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -53,10 +53,13 @@ public: struct PSPFileInfo { - PSPFileInfo() {size=0;access=0;type=FILETYPE_NORMAL;isOnSectorSystem=false;} + PSPFileInfo() + : size(0), access(0), exists(false), type(FILETYPE_NORMAL), isOnSectorSystem(false), startSector(0), numSectors(0) {} + std::string name; s64 size; u32 access; //unix 777 + bool exists; FileType type; bool isOnSectorSystem; diff --git a/Core/FileSystems/ISOFileSystem.cpp b/Core/FileSystems/ISOFileSystem.cpp index 976b3ddfa6..32b2a159cc 100644 --- a/Core/FileSystems/ISOFileSystem.cpp +++ b/Core/FileSystems/ISOFileSystem.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -23,6 +23,18 @@ const int sectorSize = 2048; +static bool parseLBN(std::string filename, u32 *sectorStart, u32 *readSize) +{ + if (filename.substr(0, 8) != "/sce_lbn") + return false; + std::string yo = filename; + filename.erase(0, 10); + sscanf(filename.c_str(), "%08x", sectorStart); + filename.erase(0, filename.find("_size") + 7); + sscanf(filename.c_str(), "%08x", readSize); + return true; +} + #pragma pack(push) #pragma pack(1) struct DirectoryEntry @@ -175,10 +187,18 @@ nextblock: name[i] = buffer[33+i] ? buffer[33+i] : '.'; name[fnLength] = '\0'; + bool relative = false; + if (!strcmp(name, ".")) // "." record - continue; + { + relative = true; + } + if (strlen(name) == 1 && name[0] == '\x01') // ".." record - continue; + { + strcpy(name,".."); + relative=true; + } TreeEntry *e = new TreeEntry; e->name = name; @@ -190,7 +210,7 @@ nextblock: DEBUG_LOG(FILESYS, "%s: %s %08x %08x %i", e->isDirectory?"D":"F", name, dir.firstDataSectorLE, e->startingPosition, e->startingPosition); - if (e->isDirectory) + if (e->isDirectory && !relative) { if (dir.firstDataSectorLE == startsector) { @@ -214,6 +234,9 @@ ISOFileSystem::TreeEntry *ISOFileSystem::GetFromPath(std::string path) return &entireISO; } + if (path.substr(0,2) == "./") + path.erase(0,2); + if (path[0] == '/') path.erase(0,1); @@ -230,7 +253,8 @@ ISOFileSystem::TreeEntry *ISOFileSystem::GetFromPath(std::string path) for (size_t i=0; ichildren.size(); i++) { std::string n = e->children[i]->name; - if (path.compare(0, n.length(), n) == 0) //TODO : bad + std::string curPath = path.substr(0, path.find_first_of('/')); + if (curPath == n) { //yay we got it ne = e->children[i]; @@ -247,6 +271,8 @@ ISOFileSystem::TreeEntry *ISOFileSystem::GetFromPath(std::string path) if (path.length() == 0 || (path.length()==1 && path[0] == '/')) return e; path.erase(0, 1); + while (path[0] == '/') + path.erase(0, 1); } else { @@ -258,16 +284,22 @@ ISOFileSystem::TreeEntry *ISOFileSystem::GetFromPath(std::string path) u32 ISOFileSystem::OpenFile(std::string filename, FileAccess access) { + // LBN unittest + /* + u32 a, b; + if (parseLBN("/sce_lbn0x307aa_size0xefffe000", &a, &b)) { + ERROR_LOG(FILESYS, "lbn: %08x %08x", a, b); + } else { + ERROR_LOG(FILESYS, "faillbn: %08x %08x", a, b); + }*/ + + OpenFileEntry entry; if (filename.compare(0,8,"/sce_lbn") == 0) { - std::string yo = filename; - filename.erase(0,10); u32 sectorStart = 0xFFFFFFFF, readSize = 0xFFFFFFFF; - sscanf(filename.c_str(), "%08x", §orStart); - filename.erase(0,filename.find('_') + 5); - sscanf(filename.c_str(), "%08x", &readSize); - INFO_LOG(FILESYS, "Got a raw sector read %s, sector %08x, size %08x", yo.c_str(), sectorStart, readSize); + parseLBN(filename, §orStart, &readSize); + INFO_LOG(FILESYS, "Got a raw sector open: %s, sector %08x, size %08x", filename.c_str(), sectorStart, readSize); u32 newHandle = hAlloc->GetNewHandle(); entry.seekPos = 0; entry.file = 0; @@ -335,16 +367,18 @@ size_t ISOFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size) blockDevice->ReadBlock(e.seekPos, pointer + i * 2048); e.seekPos++; } - return size; + return (size_t)size; } - u32 position; + u32 positionOnIso; if (e.isRawSector) { - position = e.sectorStart; - if (position + size > e.sectorStart + e.openSize) + // TODO: this seems bogus + positionOnIso = e.sectorStart * 2048; + + if (e.seekPos + size > e.openSize) { - size = e.sectorStart + e.openSize - position; + size = e.openSize - e.seekPos; } } else @@ -355,13 +389,13 @@ size_t ISOFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size) size = e.file->size - (s64)e.seekPos; } - position = e.file->startingPosition + e.seekPos; + positionOnIso = e.file->startingPosition + e.seekPos; } //okay, we have size and position, let's rock u32 totalRead = 0; - int secNum = position / 2048; - int posInSector = position & 2047; + int secNum = positionOnIso / 2048; + int posInSector = positionOnIso & 2047; s64 remain = size; u8 theSector[2048]; @@ -369,7 +403,7 @@ size_t ISOFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size) while (remain > 0) { blockDevice->ReadBlock(secNum, theSector); - size_t bytesToCopy = 2048-posInSector; + size_t bytesToCopy = 2048 - posInSector; if ((s64)bytesToCopy > remain) bytesToCopy = (size_t)remain; @@ -380,7 +414,7 @@ size_t ISOFileSystem::ReadFile(u32 handle, u8 *pointer, s64 size) posInSector = 0; secNum++; } - e.seekPos += size; + e.seekPos += (unsigned int)size; return totalRead; } else @@ -415,7 +449,7 @@ size_t ISOFileSystem::SeekFile(u32 handle, s32 position, FileMove type) if (e.isRawSector) e.seekPos = e.openSize; else - e.seekPos = e.file->size + position; + e.seekPos = (unsigned int)(e.file->size + position); break; } return (size_t)e.seekPos; @@ -430,17 +464,34 @@ size_t ISOFileSystem::SeekFile(u32 handle, s32 position, FileMove type) PSPFileInfo ISOFileSystem::GetFileInfo(std::string filename) { + if (filename.compare(0,8,"/sce_lbn") == 0) + { + u32 sectorStart = 0xFFFFFFFF, readSize = 0xFFFFFFFF; + parseLBN(filename, §orStart, &readSize); + + PSPFileInfo fileInfo; + fileInfo.name = filename; + fileInfo.exists = true; + fileInfo.size = readSize; + fileInfo.startSector = sectorStart; + fileInfo.isOnSectorSystem = true; + fileInfo.numSectors = (readSize + sectorSize - 1) / sectorSize; + return fileInfo; + } + TreeEntry *entry = GetFromPath(filename); PSPFileInfo x; if (!entry) { - x.size=0; + x.size = 0; + x.exists = false; } else { x.name = entry->name; x.access = FILEACCESS_READ; x.size = entry->size; + x.exists = true; x.type = entry->isDirectory ? FILETYPE_DIRECTORY : FILETYPE_NORMAL; x.isOnSectorSystem = true; x.startSector = entry->startingPosition/2048; @@ -457,18 +508,13 @@ std::vector ISOFileSystem::GetDirListing(std::string path) return myVector; } - // fake the . and .. - PSPFileInfo x; - x.type = FILETYPE_DIRECTORY; - x.name = "."; - x.isOnSectorSystem = true; - myVector.push_back(x); - x.name = ".."; - myVector.push_back(x); - for (size_t i=0; ichildren.size(); i++) { TreeEntry *e = entry->children[i]; + + if(!strcmp(e->name.c_str(), ".") || !strcmp(e->name.c_str(), "..")) // do not include the relative entries in the list + continue; + PSPFileInfo x; x.name = e->name; x.access = FILEACCESS_READ; diff --git a/Core/FileSystems/ISOFileSystem.h b/Core/FileSystems/ISOFileSystem.h index f14ca30fe6..530e152145 100644 --- a/Core/FileSystems/ISOFileSystem.h +++ b/Core/FileSystems/ISOFileSystem.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/FileSystems/MetaFileSystem.cpp b/Core/FileSystems/MetaFileSystem.cpp index fc3f3afa45..3427ceef4b 100644 --- a/Core/FileSystems/MetaFileSystem.cpp +++ b/Core/FileSystems/MetaFileSystem.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,6 +31,11 @@ IFileSystem *MetaFileSystem::GetHandleOwner(u32 handle) bool MetaFileSystem::MapFilePath(std::string inpath, std::string &outpath, IFileSystem **system) { + // host0 HACK + // need to figure out what to do about xxx:./... paths - is there a current dir per drive? + if (!inpath.compare(0, 8, "host0:./")) + inpath = currentDirectory + inpath.substr(7); + for (size_t i = 0; i < fileSystems.size(); i++) { int prefLen = fileSystems[i].prefix.size(); @@ -94,6 +99,11 @@ u32 MetaFileSystem::OpenFile(std::string filename, FileAccess access) PSPFileInfo MetaFileSystem::GetFileInfo(std::string filename) { std::string of; + if (filename.find(':') == std::string::npos) + { + filename = currentDirectory + "/" + filename; + DEBUG_LOG(HLE,"GetFileInfo: Expanded path to %s", filename.c_str()); + } IFileSystem *system; if (MapFilePath(filename, of, &system)) { @@ -109,6 +119,11 @@ PSPFileInfo MetaFileSystem::GetFileInfo(std::string filename) std::vector MetaFileSystem::GetDirListing(std::string path) { std::string of; + if (path.find(':') == std::string::npos) + { + path = currentDirectory + "/" + path; + DEBUG_LOG(HLE,"GetFileInfo: Expanded path to %s", path.c_str()); + } IFileSystem *system; if (MapFilePath(path, of, &system)) { diff --git a/Core/FileSystems/MetaFileSystem.h b/Core/FileSystems/MetaFileSystem.h index 8c9ef705aa..35ed0e55b5 100644 --- a/Core/FileSystems/MetaFileSystem.h +++ b/Core/FileSystems/MetaFileSystem.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/FunctionWrappers.h b/Core/HLE/FunctionWrappers.h index 06f1e3bd02..423ad49792 100644 --- a/Core/HLE/FunctionWrappers.h +++ b/Core/HLE/FunctionWrappers.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -38,24 +38,96 @@ template void WrapU_U() { RETURN(retval); } +template void WrapI_U() { + int retval = func(PARAM(0)); + RETURN(retval); +} + +template void WrapI_V() { + int retval = func(); + RETURN(retval); +} + +template void WrapU_I() { + u32 retval = func(PARAM(0)); + RETURN(retval); +} + +template void WrapI_I() { + int retval = func(PARAM(0)); + RETURN(retval); +} + template void WrapV_U() { func(PARAM(0)); } +template void WrapV_I() { + func(PARAM(0)); +} + template void WrapV_UU() { func(PARAM(0), PARAM(1)); } +template void WrapV_II() { + func(PARAM(0), PARAM(1)); +} + template void WrapU_UU() { u32 retval = func(PARAM(0), PARAM(1)); RETURN(retval); } +template void WrapU_IU() { + int retval = func(PARAM(0), PARAM(1)); + RETURN(retval); +} + +template void WrapI_IU() { + int retval = func(PARAM(0), PARAM(1)); + RETURN(retval); +} + +template void WrapI_II() { + int retval = func(PARAM(0), PARAM(1)); + RETURN(retval); +} + +template void WrapI_III() { + int retval = func(PARAM(0), PARAM(1), PARAM(2)); + RETURN(retval); +} + +template void WrapI_IIU() { + int retval = func(PARAM(0), PARAM(1), PARAM(2)); + RETURN(retval); +} + +template void WrapV_IU() { + func(PARAM(0), PARAM(1)); +} + template void WrapI_CU() { + int retval = func(Memory::GetCharPointer(PARAM(0)), PARAM(1)); + RETURN(retval); +} + +template void WrapI_CUUU() { + int retval = func(Memory::GetCharPointer(PARAM(0)), PARAM(1), PARAM(2), PARAM(3)); + RETURN(retval); +} + +template void WrapU_CU() { int retval = func(Memory::GetCharPointer(PARAM(0)), PARAM(1)); RETURN((u32)retval); } +template void WrapU_UC() { + int retval = func(PARAM(0), Memory::GetCharPointer(PARAM(1))); + RETURN(retval); +} + template void WrapU_CUU() { int retval = func(Memory::GetCharPointer(PARAM(0)), PARAM(1), PARAM(2)); RETURN((u32)retval); @@ -66,20 +138,54 @@ template void WrapU_UUU() { RETURN(retval); } +template void WrapV_IUU() { + func(PARAM(0), PARAM(1), PARAM(2)); +} + +template void WrapV_IIU() { + func(PARAM(0), PARAM(1), PARAM(2)); +} + +template void WrapV_IUUUU() { + func(PARAM(0), PARAM(1), PARAM(2), PARAM(3), PARAM(4)); +} + template void WrapV_UUU() { func(PARAM(0), PARAM(1), PARAM(2)); } +template void WrapV_UUUU() { + func(PARAM(0), PARAM(1), PARAM(2), PARAM(3)); +} + +template void WrapV_CUIIU() { + func(Memory::GetCharPointer(PARAM(0)), PARAM(1), PARAM(2), PARAM(3), PARAM(4)); +} + template void WrapU_UUUU() { u32 retval = func(PARAM(0), PARAM(1), PARAM(2), PARAM(3)); RETURN(retval); } +template void WrapI_IUUUU() { + int retval = func(PARAM(0), PARAM(1), PARAM(2), PARAM(3), PARAM(4)); + RETURN(retval); +} + template void WrapU_UUUUU() { u32 retval = func(PARAM(0), PARAM(1), PARAM(2), PARAM(3), PARAM(4)); RETURN(retval); } +template void WrapV_UUUUU() { + func(PARAM(0), PARAM(1), PARAM(2), PARAM(3), PARAM(4)); +} + +template void WrapU_CIUIU() { + int retval = func(Memory::GetCharPointer(PARAM(0)), PARAM(1), PARAM(2), PARAM(3), PARAM(4)); + RETURN(retval); +} + template void WrapU_UUUUUU() { u32 retval = func(PARAM(0), PARAM(1), PARAM(2), PARAM(3), PARAM(4), PARAM(5)); RETURN(retval); diff --git a/Core/HLE/HLE.cpp b/Core/HLE/HLE.cpp index d8620d805d..5313b5a1f2 100644 --- a/Core/HLE/HLE.cpp +++ b/Core/HLE/HLE.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -28,6 +28,7 @@ #include "../MIPS/MIPSCodeUtils.h" static std::vector moduleDB; +static std::vector unresolvedSyscalls; void HLEInit() { @@ -39,32 +40,6 @@ void HLEShutdown() moduleDB.clear(); } -/* -//unused -struct PSPHeader -{ - char psp[4]; - u32 version; //00080000 - short whatever; //0101 - char sometext[28]; - short whatever2; //0102 - u32 filesizedecrypted; - u32 filesize; - u32 unknownoffsets[3]; - short whatever3[2]; //0x40 0x40 - u32 whatever4[2]; //00 - u32 whatever5; //1067008 - u32 whatever6[2]; //00 - u32 whatever7; //1067008 - u32 whatever8; //2553296 - u32 whatever9[8]; //0 - u32 whatever10; //12 - u32 encryptedStuff[12]; - u32 filesizedecrypted2; - u32 whatever11;//0x80 - u32 whatever12[6]; -};*/ - void RegisterModule(const char *name, int numFunctions, const HLEFunction *funcTable) { HLEModule module = {name, numFunctions, funcTable}; @@ -122,7 +97,7 @@ const char *GetFuncName(const char *moduleName, u32 nib) else { static char temp[256]; - sprintf(temp,"[UNK:%08x]",nib); + sprintf(temp,"[UNK: 0x%08x ]",nib); return temp; } } @@ -157,8 +132,36 @@ void WriteSyscall(const char *moduleName, u32 nib, u32 address) Memory::Write_U32(MIPS_MAKE_NOP(), address+4); //patched out? return; } - Memory::Write_U32(MIPS_MAKE_JR_RA(), address); // jr ra - Memory::Write_U32(GetSyscallOp(moduleName, nib), address + 4); + int modindex = GetModuleIndex(moduleName); + if (modindex != -1) + { + Memory::Write_U32(MIPS_MAKE_JR_RA(), address); // jr ra + Memory::Write_U32(GetSyscallOp(moduleName, nib), address + 4); + } + else + { + // Module inexistent.. for now; let's store the syscall for it to be resolved later + INFO_LOG(HLE,"Syscall (%s,%08x) unresolved, storing for later resolving", moduleName, nib); + Syscall sysc = {"", address, nib}; + strncpy(sysc.moduleName, moduleName, 32); + sysc.moduleName[31] = '\0'; + unresolvedSyscalls.push_back(sysc); + } +} + +void ResolveSyscall(const char *moduleName, u32 nib, u32 address) +{ + for (size_t i = 0; i < unresolvedSyscalls.size(); i++) + { + Syscall *sysc = &unresolvedSyscalls[i]; + if (strncmp(sysc->moduleName, moduleName, 32) == 0 && sysc->nid == nib) + { + INFO_LOG(HLE,"Resolving %s/%08x",moduleName,nib); + // Note: doing that, we can't trace external module calls, so maybe something else should be done to debug more efficiently + Memory::Write_U32(MIPS_MAKE_JAL(address), sysc->symAddr); + Memory::Write_U32(MIPS_MAKE_NOP(), sysc->symAddr + 4); + } + } } const char *GetFuncName(int moduleIndex, int func) @@ -195,4 +198,3 @@ void CallSyscall(u32 op) ERROR_LOG(HLE,"Unimplemented HLE function %s", moduleDB[modulenum].funcTable[funcnum].name); } } - diff --git a/Core/HLE/HLE.h b/Core/HLE/HLE.h index 4258605d4f..9305057b61 100644 --- a/Core/HLE/HLE.h +++ b/Core/HLE/HLE.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -25,11 +25,17 @@ typedef void (* HLEFunc)(); +enum { + NOT_IN_INTERRUPT, + NOT_DISPATCH_SUSPENDED, +}; + struct HLEFunction { u32 ID; HLEFunc func; const char *name; + u32 flags; }; struct HLEModule @@ -39,6 +45,13 @@ struct HLEModule const HLEFunction *funcTable; }; +struct Syscall +{ + char moduleName[32]; + u32 symAddr; + u32 nid; +}; + #define PARAM(n) currentMIPS->r[4+n] #define RETURN(n) currentMIPS->r[2]=n #define RETURNF(fl) currentMIPS->f[0]=fl @@ -67,6 +80,7 @@ u32 GetNibByName(const char *module, const char *function); u32 GetSyscallOp(const char *module, u32 nib); void WriteSyscall(const char *module, u32 nib, u32 address); void CallSyscall(u32 op); +void ResolveSyscall(const char *moduleName, u32 nib, u32 address); // Need to be able to save entire kernel state int GetStateSize(); diff --git a/Core/HLE/HLETables.cpp b/Core/HLE/HLETables.cpp index 2444cb44fe..d434d337ec 100644 --- a/Core/HLE/HLETables.cpp +++ b/Core/HLE/HLETables.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -28,6 +28,7 @@ #include "scePower.h" #include "sceNet.h" #include "sceMpeg.h" +#include "sceImpose.h" #include "sceGe.h" #include "scePsmf.h" #include "sceRtc.h" @@ -36,7 +37,6 @@ #include "sceDmac.h" #include "sceKernel.h" #include "sceKernelEventFlag.h" -#include "sceKernelCallback.h" #include "sceKernelMemory.h" #include "sceKernelInterrupt.h" #include "sceKernelModule.h" @@ -57,10 +57,10 @@ //zlibdec const HLEFunction FakeSysCalls[] = { - {NID_THREADRETURN, _sceKernelReturnFromThread, "_sceKernelReturnFromThread"}, - {NID_CALLBACKRETURN, _sceKernelReturnFromCallback, "_sceKernelReturnFromCallback"}, - {NID_INTERRUPTRETURN, _sceKernelReturnFromInterrupt, "_sceKernelReturnFromInterrupt"}, - {NID_IDLE, _sceKernelIdle, "_sceKernelIdle"}, + {NID_THREADRETURN, __KernelReturnFromThread, "__KernelReturnFromThread"}, + {NID_CALLBACKRETURN, __KernelReturnFromMipsCall, "__KernelReturnFromMipsCall"}, + {NID_INTERRUPTRETURN, __KernelReturnFromInterrupt, "__KernelReturnFromInterrupt"}, + {NID_IDLE, __KernelIdle, "_sceKernelIdle"}, }; const HLEFunction UtilsForUser[] = @@ -85,6 +85,7 @@ const HLEFunction UtilsForUser[] = {0xB435DEC5, sceKernelDcacheWritebackInvalidateAll, "sceKernelDcacheWritebackInvalidateAll"}, {0x3EE30821, sceKernelDcacheWritebackRange, "sceKernelDcacheWritebackRange"}, {0x34B9FA9E, sceKernelDcacheWritebackInvalidateRange, "sceKernelDcacheWritebackInvalidateRange"}, + {0xC2DF770E, 0, "sceKernelIcacheInvalidateRange"}, {0x80001C4C, 0, "sceKernelDcacheProbe"}, {0x16641D70, 0, "sceKernelDcacheReadTag"}, {0x4FD31C9D, 0, "sceKernelIcacheProbe"}, @@ -104,8 +105,8 @@ const HLEFunction sceRtc[] = {0x34885E0D, 0, "sceRtcConvertUtcToLocalTime"}, {0x779242A2, 0, "sceRtcConvertLocalTimeToUTC"}, {0x42307A17, 0, "sceRtcIsLeapYear"}, - {0x05ef322c, 0, "sceRtcGetDaysInMonth"}, - {0x57726bc1, 0, "sceRtcGetDayOfWeek"}, + {0x05ef322c, &WrapU_UU, "sceRtcGetDaysInMonth"}, + {0x57726bc1, &WrapU_UUU, "sceRtcGetDayOfWeek"}, {0x4B1B5E82, 0, "sceRtcCheckValid"}, {0x3a807cc8, 0, "sceRtcSetTime_t"}, {0x27c4594c, 0, "sceRtcGetTime_t"}, @@ -157,7 +158,7 @@ const HLEFunction LoadCoreForKernel[] = {0xB4D6FECC, 0, "sceKernelApplyElfRelSection"}, {0x54AB2675, 0, "LoadCoreForKernel_54AB2675"}, {0x2952F5AC, 0, "sceKernelDcacheWBinvAll"}, - {0xD8779AC6, 0, "sceKernelIcacheClearAll"}, + {0xD8779AC6, sceKernelIcacheClearAll, "sceKernelIcacheClearAll"}, {0x99A695F0, 0, "sceKernelRegisterLibrary"}, {0x5873A31F, 0, "sceKernelRegisterLibraryForUser"}, {0x0B464512, 0, "sceKernelReleaseLibrary"}, @@ -278,14 +279,6 @@ const HLEFunction sceUsbstorBoot[] = {0xA55C9E16, 0, "sceUsbstorBootUnregisterNotify"}, }; -//OSD stuff? home button? -const HLEFunction sceImpose[] = -{ - {0x36aa6e91, 0, "sceImposeSetLanguageMode"}, // Seen - {0x381bd9e7, 0, "sceImposeHomeButton"}, - {0x24fd7bcf, 0, "sceImposeGetLanguageMode"}, - {0x8c943191, 0, "sceImposeGetBatteryIconStatus"}, -}; const HLEFunction sceOpenPSID[] = { @@ -315,7 +308,6 @@ const HLEModule moduleList[] = {"sceSsl"}, {"sceSIRCS_IrDA_Driver"}, {"sceRtc"}, - {"sceImpose",SZ(sceImpose),sceImpose}, //r: [UNK:36aa6e91] : 08b2cd68 //305: [MIPS32 R4K 00000000 ]: Loader: [UNK:24fd7bcf] : 08b2cd70 {"Pspnet_Scan"}, {"Pspnet_Show_MacAddr"}, {"pspeDebug", SZ(pspeDebug), pspeDebug}, @@ -347,6 +339,7 @@ void RegisterAllModules() { Register_sceMp3(); Register_sceHttp(); Register_scePower(); + Register_sceImpose(); Register_sceSuspendForUser(); Register_sceGe_user(); Register_sceUmdUser(); diff --git a/Core/HLE/HLETables.h b/Core/HLE/HLETables.h index 45faffc9cc..5f73715f10 100644 --- a/Core/HLE/HLETables.h +++ b/Core/HLE/HLETables.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/__sceAudio.cpp b/Core/HLE/__sceAudio.cpp index 6d04f57372..de2e705aa0 100644 --- a/Core/HLE/__sceAudio.cpp +++ b/Core/HLE/__sceAudio.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -24,6 +24,9 @@ #include "../CoreTiming.h" #include "../MemMap.h" #include "../Host.h" +#include "../Config.h" +#include "FixedSizeQueue.h" +#include "Common/Thread.h" // While buffers == MAX_BUFFERS, block on blocking write // non-blocking writes will return busy, I guess @@ -34,46 +37,52 @@ std::recursive_mutex section; int eventAudioUpdate = -1; +int eventHostAudioUpdate = -1; +int mixFrequency = 44100; +const int hwSampleRate = 44100; +const int hwBlockSize = 480; +const int hostAttemptBlockSize = 64; +const int audioIntervalUs = (int)(1000000ULL * hwBlockSize / hwSampleRate); +const int audioHostIntervalUs = (int)(1000000ULL * hostAttemptBlockSize / hwSampleRate); + +// High and low watermarks, basically. +const int chanQueueMaxSizeFactor = 4; +const int chanQueueMinSizeFactor = 2; + +// A whole second, should be enough for anything. +FixedSizeQueue outAudioQueue; -const int audioIntervalMs = 20; void hleAudioUpdate(u64 userdata, int cyclesLate) { - host->UpdateSound(); __AudioUpdate(); - CoreTiming::ScheduleEvent(msToCycles(audioIntervalMs), eventAudioUpdate, 0); + CoreTiming::ScheduleEvent(usToCycles(audioIntervalUs), eventAudioUpdate, 0); +} + +void hleHostAudioUpdate(u64 userdata, int cyclesLate) +{ + host->UpdateSound(); + CoreTiming::ScheduleEvent(usToCycles(audioHostIntervalUs), eventHostAudioUpdate, 0); } void __AudioInit() { - eventAudioUpdate = CoreTiming::RegisterEvent("AudioUpdate", &hleAudioUpdate); + mixFrequency = 44100; - CoreTiming::ScheduleEvent(msToCycles(1), eventAudioUpdate, 0); + eventAudioUpdate = CoreTiming::RegisterEvent("AudioUpdate", &hleAudioUpdate); + eventHostAudioUpdate = CoreTiming::RegisterEvent("AudioUpdateHost", &hleHostAudioUpdate); + + CoreTiming::ScheduleEvent(usToCycles(audioIntervalUs), eventAudioUpdate, 0); + CoreTiming::ScheduleEvent(usToCycles(audioHostIntervalUs), eventHostAudioUpdate, 0); for (int i = 0; i < 8; i++) chans[i].clear(); } void __AudioShutdown() { -} - -void __AudioUpdate() -{ - // DEBUG_LOG(HLE, "Updating audio"); - section.lock(); - for (int i = 0; i < MAX_CHANNEL; i++) - { - if (chans[i].triggered) - { - chans[i].triggered = false; - - // Instead of looping through all threads, which this does, we should keep track of which threads are waiting and just - // resume them. - __KernelTriggerWait(WAITTYPE_AUDIOCHANNEL, (SceUID)i, true); - } - } - section.unlock(); + for (int i = 0; i < 8; i++) + chans[i].clear(); } u32 __AudioEnqueue(AudioChannel &chan, int chanNum, bool blocking) @@ -81,15 +90,18 @@ u32 __AudioEnqueue(AudioChannel &chan, int chanNum, bool blocking) section.lock(); if (chan.sampleAddress == 0) return SCE_ERROR_AUDIO_NOT_OUTPUT; - if (chan.sampleQueue.size() > chan.sampleCount*2) { + if (chan.sampleQueue.size() > chan.sampleCount*2*chanQueueMaxSizeFactor) { // Block! if (blocking) { + chan.waitingThread = __KernelGetCurThread(); + // WARNING: This changes currentThread so must grab waitingThread before (line above). __KernelWaitCurThread(WAITTYPE_AUDIOCHANNEL, (SceUID)chanNum, 0, 0, false); section.unlock(); return 0; } else { + chan.waitingThread = 0; return SCE_ERROR_AUDIO_CHANNEL_BUSY; } } @@ -114,49 +126,123 @@ u32 __AudioEnqueue(AudioChannel &chan, int chanNum, bool blocking) return 0; } - -int __AudioMix(short *outstereo, int numSamples) +// Mix samples from the various audio channels into a single sample queue. +// This single sample queue is where __AudioMix should read from. If the sample queue is full, we should +// just sleep the main emulator thread a little. +void __AudioUpdate() { - memset(outstereo, 0, numSamples*sizeof(short)*2); +#ifdef _WIN32 + // HACK - TODO: Remove + bool noThrottle = GetAsyncKeyState(VK_TAB) != 0; +#else + bool noThrottle = false; +#endif + // Sleep here until the host audio hardware is ready to receive samples. + // This will effectively throttle the frame rate. - // Disable Audio for now. - // return numSamples; + if (!noThrottle && g_Config.bEnableSound) { + while (true) + { + if (outAudioQueue.size() < hwBlockSize * 4) + break; // room can only increase without us pushing, so there's no race condition between here and section.lock() + Common::SleepCurrentThread(0); + } + } section.lock(); - int numActiveChans = 0; - - for (int j = 0; j < MAX_CHANNEL; j++) - { - numActiveChans += chans[j].running ? 1 : 0; - } - - if (!numActiveChans) - { - section.unlock(); - return numSamples; - } + s32 mixBuffer[hwBlockSize * 2]; + memset(mixBuffer, 0, sizeof(mixBuffer)); for (int i = 0; i < MAX_CHANNEL; i++) { - for (int s = 0; s < numSamples; s++) + if (!chans[i].reserved) + continue; + if (!chans[i].sampleQueue.size()) { + // DEBUG_LOG(HLE, "No queued samples, skipping channel %i", i); + continue; + } + + for (int s = 0; s < hwBlockSize; s++) { if (chans[i].sampleQueue.size() >= 2) { - s16 sample1 = chans[i].sampleQueue.front(); + s16 sampleL = chans[i].sampleQueue.front(); + s16 sampleR = chans[i].sampleQueue.front(); chans[i].sampleQueue.pop(); - s16 sample2 = chans[i].sampleQueue.front(); chans[i].sampleQueue.pop(); - - outstereo[s*2] += sample1 / 4;//(sample * chans[i].vol1) >> 8; - outstereo[s*2+1] += sample2 / 4;//.(sample * chans[i].vol2) >> 8; + mixBuffer[s * 2] += sampleL; + mixBuffer[s * 2 + 1] += sampleR; + } + else + { + ERROR_LOG(HLE, "channel %i buffer underrun at %i of %i", i, s, hwBlockSize); + break; } } - if (chans[i].sampleQueue.size() < chans[i].sampleCount) + + if (chans[i].sampleQueue.size() < chans[i].sampleCount * 2 * chanQueueMinSizeFactor) { - chans[i].triggered = true; + // Ask the thread to send more samples until next time, queue is being drained. + if (chans[i].waitingThread) { + SceUID waitingThread = chans[i].waitingThread; + chans[i].waitingThread = 0; + // DEBUG_LOG(HLE, "Woke thread %i for some buffer filling", waitingThread); + __KernelResumeThreadFromWait(waitingThread); + } } } + + if (!noThrottle && g_Config.bEnableSound) { + // Push the mixed samples onto the output audio queue. + for (int i = 0; i < hwBlockSize; i++) { + s32 sampleL = mixBuffer[i * 2] >> 2; // TODO - what factor? + s32 sampleR = mixBuffer[i * 2 + 1] >> 2; + + outAudioQueue.push((s16)sampleL); + outAudioQueue.push((s16)sampleR); + } + } + section.unlock(); - return numSamples; +} + +void __AudioSetOutputFrequency(int freq) +{ + mixFrequency = freq; +} + +// numFrames is number of stereo frames. +int __AudioMix(short *outstereo, int numFrames) +{ + // TODO: if mixFrequency != the actual output frequency, resample! + + section.lock(); + int underrun = -1; + s16 sampleL = 0; + s16 sampleR = 0; + bool anythingToPlay = false; + for (int i = 0; i < numFrames; i++) { + if (outAudioQueue.size() >= 2) + { + sampleL = outAudioQueue.front(); + outAudioQueue.pop(); + sampleR = outAudioQueue.front(); + outAudioQueue.pop(); + outstereo[i * 2] = sampleL; + outstereo[i * 2 + 1] = sampleR; + anythingToPlay = true; + } else { + underrun = i; + outstereo[i * 2] = sampleL; // repeat last sample, can reduce clicking + outstereo[i * 2 + 1] = sampleR; // repeat last sample, can reduce clicking + } + } + if (anythingToPlay && underrun >= 0) { + DEBUG_LOG(HLE, "audio out buffer UNDERRUN at %i of %i", underrun, numFrames); + } else { + // DEBUG_LOG(HLE, "No underrun, mixed %i samples fine", numFrames); + } + section.unlock(); + return numFrames; } diff --git a/Core/HLE/__sceAudio.h b/Core/HLE/__sceAudio.h index 7d959ebcaf..196c16a7b8 100644 --- a/Core/HLE/__sceAudio.h +++ b/Core/HLE/__sceAudio.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -24,6 +24,7 @@ void __AudioInit(); void __AudioUpdate(); void __AudioShutdown(); +void __AudioSetOutputFrequency(int freq); // May return SCE_ERROR_AUDIO_CHANNEL_BUSY if buffer too large u32 __AudioEnqueue(AudioChannel &chan, int chanNum, bool blocking); diff --git a/Core/HLE/sceAtrac.cpp b/Core/HLE/sceAtrac.cpp index 74d27598f1..a13bfc15ad 100644 --- a/Core/HLE/sceAtrac.cpp +++ b/Core/HLE/sceAtrac.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceAtrac.h b/Core/HLE/sceAtrac.h index 524dc43261..9da361beae 100644 --- a/Core/HLE/sceAtrac.h +++ b/Core/HLE/sceAtrac.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceAudio.cpp b/Core/HLE/sceAudio.cpp index 2d211758a8..ab3cc9a0dd 100644 --- a/Core/HLE/sceAudio.cpp +++ b/Core/HLE/sceAudio.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -23,6 +23,11 @@ #include "__sceAudio.h" #include "HLE.h" + +// There's a second Audio api called Audio2 that only has one channel, I guess the 8 channel api was overkill. +// We simply map it to the first of the 8 channels. + + AudioChannel chans[8]; // Enqueues the buffer pointer on the channel. If channel buffer queue is full (2 items?) will block until it isn't. @@ -30,87 +35,129 @@ AudioChannel chans[8]; // Not sure about the range of volume, I often see 0x800 so that might be either // max or 50%? -u32 sceAudioOutputPannedBlocking(u32 chan, u32 volume1, u32 volume2, u32 samplePtr) + +void sceAudioOutputBlocking(u32 chan, u32 vol, u32 samplePtr) { - DEBUG_LOG(HLE,"sceAudioOutputPannedBlocking(%d,%d,%d, %08x )", chan, volume1, volume2, samplePtr); - - if (samplePtr == 0) - { - ERROR_LOG(HLE, "Sample pointer null"); - return 0; - } - + if (samplePtr == 0) + { + ERROR_LOG(HLE, "sceAudioOutputBlocking - Sample pointer null"); + RETURN(0); + } if (chan < 0 || chan >= MAX_CHANNEL) { - ERROR_LOG(HLE,"sceAudioOutputPannedBlocking() - BAD CHANNEL"); - return SCE_ERROR_AUDIO_INVALID_CHANNEL; + ERROR_LOG(HLE,"sceAudioOutputBlocking() - BAD CHANNEL"); + RETURN(SCE_ERROR_AUDIO_INVALID_CHANNEL); } else if (!chans[chan].reserved) - { - return SCE_ERROR_AUDIO_CHANNEL_NOT_RESERVED; - } - else { - chans[chan].running = true; - chans[chan].leftVolume = volume1; - chans[chan].rightVolume = volume2; + ERROR_LOG(HLE,"sceAudioOutputBlocking() - channel not reserved"); + RETURN(SCE_ERROR_AUDIO_CHANNEL_NOT_RESERVED); + } + else + { + DEBUG_LOG(HLE, "sceAudioOutputBlocking(%d, %d, %08x )",chan,vol,samplePtr); + chans[chan].leftVolume = vol; + chans[chan].rightVolume = vol; chans[chan].sampleAddress = samplePtr; - return __AudioEnqueue(chans[chan], chan, true); + RETURN(0); + int retval = __AudioEnqueue(chans[chan], chan, true); + if (retval != 0) { + // There was an error and didn't block (block always returns 0 here). Fine to RETURN. + RETURN(retval); + } } } -void sceAudioGetChannelRestLen() +void sceAudioOutputPannedBlocking(u32 chan, u32 volume1, u32 volume2, u32 samplePtr) { - ERROR_LOG(HLE,"UNIMPL sceAudioGetChannelRestLen(%i)", PARAM(0)); - // Remaining samples in that channel buffer. - RETURN(0); + if (samplePtr == 0) + { + ERROR_LOG(HLE, "sceAudioOutputPannedBlocking - Sample pointer null"); + RETURN(0); + } + else if (chan < 0 || chan >= MAX_CHANNEL) + { + ERROR_LOG(HLE,"sceAudioOutputPannedBlocking() - BAD CHANNEL"); + RETURN(SCE_ERROR_AUDIO_INVALID_CHANNEL); + } + else if (!chans[chan].reserved) + { + ERROR_LOG(HLE,"sceAudioOutputPannedBlocking() - CHANNEL NOT RESERVED"); + RETURN(SCE_ERROR_AUDIO_CHANNEL_NOT_RESERVED); + } + else + { + DEBUG_LOG(HLE, "sceAudioOutputPannedBlocking(%d,%d,%d, %08x )", chan, volume1, volume2, samplePtr); + chans[chan].leftVolume = volume1; + chans[chan].rightVolume = volume2; + chans[chan].sampleAddress = samplePtr; + RETURN(0); + int retval = __AudioEnqueue(chans[chan], chan, true); + if (retval != 0) { + // There was an error and didn't block (block always returns 0 here). Fine to RETURN. + RETURN(retval); + } + } +} + +u32 sceAudioOutput(u32 chan, u32 vol, u32 samplePtr) +{ + if (chan < 0 || chan >= MAX_CHANNEL) + { + ERROR_LOG(HLE,"sceAudioOutput() - BAD CHANNEL"); + return SCE_ERROR_AUDIO_INVALID_CHANNEL; + } + else if (!chans[chan].reserved) + { + ERROR_LOG(HLE,"sceAudioOutput(%d, %d, %08x) - channel not reserved", chan, vol, samplePtr); + return SCE_ERROR_AUDIO_CHANNEL_NOT_RESERVED; + } + else + { + chans[chan].leftVolume = vol; + chans[chan].rightVolume = vol; + chans[chan].sampleAddress = samplePtr; + u32 retval = __AudioEnqueue(chans[chan], chan, false); + DEBUG_LOG(HLE, "%08x=sceAudioOutputPanned(%d, %d, %08x)", retval, chan, vol, samplePtr); + return retval; + } } u32 sceAudioOutputPanned(u32 chan, u32 leftVol, u32 rightVol, u32 samplePtr) { - if (chan < 0 || chan >= MAX_CHANNEL) - { - ERROR_LOG(HLE,"sceAudioOutputPannedBlocking() - BAD CHANNEL"); - return SCE_ERROR_AUDIO_INVALID_CHANNEL; - } - else if (!chans[chan].reserved) - { - ERROR_LOG(HLE,"sceAudioOutputPanned(%d, %d, %d, %08x) - channel not reserved", chan,leftVol,rightVol,samplePtr); - return SCE_ERROR_AUDIO_CHANNEL_NOT_RESERVED; - } - else - { - chans[chan].running = true; + if (chan < 0 || chan >= MAX_CHANNEL) + { + ERROR_LOG(HLE,"sceAudioOutputPanned() - BAD CHANNEL"); + return SCE_ERROR_AUDIO_INVALID_CHANNEL; + } + else if (!chans[chan].reserved) + { + ERROR_LOG(HLE,"sceAudioOutputPanned(%d, %d, %d, %08x) - channel not reserved", chan, leftVol, rightVol, samplePtr); + return SCE_ERROR_AUDIO_CHANNEL_NOT_RESERVED; + } + else + { chans[chan].leftVolume = leftVol; chans[chan].rightVolume = rightVol; chans[chan].sampleAddress = samplePtr; - u32 retval = __AudioEnqueue(chans[chan], chan, false); - DEBUG_LOG(HLE,"%08x=sceAudioOutputPanned(%d, %d, %d, %08x)",retval,chan,leftVol,rightVol,samplePtr); - return retval; + u32 retval = __AudioEnqueue(chans[chan], chan, false); + DEBUG_LOG(HLE, "%08x=sceAudioOutputPanned(%d, %d, %d, %08x)", retval, chan, leftVol, rightVol, samplePtr); + return retval; } } -u32 sceAudioOutputBlocking(u32 chan, u32 vol, u32 samplePtr) +int sceAudioGetChannelRestLen(u32 chan) { - if (chan < 0 || chan >= MAX_CHANNEL) - { - ERROR_LOG(HLE,"sceAudioOutputBlocking() - BAD CHANNEL"); - return SCE_ERROR_AUDIO_INVALID_CHANNEL; - } - else if (!chans[chan].reserved) - { - ERROR_LOG(HLE,"sceAudioOutputBlocking() - channel not reserved"); - return SCE_ERROR_AUDIO_CHANNEL_NOT_RESERVED; - } - else - { - DEBUG_LOG(HLE,"sceAudioOutputPanned(%d, %d, %08x )",chan,vol,samplePtr); - chans[chan].running = true; - chans[chan].leftVolume = vol; - chans[chan].rightVolume = vol; - chans[chan].sampleAddress = samplePtr; - return __AudioEnqueue(chans[chan], chan, true); - } + int sz = (int)chans[chan].sampleQueue.size() / 2; + DEBUG_LOG(HLE,"UNTESTED %i = sceAudioGetChannelRestLen(%i)", PARAM(0)); + return sz; +} + +int sceAudioGetChannelRestLength(u32 chan) +{ + int sz = (int)chans[chan].sampleQueue.size() / 2; + DEBUG_LOG(HLE,"UNTESTED %i = sceAudioGetChannelRestLen(%i)", PARAM(0)); + return sz; } static int GetFreeChannel() @@ -147,7 +194,7 @@ u32 sceAudioChReserve(u32 channel, u32 sampleCount, u32 format) //.Allocate soun { WARN_LOG(HLE, "WARNING: Reserving already reserved channel. Error?"); } - DEBUG_LOG(HLE,"%i = sceAudioChReserve(%i, %i, %i)", channel, PARAM(0), sampleCount, format); + DEBUG_LOG(HLE, "%i = sceAudioChReserve(%i, %i, %i)", channel, PARAM(0), sampleCount, format); chans[channel].sampleCount = sampleCount; chans[channel].reserved = true; @@ -161,11 +208,9 @@ u32 sceAudioChRelease(u32 chan) ERROR_LOG(HLE,"sceAudioChRelease(%i): channel not reserved", chan); return SCE_ERROR_AUDIO_CHANNEL_NOT_RESERVED; } - chans[chan].triggered = false; - chans[chan].running = false; chans[chan].reserved = false; - DEBUG_LOG(HLE,"sceAudioChRelease(%i)", chan); + DEBUG_LOG(HLE, "sceAudioChRelease(%i)", chan); return 1; } @@ -183,8 +228,9 @@ u32 sceAudioSetChannelDataLen(u32 chan, u32 len) } else { - DEBUG_LOG(HLE,"sceAudioSetChannelDataLen(%i, %i)", chan, len); - chans[chan].sampleCount = len; + DEBUG_LOG(HLE, "sceAudioSetChannelDataLen(%i, %i)", chan, len); + //chans[chan].dataLen = len; + chans[chan].sampleCount = len; return 0; } } @@ -203,7 +249,7 @@ u32 sceAudioChangeChannelConfig(u32 chan, u32 format) } else { - DEBUG_LOG(HLE,"sceAudioChangeChannelConfig(%i, %i)", chan, format); + DEBUG_LOG(HLE, "sceAudioChangeChannelConfig(%i, %i)", chan, format); chans[chan].format = format; return 0; } @@ -223,7 +269,7 @@ u32 sceAudioChangeChannelVolume(u32 chan, u32 lvolume, u32 rvolume) } else { - DEBUG_LOG(HLE,"sceAudioChangeChannelVolume(%i, %i, %i)", chan, lvolume, rvolume); + DEBUG_LOG(HLE, "sceAudioChangeChannelVolume(%i, %i, %i)", chan, lvolume, rvolume); chans[chan].leftVolume = lvolume; chans[chan].rightVolume = rvolume; return 0; @@ -232,45 +278,104 @@ u32 sceAudioChangeChannelVolume(u32 chan, u32 lvolume, u32 rvolume) void sceAudioInit() { - ERROR_LOG(HLE,"UNIMPL sceAudioInit"); + DEBUG_LOG(HLE,"sceAudioInit()"); + // Don't need to do anything RETURN(0); } +void sceAudioEnd() +{ + DEBUG_LOG(HLE,"sceAudioEnd()"); + // Don't need to do anything + RETURN(0); +} + +void sceAudioOutput2Reserve() +{ + int sampleCount = PARAM(0); + ERROR_LOG(HLE,"sceAudioOutput2Reserve(%i)", sampleCount); + chans[0].sampleCount = sampleCount; + chans[0].reserved = true; + RETURN(0); +} + +void sceAudioOutput2OutputBlocking() +{ + int vol = PARAM(0); + u32 dataPtr = PARAM(1); + + WARN_LOG(HLE,"FAKE sceAudioOutput2OutputBlocking(%i, %08x)", vol, dataPtr); + chans[0].leftVolume = vol; + chans[0].rightVolume = vol; + chans[0].sampleAddress = dataPtr; + RETURN(chans[0].sampleCount); + __AudioEnqueue(chans[0], 0, true); +} + +void sceAudioOutput2ChangeLength() +{ + ERROR_LOG(HLE,"UNIMPL sceAudioOutput2ChangeLength"); + RETURN(0); +} + +u32 sceAudioOutput2GetRestSample() +{ + WARN_LOG(HLE,"UNTESTED sceAudioOutput2GetRestSample()"); + return chans[0].sampleQueue.size() * 2; +} + +void sceAudioOutput2Release() +{ + WARN_LOG(HLE,"sceAudioOutput2Release()"); + chans[0].reserved = false; + RETURN(0); +} + +u32 sceAudioSetFrequency(u32 freq) { + if (freq == 44100 || freq == 48000) { + INFO_LOG(HLE, "sceAudioSetFrequency(%i)", freq); + __AudioSetOutputFrequency(freq); + return 0; + } else { + ERROR_LOG(HLE, "sceAudioSetFrequency(%i) - invalid frequency (must be 44.1 or 48 khz)", freq); + return -1; + } +} const HLEFunction sceAudio[] = { - {0x01562ba3, 0, "sceAudioOutput2Reserve"}, - {0x2d53f36e, 0, "sceAudioOutput2OutputBlocking"}, - {0x63f2889c, 0, "sceAudioOutput2ChangeLength"}, - {0x647cef33, 0, "sceAudioOutput2GetRestSample"}, - {0x43196845, 0, "sceAudioOutput2Release"}, - {0x210567F7, 0, "sceAudioEnd"}, + {0x01562ba3, sceAudioOutput2Reserve, "sceAudioOutput2Reserve"}, // N+, Super Stardust Portable uses these + {0x2d53f36e, sceAudioOutput2OutputBlocking, "sceAudioOutput2OutputBlocking"}, + {0x63f2889c, sceAudioOutput2ChangeLength, "sceAudioOutput2ChangeLength"}, + {0x647cef33, WrapU_V, "sceAudioOutput2GetRestSample"}, + {0x43196845, sceAudioOutput2Release, "sceAudioOutput2Release"}, + {0x38553111, 0, "sceAudioSRCChReserve"}, {0x5C37C0AE, 0, "sceAudioSRCChRelease"}, {0x80F1F7E0, sceAudioInit, "sceAudioInit"}, - {0x927AC32B, 0, "sceAudioSetVolumeOffset"}, - {0xA2BEAA6C, 0, "sceAudioSetFrequency"}, - {0xA633048E, 0, "sceAudioPollInputEnd"}, - {0xB011922F, 0, "sceAudioGetChannelRestLength"}, - {0xB61595C0, 0, "sceAudioLoopbackTest"}, + {0x210567F7, sceAudioEnd, "sceAudioEnd"}, + {0x927AC32B, 0, "sceAudioSetVolumeOffset"}, + {0xA2BEAA6C, WrapU_U, "sceAudioSetFrequency"}, {0xE0727056, 0, "sceAudioSRCOutputBlocking"}, - {0xE926D3FB, 0, "sceAudioInputInitEx"}, - {0x8c1009b2, 0, "sceAudioOutput"}, - {0x136CAF51, WrapU_UUU, "sceAudioOutputBlocking"}, + {0x8c1009b2, WrapU_UUU, "sceAudioOutput"}, + {0x136CAF51, WrapV_UUU, "sceAudioOutputBlocking"}, {0xE2D56B2D, WrapU_UUUU, "sceAudioOutputPanned"}, - {0x13F592BC, WrapU_UUUU, "sceAudioOutputPannedBlocking"}, //(u32, u32, u32, void *)Output sound, blocking + {0x13F592BC, WrapV_UUUU, "sceAudioOutputPannedBlocking"}, //(u32, u32, u32, void *)Output sound, blocking {0x5EC81C55, WrapU_UUU, "sceAudioChReserve"}, //(u32, u32 samplecount, u32) Initialize channel and allocate buffer long, long samplecount, long);//init buffer? returns handle, minus if error {0x6FC46853, WrapU_U, "sceAudioChRelease"}, //(long handle)Terminate channel and deallocate buffer //free buffer? - {0xE9D97901, sceAudioGetChannelRestLen, "sceAudioGetChannelRestLen"}, - {0xCB2E439E, WrapU_UU, "sceAudioSetChannelDataLen"}, //(u32, u32) + {0xE9D97901, WrapI_U, "sceAudioGetChannelRestLen"}, + {0xB011922F, WrapI_U, "sceAudioGetChannelRestLength"}, // Is there a difference between this and sceAudioGetChannelRestLen? + {0xCB2E439E, WrapU_UU, "sceAudioSetChannelDataLen"}, //(u32, u32) {0x95FD0C2D, WrapU_UU, "sceAudioChangeChannelConfig"}, {0xB7E1D8E7, WrapU_UUU, "sceAudioChangeChannelVolume"}, - {0x41efade7, 0, "sceAudioOneshotOutput"}, - {0x086e5895, 0, "sceAudioInputBlocking"}, - {0x6d4bec68, 0, "sceAudioInput"}, + {0x41efade7, 0, "sceAudioOneshotOutput"}, + {0xB61595C0, 0, "sceAudioLoopbackTest"}, + {0x7de61688, 0, "sceAudioInputInit"}, + {0xE926D3FB, 0, "sceAudioInputInitEx"}, + {0x6d4bec68, 0, "sceAudioInput"}, + {0x086e5895, 0, "sceAudioInputBlocking"}, {0xa708c6a6, 0, "sceAudioGetInputLength"}, - {0x87b2e651, 0, "sceAudioWaitInputEnd"}, - {0x7de61688, 0, "sceAudioInputInit"}, - {0xb011922f, 0, "sceAudioGetChannelRestLength"}, + {0xA633048E, 0, "sceAudioPollInputEnd"}, + {0x87b2e651, 0, "sceAudioWaitInputEnd"}, }; diff --git a/Core/HLE/sceAudio.h b/Core/HLE/sceAudio.h index e97a4438dd..356a7efff1 100644 --- a/Core/HLE/sceAudio.h +++ b/Core/HLE/sceAudio.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -20,6 +20,7 @@ #include #include "CommonTypes.h" +#include "sceKernel.h" #include "FixedSizeQueue.h" enum PspAudioFormats { PSP_AUDIO_FORMAT_STEREO = 0, PSP_AUDIO_FORMAT_MONO = 0x10 }; @@ -39,7 +40,9 @@ enum PspAudioFrequencies { PSP_AUDIO_FREQ_44K = 44100, PSP_AUDIO_FREQ_48K = 48 struct AudioChannel { - AudioChannel() {clear();} + AudioChannel() { + clear(); + } // PSP side @@ -48,31 +51,33 @@ struct AudioChannel // last sample address u32 sampleAddress; u32 sampleCount; // Number of samples written in each OutputBlocking - - int running; - int triggered; + int dataLen; // Probably internal queue size. Not currently used. int leftVolume; int rightVolume; int format; + SceUID waitingThread; // PC side - should probably split out // We copy samples as they are written into this simple ring buffer. // Might try something more efficient later. - FixedSizeQueue sampleQueue; - + FixedSizeQueue sampleQueue; void clear() { reserved = false; - running = false; + waitingThread = 0; + leftVolume = 0; + rightVolume = 0; + format = 0; + sampleAddress = 0; + sampleCount = 0; sampleQueue.clear(); } }; - extern AudioChannel chans[8]; void Register_sceAudio(); diff --git a/Core/HLE/sceCtrl.cpp b/Core/HLE/sceCtrl.cpp index 194d24daa5..787f533a88 100644 --- a/Core/HLE/sceCtrl.cpp +++ b/Core/HLE/sceCtrl.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -24,6 +24,9 @@ #define CTRL_ANALOG_X 0 #define CTRL_ANALOG_Y 1 +#define CTRL_MODE_DIGITAL 0 +#define CTRL_MODE_ANALOG 1 + // Returned control data struct _ctrl_data @@ -34,17 +37,48 @@ struct _ctrl_data u8 unused[6]; }; +static u32 oldButtons; +struct CtrlLatch { + u32 btnMake; + u32 btnBreak; + u32 btnPress; + u32 btnRelease; +}; + + ////////////////////////////////////////////////////////////////////////// // STATE BEGIN static bool ctrlInited = false; static bool analogEnabled = false; + static _ctrl_data ctrl; +static CtrlLatch latch; + static std::recursive_mutex ctrlMutex; + // STATE END ////////////////////////////////////////////////////////////////////////// +void SampleControls() { + static int frame = 0; + _ctrl_data &data = ctrl; + data.frame=1;//frame; + frame++; +} + + +void UpdateLatch() { + u32 changed = ctrl.buttons ^ oldButtons; + latch.btnMake = ctrl.buttons & changed; + latch.btnBreak = oldButtons & changed; + latch.btnPress = ctrl.buttons; + latch.btnRelease = (oldButtons & ~ctrl.buttons) & changed; + + oldButtons = ctrl.buttons; +} + // Functions so that the rest of the emulator can control what the sceCtrl interface should return // to the game: @@ -67,7 +101,7 @@ void __CtrlSetAnalog(float x, float y) if (x > 1.0f) x = 1.0f; if (y > 1.0f) y = 1.0f; if (x < -1.0f) x = -1.0f; - if (y > -1.0f) y = -1.0f; + if (y < -1.0f) y = -1.0f; ctrl.analog[0] = (u8)(x * 127.f + 128.f); ctrl.analog[1] = (u8)(y * 127.f + 128.f); } @@ -76,94 +110,89 @@ void sceCtrlInit() { ctrlInited = true; memset(&ctrl, 0, sizeof(ctrl)); - DEBUG_LOG(HLE,"sceCtrlInit"); + ctrl.analog[0] = 128; + ctrl.analog[1] = 128; + DEBUG_LOG(HLE,"sceCtrlInit"); + RETURN(0); } -void sceCtrlSetSamplingMode() +void sceCtrlSetSamplingCycle() { + ERROR_LOG(HLE,"UNIMPL sceCtrlSetSamplingCycle"); + RETURN(0); +} + +u32 sceCtrlSetSamplingMode(u32 mode) { - DEBUG_LOG(HLE,"sceCtrlSetSamplingMode"); + u32 retVal = 0; + + DEBUG_LOG(HLE,"sceCtrlSetSamplingMode(%i)", mode); + _assert_msg_(HLE, mode >= 0 && mode <= 1, "sceCtrlSetSamplingMode: mode outside expected range."); + if (ctrlInited) { - // Looks odd - analogEnabled = true; + retVal = analogEnabled == true ? CTRL_MODE_ANALOG : CTRL_MODE_DIGITAL; + analogEnabled = mode == CTRL_MODE_ANALOG ? true : false; } + return retVal; } void sceCtrlSetIdleCancelThreshold() { DEBUG_LOG(HLE,"UNIMPL sceCtrlSetIdleCancelThreshold"); + RETURN(0); } -void sceCtrlReadBufferPositive() +u32 sceCtrlReadBufferPositive(u32 ctrlDataPtr, u32 nBufs) { - std::lock_guard guard(ctrlMutex); - if (ctrlInited) - { - static int frame = 0; - _ctrl_data &data = ctrl; - data.frame=frame; - frame++; -#ifdef _WIN32 - // TODO: Move this outta here! - data.buttons = 0; - int analogX = 128; - int analogY = 128; - if (GetAsyncKeyState(VK_SPACE)) - data.buttons|=CTRL_START; - if (GetAsyncKeyState('V')) - data.buttons|=CTRL_SELECT; - if (GetAsyncKeyState('A')) - data.buttons|=CTRL_SQUARE; - if (GetAsyncKeyState('S')) - data.buttons|=CTRL_TRIANGLE; - if (GetAsyncKeyState('X')) - data.buttons|=CTRL_CIRCLE; - if (GetAsyncKeyState('Z')) - data.buttons|=CTRL_CROSS; - if (GetAsyncKeyState('Q')) - data.buttons|=CTRL_LTRIGGER; - if (GetAsyncKeyState('W')) - data.buttons|=CTRL_RTRIGGER; - if (GetAsyncKeyState(VK_UP)) { - data.buttons|=CTRL_UP; - analogY -= 100; - } - if (GetAsyncKeyState(VK_DOWN)) { - data.buttons|=CTRL_DOWN; - analogY += 100; - } - if (GetAsyncKeyState(VK_LEFT)) { - data.buttons|=CTRL_LEFT; - analogX -= 100; - } - if (GetAsyncKeyState(VK_RIGHT)) - { - data.buttons|=CTRL_RIGHT; - analogX += 100; - } + DEBUG_LOG(HLE,"sceCtrlReadBufferPositive(%08x, %i)", ctrlDataPtr, nBufs); + _assert_msg_(HLE, nBufs > 0, "sceCtrlReadBufferPositive: trying to read nothing?"); - data.analog[0]=analogX; - data.analog[1]=analogY; -#endif + std::lock_guard guard(ctrlMutex); + // Let's just ignore if ctrl is inited or not; some games don't init it (Super Fruit Fall) + //if (ctrlInited) + //{ + SampleControls(); + memcpy(Memory::GetPointer(ctrlDataPtr), &ctrl, sizeof(_ctrl_data)); + //} + return 1; +} - memcpy(Memory::GetPointer(PARAM(0)), &data, sizeof(_ctrl_data)); - } +u32 sceCtrlPeekLatch(u32 latchDataPtr) { + ERROR_LOG(HLE,"FAKE sceCtrlPeekLatch(%08x)", latchDataPtr); + + if (Memory::IsValidAddress(latchDataPtr)) + Memory::WriteStruct(latchDataPtr, &latch); + return 1; +} + +u32 sceCtrlReadLatch(u32 latchDataPtr) { + ERROR_LOG(HLE,"FAKE sceCtrlReadLatch(%08x)", latchDataPtr); + + // Hackery to do it here. + SampleControls(); + UpdateLatch(); + + + if (Memory::IsValidAddress(latchDataPtr)) + Memory::WriteStruct(latchDataPtr, &latch); + + return 1; } static const HLEFunction sceCtrl[] = { - {0x6a2774f3, sceCtrlInit, "sceCtrlInit"}, //(int unknown), init with 0 - {0x1f4011e6, sceCtrlSetSamplingMode, "sceCtrlSetSamplingMode"}, //(int on); - {0x1f803938, sceCtrlReadBufferPositive, "sceCtrlReadBufferPositive"}, //(ctrl_data_t* paddata, int unknown) // unknown should be 1 + {0x6a2774f3, sceCtrlInit, "sceCtrlInit"}, //(int unknown), init with 0 + {0x1f4011e6, &WrapU_U, "sceCtrlSetSamplingMode"}, //(int on); + {0x1f803938, &WrapU_UU, "sceCtrlReadBufferPositive"}, //(ctrl_data_t* paddata, int unknown) // unknown should be 1 {0x6A2774F3, 0, "sceCtrlSetSamplingCycle"}, //? - {0x6A2774F3,sceCtrlInit,"sceCtrlSetSamplingCycle"}, + {0x6A2774F3,sceCtrlSetSamplingCycle,"sceCtrlSetSamplingCycle"}, {0x02BAAD91,0,"sceCtrlGetSamplingCycle"}, {0xDA6B76A1,0,"sceCtrlGetSamplingMode"}, - {0x3A622550,sceCtrlReadBufferPositive,"sceCtrlPeekBufferPositive"}, + {0x3A622550,&WrapU_UU, "sceCtrlPeekBufferPositive"}, {0xC152080A,0,"sceCtrlPeekBufferNegative"}, {0x60B81F86,0,"sceCtrlReadBufferNegative"}, - {0xB1D0E5CD,0,"sceCtrlPeekLatch"}, - {0x0B588501,0,"sceCtrlReadLatch"}, + {0xB1D0E5CD,&WrapU_U,"sceCtrlPeekLatch"}, + {0x0B588501,&WrapU_U,"sceCtrlReadLatch"}, {0x348D99D4,0,"sceCtrl_348D99D4"}, {0xAF5960F3,0,"sceCtrl_AF5960F3"}, {0xA68FD260,0,"sceCtrlClearRapidFire"}, diff --git a/Core/HLE/sceCtrl.h b/Core/HLE/sceCtrl.h index 7f1a490c4b..10bb163c14 100644 --- a/Core/HLE/sceCtrl.h +++ b/Core/HLE/sceCtrl.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceDisplay.cpp b/Core/HLE/sceDisplay.cpp index 4cab932cd9..f5af289bd3 100644 --- a/Core/HLE/sceDisplay.cpp +++ b/Core/HLE/sceDisplay.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -15,7 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include #include #else @@ -109,6 +109,11 @@ void __DisplayInit() InitGfxState(); } +void __DisplayShutdown() +{ + ShutdownGfxState(); +} + void hleEnterVblank(u64 userdata, int cyclesLate) { int vbCount = userdata; @@ -220,28 +225,34 @@ void sceDisplaySetFramebuf() void sceDisplayGetFramebuf() { - DEBUG_LOG(HLE,"sceDisplayGetFramebuf"); + DEBUG_LOG(HLE,"sceDisplayGetFramebuf()"); RETURN(framebuf.topaddr); } void sceDisplayWaitVblankStart() { - DEBUG_LOG(HLE,"sceDisplayWaitVblankStart"); + DEBUG_LOG(HLE,"sceDisplayWaitVblankStart()"); __KernelWaitCurThread(WAITTYPE_VBLANK, 0, 0, 0, false); - RETURN(0); } void sceDisplayWaitVblank() { - DEBUG_LOG(HLE,"sceDisplayWaitVblank"); + DEBUG_LOG(HLE,"sceDisplayWaitVblank()"); __KernelWaitCurThread(WAITTYPE_VBLANK, 0, 0, 0, false); - sceDisplayWaitVblankStart(); +} + +void sceDisplayWaitVblankCB() +{ + DEBUG_LOG(HLE,"sceDisplayWaitVblankCB()"); + __KernelWaitCurThread(WAITTYPE_VBLANK, 0, 0, 0, true); + __KernelCheckCallbacks(); } void sceDisplayWaitVblankStartCB() { - DEBUG_LOG(HLE,"sceDisplayWaitVblankStartCB"); + DEBUG_LOG(HLE,"sceDisplayWaitVblankStartCB()"); __KernelWaitCurThread(WAITTYPE_VBLANK, 0, 0, 0, true); + __KernelCheckCallbacks(); } void sceDisplayGetVcount() @@ -249,7 +260,7 @@ void sceDisplayGetVcount() // Too spammy // DEBUG_LOG(HLE,"%i=sceDisplayGetVcount()", vCount); // Games like Puyo Puyo call this in a tight loop at end-of-frame. We could have it consume some time from CoreTiming? - CoreTiming::Idle(100000); + CoreTiming::Idle(1000000); RETURN(vCount); } @@ -276,12 +287,13 @@ float sceDisplayGetFramePerSec() const HLEFunction sceDisplay[] = { - {0x0E20F177,&WrapU_UUU, "sceDisplaySetMode"}, - {0x289D82FE,sceDisplaySetFramebuf, "sceDisplaySetFramebuf"}, - {0x36CDFADE,sceDisplayWaitVblank, "sceDisplayWaitVblank"}, - {0x984C27E7,sceDisplayWaitVblankStart, "sceDisplayWaitVblankStart"}, - {0x46F186C3,sceDisplayWaitVblankStartCB,"sceDisplayWaitVblankStartCB"}, - {0x8EB9EC49,sceDisplayWaitVblankStartCB,"sceDisplayWaitVblankCB"}, + {0x0E20F177,&WrapU_UUU, "sceDisplaySetMode"}, + {0x289D82FE,sceDisplaySetFramebuf, "sceDisplaySetFramebuf"}, + {0x36CDFADE,sceDisplayWaitVblank, "sceDisplayWaitVblank"}, + {0x984C27E7,sceDisplayWaitVblankStart, "sceDisplayWaitVblankStart"}, + {0x8EB9EC49,sceDisplayWaitVblankCB, "sceDisplayWaitVblankCB"}, + {0x46F186C3,sceDisplayWaitVblankStartCB, "sceDisplayWaitVblankStartCB"}, + {0x77ed8b3a,0,"sceDisplayWaitVblankStartMultiCB"}, {0xdba6c4c4,&WrapF_V,"sceDisplayGetFramePerSec"}, {0x773dd3a3,sceDisplayGetCurrentHcount,"sceDisplayGetCurrentHcount"}, diff --git a/Core/HLE/sceDisplay.h b/Core/HLE/sceDisplay.h index d6de468867..e8e5995dc4 100644 --- a/Core/HLE/sceDisplay.h +++ b/Core/HLE/sceDisplay.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceDmac.cpp b/Core/HLE/sceDmac.cpp index d5f2e13526..921f62468e 100644 --- a/Core/HLE/sceDmac.cpp +++ b/Core/HLE/sceDmac.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceDmac.h b/Core/HLE/sceDmac.h index 8abcbacfa8..0f40d75120 100644 --- a/Core/HLE/sceDmac.h +++ b/Core/HLE/sceDmac.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceGe.cpp b/Core/HLE/sceGe.cpp index 43cd01c125..9e4e475a73 100644 --- a/Core/HLE/sceGe.cpp +++ b/Core/HLE/sceGe.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -20,11 +20,10 @@ #include "../System.h" #include "../CoreParameter.h" #include "sceGe.h" -#include "sceKernelCallback.h" +#include "sceKernelThread.h" #include "sceKernelInterrupt.h" - -// TODO: Bad dependency. -#include "../../GPU/GLES/DisplayListInterpreter.h" +#include "../GPU/GPUState.h" +#include "../GPU/GPUInterface.h" // TODO: This doesn't really belong here static int state; @@ -61,21 +60,17 @@ u32 sceGeEdramGetSize() u32 sceGeListEnQueue(u32 listAddress, u32 stallAddress, u32 callbackId, u32 optParamAddr) { - if (PSP_CoreParameter().gpuCore == GPU_NULL) - { - DEBUG_LOG(HLE,"No GPU - ignoring sceGeListEnqueue"); - return 0; - } - - u32 listID = GPU::EnqueueList(listAddress, stallAddress); + DEBUG_LOG(HLE,"sceGeListEnQueue(addr=%08x, stall=%08x, cbid=%08x, param=%08x)", + listAddress,stallAddress,callbackId,optParamAddr); + //if (!stallAddress) + // stallAddress = listAddress; + u32 listID = gpu->EnqueueList(listAddress, stallAddress); // HACKY if (listID) state = SCE_GE_LIST_STALLING; else state = SCE_GE_LIST_COMPLETED; - DEBUG_LOG(HLE,"%i=sceGeListEnQueue(addr=%08x, stall=%08x, cbid=%08x, param=%08x)",listID, - listAddress,stallAddress,callbackId,optParamAddr); DEBUG_LOG(HLE,"List enqueued."); //return display list ID return listID; @@ -83,7 +78,9 @@ u32 sceGeListEnQueue(u32 listAddress, u32 stallAddress, u32 callbackId, u32 optP u32 sceGeListEnQueueHead(u32 listAddress, u32 stallAddress, u32 callbackId, u32 optParamAddr) { - u32 listID = GPU::EnqueueList(listAddress,stallAddress); + if (!stallAddress) + stallAddress = listAddress; + u32 listID = gpu->EnqueueList(listAddress,stallAddress); // HACKY if (listID) state = SCE_GE_LIST_STALLING; @@ -102,7 +99,7 @@ void sceGeListUpdateStallAddr(u32 displayListID, u32 stallAddress) DEBUG_LOG(HLE,"sceGeListUpdateStallAddr(dlid=%i,stalladdr=%08x)", displayListID,stallAddress); - GPU::UpdateStall(displayListID, stallAddress); + gpu->UpdateStall(displayListID, stallAddress); } void sceGeListSync(u32 displayListID, u32 mode) //0 : wait for completion 1:check and return @@ -110,19 +107,12 @@ void sceGeListSync(u32 displayListID, u32 mode) //0 : wait for completion 1:che DEBUG_LOG(HLE,"sceGeListSync(dlid=%08x, mode=%08x)", displayListID,mode); } -u32 sceGeDrawSync(u32) +u32 sceGeDrawSync(u32 mode) { //wait/check entire drawing state - u32 mode = PARAM(0); //0 : wait for completion 1:check and return - DEBUG_LOG(HLE,"FAKE sceGeDrawSync(mode=%d)",mode); - if (mode == 1) - { - return 0; - } - else - { - return 0; - } + DEBUG_LOG(HLE,"FAKE sceGeDrawSync(mode=%d) (0=wait for completion)",mode); + gpu->DrawSync(mode); + return 0; } void sceGeBreak() @@ -139,15 +129,19 @@ void sceGeContinue() u32 sceGeSetCallback(u32 structAddr) { - ERROR_LOG(HLE,"HALFIMPL sceGeSetCallback(struct=%08x)", structAddr); + DEBUG_LOG(HLE,"sceGeSetCallback(struct=%08x)", structAddr); PspGeCallbackData ge_callback_data; Memory::ReadStruct(structAddr, &ge_callback_data); - if (ge_callback_data.finish_func) + if (ge_callback_data.finish_func) { sceKernelRegisterSubIntrHandler(PSP_GE_INTR, PSP_GE_SUBINTR_FINISH, ge_callback_data.finish_func, ge_callback_data.finish_arg); - if (ge_callback_data.signal_func) + sceKernelEnableSubIntr(PSP_GE_INTR, PSP_GE_SUBINTR_FINISH); + } + if (ge_callback_data.signal_func) { sceKernelRegisterSubIntrHandler(PSP_GE_INTR, PSP_GE_SUBINTR_SIGNAL, ge_callback_data.signal_func, ge_callback_data.signal_arg); + sceKernelEnableSubIntr(PSP_GE_INTR, PSP_GE_SUBINTR_SIGNAL); + } // TODO: This should return a callback ID return 0; @@ -155,7 +149,9 @@ u32 sceGeSetCallback(u32 structAddr) void sceGeUnsetCallback(u32 cbID) { - ERROR_LOG(HLE,"UNIMPL sceGeUnsetCallback(cbid=%08x)", cbID); + DEBUG_LOG(HLE,"sceGeUnsetCallback(cbid=%08x)", cbID); + sceKernelReleaseSubIntrHandler(PSP_GE_INTR, PSP_GE_SUBINTR_FINISH); + sceKernelReleaseSubIntrHandler(PSP_GE_INTR, PSP_GE_SUBINTR_SIGNAL); } void sceGeSaveContext() diff --git a/Core/HLE/sceGe.h b/Core/HLE/sceGe.h index 69b244f637..9a418743c7 100644 --- a/Core/HLE/sceGe.h +++ b/Core/HLE/sceGe.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceHprm.cpp b/Core/HLE/sceHprm.cpp index cd8bf7f535..63490c960d 100644 --- a/Core/HLE/sceHprm.cpp +++ b/Core/HLE/sceHprm.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceHprm.h b/Core/HLE/sceHprm.h index 978ff0bed3..43219239a0 100644 --- a/Core/HLE/sceHprm.h +++ b/Core/HLE/sceHprm.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceHttp.cpp b/Core/HLE/sceHttp.cpp index c6a4dc6771..8fbf7b90ab 100644 --- a/Core/HLE/sceHttp.cpp +++ b/Core/HLE/sceHttp.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceHttp.h b/Core/HLE/sceHttp.h index 3aa0100e4e..30dc9db448 100644 --- a/Core/HLE/sceHttp.h +++ b/Core/HLE/sceHttp.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceImpose.cpp b/Core/HLE/sceImpose.cpp new file mode 100644 index 0000000000..d37ac1f171 --- /dev/null +++ b/Core/HLE/sceImpose.cpp @@ -0,0 +1,81 @@ +// Copyright (c) 2012- PPSSPP Project. + +// 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, version 2.0 or later versions. + +// 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 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#include "HLE.h" +#include "FunctionWrappers.h" +#include "../MIPS/MIPS.h" + + +const int PSP_LANGUAGE_JAPANESE = 0; +const int PSP_LANGUAGE_ENGLISH = 1; +const int PSP_LANGUAGE_FRENCH = 2; +const int PSP_LANGUAGE_SPANISH = 3; +const int PSP_LANGUAGE_GERMAN = 4; +const int PSP_LANGUAGE_ITALIAN = 5; +const int PSP_LANGUAGE_DUTCH = 6; +const int PSP_LANGUAGE_PORTUGUESE = 7; +const int PSP_LANGUAGE_RUSSIAN = 8; +const int PSP_LANGUAGE_KOREAN = 9; +const int PSP_LANGUAGE_TRADITIONAL_CHINESE = 10; +const int PSP_LANGUAGE_SIMPLIFIED_CHINESE = 11; + +static u32 iLanguage = PSP_LANGUAGE_ENGLISH; +static u32 iButtonValue = 0; + + +u32 sceImposeGetBatteryIconStatus(u32 chargingPtr, u32 iconStatusPtr) +{ + DEBUG_LOG(HLE,"%i=sceImposeGetBatteryIconStatus(%08x, %08x)", chargingPtr, iconStatusPtr); + if (Memory::IsValidAddress(chargingPtr)) + Memory::Write_U32(1, chargingPtr); + if (Memory::IsValidAddress(iconStatusPtr)) + Memory::Write_U32(3, iconStatusPtr); + return 0; +} + +u32 sceImposeSetLanguageMode(u32 languageVal, u32 buttonVal) +{ + DEBUG_LOG(HLE,"%i=sceImposeSetLanguageMode(%08x, %08x)", languageVal, buttonVal); + iLanguage = languageVal; + iButtonValue = buttonVal; + return 0; +} + +u32 sceImposeGetLanguageMode(u32 languagePtr, u32 btnPtr) +{ + DEBUG_LOG(HLE,"%i=sceImposeGetLanguageMode(%08x, %08x)", languagePtr, btnPtr); + if (Memory::IsValidAddress(languagePtr)) + Memory::Write_U32(iLanguage, languagePtr); + if (Memory::IsValidAddress(btnPtr)) + Memory::Write_U32(iButtonValue, btnPtr); + return 0; +} + +//OSD stuff? home button? +const HLEFunction sceImpose[] = +{ + {0x36aa6e91, &WrapU_UU, "sceImposeSetLanguageMode"}, // Seen + {0x381bd9e7, 0, "sceImposeHomeButton"}, + {0x24fd7bcf, &WrapU_UU, "sceImposeGetLanguageMode"}, + {0x8c943191, &WrapU_UU, "sceImposeGetBatteryIconStatus"}, + {0x72189C48, 0, "sceImposeSetUMDPopup"}, +}; + +void Register_sceImpose() +{ + RegisterModule("sceImpose", ARRAY_SIZE(sceImpose), sceImpose); +} diff --git a/Core/HLE/sceImpose.h b/Core/HLE/sceImpose.h new file mode 100644 index 0000000000..1de2aea93e --- /dev/null +++ b/Core/HLE/sceImpose.h @@ -0,0 +1,20 @@ +// Copyright (c) 2012- PPSSPP Project. + +// 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, version 2.0 or later versions. + +// 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 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +void Register_sceImpose(); diff --git a/Core/HLE/sceIo.cpp b/Core/HLE/sceIo.cpp index c82fe252f1..e82ec1bd63 100644 --- a/Core/HLE/sceIo.cpp +++ b/Core/HLE/sceIo.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -23,6 +23,7 @@ #include "../System.h" #include "HLE.h" #include "../MIPS/MIPS.h" +#include "../HW/MemoryStick.h" #include "../FileSystems/FileSystem.h" #include "../FileSystems/MetaFileSystem.h" @@ -36,6 +37,10 @@ #define ERROR_ERRNO_FILE_NOT_FOUND 0x80010002 + +#define ERROR_MEMSTICK_DEVCTL_BAD_PARAMS 0x80220081 +#define ERROR_MEMSTICK_DEVCTL_TOO_MANY_CALLBACKS 0x80220082 + /* TODO: async io is missing features! @@ -178,10 +183,10 @@ void __IoInit() memstick = new DirectoryFileSystem(&pspFileSystem, mypath); pspFileSystem.Mount("ms0:", memstick); - pspFileSystem.Mount("fatms0:", memstick); - pspFileSystem.Mount("fatms:", memstick); - pspFileSystem.Mount("flash0:", new EmptyFileSystem()); - pspFileSystem.Mount("flash1:", new EmptyFileSystem()); + pspFileSystem.Mount("fatms0:", memstick); + pspFileSystem.Mount("fatms:", memstick); + pspFileSystem.Mount("flash0:", new EmptyFileSystem()); + pspFileSystem.Mount("flash1:", new EmptyFileSystem()); } void __IoShutdown() @@ -224,7 +229,7 @@ void __IoCompleteAsyncIO(SceUID id) { if (f->callbackID) { - __KernelNotifyCallback(__KernelGetCurThread(), f->callbackID, f->callbackArg); + // __KernelNotifyCallbackType(THREAD_CALLBACK_IO, __KernelGetCurThread(), f->callbackID, f->callbackArg); } } } @@ -240,7 +245,7 @@ void __IoGetStat(SceIoStat *stat, PSPFileInfo &info) else type = SCE_STM_FREG, attr = TYPE_FILE; - stat->st_mode = 0777 | type; + stat->st_mode = type; //0777 | type; stat->st_attr = attr; stat->st_size = info.size; stat->st_private[0] = info.startSector; @@ -251,11 +256,11 @@ void sceIoGetstat() { const char *filename = Memory::GetCharPointer(PARAM(0)); u32 addr = PARAM(1); - DEBUG_LOG(HLE,"sceIoGetstat(%s, %08x)",filename,addr); SceIoStat *stat = (SceIoStat*)Memory::GetPointer(addr); PSPFileInfo info = pspFileSystem.GetFileInfo(filename); __IoGetStat(stat, info); + DEBUG_LOG(HLE,"sceIoGetstat(%s, %08x) : sector = %08x",filename,addr,info.startSector); RETURN(0); } @@ -476,25 +481,83 @@ void sceIoDevctl() //(const char *name, int cmd, void *arg, size_t arglen, void int argLen = PARAM(3); u32 outPtr = PARAM(4); int outLen = PARAM(5); - int retVal = 0; - DEBUG_LOG(HLE,"%i=sceIoDevctl(\"%s\", %08x, %08x, %i, %08x, %i)", - retVal, name, cmd,argAddr,argLen,outPtr,outLen); + if (strcmp(name, "emulator:")) { + DEBUG_LOG(HLE,"sceIoDevctl(\"%s\", %08x, %08x, %i, %08x, %i)", name, cmd,argAddr,argLen,outPtr,outLen); + } + + // UMD checks + switch (cmd) { + case 0x01F20001: // Get Disc Type. + if (Memory::IsValidAddress(outPtr)) { + Memory::Write_U32(0x10, outPtr); // Game disc + RETURN(0); return; + } else { + RETURN(-1); return; + } + break; + case 0x01F20002: // Get current LBA. + if (Memory::IsValidAddress(outPtr)) { + Memory::Write_U32(0, outPtr); // Game disc + RETURN(0); return; + } else { + RETURN(-1); return; + } + break; + case 0x01F100A3: // Seek + RETURN(0); return; + break; + } + // This should really send it on to a FileSystem implementation instead. - if (!strcmp(name, "mscmhc0:")) + if (!strcmp(name, "mscmhc0:") || !strcmp(name, "ms0:")) { switch (cmd) { // does one of these set a callback as well? (see coded arms) + case 0x02015804: // Register callback + if (Memory::IsValidAddress(argAddr) && argLen == 4) { + u32 cbId = Memory::Read_U32(argAddr); + if (0 == __KernelRegisterCallback(THREAD_CALLBACK_MEMORYSTICK, cbId)) { + DEBUG_LOG(HLE, "sceIoDevCtl: Memstick callback %i registered, notifying immediately.", cbId); + __KernelNotifyCallbackType(THREAD_CALLBACK_MEMORYSTICK, cbId, MemoryStick_State()); + RETURN(0); + } else { + RETURN(ERROR_MEMSTICK_DEVCTL_BAD_PARAMS); + } + return; + } + break; + + case 0x02025805: // Unregister callback + if (Memory::IsValidAddress(argAddr) && argLen == 4) { + u32 cbId = Memory::Read_U32(argAddr); + if (0 == __KernelUnregisterCallback(THREAD_CALLBACK_MEMORYSTICK, cbId)) { + DEBUG_LOG(HLE, "sceIoDevCtl: Unregistered memstick callback %i", cbId); + RETURN(0); + } else { + RETURN(ERROR_MEMSTICK_DEVCTL_BAD_PARAMS); + } + return; + } + break; + case 0x02025806: // Memory stick inserted? case 0x02025801: // Memstick Driver status? - Memory::Write_U32(1, outPtr); - RETURN(0); + if (Memory::IsValidAddress(outPtr)) { + Memory::Write_U32(1, outPtr); + RETURN(0); + } else { + RETURN(ERROR_MEMSTICK_DEVCTL_BAD_PARAMS); + } return; - case 0x02425818: + + case 0x02425818: // Get memstick size etc // Pretend we have a 2GB memory stick. - { + if (Memory::IsValidAddress(argAddr)) { // "Should" be outPtr but isn't + u32 pointer = Memory::Read_U32(argAddr); + u64 totalSize = (u32)2 * 1024 * 1024 * 1024; u64 freeSize = 1 * 1024 * 1024 * 1024; DeviceSize deviceSize; @@ -503,21 +566,85 @@ void sceIoDevctl() //(const char *name, int cmd, void *arg, size_t arglen, void deviceSize.sectorsPerCluster = 0x08; deviceSize.totalClusters = (u32)((totalSize * 95 / 100) / (deviceSize.sectorSize * deviceSize.sectorsPerCluster)); deviceSize.freeClusters = (u32)((freeSize * 95 / 100) / (deviceSize.sectorSize * deviceSize.sectorsPerCluster)); - Memory::WriteStruct(outPtr, &deviceSize); + Memory::WriteStruct(pointer, &deviceSize); RETURN(0); - return; + } else { + RETURN(ERROR_MEMSTICK_DEVCTL_BAD_PARAMS); } - + return; } } - if (!strcmp(name, "fatms0:") && cmd == 0x02425823) + if (!strcmp(name, "fatms0:")) { - if (Memory::IsValidAddress(outPtr)) - Memory::Write_U32(1, outPtr); // TODO: Make a headless mode for running tests! + switch (cmd) { + case 0x02415821: // MScmRegisterMSInsertEjectCallback + { + u32 cbId = Memory::Read_U32(argAddr); + if (0 == __KernelRegisterCallback(THREAD_CALLBACK_MEMORYSTICK_FAT, cbId)) { + DEBUG_LOG(HLE, "sceIoDevCtl: Memstick FAT callback %i registered, notifying immediately.", cbId); + __KernelNotifyCallbackType(THREAD_CALLBACK_MEMORYSTICK_FAT, cbId, MemoryStick_FatState()); + RETURN(0); + } else { + RETURN(-1); + } + return; + } + break; + case 0x02415822: // MScmUnregisterMSInsertEjectCallback + { + u32 cbId = Memory::Read_U32(argAddr); + if (0 == __KernelUnregisterCallback(THREAD_CALLBACK_MEMORYSTICK_FAT, cbId)) { + DEBUG_LOG(HLE, "sceIoDevCtl: Unregistered memstick FAT callback %i", cbId); + RETURN(0); + } else { + RETURN(-1); + } + return; + } - RETURN(0); - return; + case 0x02415823: // Set FAT as enabled + if (Memory::IsValidAddress(argAddr) && argLen == 4) { + MemoryStick_SetFatState((MemStickFatState)Memory::Read_U32(argAddr)); + RETURN(0); + } else { + ERROR_LOG(HLE, "Failed 0x02415823 fat"); + RETURN(-1); + } + break; + + case 0x02425823: // Check if FAT enabled + if (Memory::IsValidAddress(outPtr) && outLen == 4) { + Memory::Write_U32(MemoryStick_FatState(), outPtr); + RETURN(0); + } else { + ERROR_LOG(HLE, "Failed 0x02425823 fat"); + RETURN(-1); + } + break; + + case 0x02425818: // Get memstick size etc + // Pretend we have a 2GB memory stick. + { + if (Memory::IsValidAddress(argAddr)) { // "Should" be outPtr but isn't + u32 pointer = Memory::Read_U32(argAddr); + + u64 totalSize = (u32)2 * 1024 * 1024 * 1024; + u64 freeSize = 1 * 1024 * 1024 * 1024; + DeviceSize deviceSize; + deviceSize.maxSectors = 512; + deviceSize.sectorSize = 0x200; + deviceSize.sectorsPerCluster = 0x08; + deviceSize.totalClusters = (u32)((totalSize * 95 / 100) / (deviceSize.sectorSize * deviceSize.sectorsPerCluster)); + deviceSize.freeClusters = (u32)((freeSize * 95 / 100) / (deviceSize.sectorSize * deviceSize.sectorsPerCluster)); + Memory::WriteStruct(pointer, &deviceSize); + RETURN(0); + } else { + RETURN(ERROR_MEMSTICK_DEVCTL_BAD_PARAMS); + } + return; + } + } } @@ -529,13 +656,14 @@ void sceIoDevctl() //(const char *name, int cmd, void *arg, size_t arglen, void case 1: // EMULATOR_DEVCTL__GET_HAS_DISPLAY if (Memory::IsValidAddress(outPtr)) Memory::Write_U32(0, outPtr); // TODO: Make a headless mode for running tests! - break; + RETURN(0); + return; case 2: // EMULATOR_DEVCTL__SEND_OUTPUT { std::string data(Memory::GetCharPointer(argAddr), argLen); if (PSP_CoreParameter().printfEmuLog) { - puts(data.c_str()); + printf("%s", data.c_str()); #ifdef _WIN32 OutputDebugString(data.c_str()); #endif @@ -546,14 +674,20 @@ void sceIoDevctl() //(const char *name, int cmd, void *arg, size_t arglen, void { DEBUG_LOG(HLE, "%s", data.c_str()); } - break; + RETURN(0); + return; } case 3: // EMULATOR_DEVCTL__IS_EMULATOR if (Memory::IsValidAddress(outPtr)) Memory::Write_U32(1, outPtr); // TODO: Make a headless mode for running tests! - break; + RETURN(0); + return; } - retVal = 0; + + ERROR_LOG(HLE, "sceIoDevCtl: UNKNOWN PARAMETERS"); + + RETURN(0); + return; } //089c6d1c weird branch @@ -564,7 +698,7 @@ void sceIoDevctl() //(const char *name, int cmd, void *arg, size_t arglen, void 089c6c78 ]: HLE: sceIoDevctl("fatms0:", 02415821, 09ffb9c4, 4, 00000000, 0) (z_un_089c6bc4) 089c6cac ]: HLE: sceIoDevctl("mscmhc0:", 02025806, 00000000, 0, 09ffb9c8, 4) (z_un_089c6bc4) */ - RETURN(retVal); + RETURN(SCE_KERNEL_ERROR_UNSUP); } void sceIoRename() //(const char *oldname, const char *newname); @@ -790,6 +924,7 @@ void sceIoDread() { if (dir->index == (int)dir->listing.size()) { + DEBUG_LOG(HLE,"sceIoDread( %d %08x ) - end of the line", PARAM(0), PARAM(1)); RETURN(0); return; } diff --git a/Core/HLE/sceIo.h b/Core/HLE/sceIo.h index 3699e9d1f5..907fd6046b 100644 --- a/Core/HLE/sceIo.h +++ b/Core/HLE/sceIo.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceKernel.cpp b/Core/HLE/sceKernel.cpp index b5780f1589..c6d3166cb2 100644 --- a/Core/HLE/sceKernel.cpp +++ b/Core/HLE/sceKernel.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -34,7 +34,6 @@ #include "sceIo.h" #include "sceKernel.h" #include "sceKernelAlarm.h" -#include "sceKernelCallback.h" #include "sceKernelInterrupt.h" #include "sceKernelThread.h" #include "sceKernelMemory.h" @@ -46,6 +45,7 @@ #include "sceKernelEventFlag.h" #include "sceKernelVTimer.h" #include "sceKernelTime.h" +#include "scePower.h" #include "sceUtility.h" #include "sceUmd.h" @@ -75,6 +75,7 @@ void __KernelInit() __DisplayInit(); __InterruptsInit(); __GeInit(); + __PowerInit(); __UtilityInit(); __UmdInit(); @@ -106,6 +107,10 @@ void __KernelShutdown() kernelRunning = false; } +bool __KernelIsRunning() { + return kernelRunning; +} + void sceKernelExitGame() { INFO_LOG(HLE,"sceKernelExitGame"); @@ -114,14 +119,22 @@ void sceKernelExitGame() else PanicAlert("Game exited"); Core_Stop(); - RETURN(0); } -void sceKernelRegisterExitCallback() +void sceKernelExitGameWithStatus() { - u32 cbid = PARAM(0); - ERROR_LOG(HLE,"UNIMPL sceKernelRegisterExitCallback(%i)", cbid); - RETURN(0); + INFO_LOG(HLE,"sceKernelExitGameWithStatus"); + if (PSP_CoreParameter().headLess) + exit(0); + else + PanicAlert("Game exited (with status)"); + Core_Stop(); +} + +u32 sceKernelRegisterExitCallback(u32 cbId) +{ + DEBUG_LOG(HLE,"NOP sceKernelRegisterExitCallback(%i)", cbId); + return 0; } // TODO: What? @@ -145,13 +158,13 @@ void sceKernelRegisterDefaultExceptionHandler() void sceKernelSetGPO() { // Sets debug LEDs. - INFO_LOG(HLE,"sceKernelSetGPO(%02x)", PARAM(0)); + DEBUG_LOG(HLE,"sceKernelSetGPO(%02x)", PARAM(0)); } void sceKernelGetGPI() { // Always returns 0 on production systems. - INFO_LOG(HLE,"0=sceKernelGetGPI()"); + DEBUG_LOG(HLE,"0=sceKernelGetGPI()"); RETURN(0); } @@ -226,7 +239,7 @@ KernelObject *&KernelObjectPool::operator [](SceUID handle) void KernelObjectPool::List() { - for (int i=0; i, "sceKernelCreateEventFlag"}, + {0x812346E4,&WrapU_IU, "sceKernelClearEventFlag"}, + {0xEF9E4C70,&WrapU_I, "sceKernelDeleteEventFlag"}, + {0x1fb15a32,&WrapU_IU, "sceKernelSetEventFlag"}, + {0x402FCF22,&WrapV_IUUUU, "sceKernelWaitEventFlag"}, + {0x328C546A,&WrapV_IUUUU, "sceKernelWaitEventFlagCB"}, + {0x30FD48F0,&WrapI_IUUUU, "sceKernelPollEventFlag"}, + {0xCD203292,&WrapU_V, "sceKernelCancelEventFlag"}, + {0xA66B0120,&WrapU_IU, "sceKernelReferEventFlagStatus"}, - {0x8FFDF9A2,sceKernelCancelSema, "sceKernelCancelSema"}, - {0xD6DA4BA1,sceKernelCreateSema, "sceKernelCreateSema"}, - {0x28b6489c,sceKernelDeleteSema, "sceKernelDeleteSema"}, - {0x58b1f937,sceKernelPollSema, "sceKernelPollSema"}, - {0xBC6FEBC5,sceKernelReferSemaStatus,"sceKernelReferSemaStatus"}, - {0x3F53E640,sceKernelSignalSema, "sceKernelSignalSema"}, - {0x4E3A1105,sceKernelWaitSema, "sceKernelWaitSema"}, - {0x6d212bac,sceKernelWaitSemaCB, "sceKernelWaitSemaCB"}, + {0x8FFDF9A2,&WrapV_IIU, "sceKernelCancelSema"}, + {0xD6DA4BA1,&WrapV_CUIIU, "sceKernelCreateSema"}, + {0x28b6489c,&WrapV_I, "sceKernelDeleteSema"}, + {0x58b1f937,&WrapV_II, "sceKernelPollSema"}, + {0xBC6FEBC5,&WrapV_IU, "sceKernelReferSemaStatus"}, + {0x3F53E640,&WrapV_II, "sceKernelSignalSema"}, + {0x4E3A1105,&WrapV_IIU, "sceKernelWaitSema"}, + {0x6d212bac,&WrapV_IIU, "sceKernelWaitSemaCB"}, {0x60107536,0,"sceKernelDeleteLwMutex"}, {0x19CFF145,0,"sceKernelCreateLwMutex"}, @@ -290,9 +337,10 @@ const HLEFunction ThreadManForUser[] = {0x5bf4dd27,&WrapU_UUU,"sceKernelLockMutexCB"}, {0x6b30100f,&WrapU_UU,"sceKernelUnlockMutex"}, {0xb7d098c6,&WrapU_CUU,"sceKernelCreateMutex"}, + {0x0DDCD2C9, 0, "sceKernelTryLockMutex"}, // NOTE: LockLwMutex and UnlockLwMutex are in Kernel_Library, see sceKernelInterrupt.cpp. - {0xFCCFAD26,0,"sceKernelCancelWakeupThread"}, + {0xFCCFAD26,sceKernelCancelWakeupThread,"sceKernelCancelWakeupThread"}, {0xea748e31,sceKernelChangeCurrentThreadAttr,"sceKernelChangeCurrentThreadAttr"}, {0x71bc9871,sceKernelChangeThreadPriority,"sceKernelChangeThreadPriority"}, {0x446D8DE6,sceKernelCreateThread,"sceKernelCreateThread"}, @@ -303,7 +351,7 @@ const HLEFunction ThreadManForUser[] = {0x68da9e36,sceKernelDelayThreadCB,"sceKernelDelayThreadCB"}, {0xaa73c935,sceKernelExitThread,"sceKernelExitThread"}, {0x809ce29b,sceKernelExitDeleteThread,"sceKernelExitDeleteThread"}, - {0x94aa61ee,0,"sceKernelGetThreadCurrentPriority"}, + {0x94aa61ee,sceKernelGetThreadCurrentPriority,"sceKernelGetThreadCurrentPriority"}, {0x293b45b8,sceKernelGetThreadId,"sceKernelGetThreadId"}, {0x3B183E26,sceKernelGetThreadExitStatus,"sceKernelGetThreadExitStatus"}, {0x52089CA1,sceKernelGetThreadStackFreeSize,"sceKernelGetThreadStackFreeSize"}, @@ -311,13 +359,13 @@ const HLEFunction ThreadManForUser[] = {0x17c1684e,sceKernelReferThreadStatus,"sceKernelReferThreadStatus"}, {0x2C34E053,0,"sceKernelReleaseWaitThread"}, {0x75156e8f,sceKernelResumeThread,"sceKernelResumeThread"}, - {0x27e22ec2,0,"sceKernelResumeDispatchThread"}, + {0x3ad58b8c,&WrapU_V,"sceKernelSuspendDispatchThread"}, + {0x27e22ec2,&WrapU_U,"sceKernelResumeDispatchThread"}, {0x912354a7,sceKernelRotateThreadReadyQueue,"sceKernelRotateThreadReadyQueue"}, {0x9ACE131E,sceKernelSleepThread,"sceKernelSleepThread"}, {0x82826f70,sceKernelSleepThreadCB,"sceKernelSleepThreadCB"}, - {0xF475845D,sceKernelStartThread,"sceKernelStartThread"}, + {0xF475845D,&WrapU_V,"sceKernelStartThread"}, {0x9944f31f,sceKernelSuspendThread,"sceKernelSuspendThread"}, - {0x3ad58b8c,0,"sceKernelSuspendDispatchThread"}, {0x616403ba,0,"sceKernelTerminateThread"}, {0x383f7bcc,sceKernelTerminateDeleteThread,"sceKernelTerminateDeleteThread"}, {0x840E8133,sceKernelWaitThreadEndCB,"sceKernelWaitThreadEndCB"}, @@ -345,8 +393,8 @@ const HLEFunction ThreadManForUser[] = {0xdb738f35,sceKernelGetSystemTime,"sceKernelGetSystemTime"}, {0x369ed59d,sceKernelGetSystemTimeLow,"sceKernelGetSystemTimeLow"}, - {0x8218B4DD,0,"sceKernelReferGlobalProfiler"}, - {0x627E6F3A,0,"sceKernelReferSystemStatus"}, + {0x8218B4DD,&WrapU_U,"sceKernelReferGlobalProfiler"}, + {0x627E6F3A,&WrapU_U,"sceKernelReferSystemStatus"}, {0x64D4540E,0,"sceKernelReferThreadProfiler"}, //Fifa Street 2 uses alarms @@ -374,17 +422,16 @@ const HLEFunction ThreadManForUser[] = {0xC11BA8C4,sceKernelNotifyCallback,"sceKernelNotifyCallback"}, {0xBA4051D6,sceKernelCancelCallback,"sceKernelCancelCallback"}, {0x2A3D44FF,sceKernelGetCallbackCount,"sceKernelGetCallbackCount"}, - {0x349D6D6C,sceKernelCheckCallback,"sceKernelCheckCallback"}, {0x730ED8BC,sceKernelReferCallbackStatus,"sceKernelReferCallbackStatus"}, - {0x8125221D,sceKernelCreateMbx,"sceKernelCreateMbx"}, - {0x86255ADA,sceKernelDeleteMbx,"sceKernelDeleteMbx"}, - {0xE9B3061E,sceKernelSendMbx,"sceKernelSendMbx"}, - {0x18260574,sceKernelReceiveMbx,"sceKernelReceiveMbx"}, - {0xF3986382,sceKernelReceiveMbxCB,"sceKernelReceiveMbxCB"}, - {0x0D81716A,sceKernelPollMbx,"sceKernelPollMbx"}, - {0x87D4DD36,sceKernelCancelReceiveMbx,"sceKernelCancelReceiveMbx"}, - {0xA8E8C846,sceKernelReferMbxStatus,"sceKernelReferMbxStatus"}, + {0x8125221D,&WrapU_CIUIU,"sceKernelCreateMbx"}, + {0x86255ADA,&WrapI_I,"sceKernelDeleteMbx"}, + {0xE9B3061E,&WrapV_IU,"sceKernelSendMbx"}, + {0x18260574,&WrapV_IUU,"sceKernelReceiveMbx"}, + {0xF3986382,&WrapV_IUU,"sceKernelReceiveMbxCB"}, + {0x0D81716A,&WrapI_IU,"sceKernelPollMbx"}, + {0x87D4DD36,&WrapI_IU,"sceKernelCancelReceiveMbx"}, + {0xA8E8C846,&WrapI_IU,"sceKernelReferMbxStatus"}, {0x7C0DC2A0,sceKernelCreateMsgPipe,"sceKernelCreateMsgPipe"}, {0xF0B7DA1C,sceKernelDeleteMsgPipe,"sceKernelDeleteMsgPipe"}, @@ -415,9 +462,11 @@ const HLEFunction ThreadManForUser[] = {0xA8AA591F,sceKernelCancelFpl,"sceKernelCancelFpl"}, {0xD8199E4C,sceKernelReferFplStatus,"sceKernelReferFplStatus"}, + // Not sure if these should be hooked up. See below. {0x0E927AED, _sceKernelReturnFromTimerHandler, "_sceKernelReturnFromTimerHandler"}, {0x532A522E, _sceKernelExitThread,"_sceKernelExitThread"}, + // Shouldn't hook this up. No games should import this function manually and call it. // {0x6E9EA350, _sceKernelReturnFromCallback,"_sceKernelReturnFromCallback"}, }; @@ -430,10 +479,10 @@ void Register_ThreadManForUser() const HLEFunction LoadExecForUser[] = { - {0x05572A5F,sceKernelExitGame, "sceKernelExitGame"}, //() - {0x4AC57943,sceKernelRegisterExitCallback,"sceKernelRegisterExitCallback"}, - {0xBD2F1094,sceKernelLoadExec,"sceKernelLoadExec"}, - {0x2AC9954B,0,"sceKernelExitGameWithStatus"}, + {0x05572A5F,&WrapV_V, "sceKernelExitGame"}, //() + {0x4AC57943,&WrapU_U,"sceKernelRegisterExitCallback"}, + {0xBD2F1094,&WrapI_CU,"sceKernelLoadExec"}, + {0x2AC9954B,&WrapV_V,"sceKernelExitGameWithStatus"}, }; void Register_LoadExecForUser() diff --git a/Core/HLE/sceKernel.h b/Core/HLE/sceKernel.h index 596d6ce614..858e787bc5 100644 --- a/Core/HLE/sceKernel.h +++ b/Core/HLE/sceKernel.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -261,9 +261,10 @@ struct SceKernelLoadExecParam void __KernelInit(); void __KernelShutdown(); +bool __KernelIsRunning(); bool __KernelLoadExec(const char *filename, SceKernelLoadExecParam *param); -void sceKernelLoadExec(); +int sceKernelLoadExec(const char *filename, u32 paramPtr); void sceKernelRegisterExitCallback(); void sceKernelExitGame(); @@ -286,6 +287,8 @@ void sceKernelDcacheWritebackInvalidateRange(); void sceKernelDcacheWritebackInvalidateAll(); void sceKernelGetThreadStackFreeSize(); void sceKernelIcacheInvalidateAll(); +void sceKernelIcacheClearAll(); + #define KERNELOBJECT_MAX_NAME_LENGTH 31 class KernelObjectPool; @@ -340,7 +343,7 @@ public: { if (handle < handleOffset || handle >= handleOffset+maxCount || !occupied[handle-handleOffset]) { - ERROR_LOG(HLE, "Kernel: Bad object handle"); + ERROR_LOG(HLE, "Kernel: Bad object handle %i (%08x)", handle, handle); outError = T::GetMissingErrorCode(); // ? return 0; } @@ -349,7 +352,7 @@ public: T* t = dynamic_cast(pool[handle - handleOffset]); if (t == 0) { - ERROR_LOG(HLE, "Kernel: Wrong type object"); + ERROR_LOG(HLE, "Kernel: Wrong type object %i (%08x)", handle, handle); outError = T::GetMissingErrorCode(); //FIX return 0; } diff --git a/Core/HLE/sceKernelAlarm.cpp b/Core/HLE/sceKernelAlarm.cpp index 220456000f..8f4cd961b2 100644 --- a/Core/HLE/sceKernelAlarm.cpp +++ b/Core/HLE/sceKernelAlarm.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceKernelAlarm.h b/Core/HLE/sceKernelAlarm.h index ba505a232b..56b004f0fc 100644 --- a/Core/HLE/sceKernelAlarm.h +++ b/Core/HLE/sceKernelAlarm.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceKernelCallback.cpp b/Core/HLE/sceKernelCallback.cpp deleted file mode 100644 index 186617212d..0000000000 --- a/Core/HLE/sceKernelCallback.cpp +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright (c) 2012- PPSSPP Project. - -// 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, version 2.0. - -// 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 2.0 for more details. - -// A copy of the GPL 2.0 should have been included with the program. -// If not, see http://www.gnu.org/licenses/ - -// Official git repository and contact information can be found at -// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. - -// Refer to http://code.google.com/p/yaupspe/source/detail?r=741987a938f87e55ac284f8c2af6d40b4fb30ffc# - -#include "HLE.h" -#include "../MIPS/MIPS.h" -#include "../MIPS/MIPSCodeUtils.h" - -#include "sceKernel.h" -#include "sceKernelThread.h" -#include "sceKernelMemory.h" -#include "sceKernelCallback.h" - - -class Callback : public KernelObject -{ -public: - const char *GetName() {return name;} - const char *GetTypeName() {return "CallBack";} - - void GetQuickInfo(char *ptr, int size) - { - sprintf(ptr, "thread=%i, argument= %08x", - //hackAddress, - threadId, - argument); - } - - ~Callback() - { - // kernelMemory.Free(hackAddress); - } - /* - void GrabAndWriteHack() - { - u32 blockSize = 8; - hackAddress = kernelMemory.Alloc(blockSize); - Memory::Write_U32(MIPS_MAKE_JAL(entrypoint), hackAddress); - Memory::Write_U32(MIPS_MAKE_NOP(), hackAddress+4); - }*/ - - static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_CBID; } - int GetIDType() const { return SCE_KERNEL_TMID_Callback; } - - SceUInt size; - char name[32]; - u32 entrypoint; - SceUID threadId; - u32 argument; - u32 notifyCount; - // u32 hackAddress; - - u32 savedPC; - u32 savedRA; - u32 savedV0; - u32 savedV1; - u32 savedIdRegister; - - int numParameters; - u32 parameters[6]; - - /* - SceUInt attr; - SceUInt initPattern; - SceUInt currentPattern; - int numWaitThreads; - */ - - bool forceDelete; - Action *actionAfter; -}; - -////////////////////////////////////////////////////////////////////////// -// CALLBACKS -////////////////////////////////////////////////////////////////////////// - - -// Internal API -u32 __KernelCreateCallback(const char *name, u32 entrypoint, u32 callbackArg, Action *actionAfter) -{ - Callback *c = new Callback; - SceUID id = kernelObjects.Create(c); - - c->size = sizeof(Callback); - strcpy(c->name, name); - - c->entrypoint = entrypoint; - c->threadId = __KernelGetCurThread(); - c->argument = callbackArg; - c->actionAfter = actionAfter; - - return id; -} - - -//extern Thread *currentThread; -void sceKernelCreateCallback() -{ - u32 entrypoint = PARAM(1); - u32 callbackArg = PARAM(2); - - const char *name = Memory::GetCharPointer(PARAM(0)); - - u32 id = __KernelCreateCallback(name, entrypoint, callbackArg); - - DEBUG_LOG(HLE,"%i=sceKernelCreateCallback(name=%s,entry= %08x, callbackArg = %08x)", id, name, entrypoint, callbackArg); - - RETURN(id); -} - -void sceKernelDeleteCallback() -{ - SceUID id = PARAM(0); - DEBUG_LOG(HLE,"sceKernelDeleteCallback(%i)", id); - RETURN(kernelObjects.Destroy(id)); -} - -void sceKernelNotifyCallback() -{ - SceUID cbid = PARAM(0); - u32 arg = PARAM(1); - DEBUG_LOG(HLE,"sceKernelNotifyCallback(%i, %i)", cbid, arg); - - __KernelNotifyCallback(__KernelGetCurThread(), cbid, arg); - RETURN(0); -} - -void sceKernelCancelCallback() -{ - SceUID cbid = PARAM(0); - ERROR_LOG(HLE,"UNIMPL sceKernelCancelCallback(%i)", cbid); - //__KernelCancelCallback(__KernelGetCurThread(), cbid); - RETURN(0); -} - -void sceKernelGetCallbackCount() -{ - SceUID cbid = PARAM(0); - ERROR_LOG(HLE,"UNIMPL sceKernelGetCallbackCount(%i)", cbid); - - RETURN(0); -} - -void sceKernelReferCallbackStatus() -{ - SceUID cbid = PARAM(0); - u32 statusAddr = PARAM(1); - ERROR_LOG(HLE,"UNIMPL sceKernelReferCallbackStatus(%i, %08x)", cbid, statusAddr); - - RETURN(0); -} - -void __KernelCallCallback(SceUID id) -{ - //First, make sure we're on the right thread - u32 error; - Callback *c = kernelObjects.Get(id, error); - if (c) - { - if (c->threadId == __KernelGetCurThread()) - { - //Alright, we're on the right thread - - // Save the few regs that need saving - c->savedPC = currentMIPS->pc; - c->savedRA = currentMIPS->r[MIPS_REG_RA]; - c->savedV0 = currentMIPS->r[MIPS_REG_V0]; - c->savedV1 = currentMIPS->r[MIPS_REG_V1]; - c->savedIdRegister = currentMIPS->r[MIPS_REG_CB_ID]; - - // Set up the new state - for (int i = 0; i < c->numParameters; c++) - currentMIPS->r[4 + i] = c->parameters[i]; - currentMIPS->pc = c->entrypoint; - currentMIPS->r[MIPS_REG_RA] = __KernelCallbackReturnAddress(); - } - } - else - { - //ARGH! - } -} - -void _sceKernelReturnFromCallback() -{ - SceUID cbid = currentMIPS->r[MIPS_REG_CB_ID]; // yeah! - DEBUG_LOG(HLE,"_sceKernelReturnFromCallback(cbid=%i)", cbid); - // Value returned by the callback function - u32 retVal = currentMIPS->r[MIPS_REG_V0]; - - u32 error; - Callback *cb = kernelObjects.Get(cbid, error); - if (!cb) - { - ERROR_LOG(HLE, "_sceKernelReturnFromCallback(): INVALID CBID in register! we're screwed"); - return; - } - - currentMIPS->pc = cb->savedPC; - currentMIPS->r[MIPS_REG_RA] = cb->savedRA; - currentMIPS->r[MIPS_REG_V0] = cb->savedV0; - currentMIPS->r[MIPS_REG_V1] = cb->savedV1; - currentMIPS->r[MIPS_REG_CB_ID] = cb->savedIdRegister; - - // Callbacks that don't return 0 are deleted. But should this be done here? - if (retVal != 0 || cb->forceDelete) - { - DEBUG_LOG(HLE, "_sceKernelReturnFromCallback(): Callback returned non-zero, gets deleted!"); - kernelObjects.Destroy(cbid); - } - - if (cb->actionAfter) - { - cb->actionAfter->run(); - } - // yeah! back in the real world, let's keep going.... -} - -void sceKernelCheckCallback() -{ - //only check those of current thread - ERROR_LOG(HLE,"UNIMPL sceKernelCheckCallback()"); - - // HACK that makes the audio thread work in Puyo Puyo Fever - the main thread never yields! - // Probably because callbacks aren't working right. - __KernelReSchedule("checkcallbackhack"); - - RETURN(0); -} - diff --git a/Core/HLE/sceKernelEventFlag.cpp b/Core/HLE/sceKernelEventFlag.cpp index f6ea23577f..bd8478ecdc 100644 --- a/Core/HLE/sceKernelEventFlag.cpp +++ b/Core/HLE/sceKernelEventFlag.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -87,30 +87,24 @@ enum PspEventFlagWaitTypes }; //SceUID sceKernelCreateEventFlag(const char *name, int attr, int bits, SceKernelEventFlagOptParam *opt); -void sceKernelCreateEventFlag() +int sceKernelCreateEventFlag(const char *name, u32 flag_attr, u32 flag_initPattern, u32 optPtr) { - const char *name = Memory::GetCharPointer(PARAM(0)); - EventFlag *e = new EventFlag(); SceUID id = kernelObjects.Create(e); e->nef.size = sizeof(NativeEventFlag); strncpy(e->nef.name, name, 32); - e->nef.attr = PARAM(1); - e->nef.initPattern = PARAM(2); + e->nef.attr = flag_attr; + e->nef.initPattern = flag_initPattern; e->nef.currentPattern = e->nef.initPattern; e->nef.numWaitThreads = 0; - DEBUG_LOG(HLE,"%i=sceKernelCreateEventFlag(\"%s\", %08x, %08x, %08x)", id, e->nef.name, e->nef.attr, e->nef.currentPattern, PARAM(3)); - RETURN(id); + DEBUG_LOG(HLE,"%i=sceKernelCreateEventFlag(\"%s\", %08x, %08x, %08x)", id, e->nef.name, e->nef.attr, e->nef.currentPattern, optPtr); + return id; } -//int sceKernelClearEventFlag(SceUID evid, u32 bits); -void sceKernelClearEventFlag() +u32 sceKernelClearEventFlag(SceUID id, u32 bits) { - SceUID id = PARAM(0); - u32 bits = PARAM(1); - u32 error; EventFlag *e = kernelObjects.Get(id, error); if (e) @@ -118,21 +112,19 @@ void sceKernelClearEventFlag() DEBUG_LOG(HLE,"sceKernelClearEventFlag(%i, %08x)", id, bits); e->nef.currentPattern &= bits; // Note that it's not possible for threads to get woken up by this action. - RETURN(0); + return 0; } else { ERROR_LOG(HLE,"sceKernelClearEventFlag(%i, %08x) - error", id, bits); - RETURN(error); + return error; } } -//int sceKernelDeleteEventFlag(int evid); -void sceKernelDeleteEventFlag() +u32 sceKernelDeleteEventFlag(SceUID uid) { - SceUID uid = PARAM(0); DEBUG_LOG(HLE,"sceKernelDeleteEventFlag(%i)", uid); - RETURN(kernelObjects.Destroy(uid)); + return kernelObjects.Destroy(uid); } u8 __KernelEventFlagMatches(u32 *pattern, u32 bits, u8 wait, u32 outAddr) @@ -151,11 +143,8 @@ u8 __KernelEventFlagMatches(u32 *pattern, u32 bits, u8 wait, u32 outAddr) return 0; } -//int sceKernelSetEventFlag(SceUID evid, u32 bits); -void sceKernelSetEventFlag() +u32 sceKernelSetEventFlag(SceUID id, u32 bitsToSet) { - SceUID id = PARAM(0); - u32 bitsToSet = PARAM(1); u32 error; DEBUG_LOG(HLE,"sceKernelSetEventFlag(%i, %08x)", id, bitsToSet); EventFlag *e = kernelObjects.Get(id, error); @@ -171,30 +160,24 @@ retry: EventFlagTh *t = &e->waitingThreads[i]; if (__KernelEventFlagMatches(&e->nef.currentPattern, t->bits, t->wait, t->outAddr)) { - __KernelResumeThread(t->tid); + __KernelResumeThreadFromWait(t->tid); wokeThreads = true; e->nef.numWaitThreads--; e->waitingThreads.erase(e->waitingThreads.begin() + i); goto retry; } } - RETURN(0); + return 0; } else { - RETURN(error); + return error; } } -//int sceKernelWaitEventFlag(SceUID evid, u32 bits, u32 wait, u32 *outBits, SceUInt *timeout); -void sceKernelWaitEventFlag() +// Actually RETURNs a u32 +void sceKernelWaitEventFlag(SceUID id, u32 bits, u32 wait, u32 outBitsPtr, u32 timeoutPtr) { - SceUID id = PARAM(0); - u32 bits = PARAM(1); - u32 wait = PARAM(2); - u32 outBitsPtr = PARAM(3); - u32 timeoutPtr = PARAM(4); - DEBUG_LOG(HLE,"sceKernelWaitEventFlag(%i, %08x, %i, %08x, %08x)", id, bits, wait, outBitsPtr, timeoutPtr); u32 error; @@ -215,9 +198,9 @@ void sceKernelWaitEventFlag() if (Memory::IsValidAddress(timeoutPtr)) timeout = Memory::Read_U32(timeoutPtr); - __KernelWaitCurThread(WAITTYPE_EVENTFLAG, id, 0, 0, false); + __KernelWaitCurThread(WAITTYPE_EVENTFLAG, id, 0, 0, false); // sets RETURN + // Do not set RETURN here; it's already set for us and we'd overwrite the wrong thread's RETURN } - RETURN(0); } else { @@ -225,15 +208,9 @@ void sceKernelWaitEventFlag() } } -//int sceKernelWaitEventFlagCB(SceUID evid, u32 bits, u32 wait, u32 *outBits, SceUInt *timeout); -void sceKernelWaitEventFlagCB() +// Actually RETURNs a u32 +void sceKernelWaitEventFlagCB(SceUID id, u32 bits, u32 wait, u32 outBitsPtr, u32 timeoutPtr) { - SceUID id = PARAM(0); - u32 bits = PARAM(1); - u32 wait = PARAM(2); - u32 outBitsPtr = PARAM(3); - u32 timeoutPtr = PARAM(4); - DEBUG_LOG(HLE,"sceKernelWaitEventFlagCB(%i, %08x, %i, %08x, %08x)", id, bits, wait, outBitsPtr, timeoutPtr); u32 error; @@ -254,9 +231,9 @@ void sceKernelWaitEventFlagCB() if (Memory::IsValidAddress(timeoutPtr)) timeout = Memory::Read_U32(timeoutPtr); - __KernelWaitCurThread(WAITTYPE_EVENTFLAG, id, 0, 0, true); + __KernelWaitCurThread(WAITTYPE_EVENTFLAG, id, 0, 0, true); // sets RETURN + __KernelCheckCallbacks(); } - RETURN(0); } else { @@ -264,15 +241,8 @@ void sceKernelWaitEventFlagCB() } } -//int sceKernelPollEventFlag(int evid, u32 bits, u32 wait, u32 *outBits); -void sceKernelPollEventFlag() +int sceKernelPollEventFlag(SceUID id, u32 bits, u32 wait, u32 outBitsPtr, u32 timeoutPtr) { - SceUID id = PARAM(0); - u32 bits = PARAM(1); - u32 wait = PARAM(2); - u32 outBitsPtr = PARAM(3); - u32 timeoutPtr = PARAM(4); - DEBUG_LOG(HLE,"sceKernelPollEventFlag(%i, %08x, %i, %08x, %08x)", id, bits, wait, outBitsPtr, timeoutPtr); u32 error; @@ -284,42 +254,39 @@ void sceKernelPollEventFlag() if (Memory::IsValidAddress(outBitsPtr)) Memory::Write_U32(e->nef.currentPattern, outBitsPtr); // No match - return that, this is polling, not waiting. - RETURN(SCE_KERNEL_ERROR_EVF_COND); + return SCE_KERNEL_ERROR_EVF_COND; } else { - RETURN(0); + return 0; } } else { - RETURN(error); + return error; } } //int sceKernelReferEventFlagStatus(SceUID event, SceKernelEventFlagInfo *status); -void sceKernelReferEventFlagStatus() +u32 sceKernelReferEventFlagStatus(SceUID id, u32 statusPtr) { - SceUID id = PARAM(0); - u32 statusAddr = PARAM(1); - - DEBUG_LOG(HLE,"sceKernelReferEventFlagStatus(%i, %08x)", id, statusAddr); + DEBUG_LOG(HLE,"sceKernelReferEventFlagStatus(%i, %08x)", id, statusPtr); u32 error; EventFlag *e = kernelObjects.Get(id, error); if (e) { - Memory::WriteStruct(statusAddr, &e->nef); - RETURN(0); + Memory::WriteStruct(statusPtr, &e->nef); + return 0; } else { - RETURN(error); + return error; } } // never seen this one -void sceKernelCancelEventFlag() +u32 sceKernelCancelEventFlag() { ERROR_LOG(HLE,"UNIMPL: sceKernelCancelEventFlag()"); - RETURN(0); + return 0; } diff --git a/Core/HLE/sceKernelEventFlag.h b/Core/HLE/sceKernelEventFlag.h index ccae315d0e..3b4c98ae96 100644 --- a/Core/HLE/sceKernelEventFlag.h +++ b/Core/HLE/sceKernelEventFlag.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -17,12 +17,12 @@ #pragma once -void sceKernelCreateEventFlag(); -void sceKernelClearEventFlag(); -void sceKernelDeleteEventFlag(); -void sceKernelSetEventFlag(); -void sceKernelWaitEventFlag(); -void sceKernelWaitEventFlagCB(); -void sceKernelPollEventFlag(); -void sceKernelCancelEventFlag(); -void sceKernelReferEventFlagStatus(); +int sceKernelCreateEventFlag(const char *name, u32 flag_attr, u32 flag_initPattern, u32 optPtr); +u32 sceKernelClearEventFlag(SceUID id, u32 bits); +u32 sceKernelDeleteEventFlag(SceUID uid); +u32 sceKernelSetEventFlag(SceUID id, u32 bitsToSet); +void sceKernelWaitEventFlag(SceUID id, u32 bits, u32 wait, u32 outBitsPtr, u32 timeoutPtr); +void sceKernelWaitEventFlagCB(SceUID id, u32 bits, u32 wait, u32 outBitsPtr, u32 timeoutPtr); +int sceKernelPollEventFlag(SceUID id, u32 bits, u32 wait, u32 outBitsPtr, u32 timeoutPtr); +u32 sceKernelReferEventFlagStatus(SceUID id, u32 statusPtr); +u32 sceKernelCancelEventFlag(); \ No newline at end of file diff --git a/Core/HLE/sceKernelInterrupt.cpp b/Core/HLE/sceKernelInterrupt.cpp index 8e1f8a12e0..c872d68906 100644 --- a/Core/HLE/sceKernelInterrupt.cpp +++ b/Core/HLE/sceKernelInterrupt.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -35,6 +35,8 @@ struct Interrupt // Yeah, this bit is a bit silly. static int interruptsEnabled = 1; +static bool inInterrupt; + void __InterruptsInit() { interruptsEnabled = 1; @@ -60,8 +62,6 @@ bool __InterruptsEnabled() } - - // InterruptsManager ////////////////////////////////////////////////////////////////////////// // INTERRUPT MANAGEMENT @@ -116,8 +116,6 @@ void sceKernelCpuResumeIntrWithSync(u32 enable) -static bool inInterrupt; - bool __IsInInterrupt() { return inInterrupt; @@ -128,30 +126,55 @@ bool __CanExecuteInterrupt() return !inInterrupt; } +class AllegrexInterruptHandler; + +struct PendingInterrupt { + AllegrexInterruptHandler *handler; + int arg; + bool hasArg; +}; + class AllegrexInterruptHandler { public: virtual ~AllegrexInterruptHandler() {} - virtual void copyArgsToCPU() = 0; + virtual void copyArgsToCPU(const PendingInterrupt &pend) = 0; virtual void queueUp() = 0; + virtual void queueUpWithArg(int arg) = 0; }; - -std::list pendingInterrupts; +std::list pendingInterrupts; class SubIntrHandler : public AllegrexInterruptHandler { public: - virtual void queueUp() + SubIntrHandler() {} + virtual void queueUp() { - pendingInterrupts.push_back(this); + if (!enabled) + return; + PendingInterrupt pend; + pend.handler = this; + pend.hasArg = false; + pendingInterrupts.push_back(pend); + } + virtual void queueUpWithArg(int arg) + { + if (!enabled) + return; + PendingInterrupt pend; + pend.handler = this; + pend.arg = arg; + pend.hasArg = true; + pendingInterrupts.push_back(pend); } - virtual void copyArgsToCPU() + virtual void copyArgsToCPU(const PendingInterrupt &pend) { + DEBUG_LOG(CPU, "Entering interrupt handler %08x", handlerAddress); currentMIPS->pc = handlerAddress; - currentMIPS->r[MIPS_REG_A0] = number; + currentMIPS->r[MIPS_REG_A0] = pend.hasArg ? pend.arg : number; currentMIPS->r[MIPS_REG_A1] = handlerArg; // RA is already taken care of } @@ -162,8 +185,6 @@ public: u32 handlerArg; }; - - class IntrHandler { public: void add(int subIntrNum, SubIntrHandler handler) @@ -185,13 +206,25 @@ public: // what to do, what to do... } - void queueUp() + void queueUp(int subintr) { // Just call execute on all the subintr handlers for this interrupt. // They will get queued up. for (std::map::iterator iter = subIntrHandlers.begin(); iter != subIntrHandlers.end(); ++iter) { - iter->second.queueUp(); + if (subintr == -1 || iter->first == subintr) + iter->second.queueUp(); + } + } + + void queueUpWithArg(int subintr, int arg) + { + // Just call execute on all the subintr handlers for this interrupt. + // They will get queued up. + for (std::map::iterator iter = subIntrHandlers.begin(); iter != subIntrHandlers.end(); ++iter) + { + if (subintr == -1 || iter->first == subintr) + iter->second.queueUpWithArg(arg); } } @@ -242,13 +275,13 @@ bool __RunOnePendingInterrupt() // Can easily prioritize between different kinds of interrupts if necessary. if (pendingInterrupts.size()) { - AllegrexInterruptHandler *front = pendingInterrupts.front(); + PendingInterrupt pend = pendingInterrupts.front(); pendingInterrupts.pop_front(); intState.save(); - front->copyArgsToCPU(); + pend.handler->copyArgsToCPU(pend); + currentMIPS->r[MIPS_REG_RA] = __KernelInterruptReturnAddress(); inInterrupt = true; - DEBUG_LOG(CPU, "Entering interrupt handler"); return true; } else @@ -258,17 +291,25 @@ bool __RunOnePendingInterrupt() } } -void __TriggerInterrupt(PSPInterrupt intno) +void __TriggerInterrupt(PSPInterrupt intno, int subintr) { - intrHandlers[intno].queueUp(); - DEBUG_LOG(HLE, "Triggering subinterrupts for interrupt %i (%i in queue)", intno, (int)pendingInterrupts.size()); + intrHandlers[intno].queueUp(subintr); + DEBUG_LOG(HLE, "Triggering subinterrupts for interrupt %i sub %i (%i in queue)", intno, subintr, pendingInterrupts.size()); if (!inInterrupt) __RunOnePendingInterrupt(); } -void _sceKernelReturnFromInterrupt() +void __TriggerInterruptWithArg(PSPInterrupt intno, int subintr, int arg) { - DEBUG_LOG(CPU, "Left interrupt handler"); + intrHandlers[intno].queueUpWithArg(subintr, arg); + DEBUG_LOG(HLE, "Triggering subinterrupts for interrupt %i sub %i with arg %i (%i in queue)", intno, subintr, arg, pendingInterrupts.size()); + if (!inInterrupt) + __RunOnePendingInterrupt(); +} + +void __KernelReturnFromInterrupt() +{ + DEBUG_LOG(CPU, "Left interrupt handler at %08x", currentMIPS->pc); inInterrupt = false; // Restore context after running the interrupt. intState.restore(); @@ -296,7 +337,6 @@ u32 sceKernelRegisterSubIntrHandler(u32 intrNumber, u32 subIntrNumber, u32 handl subIntrHandler.handlerAddress = handler; subIntrHandler.handlerArg = handlerArg; intrHandlers[intrNumber].add(subIntrNumber, subIntrHandler); - return 0; } @@ -318,8 +358,8 @@ u32 sceKernelReleaseSubIntrHandler(u32 intrNumber, u32 subIntrNumber) u32 sceKernelEnableSubIntr(u32 intrNumber, u32 subIntrNumber) { - ERROR_LOG(HLE,"sceKernelEnableSubIntr(%i, %i)", intrNumber, subIntrNumber); - if (intrNumber >= PSP_NUMBER_INTERRUPTS) + DEBUG_LOG(HLE,"sceKernelEnableSubIntr(%i, %i)", intrNumber, subIntrNumber); + if (intrNumber < 0 || intrNumber >= PSP_NUMBER_INTERRUPTS) return -1; if (!intrHandlers[intrNumber].has(subIntrNumber)) @@ -331,8 +371,8 @@ u32 sceKernelEnableSubIntr(u32 intrNumber, u32 subIntrNumber) u32 sceKernelDisableSubIntr(u32 intrNumber, u32 subIntrNumber) { - ERROR_LOG(HLE,"sceKernelDisableSubIntr(%i, %i)", intrNumber, subIntrNumber); - if (intrNumber >= PSP_NUMBER_INTERRUPTS) + DEBUG_LOG(HLE,"sceKernelDisableSubIntr(%i, %i)", intrNumber, subIntrNumber); + if (intrNumber < 0 || intrNumber >= PSP_NUMBER_INTERRUPTS) return -1; if (!intrHandlers[intrNumber].has(subIntrNumber)) @@ -343,8 +383,6 @@ u32 sceKernelDisableSubIntr(u32 intrNumber, u32 subIntrNumber) } - - struct PspIntrHandlerOptionParam { int size; //+00 u32 entry; //+04 @@ -388,9 +426,12 @@ const HLEFunction Kernel_Library[] = {0x47a0b729,sceKernelIsCpuIntrSuspended, "sceKernelIsCpuIntrSuspended"}, //flags {0xb55249d2,sceKernelIsCpuIntrEnable, "sceKernelIsCpuIntrEnable"}, {0xa089eca4,sceKernelMemset, "sceKernelMemset"}, + {0xDC692EE3,0, "sceKernelTryLockLwMutex"}, + {0x37431849,0, "sceKernelTryLockLwMutex_600"}, {0xbea46419,0, "sceKernelLockLwMutex"}, + {0x1FC64E09,0, "sceKernelLockLwMutexCB"}, {0x15b6446b,0, "sceKernelUnlockLwMutex"}, - {0x293b45b8,0, "sceKernelGetThreadId"}, + {0x293b45b8,sceKernelGetThreadId, "sceKernelGetThreadId"}, {0x1839852A,0,"sce_paf_private_memcpy"}, {0xA089ECA4,0,"sce_paf_private_memset"}, }; diff --git a/Core/HLE/sceKernelInterrupt.h b/Core/HLE/sceKernelInterrupt.h index a912cfa17f..adc13e5bcd 100644 --- a/Core/HLE/sceKernelInterrupt.h +++ b/Core/HLE/sceKernelInterrupt.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -57,10 +57,14 @@ enum PSPGeSubInterrupts { bool __IsInInterrupt(); void __InterruptsInit(); void __InterruptsShutdown(); -void __TriggerInterrupt(PSPInterrupt intno); +void __TriggerInterrupt(PSPInterrupt intno, int subInterrupts = -1); +void __TriggerInterruptWithArg(PSPInterrupt intno, int subintr, int arg); // For GE "callbacks" +bool __RunOnePendingInterrupt(); +void __KernelReturnFromInterrupt(); -void _sceKernelReturnFromInterrupt(); u32 sceKernelRegisterSubIntrHandler(u32 intrNumber, u32 subIntrNumber, u32 handler, u32 handlerArg); +u32 sceKernelReleaseSubIntrHandler(u32 intrNumber, u32 subIntrNumber); +u32 sceKernelEnableSubIntr(u32 intrNumber, u32 subIntrNumber); void Register_Kernel_Library(); void Register_InterruptManager(); diff --git a/Core/HLE/sceKernelMbx.cpp b/Core/HLE/sceKernelMbx.cpp index 5fe5cf4137..beb29cad3c 100644 --- a/Core/HLE/sceKernelMbx.cpp +++ b/Core/HLE/sceKernelMbx.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -16,17 +16,14 @@ // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. #include "sceKernel.h" +#include "sceKernelThread.h" #include "sceKernelMbx.h" #include "HLE.h" -struct NativeMbxPacket -{ - u32 next; - u8 priority; - u8 padding[3]; +#define SCE_KERNEL_MBA_THPRI 0x100 +#define SCE_KERNEL_MBA_MSPRI 0x400 - // data follows -}; +// TODO: when a thread is being resumed (message received or cancellation), sceKernelReceiveMbx() always returns 0 struct NativeMbx { @@ -45,20 +42,34 @@ struct Mbx : public KernelObject static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_MBXID; } int GetIDType() const { return SCE_KERNEL_TMID_Mbox; } + void AddWaitingThread(SceUID id, u32 addr) + { + if (nmb.attr & SCE_KERNEL_MBA_THPRI) + { + for (std::vector>::iterator it = waitingThreads.begin(); it != waitingThreads.end(); it++) + { + if (__KernelGetThreadPrio(id) >= __KernelGetThreadPrio((*it).first)) + { + waitingThreads.insert(it, std::make_pair(id, addr)); + break; + } + } + } + else + { + waitingThreads.push_back(std::make_pair(id, addr)); + } + } + NativeMbx nmb; - std::vector receiveWaitingThreads; + std::vector> waitingThreads; + std::vector messageQueue; }; -void sceKernelCreateMbx() +SceUID sceKernelCreateMbx(const char *name, int memoryPartition, SceUInt attr, int size, u32 optAddr) { - const char *name = Memory::GetCharPointer(PARAM(0)); - int memoryPartition = PARAM(1); - SceUInt attr = PARAM(2); - int size = PARAM(3); - int opt = PARAM(4); - - ERROR_LOG(HLE, "sceKernelCreateMbx(%s, %i, %08x, %i, %08x)", name, memoryPartition, attr, size, opt); + DEBUG_LOG(HLE, "sceKernelCreateMbx(%s, %i, %08x, %i, %08x)", name, memoryPartition, attr, size, optAddr); Mbx *m = new Mbx(); SceUID id = kernelObjects.Create(m); @@ -70,88 +81,230 @@ void sceKernelCreateMbx() m->nmb.numMessages = 0; m->nmb.packetListHead = 0; - RETURN(id); + return id; } -void sceKernelDeleteMbx() +int sceKernelDeleteMbx(SceUID id) { - SceUInt uid = PARAM(0); - ERROR_LOG(HLE, "sceKernelDeleteMbx(%i)", uid); - RETURN(kernelObjects.Destroy(uid)); -} - -void sceKernelSendMbx() -{ - SceUInt uid = PARAM(0); - u32 packetAddr = PARAM(1); - - ERROR_LOG(HLE, "UNIMPL sceKernelSendMbx(%i, %08x)", uid, packetAddr); - RETURN(0); -} - -void sceKernelReceiveMbx() -{ - SceUInt uid = PARAM(0); - u32 packetAddrPtr = PARAM(1); - u32 timeoutPtr = PARAM(2); - - ERROR_LOG(HLE, "UNIMPL sceKernelReceiveMbx(%i, %08x, %08x)", uid, packetAddrPtr, timeoutPtr); - RETURN(0); -} - -void sceKernelReceiveMbxCB() -{ - SceUInt uid = PARAM(0); - u32 packetAddrPtr = PARAM(1); - u32 timeoutPtr = PARAM(2); - - ERROR_LOG(HLE, "UNIMPL sceKernelReceiveMbxCB(%i, %08x, %08x)", uid, packetAddrPtr, timeoutPtr); - RETURN(0); -} - -void sceKernelPollMbx() -{ - SceUInt uid = PARAM(0); - u32 packetAddrPtr = PARAM(1); - - ERROR_LOG(HLE, "UNIMPL sceKernelPollMbx(%i, %08x)", uid, packetAddrPtr); - RETURN(0); -} - -void sceKernelCancelReceiveMbx() -{ - SceUInt uid = PARAM(0); - int numWaitingThreadsAddr = PARAM(1); - - ERROR_LOG(HLE, "UNIMPL sceKernelCancelReceiveMbx(%i, %i)", uid, numWaitingThreadsAddr); - RETURN(0); -} - -void sceKernelCancelMbx() -{ - SceUInt uid = PARAM(0); - u32 numSendThreads = PARAM(1); - u32 numReceiveThreads = PARAM(2); - - ERROR_LOG(HLE, "UNIMPL sceKernelCancelMbx(%i, %i, %i)", uid, numSendThreads, numReceiveThreads); - RETURN(0); -} - -void sceKernelReferMbxStatus() -{ - SceUInt uid = PARAM(0); - u32 mbxStatusAddr = PARAM(1); - - ERROR_LOG(HLE, "sceKernelReferMbxStatus(%i, %08x)", uid, mbxStatusAddr); u32 error; - Mbx *mp = kernelObjects.Get(uid, error); - if (mp) + Mbx *m = kernelObjects.Get(id, error); + if (m) { - Memory::WriteStruct(mbxStatusAddr, &mp->nmb); + DEBUG_LOG(HLE, "sceKernelDeleteMbx(%i)", id); + for (size_t i = 0; i < m->waitingThreads.size(); i++) + { + Memory::Write_U32(0, m->waitingThreads[i].second); + __KernelResumeThreadFromWait(m->waitingThreads[i].first); + } + } + else + { + ERROR_LOG(HLE, "sceKernelDeleteMbx(%i): invalid mbx id", id); + } + return kernelObjects.Destroy(id); +} + +void sceKernelSendMbx(SceUID id, u32 packetAddr) +{ + u32 error; + Mbx *m = kernelObjects.Get(id, error); + NativeMbxPacket *addPacket = (NativeMbxPacket*)Memory::GetPointer(packetAddr); + if (addPacket == 0) + { + ERROR_LOG(HLE, "sceKernelSendMbx(%i, %08x): invalid packet address", id, packetAddr); + RETURN(-1); + return; + } + + if (!m) + { + ERROR_LOG(HLE, "sceKernelSendMbx(%i, %08x): invalid mbx id", id, packetAddr); + RETURN(error); + return; + } + + if (m->waitingThreads.empty()) + { + DEBUG_LOG(HLE, "sceKernelSendMbx(%i, %08x): no threads currently waiting, adding message to queue", id, packetAddr); + if (m->nmb.attr & SCE_KERNEL_MBA_MSPRI) + { + for (std::vector::iterator it = m->messageQueue.begin(); it != m->messageQueue.end(); it++) + { + NativeMbxPacket *p = (NativeMbxPacket*)Memory::GetPointer(*it); + if (addPacket->priority >= p->priority) + { + m->messageQueue.insert(it, packetAddr); + break; + } + } + } + else + { + m->messageQueue.push_back(packetAddr); + } + RETURN(0); + } + else if (m->messageQueue.empty()) + { + Memory::Write_U32(packetAddr, m->waitingThreads.front().second); + __KernelResumeThreadFromWait(m->waitingThreads.front().first); + DEBUG_LOG(HLE, "sceKernelSendMbx(%i, %08x): threads waiting, resuming %d", id, packetAddr, m->waitingThreads.front().first); + m->waitingThreads.erase(m->waitingThreads.begin()); + RETURN(0); + __KernelReSchedule(); + } + else + { + ERROR_LOG(HLE, "sceKernelSendMbx(%i, %08x): WTF!? thread waiting while there is a message in the queue?", id, packetAddr); + RETURN(-1); + } +} + +void sceKernelReceiveMbx(SceUID id, u32 packetAddrPtr, u32 timeoutPtr) +{ + u32 error; + Mbx *m = kernelObjects.Get(id, error); + + if (!m) + { + ERROR_LOG(HLE, "sceKernelReceiveMbx(%i, %08x, %08x): invalid mbx id", id, packetAddrPtr, timeoutPtr); + RETURN(error); + return; + } + + if (!m->messageQueue.empty()) + { + DEBUG_LOG(HLE, "sceKernelReceiveMbx(%i, %08x, %08x): sending first queue message", id, packetAddrPtr, timeoutPtr); + Memory::Write_U32(m->messageQueue.front(), packetAddrPtr); + m->messageQueue.erase(m->messageQueue.begin()); RETURN(0); } else { - RETURN(error); + DEBUG_LOG(HLE, "sceKernelReceiveMbx(%i, %08x, %08x): no message in queue, waiting", id, packetAddrPtr, timeoutPtr); + m->AddWaitingThread(__KernelGetCurThread(), packetAddrPtr); + RETURN(0); + __KernelWaitCurThread(WAITTYPE_MBX, 0, 0, 0, false); // ? } } + +void sceKernelReceiveMbxCB(SceUID id, u32 packetAddrPtr, u32 timeoutPtr) +{ + u32 error; + Mbx *m = kernelObjects.Get(id, error); + __KernelCheckCallbacks(); + + if (!m) + { + ERROR_LOG(HLE, "sceKernelReceiveMbxCB(%i, %08x, %08x): invalid mbx id", id, packetAddrPtr, timeoutPtr); + RETURN(error); + return; + } + + if (!m->messageQueue.empty()) + { + DEBUG_LOG(HLE, "sceKernelReceiveMbxCB(%i, %08x, %08x): sending first queue message", id, packetAddrPtr, timeoutPtr); + Memory::Write_U32(m->messageQueue.front(), packetAddrPtr); + m->messageQueue.erase(m->messageQueue.begin()); + RETURN(0); + } + else + { + DEBUG_LOG(HLE, "sceKernelReceiveMbxCB(%i, %08x, %08x): no message in queue, waiting", id, packetAddrPtr, timeoutPtr); + m->AddWaitingThread(id, packetAddrPtr); + RETURN(0); + __KernelWaitCurThread(WAITTYPE_MBX, 0, 0, 0, true); // ? + } +} + +int sceKernelPollMbx(SceUID id, u32 packetAddrPtr) +{ + u32 error; + Mbx *m = kernelObjects.Get(id, error); + + if (!m) + { + ERROR_LOG(HLE, "sceKernelPollMbx(%i, %08x): invalid mbx id", id, packetAddrPtr); + return error; + } + + if (!m->messageQueue.empty()) + { + DEBUG_LOG(HLE, "sceKernelPollMbx(%i, %08x): sending first queue message", id, packetAddrPtr); + Memory::Write_U32(m->messageQueue.front(), packetAddrPtr); + m->messageQueue.erase(m->messageQueue.begin()); + return 0; + } + else + { + DEBUG_LOG(HLE, "SCE_KERNEL_ERROR_MBOX_NOMSG=sceKernelPollMbx(%i, %08x): no message in queue", id, packetAddrPtr); + return SCE_KERNEL_ERROR_MBOX_NOMSG; + } +} + +int sceKernelCancelReceiveMbx(SceUID id, u32 numWaitingThreadsAddr) +{ + u32 error; + Mbx *m = kernelObjects.Get(id, error); + int *numWaitingThreads = (int*)Memory::GetPointer(numWaitingThreadsAddr); + + if (!m) + { + ERROR_LOG(HLE, "sceKernelCancelReceiveMbx(%i, %08x): invalid mbx id", id, numWaitingThreadsAddr); + return error; + } + + u32 count = m->waitingThreads.size(); + DEBUG_LOG(HLE, "sceKernelCancelReceiveMbx(%i, %08x): cancelling %d threads", id, numWaitingThreadsAddr, count); + for (size_t i = 0; i < m->waitingThreads.size(); i++) + { + Memory::Write_U32(0, m->waitingThreads[i].second); + __KernelResumeThreadFromWait(m->waitingThreads[i].first); + } + m->waitingThreads.clear(); + if (numWaitingThreads) + *numWaitingThreads = count; + return 0; +} + +int sceKernelReferMbxStatus(SceUID id, u32 infoAddr) +{ + u32 error; + Mbx *m = kernelObjects.Get(id, error); + if (!m) + { + ERROR_LOG(HLE, "sceKernelReferMbxStatus(%i, %08x): invalid mbx id", id, infoAddr); + return error; + } + + SceKernelMbxInfo *info = (SceKernelMbxInfo*)Memory::GetPointer(infoAddr); + DEBUG_LOG(HLE, "sceKernelReferMbxStatus(%i, %08x)", id, infoAddr); + if (info) + { + strncpy(info->name, m->nmb.name, 32); + info->attr = m->nmb.attr; + info->numWaitThreads = m->waitingThreads.size(); + info->numMessage = m->messageQueue.size(); + // Fill the 'next' parameter of packets which we don't use by default but could be used by a game + if (m->messageQueue.size() != 0) + { + info->topPacketAddr = m->messageQueue[0]; + for (u32 i = 0; i < m->messageQueue.size() - 1; i++) + { + Memory::Write_U32(m->messageQueue[i + 1], Memory::Read_U32(m->messageQueue[i])); + } + Memory::Write_U32(m->messageQueue[m->messageQueue.size() - 1], 0); + } + else + { + info->topPacketAddr = 0; + } + } + else + { + return -1; + } + + return 0; +} + diff --git a/Core/HLE/sceKernelMbx.h b/Core/HLE/sceKernelMbx.h index aff43115da..e841dcb6d0 100644 --- a/Core/HLE/sceKernelMbx.h +++ b/Core/HLE/sceKernelMbx.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -17,11 +17,29 @@ #pragma once -void sceKernelCreateMbx(); -void sceKernelDeleteMbx(); -void sceKernelSendMbx(); -void sceKernelReceiveMbx(); -void sceKernelReceiveMbxCB(); -void sceKernelPollMbx(); -void sceKernelCancelReceiveMbx(); -void sceKernelReferMbxStatus(); \ No newline at end of file +struct NativeMbxPacket +{ + u32 next; + u8 priority; + u8 padding[3]; +}; + +struct SceKernelMbxInfo +{ + SceSize size; + char name[KERNELOBJECT_MAX_NAME_LENGTH+1]; + SceUInt attr; + int numWaitThreads; + int numMessage; + u32 topPacketAddr; +}; + +SceUID sceKernelCreateMbx(const char *name, int memoryPartition, SceUInt attr, int size, u32 optAddr); +int sceKernelDeleteMbx(SceUID id); +void sceKernelSendMbx(SceUID id, u32 addPacketAddr); +void sceKernelReceiveMbx(SceUID id, u32 packetAddrPtr, u32 timeoutPtr); +void sceKernelReceiveMbxCB(SceUID id, u32 packetAddrPtr, u32 timeoutPtr); +int sceKernelPollMbx(SceUID id, u32 packetAddrPtr); +int sceKernelCancelReceiveMbx(SceUID id, u32 numWaitingThreadsAddr); +int sceKernelReferMbxStatus(SceUID id, u32 infoAddr); + diff --git a/Core/HLE/sceKernelMemory.cpp b/Core/HLE/sceKernelMemory.cpp index 6ca8848d97..1493ad565a 100644 --- a/Core/HLE/sceKernelMemory.cpp +++ b/Core/HLE/sceKernelMemory.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -27,8 +27,8 @@ ////////////////////////////////////////////////////////////////////////// // STATE BEGIN -BlockAllocator userMemory; -BlockAllocator kernelMemory; +BlockAllocator userMemory(256); +BlockAllocator kernelMemory(256); // STATE END ////////////////////////////////////////////////////////////////////////// @@ -39,6 +39,7 @@ struct NativeFPL char name[KERNELOBJECT_MAX_NAME_LENGTH+1]; SceUID mpid; u32 attr; + int blocksize; int numBlocks; int numFreeBlocks; @@ -53,8 +54,31 @@ struct FPL : KernelObject static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_FPLID; } int GetIDType() const { return SCE_KERNEL_TMID_Fpl; } NativeFPL nf; - bool *freeBlocks; + bool *blocks; u32 address; + + int findFreeBlock() { + for (int i = 0; i < nf.numBlocks; i++) { + if (!blocks[i]) + return i; + } + return -1; + } + + int allocateBlock() { + int block = findFreeBlock(); + if (block >= 0) + blocks[block] = true; + return block; + } + + bool freeBlock(int b) { + if (blocks[b]) { + blocks[b] = false; + return true; + } + return false; + } }; struct SceKernelVplInfo @@ -65,7 +89,6 @@ struct SceKernelVplInfo int poolSize; int freeSize; int numWaitThreads; - }; struct VPL : KernelObject @@ -110,7 +133,9 @@ void sceKernelCreateFpl() u32 totalSize = blockSize * numBlocks; - u32 address = userMemory.Alloc(totalSize, false, "FPL"); + bool atEnd = false; // attr can change this I think + + u32 address = userMemory.Alloc(totalSize, atEnd, "FPL"); if (address == (u32)-1) { DEBUG_LOG(HLE,"sceKernelCreateFpl(\"%s\", partition=%i, attr=%i, bsize=%i, nb=%i) FAILED - out of ram", @@ -124,16 +149,15 @@ void sceKernelCreateFpl() strncpy(fpl->nf.name, name, 32); fpl->nf.size = sizeof(fpl->nf); - fpl->nf.mpid = mpid; //partition + fpl->nf.mpid = mpid; // partition fpl->nf.attr = attr; fpl->nf.blocksize = blockSize; fpl->nf.numBlocks = numBlocks; fpl->nf.numWaitThreads = 0; - fpl->freeBlocks = new bool[fpl->nf.numBlocks]; - + fpl->blocks = new bool[fpl->nf.numBlocks]; + memset(fpl->blocks, 0, fpl->nf.numBlocks * sizeof(bool)); fpl->address = address; - memset(fpl->freeBlocks, 0, fpl->nf.numBlocks * sizeof(bool)); DEBUG_LOG(HLE,"%i=sceKernelCreateFpl(\"%s\", partition=%i, attr=%i, bsize=%i, nb=%i)", id, name, mpid, attr, blockSize, numBlocks); @@ -166,12 +190,23 @@ void sceKernelAllocateFpl() { u32 blockPtrAddr = PARAM(1); int timeOut = PARAM(2); - DEBUG_LOG(HLE,"FAKEY sceKernelAllocateFpl(%i, %08x, %i)", id, PARAM(1), timeOut); - Memory::Write_U32(fpl->address, blockPtrAddr); + + int blockNum = fpl->allocateBlock(); + if (blockNum >= 0) { + u32 blockPtr = fpl->address + fpl->nf.blocksize * blockNum; + Memory::Write_U32(blockPtr, blockPtrAddr); + RETURN(0); + } else { + // TODO: Should block! + RETURN(0); + } + + DEBUG_LOG(HLE,"sceKernelAllocateFpl(%i, %08x, %i)", id, blockPtrAddr, timeOut); RETURN(0); } else { + DEBUG_LOG(HLE,"ERROR: sceKernelAllocateFpl(%i)", id); RETURN(error); } } @@ -179,15 +214,28 @@ void sceKernelAllocateFpl() void sceKernelAllocateFplCB() { SceUID id = PARAM(0); - DEBUG_LOG(HLE,"UNIMPL: sceKernelAllocateFplCB(%i)", id); u32 error; FPL *fpl = kernelObjects.Get(id, error); if (fpl) { - RETURN(0); + u32 blockPtrAddr = PARAM(1); + int timeOut = PARAM(2); + + int blockNum = fpl->allocateBlock(); + if (blockNum >= 0) { + u32 blockPtr = fpl->address + fpl->nf.blocksize * blockNum; + Memory::Write_U32(blockPtr, blockPtrAddr); + RETURN(0); + } else { + // TODO: Should block and process callbacks! + __KernelCheckCallbacks(); + } + + DEBUG_LOG(HLE,"sceKernelAllocateFpl(%i, %08x, %i)", id, PARAM(1), timeOut); } else { + DEBUG_LOG(HLE,"ERROR: sceKernelAllocateFplCB(%i)", id); RETURN(error); } } @@ -195,18 +243,25 @@ void sceKernelAllocateFplCB() void sceKernelTryAllocateFpl() { SceUID id = PARAM(0); - DEBUG_LOG(HLE,"BAD sceKernelTryAllocateFpl(%i)", id); u32 error; FPL *fpl = kernelObjects.Get(id, error); if (fpl) { u32 blockPtrAddr = PARAM(1); DEBUG_LOG(HLE,"sceKernelTryAllocateFpl(%i, %08x)", id, PARAM(1)); - Memory::Write_U32(fpl->address, blockPtrAddr); - RETURN(0); + + int blockNum = fpl->allocateBlock(); + if (blockNum >= 0) { + u32 blockPtr = fpl->address + fpl->nf.blocksize * blockNum; + Memory::Write_U32(blockPtr, blockPtrAddr); + RETURN(0); + } else { + RETURN(SCE_KERNEL_ERROR_NO_MEMORY); + } } else { + DEBUG_LOG(HLE,"sceKernelTryAllocateFpl(%i) - bad UID", id); RETURN(error); } } @@ -214,12 +269,21 @@ void sceKernelTryAllocateFpl() void sceKernelFreeFpl() { SceUID id = PARAM(0); - ERROR_LOG(HLE,"UNIMPL: sceKernelFreeFpl(%i)", id); + u32 blockAddr = PARAM(1); + + DEBUG_LOG(HLE,"sceKernelFreeFpl(%i, %08x)", id, blockAddr); u32 error; FPL *fpl = kernelObjects.Get(id, error); - if (fpl) - { - RETURN(0); + if (fpl) { + int blockNum = (blockAddr - fpl->address) / fpl->nf.blocksize; + if (blockNum < 0 || blockNum >= fpl->nf.numBlocks) { + RETURN(SCE_KERNEL_ERROR_ILLEGAL_MEMBLOCK); + } else { + if (fpl->freeBlock(blockNum)) { + // TODO: If there are waiting threads, wake them up + } + RETURN(0); + } } else { @@ -285,7 +349,7 @@ public: PartitionMemoryBlock(BlockAllocator *_alloc, u32 size, bool fromEnd) { alloc = _alloc; - address = alloc->Alloc(size, fromEnd); + address = alloc->Alloc(size, fromEnd, "PMB"); alloc->ListBlocks(); } ~PartitionMemoryBlock() @@ -302,10 +366,11 @@ public: void sceKernelMaxFreeMemSize() { // TODO: Fudge factor improvement - u32 retVal = userMemory.GetLargestFreeBlockSize()-0x8000; + u32 retVal = userMemory.GetLargestFreeBlockSize()-0x40000; DEBUG_LOG(HLE,"%08x (dec %i)=sceKernelMaxFreeMemSize",retVal,retVal); RETURN(retVal); } + void sceKernelTotalFreeMemSize() { u32 retVal = userMemory.GetLargestFreeBlockSize()-0x8000; @@ -367,7 +432,10 @@ void sceKernelGetBlockHeadAddr() void sceKernelPrintf() { + const char *formatString = Memory::GetCharPointer(PARAM(0)); + ERROR_LOG(HLE,"UNIMPL sceKernelPrintf(%08x, %08x, %08x, %08x)", PARAM(0),PARAM(1),PARAM(2),PARAM(3)); + ERROR_LOG(HLE,"%s", formatString); RETURN(0); } @@ -390,19 +458,28 @@ void sceKernelSetCompilerVersion() void sceKernelCreateVpl() { const char *name = Memory::GetCharPointer(PARAM(0)); + + u32 vplSize = PARAM(3); + u32 memBlockPtr = userMemory.Alloc(vplSize, false, "VPL"); + if (memBlockPtr == -1) { + ERROR_LOG(HLE, "sceKernelCreateVpl: Failed to allocate %i bytes of pool data", vplSize); + RETURN(-1); + return; + } + VPL *vpl = new VPL; SceUID id = kernelObjects.Create(vpl); strncpy(vpl->nv.name, name, 32); //vpl->nv.mpid = PARAM(1); //seems to be the standard memory partition (user, kernel etc) vpl->nv.attr = PARAM(2); - vpl->size = PARAM(3); + vpl->size = vplSize; vpl->nv.poolSize = vpl->size; vpl->nv.size = sizeof(vpl->nv); vpl->nv.numWaitThreads = 0; vpl->nv.freeSize = vpl->nv.poolSize; - vpl->address = userMemory.Alloc(vpl->size, false, "VPL"); + vpl->address = memBlockPtr; vpl->alloc.Init(vpl->address, vpl->size); DEBUG_LOG(HLE,"sceKernelCreateVpl(\"%s\", block=%i, attr=%i, size=%i)", @@ -480,6 +557,7 @@ void sceKernelAllocateVplCB() else { ERROR_LOG(HLE, "sceKernelAllocateVplCB FAILURE"); + __KernelCheckCallbacks(); RETURN(-1); } } @@ -522,8 +600,24 @@ void sceKernelTryAllocateVpl() void sceKernelFreeVpl() { - ERROR_LOG(HLE,"UNIMPL: sceKernelFreeVpl()"); - RETURN(0); + SceUID id = PARAM(0); + u32 blockPtr = PARAM(1); + DEBUG_LOG(HLE,"sceKernelFreeVpl(%i, %08x)", id, blockPtr); + u32 error; + VPL *vpl = kernelObjects.Get(id, error); + if (vpl) + { + if (vpl->alloc.Free(blockPtr)) { + RETURN(0); + // Should trigger waiting threads + } else { + ERROR_LOG(HLE, "sceKernelFreeVpl: Error freeing %08x", blockPtr); + RETURN(-1); + } + } + else { + RETURN(error); + } } void sceKernelCancelVpl() @@ -552,6 +646,35 @@ void sceKernelReferVplStatus() RETURN(0); } +void AllocMemoryBlock() { + const char *pname = Memory::GetCharPointer(PARAM(0)); + int type = PARAM(1); + u32 size = PARAM(2); + int paramsAddr = PARAM(3); + + DEBUG_LOG(HLE,"AllocMemoryBlock(SysMemUserForUser_FE707FDF)(%s, %i, %i, %08x)", pname, type, size, paramsAddr); + + // Just support allocating a block in the user region. + + u32 blockPtr = userMemory.Alloc(size, false, pname); + + // Create a UID object??? Nah, let's just us the UID itself (hack!) + + RETURN(blockPtr); +} + +void FreeMemoryBlock() { + SceUID uid = PARAM(0); + DEBUG_LOG(HLE, "FreeMemoryBlock(%i)", uid); + userMemory.Free(uid); + RETURN(0); +} + +void GetMemoryBlockPtr() { + SceUID uid = PARAM(0); + DEBUG_LOG(HLE, "GetMemoryBlockPtr(%i)", uid); + RETURN(uid); +} const HLEFunction SysMemUserForUser[] = { @@ -567,8 +690,14 @@ const HLEFunction SysMemUserForUser[] = {0x315AD3A0,0,"sceKernelSetCompiledSdkVersion380_390"}, {0xEBD5C3E6,0,"sceKernelSetCompiledSdkVersion395"}, {0xf77d77cb,sceKernelSetCompilerVersion,"sceKernelSetCompilerVersion"}, - {0x35669d4c,0,"SysMemUserForUser_35669d4c"}, - {0x1b4217bc,0,"SysMemUserForUser_1b4217bc"}, + {0x35669d4c,0,"sceKernelSetCompiledSdkVersion600_602"}, //?? + {0x1b4217bc,0,"sceKernelSetCompiledSdkVersion603_605"}, + {0x358ca1bb,0,"sceKernelSetCompiledSdkVersion606"}, + // Obscure raw block API + {0xDB83A952,GetMemoryBlockPtr,"SysMemUserForUser_DB83A952"}, // GetMemoryBlockAddr + {0x91DE343C,0,"SysMemUserForUser_91DE343C"}, + {0x50F61D8A,FreeMemoryBlock,"SysMemUserForUser_50F61D8A"}, // FreeMemoryBlock + {0xFE707FDF,AllocMemoryBlock,"SysMemUserForUser_FE707FDF"}, // AllocMemoryBlock }; diff --git a/Core/HLE/sceKernelMemory.h b/Core/HLE/sceKernelMemory.h index 5edfd4f6b0..247f683d7f 100644 --- a/Core/HLE/sceKernelMemory.h +++ b/Core/HLE/sceKernelMemory.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceKernelModule.cpp b/Core/HLE/sceKernelModule.cpp index 2051241c78..bc5baa2e1d 100644 --- a/Core/HLE/sceKernelModule.cpp +++ b/Core/HLE/sceKernelModule.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -16,12 +16,16 @@ // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. #include -#include "HLE.h" +#include +#include "HLE.h" +#include "Common/Action.h" +#include "Common/FileUtil.h" #include "../Host.h" #include "../MIPS/MIPS.h" #include "../MIPS/MIPSAnalyst.h" #include "../ELF/ElfReader.h" +#include "../ELF/PrxDecrypter.h" #include "../Debugger/SymbolMap.h" #include "../FileSystems/FileSystem.h" #include "../FileSystems/MetaFileSystem.h" @@ -40,37 +44,84 @@ enum { PSP_THREAD_ATTR_USER = 0x80000000 }; -struct Module : public KernelObject +static const char *blacklistedModules[] = { + "sceATRAC3plus_Library", + "sceFont_Library", + "SceFont_Library", + "sceNetAdhocctl_Library", + "sceNetAdhocDownload_Library", + "sceNetAdhocMatching_Library", + "sceNetAdhoc_Library", + "sceNetApctl_Library", + "sceNetInet_Library", + "sceNet_Library", +}; + +struct NativeModule { + u32 next; + u16 attribute; + u8 version[2]; + char name[28]; + u32 status; + u32 unk1; + u32 usermod_thid; + u32 memid; + u32 mpidtext; + u32 mpiddata; + u32 ent_top; + u32 ent_size; + u32 stub_top; + u32 stub_size; + u32 module_start_func; + u32 module_stop_func; + u32 module_bootstart_func; + u32 module_reboot_before_func; + u32 module_reboot_phase_func; + u32 entry_addr; + u32 gp_value; + u32 text_addr; + u32 text_size; + u32 data_size; + u32 bss_size; + u32 nsegment; + u32 segmentaddr[4]; + u32 segmentsize[4]; + u32 module_start_thread_priority; + u32 module_start_thread_stacksize; + u32 module_start_thread_attr; + u32 module_stop_thread_priority; + u32 module_stop_thread_stacksize; + u32 module_stop_thread_attr; + u32 module_reboot_before_thread_priority; + u32 module_reboot_before_thread_stacksize; + u32 module_reboot_before_thread_attr; +}; + +class Module : public KernelObject { - const char *GetName() {return name;} +public: + Module() : memoryBlockAddr(0) {} + ~Module() { + if (memoryBlockAddr) { + userMemory.Free(memoryBlockAddr); + } + } + const char *GetName() {return nm.name;} const char *GetTypeName() {return "Module";} void GetQuickInfo(char *ptr, int size) { // ignore size sprintf(ptr, "name=%s gp=%08x entry=%08x", - name, - gp_value, - entry_addr); + nm.name, + nm.gp_value, + nm.entry_addr); } static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_MODULE; } int GetIDType() const { return 0; } - SceSize size; - char nsegment; - char reserved[3]; - int segmentaddr[4]; - int segmentsize[4]; - unsigned int entry_addr; - unsigned int gp_value; - unsigned int text_addr; - unsigned int text_size; - unsigned int data_size; - unsigned int bss_size; - // The following is only available in the v1.5 firmware and above, - // but as sceKernelQueryModuleInfo is broken in v1.0 it doesn't matter. - unsigned short attribute; - unsigned char version[2]; - char name[28]; + NativeModule nm; + + u32 memoryBlockAddr; }; ////////////////////////////////////////////////////////////////////////// @@ -105,37 +156,52 @@ struct SceKernelSMOption { ////////////////////////////////////////////////////////////////////////// // STATE BEGIN -static int numLoadedModules; static SceUID mainModuleID; // hack // STATE END ////////////////////////////////////////////////////////////////////////// -Module *__KernelLoadELFFromPtr(const u8 *ptr, u32 loadAddress, SceUID &id, std::string *error_string) +Module *__KernelLoadELFFromPtr(const u8 *ptr, u32 loadAddress, std::string *error_string) { - Module *m = new Module; - SceUID uid = kernelObjects.Create(m); + Module *module = new Module; + kernelObjects.Create(module); - u32 magic = *((u32*)ptr); + u8 *newptr = 0; - if (magic == 0x5053507e) { // "~PSP" - ERROR_LOG(HLE, "File encrypted - not yet supported"); - *error_string = "Executable encrypted - not yet supported"; + if (*(u32*)ptr == 0x5053507e) { // "~PSP" + // Decrypt module! YAY! + INFO_LOG(HLE, "Decrypting ~PSP file"); + PSP_Header *head = (PSP_Header*)ptr; + const u8 *in = ptr; + u32 size = head->elf_size; + if (head->psp_size > size) + { + size = head->psp_size; + } + newptr = new u8[head->elf_size + head->psp_size]; + ptr = newptr; + pspDecryptPRX(in, (u8*)ptr, head->psp_size); + } + + if (*(u32*)ptr == 0x4543537e) { // "~SCE" + ERROR_LOG(HLE, "Wrong magic number %08x (~SCE, kernel module?)",*(u32*)ptr); + *error_string = "Kernel module?"; + if (newptr) + { + delete [] newptr; + } + kernelObjects.Destroy(module->GetUID()); return 0; } - if (magic == 0x00000000) { - // BOOT.BIN is empty, we have to look for EBOOT.BIN which is encrypted. - ERROR_LOG(HLE, "File encrypted - not yet supported (2)"); - *error_string = "Executable encrypted - not yet supported"; - return 0; - } - if (*(u32*)ptr != 0x464c457f) { - char c[4]; - memcpy(c, ptr, 4); - ERROR_LOG(HLE, "Wrong magic number %c%c%c%c %08x", c[0],c[1],c[2],c[3],*(u32*)ptr); - *error_string = "File corrupt or encrypted?"; + ERROR_LOG(HLE, "Wrong magic number %08x",*(u32*)ptr); + *error_string = "File corrupt"; + if (newptr) + { + delete [] newptr; + } + kernelObjects.Destroy(module->GetUID()); return 0; } // Open ELF reader @@ -144,8 +210,14 @@ Module *__KernelLoadELFFromPtr(const u8 *ptr, u32 loadAddress, SceUID &id, std:: if (!reader.LoadInto(loadAddress)) { ERROR_LOG(HLE, "LoadInto failed"); + if (newptr) + { + delete [] newptr; + } + kernelObjects.Destroy(module->GetUID()); return 0; } + module->memoryBlockAddr = reader.GetVaddr(); struct libent { @@ -158,56 +230,6 @@ Module *__KernelLoadELFFromPtr(const u8 *ptr, u32 loadAddress, SceUID &id, std:: u32 __entrytableAddr; }; - SectionID entSection = reader.GetSectionByName(".lib.ent"); - SectionID textSection = reader.GetSectionByName(".text"); - - u32 sceResidentAddr = 0; - u32 moduleInfoAddr = 0; - u32 textStart = reader.GetSectionAddr(textSection); - u32 textSize = reader.GetSectionSize(textSection); - - SectionID sceResidentSection = reader.GetSectionByName(".rodata.sceResident"); - SectionID sceModuleInfoSection = reader.GetSectionByName(".rodata.sceModuleInfo"); - - bool hasSymbols = false; - bool dontadd = false; - - if (!host->AttemptLoadSymbolMap()) - { - hasSymbols = reader.LoadSymbols(); - if (!hasSymbols) - { - symbolMap.ResetSymbolMap(); - MIPSAnalyst::ScanForFunctions(textStart, textStart+textSize); - } - } - else - { - dontadd = true; - } - - if (entSection != -1) - { - libent *lib = (libent *)(Memory::GetPointer(reader.GetSectionAddr(entSection))); - //what's this for? - //lib->l1+=0; - } - - sceResidentAddr = reader.GetSectionAddr(sceResidentSection); - moduleInfoAddr = reader.GetSectionAddr(sceModuleInfoSection); - - struct PspResidentData - { - u32 l1; // unknown 0xd632acdb - u32 l2; // unknown 0xf01d73a7 - u32 startAddress; // address of _start - u32 moduleInfoAddr; // address of sceModuleInfo struct - }; - - DEBUG_LOG(LOADER,"Resident data addr: %08x", sceResidentAddr); - - PspResidentData *resdata = (PspResidentData *)Memory::GetPointer(sceResidentAddr); - struct PspModuleInfo { // 0, 0, 1, 1 ? @@ -222,23 +244,65 @@ Module *__KernelLoadELFFromPtr(const u8 *ptr, u32 loadAddress, SceUID &id, std:: u32 libstubend; // ptr to end of .lib.stub section }; - PspModuleInfo *modinfo = (PspModuleInfo *)Memory::GetPointer(moduleInfoAddr); - m->gp_value = modinfo->gp; - strncpy(m->name, modinfo->name, 28); // TODO + SectionID sceModuleInfoSection = reader.GetSectionByName(".rodata.sceModuleInfo"); + PspModuleInfo *modinfo; + if (sceModuleInfoSection != -1) + modinfo = (PspModuleInfo *)Memory::GetPointer(reader.GetSectionAddr(sceModuleInfoSection)); + else + modinfo = (PspModuleInfo *)Memory::GetPointer(reader.GetVaddr() + (reader.GetSegmentPaddr(0) & 0x7FFFFFFF) - reader.GetSegmentOffset(0)); - DEBUG_LOG(LOADER,"Module %s: %08x %08x %08x", modinfo->name, modinfo->gp, modinfo->libent,modinfo->libstub); + // Check for module blacklist - we don't allow games to load these modules from disc + // as we have HLE implementations and the originals won't run in the emu because they + // directly access hardware or for other reasons. + for (u32 i = 0; i < ARRAY_SIZE(blacklistedModules); i++) { + if (strcmp(modinfo->name, blacklistedModules[i]) == 0) { + *error_string = "Blacklisted"; + if (newptr) + { + delete [] newptr; + } + kernelObjects.Destroy(module->GetUID()); + return 0; + } + } + + bool hasSymbols = false; + bool dontadd = false; + + SectionID textSection = reader.GetSectionByName(".text"); + + if (textSection != -1) + { + u32 textStart = reader.GetSectionAddr(textSection); + u32 textSize = reader.GetSectionSize(textSection); + + if (!host->AttemptLoadSymbolMap()) + { + hasSymbols = reader.LoadSymbols(); + if (!hasSymbols) + { + symbolMap.ResetSymbolMap(); + MIPSAnalyst::ScanForFunctions(textStart, textStart+textSize); + } + } + else + { + dontadd = true; + } + } + + module->nm.gp_value = modinfo->gp; + strncpy(module->nm.name, modinfo->name, 28); + + INFO_LOG(LOADER,"Module %s: %08x %08x %08x", modinfo->name, modinfo->gp, modinfo->libent,modinfo->libstub); struct PspLibStubEntry { - // pointer to module name (will be in .rodata.sceResident section) - u32 moduleNameSymbol; - // mod version?? - unsigned short version; - unsigned short val1; - unsigned char val2; // 0x5 - unsigned char val3; - // number of function symbols - unsigned short numFuncs; + u32 name; + u16 version; + u16 flags; + u16 size; + u16 numFuncs; // each symbol has an associated nid; nidData is a pointer // (in .rodata.sceNid section) to an array of longs, one // for each function, which identifies the function whose @@ -252,8 +316,6 @@ Module *__KernelLoadELFFromPtr(const u8 *ptr, u32 loadAddress, SceUID &id, std:: // should be filled in u32 firstSymAddr; }; - //sceDisplay at 5968- - int numModules = (modinfo->libstubend - modinfo->libstub)/sizeof(PspLibStubEntry); @@ -263,11 +325,11 @@ Module *__KernelLoadELFFromPtr(const u8 *ptr, u32 loadAddress, SceUID &id, std:: PspLibStubEntry *entry = (PspLibStubEntry *)Memory::GetPointer(modinfo->libstub); int numSyms=0; - for (int m=0; mentry_addr = reader.GetEntryPoint(); + // Look at the exports, too. - return m; + struct PspLibEntEntry + { + u32 name; /* ent's name (module name) address */ + u16 version; + u16 flags; + u8 size; + u8 vcount; + u16 fcount; + u32 resident; + }; + + int numEnts = (modinfo->libentend - modinfo->libent)/sizeof(PspLibEntEntry); + PspLibEntEntry *ent = (PspLibEntEntry *)Memory::GetPointer(modinfo->libent); + for (int m=0; msize == 0) + { + continue; + } + + if (ent->name == 0) + { + // ? + name = module->nm.name; + } + else + { + name = (const char*)Memory::GetPointer(ent->name); + } + + INFO_LOG(HLE,"Exporting ent %d named %s, %d funcs, %d vars, resident %08x", m, name, ent->fcount, ent->vcount, ent->resident); + + u32 *residentPtr = (u32*)Memory::GetPointer(ent->resident); + + for (u32 j = 0; j < ent->fcount; j++) + { + u32 nid = residentPtr[j]; + u32 exportAddr = residentPtr[ent->fcount + ent->vcount + j]; + ResolveSyscall(name, nid, exportAddr); + } + if (ent->size > 4) + { + ent = (PspLibEntEntry*)((u8*)ent + ent->size * 4); + } + else + { + ent++; + } + } + + module->nm.entry_addr = reader.GetEntryPoint(); + + if (newptr) + { + delete [] newptr; + } + return module; } bool __KernelLoadPBP(const char *filename, std::string *error_string) @@ -331,21 +450,19 @@ bool __KernelLoadPBP(const char *filename, std::string *error_string) { u8 *temp = new u8[1024*1024*8]; in.read((char*)temp, 1024*1024*8); - SceUID id; - Module *m = __KernelLoadELFFromPtr(temp, PSP_GetDefaultLoadAddress(), id, error_string); - if (!m) + Module *module = __KernelLoadELFFromPtr(temp, PSP_GetDefaultLoadAddress(), error_string); + if (!module) return false; - mipsr4k.pc = m->entry_addr; + mipsr4k.pc = module->nm.entry_addr; delete [] temp; } in.close(); return true; } - -Module *__KernelLoadModule(u8 *fileptr, SceUID &id, SceKernelLMOption *options, std::string *error_string) +Module *__KernelLoadModule(u8 *fileptr, SceKernelLMOption *options, std::string *error_string) { - Module *m = 0; + Module *module = 0; // Check for PBP if (memcmp(fileptr, "\0PBP", 4) == 0) { @@ -360,14 +477,14 @@ Module *__KernelLoadModule(u8 *fileptr, SceUID &id, SceKernelLMOption *options, offsets[0] = offset0; for (int i = 1; i < numfiles; i++) memcpy(&offsets[i], fileptr + 12 + 4*i, 4); - m = __KernelLoadELFFromPtr(fileptr + offsets[5], PSP_GetDefaultLoadAddress(), id, error_string); + module = __KernelLoadELFFromPtr(fileptr + offsets[5], PSP_GetDefaultLoadAddress(), error_string); } else { - m = __KernelLoadELFFromPtr(fileptr, PSP_GetDefaultLoadAddress(), id, error_string); + module = __KernelLoadELFFromPtr(fileptr, PSP_GetDefaultLoadAddress(), error_string); } - return m; + return module; } void __KernelStartModule(Module *m, int args, const char *argp, SceKernelSMOption *options) @@ -378,13 +495,13 @@ void __KernelStartModule(Module *m, int args, const char *argp, SceKernelSMOptio } -u32 __KernelGetModuleGP(SceUID module) +u32 __KernelGetModuleGP(SceUID uid) { u32 error; - Module *m = kernelObjects.Get(module,error); - if (m) + Module *module = kernelObjects.Get(uid, error); + if (module) { - return m->gp_value; + return module->nm.gp_value; } else { @@ -395,30 +512,27 @@ u32 __KernelGetModuleGP(SceUID module) bool __KernelLoadExec(const char *filename, SceKernelLoadExecParam *param, std::string *error_string) { // Wipe kernel here, loadexec should reset the entire system - __KernelInit(); + if (__KernelIsRunning()) + __KernelShutdown(); + __KernelInit(); + PSPFileInfo info = pspFileSystem.GetFileInfo(filename); - s64 size = (s64)info.size; - if (!size) - { - ERROR_LOG(LOADER, "File is size 0: %s", filename); - return false; - } + u32 handle = pspFileSystem.OpenFile(filename, FILEACCESS_READ); - u8 *temp = new u8[(int)size]; + u8 *temp = new u8[(int)info.size + 0x1000000]; - pspFileSystem.ReadFile(handle, temp, (size_t)size); + pspFileSystem.ReadFile(handle, temp, (size_t)info.size); - SceUID moduleID; - Module *m = __KernelLoadModule(temp, moduleID, 0, error_string); + Module *module = __KernelLoadModule(temp, 0, error_string); - if (!m) { + if (!module) { ERROR_LOG(LOADER, "Failed to load module %s", filename); return false; } - mipsr4k.pc = m->entry_addr; + mipsr4k.pc = module->nm.entry_addr; INFO_LOG(LOADER, "Module entry: %08x", mipsr4k.pc); @@ -433,93 +547,195 @@ bool __KernelLoadExec(const char *filename, SceKernelLoadExecParam *param, std:: option.priority = 0x20; option.stacksize = 0x40000; // crazy? but seems to be the truth - __KernelStartModule(m, (u32)strlen(filename), filename, &option); + __KernelStartModule(module, (u32)strlen(filename) + 1, filename, &option); __KernelStartIdleThreads(); return true; } //TODO: second param -void sceKernelLoadExec() +int sceKernelLoadExec(const char *filename, u32 paramPtr) { - const char *name = Memory::GetCharPointer(PARAM(0)); SceKernelLoadExecParam *param = 0; - if (PARAM(1)) + if (paramPtr) { - param = (SceKernelLoadExecParam*)Memory::GetPointer(PARAM(1)); + param = (SceKernelLoadExecParam*)Memory::GetPointer(paramPtr); } - DEBUG_LOG(HLE,"sceKernelLoadExec(name=%s,...)", name); + + PSPFileInfo info = pspFileSystem.GetFileInfo(filename); + + if (!info.exists) { + ERROR_LOG(LOADER, "sceKernelLoadExec(%s, ...): File does not exist", filename); + return SCE_KERNEL_ERROR_NOFILE; + } + + s64 size = (s64)info.size; + if (!size) + { + ERROR_LOG(LOADER, "sceKernelLoadExec(%s, ...): File is size 0", filename); + return SCE_KERNEL_ERROR_ILLEGAL_OBJECT; + } + + DEBUG_LOG(HLE,"sceKernelLoadExec(name=%s,...)", filename); std::string error_string; - if (!__KernelLoadExec(name, param, &error_string)) + if (!__KernelLoadExec(filename, param, &error_string)) { ERROR_LOG(HLE, "sceKernelLoadExec failed: %s", error_string.c_str()); + return -1; + } + return 0; } -void sceKernelLoadModule() +u32 sceKernelLoadModule(const char *name, u32 flags) { - const char *name = Memory::GetCharPointer(PARAM(0)); - u32 flags = PARAM(1); + if(!name) + return 0; + + PSPFileInfo info = pspFileSystem.GetFileInfo(name); + std::string error_string; + s64 size = (s64)info.size; + + if (!info.exists) { + ERROR_LOG(LOADER, "sceKernelLoadModule(%s, %08x): File does not exist", name, flags); + return SCE_KERNEL_ERROR_NOFILE; + } + + if (!size) + { + ERROR_LOG(LOADER, "sceKernelLoadModule(%s, %08x): Module file is size 0", name, flags); + return SCE_KERNEL_ERROR_ILLEGAL_OBJECT; + } + + DEBUG_LOG(LOADER, "sceKernelLoadModule(%s, %08x)", name, flags); + + SceKernelLMOption *lmoption = 0; + int position = 0; + // TODO: Use position to decide whether to load high or low if (PARAM(2)) { - SceKernelLMOption *lmoption= (SceKernelLMOption *)Memory::GetPointer(PARAM(2)); + SceKernelLMOption *lmoption = (SceKernelLMOption *)Memory::GetPointer(PARAM(2)); + + } - //TODO: Check if module name is in "blacklist" (HLE:d list) - //If it is, don't load it. - //Else, actually do load it and resolve pointers! + Module *module = 0; + u8 *temp = new u8[(int)size]; + u32 handle = pspFileSystem.OpenFile(name, FILEACCESS_READ); + pspFileSystem.ReadFile(handle, temp, (size_t)size); + module = __KernelLoadELFFromPtr(temp, 0, &error_string); + delete [] temp; + pspFileSystem.CloseFile(handle); - DEBUG_LOG(HLE,"%i=sceKernelLoadModule(name=%s,flag=%08x,%08x,%08x,%08x,%08x(...))", - numLoadedModules+1,name,flags, + if (!module) { + // Module was blacklisted or couldn't be decrypted, which means it's a kernel module we don't want to run. + // Let's just act as if it worked. + NOTICE_LOG(LOADER, "Module %s is blacklisted or undecryptable - we lie about success", name); + return 1; + } + + if (lmoption) { + INFO_LOG(HLE,"%i=sceKernelLoadModule(name=%s,flag=%08x,%08x,%08x,%08x,position = %08x)", + module->GetUID(),name,flags, lmoption->size,lmoption->mpidtext,lmoption->mpiddata,lmoption->position); - - } else { - ERROR_LOG(HLE,"%i=sceKernelLoadModule(name=%s,flag=%08x,(...))", numLoadedModules+1, name, flags); + INFO_LOG(HLE,"%i=sceKernelLoadModule(name=%s,flag=%08x,(...))", module->GetUID(), name, flags); } - RETURN(++numLoadedModules); + + return module->GetUID(); } -void sceKernelStartModule() -{ - int id = PARAM(0); - int argsize = PARAM(1); - u32 argptr = PARAM(2); - u32 ptrReturn = PARAM(3); - if (PARAM(4)) { - SceKernelSMOption *smoption = (SceKernelSMOption*)Memory::GetPointer(PARAM(4)); - } - ERROR_LOG(HLE,"UNIMPL sceKernelStartModule(%d,asize=%08x,aptr=%08x,retptr=%08x,...)", - id,argsize,argptr,ptrReturn); - RETURN(0); +class AfterModuleEntryCall : public Action { +public: + AfterModuleEntryCall() {} + Module *module_; + u32 retValAddr; + virtual void run(); +}; + +void AfterModuleEntryCall::run() { + Memory::Write_U32(retValAddr, currentMIPS->r[2]); } -void sceKernelStopModule() +void sceKernelStartModule(u32 moduleId, u32 argsize, u32 argAddr, u32 returnValueAddr, u32 optionAddr) { - ERROR_LOG(HLE,"UNIMPL sceKernelStopModule"); - RETURN(0); + // Dunno what these three defaults should be... + u32 priority = 0x20; + u32 stacksize = 0x40000; + u32 attr = 0; + int stackPartition = 0; + if (optionAddr) { + SceKernelSMOption smoption; + Memory::ReadStruct(optionAddr, &smoption);; + priority = smoption.priority; + attr = smoption.attribute; + stacksize = smoption.stacksize; + stackPartition = smoption.mpidstack; + } + u32 error; + Module *module = kernelObjects.Get(moduleId, error); + if (!module) { + // TODO: Try not to lie so much. + /* + RETURN(error); + return; + */ + } else { + u32 entryAddr = module->nm.entry_addr; + if (entryAddr == -1) { + entryAddr = module->nm.module_start_func; + // attr = module->nm + } + } + //SceUID threadId; + //__KernelCreateThread(threadId, moduleId, module->nm.name, module->nm.entry_addr, priority, stacksize, attr); + + ERROR_LOG(HLE,"UNIMPL sceKernelStartModule(%d,asize=%08x,aptr=%08x,retptr=%08x,%08x)", + moduleId,argsize,argAddr,returnValueAddr,optionAddr); + + // Apparently, we need to call the entry point directly and insert the return value afterwards. This calls + // for a MipsCall and an Action. TODO + RETURN(0); // TODO: Delete +} + +void sceKernelStopModule(u32 moduleId, u32 argSize, u32 argAddr, u32 returnValueAddr, u32 optionAddr) +{ + ERROR_LOG(HLE,"UNIMPL sceKernelStopModule(%i, %i, %08x, %08x, %08x)", + moduleId, argSize, argAddr, returnValueAddr, optionAddr); + + // We should call the "stop" entry point and return the value in returnValueAddr. See StartModule. + RETURN(0); } void sceKernelUnloadModule() { - ERROR_LOG(HLE,"UNIMPL sceKernelUnloadModule"); - RETURN(0); + u32 moduleId = PARAM(0); + ERROR_LOG(HLE,"UNIMPL sceKernelUnloadModule(%i)", moduleId); + u32 error; + Module *module = kernelObjects.Get(moduleId, error); + if (!module) + { + RETURN(error); + return; + } + kernelObjects.Destroy(moduleId); + RETURN(0); } void sceKernelGetModuleIdByAddress() { - ERROR_LOG(HLE,"UNIMPL sceKernelGetModuleIdByAddress(%08x)", PARAM(0)); - if (PARAM(0) == 0x08800000) + ERROR_LOG(HLE,"HACKIMPL sceKernelGetModuleIdByAddress(%08x)", PARAM(0)); + if ((PARAM(0) & 0xFFFF0000) == 0x08800000) RETURN(mainModuleID); else RETURN(0); } + void sceKernelGetModuleId() { - ERROR_LOG(HLE,"UNIMPL sceKernelGetModuleId"); - RETURN(0); - + ERROR_LOG(HLE,"sceKernelGetModuleId()"); + RETURN(__KernelGetCurThreadModuleId()); } void sceKernelFindModuleByName() @@ -528,23 +744,27 @@ void sceKernelFindModuleByName() RETURN(1); } - +u32 sceKernelLoadModuleByID(u32 id) { + ERROR_LOG(HLE,"UNIMPL sceKernelLoadModuleById(%08x)", id); + // Apparenty, ID is a sceIo File UID. So this shouldn't be too hard when needed. + return 0; +} const HLEFunction ModuleMgrForUser[] = { - {0x977DE386,sceKernelLoadModule,"sceKernelLoadModule"}, - {0xb7f46618,0,"sceKernelLoadModuleByID"}, - {0x50F0C1EC,sceKernelStartModule,"sceKernelStartModule"}, - {0xD675EBB8,sceKernelExitGame,"sceKernelSelfStopUnloadModule"}, //HACK - {0xd1ff982a,sceKernelStopModule,"sceKernelStopModule"}, - {0x2e0911aa,sceKernelUnloadModule,"sceKernelUnloadModule"}, + {0x977DE386,&WrapU_CU,"sceKernelLoadModule"}, + {0xb7f46618,&WrapU_U,"sceKernelLoadModuleByID"}, + {0x50F0C1EC,&WrapV_UUUUU,"sceKernelStartModule"}, + {0xD675EBB8,&sceKernelExitGame,"sceKernelSelfStopUnloadModule"}, //HACK + {0xd1ff982a,&WrapV_UUUUU,"sceKernelStopModule"}, + {0x2e0911aa,&sceKernelUnloadModule,"sceKernelUnloadModule"}, {0x710F61B5,0,"sceKernelLoadModuleMs"}, {0xF9275D98,0,"sceKernelLoadModuleBufferUsbWlan"}, ///??? {0xCC1D3699,0,"sceKernelStopUnloadSelfModule"}, {0x748CBED9,0,"sceKernelQueryModuleInfo"}, - {0xd8b73127,sceKernelGetModuleIdByAddress, "sceKernelGetModuleIdByAddress"}, - {0xf0a26395,sceKernelGetModuleId, "sceKernelGetModuleId"}, - {0x8f2df740,0,"sceKernel_ModuleMgr_8f2df740"}, + {0xd8b73127,&sceKernelGetModuleIdByAddress, "sceKernelGetModuleIdByAddress"}, + {0xf0a26395,&sceKernelGetModuleId, "sceKernelGetModuleId"}, + {0x8f2df740,0,"sceKernelStopUnloadSelfModuleWithStatus"}, }; diff --git a/Core/HLE/sceKernelModule.h b/Core/HLE/sceKernelModule.h index 3967cc0ab3..2652e1e55f 100644 --- a/Core/HLE/sceKernelModule.h +++ b/Core/HLE/sceKernelModule.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -20,7 +20,6 @@ #include "sceKernel.h" #include "HLE.h" -bool __KernelLoadPBP(const char *filename, std::string *error_string); u32 __KernelGetModuleGP(SceUID module); bool __KernelLoadExec(const char *filename, SceKernelLoadExecParam *param, std::string *error_string); diff --git a/Core/HLE/sceKernelMsgPipe.cpp b/Core/HLE/sceKernelMsgPipe.cpp index 2dc6b9f5b1..ca8fa76a73 100644 --- a/Core/HLE/sceKernelMsgPipe.cpp +++ b/Core/HLE/sceKernelMsgPipe.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -18,6 +18,15 @@ #include "HLE.h" #include "sceKernel.h" #include "sceKernelMsgPipe.h" +#include "sceKernelThread.h" + +#define SCE_KERNEL_MPA_THFIFO_S 0x0000 +#define SCE_KERNEL_MPA_THPRI_S 0x0100 +#define SCE_KERNEL_MPA_THFIFO_R 0x0000 +#define SCE_KERNEL_MPA_THPRI_R 0x1000 + +#define SCE_KERNEL_MPW_FULL 0 +#define SCE_KERNEL_MPW_ASAP 1 struct NativeMsgPipe { @@ -30,7 +39,17 @@ struct NativeMsgPipe int numReceiveWaitThreads; }; -struct MsgPipe : public KernelObject +struct MsgPipeWaitingThread +{ + SceUID id; + u32 bufAddr; + u32 bufSize; + u32 freeSize; + int waitMode; + u32 transferredBytesAddr; +}; + +struct MsgPipe : public KernelObject { const char *GetName() {return nmp.name;} const char *GetTypeName() {return "MsgPipe";} @@ -39,10 +58,98 @@ struct MsgPipe : public KernelObject NativeMsgPipe nmp; - std::vector sendWaitingThreads; - std::vector receiveWaitingThreads; + std::vector sendWaitingThreads; + std::vector receiveWaitingThreads; + + void AddWaitingThread(std::vector &list, SceUID id, u32 addr, u32 size, int waitMode, u32 transferredBytesAddr, bool usePrio) + { + MsgPipeWaitingThread thread = { id, addr, size, size, waitMode, transferredBytesAddr }; + if (usePrio) + { + for (std::vector::iterator it = list.begin(); it != list.end(); it++) + { + if (__KernelGetThreadPrio(id) >= __KernelGetThreadPrio((*it).id)) + { + list.insert(it, thread); + break; + } + } + } + else + { + list.push_back(thread); + } + } + + void AddSendWaitingThread(SceUID id, u32 addr, u32 size, int waitMode, u32 transferredBytesAddr) + { + bool usePrio = ((nmp.attr & SCE_KERNEL_MPA_THPRI_S) != 0); + AddWaitingThread(sendWaitingThreads, id, addr, size, waitMode, transferredBytesAddr, usePrio); + } + + void AddReceiveWaitingThread(SceUID id, u32 addr, u32 size, int waitMode, u32 transferredBytesAddr) + { + bool usePrio = ((nmp.attr & SCE_KERNEL_MPA_THPRI_R) != 0); + AddWaitingThread(receiveWaitingThreads, id, addr, size, waitMode, transferredBytesAddr, usePrio); + } + + void CheckSendThreads() + { + if (sendWaitingThreads.empty()) + return; + MsgPipeWaitingThread *thread = &sendWaitingThreads.front(); + if (nmp.freeSize >= thread->bufSize) + { + // Put all the data to the buffer + memcpy(buffer + (nmp.bufSize - nmp.freeSize), Memory::GetPointer(thread->bufAddr), thread->bufSize); + Memory::Write_U32(thread->bufSize, thread->transferredBytesAddr); + nmp.freeSize -= thread->bufSize; + __KernelResumeThreadFromWait(thread->id); + sendWaitingThreads.erase(sendWaitingThreads.begin()); + CheckReceiveThreads(); + } + else if (thread->waitMode == SCE_KERNEL_MPW_ASAP && nmp.freeSize != 0) + { + // Put as much data as possible into the buffer + memcpy(buffer + (nmp.bufSize - nmp.freeSize), Memory::GetPointer(thread->bufAddr), nmp.freeSize); + Memory::Write_U32(nmp.freeSize, thread->transferredBytesAddr); + nmp.freeSize = 0; + __KernelResumeThreadFromWait(thread->id); + receiveWaitingThreads.erase(receiveWaitingThreads.begin()); + CheckReceiveThreads(); + } + } + + // This function should be only ran when the temporary buffer size is not 0 (otherwise, data is copied directly to the threads) + void CheckReceiveThreads() + { + if (receiveWaitingThreads.empty()) + return; + MsgPipeWaitingThread *thread = &receiveWaitingThreads.front(); + if (nmp.bufSize - nmp.freeSize >= thread->bufSize) + { + // Get the needed data from the buffer + Memory::Memcpy(thread->bufAddr, buffer, thread->bufSize); + // Put the unused data at the start of the buffer + memmove(buffer, buffer + thread->bufSize, nmp.bufSize - nmp.freeSize); + Memory::Write_U32(thread->bufSize, thread->transferredBytesAddr); + nmp.freeSize += thread->bufSize; + __KernelResumeThreadFromWait(thread->id); + receiveWaitingThreads.erase(receiveWaitingThreads.begin()); + CheckSendThreads(); + } + else if (thread->waitMode == SCE_KERNEL_MPW_ASAP && nmp.freeSize != nmp.bufSize) + { + // Get all the data from the buffer + Memory::Memcpy(thread->bufAddr, buffer, nmp.bufSize - nmp.freeSize); + Memory::Write_U32(nmp.bufSize - nmp.freeSize, thread->transferredBytesAddr); + nmp.freeSize = nmp.bufSize; + __KernelResumeThreadFromWait(thread->id); + receiveWaitingThreads.erase(receiveWaitingThreads.begin()); + CheckSendThreads(); + } + } - // Ring buffer u8 *buffer; }; @@ -65,25 +172,145 @@ void sceKernelCreateMsgPipe() m->nmp.numSendWaitThreads = 0; m->nmp.numReceiveWaitThreads = 0; - m->buffer = new u8[size]; + m->buffer = 0; + if (size != 0) + { + m->buffer = new u8[size]; + } + + DEBUG_LOG(HLE, "%d=sceKernelCreateMsgPipe(%s, part=%d, attr=%08x, size=%d, opt=%08x)", id, name, memoryPartition, attr, size, opt); + RETURN(id); } void sceKernelDeleteMsgPipe() { - SceUInt uid = PARAM(0); + SceUID uid = PARAM(0); u32 error; - MsgPipe *p = kernelObjects.Get(uid, error); - if (!p) + MsgPipe *m = kernelObjects.Get(uid, error); + if (!m) { ERROR_LOG(HLE, "sceKernelDeleteMsgPipe(%i) - ERROR %08x", uid, error); + RETURN(error); return; } - delete [] p->buffer; - ERROR_LOG(HLE, "sceKernelDeleteMsgPipe(%i)", uid); + if (m->buffer != 0) + { + delete [] m->buffer; + } + for (u32 i = 0; i < m->sendWaitingThreads.size(); i++) + { + __KernelResumeThreadFromWait(m->sendWaitingThreads[i].id); + } + for (u32 i = 0; i < m->receiveWaitingThreads.size(); i++) + { + __KernelResumeThreadFromWait(m->receiveWaitingThreads[i].id); + } + DEBUG_LOG(HLE, "sceKernelDeleteMsgPipe(%i)", uid); RETURN(kernelObjects.Destroy(uid)); } +void __KernelSendMsgPipe(MsgPipe *m, u32 sendBufAddr, u32 sendSize, int waitMode, u32 resultAddr, u32 timeoutPtr, bool cbEnabled, bool pool) +{ + u32 curSendAddr = sendBufAddr; + if (m->nmp.bufSize == 0) + { + while (!m->receiveWaitingThreads.empty()) + { + MsgPipeWaitingThread *thread = &m->receiveWaitingThreads.front(); + if (thread->freeSize > sendSize) + { + Memory::Memcpy(thread->bufAddr + (thread->bufSize - thread->freeSize), Memory::GetPointer(curSendAddr), sendSize); + thread->freeSize -= sendSize; + curSendAddr += sendSize; + sendSize = 0; + if (thread->waitMode == SCE_KERNEL_MPW_ASAP) + { + Memory::Write_U32(thread->bufSize - thread->freeSize, thread->transferredBytesAddr); + __KernelResumeThreadFromWait(thread->id); + m->receiveWaitingThreads.erase(m->receiveWaitingThreads.begin()); + } + break; + } + else if (thread->freeSize == sendSize) + { + Memory::Memcpy(thread->bufAddr + (thread->bufSize - thread->freeSize), Memory::GetPointer(curSendAddr), sendSize); + Memory::Write_U32(thread->bufSize, thread->transferredBytesAddr); + __KernelResumeThreadFromWait(thread->id); + m->receiveWaitingThreads.erase(m->receiveWaitingThreads.begin()); + curSendAddr += sendSize; + sendSize = 0; + break; + } + else + { + Memory::Memcpy(thread->bufAddr + (thread->bufSize - thread->freeSize), Memory::GetPointer(curSendAddr), thread->freeSize); + sendSize -= thread->freeSize; + curSendAddr += thread->freeSize; + Memory::Write_U32(thread->bufSize, thread->transferredBytesAddr); + __KernelResumeThreadFromWait(thread->id); + m->receiveWaitingThreads.erase(m->receiveWaitingThreads.begin()); + } + } + // If there is still data to send and (we want to send all of it or we didn't send anything) + if (sendSize != 0 && (waitMode != SCE_KERNEL_MPW_ASAP || curSendAddr == sendBufAddr)) + { + if (pool) + { + RETURN(SCE_KERNEL_ERROR_MPP_FULL); + return; + } + else + { + m->AddSendWaitingThread(__KernelGetCurThread(), curSendAddr, sendSize, waitMode, resultAddr); + RETURN(0); + __KernelWaitCurThread(WAITTYPE_MSGPIPE, 0, 0, 0, cbEnabled); + return; + } + } + } + else + { + if (sendSize <= m->nmp.freeSize) + { + memcpy(m->buffer + (m->nmp.bufSize - m->nmp.freeSize), Memory::GetPointer(sendBufAddr), sendSize); + m->nmp.freeSize -= sendSize; + curSendAddr = sendBufAddr + sendSize; + sendSize = 0; + } + else if (waitMode == SCE_KERNEL_MPW_ASAP && m->nmp.freeSize != 0) + { + memcpy(m->buffer + (m->nmp.bufSize - m->nmp.freeSize), Memory::GetPointer(sendBufAddr), m->nmp.freeSize); + curSendAddr = sendBufAddr + m->nmp.freeSize; + sendSize -= m->nmp.freeSize; + m->nmp.freeSize = 0; + } + else + { + if (pool) + { + RETURN(SCE_KERNEL_ERROR_MPP_FULL); + return; + } + else + { + m->AddSendWaitingThread(__KernelGetCurThread(), curSendAddr, sendSize, waitMode, resultAddr); + RETURN(0); + __KernelWaitCurThread(WAITTYPE_MSGPIPE, 0, 0, 0, cbEnabled); + return; + } + } + + if (curSendAddr != sendBufAddr) + { + m->CheckReceiveThreads(); + } + } + Memory::Write_U32(curSendAddr - sendBufAddr, resultAddr); + + RETURN(0); +} + void sceKernelSendMsgPipe() { SceUInt uid = PARAM(0); @@ -93,8 +320,16 @@ void sceKernelSendMsgPipe() u32 resultAddr = PARAM(4); u32 timeoutPtr = PARAM(5); - ERROR_LOG(HLE, "UNIMPL sceKernelSendMsgPipe(%i, %08x, %i, %i, %08x, %08x)", uid, sendBufAddr, sendSize, waitMode, resultAddr, timeoutPtr); - RETURN(0); + u32 error; + MsgPipe *m = kernelObjects.Get(uid, error); + if (!m) { + ERROR_LOG(HLE, "sceKernelSendMsgPipe(%i) - ERROR %08x", uid, error); + RETURN(error); + return; + } + + DEBUG_LOG(HLE, "sceKernelSendMsgPipe(id=%i, addr=%08x, size=%i, mode=%i, result=%08x, timeout=%08x)", uid, sendBufAddr, sendSize, waitMode, resultAddr, timeoutPtr); + __KernelSendMsgPipe(m, sendBufAddr, sendSize, waitMode, resultAddr, timeoutPtr, false, false); } void sceKernelSendMsgPipeCB() @@ -106,8 +341,17 @@ void sceKernelSendMsgPipeCB() u32 resultAddr = PARAM(4); u32 timeoutPtr = PARAM(5); - ERROR_LOG(HLE, "UNIMPL sceKernelSendMsgPipeCB(%i, %08x, %i, %i, %08x, %08x)", uid, sendBufAddr, sendSize, waitMode, resultAddr, timeoutPtr); - RETURN(0); + u32 error; + MsgPipe *m = kernelObjects.Get(uid, error); + if (!m) { + ERROR_LOG(HLE, "sceKernelSendMsgPipeCB(%i) - ERROR %08x", uid, error); + RETURN(error); + return; + } + + DEBUG_LOG(HLE, "sceKernelSendMsgPipeCB(id=%i, addr=%08x, size=%i, mode=%i, result=%08x, timeout=%08x)", uid, sendBufAddr, sendSize, waitMode, resultAddr, timeoutPtr); + __KernelSendMsgPipe(m, sendBufAddr, sendSize, waitMode, resultAddr, timeoutPtr, true, false); + __KernelCheckCallbacks(); } void sceKernelTrySendMsgPipe() @@ -118,55 +362,223 @@ void sceKernelTrySendMsgPipe() int waitMode = PARAM(3); u32 resultAddr = PARAM(4); - ERROR_LOG(HLE, "UNIMPL sceKernelTrySendMsgPipe(%i, %08x, %i, %i, %08x)", uid, sendBufAddr, sendSize, waitMode, resultAddr); + u32 error; + MsgPipe *m = kernelObjects.Get(uid, error); + if (!m) { + ERROR_LOG(HLE, "sceKernelTrySendMsgPipe(%i) - ERROR %08x", uid, error); + RETURN(error); + return; + } + + DEBUG_LOG(HLE, "sceKernelTrySendMsgPipeCB(id=%i, addr=%08x, size=%i, mode=%i, result=%08x)", uid, sendBufAddr, sendSize, waitMode, resultAddr); + __KernelSendMsgPipe(m, sendBufAddr, sendSize, waitMode, resultAddr, 0, false, true); +} + +void __KernelReceiveMsgPipe(MsgPipe *m, u32 receiveBufAddr, u32 receiveSize, int waitMode, u32 resultAddr, u32 timeoutPtr, bool cbEnabled, bool pool) +{ + u32 curReceiveAddr = receiveBufAddr; + // MsgPipe buffer size is 0, receiving directly from waiting send threads + if (m->nmp.bufSize == 0) + { + // While they're still sending waiting threads (which can send data) + while (!m->sendWaitingThreads.empty()) + { + MsgPipeWaitingThread *thread = &m->sendWaitingThreads.front(); + // Sending thread has more data than we have to receive: retrieve just the amount of data we want + if (thread->bufSize - thread->freeSize > receiveSize) + { + Memory::Memcpy(curReceiveAddr, Memory::GetPointer(thread->bufAddr), receiveSize); + thread->freeSize += receiveSize; + // Move still available data at the beginning of the sending thread buffer + Memory::Memcpy(thread->bufAddr, Memory::GetPointer(thread->bufAddr + receiveSize), thread->bufSize - thread->freeSize); + curReceiveAddr += receiveSize; + receiveSize = 0; + // The sending thread mode is ASAP: we have sent some data so restart it even though its buffer isn't empty + if (thread->waitMode == SCE_KERNEL_MPW_ASAP) + { + Memory::Write_U32(thread->bufSize - thread->freeSize, thread->transferredBytesAddr); + __KernelResumeThreadFromWait(thread->id); + m->sendWaitingThreads.erase(m->sendWaitingThreads.begin()); + } + break; + } + // Sending thread wants to send the same amount of data as we want to retrieve: get the data and resume thread + else if (thread->bufSize - thread->freeSize == receiveSize) + { + Memory::Memcpy(curReceiveAddr, Memory::GetPointer(thread->bufAddr), receiveSize); + Memory::Write_U32(thread->bufSize, thread->transferredBytesAddr); + __KernelResumeThreadFromWait(thread->id); + m->sendWaitingThreads.erase(m->sendWaitingThreads.begin()); + curReceiveAddr += receiveSize; + receiveSize = 0; + break; + } + // Not enough data in the sending thread: get the data available and restart the sending thread, then loop + else + { + Memory::Memcpy(curReceiveAddr, Memory::GetPointer(thread->bufAddr), thread->bufSize - thread->freeSize); + receiveSize -= thread->bufSize - thread->freeSize; + curReceiveAddr += thread->bufSize - thread->freeSize; + Memory::Write_U32(thread->bufSize, thread->transferredBytesAddr); + __KernelResumeThreadFromWait(thread->id); + m->sendWaitingThreads.erase(m->sendWaitingThreads.begin()); + } + } + // All data hasn't been received and (mode isn't ASAP or nothing was received) + if (receiveSize != 0 && (waitMode != SCE_KERNEL_MPW_ASAP || curReceiveAddr == receiveBufAddr)) + { + if (pool) + { + RETURN(SCE_KERNEL_ERROR_MPP_EMPTY); + return; + } + else + { + m->AddReceiveWaitingThread(__KernelGetCurThread(), curReceiveAddr, receiveSize, waitMode, resultAddr); + RETURN(0); + __KernelWaitCurThread(WAITTYPE_MSGPIPE, 0, 0, 0, cbEnabled); + return; + } + } + } + // Getting data from the MsgPipe buffer + else + { + // Enough data in the buffer: copy just the needed amount of data + if (receiveSize <= m->nmp.bufSize - m->nmp.freeSize) + { + Memory::Memcpy(receiveBufAddr, m->buffer, receiveSize); + m->nmp.freeSize += receiveSize; + memmove(m->buffer, m->buffer + receiveSize, m->nmp.bufSize - m->nmp.freeSize); + curReceiveAddr = receiveBufAddr + receiveSize; + receiveSize = 0; + } + // Else, if mode is ASAP and there's at list 1 available byte of data: copy all the available data + else if (waitMode == SCE_KERNEL_MPW_ASAP && m->nmp.freeSize != m->nmp.bufSize) + { + Memory::Memcpy(receiveBufAddr, m->buffer, m->nmp.bufSize - m->nmp.freeSize); + receiveSize -= m->nmp.bufSize - m->nmp.freeSize; + curReceiveAddr = receiveBufAddr + m->nmp.bufSize - m->nmp.freeSize; + m->nmp.freeSize = m->nmp.bufSize; + } + else + { + if (pool) + { + RETURN(SCE_KERNEL_ERROR_MPP_EMPTY); + return; + } + else + { + m->AddReceiveWaitingThread(__KernelGetCurThread(), curReceiveAddr, receiveSize, waitMode, resultAddr); + RETURN(0); + __KernelWaitCurThread(WAITTYPE_MSGPIPE, 0, 0, 0, cbEnabled); + return; + } + } + + if (curReceiveAddr != receiveBufAddr) + { + m->CheckSendThreads(); + } + } + Memory::Write_U32(curReceiveAddr - receiveBufAddr, resultAddr); + RETURN(0); } void sceKernelReceiveMsgPipe() { - SceUInt uid = PARAM(0); + SceUID uid = PARAM(0); u32 receiveBufAddr = PARAM(1); u32 receiveSize = PARAM(2); int waitMode = PARAM(3); u32 resultAddr = PARAM(4); u32 timeoutPtr = PARAM(5); - ERROR_LOG(HLE, "UNIMPL sceKernelReceiveMsgPipe(%i, %08x, %i, %i, %08x, %08x)", uid, receiveBufAddr, receiveSize, waitMode, resultAddr, timeoutPtr); - RETURN(0); + u32 error; + MsgPipe *m = kernelObjects.Get(uid, error); + if (!m) { + ERROR_LOG(HLE, "sceKernelReceiveMsgPipe(%i) - ERROR %08x", uid, error); + RETURN(error); + return; + } + + DEBUG_LOG(HLE, "sceKernelReceiveMsgPipe(%i, %08x, %i, %i, %08x, %08x)", uid, receiveBufAddr, receiveSize, waitMode, resultAddr, timeoutPtr); + __KernelReceiveMsgPipe(m, receiveBufAddr, receiveSize, waitMode, resultAddr, timeoutPtr, false, false); } void sceKernelReceiveMsgPipeCB() { - SceUInt uid = PARAM(0); + SceUID uid = PARAM(0); u32 receiveBufAddr = PARAM(1); u32 receiveSize = PARAM(2); int waitMode = PARAM(3); u32 resultAddr = PARAM(4); u32 timeoutPtr = PARAM(5); - ERROR_LOG(HLE, "UNIMPL sceKernelReceiveMsgPipeCB(%i, %08x, %i, %i, %08x, %08x)", uid, receiveBufAddr, receiveSize, waitMode, resultAddr, timeoutPtr); - RETURN(0); + u32 error; + MsgPipe *m = kernelObjects.Get(uid, error); + if (!m) { + ERROR_LOG(HLE, "sceKernelReceiveMsgPipeCB(%i) - ERROR %08x", uid, error); + RETURN(error); + return; + } + + DEBUG_LOG(HLE, "sceKernelReceiveMsgPipeCB(%i, %08x, %i, %i, %08x, %08x)", uid, receiveBufAddr, receiveSize, waitMode, resultAddr, timeoutPtr); + __KernelReceiveMsgPipe(m, receiveBufAddr, receiveSize, waitMode, resultAddr, timeoutPtr, true, false); } void sceKernelTryReceiveMsgPipe() { - SceUInt uid = PARAM(0); + SceUID uid = PARAM(0); u32 receiveBufAddr = PARAM(1); u32 receiveSize = PARAM(2); int waitMode = PARAM(3); u32 resultAddr = PARAM(4); - ERROR_LOG(HLE, "UNIMPL sceKernelTryReceiveMsgPipe(%i, %08x, %i, %i, %08x)", uid, receiveBufAddr, receiveSize, waitMode, resultAddr); - RETURN(0); + u32 error; + MsgPipe *m = kernelObjects.Get(uid, error); + if (!m) { + ERROR_LOG(HLE, "sceKernelTryReceiveMsgPipe(%i) - ERROR %08x", uid, error); + RETURN(error); + return; + } + + DEBUG_LOG(HLE, "sceKernelTryReceiveMsgPipe(%i, %08x, %i, %i, %08x)", uid, receiveBufAddr, receiveSize, waitMode, resultAddr); + __KernelReceiveMsgPipe(m, receiveBufAddr, receiveSize, waitMode, resultAddr, 0, false, true); } void sceKernelCancelMsgPipe() { - SceUInt uid = PARAM(0); - u32 numSendThreads = PARAM(1); - u32 numReceiveThreads = PARAM(2); + SceUID uid = PARAM(0); + u32 numSendThreadsAddr = PARAM(1); + u32 numReceiveThreadsAddr = PARAM(2); - ERROR_LOG(HLE, "UNIMPL sceKernelCancelMsgPipe(%i, %i, %i)", uid, numSendThreads, numReceiveThreads); + u32 error; + MsgPipe *m = kernelObjects.Get(uid, error); + if (!m) + { + ERROR_LOG(HLE, "sceKernelCancelMsgPipe(%i) - ERROR %08x", uid, error); + RETURN(error); + return; + } + if (m->buffer != 0) + { + delete [] m->buffer; + } + u32 count; + for (count = 0; count < m->sendWaitingThreads.size(); count++) + { + __KernelResumeThreadFromWait(m->sendWaitingThreads[count].id); + } + Memory::Write_U32(count, numSendThreadsAddr); + for (count = 0; count < m->receiveWaitingThreads.size(); count++) + { + __KernelResumeThreadFromWait(m->receiveWaitingThreads[count].id); + } + Memory::Write_U32(count, numReceiveThreadsAddr); + DEBUG_LOG(HLE, "sceKernelCancelMsgPipe(%i, %i, %i)", uid, numSendThreadsAddr, numReceiveThreadsAddr); RETURN(0); } @@ -177,10 +589,12 @@ void sceKernelReferMsgPipeStatus() DEBUG_LOG(HLE,"sceKernelReferMsgPipeStatus(%i, %08x)", uid, msgPipeStatusAddr); u32 error; - MsgPipe *mp = kernelObjects.Get(uid, error); - if (mp) + MsgPipe *m = kernelObjects.Get(uid, error); + if (m) { - Memory::WriteStruct(msgPipeStatusAddr, &mp->nmp); + m->nmp.numSendWaitThreads = m->sendWaitingThreads.size(); + m->nmp.numReceiveWaitThreads = m->receiveWaitingThreads.size(); + Memory::WriteStruct(msgPipeStatusAddr, &m->nmp); RETURN(0); } else diff --git a/Core/HLE/sceKernelMsgPipe.h b/Core/HLE/sceKernelMsgPipe.h index c7681e6b76..0f262038b8 100644 --- a/Core/HLE/sceKernelMsgPipe.h +++ b/Core/HLE/sceKernelMsgPipe.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceKernelMutex.cpp b/Core/HLE/sceKernelMutex.cpp index 0862b258c7..40448dca8a 100644 --- a/Core/HLE/sceKernelMutex.cpp +++ b/Core/HLE/sceKernelMutex.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -110,13 +110,14 @@ u32 sceKernelLockMutex(u32 id, u32 count, u32 timeoutPtr) else { // Yeah, we need to block. Somehow. + ERROR_LOG(HLE,"Mutex should block!"); } return 0; } u32 sceKernelLockMutexCB(u32 id, u32 count, u32 timeoutPtr) { - DEBUG_LOG(HLE,"UNIMPL sceKernelLockMutexCB(%i, %i, %08x)", id, count, timeoutPtr); + ERROR_LOG(HLE,"UNIMPL sceKernelLockMutexCB(%i, %i, %08x)", id, count, timeoutPtr); return 0; } @@ -133,3 +134,51 @@ u32 sceKernelUnlockMutex(u32 id, u32 count) // TODO.... return 0; } + +struct NativeLwMutex +{ + SceSize size; + char name[32]; + SceUInt attr; + SceUID mutexUid; + SceUInt opaqueWorkAreaAddr; + int numWaitThreads; + int locked; + int threadid; // thread holding the lock +}; + +void sceKernelCreateLwMutex() +{ + ERROR_LOG(HLE,"UNIMPL sceKernelCreateLwMutex()"); + RETURN(0); +} + +void sceKernelDeleteLwMutex() +{ + ERROR_LOG(HLE,"UNIMPL sceKernelDeleteLwMutex()"); + RETURN(0); +} + +void sceKernelTryLockLwMutex() +{ + ERROR_LOG(HLE,"UNIMPL sceKernelTryLockLwMutex()"); + RETURN(0); +} + +void sceKernelLockLwMutex() +{ + ERROR_LOG(HLE,"UNIMPL sceKernelLockLwMutex()"); + RETURN(0); +} + +void sceKernelLockLwMutexCB() +{ + ERROR_LOG(HLE,"UNIMPL sceKernelLockLwMutexCB()"); + RETURN(0); +} + +void sceKernelUnlockLwMutex() +{ + ERROR_LOG(HLE,"UNIMPL void sceKernelUnlockLwMutex()"); + RETURN(0); +} \ No newline at end of file diff --git a/Core/HLE/sceKernelMutex.h b/Core/HLE/sceKernelMutex.h index c02842ab39..f5f19c67fb 100644 --- a/Core/HLE/sceKernelMutex.h +++ b/Core/HLE/sceKernelMutex.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -24,7 +24,9 @@ u32 sceKernelLockMutex(u32 id, u32 count, u32 timeoutPtr); u32 sceKernelLockMutexCB(u32 id, u32 count, u32 timeoutPtr); u32 sceKernelUnlockMutex(u32 id, u32 count); -/* void sceKernelCreateLwMutex(); void sceKernelDeleteLwMutex(); -*/ +void sceKernelTryLockLwMutex(); +void sceKernelLockLwMutex(); +void sceKernelLockLwMutexCB(); +void sceKernelUnlockLwMutex(); \ No newline at end of file diff --git a/Core/HLE/sceKernelSemaphore.cpp b/Core/HLE/sceKernelSemaphore.cpp index 0155cdcd3f..ee015af652 100644 --- a/Core/HLE/sceKernelSemaphore.cpp +++ b/Core/HLE/sceKernelSemaphore.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -22,6 +22,9 @@ #include "sceKernelThread.h" #include "sceKernelSemaphore.h" +#define PSP_SEMA_ATTR_FIFO 0 +#define PSP_SEMA_ATTR_PRIORITY 0x100 + /** Current state of a semaphore. * @see sceKernelReferSemaStatus. */ @@ -57,53 +60,130 @@ struct Semaphore : public KernelObject std::vector waitingThreads; }; -void sceKernelCancelSema() +// Resume all waiting threads (for delete / cancel.) +// Returns true if it woke any threads. +bool __KernelClearSemaThreads(Semaphore *s, int reason) { - SceUID id = PARAM(0); - ERROR_LOG(HLE,"UNIMPL sceKernelCancelSema(%i)", id); - RETURN(0); + bool wokeThreads = false; + + // TODO: PSP_SEMA_ATTR_PRIORITY + std::vector::iterator iter; + for (iter = s->waitingThreads.begin(); iter!=s->waitingThreads.end(); iter++) + { + SceUID threadID = *iter; + + // TODO: Set returnValue = reason? + __KernelResumeThreadFromWait(threadID); + wokeThreads = true; + } + s->waitingThreads.empty(); + + return wokeThreads; } -//SceUID sceKernelCreateSema(const char *name, SceUInt attr, int initVal, int maxVal, SceKernelSemaOptParam *option); -void sceKernelCreateSema() +// int sceKernelCancelSema(SceUID id, int newCount, int *numWaitThreads); +// void because it changes threads. +void sceKernelCancelSema(SceUID id, int newCount, u32 numWaitThreadsPtr) { - const char *name = Memory::GetCharPointer(PARAM(0)); + DEBUG_LOG(HLE,"sceKernelCancelSema(%i)", id); - Semaphore *s = new Semaphore; - SceUID id = kernelObjects.Create(s); - - strncpy(s->ns.name, name, 32); - s->ns.attr = PARAM(1); - s->ns.initCount = PARAM(2); - s->ns.currentCount = s->ns.initCount; - s->ns.maxCount = PARAM(3); - s->ns.numWaitThreads = 0; - - DEBUG_LOG(HLE,"%i=sceKernelCreateSema(%s, %08x, %i, %i, %08x)", id, s->ns.name, s->ns.attr, s->ns.initCount, s->ns.maxCount, PARAM(4)); - - RETURN(id); -} - -//int sceKernelDeleteSema(SceUID semaid); -void sceKernelDeleteSema() -{ - SceUID id = PARAM(0); - DEBUG_LOG(HLE,"sceKernelDeleteSema(%i)", id); - RETURN(kernelObjects.Destroy(id)); -} - -void sceKernelReferSemaStatus() -{ - SceUID id = PARAM(0); u32 error; Semaphore *s = kernelObjects.Get(id, error); if (s) { - DEBUG_LOG(HLE,"sceKernelReferSemaStatus(%i, %08x)", id, PARAM(1)); - NativeSemaphore *outptr = (NativeSemaphore*)Memory::GetPointer(PARAM(1)); - int szToCopy = outptr->size - 4; - memcpy((char*)outptr + 4, (char*)s + 4, szToCopy); + if (newCount > s->ns.maxCount) + { + RETURN(SCE_KERNEL_ERROR_ILLEGAL_COUNT); + return; + } + + if (numWaitThreadsPtr) + { + u32* numWaitThreads = (u32*)Memory::GetPointer(numWaitThreadsPtr); + *numWaitThreads = s->ns.numWaitThreads; + } + + if (newCount == -1) + s->ns.currentCount = s->ns.initCount; + else + s->ns.currentCount = newCount; + s->ns.numWaitThreads = 0; + + // We need to set the return value BEFORE rescheduling threads. RETURN(0); + + __KernelClearSemaThreads(s, SCE_KERNEL_ERROR_WAIT_CANCEL); + __KernelReSchedule("semaphore cancelled"); + } + else + { + ERROR_LOG(HLE, "sceKernelCancelSema : Trying to cancel invalid semaphore %i", id); + RETURN(error); + } +} + +//SceUID sceKernelCreateSema(const char *name, SceUInt attr, int initVal, int maxVal, SceKernelSemaOptParam *option); +// void because it changes threads. +void sceKernelCreateSema(const char* name, u32 attr, int initVal, int maxVal, u32 optionPtr) +{ + if (!name) + { + RETURN(SCE_KERNEL_ERROR_ERROR); + return; + } + + Semaphore *s = new Semaphore; + SceUID id = kernelObjects.Create(s); + + s->ns.size = sizeof(NativeSemaphore); + strncpy(s->ns.name, name, 31); + s->ns.name[31] = 0; + s->ns.attr = attr; + s->ns.initCount = initVal; + s->ns.currentCount = s->ns.initCount; + s->ns.maxCount = maxVal; + s->ns.numWaitThreads = 0; + + DEBUG_LOG(HLE,"%i=sceKernelCreateSema(%s, %08x, %i, %i, %08x)", id, s->ns.name, s->ns.attr, s->ns.initCount, s->ns.maxCount, optionPtr); + + RETURN(id); + + __KernelReSchedule("semaphore created"); +} + +//int sceKernelDeleteSema(SceUID semaid); +// void because it changes threads. +void sceKernelDeleteSema(SceUID id) +{ + DEBUG_LOG(HLE,"sceKernelDeleteSema(%i)", id); + + u32 error; + Semaphore *s = kernelObjects.Get(id, error); + if (s) + { + __KernelClearSemaThreads(s, SCE_KERNEL_ERROR_WAIT_DELETE); + RETURN(kernelObjects.Destroy(id)); + __KernelReSchedule("semaphore deleted"); + } + else + { + ERROR_LOG(HLE, "sceKernelDeleteSema : Trying to delete invalid semaphore %i", id); + RETURN(error); + } +} + +//int sceKernelDeleteSema(SceUID semaid, SceKernelSemaInfo *info); +// void because it changes threads. +void sceKernelReferSemaStatus(SceUID id, u32 infoPtr) +{ + u32 error; + Semaphore *s = kernelObjects.Get(id, error); + if (s) + { + DEBUG_LOG(HLE,"sceKernelReferSemaStatus(%i, %08x)", id, infoPtr); + Memory::WriteStruct(infoPtr, &s->ns); + RETURN(0); + __KernelReSchedule("semaphore refer status"); } else { @@ -113,32 +193,41 @@ void sceKernelReferSemaStatus() } //int sceKernelSignalSema(SceUID semaid, int signal); -void sceKernelSignalSema() +// void because it changes threads. +void sceKernelSignalSema(SceUID id, int signal) { //TODO: check that this thing really works :) - SceUID id = PARAM(0); - u32 signal = PARAM(1); u32 error; Semaphore *s = kernelObjects.Get(id, error); if (s) { - int oldval = s->ns.currentCount; + if (s->ns.currentCount + signal > s->ns.maxCount) + { + RETURN(SCE_KERNEL_ERROR_SEMA_OVF); + return; + } + int oldval = s->ns.currentCount; s->ns.currentCount += signal; DEBUG_LOG(HLE,"sceKernelSignalSema(%i, %i) (old: %i, new: %i)", id, signal, oldval, s->ns.currentCount); - + + // We need to set the return value BEFORE processing other threads. + RETURN(0); + bool wokeThreads = false; retry: - //TODO: check for threads to wake up - wake them + // TODO: PSP_SEMA_ATTR_PRIORITY std::vector::iterator iter; - for (iter = s->waitingThreads.begin(); iter!=s->waitingThreads.end(); s++) + for (iter = s->waitingThreads.begin(); iter!=s->waitingThreads.end(); iter++) { - SceUID id = *iter; - int wVal = (int)__KernelGetWaitValue(id, error); + SceUID threadID = *iter; + int wVal = (int)__KernelGetWaitValue(threadID, error); if (wVal <= s->ns.currentCount) { - __KernelResumeThread(id); s->ns.currentCount -= wVal; + s->ns.numWaitThreads--; + + __KernelResumeThreadFromWait(threadID); wokeThreads = true; s->waitingThreads.erase(iter); goto retry; @@ -148,109 +237,92 @@ retry: break; } } - //pop the thread that were released from waiting - // I don't think we should reschedule here - //if (wokeThreads) - // __KernelReSchedule("semaphore signalled"); - - RETURN(0); + __KernelReSchedule("semaphore signalled"); } else { ERROR_LOG(HLE, "sceKernelSignalSema : Trying to signal invalid semaphore %i", id); + RETURN(error;) + } +} + +void __KernelWaitSema(SceUID id, int wantedCount, u32 timeoutPtr, const char *badSemaMessage, bool processCallbacks) +{ + u32 error; + Semaphore *s = kernelObjects.Get(id, error); + if (s) + { + // We need to set the return value BEFORE processing callbacks / etc. + RETURN(0); + + if (s->ns.currentCount >= wantedCount) + s->ns.currentCount -= wantedCount; + else + { + s->ns.numWaitThreads++; + s->waitingThreads.push_back(__KernelGetCurThread()); + // TODO: timeoutPtr? + __KernelWaitCurThread(WAITTYPE_SEMA, id, wantedCount, 0, processCallbacks); + if (processCallbacks) + __KernelCheckCallbacks(); + } + + __KernelReSchedule("semaphore waited"); + } + else + { + ERROR_LOG(HLE, badSemaMessage, id); RETURN(error); } } //int sceKernelWaitSema(SceUID semaid, int signal, SceUInt *timeout); -void sceKernelWaitSema() +// void because it changes threads. +void sceKernelWaitSema(SceUID id, int wantedCount, u32 timeoutPtr) { - SceUID id = PARAM(0); - int wantedCount = PARAM(1); - u32 timeoutPtr = PARAM(2); - - u32 error; - Semaphore *s = kernelObjects.Get(id, error); - if (s) - { - DEBUG_LOG(HLE,"sceKernelWaitSema(%i, %i, %i)", id, wantedCount, timeoutPtr); - if (s->ns.currentCount >= wantedCount) //TODO fix - { - s->ns.currentCount -= wantedCount; - RETURN(0); - } - else - { - s->waitingThreads.push_back(__KernelGetCurThread()); - __KernelWaitCurThread(WAITTYPE_SEMA, id, wantedCount, 0, false); - return; - } - } - else - { - ERROR_LOG(HLE, "sceKernelWaitSema : Trying to wait for invalid semaphore %i", id); - RETURN(error); - } + DEBUG_LOG(HLE,"sceKernelWaitSema(%i, %i, %i)", id, wantedCount, timeoutPtr); + + __KernelWaitSema(id, wantedCount, timeoutPtr, "sceKernelWaitSema: Trying to wait for invalid semaphore %i", false); } //int sceKernelWaitSemaCB(SceUID semaid, int signal, SceUInt *timeout); -void sceKernelWaitSemaCB() +// void because it changes threads. +void sceKernelWaitSemaCB(SceUID id, int wantedCount, u32 timeoutPtr) { - SceUID id = PARAM(0); - int wantedCount = PARAM(1); - int timeout = PARAM(2); - DEBUG_LOG(HLE,"sceKernelWaitSemaCB(%i, %i, %i)", id, wantedCount, timeout); - u32 error; - Semaphore *s = kernelObjects.Get(id, error); - if (s) - { - DEBUG_LOG(HLE,"CurrentCount: %i, Signal: %i", s->ns.currentCount, wantedCount); - if (s->ns.currentCount >= wantedCount) //TODO fix - { - DEBUG_LOG(HLE,"Subtracting"); - s->ns.currentCount -= wantedCount; - } - else - { - s->waitingThreads.push_back(__KernelGetCurThread()); - __KernelWaitCurThread(WAITTYPE_SEMA, id, wantedCount, 0, true); - return; - } - DEBUG_LOG(HLE,"After: CurrentCount: %i, Signal: %i", s->ns.currentCount, wantedCount); - RETURN(0); - } - else - { - ERROR_LOG(HLE,"sceKernelWaitSemaCB - Bad semaphore"); - RETURN(error); - } + DEBUG_LOG(HLE,"sceKernelWaitSemaCB(%i, %i, %i)", id, wantedCount, timeoutPtr); + + __KernelWaitSema(id, wantedCount, timeoutPtr, "sceKernelWaitSemaCB: Trying to wait for invalid semaphore %i", true); } // Should be same as WaitSema but without the wait, instead returning SCE_KERNEL_ERROR_SEMA_ZERO -void sceKernelPollSema() +void sceKernelPollSema(SceUID id, int wantedCount) { - SceUID id = PARAM(0); - int wantedCount = PARAM(1); + DEBUG_LOG(HLE,"sceKernelPollSema(%i, %i)", id, wantedCount); + + if (wantedCount <= 0) + { + RETURN(SCE_KERNEL_ERROR_ILLEGAL_COUNT); + return; + } u32 error; Semaphore *s = kernelObjects.Get(id, error); if (s) { - DEBUG_LOG(HLE,"sceKernelPollSema(%i, %i)", id, wantedCount); - if (s->ns.currentCount >= wantedCount) //TODO fix + if (s->ns.currentCount >= wantedCount) { s->ns.currentCount -= wantedCount; RETURN(0); } else - { RETURN(SCE_KERNEL_ERROR_SEMA_ZERO); - } + + __KernelReSchedule("semaphore polled"); } else { - ERROR_LOG(HLE, "sceKernelPollSema : Trying to poll invalid semaphore %i", id); + ERROR_LOG(HLE, "sceKernelPollSema: Trying to poll invalid semaphore %i", id); RETURN(error); } } diff --git a/Core/HLE/sceKernelSemaphore.h b/Core/HLE/sceKernelSemaphore.h index d4c4147328..4027fda2d8 100644 --- a/Core/HLE/sceKernelSemaphore.h +++ b/Core/HLE/sceKernelSemaphore.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -17,11 +17,11 @@ #pragma once -void sceKernelCancelSema(); -void sceKernelCreateSema(); -void sceKernelDeleteSema(); -void sceKernelPollSema(); -void sceKernelReferSemaStatus(); -void sceKernelSignalSema(); -void sceKernelWaitSema(); -void sceKernelWaitSemaCB(); +void sceKernelCancelSema(SceUID id, int newCount, u32 numWaitThreadsPtr); +void sceKernelCreateSema(const char* name, u32 attr, int initVal, int maxVal, u32 optionPtr); +void sceKernelDeleteSema(SceUID id); +void sceKernelPollSema(SceUID id, int wantedCount); +void sceKernelReferSemaStatus(SceUID id, u32 infoPtr); +void sceKernelSignalSema(SceUID id, int signal); +void sceKernelWaitSema(SceUID semaid, int signal, u32 timeoutPtr); +void sceKernelWaitSemaCB(SceUID semaid, int signal, u32 timeoutPtr); diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 3880587691..e2b8105325 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -15,12 +15,18 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. +#include +#include +#include + #include "HLE.h" #include "HLETables.h" #include "../MIPS/MIPSInt.h" #include "../MIPS/MIPSCodeUtils.h" #include "../MIPS/MIPS.h" #include "../../Core/CoreTiming.h" +#include "../../Core/MemMap.h" +#include "../../Common/Action.h" #include "sceAudio.h" #include "sceKernel.h" @@ -29,17 +35,6 @@ #include "sceKernelModule.h" #include "sceKernelInterrupt.h" -#include - -enum ThreadStatus -{ - THREADSTATUS_RUNNING = 1, - THREADSTATUS_READY = 2, - THREADSTATUS_WAIT = 4, - THREADSTATUS_SUSPEND = 8, - THREADSTATUS_DORMANT = 16, - THREADSTATUS_DEAD = 32, -}; enum { ERROR_KERNEL_THREAD_ALREADY_DORMANT = 0x800201a2, @@ -72,7 +67,7 @@ const char *waitTypeStrings[] = "Vpl", "Fpl", "", - "ThreadEnd", + "ThreadEnd", // These are nonstandard wait types "AudioChannel", "Umd", "Vblank", @@ -84,6 +79,59 @@ struct SceKernelSysClock { u32 hi; }; + +struct NativeCallback +{ + SceUInt size; + char name[32]; + SceUID threadId; + u32 entrypoint; + u32 commonArgument; + + int notifyCount; + int notifyArg; +}; + +class Callback : public KernelObject +{ +public: + const char *GetName() {return nc.name;} + const char *GetTypeName() {return "CallBack";} + + void GetQuickInfo(char *ptr, int size) + { + sprintf(ptr, "thread=%i, argument= %08x", + //hackAddress, + nc.threadId, + nc.commonArgument); + } + + ~Callback() + { + } + + static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_CBID; } + int GetIDType() const { return SCE_KERNEL_TMID_Callback; } + + NativeCallback nc; + + u32 savedPC; + u32 savedRA; + u32 savedV0; + u32 savedV1; + u32 savedIdRegister; + + /* + SceUInt attr; + SceUInt initPattern; + SceUInt currentPattern; + int numWaitThreads; + */ + + bool forceDelete; +}; + +// Real PSP struct, don't change the fields struct NativeThread { u32 nativeSize; @@ -109,11 +157,8 @@ struct NativeThread int numReleases; }; -struct CallbackNotification -{ - SceUID cbid; - int count; - int arg; +struct ThreadWaitInfo { + u32 waitValue; }; class Thread : public KernelObject @@ -133,20 +178,23 @@ public: (nt.status & THREADSTATUS_DEAD) ? "DEAD" : "", nt.waitType, nt.waitID, - waitValue); + waitInfo.waitValue); } - static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_THID; } - int GetIDType() const { return SCE_KERNEL_TMID_Thread; } - bool GrabStack(u32 &stackSize) + + static u32 GetMissingErrorCode() { return SCE_KERNEL_ERROR_UNKNOWN_THID; } + + int GetIDType() const { return SCE_KERNEL_TMID_Thread; } + + bool AllocateStack(u32 &stackSize) { if (nt.attr & PSP_THREAD_ATTR_KERNEL) { // Allocate stacks for kernel threads (idle) in kernel RAM - stackBlock = kernelMemory.Alloc(stackSize, true, "stack"); + stackBlock = kernelMemory.Alloc(stackSize, true, (std::string("stack/") + nt.name).c_str()); } else { - stackBlock = userMemory.Alloc(stackSize, true, "stack"); + stackBlock = userMemory.Alloc(stackSize, true, (std::string("stack/") + nt.name).c_str()); } if (stackBlock == (u32)-1) { @@ -163,25 +211,55 @@ public: context.r[MIPS_REG_SP] -= 512; return true; } - ~Thread() - { - userMemory.Free(stackBlock); + + void FreeStack() { + if (stackBlock != 0) { + DEBUG_LOG(HLE, "Freeing thread stack %s", nt.name); + if (nt.attr & PSP_THREAD_ATTR_KERNEL) { + kernelMemory.Free(stackBlock); + } else { + userMemory.Free(stackBlock); + } + stackBlock = 0; + } } + ~Thread() + { + FreeStack(); + } + + void setReturnValue(u32 retval); + + // Utils + bool isRunning() const { return (nt.status & THREADSTATUS_RUNNING) != 0; } + bool isStopped() const { return (nt.status & THREADSTATUS_DORMANT) != 0; } + bool isReady() const { return (nt.status & THREADSTATUS_DORMANT) != 0; } + bool isWaiting() const { return (nt.status & THREADSTATUS_WAIT) != 0; } + bool isSuspended() const { return (nt.status & THREADSTATUS_SUSPEND) != 0; } + NativeThread nt; - u32 waitValue; + ThreadWaitInfo waitInfo; bool sleeping; + SceUID moduleId; bool isProcessingCallbacks; ThreadContext context; - std::vector callbacks; + std::set registeredCallbacks[THREAD_CALLBACK_NUM_TYPES]; + std::list readyCallbacks[THREAD_CALLBACK_NUM_TYPES]; + + std::list pendingMipsCalls; u32 stackBlock; }; +void __KernelExecuteMipsCallOnCurrentThread(int callId); + + +int g_inCbCount = 0; Thread *__KernelCreateThread(SceUID &id, SceUID moduleID, const char *name, u32 entryPoint, u32 priority, int stacksize, u32 attr); @@ -199,6 +277,9 @@ SceUID threadIdleID[2]; int eventScheduledWakeup; +bool dispatchEnabled = true; + + // This seems nasty SceUID curModule; @@ -206,7 +287,14 @@ SceUID curModule; //STATE END ////////////////////////////////////////////////////////////////////////// -u32 __KernelCallbackReturnAddress() + +// TODO: Should move to this wrapper so we can keep the current thread as a SceUID instead +// of a dangerous raw pointer. +Thread *__GetCurrentThread() { + return currentThread; +} + +u32 __KernelMipsCallReturnAddress() { return cbReturnHackAddr; } @@ -222,6 +310,8 @@ void __KernelThreadingInit() { u32 blockSize = 4 * 4 + 4 * 2 * 3; // One 16-byte thread plus 3 8-byte "hacks" + dispatchEnabled = true; + idleThreadHackAddr = kernelMemory.Alloc(blockSize, false, "threadrethack"); // Make sure it got allocated where we expect it... at the very start of kernel RAM //CHECK_EQ(idleThreadHackAddr & 0x3FFFFFFF, 0x08000000); @@ -246,9 +336,9 @@ void __KernelThreadingInit() eventScheduledWakeup = CoreTiming::RegisterEvent("ScheduledWakeup", &hleScheduledWakeup); // Create the two idle threads, as well. With the absolute minimal possible priority. - // Zero stack size. Hm, if callbacks are ever to run on these threads, that's not a good idea. - __KernelCreateThread(threadIdleID[0], 0, "idle0", idleThreadHackAddr, 0x7f, 0, PSP_THREAD_ATTR_KERNEL); - __KernelCreateThread(threadIdleID[1], 0, "idle1", idleThreadHackAddr, 0x7f, 0, PSP_THREAD_ATTR_KERNEL); + // 4096 stack size - don't know what the right value is. Hm, if callbacks are ever to run on these threads... + __KernelCreateThread(threadIdleID[0], 0, "idle0", idleThreadHackAddr, 0x7f, 4096, PSP_THREAD_ATTR_KERNEL); + __KernelCreateThread(threadIdleID[1], 0, "idle1", idleThreadHackAddr, 0x7f, 4096, PSP_THREAD_ATTR_KERNEL); // These idle threads are later started in LoadExec, which calls __KernelStartIdleThreads below. } @@ -265,12 +355,11 @@ void __KernelStartIdleThreads() } } -void _sceKernelIdle() +void __KernelIdle() { CoreTiming::Idle(); // Advance must happen between Idle and Reschedule, so that threads that were waiting for something // that was triggered at the end of the Idle period must get a chance to be scheduled. - // get a chance to be rescheduled. CoreTiming::Advance(); // In Advance, we might trigger an interrupt such as vblank. @@ -285,6 +374,7 @@ void __KernelThreadingShutdown() threadReturnHackAddr = 0; cbReturnHackAddr = 0; currentThread = 0; + intReturnHackAddr = 0; threadqueue.clear(); } @@ -293,7 +383,7 @@ u32 __KernelGetWaitValue(SceUID threadID, u32 &error) Thread *t = kernelObjects.Get(threadID, error); if (t) { - return t->waitValue; + return t->waitInfo.waitValue; } else { @@ -302,30 +392,6 @@ u32 __KernelGetWaitValue(SceUID threadID, u32 &error) } } -// TODO: If cbid == -1, notify the callback ID on all threads that have it. -void __KernelNotifyCallback(SceUID threadID, SceUID cbid, u32 notifyArg) -{ - u32 error; - Thread *t = kernelObjects.Get(threadID, error); - if (t) - { - for (size_t i = 0; i < t->callbacks.size(); t++) - { - if (t->callbacks[i].cbid == cbid) - { - t->callbacks[i].arg = notifyArg; - t->callbacks[i].count++; - return; - } - } - CallbackNotification cb; - cb.cbid = cbid; - cb.arg = notifyArg; - cb.count = 1; - } - // TODO: error checking -} - void sceKernelReferThreadStatus() { SceUID threadID = PARAM(0); @@ -338,8 +404,11 @@ void sceKernelReferThreadStatus() { DEBUG_LOG(HLE,"sceKernelReferThreadStatus(%i, %08x)", threadID, PARAM(1)); void *outptr = (void*)Memory::GetPointer(PARAM(1)); - int sz = sizeof(NativeThread); - t->nt.nativeSize = sz; + u32 wantedSize = *(u32 *)outptr; + u32 sz = sizeof(NativeThread); + if (wantedSize) { + t->nt.nativeSize = sz = std::min(sz, wantedSize); + } memcpy(outptr, &(t->nt), sz); RETURN(0); } @@ -396,7 +465,7 @@ void sceKernelGetThreadmanIdType() // Saves the current CPU context void __KernelSaveContext(ThreadContext *ctx) { - for (int i=0; i<32; i++) + for (int i = 0; i < 32; i++) { ctx->r[i] = currentMIPS->r[i]; ctx->f[i] = currentMIPS->f[i]; @@ -464,6 +533,8 @@ bool __KernelTriggerWait(WaitType type, int id, bool dontSwitch) { t->nt.status = THREADSTATUS_READY; } + // Non-waiting threads do not process callbacks. + t->isProcessingCallbacks = false; doneAnything = true; } } @@ -482,7 +553,7 @@ bool __KernelTriggerWait(WaitType type, int id, bool dontSwitch) return true; } -u32 __KernelResumeThread(SceUID threadID) +u32 __KernelResumeThreadFromWait(SceUID threadID) { u32 error; Thread *t = kernelObjects.Get(threadID, error); @@ -491,11 +562,12 @@ u32 __KernelResumeThread(SceUID threadID) t->nt.status &= ~THREADSTATUS_WAIT; if (!(t->nt.status & (THREADSTATUS_SUSPEND | THREADSTATUS_WAIT))) t->nt.status |= THREADSTATUS_READY; + t->isProcessingCallbacks = false; return 0; } else { - ERROR_LOG(HLE, "__KernelResumeThread(%d): bad thread: %08x", threadID, error); + ERROR_LOG(HLE, "__KernelResumeThreadFromWait(%d): bad thread: %08x", threadID, error); return error; } } @@ -503,12 +575,11 @@ u32 __KernelResumeThread(SceUID threadID) // makes the current thread wait for an event void __KernelWaitCurThread(WaitType type, SceUID waitID, u32 waitValue, int timeout, bool processCallbacks) { - currentThread->nt.status = THREADSTATUS_WAIT; currentThread->nt.waitID = waitID; currentThread->nt.waitType = type; + __KernelChangeThreadState(currentThread, THREADSTATUS_WAIT); currentThread->nt.numReleases++; - currentThread->waitValue = waitValue; - currentThread->isProcessingCallbacks = processCallbacks; + currentThread->waitInfo.waitValue = waitValue; if (timeout) { // TODO: @@ -519,7 +590,8 @@ void __KernelWaitCurThread(WaitType type, SceUID waitID, u32 waitValue, int time // TODO: time waster char temp[256]; sprintf(temp, "started wait %s", waitTypeStrings[(int)type]); - __KernelReSchedule(temp); + + __KernelReSchedule(processCallbacks, temp); // TODO: Remove thread from Ready queue? } @@ -536,32 +608,26 @@ void __KernelScheduleWakeup(SceUID threadID, int usFromNow) void __KernelRemoveFromThreadQueue(Thread *t) { - for (int i = 0; i < threadqueue.size(); i++) + for (size_t i = 0; i < threadqueue.size(); i++) { if (threadqueue[i] == t) { - DEBUG_LOG(HLE, "Deleted thread %p from thread queue", t); + DEBUG_LOG(HLE, "Deleted thread %p (%i) from thread queue", t, t->GetUID()); threadqueue.erase(threadqueue.begin() + i); return; } } } -void __KernelReSchedule(const char *reason) -{ - if (__IsInInterrupt()) - { - reason = "WTF"; - } +Thread *__KernelNextThread() { // round-robin scheduler // seems to work ? // not accurate! -retry: int bestthread = -1; - int prio=0xffffff; + int prio = 0xffffff; int next = 0; - for (size_t i=0; icontext); - // currentThread->context.pc = pc; - DEBUG_LOG(HLE,"Context saved (%s): %i - %s - pc: %08x", reason, currentThread->GetUID(), currentThread->GetName(), currentMIPS->pc); - } - //currentThread->nt.status = THREADSTATUS_READY; - currentThread = threadqueue[bestthread]; - __KernelLoadContext(¤tThread->context); - DEBUG_LOG(HLE,"Context loaded (%s): %i - %s - pc: %08x", reason, currentThread->GetUID(), currentThread->GetName(), currentMIPS->pc); - //currentThread->nt.status = THREADSTATUS_RUNNING; - // currentMIPS->pc -= 4; //compensate for +=4 ADJUSTPC + __KernelSwitchContext(nextThread, reason); return; } else { - _dbg_assert_msg_(HLE,0,"No threads available to schedule! There should be at least one idle thread available."); - // This shouldn't happen anymore now that we have idle threads. - - // No threads want to run : increase timers, skip time in general - // MessageBox(0,"Error: no thread to transition to",0,0); - - // DEBUG_LOG(HLE,"No thread to transition to, idling"); + // This shouldn't happen anymore now that we have idle threads. + _dbg_assert_msg_(HLE,0,"No threads available to schedule! There should be at least one idle thread available."); CoreTiming::Idle(); goto retry; } } + +void __KernelReSchedule(bool doCallbacks, const char *reason) +{ + Thread *thread = currentThread; + if (doCallbacks) + { + if (thread) + thread->isProcessingCallbacks = doCallbacks; + __KernelCheckCallbacks(); + } + __KernelReSchedule(reason); + if (doCallbacks && thread == currentThread) { + if (thread->isRunning()) { + thread->isProcessingCallbacks = false; + } + } +} + + ////////////////////////////////////////////////////////////////////////// // Thread Management @@ -624,7 +709,7 @@ void sceKernelCheckThreadStack() { u32 error; Thread *t = kernelObjects.Get(__KernelGetCurThread(), error); - u32 diff = abs((s64)t->stackBlock - (s64)currentMIPS->r[MIPS_REG_SP]); + u32 diff = (u32)abs((s64)t->stackBlock - (s64)currentMIPS->r[MIPS_REG_SP]); ERROR_LOG(HLE, "%i=sceKernelCheckThreadStack()", diff); RETURN(diff); //Blatant lie } @@ -646,7 +731,7 @@ void ThreadContext::reset() } vfpuCtrl[VFPU_CTRL_SPREFIX] = 0xe4; // neutral vfpuCtrl[VFPU_CTRL_TPREFIX] = 0xe4; // neutral - vfpuCtrl[VFPU_CTRL_DPREFIX] = 0x0; + vfpuCtrl[VFPU_CTRL_DPREFIX] = 0x0; // neutral vfpuCtrl[VFPU_CTRL_CC] = 0x3f; vfpuCtrl[VFPU_CTRL_INF4] = 0; vfpuCtrl[VFPU_CTRL_RCX0] = 0x3f800001; @@ -664,7 +749,7 @@ void ThreadContext::reset() lo = 0; } -Thread *__KernelCreateThread(SceUID &id, SceUID moduleID, const char *name, u32 entryPoint, u32 priority, int stacksize, u32 attr) +Thread *__KernelCreateThread(SceUID &id, SceUID moduleId, const char *name, u32 entryPoint, u32 priority, int stacksize, u32 attr) { Thread *t = new Thread; id = kernelObjects.Create(t); @@ -686,7 +771,7 @@ Thread *__KernelCreateThread(SceUID &id, SceUID moduleID, const char *name, u32 t->nt.status = THREADSTATUS_DORMANT; t->nt.waitType = WAITTYPE_NONE; t->nt.waitID = 0; - t->waitValue = 0; + memset(&t->waitInfo, 0, sizeof(t->waitInfo)); t->nt.exitStatus = 0; t->nt.numInterruptPreempts = 0; t->nt.numReleases = 0; @@ -694,14 +779,16 @@ Thread *__KernelCreateThread(SceUID &id, SceUID moduleID, const char *name, u32 t->nt.runForClocks.low = 0; t->nt.runForClocks.hi = 0; t->nt.wakeupCount = 0; - if (moduleID) - t->nt.gpreg = __KernelGetModuleGP(moduleID); + t->isProcessingCallbacks = false; + if (moduleId) + t->nt.gpreg = __KernelGetModuleGP(moduleId); else t->nt.gpreg = 0; // sceKernelStartThread will take care of this. + t->moduleId = moduleId; strncpy(t->nt.name, name, 32); t->context.r[MIPS_REG_RA] = threadReturnHackAddr; //hack! TODO fix - t->GrabStack(t->nt.stackSize); // can change the stacksize! + t->AllocateStack(t->nt.stackSize); // can change the stacksize! return t; } @@ -720,8 +807,8 @@ void __KernelSetupRootThread(SceUID moduleID, int args, const char *argp, int pr mipsr4k.r[MIPS_REG_SP] -= 256; u32 location = mipsr4k.r[MIPS_REG_SP]; mipsr4k.r[MIPS_REG_A1] = location; - for (int i=0; i 0x4000) stacksize = 0x4000; - SceUID id; __KernelCreateThread(id, curModule, threadName, entry, prio, stacksize, attr); INFO_LOG(HLE,"%i = sceKernelCreateThread(name=\"%s\", entry= %08x, stacksize=%i )", id, threadName, entry, stacksize); @@ -745,7 +829,7 @@ void sceKernelCreateThread() } -void sceKernelStartThread() +u32 sceKernelStartThread() { int threadToStartID = PARAM(0); u32 argSize = PARAM(1); @@ -755,50 +839,72 @@ void sceKernelStartThread() { u32 error; Thread *startThread = kernelObjects.Get(threadToStartID, error); + if (startThread == 0) + { + ERROR_LOG(HLE,"%08x=sceKernelStartThread(thread=%i, argSize=%i, argPtr= %08x): thread does not exist!", + error,threadToStartID,argSize,argBlockPtr) + return error; + } if (startThread->nt.status != THREADSTATUS_DORMANT) { - //Not dormant, WTF? - RETURN(ERROR_KERNEL_THREAD_IS_NOT_DORMANT); - return; + //Not dormant, WTF? + return ERROR_KERNEL_THREAD_IS_NOT_DORMANT; } INFO_LOG(HLE,"sceKernelStartThread(thread=%i, argSize=%i, argPtr= %08x )", threadToStartID,argSize,argBlockPtr); - RETURN(0); //return success (this does not exit this function) - startThread->nt.status = THREADSTATUS_READY; u32 sp = startThread->context.r[MIPS_REG_SP]; - if (argBlockPtr) - { - startThread->context.r[MIPS_REG_A0] = argSize; - startThread->context.r[MIPS_REG_A1] = sp; - } - else - { - startThread->context.r[MIPS_REG_A0] = 0; - startThread->context.r[MIPS_REG_A1] = 0; - } - startThread->context.r[MIPS_REG_GP] = startThread->nt.gpreg; + if (argBlockPtr && argSize > 0) + { + startThread->context.r[MIPS_REG_A0] = argSize; + startThread->context.r[MIPS_REG_A1] = sp; + } + else + { + startThread->context.r[MIPS_REG_A0] = 0; + startThread->context.r[MIPS_REG_A1] = 0; + } + startThread->context.r[MIPS_REG_GP] = startThread->nt.gpreg; //now copy argument to stack for (int i = 0; i < (int)argSize; i++) - Memory::Write_U8(Memory::Read_U8(argBlockPtr + i), sp + i); + Memory::Write_U8(argBlockPtr ? Memory::Read_U8(argBlockPtr + i) : 0, sp + i); + + if (!argBlockPtr && argSize > 0) { + WARN_LOG(HLE,"sceKernelStartThread : had NULL arg"); + } + return 0; } else { ERROR_LOG(HLE,"thread %i trying to start itself", threadToStartID); - RETURN(-1); + return -1; } } void sceKernelGetThreadStackFreeSize() { - SceUID threadID = PARAM(0); - INFO_LOG(HLE,"sceKernelGetThreadStackFreeSize(%i)", threadID); - u32 error; - Thread *thread = kernelObjects.Get(threadID, error); + SceUID threadID = PARAM(0); + Thread *thread; + + INFO_LOG(HLE,"sceKernelGetThreadStackFreeSize(%i)", threadID); + + if (threadID == 0) + thread = currentThread; + else + { + u32 error; + thread = kernelObjects.Get(threadID, error); + if (thread == 0) + { + ERROR_LOG(HLE,"sceKernelGetThreadStackFreeSize: invalid thread id %i", threadID); + RETURN(error); + return; + } + } // Scan the stack for 0xFF int sz = 0; @@ -812,10 +918,15 @@ void sceKernelGetThreadStackFreeSize() RETURN(sz & ~3); } - -void _sceKernelReturnFromThread() +// Internal function +void __KernelReturnFromThread() { - INFO_LOG(HLE,"_sceKernelReturnFromThread : %s", currentThread->GetName()); + INFO_LOG(HLE,"__KernelReturnFromThread : %s", currentThread->GetName()); + // TEMPORARY HACK: kill the stack of the root thread early: + if (!strcmp(currentThread->GetName(), "root")) { + currentThread->FreeStack(); + } + currentThread->nt.exitStatus = currentThread->context.r[2]; currentThread->nt.status = THREADSTATUS_DORMANT; @@ -825,6 +936,8 @@ void _sceKernelReturnFromThread() // Wake them if (!__KernelTriggerWait(WAITTYPE_THREADEND, __KernelGetCurThread())) __KernelReSchedule("return from thread"); + + // The stack will be deallocated when the thread is deleted. } void sceKernelExitThread() @@ -836,6 +949,8 @@ void sceKernelExitThread() // Wake them if (!__KernelTriggerWait(WAITTYPE_THREADEND, __KernelGetCurThread())) __KernelReSchedule("exited thread"); + + // The stack will be deallocated when the thread is deleted. } void _sceKernelExitThread() @@ -847,6 +962,8 @@ void _sceKernelExitThread() // Wake them if (!__KernelTriggerWait(WAITTYPE_THREADEND, __KernelGetCurThread())) __KernelReSchedule("exit-deleted thread"); + + // The stack will be deallocated when the thread is deleted. } void sceKernelExitDeleteThread() @@ -859,6 +976,8 @@ void sceKernelExitDeleteThread() ERROR_LOG(HLE,"sceKernelExitDeleteThread()"); currentThread->nt.status = THREADSTATUS_DORMANT; currentThread->nt.exitStatus = PARAM(0); + //userMemory.Free(currentThread->stackBlock); + currentThread->stackBlock = -1; __KernelRemoveFromThreadQueue(t); currentThread = 0; @@ -874,6 +993,21 @@ void sceKernelExitDeleteThread() } } +u32 sceKernelSuspendDispatchThread() +{ + u32 oldDispatchSuspended = !dispatchEnabled; + dispatchEnabled = false; + DEBUG_LOG(HLE,"%i=sceKernelSuspendDispatchThread()", oldDispatchSuspended); + return oldDispatchSuspended; +} + +u32 sceKernelResumeDispatchThread(u32 suspended) +{ + u32 oldDispatchSuspended = !dispatchEnabled; + dispatchEnabled = !suspended; + DEBUG_LOG(HLE,"%i=sceKernelResumeDispatchThread(%i)", oldDispatchSuspended, suspended); + return oldDispatchSuspended; +} void sceKernelRotateThreadReadyQueue() { @@ -936,6 +1070,12 @@ SceUID __KernelGetCurThread() return currentThread->GetUID(); } +SceUID __KernelGetCurThreadModuleId() +{ + return currentThread->moduleId; +} + + void sceKernelGetThreadId() { u32 retVal = currentThread->GetUID(); @@ -943,6 +1083,13 @@ void sceKernelGetThreadId() RETURN(retVal); } +void sceKernelGetThreadCurrentPriority() +{ + u32 retVal = __GetCurrentThread()->nt.currentPriority; + DEBUG_LOG(HLE,"%i = sceKernelGetThreadCurrentPriority()", retVal); + RETURN(retVal); +} + void sceKernelChangeCurrentThreadAttr() { int clearAttr = PARAM(0); @@ -967,7 +1114,7 @@ void sceKernelChangeThreadPriority() } else { - ERROR_LOG(HLE,"%08x=sceKernelChangeThreadPriority(%i, %i) failed", error, id, PARAM(1)); + ERROR_LOG(HLE,"%08x=sceKernelChangeThreadPriority(%i, %i) failed - no such thread", error, id, PARAM(1)); RETURN(error); } } @@ -981,6 +1128,8 @@ void sceKernelDelayThreadCB() SceUID curThread = __KernelGetCurThread(); __KernelScheduleWakeup(curThread, usec); __KernelWaitCurThread(WAITTYPE_DELAY, curThread, 0, 0, true); + if (__KernelCheckCallbacks()) + __KernelExecutePendingMipsCalls(); } void sceKernelDelayThread() @@ -993,51 +1142,81 @@ void sceKernelDelayThread() __KernelWaitCurThread(WAITTYPE_DELAY, curThread, 0, 0, false); } +u32 __KernelGetThreadPrio(SceUID id) +{ + u32 error; + Thread *thread = kernelObjects.Get(id, error); + if (thread) + return thread->nt.currentPriority; + return 0; +} + ////////////////////////////////////////////////////////////////////////// // WAIT/SLEEP ETC ////////////////////////////////////////////////////////////////////////// void sceKernelWakeupThread() { - SceUID id = PARAM(0); + SceUID uid = PARAM(0); u32 error; - Thread *t = kernelObjects.Get(id, error); + Thread *t = kernelObjects.Get(uid, error); if (t) { - t->nt.wakeupCount++; - DEBUG_LOG(HLE,"sceKernelWakeupThread(%i) - wakeupCount incremented to %i",id,t->nt.wakeupCount); - if (t->nt.waitType == WAITTYPE_SLEEP && t->nt.wakeupCount>=0) - { - __KernelResumeThread(id); + if (t->nt.waitType != WAITTYPE_SLEEP) { + t->nt.wakeupCount++; + DEBUG_LOG(HLE,"sceKernelWakeupThread(%i) - wakeupCount incremented to %i", uid, t->nt.wakeupCount); + RETURN(0); + } else { + __KernelResumeThreadFromWait(uid); } + } + else { + ERROR_LOG(HLE,"sceKernelWakeupThread(%i) - bad thread id"); + RETURN(error); + } +} + +void sceKernelCancelWakeupThread() +{ + SceUID uid = PARAM(0); + u32 error; + if (uid == 0) uid = __KernelGetCurThread(); + Thread *t = kernelObjects.Get(uid, error); + if (t) + { + int wCount = t->nt.wakeupCount; + t->nt.wakeupCount = 0; + DEBUG_LOG(HLE,"sceKernelCancelWakeupThread(%i) - wakeupCount reset from %i", uid, wCount); + RETURN(wCount); + } + else { + ERROR_LOG(HLE,"sceKernelCancelWakeupThread(%i) - bad thread id"); + RETURN(error); + } +} + +static void __KernelSleepThread(bool doCallbacks) { + DEBUG_LOG(HLE,"sceKernelSleepThread() - wakeupCount decremented to %i", currentThread->nt.wakeupCount); + if (currentThread->nt.wakeupCount > 0) { + currentThread->nt.wakeupCount--; + RETURN(0); + } else { + RETURN(0); + __KernelWaitCurThread(WAITTYPE_SLEEP, 0, 0, 0, doCallbacks); } - RETURN(0); } void sceKernelSleepThread() { - currentThread->nt.wakeupCount--; - DEBUG_LOG(HLE,"sceKernelSleepThread() - wakeupCount decremented to %i", currentThread->nt.wakeupCount); - if (currentThread->nt.wakeupCount < 0) - __KernelWaitCurThread(WAITTYPE_SLEEP, 0, 0, 0, false); - else - { - RETURN(0); - } + __KernelSleepThread(false); } //the homebrew PollCallbacks void sceKernelSleepThreadCB() { - DEBUG_LOG(HLE,"sceKernelSleepThreadCB()"); - //set it to waiting - currentThread->nt.wakeupCount--; - DEBUG_LOG(HLE,"sceKernelSleepThread() - wakeupCount decremented to %i", currentThread->nt.wakeupCount); - if (currentThread->nt.wakeupCount < 0) - __KernelWaitCurThread(WAITTYPE_SLEEP, 0, 0, 0, true); - else - { - RETURN(0); - } + DEBUG_LOG(HLE, "sceKernelSleepThreadCB()"); + __KernelSleepThread(true); + __KernelCheckCallbacks(); + __KernelExecutePendingMipsCalls(); } void sceKernelWaitThreadEnd() @@ -1048,12 +1227,11 @@ void sceKernelWaitThreadEnd() Thread *t = kernelObjects.Get(id, error); if (t) { - if (t->nt.status != THREADSTATUS_DORMANT) - { + if (t->nt.status != THREADSTATUS_DORMANT) { __KernelWaitCurThread(WAITTYPE_THREADEND, id, 0, 0, false); - return; + } else { + DEBUG_LOG(HLE,"sceKernelWaitThreadEnd - thread %i already ended. Doing nothing.", id); } - DEBUG_LOG(HLE,"sceKernelWaitThreadEnd - thread %i already ended. Doing nothing.", id); } else { @@ -1070,12 +1248,12 @@ void sceKernelWaitThreadEndCB() Thread *t = kernelObjects.Get(id, error); if (t) { - if (t->nt.status != THREADSTATUS_DORMANT) - { + if (t->nt.status != THREADSTATUS_DORMANT) { __KernelWaitCurThread(WAITTYPE_THREADEND, id, 0, 0, true); - return; - } - DEBUG_LOG(HLE,"sceKernelWaitThreadEnd - thread %i already ended. Doing nothing.", id); + } else { + DEBUG_LOG(HLE,"sceKernelWaitThreadEnd - thread %i already ended. Doing nothing.", id); + } + __KernelCheckCallbacks(); } else { @@ -1095,3 +1273,528 @@ void sceKernelResumeThread() DEBUG_LOG(HLE,"UNIMPL sceKernelResumeThread"); RETURN(0); } + + + +////////////////////////////////////////////////////////////////////////// +// CALLBACKS +////////////////////////////////////////////////////////////////////////// + + +// Internal API +u32 __KernelCreateCallback(const char *name, u32 entrypoint, u32 commonArg) +{ + Callback *cb = new Callback; + SceUID id = kernelObjects.Create(cb); + + cb->nc.size = sizeof(NativeCallback); + strcpy(cb->nc.name, name); + + cb->nc.entrypoint = entrypoint; + cb->nc.threadId = __KernelGetCurThread(); + cb->nc.commonArgument = commonArg; + cb->nc.notifyCount = 0; + cb->nc.notifyArg = 0; + + cb->forceDelete = false; + + return id; +} + +void sceKernelCreateCallback() +{ + u32 entrypoint = PARAM(1); + u32 callbackArg = PARAM(2); + + const char *name = Memory::GetCharPointer(PARAM(0)); + + u32 id = __KernelCreateCallback(name, entrypoint, callbackArg); + + DEBUG_LOG(HLE,"%i=sceKernelCreateCallback(name=%s,entry= %08x, callbackArg = %08x)", id, name, entrypoint, callbackArg); + + RETURN(id); +} + +void sceKernelDeleteCallback() +{ + SceUID id = PARAM(0); + DEBUG_LOG(HLE,"sceKernelDeleteCallback(%i)", id); + + // TODO: Make sure it's gone from all threads first! + + RETURN(kernelObjects.Destroy(id)); +} + +// Rarely used +void sceKernelNotifyCallback() +{ + SceUID cbId = PARAM(0); + u32 arg = PARAM(1); + DEBUG_LOG(HLE,"sceKernelNotifyCallback(%i, %i)", cbId, arg); + + __KernelNotifyCallback(THREAD_CALLBACK_USER_DEFINED, __KernelGetCurThread(), cbId, arg); + RETURN(0); +} + +void sceKernelCancelCallback() +{ + SceUID cbId = PARAM(0); + ERROR_LOG(HLE,"sceKernelCancelCallback(%i) - BAD", cbId); + u32 error; + Callback *cb = kernelObjects.Get(cbId, error); + if (cb) { + // This is what JPCSP does. Huh? + cb->nc.notifyArg = 0; + RETURN(0); + } else { + ERROR_LOG(HLE,"sceKernelCancelCallback(%i) - bad cbId", cbId); + RETURN(error); + } + RETURN(0); +} + +void sceKernelGetCallbackCount() +{ + SceUID cbId = PARAM(0); + u32 error; + Callback *cb = kernelObjects.Get(cbId, error); + if (cb) { + RETURN(cb->nc.notifyCount); + } else { + ERROR_LOG(HLE,"sceKernelGetCallbackCount(%i) - bad cbId", cbId); + RETURN(error); + } +} + +void sceKernelReferCallbackStatus() +{ + SceUID cbId = PARAM(0); + u32 statusAddr = PARAM(1); + u32 error; + Callback *c = kernelObjects.Get(cbId, error); + if (c) { + DEBUG_LOG(HLE,"sceKernelReferCallbackStatus(%i, %08x)", cbId, statusAddr); + if (Memory::IsValidAddress(statusAddr)) { + Memory::WriteStruct(statusAddr, &c->nc); + } // else TODO + RETURN(0); + } else { + ERROR_LOG(HLE,"sceKernelReferCallbackStatus(%i, %08x) - bad cbId", cbId, statusAddr); + RETURN(error); + } +} + +// Owns outstanding MIPS calls and provides a way to get them by ID. +// TODO: MipsCall structs are kinda big, try to cut down on the copying by owning pointers instead. +class MipsCallManager { +public: + MipsCallManager() : idGen_(0) {} + int add(MipsCall *call) { + int id = genId(); + calls_.insert(std::pair(id, call)); + return id; + } + MipsCall *get(int id) { + return calls_[id]; + } + MipsCall *pop(int id) { + MipsCall *temp = calls_[id]; + calls_.erase(id); + return temp; + } + +private: + int genId() { return ++idGen_; } + std::map calls_; + int idGen_; +}; + +MipsCallManager mipsCalls; + + +class ActionAfterMipsCall : public Action +{ +public: + virtual void run(); + Thread *thread; + + // Saved thread state + int status; + WaitType waitType; + int waitId; + ThreadWaitInfo waitInfo; + bool isProcessingCallbacks; + + Action *chainedAction; +}; + +void ActionAfterMipsCall::run() { + thread->nt.status = status; + thread->nt.waitType = waitType; + thread->nt.waitID = waitId; + thread->waitInfo = waitInfo; + thread->isProcessingCallbacks = isProcessingCallbacks; + + if (chainedAction) { + chainedAction->run(); + delete chainedAction; + } +} + + +void Thread::setReturnValue(u32 retval) +{ + if (this == currentThread) { + if (g_inCbCount) { + int callId = currentMIPS->r[MIPS_REG_CALL_ID]; + MipsCall *call = mipsCalls.get(callId); + if (call) { + call->savedV0 = retval; + } else { + ERROR_LOG(HLE, "Failed to inject return value %08x in thread", retval); + } + } else { + currentMIPS->r[2] = retval; + } + } else { + context.r[2] = retval; + } +} + +void __KernelSwitchContext(Thread *target, const char *reason) +{ + if (currentThread) // It might just have been deleted. + { + __KernelSaveContext(¤tThread->context); + DEBUG_LOG(HLE,"Context saved (%s): %i - %s - pc: %08x", reason, currentThread->GetUID(), currentThread->GetName(), currentMIPS->pc); + } + currentThread = target; + __KernelLoadContext(¤tThread->context); + DEBUG_LOG(HLE,"Context loaded (%s): %i - %s - pc: %08x", reason, currentThread->GetUID(), currentThread->GetName(), currentMIPS->pc); + + __KernelExecutePendingMipsCalls(); +} + +void __KernelChangeThreadState(Thread *thread, ThreadStatus newStatus) { + if (!thread || thread->nt.status == newStatus) + return; + + if (!dispatchEnabled && thread == currentThread && newStatus != THREADSTATUS_RUNNING) { + ERROR_LOG(HLE, "Dispatching suspended, not changing thread state"); + return; + } + + // TODO: JPSCP has many conditions here, like removing wait timeout actions etc. + // if (thread->nt.status == THREADSTATUS_WAIT && newStatus != THREADSTATUS_WAITSUSPEND) { + + thread->nt.status = newStatus; + + if (newStatus == THREADSTATUS_WAIT) { + if (thread->nt.waitType == WAITTYPE_NONE) { + ERROR_LOG(HLE, "Waittype none not allowed here"); + } + + // Schedule deletion of stopped threads here. if (thread->isStopped()) + } +} + + +bool __CanExecuteCallbackNow(Thread *thread) { + return g_inCbCount == 0; +} + +void __KernelCallAddress(Thread *thread, u32 entryPoint, Action *afterAction, bool returnVoid, std::vector args) { + if (thread) { + ActionAfterMipsCall *after = new ActionAfterMipsCall(); + after->chainedAction = afterAction; + after->thread = thread; + after->status = thread->nt.status; + after->waitType = thread->nt.waitType; + after->waitId = thread->nt.waitID; + after->waitInfo = thread->waitInfo; + + afterAction = after; + + // Release thread from waiting + thread->nt.waitType = WAITTYPE_NONE; + + __KernelChangeThreadState(thread, THREADSTATUS_READY); + } + + MipsCall *call = new MipsCall(); + call->entryPoint = entryPoint; + for (size_t i = 0; i < args.size(); i++) { + call->args[i] = args[i]; + } + call->numArgs = args.size(); + call->doAfter = afterAction; + call->tag = "callAddress"; + + int callId = mipsCalls.add(call); + + bool called = false; + if (!thread || thread == currentThread) { + if (__CanExecuteCallbackNow(thread)) { + thread = currentThread; + __KernelChangeThreadState(thread, THREADSTATUS_RUNNING); + __KernelExecuteMipsCallOnCurrentThread(callId); + called = true; + } + } + + if (!called) { + DEBUG_LOG(HLE, "Making mipscall pending on thread"); + thread->pendingMipsCalls.push_back(callId); + } +} + +void __KernelExecuteMipsCallOnCurrentThread(int callId) +{ + if (g_inCbCount > 0) { + WARN_LOG(HLE, "__KernelExecuteMipsCallOnCurrentThread: Already in a callback!"); + } + DEBUG_LOG(HLE, "Executing mipscall %i", callId); + MipsCall *call = mipsCalls.get(callId); + + // Save the few regs that need saving + call->savedPc = currentMIPS->pc; + call->savedRa = currentMIPS->r[MIPS_REG_RA]; + call->savedV0 = currentMIPS->r[MIPS_REG_V0]; + call->savedV1 = currentMIPS->r[MIPS_REG_V1]; + call->savedIdRegister = currentMIPS->r[MIPS_REG_CALL_ID]; + call->returnVoid = false; + + // Set up the new state + currentMIPS->pc = call->entryPoint; + currentMIPS->r[MIPS_REG_RA] = __KernelMipsCallReturnAddress(); + currentMIPS->r[MIPS_REG_CALL_ID] = callId; + for (int i = 0; i < call->numArgs; i++) { + currentMIPS->r[MIPS_REG_A0 + i] = call->args[i]; + } + + g_inCbCount++; +} + +void __KernelReturnFromMipsCall() +{ + int callId = currentMIPS->r[MIPS_REG_CALL_ID]; + + MipsCall *call = mipsCalls.pop(callId); + + // Value returned by the callback function + u32 retVal = currentMIPS->r[MIPS_REG_V0]; + DEBUG_LOG(HLE,"__KernelReturnFromMipsCall(), returned %08x", retVal); + + // Should also save/restore wait state here. + if (call->doAfter) + call->doAfter->run(); + + currentMIPS->pc = call->savedPc; + currentMIPS->r[MIPS_REG_RA] = call->savedRa; + currentMIPS->r[MIPS_REG_V0] = call->savedV0; + currentMIPS->r[MIPS_REG_V1] = call->savedV1; + currentMIPS->r[MIPS_REG_CALL_ID] = call->savedIdRegister; + + g_inCbCount--; + + // yeah! back in the real world, let's keep going. Should we process more callbacks? + __KernelCheckCallbacks(); + if (!__KernelExecutePendingMipsCalls()) + { + // We should definitely reschedule as we might still be asleep. - except if we came from checkcallbacks? + __KernelReSchedule("return from callback"); + } +} + +bool __KernelExecutePendingMipsCalls() +{ + Thread *thread = __GetCurrentThread(); + + if (thread->pendingMipsCalls.empty()) { + // Nothing to do + return false; + } + + if (__CanExecuteCallbackNow(thread)) + { + // Pop off the first pending mips call + int callId = thread->pendingMipsCalls.front(); + thread->pendingMipsCalls.pop_front(); + __KernelExecuteMipsCallOnCurrentThread(callId); + return true; + } + return false; +} + + +class ActionAfterCallback : public Action +{ +public: + ActionAfterCallback(SceUID cbId_) : cbId(cbId_) {} + virtual void run(); + SceUID cbId; +}; + +// Executes the callback, when it next is context switched to. +void __KernelRunCallbackOnThread(SceUID cbId, Thread *thread) +{ + u32 error; + Callback *cb = kernelObjects.Get(cbId, error); + if (!cb) { + ERROR_LOG(HLE, "__KernelRunCallbackOnThread: Bad cbId %i", cbId); + return; + } + + DEBUG_LOG(HLE, "__KernelRunCallbackOnThread: Turning callback %i into pending mipscall", cbId); + + // Alright, we're on the right thread + // Should save/restore wait state? + + std::vector args; + args.push_back(cb->nc.notifyCount); + args.push_back(cb->nc.notifyArg); + args.push_back(cb->nc.commonArgument); + + // Clear the notify count / arg + cb->nc.notifyCount = 0; + cb->nc.notifyArg = 0; + + Action *action = new ActionAfterCallback(cbId); + __KernelCallAddress(thread, cb->nc.entrypoint, action, false, args); +} + +void ActionAfterCallback::run() { + if (cbId != -1) { + u32 error; + Callback *cb = kernelObjects.Get(cbId, error); + if (cb) + { + DEBUG_LOG(HLE, "Left callback %i - %s", cbId, cb->nc.name); + // Callbacks that don't return 0 are deleted. But should this be done here? + if (currentMIPS->r[MIPS_REG_V0] != 0 || cb->forceDelete) + { + DEBUG_LOG(HLE, "ActionAfterCallback::run(): Callback returned non-zero, gets deleted!"); + kernelObjects.Destroy(cbId); + } + } + } +} + +// Check callbacks on the current thread only. +// Returns true if any callbacks were processed on the current thread. +bool __KernelCheckThreadCallbacks(Thread *thread) { + if (!thread->isProcessingCallbacks) + return false; + + for (int i = 0; i < THREAD_CALLBACK_NUM_TYPES; i++) { + if (thread->readyCallbacks[i].size()) { + SceUID readyCallback = thread->readyCallbacks[i].front(); + thread->readyCallbacks[i].pop_front(); + __KernelRunCallbackOnThread(readyCallback, thread); // makes pending + return true; + } + } + return false; +} + +// Checks for callbacks on all threads +bool __KernelCheckCallbacks() { + // SceUID currentThread = __KernelGetCurThread(); + // currentThread->isProcessingCallbacks = true; + // do { + bool processed = false; + + for (std::vector::iterator iter = threadqueue.begin(); iter != threadqueue.end(); iter++) { + Thread *thread = *iter; + if (thread->isProcessingCallbacks && __KernelCheckThreadCallbacks(thread)) { + processed = true; + } + } + // } while (processed && currentThread == __KernelGetCurThread()); + return processed; +} + +void sceKernelCheckCallback() { + Thread *curThread = __GetCurrentThread(); + + // This thread can now process callbacks. + curThread->isProcessingCallbacks = true; + + bool callbacksProcessed = __KernelCheckThreadCallbacks(curThread); + + // Note - same thread as above - checking callbacks may switch threads. + curThread->isProcessingCallbacks = false; + + if (callbacksProcessed) { + curThread->setReturnValue(1); + ERROR_LOG(HLE,"sceKernelCheckCallback() - processed a callback."); + __KernelExecutePendingMipsCalls(); + } else { + RETURN(0); + DEBUG_LOG(HLE,"sceKernelCheckCallback() - no callbacks to process, simply rescheduling"); + __KernelReSchedule(false, "checkcallbackhack"); + } +} + +bool __KernelInCallback() +{ + return (g_inCbCount != 0); +} + + +u32 __KernelRegisterCallback(RegisteredCallbackType type, SceUID cbId) +{ + Thread *t = __GetCurrentThread(); + if (cbId > 0 && t->registeredCallbacks[type].find(cbId) == t->registeredCallbacks[type].end()) { + t->registeredCallbacks[type].insert(cbId); + return 0; + } else { + return SCE_KERNEL_ERROR_INVAL; + } +} + +u32 __KernelUnregisterCallback(RegisteredCallbackType type, SceUID cbId) +{ + Thread *t = __GetCurrentThread(); + if (t->registeredCallbacks[type].find(cbId) != t->registeredCallbacks[type].end()) { + t->registeredCallbacks[type].erase(cbId); + return 0; + } else { + return 0x80010016; + } +} + +void __KernelNotifyCallback(RegisteredCallbackType type, SceUID threadId, SceUID cbId, int notifyArg) +{ + u32 error; + + Callback *cb = kernelObjects.Get(cbId, error); + if (!cb) { + // Yeah, we're screwed, this shouldn't happen. + ERROR_LOG(HLE, "__KernelNotifyCallback - invalid callback 0"); + return; + } + cb->nc.notifyCount++; + cb->nc.notifyArg = notifyArg; + + Thread *t = kernelObjects.Get(threadId, error); + t->readyCallbacks[type].remove(cbId); + t->readyCallbacks[type].push_back(cbId); +} + +// TODO: If cbId == -1, notify the callback ID on all threads that have it. +u32 __KernelNotifyCallbackType(RegisteredCallbackType type, SceUID cbId, int notifyArg) +{ + for (std::vector::iterator iter = threadqueue.begin(); iter != threadqueue.end(); iter++) { + Thread *t = *iter; + for (std::set::iterator citer = t->registeredCallbacks[type].begin(); citer != t->registeredCallbacks[type].end(); citer++) { + if (cbId == -1 || cbId == *citer) { + __KernelNotifyCallback(type, t->GetUID(), *citer, notifyArg); + } + } + } + + // checkCallbacks on other threads? + return 0; +} + diff --git a/Core/HLE/sceKernelThread.h b/Core/HLE/sceKernelThread.h index 0705451f56..0a93b52c51 100644 --- a/Core/HLE/sceKernelThread.h +++ b/Core/HLE/sceKernelThread.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -34,7 +34,10 @@ void sceKernelExitDeleteThread(); void sceKernelExitThread(); void _sceKernelExitThread(); void sceKernelGetThreadId(); -void sceKernelStartThread(); +void sceKernelGetThreadCurrentPriority(); +u32 sceKernelStartThread(); +u32 sceKernelSuspendDispatchThread(); +u32 sceKernelResumeDispatchThread(u32 suspended); void sceKernelWaitThreadEnd(); void sceKernelReferThreadStatus(); void sceKernelChangeCurrentThreadAttr(); @@ -43,6 +46,7 @@ void sceKernelCheckThreadStack(); void sceKernelSuspendThread(); void sceKernelResumeThread(); void sceKernelWakeupThread(); +void sceKernelCancelWakeupThread(); void sceKernelTerminateDeleteThread(); void sceKernelWaitThreadEndCB(); void sceKernelGetThreadExitStatus(); @@ -59,7 +63,7 @@ enum WaitType //probably not the real values WAITTYPE_MBX = 5, WAITTYPE_VPL = 6, WAITTYPE_FPL = 7, - // + WAITTYPE_MSGPIPE = 8, // fake WAITTYPE_THREADEND = 9, WAITTYPE_AUDIOCHANNEL = 10, // this is fake, should be replaced with 8 eventflags ( ?? ) WAITTYPE_UMD = 11, // this is fake, should be replaced with 1 eventflag ( ?? ) @@ -85,7 +89,6 @@ struct ThreadContext u32 fcr31; }; - // Internal API, used by implementations of kernel functions void __KernelThreadingInit(); @@ -99,20 +102,94 @@ void __KernelLoadContext(ThreadContext *ctx); // TODO: Replace this with __KernelResumeThread over time as it's misguided. bool __KernelTriggerWait(WaitType type, int id, bool dontSwitch = false); -u32 __KernelResumeThread(SceUID threadID); // can return an error value +u32 __KernelResumeThreadFromWait(SceUID threadID); // can return an error value u32 __KernelGetWaitValue(SceUID threadID, u32 &error); void __KernelWaitCurThread(WaitType type, SceUID waitId, u32 waitValue, int timeout, bool processCallbacks); void __KernelReSchedule(const char *reason = "no reason"); -void __KernelNotifyCallback(SceUID threadID, SceUID cbid, u32 arg); +void __KernelReSchedule(bool doCallbacks, const char *reason); +// Registered callback types +enum RegisteredCallbackType { + THREAD_CALLBACK_UMD = 0, + THREAD_CALLBACK_IO = 1, + THREAD_CALLBACK_MEMORYSTICK = 2, + THREAD_CALLBACK_MEMORYSTICK_FAT = 3, + THREAD_CALLBACK_POWER = 4, + THREAD_CALLBACK_EXIT = 5, + THREAD_CALLBACK_USER_DEFINED = 6, + THREAD_CALLBACK_SIZE = 7, + THREAD_CALLBACK_NUM_TYPES = 8, +}; + +// These operate on the current thread +u32 __KernelRegisterCallback(RegisteredCallbackType type, SceUID cbId); +u32 __KernelUnregisterCallback(RegisteredCallbackType type, SceUID cbId); + +// If cbId == -1, all the callbacks of the type on all the threads get notified. +// If not, only this particular callback gets notified. +u32 __KernelNotifyCallbackType(RegisteredCallbackType type, SceUID cbId, int notifyArg); SceUID __KernelGetCurThread(); +SceUID __KernelGetCurThreadModuleId(); void __KernelSetupRootThread(SceUID moduleId, int args, const char *argp, int prio, int stacksize, int attr); //represents the real PSP elf loader, run before execution void __KernelStartIdleThreads(); +void __KernelReturnFromThread(); // Called as HLE function +u32 __KernelGetThreadPrio(SceUID id); -void _sceKernelReturnFromThread(); -void _sceKernelIdle(); +void __KernelIdle(); -u32 __KernelCallbackReturnAddress(); -u32 __KernelInterruptReturnAddress(); +u32 __KernelMipsCallReturnAddress(); +u32 __KernelInterruptReturnAddress(); // TODO: remove + +// Internal access - used by sceSetGeCallback +u32 __KernelCreateCallback(const char *name, u32 entrypoint, u32 signalArg); + +void sceKernelCreateCallback(); +void sceKernelDeleteCallback(); +void sceKernelNotifyCallback(); +void sceKernelCancelCallback(); +void sceKernelGetCallbackCount(); +void sceKernelCheckCallback(); +void sceKernelGetCallbackCount(); +void sceKernelReferCallbackStatus(); +void __KernelReturnFromMipsCall(); // Called as HLE function +bool __KernelInCallback(); + +// Should be called by (nearly) all ...CB functions. +bool __KernelCheckCallbacks(); +class Thread; +void __KernelSwitchContext(Thread *target, const char *reason); +bool __KernelExecutePendingMipsCalls(); +void __KernelNotifyCallback(RegisteredCallbackType type, SceUID threadId, SceUID cbId, int notifyArg); + +// A call into game code. These can be pending on a thread. +// Similar to Callback-s (NOT CallbackInfos) in JPCSP. +class Action; +struct MipsCall { + u32 entryPoint; + u32 cbId; + u32 args[6]; + int numArgs; + Action *doAfter; + u32 savedIdRegister; + u32 savedRa; + u32 savedPc; + u32 savedV0; + u32 savedV1; + bool returnVoid; + const char *tag; +}; +enum ThreadStatus +{ + THREADSTATUS_RUNNING = 1, + THREADSTATUS_READY = 2, + THREADSTATUS_WAIT = 4, + THREADSTATUS_SUSPEND = 8, + THREADSTATUS_DORMANT = 16, + THREADSTATUS_DEAD = 32, + + THREADSTATUS_WAITSUSPEND = THREADSTATUS_WAIT | THREADSTATUS_SUSPEND +}; + +void __KernelChangeThreadState(Thread *thread, ThreadStatus newStatus); diff --git a/Core/HLE/sceKernelTime.cpp b/Core/HLE/sceKernelTime.cpp index 08ac6df389..c88f6966eb 100644 --- a/Core/HLE/sceKernelTime.cpp +++ b/Core/HLE/sceKernelTime.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -54,7 +54,7 @@ void sceKernelGetSystemTimeLow() { // This clock should tick at 1 Mhz. u64 t = CoreTiming::GetTicks() / CoreTiming::GetClockFrequencyMHz(); - DEBUG_LOG(HLE,"%08x=sceKernelGetSystemTimeLow()",(u32)t); + // DEBUG_LOG(HLE,"%08x=sceKernelGetSystemTimeLow()",(u32)t); RETURN((u32)t); } @@ -81,8 +81,10 @@ void sceKernelSysClock2USec() Memory::ReadStruct(PARAM(0), &clock); DEBUG_LOG(HLE, "sceKernelSysClock2USec(clock = , lo = %08x, hi = %08x)", PARAM(1), PARAM(2)); u64 time = clock.lo | ((u64)clock.hi << 32); - Memory::Write_U32((u32)(time / 1000000), PARAM(1)); - Memory::Write_U32((u32)(time % 1000000), PARAM(2)); + if (Memory::IsValidAddress(PARAM(1))) + Memory::Write_U32((u32)(time / 1000000), PARAM(1)); + if (Memory::IsValidAddress(PARAM(2))) + Memory::Write_U32((u32)(time % 1000000), PARAM(2)); RETURN(0); } @@ -90,8 +92,10 @@ void sceKernelSysClock2USecWide() { u64 clock = PARAM(0) | ((u64)PARAM(1) << 32); DEBUG_LOG(HLE, "sceKernelSysClock2USecWide(clock = %llu, lo = %08x, hi = %08x)", clock, PARAM(2), PARAM(3)); - Memory::Write_U32((u32)(clock / 1000000), PARAM(2)); - Memory::Write_U32((u32)(clock % 1000000), PARAM(3)); + if (Memory::IsValidAddress(PARAM(2))) + Memory::Write_U32((u32)(clock / 1000000), PARAM(2)); + if (Memory::IsValidAddress(PARAM(3))) + Memory::Write_U32((u32)(clock % 1000000), PARAM(3)); RETURN(0); } @@ -146,6 +150,42 @@ void sceRtcGetTick() RETURN(0); } +u32 sceRtcGetDayOfWeek(u32 year, u32 month, u32 day) +{ + static u32 t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; + + year -= month < 3; + return ( year + year/4 - year/100 + year/400 + t[month-1] + day) % 7; +} + +u32 sceRtcGetDaysInMonth(u32 year, u32 month) +{ + DEBUG_LOG(HLE,"0=sceRtcGetDaysInMonth()"); + u32 numberOfDays; + + switch (month) + { + case 4: + case 6: + case 9: + case 11: + numberOfDays = 30; + break; + case 2: + if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) + numberOfDays = 29; + else + numberOfDays = 28; + break; + + default: + numberOfDays = 31; + break; + } + + return numberOfDays; +} + void sceRtcGetTickResolution() { DEBUG_LOG(HLE,"100=sceRtcGetTickResolution()"); diff --git a/Core/HLE/sceKernelTime.h b/Core/HLE/sceKernelTime.h index 7ebd39cd8c..6eaf4b5e5a 100644 --- a/Core/HLE/sceKernelTime.h +++ b/Core/HLE/sceKernelTime.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -29,3 +29,5 @@ void sceKernelSysClock2USecWide(); void sceRtcGetCurrentClockLocalTime(); void sceRtcGetTickResolution(); void sceRtcGetTick(); +u32 sceRtcGetDaysInMonth(u32 year, u32 month); +u32 sceRtcGetDayOfWeek(u32 year, u32 month, u32 day); \ No newline at end of file diff --git a/Core/HLE/sceKernelVTimer.cpp b/Core/HLE/sceKernelVTimer.cpp index 2911311428..299e47fd6b 100644 --- a/Core/HLE/sceKernelVTimer.cpp +++ b/Core/HLE/sceKernelVTimer.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -46,11 +46,11 @@ void sceKernelCreateVTimer() VTimer *vt = new VTimer(); - SceUID id = kernelObjects.Create(vt); + SceUID uid = kernelObjects.Create(vt); strncpy(vt->name, name, 32); vt->running = true; vt->startTime = 0; //TODO fix - RETURN(id); //TODO: return timer ID + RETURN(uid); //TODO: return timer ID } void sceKernelStartVTimer() @@ -70,5 +70,6 @@ void sceKernelSetVTimerHandler() // Not sure why this is exposed... void _sceKernelReturnFromTimerHandler() { + DEBUG_LOG(HLE,"_sceKernelReturnFromTimerHandler"); } diff --git a/Core/HLE/sceKernelVTimer.h b/Core/HLE/sceKernelVTimer.h index 0f46a3460a..260341b214 100644 --- a/Core/HLE/sceKernelVTimer.h +++ b/Core/HLE/sceKernelVTimer.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceMpeg.cpp b/Core/HLE/sceMpeg.cpp index ab81185911..2d7ff2d38b 100644 --- a/Core/HLE/sceMpeg.cpp +++ b/Core/HLE/sceMpeg.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -20,73 +20,264 @@ void sceMpegInit() { - DEBUG_LOG(HLE, "HACK sceMpegInit(...)"); + WARN_LOG(HLE, "HACK sceMpegInit(...)"); RETURN(0); } void sceMpegCreate() { - DEBUG_LOG(HLE, "HACK sceMpegCreate(...)"); + WARN_LOG(HLE, "HACK sceMpegCreate(...)"); RETURN(0); } void sceMpegInitAu() { - DEBUG_LOG(HLE, "HACK sceMpegInitAu(...)"); + WARN_LOG(HLE, "HACK sceMpegInitAu(...)"); RETURN(0); } void sceMpegQueryMemSize() { - DEBUG_LOG(HLE, "HACK sceMpegQueryMemSize(...)"); + WARN_LOG(HLE, "HACK sceMpegQueryMemSize(...)"); RETURN(0x10000); // 64K } void sceMpegRingbufferQueryMemSize() { int packets = PARAM(0); - DEBUG_LOG(HLE, "HACK sceMpegRingbufferQueryMemSize(...)"); + WARN_LOG(HLE, "HACK sceMpegRingbufferQueryMemSize(...)"); RETURN(packets * (104 + 2048)); } void sceMpegRingbufferConstruct() { - DEBUG_LOG(HLE, "HACK sceMpegRingbufferConstruct(...)"); + WARN_LOG(HLE, "HACK sceMpegRingbufferConstruct(...)"); + RETURN(0); +} + +void sceMpegRegistStream() +{ + WARN_LOG(HLE, "HACK sceMpegRegistStream(...)"); + RETURN(0); +} + +void sceMpegUnRegistStream() +{ + WARN_LOG(HLE, "HACK sceMpegRegistStream(...)"); + RETURN(0); +} + +void sceMpegGetAtracAu() +{ + WARN_LOG(HLE, "HACK sceMpegGetAtracAu(...)"); + RETURN(0); +} + +void sceMpegQueryPcmEsSize() +{ + WARN_LOG(HLE, "HACK sceMpegQueryPcmEsSize(...)"); + RETURN(0); +} + +void sceMpegQueryAtracEsSize() +{ + WARN_LOG(HLE, "HACK sceMpegQueryAtracEsSize(...)"); + RETURN(0); +} + +void sceMpegChangeGetAuMode() +{ + WARN_LOG(HLE, "HACK sceMpegChangeGetAuMode(...)"); + RETURN(0); +} + +void sceMpegQueryStreamOffset() +{ + WARN_LOG(HLE, "HACK sceMpegQueryStreamOffset(...)"); + RETURN(0); +} + +void sceMpegGetPcmAu() +{ + WARN_LOG(HLE, "HACK sceMpegGetPcmAu(...)"); + RETURN(0); +} + +void sceMpegRingbufferQueryPackNum() +{ + WARN_LOG(HLE, "HACK sceMpegRingbufferQueryPackNum(...)"); + RETURN(0); +} + +void sceMpegFlushAllStream() +{ + WARN_LOG(HLE, "HACK sceMpegFlushAllStream(...)"); + RETURN(0); +} + +void sceMpegMallocAvcEsBuf() +{ + WARN_LOG(HLE, "HACK sceMpegMallocAvcEsBuf(...)"); + RETURN(0); +} + +void sceMpegAvcCopyYCbCr() +{ + WARN_LOG(HLE, "HACK sceMpegAvcCopyYCbCr(...)"); + RETURN(0); +} + +void sceMpegFreeAvcEsBuf() +{ + WARN_LOG(HLE, "HACK sceMpegFreeAvcEsBuf(...)"); + RETURN(0); +} + +void sceMpegAtracDecode() +{ + WARN_LOG(HLE, "HACK sceMpegAtracDecode(...)"); + RETURN(0); +} + +void sceMpegAvcDecodeStop() +{ + WARN_LOG(HLE, "HACK sceMpegAvcDecodeStop(...)"); + RETURN(0); +} + +void sceMpegAvcDecodeMode() +{ + WARN_LOG(HLE, "HACK sceMpegAvcDecodeMode(...)"); + RETURN(0); +} + +void sceMpegAvcDecode() +{ + WARN_LOG(HLE, "HACK sceMpegAvcDecode(...)"); + RETURN(0); +} + +void sceMpegAvcCsc() +{ + WARN_LOG(HLE, "HACK sceMpegAvcCsc(...)"); + RETURN(0); +} + +void sceMpegAvcDecodeStopYCbCr() +{ + WARN_LOG(HLE, "HACK sceMpegAvcDecodeStopYCbCr(...)"); + RETURN(0); +} + +void sceMpegRingbufferDestruct() +{ + WARN_LOG(HLE, "HACK sceMpegRingbufferDestruct(...)"); + RETURN(0); +} + +void sceMpegAvcDecodeYCbCr() +{ + WARN_LOG(HLE, "HACK sceMpegAvcDecodeYCbCr(...)"); + RETURN(0); +} + +void sceMpegRingbufferPut() +{ + WARN_LOG(HLE, "HACK sceMpegRingbufferPut(...)"); + RETURN(0); +} + +void sceMpegAvcInitYCbCr() +{ + WARN_LOG(HLE, "HACK sceMpegAvcInitYCbCr(...)"); + RETURN(0); +} + +void sceMpegAvcQueryYCbCrSize() +{ + WARN_LOG(HLE, "HACK sceMpegAvcQueryYCbCrSize(...)"); + RETURN(0); +} + +void sceMpegRingbufferAvailableSize() +{ + WARN_LOG(HLE, "HACK sceMpegRingbufferAvailableSize(...)"); + RETURN(0); +} + +void sceMpegAvcDecodeDetail() +{ + WARN_LOG(HLE, "HACK sceMpegAvcDecodeDetail(...)"); + RETURN(0); +} + +void sceMpegAvcDecodeFlush() +{ + WARN_LOG(HLE, "HACK sceMpegAvcDecodeFlush(...)"); + RETURN(0); +} + +void sceMpegFinish() +{ + WARN_LOG(HLE, "HACK sceMpegFinish(...)"); + RETURN(0); +} + +void sceMpegDelete() +{ + WARN_LOG(HLE, "HACK sceMpegDelete(...)"); + RETURN(0); +} + +void sceMpegGetAvcAu() +{ + WARN_LOG(HLE, "HACK sceMpegGetAvcAu(...)"); + RETURN(0); +} + +void sceMpegQueryStreamSize() +{ + WARN_LOG(HLE, "HACK sceMpegQueryStreamSize(...)"); RETURN(0); } const HLEFunction sceMpeg[] = { - {0xe1ce83a7,0,"sceMpegGetAtracAu"}, - {0xfe246728,0,"sceMpegGetAvcAu"}, + {0xe1ce83a7,sceMpegGetAtracAu,"sceMpegGetAtracAu"}, + {0xfe246728,sceMpegGetAvcAu,"sceMpegGetAvcAu"}, {0xd8c5f121,sceMpegCreate,"sceMpegCreate"}, - {0xf8dcb679,0,"sceMpegQueryAtracEsSize"}, + {0xf8dcb679,sceMpegQueryAtracEsSize,"sceMpegQueryAtracEsSize"}, {0xc132e22f,sceMpegQueryMemSize,"sceMpegQueryMemSize"}, - {0x21ff80e4,0,"sceMpegQueryStreamOffset"}, - {0x611e9e11,0,"sceMpegQueryStreamSize"}, - {0x42560f23,0,"sceMpegRegistStream"}, - {0x591a4aa2,0,"sceMpegUnRegistStream"}, - {0x707b7629,0,"sceMpegFlushAllStream"}, - {0xa780cf7e,0,"sceMpegMallocAvcEsBuf"}, - {0xceb870b1,0,"sceMpegFreeAvcEsBuf"}, + {0x21ff80e4,sceMpegQueryStreamOffset,"sceMpegQueryStreamOffset"}, + {0x611e9e11,sceMpegQueryStreamSize,"sceMpegQueryStreamSize"}, + {0x42560f23,sceMpegRegistStream,"sceMpegRegistStream"}, + {0x591a4aa2,sceMpegUnRegistStream,"sceMpegUnRegistStream"}, + {0x707b7629,sceMpegFlushAllStream,"sceMpegFlushAllStream"}, + {0xa780cf7e,sceMpegMallocAvcEsBuf,"sceMpegMallocAvcEsBuf"}, + {0xceb870b1,sceMpegFreeAvcEsBuf,"sceMpegFreeAvcEsBuf"}, {0x167afd9e,sceMpegInitAu,"sceMpegInitAu"}, {0x682a619b,sceMpegInit,"sceMpegInit"}, - {0x800c44df,0,"sceMpegAtracDecode"}, - {0x740fccd1,0,"sceMpegAvcDecodeStop"}, - {0x0e3c2e9d,0,"sceMpegAvcDecode"}, + {0x800c44df,sceMpegAtracDecode,"sceMpegAtracDecode"}, + {0x740fccd1,sceMpegAvcDecodeStop,"sceMpegAvcDecodeStop"}, + {0x0e3c2e9d,sceMpegAvcDecode,"sceMpegAvcDecode"}, {0xd7a29f46,sceMpegRingbufferQueryMemSize,"sceMpegRingbufferQueryMemSize"}, {0x37295ed8,sceMpegRingbufferConstruct,"sceMpegRingbufferConstruct"}, - {0x13407f13,0,"sceMpegRingbufferDestruct"}, - {0xb240a59e,0,"sceMpegRingbufferPut"}, - {0xb5f6dc87,0,"sceMpegRingbufferAvailableSize"}, - {0x606a4649,0,"sceMpegDelete"}, - {0x874624d6,0,"sceMpegFinish"}, - {0x4571cc64,0,"sceMpegAvcDecodeFlush"}, - {0x0f6c18d7,0,"sceMpegAvcDecodeDetail"}, - {0x211a057c,0,"sceMpegAvcQueryYCbCrSize"}, - {0x67179b1b,0,"sceMpegAvcInitYCbCr"}, - {0xf0eb1125,0,"sceMpegAvcDecodeYCbCr"}, - {0xf2930c9c,0,"sceMpegAvcDecodeStopYCbCr"}, - {0x31bd0272,0,"sceMpegAvcCsc"}, - {0xa11c7026,0,"sceMpegAvcDecodeMode"}, + {0x13407f13,sceMpegRingbufferDestruct,"sceMpegRingbufferDestruct"}, + {0xb240a59e,sceMpegRingbufferPut,"sceMpegRingbufferPut"}, + {0xb5f6dc87,sceMpegRingbufferAvailableSize,"sceMpegRingbufferAvailableSize"}, + {0x606a4649,sceMpegDelete,"sceMpegDelete"}, + {0x874624d6,sceMpegFinish,"sceMpegFinish"}, + {0x4571cc64,sceMpegAvcDecodeFlush,"sceMpegAvcDecodeFlush"}, + {0x0f6c18d7,sceMpegAvcDecodeDetail,"sceMpegAvcDecodeDetail"}, + {0x211a057c,sceMpegAvcQueryYCbCrSize,"sceMpegAvcQueryYCbCrSize"}, + {0x67179b1b,sceMpegAvcInitYCbCr,"sceMpegAvcInitYCbCr"}, + {0xf0eb1125,sceMpegAvcDecodeYCbCr,"sceMpegAvcDecodeYCbCr"}, + {0xf2930c9c,sceMpegAvcDecodeStopYCbCr,"sceMpegAvcDecodeStopYCbCr"}, + {0x31bd0272,sceMpegAvcCsc,"sceMpegAvcCsc"}, + {0xa11c7026,sceMpegAvcDecodeMode,"sceMpegAvcDecodeMode"}, + {0x0558B075,sceMpegAvcCopyYCbCr,"sceMpegAvcCopyYCbCr"}, + {0x769BEBB6,sceMpegRingbufferQueryPackNum,"sceMpegRingbufferQueryPackNum"}, + {0x8C1E027D,sceMpegGetPcmAu,"sceMpegGetPcmAu"}, + {0x9DCFB7EA,sceMpegChangeGetAuMode,"sceMpegChangeGetAuMode"}, + {0xC02CF6B5,sceMpegQueryPcmEsSize,"sceMpegQueryPcmEsSize"}, }; const HLEFunction sceMp3[] = diff --git a/Core/HLE/sceMpeg.h b/Core/HLE/sceMpeg.h index ba5b4d4af3..edd004439a 100644 --- a/Core/HLE/sceMpeg.h +++ b/Core/HLE/sceMpeg.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceNet.cpp b/Core/HLE/sceNet.cpp index 487412cbac..5ddd25ea71 100644 --- a/Core/HLE/sceNet.cpp +++ b/Core/HLE/sceNet.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -59,6 +59,7 @@ const HLEFunction sceNet[] = {0x0bf0a3ae, 0, "sceNetGetLocalEtherAddr"}, {0xd27961c9, 0, "sceNetEtherStrton"}, {0x50647530, 0, "sceNetFreeThreadinfo"}, + {0xcc393e48, 0, "sceNetGetMallocStat"} }; const HLEFunction sceNetAdhoc[] = @@ -159,6 +160,10 @@ const HLEFunction sceNetInet[] = {0x8ca3a97e, 0, "sceNetInetGetPspError"}, {0xa9ed66b9, 0, "sceNetInetTerm"}, {0xE30B8C19, 0, "sceNetInetInetPton"}, + {0xE247B6D6, 0, "sceNetInetGetpeername"}, + {0x162e6fd5 ,0, "sceNetInetGetsockname"}, + {0x4a114c7c ,0, "sceNetInetGetsockopt"}, + {0xfaabb1dd ,0, "sceNetInetPoll"}, }; const HLEFunction sceNetApctl[] = { diff --git a/Core/HLE/sceNet.h b/Core/HLE/sceNet.h index e2a9d82b2c..2bbe87483a 100644 --- a/Core/HLE/sceNet.h +++ b/Core/HLE/sceNet.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/scePower.cpp b/Core/HLE/scePower.cpp index e4cef3bfee..4f6f178bcd 100644 --- a/Core/HLE/scePower.cpp +++ b/Core/HLE/scePower.cpp @@ -2,11 +2,11 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // 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 +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License 2.0 for more details. // A copy of the GPL 2.0 should have been included with the program. @@ -14,192 +14,279 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. - +#include #include "HLE.h" #include "../MIPS/MIPS.h" #include "../CoreTiming.h" #include "scePower.h" +#include "sceKernelThread.h" static bool volatileMemLocked; -void scePowerGetBatteryLifePercent() -{ - DEBUG_LOG(HLE, "100=scePowerGetBatteryLifePercent"); - RETURN(100); -} -void scePowerIsPowerOnline() -{ - DEBUG_LOG(HLE, "1=scePowerIsPowerOnline"); - RETURN( 1); -} -void scePowerIsBatteryExist() -{ - DEBUG_LOG(HLE, "1=scePowerIsBatteryExist"); - RETURN( 1); -} -void scePowerIsBatteryCharging() -{ - DEBUG_LOG(HLE, "0=scePowerIsBatteryCharging"); - RETURN( 0); -} -void scePowerGetBatteryChargingStatus() -{ - DEBUG_LOG(HLE, "0=scePowerGetBatteryChargingStatus"); - RETURN( 0); -} -void scePowerIsLowBattery() -{ - DEBUG_LOG(HLE, "0=scePowerIsLowBattery"); - RETURN( 0); +const int POWER_CB_AUTO = -1; + +const int numberOfCBPowerSlots = 16; +static int powerCbSlots[numberOfCBPowerSlots]; + + +void __PowerInit() { + memset(powerCbSlots, 0, sizeof(powerCbSlots)); } -void scePowerRegisterCallback() +int scePowerGetBatteryLifePercent() { - DEBUG_LOG(HLE,"0=scePowerRegisterCallback() UNIMPL"); - RETURN (0); + DEBUG_LOG(HLE, "100=scePowerGetBatteryLifePercent"); + return 100; } -void sceKernelPowerLock() + +int scePowerIsPowerOnline() { - DEBUG_LOG(HLE,"UNIMPL 0=sceKernelPowerLock()"); - RETURN (0); + DEBUG_LOG(HLE, "1=scePowerIsPowerOnline"); + return 1; } -void sceKernelPowerUnlock() + +int scePowerIsBatteryExist() { - DEBUG_LOG(HLE,"UNIMPL 0=sceKernelPowerUnlock()"); - RETURN (0); + DEBUG_LOG(HLE, "1=scePowerIsBatteryExist"); + return 1; } -void sceKernelPowerTick() + +int scePowerIsBatteryCharging() +{ + DEBUG_LOG(HLE, "0=scePowerIsBatteryCharging"); + return 0; +} + +int scePowerGetBatteryChargingStatus() +{ + DEBUG_LOG(HLE, "0=scePowerGetBatteryChargingStatus"); + return 0; +} + +int scePowerIsLowBattery() +{ + DEBUG_LOG(HLE, "0=scePowerIsLowBattery"); + return 0; +} + +int scePowerRegisterCallback(int slot, int cbId) +{ + DEBUG_LOG(HLE,"0=scePowerRegisterCallback(%i, %i)", slot, cbId); + int foundSlot = -1; + + if (slot == POWER_CB_AUTO) // -1 signifies auto select of bank + { + for(int i=0; i < numberOfCBPowerSlots; i++) + { + if ((powerCbSlots[i]==0) && (foundSlot == POWER_CB_AUTO)) // found an empty slot + { + powerCbSlots[i] = cbId; + foundSlot = i; + } + } + } + else + { + if (powerCbSlots[slot] == 0) + { + powerCbSlots[slot] = cbId; + foundSlot = 0; + } + else + { + // slot already in use! + foundSlot = POWER_CB_AUTO; + } + } + if (foundSlot>=0) + { + __KernelRegisterCallback(THREAD_CALLBACK_POWER, cbId); + + // Immediately notify + RETURN(0); + + __KernelNotifyCallbackType(THREAD_CALLBACK_POWER, cbId, 0x185); // TODO: I have no idea what the 0x185 is from the flags, but its needed for the test to pass. Need another example of it being called + } + return foundSlot; +} + +int scePowerUnregisterCallback(int slotId) +{ + if (slotId < 0 || slotId >= numberOfCBPowerSlots) + { + return -1; + } + + if (powerCbSlots[slotId] != 0) + { + int cbId = powerCbSlots[slotId]; + DEBUG_LOG(HLE,"0=scePowerUnregisterCallback(%i) (cbid = %i)", slotId, cbId); + __KernelUnregisterCallback(THREAD_CALLBACK_POWER, cbId); + powerCbSlots[slotId] = 0; + } + else + { + return 0x80000025; // TODO: docs say a value less than 0, test checks for this specifically. why?? + } + + return 0; +} + +int sceKernelPowerLock(int lockType) +{ + DEBUG_LOG(HLE,"UNIMPL 0=sceKernelPowerLock(%i)", lockType); + return 0; +} +int sceKernelPowerUnlock(int lockType) +{ + DEBUG_LOG(HLE,"UNIMPL 0=sceKernelPowerUnlock(%i)"); + return 0; +} +int sceKernelPowerTick(int flag) { DEBUG_LOG(HLE,"UNIMPL 0=sceKernelPowerTick()"); - RETURN (0); + return 0; } #define ERROR_POWER_VMEM_IN_USE 0x802b0200 -void sceKernelVolatileMemTryLock() +int sceKernelVolatileMemTryLock(int type, int paddr, int psize) { - int type = PARAM(0); - int paddr = PARAM(1); - int psize = PARAM(2); - if (!volatileMemLocked) - { - INFO_LOG(HLE,"sceKernelVolatileMemTryLock(%i, %08x, %i) - success", type, paddr, psize); - volatileMemLocked = true; - } - else - { - ERROR_LOG(HLE, "sceKernelVolatileMemTryLock - already locked!"); - RETURN(ERROR_POWER_VMEM_IN_USE); - return; - } + if (!volatileMemLocked) + { + INFO_LOG(HLE,"sceKernelVolatileMemTryLock(%i, %08x, %i) - success", type, paddr, psize); + volatileMemLocked = true; + } + else + { + ERROR_LOG(HLE, "sceKernelVolatileMemTryLock - already locked!"); + //RETURN(ERROR_POWER_VMEM_IN_USE); // does this line still need to be here?? + return ERROR_POWER_VMEM_IN_USE; + } - // Volatile RAM is always at 0x08400000 and is of size 0x00400000. - // It's always available in the emu. - Memory::Write_U32(0x08400000, paddr); - Memory::Write_U32(0x00400000, psize); + // Volatile RAM is always at 0x08400000 and is of size 0x00400000. + // It's always available in the emu. + Memory::Write_U32(0x08400000, paddr); + Memory::Write_U32(0x00400000, psize); - RETURN(0); + return 0; } -void sceKernelVolatileMemUnlock() +int sceKernelVolatileMemUnlock(int type) { - INFO_LOG(HLE,"sceKernelVolatileMemUnlock()"); - // TODO: sanity check - volatileMemLocked = false; + INFO_LOG(HLE,"sceKernelVolatileMemUnlock()"); + // TODO: sanity check + volatileMemLocked = false; + + return 0; } -void sceKernelVolatileMemLock() +int sceKernelVolatileMemLock(int type, int paddr, int psize) { - sceKernelVolatileMemTryLock(); + return sceKernelVolatileMemTryLock(type, paddr, psize); } void scePowerSetClockFrequency(u32 cpufreq, u32 busfreq, u32 gpufreq) { - CoreTiming::SetClockFrequencyMHz(cpufreq); + CoreTiming::SetClockFrequencyMHz(cpufreq); - INFO_LOG(HLE,"scePowerSetClockFrequency(%i,%i,%i)", cpufreq, busfreq, gpufreq); + INFO_LOG(HLE,"scePowerSetClockFrequency(%i,%i,%i)", cpufreq, busfreq, gpufreq); } void scePowerGetCpuClockFrequencyInt() { - INFO_LOG(HLE,"scePowerGetCpuClockFrequencyInt()"); - RETURN(CoreTiming::GetClockFrequencyMHz()); + int freq = CoreTiming::GetClockFrequencyMHz(); + INFO_LOG(HLE,"%i=scePowerGetCpuClockFrequencyInt()", freq); + RETURN(freq); +} + +void scePowerGetPllClockFrequencyInt() { + int freq = CoreTiming::GetClockFrequencyMHz() / 2; + INFO_LOG(HLE,"%i=scePowerGetPllClockFrequencyInt()", freq); + RETURN(freq); +} + +void scePowerGetBusClockFrequencyInt() { + int freq = CoreTiming::GetClockFrequencyMHz() / 2; + INFO_LOG(HLE,"%i=scePowerGetBusClockFrequencyInt()", freq); + RETURN(freq); } static const HLEFunction scePower[] = { - {0x04B7766E,scePowerRegisterCallback,"scePowerRegisterCallback"}, - {0x2B51FE2F,0,"scePower_2B51FE2F"}, - {0x442BFBAC,0,"scePowerGetBacklightMaximum"}, - {0xEFD3C963,0,"scePowerTick"}, - {0xEDC13FE5,0,"scePowerGetIdleTimer"}, - {0x7F30B3B1,0,"scePowerIdleTimerEnable"}, - {0x972CE941,0,"scePowerIdleTimerDisable"}, - {0x27F3292C,0,"scePowerBatteryUpdateInfo"}, - {0xE8E4E204,0,"scePower_E8E4E204"}, - {0xB999184C,0,"scePowerGetLowBatteryCapacity"}, - {0x87440F5E,scePowerIsPowerOnline,"scePowerIsPowerOnline"}, - {0x0AFD0D8B,scePowerIsBatteryExist,"scePowerIsBatteryExist"}, - {0x1E490401,scePowerIsBatteryCharging,"scePowerIsBatteryCharging"}, - {0xB4432BC8,scePowerGetBatteryChargingStatus,"scePowerGetBatteryChargingStatus"}, - {0xD3075926,scePowerIsLowBattery,"scePowerIsLowBattery"}, - {0x78A1A796,0,"scePowerIsSuspendRequired"}, - {0x94F5A53F,0,"scePowerGetBatteryRemainCapacity"}, - {0xFD18A0FF,0,"scePowerGetBatteryFullCapacity"}, - {0x2085D15D,scePowerGetBatteryLifePercent,"scePowerGetBatteryLifePercent"}, - {0x8EFB3FA2,0,"scePowerGetBatteryLifeTime"}, - {0x28E12023,0,"scePowerGetBatteryTemp"}, - {0x862AE1A6,0,"scePowerGetBatteryElec"}, - {0x483CE86B,0,"scePowerGetBatteryVolt"}, - {0x23436A4A,0,"scePowerGetInnerTemp"}, - {0x0CD21B1F,0,"scePowerSetPowerSwMode"}, - {0x165CE085,0,"scePowerGetPowerSwMode"}, - {0xD6D016EF,0,"scePowerLock"}, - {0xCA3D34C1,0,"scePowerUnlock"}, - {0xDB62C9CF,0,"scePowerCancelRequest"}, - {0x7FA406DD,0,"scePowerIsRequest"}, - {0x2B7C7CF4,0,"scePowerRequestStandby"}, - {0xAC32C9CC,0,"scePowerRequestSuspend"}, - {0x2875994B,0,"scePower_2875994B"}, - {0x0074EF9B,0,"scePowerGetResumeCount"}, - {0x04B7766E,0,"scePowerRegisterCallback"}, - {0xDFA8BAF8,0,"scePowerUnregisterCallback"}, - {0xDB9D28DD,0,"scePowerUnregitserCallback"}, //haha - {0x843FBF43,0,"scePowerSetCpuClockFrequency"}, - {0xB8D7B3FB,0,"scePowerSetBusClockFrequency"}, - {0xFEE03A2F,0,"scePowerGetCpuClockFrequency"}, - {0x478FE6F5,0,"scePowerGetBusClockFrequency"}, - {0xFDB5BFE9,scePowerGetCpuClockFrequencyInt,"scePowerGetCpuClockFrequencyInt"}, - {0xBD681969,0,"scePowerGetBusClockFrequencyInt"}, - {0xB1A52C83,0,"scePowerGetCpuClockFrequencyFloat"}, - {0x9BADB3EB,0,"scePowerGetBusClockFrequencyFloat"}, - {0x737486F2,&WrapV_UUU,"scePowerSetClockFrequency"}, - {0x34f9c463,0,"scePowerGetPllClockFrequencyInt"}, - {0xea382a27,0,"scePowerGetPllClockFrequencyFloat"}, - {0xebd177d6,0,"scePower_driver_EBD177D6"}, + {0x04B7766E,&WrapI_II,"scePowerRegisterCallback"}, + {0x2B51FE2F,0,"scePower_2B51FE2F"}, + {0x442BFBAC,0,"scePowerGetBacklightMaximum"}, + {0xEFD3C963,0,"scePowerTick"}, + {0xEDC13FE5,0,"scePowerGetIdleTimer"}, + {0x7F30B3B1,0,"scePowerIdleTimerEnable"}, + {0x972CE941,0,"scePowerIdleTimerDisable"}, + {0x27F3292C,0,"scePowerBatteryUpdateInfo"}, + {0xE8E4E204,0,"scePower_E8E4E204"}, + {0xB999184C,0,"scePowerGetLowBatteryCapacity"}, + {0x87440F5E,&WrapI_V,"scePowerIsPowerOnline"}, + {0x0AFD0D8B,&WrapI_V,"scePowerIsBatteryExist"}, + {0x1E490401,&WrapI_V,"scePowerIsBatteryCharging"}, + {0xB4432BC8,&WrapI_V,"scePowerGetBatteryChargingStatus"}, + {0xD3075926,&WrapI_V,"scePowerIsLowBattery"}, + {0x78A1A796,0,"scePowerIsSuspendRequired"}, + {0x94F5A53F,0,"scePowerGetBatteryRemainCapacity"}, + {0xFD18A0FF,0,"scePowerGetBatteryFullCapacity"}, + {0x2085D15D,&WrapI_V,"scePowerGetBatteryLifePercent"}, + {0x8EFB3FA2,0,"scePowerGetBatteryLifeTime"}, + {0x28E12023,0,"scePowerGetBatteryTemp"}, + {0x862AE1A6,0,"scePowerGetBatteryElec"}, + {0x483CE86B,0,"scePowerGetBatteryVolt"}, + {0x23436A4A,0,"scePowerGetInnerTemp"}, + {0x0CD21B1F,0,"scePowerSetPowerSwMode"}, + {0x165CE085,0,"scePowerGetPowerSwMode"}, + {0xD6D016EF,0,"scePowerLock"}, + {0xCA3D34C1,0,"scePowerUnlock"}, + {0xDB62C9CF,0,"scePowerCancelRequest"}, + {0x7FA406DD,0,"scePowerIsRequest"}, + {0x2B7C7CF4,0,"scePowerRequestStandby"}, + {0xAC32C9CC,0,"scePowerRequestSuspend"}, + {0x2875994B,0,"scePower_2875994B"}, + {0x0074EF9B,0,"scePowerGetResumeCount"}, + {0xDFA8BAF8,&WrapI_I,"scePowerUnregisterCallback"}, + {0xDB9D28DD,&WrapI_I,"scePowerUnregitserCallback"}, //haha + {0x843FBF43,0,"scePowerSetCpuClockFrequency"}, + {0xB8D7B3FB,0,"scePowerSetBusClockFrequency"}, + {0xFEE03A2F,0,"scePowerGetCpuClockFrequency"}, + {0x478FE6F5,0,"scePowerGetBusClockFrequency"}, + {0xFDB5BFE9,scePowerGetCpuClockFrequencyInt,"scePowerGetCpuClockFrequencyInt"}, + {0xBD681969,scePowerGetBusClockFrequencyInt,"scePowerGetBusClockFrequencyInt"}, + {0xB1A52C83,0,"scePowerGetCpuClockFrequencyFloat"}, + {0x9BADB3EB,0,"scePowerGetBusClockFrequencyFloat"}, + {0x737486F2,&WrapV_UUU,"scePowerSetClockFrequency"}, + {0x34f9c463,scePowerGetPllClockFrequencyInt,"scePowerGetPllClockFrequencyInt"}, + {0xea382a27,0,"scePowerGetPllClockFrequencyFloat"}, + {0xebd177d6,&WrapV_UUU,"scePower_driver_EBD177D6"}, //TODO: used in a few places, jpcsp says is the same as scePowerSetClockFrequency + {0x469989ad,0,"scePower_469989ad"}, + {0xa85880d0,0,"scePower_a85880d0"}, }; //890129c in tyshooter looks bogus const HLEFunction sceSuspendForUser[] = { - {0xEADB1BD7,sceKernelPowerLock,"sceKernelPowerLock"}, //(int param) set param to 0 - {0x3AEE7261,sceKernelPowerUnlock,"sceKernelPowerUnlock"},//(int param) set param to 0 - {0x090ccb3f,sceKernelPowerTick,"sceKernelPowerTick"}, + {0xEADB1BD7,&WrapI_I,"sceKernelPowerLock"}, //(int param) set param to 0 + {0x3AEE7261,&WrapI_I,"sceKernelPowerUnlock"},//(int param) set param to 0 + {0x090ccb3f,&WrapI_I,"sceKernelPowerTick"}, - // There's an extra 4MB that can be allocated, which seems to be "volatile". These functions - // let you grab it. - {0xa14f40b2,sceKernelVolatileMemTryLock,"sceKernelVolatileMemTryLock"}, - {0xa569e425,sceKernelVolatileMemUnlock,"sceKernelVolatileMemUnlock"}, - {0x3e0271d3,sceKernelVolatileMemLock,"sceKernelVolatileMemLock"}, //when "acquiring mem pool" (fired up) + // There's an extra 4MB that can be allocated, which seems to be "volatile". These functions + // let you grab it. + {0xa14f40b2,&WrapI_III,"sceKernelVolatileMemTryLock"}, + {0xa569e425,&WrapI_I,"sceKernelVolatileMemUnlock"}, + {0x3e0271d3,&WrapI_III,"sceKernelVolatileMemLock"}, //when "acquiring mem pool" (fired up) }; void Register_scePower() { - RegisterModule("scePower",ARRAY_SIZE(scePower),scePower); + RegisterModule("scePower",ARRAY_SIZE(scePower),scePower); } void Register_sceSuspendForUser() { - RegisterModule("sceSuspendForUser", ARRAY_SIZE(sceSuspendForUser), sceSuspendForUser); + RegisterModule("sceSuspendForUser", ARRAY_SIZE(sceSuspendForUser), sceSuspendForUser); } diff --git a/Core/HLE/scePower.h b/Core/HLE/scePower.h index 1fef59b4f8..ac99c6a769 100644 --- a/Core/HLE/scePower.h +++ b/Core/HLE/scePower.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -17,5 +17,7 @@ #pragma once +void __PowerInit(); + void Register_scePower(); void Register_sceSuspendForUser(); diff --git a/Core/HLE/scePsmf.cpp b/Core/HLE/scePsmf.cpp index 46e8c7f35c..a119bfc20b 100644 --- a/Core/HLE/scePsmf.cpp +++ b/Core/HLE/scePsmf.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -79,13 +79,25 @@ const HLEFunction scePsmf[] = {0xc7db3a5b,0,"scePsmfGetCurrentStreamTypeFunction"}, {0xB78EB9E9,0,"scePsmfGetHeaderSizeFunction"}, {0xA5EBFE81,0,"scePsmfGetStreamSizeFunction"}, + {0xE1283895,0,"scePsmfGetPsmfVersionFunction"}, }; +void scePsmfPlayerCreate() { + DEBUG_LOG(HLE, "scePsmfPlayerCreate"); + RETURN(0); +} + +void scePsmfPlayerReleasePsmf() { + DEBUG_LOG(HLE, "scePsmfPlayerReleasePsmf"); + RETURN(0); +} + + const HLEFunction scePsmfPlayer[] = { + {0x235d8787,scePsmfPlayerCreate,"scePsmfPlayerCreateFunction"}, {0x1078c008,0,"scePsmfPlayerStopFunction"}, {0x1e57a8e7,0,"scePsmfPlayerConfigPlayer"}, - {0x235d8787,0,"scePsmfPlayerCreateFunction"}, {0x2beb1569,0,"scePsmfPlayerBreak"}, {0x3d6d25a9,0,"scePsmfPlayerSetPsmfFunction"}, {0x3ea82a4b,0,"scePsmfPlayerGetAudioOutSize"}, @@ -103,9 +115,14 @@ const HLEFunction scePsmfPlayer[] = {0xb8d10c56,0,"scePsmfPlayerSelectAudio"}, {0xb9848a74,0,"scePsmfPlayerGetAudioData"}, {0xdf089680,0,"scePsmfPlayerGetPsmfInfo"}, - {0xe792cd94,0,"scePsmfPlayerReleasePsmfFunction"}, + {0xe792cd94,scePsmfPlayerReleasePsmf,"scePsmfPlayerReleasePsmfFunction"}, {0xf3efaa91,0,"scePsmfPlayerGetCurrentPlayMode"}, {0xf8ef08a6,0,"scePsmfPlayerGetCurrentStatus"}, + {0x2D0E4E0A,0,"scePsmfPlayerSetTempBufFunction"}, + {0x58B83577,0,"scePsmfPlayerSetPsmfCBFunction"}, + {0x2673646B,0,"scePsmfVerifyPsmf"}, + {0x4E624A34,0,"scePsmfGetEPWithId"}, + {0x5F457515,0,"scePsmfGetEPidWithTimestampFunction"}, }; void Register_scePsmf() { diff --git a/Core/HLE/scePsmf.h b/Core/HLE/scePsmf.h index 9e8bde19ec..50dd93b028 100644 --- a/Core/HLE/scePsmf.h +++ b/Core/HLE/scePsmf.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceRtc.cpp b/Core/HLE/sceRtc.cpp index 33c921f6a8..2eb31eba5a 100644 --- a/Core/HLE/sceRtc.cpp +++ b/Core/HLE/sceRtc.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceRtc.h b/Core/HLE/sceRtc.h index 19ec32074b..95d7c03858 100644 --- a/Core/HLE/sceRtc.h +++ b/Core/HLE/sceRtc.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceSas.cpp b/Core/HLE/sceSas.cpp index 52dd8e8a11..d5bd7d2342 100644 --- a/Core/HLE/sceSas.cpp +++ b/Core/HLE/sceSas.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -161,7 +161,7 @@ void SasInstance::mix(u32 outAddr) { Voice &voice = sas.voices[v]; - if (voice.playing) + if (voice.playing && voice.vagAddr != 0) { for (int i = 0; i < grainSize; i++) { @@ -419,6 +419,7 @@ const HLEFunction sceSasCore[] = {0xe175ef66, sceSasGetOutputMode, "__sceSasGetOutputmode"}, {0xe855bf76, 0, "__sceSasSetOutputmode"}, {0x07f58c24, 0, "__sceSasGetAllEnvelopeHeights"}, // (int sasCore, int heightAddr) 32-bit heights, 0-0x40000000 + {0xE1CD9561, 0, "__sceSasSetVoicePCM"}, }; void Register_sceSasCore() diff --git a/Core/HLE/sceSas.h b/Core/HLE/sceSas.h index 8c063ae3a4..bc3e331bbf 100644 --- a/Core/HLE/sceSas.h +++ b/Core/HLE/sceSas.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceUmd.cpp b/Core/HLE/sceUmd.cpp index 5c79fdf15b..f520f78e8b 100644 --- a/Core/HLE/sceUmd.cpp +++ b/Core/HLE/sceUmd.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -18,7 +18,7 @@ #include "HLE.h" #include "../MIPS/MIPS.h" #include "sceUmd.h" - +#include "sceKernelThread.h" #define UMD_NOT_PRESENT 0x01 #define UMD_PRESENT 0x02 @@ -27,19 +27,27 @@ #define UMD_READY 0x10 #define UMD_READABLE 0x20 + u8 umdActivated = 1; u32 umdStatus = 0; +u32 umdErrorStat = 0; +#define PSP_UMD_TYPE_GAME 0x10 +#define PSP_UMD_TYPE_VIDEO 0x20 +#define PSP_UMD_TYPE_AUDIO 0x40 + +struct PspUmdInfo { + int type; +}; + void __UmdInit() { umdActivated = 1; umdStatus = 0; + umdErrorStat = 0; } - - - u8 __KernelUmdGetState() { u8 state = UMD_PRESENT; @@ -69,46 +77,64 @@ void __KernelUmdDeactivate() void sceUmdCheckMedium() { DEBUG_LOG(HLE,"1=sceUmdCheckMedium(?)"); - //ignore PARAM(0) + //ignore PARAM(0) RETURN(1); //non-zero: disc in drive } void sceUmdGetDiscInfo() { - ERROR_LOG(HLE,"UNIMPL sceUmdGetDiscInfo(?)"); + u32 infoAddr = PARAM(0); + ERROR_LOG(HLE,"sceUmdGetDiscInfo(%08x)", infoAddr); + PspUmdInfo info; + info.type = PSP_UMD_TYPE_GAME; + if (Memory::IsValidAddress(infoAddr)) + { + Memory::WriteStruct(infoAddr, &info); + } RETURN(0); } -void sceUmdActivate() +u32 sceUmdActivate(u32 unknown, const char *name) { - u32 unknown = PARAM(0); - const char *name = Memory::GetCharPointer(PARAM(1)); - u32 retVal = 1; + u32 retVal = 0; __KernelUmdActivate(); DEBUG_LOG(HLE,"%i=sceUmdActivate(%08x, %s)", retVal, unknown, name); - //__KernelUMDActivate(); - RETURN(retVal); + u32 notifyArg = UMD_PRESENT | UMD_READABLE; + __KernelNotifyCallbackType(THREAD_CALLBACK_UMD, -1, notifyArg); + return retVal; } -void sceUmdDeactivate() +u32 sceUmdDeactivate(u32 unknown, const char *name) { - ERROR_LOG(HLE,"sceUmdDeactivate()"); + DEBUG_LOG(HLE,"sceUmdDeactivate()"); + u8 triggerCallback = umdActivated; __KernelUmdDeactivate(); - RETURN(0); + + if (triggerCallback) { + u32 notifyArg = UMD_PRESENT | UMD_READY; + __KernelNotifyCallbackType(THREAD_CALLBACK_UMD, -1, notifyArg); + } + return 0; } -void sceUmdRegisterUMDCallBack() +u32 sceUmdRegisterUMDCallBack(u32 cbId) { - ERROR_LOG(HLE,"UNIMPL 0=sceUmdRegisterUMDCallback(id=%i)",PARAM(0)); - RETURN(0); + DEBUG_LOG(HLE,"0=sceUmdRegisterUMDCallback(id=%i)",PARAM(0)); + return __KernelRegisterCallback(THREAD_CALLBACK_UMD, cbId); } -void sceUmdGetDriveStat() +u32 sceUmdUnRegisterUMDCallBack(u32 cbId) +{ + DEBUG_LOG(HLE,"0=sceUmdUnRegisterUMDCallBack(id=%i)",PARAM(0)); + return __KernelUnregisterCallback(THREAD_CALLBACK_UMD, cbId); +} + +u32 sceUmdGetDriveStat() { //u32 retVal = PSP_UMD_INITED | PSP_UMD_READY | PSP_UMD_PRESENT; u32 retVal = __KernelUmdGetState(); DEBUG_LOG(HLE,"0x%02x=sceUmdGetDriveStat()",retVal); - RETURN(retVal); + return retVal; } /** @@ -150,22 +176,28 @@ void sceUmdCancelWaitDriveStat() RETURN(0); } +u32 sceUmdGetErrorStat() +{ + DEBUG_LOG(HLE,"%i=sceUmdGetErrorStat()", umdErrorStat); + return umdErrorStat; +} + const HLEFunction sceUmdUser[] = { - {0xC6183D47,sceUmdActivate,"sceUmdActivate"}, - {0x6B4A146C,sceUmdGetDriveStat,"sceUmdGetDriveStat"}, + {0xC6183D47,&WrapU_UC,"sceUmdActivate"}, + {0x6B4A146C,&WrapU_V,"sceUmdGetDriveStat"}, {0x46EBB729,sceUmdCheckMedium,"sceUmdCheckMedium"}, - {0xE83742BA,sceUmdDeactivate,"sceUmdDeactivate"}, + {0xE83742BA,&WrapU_UC,"sceUmdDeactivate"}, {0x8EF08FCE,sceUmdWaitDriveStat,"sceUmdWaitDriveStat"}, {0x56202973,sceUmdWaitDriveStatWithTimer,"sceUmdWaitDriveStatWithTimer"}, {0x4A9E5E29,sceUmdWaitDriveStatCB,"sceUmdWaitDriveStatCB"}, {0x6af9b50a,sceUmdCancelWaitDriveStat,"sceUmdCancelWaitDriveStat"}, - {0x6B4A146C,sceUmdGetDriveStat,"sceUmdGetDriveStat"}, - {0x20628E6F,0,"sceUmdGetErrorStat"}, + {0x6B4A146C,&WrapU_V,"sceUmdGetDriveStat"}, + {0x20628E6F,&WrapU_V,"sceUmdGetErrorStat"}, {0x340B7686,sceUmdGetDiscInfo,"sceUmdGetDiscInfo"}, - {0xAEE7404D,sceUmdRegisterUMDCallBack,"sceUmdRegisterUMDCallBack"}, - {0xBD2BDE07,0,"sceUmdUnRegisterUMDCallBack"}, + {0xAEE7404D,&WrapU_U,"sceUmdRegisterUMDCallBack"}, + {0xBD2BDE07,&WrapU_U,"sceUmdUnRegisterUMDCallBack"}, {0x87533940,0,"sceUmdReplaceProhibit"}, // ??? sounds bogus }; diff --git a/Core/HLE/sceUmd.h b/Core/HLE/sceUmd.h index c20672b9ad..ceaa832a42 100644 --- a/Core/HLE/sceUmd.h +++ b/Core/HLE/sceUmd.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HLE/sceUtility.cpp b/Core/HLE/sceUtility.cpp index afaffd4ebc..7dec4ae316 100644 --- a/Core/HLE/sceUtility.cpp +++ b/Core/HLE/sceUtility.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -252,15 +252,15 @@ void sceUtilitySavedataUpdate() void sceUtilityLoadAvModule() { DEBUG_LOG(HLE,"sceUtilityLoadAvModule(%i)", PARAM(0)); - __KernelReSchedule("utilityloadavmodule"); RETURN(0); + __KernelReSchedule("utilityloadavmodule"); } void sceUtilityLoadModule() { DEBUG_LOG(HLE,"sceUtilityLoadModule(%i)", PARAM(0)); - __KernelReSchedule("utilityloadmodule"); RETURN(0); + __KernelReSchedule("utilityloadmodule"); } typedef struct @@ -350,42 +350,170 @@ void sceUtilityOskGetStatus() } -void sceUtilityGetSystemParamString() +void sceUtilityNetconfInitStart() { - int id = PARAM(0); - DEBUG_LOG(HLE,"sceUtilityGetSystemParamString(%i, %08x, %i)", id, PARAM(1), PARAM(2)); - char *buf = (char *)Memory::GetPointer(PARAM(1)); - strcpy(buf, "FAKE"); + DEBUG_LOG(HLE,"FAKE sceUtilityNetconfInitStart(%i)", PARAM(0)); + __UtilityInitStart(); +} + +void sceUtilityNetconfShutdownStart() +{ + DEBUG_LOG(HLE,"FAKE sceUtilityNetconfShutdownStart(%i)", PARAM(0)); + __UtilityShutdownStart(); RETURN(0); } -void sceUtilityGetSystemParamInt() +void sceUtilityNetconfUpdate() { - DEBUG_LOG(HLE,"sceUtilityGetSystemParamInt(%i, %08x)", PARAM(0), PARAM(1)); - u32 *outPtr = (u32*)Memory::GetPointer(PARAM(1)); - const int defaultValues[16] = - { - 0, - 0, - 0, - 0,//date notation - 0,//time notation - 0,//timezone offset in minutes - 0,//daylight savings - 1,//language (0=jap 1=eng) - 0, - }; - *outPtr = defaultValues[PARAM(0)]; + DEBUG_LOG(HLE,"FAKE sceUtilityNetconfUpdate(%i)", PARAM(0)); + __UtilityUpdate(); RETURN(0); } +void sceUtilityNetconfGetStatus() +{ + DEBUG_LOG(HLE,"sceUtilityNetconfGetStatus()"); + RETURN(__UtilityGetStatus()); +} + +#define PSP_SYSTEMPARAM_ID_STRING_NICKNAME 1 +#define PSP_SYSTEMPARAM_ID_INT_ADHOC_CHANNEL 2 +#define PSP_SYSTEMPARAM_ID_INT_WLAN_POWERSAVE 3 +#define PSP_SYSTEMPARAM_ID_INT_DATE_FORMAT 4 +#define PSP_SYSTEMPARAM_ID_INT_TIME_FORMAT 5 +//Timezone offset from UTC in minutes, (EST = -300 = -5 * 60) +#define PSP_SYSTEMPARAM_ID_INT_TIMEZONE 6 +#define PSP_SYSTEMPARAM_ID_INT_DAYLIGHTSAVINGS 7 +#define PSP_SYSTEMPARAM_ID_INT_LANGUAGE 8 +/** + * #9 seems to be Region or maybe X/O button swap. + * It doesn't exist on JAP v1.0 + * is 1 on NA v1.5s + * is 0 on JAP v1.5s + * is read-only + */ +#define PSP_SYSTEMPARAM_ID_INT_UNKNOWN 9 + +/** + * Return values for the SystemParam functions + */ +#define PSP_SYSTEMPARAM_RETVAL_OK 0 +#define PSP_SYSTEMPARAM_RETVAL_FAIL 0x80110103 + +/** + * Valid values for PSP_SYSTEMPARAM_ID_INT_ADHOC_CHANNEL + */ +#define PSP_SYSTEMPARAM_ADHOC_CHANNEL_AUTOMATIC 0 +#define PSP_SYSTEMPARAM_ADHOC_CHANNEL_1 1 +#define PSP_SYSTEMPARAM_ADHOC_CHANNEL_6 6 +#define PSP_SYSTEMPARAM_ADHOC_CHANNEL_11 11 + +/** + * Valid values for PSP_SYSTEMPARAM_ID_INT_WLAN_POWERSAVE + */ +#define PSP_SYSTEMPARAM_WLAN_POWERSAVE_OFF 0 +#define PSP_SYSTEMPARAM_WLAN_POWERSAVE_ON 1 + +/** + * Valid values for PSP_SYSTEMPARAM_ID_INT_DATE_FORMAT + */ +#define PSP_SYSTEMPARAM_DATE_FORMAT_YYYYMMDD 0 +#define PSP_SYSTEMPARAM_DATE_FORMAT_MMDDYYYY 1 +#define PSP_SYSTEMPARAM_DATE_FORMAT_DDMMYYYY 2 + +/** + * Valid values for PSP_SYSTEMPARAM_ID_INT_TIME_FORMAT + */ +#define PSP_SYSTEMPARAM_TIME_FORMAT_24HR 0 +#define PSP_SYSTEMPARAM_TIME_FORMAT_12HR 1 + +/** + * Valid values for PSP_SYSTEMPARAM_ID_INT_DAYLIGHTSAVINGS + */ +#define PSP_SYSTEMPARAM_DAYLIGHTSAVINGS_STD 0 +#define PSP_SYSTEMPARAM_DAYLIGHTSAVINGS_SAVING 1 + +/** + * Valid values for PSP_SYSTEMPARAM_ID_INT_LANGUAGE + */ +#define PSP_SYSTEMPARAM_LANGUAGE_JAPANESE 0 +#define PSP_SYSTEMPARAM_LANGUAGE_ENGLISH 1 +#define PSP_SYSTEMPARAM_LANGUAGE_FRENCH 2 +#define PSP_SYSTEMPARAM_LANGUAGE_SPANISH 3 +#define PSP_SYSTEMPARAM_LANGUAGE_GERMAN 4 +#define PSP_SYSTEMPARAM_LANGUAGE_ITALIAN 5 +#define PSP_SYSTEMPARAM_LANGUAGE_DUTCH 6 +#define PSP_SYSTEMPARAM_LANGUAGE_PORTUGUESE 7 +#define PSP_SYSTEMPARAM_LANGUAGE_KOREAN 8 + + + + +u32 sceUtilityGetSystemParamString(u32 id, u32 destaddr, u32 unknownparam) +{ + //DEBUG_LOG(HLE,"sceUtilityGetSystemParamString(%i, %08x, %i)", id,destaddr,unknownparam); + char *buf = (char *)Memory::GetPointer(destaddr); + switch (id) { + case PSP_SYSTEMPARAM_ID_STRING_NICKNAME: + strcpy(buf, "shadow"); + break; + + default: + return PSP_SYSTEMPARAM_RETVAL_FAIL; + } + + return 0; +} + +u32 sceUtilityGetSystemParamInt(u32 id, u32 destaddr) +{ + DEBUG_LOG(HLE,"sceUtilityGetSystemParamInt(%i, %08x)", id,destaddr); + u32 *outPtr = (u32*)Memory::GetPointer(destaddr); + switch (id) { + case PSP_SYSTEMPARAM_ID_INT_ADHOC_CHANNEL: + *outPtr = PSP_SYSTEMPARAM_ADHOC_CHANNEL_AUTOMATIC; + break; + case PSP_SYSTEMPARAM_ID_INT_WLAN_POWERSAVE: + *outPtr = PSP_SYSTEMPARAM_WLAN_POWERSAVE_OFF; + break; + case PSP_SYSTEMPARAM_ID_INT_DATE_FORMAT: + *outPtr = PSP_SYSTEMPARAM_DATE_FORMAT_DDMMYYYY; + break; + case PSP_SYSTEMPARAM_ID_INT_TIME_FORMAT: + *outPtr = PSP_SYSTEMPARAM_TIME_FORMAT_24HR; + break; + case PSP_SYSTEMPARAM_ID_INT_TIMEZONE: + *outPtr = 60; + break; + case PSP_SYSTEMPARAM_ID_INT_DAYLIGHTSAVINGS: + *outPtr = PSP_SYSTEMPARAM_TIME_FORMAT_24HR; + break; + case PSP_SYSTEMPARAM_ID_INT_LANGUAGE: + *outPtr = PSP_SYSTEMPARAM_LANGUAGE_ENGLISH; + break; + case PSP_SYSTEMPARAM_ID_INT_UNKNOWN: + *outPtr = 1; + break; + default: + return PSP_SYSTEMPARAM_RETVAL_FAIL; + } + + return 0; +} + +u32 sceUtilityLoadNetModule(u32 module) +{ + DEBUG_LOG(HLE,"FAKE: sceUtilityLoadNetModule(%i)", module); + return 0; +} + const HLEFunction sceUtility[] = { - {0x1579a159, 0, "sceUtilityLoadNetModule"}, - {0xf88155f6, 0, "sceUtilityNetconfShutdownStart"}, - {0x4db1e739, 0, "sceUtilityNetconfInitStart"}, - {0x91e70e35, 0, "sceUtilityNetconfUpdate"}, - {0x6332aa39, 0, "sceUtilityNetconfGetStatus"}, + {0x1579a159, &WrapU_U, "sceUtilityLoadNetModule"}, + {0xf88155f6, sceUtilityNetconfShutdownStart, "sceUtilityNetconfShutdownStart"}, + {0x4db1e739, sceUtilityNetconfInitStart, "sceUtilityNetconfInitStart"}, + {0x91e70e35, sceUtilityNetconfUpdate, "sceUtilityNetconfUpdate"}, + {0x6332aa39, sceUtilityNetconfGetStatus, "sceUtilityNetconfGetStatus"}, {0x67af3428, sceUtilityMsgDialogShutdownStart, "sceUtilityMsgDialogShutdownStart"}, {0x2ad8e239, sceUtilityMsgDialogInitStart, "sceUtilityMsgDialogInitStart"}, @@ -403,8 +531,8 @@ const HLEFunction sceUtility[] = {0xf3f76017, sceUtilityOskGetStatus, "sceUtilityOskGetStatus"}, {0x41e30674, 0, "sceUtilitySetSystemParamString"}, - {0x34b78343, sceUtilityGetSystemParamString, "sceUtilityGetSystemParamString"}, - {0xA5DA2406, sceUtilityGetSystemParamInt, "sceUtilityGetSystemParamInt"}, + {0x34b78343, &WrapU_UUU, "sceUtilityGetSystemParamString"}, + {0xA5DA2406, &WrapU_UU, "sceUtilityGetSystemParamInt"}, {0xc492f751, 0, "sceUtilityGameSharingInitStart"}, {0xefc6f80f, 0, "sceUtilityGameSharingShutdownStart"}, {0x7853182d, 0, "sceUtilityGameSharingUpdate"}, @@ -423,12 +551,23 @@ const HLEFunction sceUtility[] = {0xf5ce1134, 0, "sceUtilityHtmlViewerShutdownStart"}, {0x05afb9e4, 0, "sceUtilityHtmlViewerUpdate"}, {0xc629af26, sceUtilityLoadAvModule, "sceUtilityLoadAvModule"}, - {0xf7d8d092, 0, "sceUtilityUnloadAvModule"}, + {0xf7d8d092, 0, "sceUtilityUnloadAvModule"}, {0x2a2b3de0, sceUtilityLoadModule, "sceUtilityLoadModule"}, {0xe49bfe92, 0, "sceUtilityUnloadModule"}, - {0xab083ea9, 0, "sceUtility_ab083ea9"}, - {0xd81957b7, 0, "sceUtility_d81957b7"}, - {0xf9e0008c, 0, "sceUtility_f9e0008c"}, + {0x0251B134, 0, "sceUtilityScreenshotInitStart"}, + {0xF9E0008C, 0, "sceUtilityScreenshotShutdownStart"}, + {0xAB083EA9, 0, "sceUtilityScreenshotUpdate"}, + {0xD81957B7, 0, "sceUtilityScreenshotGetStatus"}, + {0x86A03A27, 0, "sceUtilityScreenshotContStart"}, + + {0x0D5BC6D2, 0, "sceUtilityLoadUsbModule"}, + {0xF64910F0, 0, "sceUtilityUnloadUsbModule"}, + + {0x24AC31EB, 0, "sceUtilityGamedataInstallInitStart"}, + {0x32E32DCB, 0, "sceUtilityGamedataInstallShutdownStart"}, + {0x4AECD179, 0, "sceUtilityGamedataInstallUpdate"}, + {0xB57E95D9, 0, "sceUtilityGamedataInstallGetStatus"}, + {0x180F7B62, 0, "sceUtilityGamedataInstallAbortFunction"}, }; void Register_sceUtility() diff --git a/Core/HLE/sceUtility.h b/Core/HLE/sceUtility.h index ad13602e61..3eefa42b8e 100644 --- a/Core/HLE/sceUtility.h +++ b/Core/HLE/sceUtility.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/HW/MemoryStick.cpp b/Core/HW/MemoryStick.cpp new file mode 100644 index 0000000000..4d83e4783c --- /dev/null +++ b/Core/HW/MemoryStick.cpp @@ -0,0 +1,30 @@ +#include "MemoryStick.h" + +// MS and FatMS states. +static MemStickState memStickState = PSP_MEMORYSTICK_STATE_DRIVER_READY; +static MemStickFatState memStickFatState = PSP_FAT_MEMORYSTICK_STATE_ASSIGNED; + +MemStickState MemoryStick_State() +{ + return memStickState; +} + +MemStickFatState MemoryStick_FatState() +{ + return memStickFatState; +} + +u64 MemoryStick_SectorSize() +{ + return 32 * 1024; // 32KB +} + +u64 MemoryStick_FreeSpace() +{ + return 1ULL * 1024 * 1024 * 1024; // 1GB +} + +void MemoryStick_SetFatState(MemStickFatState state) +{ + memStickFatState = state; +} diff --git a/Core/HW/MemoryStick.h b/Core/HW/MemoryStick.h new file mode 100644 index 0000000000..1ccd9b64fa --- /dev/null +++ b/Core/HW/MemoryStick.h @@ -0,0 +1,23 @@ +#include "../../Globals.h" + +// mscmhc0 states +enum MemStickState { + PSP_MEMORYSTICK_STATE_DRIVER_READY = 1, + PSP_MEMORYSTICK_STATE_DRIVER_BUSY = 2, + PSP_MEMORYSTICK_STATE_DEVICE_INSERTED = 4, + PSP_MEMORYSTICK_STATE_DEVICE_REMOVED = 8, +}; + +// memstick FAT states. +enum MemStickFatState { + PSP_FAT_MEMORYSTICK_STATE_UNASSIGNED = 0, + PSP_FAT_MEMORYSTICK_STATE_ASSIGNED = 1, +}; + +MemStickState MemoryStick_State(); +MemStickFatState MemoryStick_FatState(); + +void MemoryStick_SetFatState(MemStickFatState state); + +u64 MemoryStick_SectorSize(); +u64 MemoryStick_FreeSpace(); \ No newline at end of file diff --git a/Core/Host.cpp b/Core/Host.cpp index b1d98dc4ec..933b54b539 100644 --- a/Core/Host.cpp +++ b/Core/Host.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/Host.h b/Core/Host.h index 1cb1fedc22..b0860c24c6 100644 --- a/Core/Host.h +++ b/Core/Host.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/Loaders.cpp b/Core/Loaders.cpp index e47e6c6c4d..fd3eabf6a9 100644 --- a/Core/Loaders.cpp +++ b/Core/Loaders.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -30,7 +30,6 @@ // TODO : improve, look in the file more EmuFileType Identify_File(const char *filename) { - //then: easy bulletproof IDs. FILE *f = fopen(filename, "rb"); if (!f) @@ -43,7 +42,7 @@ EmuFileType Identify_File(const char *filename) fclose(f); if (id == 'FLE\x7F') { - if (strstr(filename,".plf") || strstr(filename,"BOOT.BIN") || strstr(filename,".elf") ) + if (strstr(filename,".plf") || strstr(filename,"BOOT.BIN") || strstr(filename,".elf") || strstr(filename,".prx") ) { return FILETYPE_PSP_ELF; } @@ -60,15 +59,15 @@ EmuFileType Identify_File(const char *filename) { return FILETYPE_PSP_PBP; } - else if (strstr(filename,".iso")) + else if (strstr(filename,".iso") || strstr(filename,".ISO")) { return FILETYPE_PSP_ISO; } - else if (strstr(filename,".cso")) + else if (strstr(filename,".cso") || strstr(filename,".CSO")) { return FILETYPE_PSP_ISO; } - else if (strstr(filename,".bin")) + else if (strstr(filename,".bin") || strstr(filename,".BIN")) { return FILETYPE_UNKNOWN_BIN; } diff --git a/Core/Loaders.h b/Core/Loaders.h index 55c79ce468..93e198e461 100644 --- a/Core/Loaders.h +++ b/Core/Loaders.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/ARM/Asm.cpp b/Core/MIPS/ARM/Asm.cpp index 61106d6ee2..da68215c7b 100644 --- a/Core/MIPS/ARM/Asm.cpp +++ b/Core/MIPS/ARM/Asm.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -16,9 +16,9 @@ // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. #include "ABI.h" -#include "ARMEmitter.h" +#include -#include "../../Memmap.h" +#include "../../MemMap.h" #include "../MIPS.h" #include "../../CoreTiming.h" diff --git a/Core/MIPS/ARM/Asm.h b/Core/MIPS/ARM/Asm.h index 411eb5563a..4897d885f4 100644 --- a/Core/MIPS/ARM/Asm.h +++ b/Core/MIPS/ARM/Asm.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -18,7 +18,7 @@ #ifndef _JIT64ASM_H #define _JIT64ASM_H -#include "ArmEmitter.h" +#include #include "../MIPS.h" // In PPSSPP, we don't use inline assembly. Instead, we generate all machine-near diff --git a/Core/MIPS/ARM/CompALU.cpp b/Core/MIPS/ARM/CompALU.cpp index e15bab92f0..da608b6655 100644 --- a/Core/MIPS/ARM/CompALU.cpp +++ b/Core/MIPS/ARM/CompALU.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -17,7 +17,7 @@ #include "Jit.h" #include "RegCache.h" -#include "ArmEmitter.h" +#include using namespace MIPSAnalyst; #define _RS ((op>>21) & 0x1F) diff --git a/Core/MIPS/ARM/CompBranch.cpp b/Core/MIPS/ARM/CompBranch.cpp index 96a2ed87d0..e9112d5fcb 100644 --- a/Core/MIPS/ARM/CompBranch.cpp +++ b/Core/MIPS/ARM/CompBranch.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -24,7 +24,7 @@ #include "Jit.h" #include "RegCache.h" #include "JitCache.h" -#include "ArmEmitter.h" +#include #define _RS ((op>>21) & 0x1F) #define _RT ((op>>16) & 0x1F) @@ -353,4 +353,4 @@ void Jit::Comp_Syscall(u32 op) } -} // namespace Mipscomp \ No newline at end of file +} // namespace Mipscomp diff --git a/Core/MIPS/ARM/CompFPU.cpp b/Core/MIPS/ARM/CompFPU.cpp index 4f66f6f597..0ed608eac2 100644 --- a/Core/MIPS/ARM/CompFPU.cpp +++ b/Core/MIPS/ARM/CompFPU.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/ARM/CompLoadStore.cpp b/Core/MIPS/ARM/CompLoadStore.cpp index 1bebb8f49c..9db18b946c 100644 --- a/Core/MIPS/ARM/CompLoadStore.cpp +++ b/Core/MIPS/ARM/CompLoadStore.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/ARM/Jit.cpp b/Core/MIPS/ARM/Jit.cpp index 29ca4ece4d..c1e55cada4 100644 --- a/Core/MIPS/ARM/Jit.cpp +++ b/Core/MIPS/ARM/Jit.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/ARM/Jit.h b/Core/MIPS/ARM/Jit.h index 06b76db9bb..fe81735e41 100644 --- a/Core/MIPS/ARM/Jit.h +++ b/Core/MIPS/ARM/Jit.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -20,12 +20,12 @@ #include "../../../Globals.h" #include "Asm.h" -#ifndef ANDROID +#if !defined(ANDROID) && !defined(BLACKBERRY) #error DO NOT BUILD ARM JIT ON x86 #endif -#include "ArmEmitter.h" +#include #include "JitCache.h" #include "RegCache.h" diff --git a/Core/MIPS/ARM/JitCache.cpp b/Core/MIPS/ARM/JitCache.cpp index 0bfc94f25a..4cb912afe8 100644 --- a/Core/MIPS/ARM/JitCache.cpp +++ b/Core/MIPS/ARM/JitCache.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -34,7 +34,7 @@ #include "Asm.h" // #include "JitBase.h" -#include "ArmEmitter.h" +#include #if defined USE_OPROFILE && USE_OPROFILE #include diff --git a/Core/MIPS/ARM/JitCache.h b/Core/MIPS/ARM/JitCache.h index 4eed56408e..ae38f06e6a 100644 --- a/Core/MIPS/ARM/JitCache.h +++ b/Core/MIPS/ARM/JitCache.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/ARM/RegCache.cpp b/Core/MIPS/ARM/RegCache.cpp index b57d682588..5c64fca2a0 100644 --- a/Core/MIPS/ARM/RegCache.cpp +++ b/Core/MIPS/ARM/RegCache.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/ARM/RegCache.h b/Core/MIPS/ARM/RegCache.h index ae45c309cb..afab156b52 100644 --- a/Core/MIPS/ARM/RegCache.h +++ b/Core/MIPS/ARM/RegCache.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -18,7 +18,7 @@ #pragma once #include "../MIPSAnalyst.h" -#include "ArmEmitter.h" +#include using namespace ArmGen; enum FlushMode diff --git a/Core/MIPS/JitCommon/JitCommon.cpp b/Core/MIPS/JitCommon/JitCommon.cpp index 933a926da4..1622b71219 100644 --- a/Core/MIPS/JitCommon/JitCommon.cpp +++ b/Core/MIPS/JitCommon/JitCommon.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/JitCommon/JitCommon.h b/Core/MIPS/JitCommon/JitCommon.h index 3d71ef8fde..81834be6f2 100644 --- a/Core/MIPS/JitCommon/JitCommon.h +++ b/Core/MIPS/JitCommon/JitCommon.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -17,7 +17,7 @@ #pragma once -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include "../ARM/Jit.h" #else #include "../x86/Jit.h" diff --git a/Core/MIPS/MIPS.cpp b/Core/MIPS/MIPS.cpp index be3dab99a1..2108cde51b 100644 --- a/Core/MIPS/MIPS.cpp +++ b/Core/MIPS/MIPS.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -23,7 +23,7 @@ #include "../System.h" #include "../Debugger/Breakpoints.h" -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include "ARM/JitCache.h" #include "ARM/Jit.h" #else @@ -77,6 +77,7 @@ void MIPSState::Reset() SetWriteMask(b); pc = 0; + prevPC = 0; hi = 0; lo = 0; fpcond = 0; @@ -86,6 +87,7 @@ void MIPSState::Reset() exceptions = 0; currentMIPS = this; inDelaySlot = false; + llBit = 0; nextPC = 0; // Initialize the VFPU random number generator with .. something? rng.Init(0x1337); @@ -108,7 +110,7 @@ void MIPSState::RunLoopUntil(u64 globalTicks) { // Don't subvert this by setting useJIT to true - other places also check the coreparameter bool useJIT = PSP_CoreParameter().cpuCore == CPU_JIT; -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) useJIT = false; #endif @@ -125,7 +127,7 @@ void MIPSState::RunLoopUntil(u64 globalTicks) #ifdef _DEBUG while (CoreTiming::downcount >= 0 && coreState == CORE_RUNNING) #else - while (CoreTiming::downcount >= 0) + while (CoreTiming::downcount >= 0 && mipsr4k.pc) #endif { // int cycles = 0; @@ -155,7 +157,7 @@ void MIPSState::RunLoopUntil(u64 globalTicks) break; } #endif - // u32 lastpc = pc; + prevPC = pc; if (inDelaySlot) { MIPSInterpret(op); diff --git a/Core/MIPS/MIPS.h b/Core/MIPS/MIPS.h index 8314ab596e..48d86499c3 100644 --- a/Core/MIPS/MIPS.h +++ b/Core/MIPS/MIPS.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -50,8 +50,8 @@ enum MIPS_REG_FP=30, MIPS_REG_RA=31, - // ID for callback is stored here - from JPCSP - MIPS_REG_CB_ID=MIPS_REG_S0, + // ID for mipscall "callback" is stored here - from JPCSP + MIPS_REG_CALL_ID=MIPS_REG_S0, }; enum @@ -112,6 +112,7 @@ public: u32 pc; u32 nextPC; + u32 prevPC; u32 hi; u32 lo; @@ -123,6 +124,7 @@ public: GMRng rng; // VFPU hardware random number generator. Probably not the right type. bool inDelaySlot; + int llBit; // ll/sc CPUType cpuType; diff --git a/Core/MIPS/MIPSAnalyst.cpp b/Core/MIPS/MIPSAnalyst.cpp index 7557ab4925..a97b168d8b 100644 --- a/Core/MIPS/MIPSAnalyst.cpp +++ b/Core/MIPS/MIPSAnalyst.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/MIPSAnalyst.h b/Core/MIPS/MIPSAnalyst.h index a36e6383c5..ad58a3ed77 100644 --- a/Core/MIPS/MIPSAnalyst.h +++ b/Core/MIPS/MIPSAnalyst.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/MIPSCodeUtils.cpp b/Core/MIPS/MIPSCodeUtils.cpp index 43c2c0bb59..3aade2c9f8 100644 --- a/Core/MIPS/MIPSCodeUtils.cpp +++ b/Core/MIPS/MIPSCodeUtils.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/MIPSCodeUtils.h b/Core/MIPS/MIPSCodeUtils.h index 75a8ea16a5..87d61e8192 100644 --- a/Core/MIPS/MIPSCodeUtils.h +++ b/Core/MIPS/MIPSCodeUtils.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/MIPSDebugInterface.cpp b/Core/MIPS/MIPSDebugInterface.cpp index cddc5d5466..6c4d7d3d07 100644 --- a/Core/MIPS/MIPSDebugInterface.cpp +++ b/Core/MIPS/MIPSDebugInterface.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/MIPSDebugInterface.h b/Core/MIPS/MIPSDebugInterface.h index 7822ed9fe2..46ae3ae439 100644 --- a/Core/MIPS/MIPSDebugInterface.h +++ b/Core/MIPS/MIPSDebugInterface.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/MIPSDis.cpp b/Core/MIPS/MIPSDis.cpp index 0d47410a94..a4d007cd76 100644 --- a/Core/MIPS/MIPSDis.cpp +++ b/Core/MIPS/MIPSDis.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -21,7 +21,7 @@ #include "MIPSTables.h" #include "MIPSDebugInterface.h" -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include "ARM/Jit.h" #else #include "x86/Jit.h" diff --git a/Core/MIPS/MIPSDis.h b/Core/MIPS/MIPSDis.h index 760754c004..e07351eec6 100644 --- a/Core/MIPS/MIPSDis.h +++ b/Core/MIPS/MIPSDis.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/MIPSDisVFPU.cpp b/Core/MIPS/MIPSDisVFPU.cpp index 22124c0cf2..8fabb7e5d3 100644 --- a/Core/MIPS/MIPSDisVFPU.cpp +++ b/Core/MIPS/MIPSDisVFPU.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/MIPSDisVFPU.h b/Core/MIPS/MIPSDisVFPU.h index e6bee375c6..79206cc6f3 100644 --- a/Core/MIPS/MIPSDisVFPU.h +++ b/Core/MIPS/MIPSDisVFPU.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/MIPSInt.cpp b/Core/MIPS/MIPSInt.cpp index cd17ab5426..fcd623fed7 100644 --- a/Core/MIPS/MIPSInt.cpp +++ b/Core/MIPS/MIPSInt.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -55,7 +55,7 @@ void DelayBranchTo(u32 where) int MIPS_SingleStep() { -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) u32 op = Memory::ReadUnchecked_U32(mipsr4k.pc); #else u32 op = Memory::Read_Opcode_JIT(mipsr4k.pc); @@ -109,7 +109,7 @@ namespace MIPSInt { void Int_Cache(u32 op) { - DEBUG_LOG(CPU,"cache instruction %08x",op); + // DEBUG_LOG(CPU,"cache instruction %08x",op); PC += 4; } @@ -176,10 +176,14 @@ namespace MIPSInt switch ((op>>16) & 0x1F) { - case 0: if ((s32)R(rs) < 0) DelayBranchTo(addr); else PC += 4; break;//bltz + case 0: if ((s32)R(rs) < 0) DelayBranchTo(addr); else PC += 4; break;//bltz case 1: if ((s32)R(rs) >= 0) DelayBranchTo(addr); else PC += 4; break;//bgez case 2: if ((s32)R(rs) < 0) DelayBranchTo(addr); else PC += 8; break;//bltzl case 3: if ((s32)R(rs) >= 0) DelayBranchTo(addr); else PC += 8; break;//bgezl + case 16: R(MIPS_REG_RA) = PC + 8; if ((s32)R(rs) < 0) DelayBranchTo(addr); else PC += 4; break;//bltz + case 17: R(MIPS_REG_RA) = PC + 8; if ((s32)R(rs) >= 0) DelayBranchTo(addr); else PC += 4; break;//bgez + case 18: R(MIPS_REG_RA) = PC + 8; if ((s32)R(rs) < 0) DelayBranchTo(addr); else PC += 8; break;//bltzl + case 19: R(MIPS_REG_RA) = PC + 8; if ((s32)R(rs) >= 0) DelayBranchTo(addr); else PC += 8; break;//bgezl default: _dbg_assert_msg_(CPU,0,"Trying to interpret instruction that can't be interpreted"); break; @@ -297,23 +301,58 @@ namespace MIPSInt PC += 4; } + void Int_StoreSync(u32 op) + { + s32 imm = (signed short)(op&0xFFFF); + int base = ((op >> 21) & 0x1f); + int rt = (op >> 16) & 0x1f; + u32 addr = R(base) + imm; + + switch (op >> 26) + { + case 48: // ll + R(rt) = Memory::Read_U32(addr); + currentMIPS->llBit = 1; + break; + case 56: // sc + if (currentMIPS->llBit) { + Memory::Write_U32(R(rt), addr); + R(rt) = 1; + } else { + R(rt) = 0; + } + break; + default: + _dbg_assert_msg_(CPU,0,"Trying to interpret instruction that can't be interpreted"); + break; + } + PC += 4; + } + void Int_RType3(u32 op) { int rt = _RT; int rs = _RS; int rd = _RD; + static bool has_warned = false; switch (op & 63) { case 10: if (R(rt) == 0) R(rd) = R(rs); break; //movz case 11: if (R(rt) != 0) R(rd) = R(rs); break; //movn case 32: - ERROR_LOG(HLE,"WARNING : exception-causing add at %08x", PC); + if (!has_warned) { + ERROR_LOG(HLE,"WARNING : exception-causing add at %08x", PC); + has_warned = true; + } R(rd) = R(rs) + R(rt); break; //add case 33: R(rd) = R(rs) + R(rt); break; //addu case 34: - ERROR_LOG(HLE,"WARNING : exception-causing sub at %08x", PC); + if (!has_warned) { + ERROR_LOG(HLE,"WARNING : exception-causing sub at %08x", PC); + has_warned = true; + } R(rd) = R(rs) - R(rt); break; //sub case 35: R(rd) = R(rs) - R(rt); break; //subu case 36: R(rd) = R(rs) & R(rt); break; //and @@ -513,6 +552,26 @@ namespace MIPSInt HI = (u32)(result>>32); } break; + case 46: //msub + { + u32 a=R(rs),b=R(rt),hi=HI,lo=LO; + u64 origValBits = (u64)lo | ((u64)(hi)<<32); + s64 origVal = (s64)origValBits; + s64 result = origVal - (s64)(s32)a * (s64)(s32)b; + u64 resultBits = (u64)(result); + LO = (u32)(resultBits); + HI = (u32)(resultBits>>32); + } + break; + case 47: //msubu + { + u32 a=R(rs),b=R(rt),hi=HI,lo=LO; + u64 origVal = (u64)lo | ((u64)(hi)<<32); + u64 result = origVal - (u64)a * (u64)b; + LO = (u32)(result); + HI = (u32)(result>>32); + } + break; case 16: R(rd) = HI; break; //mfhi case 17: HI = R(rs); break; //mthi case 18: R(rd) = LO; break; //mflo @@ -521,9 +580,11 @@ namespace MIPSInt { s32 a = (s32)R(rs); s32 b = (s32)R(rt); - if (b != 0) { - LO = (u32)(a/b); - HI = (u32)(a%b); + if (a == 0x80000000 && b == -1) { + LO = 0x80000000; + } else if (b != 0) { + LO = (u32)(a / b); + HI = (u32)(a % b); } else { LO = HI = 0; // Not sure what the right thing to do is? } @@ -677,6 +738,16 @@ namespace MIPSInt PC += 4; } + #ifdef _MSC_VER + static float roundf(float num) + { + float integer = ceilf(num); + if (num > 0) + return integer - num > 0.5f ? integer - 1.0f : integer; + return integer - num >= 0.5f ? integer - 1.0f : integer; + } + #endif + void Int_FPU2op(u32 op) { int fs = _FS; @@ -693,7 +764,16 @@ namespace MIPSInt case 14: FsI(fd) = (int)ceilf (F(fs)); break; //ceil.w.s case 15: FsI(fd) = (int)floorf(F(fs)); break; //floor.w.s case 32: F(fd) = (float)FsI(fs); break; //cvt.s.w - case 36: FsI(fd) = (int) F(fs); break; //cvt.w.s + + case 36: + switch (currentMIPS->fcr31 & 3) + { + case 0: FsI(fd) = roundf(F(fs)); break; // RINT_0 // TODO: rintf or roundf? + case 1: FsI(fd) = (int)F(fs); break; // CAST_1 + case 2: FsI(fd) = ceilf(F(fs)); break; // CEIL_2 + case 3: FsI(fd) = floorf(F(fs)); break; // FLOOR_3 + } + break; //cvt.w.s default: _dbg_assert_msg_(CPU,0,"Trying to interpret FPU2Op instruction that can't be interpreted"); break; @@ -762,10 +842,14 @@ namespace MIPSInt void Int_Interrupt(u32 op) { + static int reported = 0; switch (op & 1) { case 0: - DEBUG_LOG(CPU,"Disable/Enable Interrupt CPU instruction"); + if (!reported) { + WARN_LOG(CPU,"Disable/Enable Interrupt CPU instruction"); + reported = 1; + } break; } PC += 4; diff --git a/Core/MIPS/MIPSInt.h b/Core/MIPS/MIPSInt.h index edddca1706..7f7ad7d1c1 100644 --- a/Core/MIPS/MIPSInt.h +++ b/Core/MIPS/MIPSInt.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -53,4 +53,5 @@ namespace MIPSInt void Int_Cache(u32 op); void Int_Sync(u32 op); void Int_Break(u32 op); + void Int_StoreSync(u32 op); } diff --git a/Core/MIPS/MIPSIntVFPU.cpp b/Core/MIPS/MIPSIntVFPU.cpp index 3baad5f7df..4e9c6663b7 100644 --- a/Core/MIPS/MIPSIntVFPU.cpp +++ b/Core/MIPS/MIPSIntVFPU.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -26,6 +26,8 @@ #include +using std::isnan; + #define R(i) (currentMIPS->r[i]) #define RF(i) (*(float*)(&(currentMIPS->r[i]))) #define V(i) (currentMIPS->v[i]) @@ -47,26 +49,26 @@ #define LO currentMIPS->lo #ifndef M_LOG2E -#define M_E 2.71828182845904523536 -#define M_LOG2E 1.44269504088896340736 -#define M_LOG10E 0.434294481903251827651 -#define M_LN2 0.693147180559945309417 -#define M_LN10 2.30258509299404568402 -#define M_PI 3.14159265358979323846 -#define M_PI_2 1.57079632679489661923 -#define M_PI_4 0.785398163397448309616 -#define M_1_PI 0.318309886183790671538 -#define M_2_PI 0.636619772367581343076 -#define M_2_SQRTPI 1.12837916709551257390 -#define M_SQRT2 1.41421356237309504880 -#define M_SQRT1_2 0.707106781186547524401 +#define M_E 2.71828182845904523536f +#define M_LOG2E 1.44269504088896340736f +#define M_LOG10E 0.434294481903251827651f +#define M_LN2 0.693147180559945309417f +#define M_LN10 2.30258509299404568402f +#define M_PI 3.14159265358979323846f +#define M_PI_2 1.57079632679489661923f +#define M_PI_4 0.785398163397448309616f +#define M_1_PI 0.318309886183790671538f +#define M_2_PI 0.636619772367581343076f +#define M_2_SQRTPI 1.12837916709551257390f +#define M_SQRT2 1.41421356237309504880f +#define M_SQRT1_2 0.707106781186547524401f #endif void ApplyPrefixST(float *v, u32 data, VectorSize size) { // Possible optimization shortcut: - // if (data == 0xe4) - // return; + if (data == 0xe4) + return; int n = GetNumVectorElements(size); float origV[4]; @@ -100,35 +102,39 @@ void ApplyPrefixST(float *v, u32 data, VectorSize size) } } -void ApplySwizzleS(float *v, VectorSize size) +inline void ApplySwizzleS(float *v, VectorSize size) { ApplyPrefixST(v, currentMIPS->vfpuCtrl[VFPU_CTRL_SPREFIX], size); } -void ApplySwizzleT(float *v, VectorSize size) +inline void ApplySwizzleT(float *v, VectorSize size) { ApplyPrefixST(v, currentMIPS->vfpuCtrl[VFPU_CTRL_TPREFIX], size); } -void ApplyPrefixD(float *v, VectorSize size) +void ApplyPrefixD(float *v, VectorSize size, bool onlyWriteMask = false) { + u32 data = currentMIPS->vfpuCtrl[VFPU_CTRL_DPREFIX]; + if (!data) + return; int n = GetNumVectorElements(size); bool writeMask[4]; - u32 data = currentMIPS->vfpuCtrl[VFPU_CTRL_DPREFIX]; for (int i = 0; i < n; i++) { - int sat = (data >> i*2) & 3; - int mask = (data >> (8+i)) & 1; + int mask = (data >> (8 + i)) & 1; writeMask[i] = mask ? true : false; - if (sat == 1) - { - if (v[i] > 1.0f) v[i]=1.0f; - if (v[i] < 0.0f) v[i]=0.0f; - } - else if (sat == 3) - { - if (v[i] > 1.0f) v[i]=1.0f; - if (v[i] < -1.0f) v[i]=-1.0f; + if (!onlyWriteMask) { + int sat = (data >> (i * 2)) & 3; + if (sat == 1) + { + if (v[i] > 1.0f) v[i] = 1.0f; + if (v[i] < 0.0f) v[i] = 0.0f; + } + else if (sat == 3) + { + if (v[i] > 1.0f) v[i] = 1.0f; + if (v[i] < -1.0f) v[i] = -1.0f; + } } } currentMIPS->SetWriteMask(writeMask); @@ -136,8 +142,8 @@ void ApplyPrefixD(float *v, VectorSize size) void EatPrefixes() { - currentMIPS->vfpuCtrl[VFPU_CTRL_SPREFIX] = 0xe4; //passthru - currentMIPS->vfpuCtrl[VFPU_CTRL_TPREFIX] = 0xe4; //passthru + currentMIPS->vfpuCtrl[VFPU_CTRL_SPREFIX] = 0xe4; // passthru + currentMIPS->vfpuCtrl[VFPU_CTRL_TPREFIX] = 0xe4; // passthru currentMIPS->vfpuCtrl[VFPU_CTRL_DPREFIX] = 0; static const bool noWriteMask[4] = {false, false, false, false}; currentMIPS->SetWriteMask(noWriteMask); @@ -145,12 +151,6 @@ void EatPrefixes() namespace MIPSInt { -#define S_not(a,b,c) (a<<2) | (b) | (c << 5) -#define SgetA(v) (((v)>>2)&0x7) -#define SgetB(v) ((v)&3) -#define SgetC(v) (((v)>>5)&0x3) -#define VS(m,row,col) V(m*4+(row)+(col)*32) - void Int_VPFX(u32 op) { int data = op & 0xFFFFF; @@ -281,9 +281,9 @@ namespace MIPSInt switch ((op >> 16) & 0xF) { - case 3: m=idt; break; //identity - case 6: m=zero; break; - case 7: m=one; break; + case 3: m=idt; break; //identity // vmidt + case 6: m=zero; break; // vzero + case 7: m=one; break; // vone default: _dbg_assert_msg_(CPU,0,"Trying to interpret instruction that can't be interpreted"); return; @@ -299,13 +299,13 @@ namespace MIPSInt int vd = _VD; VectorSize sz = GetVecSize(op); int n = GetNumVectorElements(sz); - const float ones[4] = {1,1,1,1}; - const float zeros[4] = {0,0,0,0}; + static const float ones[4] = {1,1,1,1}; + static const float zeros[4] = {0,0,0,0}; const float *v; switch ((op >> 16) & 0xF) { - case 6: v=zeros; break; - case 7: v=ones; break; + case 6: v=zeros; break; //vzero + case 7: v=ones; break; //vone default: _dbg_assert_msg_(CPU,0,"Trying to interpret instruction that can't be interpreted"); return; @@ -323,16 +323,20 @@ namespace MIPSInt void Int_Viim(u32 op) { int vt = _VT; - int imm = op&0xFFFF; + s32 imm = (s16)(op&0xFFFF); + u16 uimm16 = (op&0xFFFF); //V(vt) = (float)imm; + float f[1]; int type = (op >> 23) & 7; if (type == 6) - V(vt) = (float)imm; + f[0] = (float)imm; // viim else if (type == 7) - V(vt) = Float16ToFloat32((u16)imm); + f[0] = Float16ToFloat32((u16)uimm16); // vfim else _dbg_assert_msg_(CPU,0,"Trying to interpret instruction that can't be interpreted"); + ApplyPrefixD(f, V_Single); + V(vt) = f[0]; PC += 4; EatPrefixes(); } @@ -358,6 +362,7 @@ namespace MIPSInt _dbg_assert_msg_(CPU,0,"Trying to interpret instruction that can't be interpreted"); break; } + ApplyPrefixD(f, sz); WriteVector(f, sz, vd); PC += 4; EatPrefixes(); @@ -438,7 +443,7 @@ namespace MIPSInt void Int_Vflush(u32 op) { - DEBUG_LOG(CPU,"vflush"); + // DEBUG_LOG(CPU,"vflush"); PC += 4; } @@ -467,7 +472,9 @@ namespace MIPSInt case 21: d[i] = logf(s[i])/log(2.0f); break; case 22: d[i] = sqrtf(s[i]); break; //vsqrt case 23: d[i] = asinf(s[i] * (float)M_2_PI); break; //vasin - + // case 24: vnrcp + // case 26: vnsin + case 28: d[i] = 1.0f / expf(s[i] * (float)M_LOG2E); break; // vrexp2 default: _dbg_assert_msg_(CPU,0,"Trying to interpret VV2Op instruction that can't be interpreted"); break; @@ -479,41 +486,49 @@ namespace MIPSInt EatPrefixes(); } - void Int_Vocp(u32 op) - { - float s[4], d[4]; - int vd = _VD; - int vs = _VS; - VectorSize sz = GetVecSize(op); - ReadVector(s, sz, vs); - ApplySwizzleS(s, sz); - for (int i = 0; i < GetNumVectorElements(sz); i++) - { - d[i] = 1.0f - s[i]; //vocp - } - ApplyPrefixD(d, sz); - WriteVector(d, sz, vd); - PC += 4; - EatPrefixes(); - } + void Int_Vocp(u32 op) + { + float s[4], d[4]; + int vd = _VD; + int vs = _VS; + VectorSize sz = GetVecSize(op); + ReadVector(s, sz, vs); + ApplySwizzleS(s, sz); + for (int i = 0; i < GetNumVectorElements(sz); i++) + { + d[i] = 1.0f - s[i]; + } + ApplyPrefixD(d, sz); + WriteVector(d, sz, vd); + PC += 4; + EatPrefixes(); + } - void Int_Vsgn(u32 op) - { - float s[4], d[4]; - int vd = _VD; - int vs = _VS; - VectorSize sz = GetVecSize(op); - ReadVector(s, sz, vs); - ApplySwizzleS(s, sz); - for (int i = 0; i < GetNumVectorElements(sz); i++) - { - d[i] = s[i] > 0.0f ? 1.0f : (s[i] < 0.0f ? -1.0f : 0.0f); - } - ApplyPrefixD(d, sz); - WriteVector(d, sz, vd); - PC += 4; - EatPrefixes(); - } + void Int_Vsgn(u32 op) + { + float s[4], d[4]; + int vd = _VD; + int vs = _VS; + VectorSize sz = GetVecSize(op); + ReadVector(s, sz, vs); + ApplySwizzleS(s, sz); + for (int i = 0; i < GetNumVectorElements(sz); i++) + { + // To handle NaNs correctly, we do this with integer hackery + u32 val; + memcpy(&val, &s[i], sizeof(u32)); + if (val == 0 || val == 0x80000000) + d[i] = 0.0f; + else if ((val >> 31) == 0) + d[i] = 1.0f; + else + d[i] = -1.0f; + } + ApplyPrefixD(d, sz); + WriteVector(d, sz, vd); + PC += 4; + EatPrefixes(); + } void Int_Vf2i(u32 op) { @@ -536,7 +551,7 @@ namespace MIPSInt case 19: d[i] = (int)floor(s[i] * mult); break; //d } } - ApplyPrefixD((float*)d, sz); //TODO: and the mask to kill everything but mask + ApplyPrefixD((float*)d, sz, true); WriteVector((float*)d, sz, vd); PC += 4; EatPrefixes(); @@ -562,6 +577,129 @@ namespace MIPSInt PC += 4; EatPrefixes(); } + + // TODO: CHECK + void Int_Vh2f(u32 op) + { + _dbg_assert_msg_(CPU,0,"Trying to interpret instruction that can't be interpreted"); + /* + int s[4]; + float d[4]; + int vd = _VD; + int vs = _VS; + int imm = (op >> 16) & 0x1f; + float mult = 1.0f/(float)(1 << imm); + VectorSize sz = GetVecSize(op); + ReadVector((float*)&s, sz, vs); + ApplySwizzleS((float*)&s, sz); //TODO: and the mask to kill everything but swizzle + + for (int i = 0; i < GetNumVectorElements(sz); i++) + { + d[i] = (float)s[i] * mult; + } + ApplyPrefixD(d, sz); //TODO: and the mask to kill everything but mask + WriteVector(d, sz, vd); + */ + PC += 4; + EatPrefixes(); + } + + void Int_Vf2h(u32 op) + { + _dbg_assert_msg_(CPU,0,"Trying to interpret instruction that can't be interpreted"); + // See http://stackoverflow.com/questions/1659440/32-bit-to-16-bit-floating-point-conversion + + /* + int s[4]; + float d[4]; + int vd = _VD; + int vs = _VS; + int imm = (op >> 16) & 0x1f; + float mult = 1.0f/(float)(1 << imm); + VectorSize sz = GetVecSize(op); + ReadVector((float*)&s, sz, vs); + ApplySwizzleS((float*)&s, sz); //TODO: and the mask to kill everything but swizzle + + for (int i = 0; i < GetNumVectorElements(sz); i++) + { + d[i] = (float)s[i] * mult; + } + ApplyPrefixD(d, sz); //TODO: and the mask to kill everything but mask + WriteVector(d, sz, vd); + */ + PC += 4; + EatPrefixes(); + } + + void Int_Vx2i(u32 op) + { + int s[4]; + u32 d[4] = {0}; + int vd = _VD; + int vs = _VS; + VectorSize sz = GetVecSize(op); + VectorSize oz = sz; + ReadVector((float*)s, sz, vs); + // ForbidVPFXS + + switch ((op >> 16) & 3) { + case 0: // vuc2i + // Quad is the only option. + // This operation is weird. This particular way of working matches hw but does not + // seem quite sane. + { + u32 value = s[0]; + u32 value2 = value / 2; + for (int i = 0; i < 4; i++) { + d[i] = (u32)((value & 0xFF) * 0x01010101) >> 1; + value >>= 8; + } + oz = V_Quad; + } + break; + + case 1: // vc2i + // Quad is the only option + { + u32 value = s[0]; + d[0] = (value & 0xFF) << 24; + d[1] = (value & 0xFF00) << 16; + d[2] = (value & 0xFF0000) << 8; + d[3] = (value & 0xFF000000); + oz = V_Quad; + } + break; + + case 2: // vus2i + for (int i = 0; i < GetNumVectorElements(sz); i++) { + u32 value = s[i]; + d[i * 2] = (value & 0xFFFF) << 15; + d[i * 2 + 1] = (value & 0xFFFF0000) >> 1; + } + oz = V_Pair; + if (sz == V_Pair) oz = V_Quad; + break; + + case 3: // vs2i + for (int i = 0; i < GetNumVectorElements(sz); i++) { + u32 value = s[i]; + d[i * 2] = (value & 0xFFFF) << 16; + d[i * 2 + 1] = value & 0xFFFF0000; + } + oz = V_Pair; + if (sz == V_Pair) oz = V_Quad; + break; + default: + _dbg_assert_msg_(CPU,0,"Trying to interpret instruction that can't be interpreted"); + break; + } + + ApplyPrefixD((float*)d,oz, true); // Only write mask + WriteVector((float*)d,oz,vd); + PC += 4; + EatPrefixes(); + } + void Int_Vi2x(u32 op) { int s[4]; @@ -600,14 +738,38 @@ namespace MIPSInt break; case 2: //vi2us - //break; + { + for (int i = 0; i < GetNumVectorElements(sz) / 2; i++) { + int low = s[i * 2]; + int high = s[i * 2 + 1]; + if (low < 0) low = 0; + if (high < 0) high = 0; + low >>= 15; + high >>= 15; + d[i] = low | (high << 16); + } + if (sz == V_Quad) oz = V_Pair; + if (sz == V_Pair) oz = V_Single; + } + break; case 3: //vi2s - //break; + { + for (int i = 0; i < GetNumVectorElements(sz) / 2; i++) { + u32 low = s[i * 2]; + u32 high = s[i * 2 + 1]; + low >>= 16; + high >>= 16; + d[i] = low | (high << 16); + } + if (sz == V_Quad) oz = V_Pair; + if (sz == V_Pair) oz = V_Single; + } + break; default: _dbg_assert_msg_(CPU,0,"Trying to interpret instruction that can't be interpreted"); break; } - ApplyPrefixD((float*)d,oz); + ApplyPrefixD((float*)d,oz,true); WriteVector((float*)d,oz,vd); PC += 4; EatPrefixes(); @@ -623,7 +785,7 @@ namespace MIPSInt u16 colors[4]; for (int i = 0; i < 4; i++) { - u32 in = colors[i]; + u32 in = s[i]; u16 col = 0; switch ((op >> 16) & 3) { @@ -638,10 +800,10 @@ namespace MIPSInt } case 2: // 5551 { - int a = ((in >> 24) & 0xFF) >> 4; - int b = ((in >> 16) & 0xFF) >> 4; - int g = ((in >> 8) & 0xFF) >> 4; - int r = ((in) & 0xFF) >> 4; + int a = ((in >> 24) & 0xFF) >> 7; + int b = ((in >> 16) & 0xFF) >> 3; + int g = ((in >> 8) & 0xFF) >> 3; + int r = ((in) & 0xFF) >> 3; col = (a << 15) | (b << 10) | (g << 5) | (r); break; } @@ -826,7 +988,7 @@ namespace MIPSInt { switch ((op >> 16) & 0x1f) { - case 1: d[i] = currentMIPS->rng.R32(); break; // vrndi - TODO: copy bits instead? + case 1: d[i] = (float)currentMIPS->rng.R32(); break; // vrndi - TODO: copy bits instead? case 2: d[i] = 1.0f + ((float)currentMIPS->rng.R32() / 0xFFFFFFFF); break; // vrndf1 TODO: make more accurate case 3: d[i] = 2.0f + 2 * ((float)currentMIPS->rng.R32() / 0xFFFFFFFF); break; // vrndf2 TODO: make more accurate case 4: d[i] = 0.0f; // Should not get here @@ -845,7 +1007,7 @@ namespace MIPSInt int vs = _VS; int imm = (op >> 16) & 0x1f; VectorSize sz = GetVecSize(op); - float angle = V(vs) * (float)M_PI * 0.5f; + float angle = V(vs) * M_PI_2; bool negSin = (imm & 0x10) ? true : false; float sine = sinf(angle); float cosine = cosf(angle); @@ -970,7 +1132,7 @@ namespace MIPSInt static const float constants[32] = { 0, - std::numeric_limits::infinity(), // or max() ?? pspautotests seem to indicate inf + std::numeric_limits::max(), // or max() ?? pspautotests seem to indicate inf sqrtf(2.0f), sqrtf(0.5f), 2.0f/sqrtf((float)M_PI), @@ -1022,6 +1184,10 @@ namespace MIPSInt VC_NS }; +#ifdef _MSC_VER +#define isnan _isnan +#endif + void Int_Vcmp(u32 op) { int vt = _VT; @@ -1038,11 +1204,13 @@ namespace MIPSInt int cc = 0; int or_val = 0; int and_val = 1; + int affected_bits = (1 << 4) | (1 << 5); // 4 and 5 for (int i = 0; i < n; i++) { int c; switch (cond) { + case VC_EQ: c = s[i] == t[i]; break; case VC_EZ: c = s[i] == 0.0f || s[i] == -0.0f; break; case VC_LT: c = s[i] < t[i]; break; case VC_LE: c = s[i] <= t[i]; break; @@ -1052,26 +1220,29 @@ namespace MIPSInt case VC_GT: c = s[i] > t[i]; break; case VC_GE: c = s[i] >= t[i]; break; case VC_NZ: c = s[i] != 0; break; + case VC_ES: c = (s[i] != s[i]) || (s[i] == std::numeric_limits::infinity()); break; // Tekken Dark Resurrection + case VC_EN: c = isnan(s[i]); break; default: - _dbg_assert_msg_(CPU,0,"Unsupported vcmp condition code"); //, cond); + _dbg_assert_msg_(CPU,0,"Unsupported vcmp condition code %d", cond); return; } cc |= (c<vfpuCtrl[VFPU_CTRL_CC] = cc | (or_val<<4) | (and_val << 5); + // Use masking to only change the affected bits + currentMIPS->vfpuCtrl[VFPU_CTRL_CC] = (currentMIPS->vfpuCtrl[VFPU_CTRL_CC] & ~affected_bits) | + (cc | (or_val << 4) | (and_val << 5)) & affected_bits; PC += 4; EatPrefixes(); } - - void Int_Vcmov(u32 op) - { + void Int_Vminmax(u32 op) { + int vt = _VT; int vs = _VS; - int vd = _VD; - int tf = (op >> 19)&3; - int imm3 = (op >> 16)&7; + int vd = _VD; + int cond = op&15; VectorSize sz = GetVecSize(op); int n = GetNumVectorElements(sz); float s[4]; @@ -1079,16 +1250,48 @@ namespace MIPSInt float d[4]; ReadVector(s, sz, vs); ApplySwizzleS(s, sz); - ReadVector(t,sz,vd); //Yes! + ReadVector(t, sz, vt); ApplySwizzleT(t, sz); - for (int i = 0; i < n; i++) - d[i] = t[i]; + // positive NAN always loses, unlike SSE + // negative NAN seems different? TODO + switch ((op >> 23) & 3) { + case 2: // vmin + for (int i = 0; i < GetNumVectorElements(sz); i++) + d[i] = isnan(t[i]) ? s[i] : (isnan(s[i]) ? t[i] : std::min(s[i], t[i])); + break; + case 3: // vmax + for (int i = 0; i < GetNumVectorElements(sz); i++) + d[i] = isnan(t[i]) ? s[i] : (isnan(s[i]) ? t[i] : std::max(s[i], t[i])); + break; + default: + _dbg_assert_msg_(CPU,0,"unknown min/max op %d", cond); + return; + } + ApplyPrefixD(d, sz); + WriteVector(d, sz, vd); + PC += 4; + EatPrefixes(); + } + + void Int_Vcmov(u32 op) + { + int vs = _VS; + int vd = _VD; + int tf = (op >> 19) & 1; + int imm3 = (op >> 16) & 7; + VectorSize sz = GetVecSize(op); + int n = GetNumVectorElements(sz); + float s[4]; + float d[4]; + ReadVector(s, sz, vs); + ApplySwizzleS(s, sz); + ReadVector(d, sz, vd); //Yes! int CC = currentMIPS->vfpuCtrl[VFPU_CTRL_CC]; - if (imm3<6) + if (imm3 < 6) { - if (((CC>>imm3)&1) == !tf) + if (((CC >> imm3) & 1) == !tf) { for (int i = 0; i < n; i++) d[i] = s[i]; @@ -1098,7 +1301,7 @@ namespace MIPSInt { for (int i = 0; i < n; i++) { - if (((CC>>i)&1) == !tf) + if (((CC >> i) & 1) == !tf) d[i] = s[i]; } } @@ -1164,7 +1367,7 @@ bad: EatPrefixes(); } - + void Int_CrossQuat(u32 op) { int vd = _VD; @@ -1178,7 +1381,7 @@ bad: ReadVector(t, sz, vt); switch (sz) { - case V_Triple: + case V_Triple: // vcrsp d[0] = s[1]*t[2] - s[2]*t[1]; d[1] = s[2]*t[0] - s[0]*t[2]; d[2] = s[0]*t[1] - s[1]*t[0]; @@ -1191,6 +1394,7 @@ bad: _dbg_assert_msg_(CPU,0,"Trying to interpret instruction that can't be interpreted"); break; } + ApplyPrefixD(d, sz); WriteVector(d, sz, vd); PC += 4; EatPrefixes(); diff --git a/Core/MIPS/MIPSIntVFPU.h b/Core/MIPS/MIPSIntVFPU.h index fdfcc4a254..d246c43a44 100644 --- a/Core/MIPS/MIPSIntVFPU.h +++ b/Core/MIPS/MIPSIntVFPU.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -34,20 +34,21 @@ namespace MIPSInt void Int_VMatrixInit(u32 op); void Int_VVectorInit(u32 op); void Int_Vmmul(u32 op); - void Int_Vmscl(u32 op); + void Int_Vmscl(u32 op); void Int_Vmmov(u32 op); void Int_VV2Op(u32 op); void Int_Vrot(u32 op); void Int_VDot(u32 op); - void Int_Vavg(u32 op); - void Int_Vfad(u32 op); - void Int_Vocp(u32 op); + void Int_Vavg(u32 op); + void Int_Vfad(u32 op); + void Int_Vocp(u32 op); void Int_Vsgn(u32 op); void Int_Vtfm(u32 op); void Int_Viim(u32 op); void Int_VScl(u32 op); void Int_Vidt(u32 op); void Int_Vcmp(u32 op); + void Int_Vminmax(u32 op); void Int_Vcrs(u32 op); void Int_Vcmov(u32 op); void Int_CrossQuat(u32 op); @@ -57,9 +58,12 @@ namespace MIPSInt void Int_Vf2i(u32 op); void Int_Vi2f(u32 op); void Int_Vi2x(u32 op); + void Int_Vx2i(u32 op); void Int_VBranch(u32 op); - void Int_Vrnds(u32 op); - void Int_VrndX(u32 op); - void Int_ColorConv(u32 op); + void Int_Vrnds(u32 op); + void Int_VrndX(u32 op); + void Int_ColorConv(u32 op); + void Int_Vh2f(u32 op); + void Int_Vf2h(u32 op); } diff --git a/Core/MIPS/MIPSTables.cpp b/Core/MIPS/MIPSTables.cpp index fe2523e84e..c8940bfb49 100644 --- a/Core/MIPS/MIPSTables.cpp +++ b/Core/MIPS/MIPSTables.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -24,7 +24,7 @@ #include "MIPSIntVFPU.h" #include "MIPSCodeUtils.h" -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include "ARM/Jit.h" #else #include "x86/Jit.h" @@ -148,7 +148,7 @@ const MIPSInstruction tableImmediate[64] = //xxxxxx ..... INSTR("swr", &Jit::Comp_ITypeMem, Dis_ITypeMem, Int_ITypeMem, IN_IMM16|IN_RS_ADDR|IN_RT|OUT_MEM), INSTR("cache", &Jit::Comp_Generic, Dis_Generic, Int_Cache, 0), //48 - INSTR("ll", &Jit::Comp_Generic, Dis_Generic, 0, 0), + INSTR("ll", &Jit::Comp_Generic, Dis_Generic, Int_StoreSync, 0), INSTR("lwc1", &Jit::Comp_FPULS, Dis_FPULS, Int_FPULS, IN_RT|IN_RS_ADDR), INSTR("lv.s", &Jit::Comp_Generic, Dis_SV, Int_SV, IS_VFPU), {-2}, // HIT THIS IN WIPEOUT @@ -157,7 +157,7 @@ const MIPSInstruction tableImmediate[64] = //xxxxxx ..... INSTR("lv.q", &Jit::Comp_Generic, Dis_SVQ, Int_SVQ, IS_VFPU), //copU {VFPU5}, //56 - INSTR("sc", &Jit::Comp_Generic, Dis_Generic, 0, 0), + INSTR("sc", &Jit::Comp_Generic, Dis_Generic, Int_StoreSync, 0), INSTR("swc1", &Jit::Comp_FPULS, Dis_FPULS, Int_FPULS, 0), //copU INSTR("sv.s", &Jit::Comp_Generic, Dis_SV, Int_SV,IS_VFPU), {-2}, @@ -183,8 +183,8 @@ const MIPSInstruction tableSpecial[64] = /// 000000 ...... ...... .......... xxx //8 INSTR("jr", &Jit::Comp_JumpReg, Dis_JumpRegType, Int_JumpRegType,0), INSTR("jalr", &Jit::Comp_JumpReg, Dis_JumpRegType, Int_JumpRegType,0), - INSTR("movz", &Jit::Comp_Generic, Dis_RType3, Int_RType3, OUT_RD|IN_RS|IN_RT), - INSTR("movn", &Jit::Comp_Generic, Dis_RType3, Int_RType3, OUT_RD|IN_RS|IN_RT), + INSTR("movz", &Jit::Comp_RType3, Dis_RType3, Int_RType3, OUT_RD|IN_RS|IN_RT), + INSTR("movn", &Jit::Comp_RType3, Dis_RType3, Int_RType3, OUT_RD|IN_RS|IN_RT), INSTR("syscall", &Jit::Comp_Syscall, Dis_Syscall, Int_Syscall,0), INSTR("break", &Jit::Comp_Generic, Dis_Generic, Int_Break, 0), {-2}, @@ -223,12 +223,12 @@ const MIPSInstruction tableSpecial[64] = /// 000000 ...... ...... .......... xxx //40 {-2}, {-2}, - INSTR("slt", &Jit::Comp_Generic, Dis_RType3, Int_RType3,IN_RS|IN_RT|OUT_RD), - INSTR("sltu", &Jit::Comp_Generic, Dis_RType3, Int_RType3,IN_RS|IN_RT|OUT_RD), + INSTR("slt", &Jit::Comp_RType3, Dis_RType3, Int_RType3,IN_RS|IN_RT|OUT_RD), + INSTR("sltu", &Jit::Comp_RType3, Dis_RType3, Int_RType3,IN_RS|IN_RT|OUT_RD), INSTR("max", &Jit::Comp_Generic, Dis_RType3, Int_RType3,IN_RS|IN_RT|OUT_RD), INSTR("min", &Jit::Comp_Generic, Dis_RType3, Int_RType3,IN_RS|IN_RT|OUT_RD), - {-2}, - {-2}, + INSTR("msub", &Jit::Comp_Generic, Dis_MulDivType, Int_MulDivType, IN_RS|IN_RT|OUT_OTHER), + INSTR("msubu", &Jit::Comp_Generic, Dis_MulDivType, Int_MulDivType, IN_RS|IN_RT|OUT_OTHER), //48 INSTR("tge", &Jit::Comp_Generic, Dis_RType3, 0, 0), @@ -241,7 +241,11 @@ const MIPSInstruction tableSpecial[64] = /// 000000 ...... ...... .......... xxx {-2}, //56 - {-2}, {-2}, {-2}, {-2}, {-2}, {-2}, {-2}, {-2}, + {-2}, {-2}, {-2}, {-2}, {-2}, + + {-2}, + {-2}, + {-2}, }; const MIPSInstruction tableSpecial2[64] = @@ -344,10 +348,10 @@ const MIPSInstruction tableRegImm[32] = INSTR("tnei", &Jit::Comp_Generic, Dis_Generic, 0, 0), {-2}, - INSTR("bltzal", &Jit::Comp_Generic, Dis_RelBranch, 0, IS_CONDBRANCH|IN_RS|OUT_RA), - INSTR("bgezal", &Jit::Comp_Generic, Dis_RelBranch, 0, IS_CONDBRANCH|IN_RS|OUT_RA), - INSTR("bltzall", &Jit::Comp_Generic, Dis_RelBranch, 0, IS_CONDBRANCH|IN_RS|OUT_RA), //L = likely - INSTR("bgezall", &Jit::Comp_Generic, Dis_RelBranch, 0, IS_CONDBRANCH|IN_RS|OUT_RA), + INSTR("bltzal", &Jit::Comp_Generic, Dis_RelBranch, Int_RelBranchRI, IS_CONDBRANCH|IN_RS|OUT_RA), + INSTR("bgezal", &Jit::Comp_Generic, Dis_RelBranch, Int_RelBranchRI, IS_CONDBRANCH|IN_RS|OUT_RA), + INSTR("bltzall", &Jit::Comp_Generic, Dis_RelBranch, Int_RelBranchRI, IS_CONDBRANCH|IN_RS|OUT_RA), //L = likely + INSTR("bgezall", &Jit::Comp_Generic, Dis_RelBranch, Int_RelBranchRI, IS_CONDBRANCH|IN_RS|OUT_RA), {-2}, {-2}, {-2}, @@ -501,9 +505,9 @@ MIPSInstruction tableVFPU1[8] = MIPSInstruction tableVFPU3[8] = //011011 xxx { INSTR("vcmp",&Jit::Comp_Generic, Dis_Vcmp, Int_Vcmp, IS_VFPU), - INSTR("v???",&Jit::Comp_Generic, Dis_Generic, Int_Vcmp, IS_VFPU), // 0x6de84848 in motogp - INSTR("vmin",&Jit::Comp_Generic, Dis_Generic, 0, IS_VFPU), - INSTR("vmax",&Jit::Comp_Generic, Dis_Generic, 0, IS_VFPU), + {-2}, + INSTR("vmin",&Jit::Comp_Generic, Dis_Generic, Int_Vminmax, IS_VFPU), + INSTR("vmax",&Jit::Comp_Generic, Dis_Generic, Int_Vminmax, IS_VFPU), {-2}, INSTR("vscmp",&Jit::Comp_Generic, Dis_Generic, 0, IS_VFPU), INSTR("vsge",&Jit::Comp_Generic, Dis_Generic, 0, IS_VFPU), @@ -558,18 +562,18 @@ MIPSInstruction tableVFPU7[32] = //16 {-2}, {-2}, - INSTR("vf2h", &Jit::Comp_Generic, Dis_Generic, 0, IS_VFPU), - INSTR("vh2f", &Jit::Comp_Generic, Dis_Generic, 0, IS_VFPU), + INSTR("vf2h", &Jit::Comp_Generic, Dis_Generic, Int_Vf2h, IS_VFPU), + INSTR("vh2f", &Jit::Comp_Generic, Dis_Generic, Int_Vh2f, IS_VFPU), {-2}, {-2}, {-2}, INSTR("vlgb", &Jit::Comp_Generic, Dis_Generic, 0, IS_VFPU), //24 - {-2}, // Seen in BraveStory, initialization - {-2}, - INSTR("vus2i", &Jit::Comp_Generic, Dis_Generic, 0, IS_VFPU), - INSTR("vs2i", &Jit::Comp_Generic, Dis_Generic, 0, IS_VFPU), + INSTR("vuc2i", &Jit::Comp_Generic, Dis_Generic, Int_Vx2i, IS_VFPU), // Seen in BraveStory, initialization 110100 00001110000 000 0001 0000 0000 + INSTR("vc2i", &Jit::Comp_Generic, Dis_Generic, Int_Vx2i, IS_VFPU), + INSTR("vus2i", &Jit::Comp_Generic, Dis_Generic, Int_Vx2i, IS_VFPU), + INSTR("vs2i", &Jit::Comp_Generic, Dis_Generic, Int_Vx2i, IS_VFPU), INSTR("vi2uc", &Jit::Comp_Generic, Dis_Vi2x, Int_Vi2x, IS_VFPU), INSTR("vi2c", &Jit::Comp_Generic, Dis_Vi2x, Int_Vi2x, IS_VFPU), @@ -778,7 +782,7 @@ const int encodingBits[NumEncodings][2] = {0, 0}, //Cop2Rese {23, 3}, //VFPU0 {23, 3}, //VFPU1 - {23, 1}, //VFPU3 + {23, 3}, //VFPU3 {21, 5}, //VFPU4Jump {16, 5}, //VFPU7 {16, 5}, //VFPU4 @@ -854,6 +858,7 @@ const MIPSInstruction *MIPSGetInstruction(u32 op) if (instr->altEncoding == -2) { //BAD!! + //ERROR_LOG(CPU, "Invalid instruction %08x in table %i, entry %i", op, (int)encoding, subop); return 0; //invalid instruction } encoding = (MipsEncoding)instr->altEncoding; diff --git a/Core/MIPS/MIPSTables.h b/Core/MIPS/MIPSTables.h index 56cda4b62a..f76575cb7b 100644 --- a/Core/MIPS/MIPSTables.h +++ b/Core/MIPS/MIPSTables.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/MIPSVFPUUtils.cpp b/Core/MIPS/MIPSVFPUUtils.cpp index 86088d98bb..cf1015f28b 100644 --- a/Core/MIPS/MIPSVFPUUtils.cpp +++ b/Core/MIPS/MIPSVFPUUtils.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/MIPSVFPUUtils.h b/Core/MIPS/MIPSVFPUUtils.h index 933e3e7c7a..0c9307decd 100644 --- a/Core/MIPS/MIPSVFPUUtils.h +++ b/Core/MIPS/MIPSVFPUUtils.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/x86/Asm.cpp b/Core/MIPS/x86/Asm.cpp index 9141400476..8aca44f08e 100644 --- a/Core/MIPS/x86/Asm.cpp +++ b/Core/MIPS/x86/Asm.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/x86/Asm.h b/Core/MIPS/x86/Asm.h index 717e096116..22b93e174e 100644 --- a/Core/MIPS/x86/Asm.h +++ b/Core/MIPS/x86/Asm.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/x86/CompALU.cpp b/Core/MIPS/x86/CompALU.cpp index e60a3478d4..c86551baf2 100644 --- a/Core/MIPS/x86/CompALU.cpp +++ b/Core/MIPS/x86/CompALU.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -29,7 +29,12 @@ using namespace MIPSAnalyst; #define _POS ((op>>6 ) & 0x1F) #define _SIZE ((op>>11 ) & 0x1F) -#define OLDD Comp_Generic(op); return; +// All functions should have CONDITIONAL_DISABLE, so we can narrow things down to a file quickly. +// Currently known non working ones should have DISABLE. + +//#define CONDITIONAL_DISABLE Comp_Generic(op); return; +#define CONDITIONAL_DISABLE ; +#define DISABLE Comp_Generic(op); return; namespace MIPSComp { @@ -48,7 +53,7 @@ namespace MIPSComp void Jit::Comp_IType(u32 op) { - // OLDD + CONDITIONAL_DISABLE; s32 simm = (s16)(op & 0xFFFF); u32 uimm = (u16)(op & 0xFFFF); @@ -141,7 +146,8 @@ namespace MIPSComp void Jit::Comp_RType3(u32 op) { - // OLDD + CONDITIONAL_DISABLE + int rt = _RT; int rs = _RS; int rd = _RD; @@ -175,8 +181,9 @@ namespace MIPSComp break; case 42: //R(rd) = (int)R(rs) < (int)R(rt); break; //slt - gpr.Lock(rt, rs); + gpr.Lock(rt, rs, rd); gpr.BindToRegister(rs, true, true); + gpr.BindToRegister(rd, true, true); XOR(32, R(EAX), R(EAX)); CMP(32, gpr.R(rs), gpr.R(rt)); SETcc(CC_L, R(EAX)); @@ -187,6 +194,7 @@ namespace MIPSComp case 43: //R(rd) = R(rs) < R(rt); break; //sltu gpr.Lock(rd, rs, rt); gpr.BindToRegister(rs, true, true); + gpr.BindToRegister(rd, true, true); XOR(32, R(EAX), R(EAX)); CMP(32, gpr.R(rs), gpr.R(rt)); SETcc(CC_B, R(EAX)); @@ -222,6 +230,7 @@ namespace MIPSComp // "over-shifts" work the same as on x86 - only bottom 5 bits are used to get the shift value void Jit::CompShiftVar(u32 op, void (XEmitter::*shift)(int, OpArg, OpArg)) { + DISABLE; int rd = _RD; int rt = _RT; int rs = _RS; @@ -239,17 +248,19 @@ namespace MIPSComp void Jit::Comp_ShiftType(u32 op) { + CONDITIONAL_DISABLE + int rs = _RS; + int fd = _FD; // WARNIGN : ROTR - // OLDD switch (op & 0x3f) { case 0: CompShiftImm(op, &XEmitter::SHL); break; - case 2: CompShiftImm(op, &XEmitter::SHR); break; // srl + case 2: CompShiftImm(op, rs == 1 ? &XEmitter::ROR : &XEmitter::SHR); break; // srl, rotr case 3: CompShiftImm(op, &XEmitter::SAR); break; // sra - case 4: CompShiftVar(op, &XEmitter::SHL); break; // R(rd) = R(rt) << R(rs); break; //sllv - case 6: CompShiftVar(op, &XEmitter::SHR); break; // R(rd) = R(rt) >> R(rs); break; //srlv - case 7: CompShiftVar(op, &XEmitter::SAR); break; // R(rd) = ((s32)R(rt)) >> R(rs); break; //srav + case 4: CompShiftVar(op, &XEmitter::SHL); break; //sllv + case 6: CompShiftVar(op, fd == 1 ? &XEmitter::ROR : &XEmitter::SHR); break; //srlv + case 7: CompShiftVar(op, &XEmitter::SAR); break; //srav default: Comp_Generic(op); @@ -260,7 +271,7 @@ namespace MIPSComp void Jit::Comp_Allegrex(u32 op) { - // OLDD + CONDITIONAL_DISABLE int rt = _RT; int rd = _RD; switch ((op >> 6) & 31) diff --git a/Core/MIPS/x86/CompBranch.cpp b/Core/MIPS/x86/CompBranch.cpp index b86a6d3f02..85a47125e5 100644 --- a/Core/MIPS/x86/CompBranch.cpp +++ b/Core/MIPS/x86/CompBranch.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -39,6 +39,9 @@ using namespace MIPSAnalyst; +// NOTE: Can't use CONDITIONAL_DISABLE in this file, branches are so special +// that they cannot be interpreted in the context of the Jit. + namespace MIPSComp { diff --git a/Core/MIPS/x86/CompFPU.cpp b/Core/MIPS/x86/CompFPU.cpp index f52d0f3212..f14ac8911d 100644 --- a/Core/MIPS/x86/CompFPU.cpp +++ b/Core/MIPS/x86/CompFPU.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -30,7 +30,12 @@ #define _POS ((op>>6 ) & 0x1F) #define _SIZE ((op>>11 ) & 0x1F) -#define OLDD Comp_Generic(op); return; +// All functions should have CONDITIONAL_DISABLE, so we can narrow things down to a file quickly. +// Currently known non working ones should have DISABLE. + +// #define CONDITIONAL_DISABLE Comp_Generic(op); return; +#define CONDITIONAL_DISABLE ; +#define DISABLE Comp_Generic(op); return; namespace MIPSComp { @@ -65,12 +70,13 @@ void Jit::CompFPTriArith(u32 op, void (XEmitter::*arith)(X64Reg reg, OpArg), boo void Jit::Comp_FPU3op(u32 op) { + CONDITIONAL_DISABLE; switch (op & 0x3f) { case 0: CompFPTriArith(op, &XEmitter::ADDSS, false); break; //F(fd) = F(fs) + F(ft); //add - case 1: CompFPTriArith(op, &XEmitter::SUBSS, true); break; //F(fd) = F(fs) - F(ft); //sub + case 1: CompFPTriArith(op, &XEmitter::SUBSS, true); break; //F(fd) = F(fs) - F(ft); //sub case 2: CompFPTriArith(op, &XEmitter::MULSS, false); break; //F(fd) = F(fs) * F(ft); //mul - case 3: CompFPTriArith(op, &XEmitter::DIVSS, true); break; //F(fd) = F(fs) / F(ft); //div + case 3: CompFPTriArith(op, &XEmitter::DIVSS, true); break; //F(fd) = F(fs) / F(ft); //div default: _dbg_assert_msg_(CPU,0,"Trying to compile FPU3Op instruction that can't be interpreted"); break; @@ -79,6 +85,8 @@ void Jit::Comp_FPU3op(u32 op) void Jit::Comp_FPULS(u32 op) { + CONDITIONAL_DISABLE; + s32 offset = (s16)(op&0xFFFF); int ft = ((op>>16)&0x1f); int rs = _RS; @@ -128,6 +136,8 @@ static const u64 GC_ALIGNED16(ssNoSignMask[2]) = {0x7FFFFFFF7FFFFFFFULL, 0x7FFFF void Jit::Comp_FPU2op(u32 op) { + CONDITIONAL_DISABLE; + int fs = _FS; int fd = _FD; @@ -189,6 +199,8 @@ void Jit::Comp_FPU2op(u32 op) void Jit::Comp_mxc1(u32 op) { + CONDITIONAL_DISABLE; + int fs = _FS; int rt = _RT; diff --git a/Core/MIPS/x86/CompLoadStore.cpp b/Core/MIPS/x86/CompLoadStore.cpp index cc1d6ec5ac..69560307f8 100644 --- a/Core/MIPS/x86/CompLoadStore.cpp +++ b/Core/MIPS/x86/CompLoadStore.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,7 +31,12 @@ #define _POS ((op>>6 ) & 0x1F) #define _SIZE ((op>>11 ) & 0x1F) -#define OLDD Comp_Generic(op); return; +// All functions should have CONDITIONAL_DISABLE, so we can narrow things down to a file quickly. +// Currently known non working ones should have DISABLE. + +// #define CONDITIONAL_DISABLE Comp_Generic(op); return; +#define CONDITIONAL_DISABLE ; +#define DISABLE Comp_Generic(op); return; namespace MIPSComp { diff --git a/Core/MIPS/x86/CompVFPU.cpp b/Core/MIPS/x86/CompVFPU.cpp index 24a5751800..fddc4bc419 100644 --- a/Core/MIPS/x86/CompVFPU.cpp +++ b/Core/MIPS/x86/CompVFPU.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -21,6 +21,13 @@ #include "Jit.h" #include "RegCache.h" +// All functions should have CONDITIONAL_DISABLE, so we can narrow things down to a file quickly. +// Currently known non working ones should have DISABLE. + +// #define CONDITIONAL_DISABLE Comp_Generic(op); return; +#define CONDITIONAL_DISABLE ; +#define DISABLE Comp_Generic(op); return; + #define _RS ((op>>21) & 0x1F) #define _RT ((op>>16) & 0x1F) diff --git a/Core/MIPS/x86/Jit.cpp b/Core/MIPS/x86/Jit.cpp index 519f7aa1f2..f046de4453 100644 --- a/Core/MIPS/x86/Jit.cpp +++ b/Core/MIPS/x86/Jit.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/x86/Jit.h b/Core/MIPS/x86/Jit.h index 512a8c9a5e..eac06d027c 100644 --- a/Core/MIPS/x86/Jit.h +++ b/Core/MIPS/x86/Jit.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -20,7 +20,7 @@ #include "../../../Globals.h" #include "Asm.h" -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #error DO NOT BUILD X86 JIT ON ANDROID #endif diff --git a/Core/MIPS/x86/JitCache.cpp b/Core/MIPS/x86/JitCache.cpp index 6433091ec3..7b8bd1a358 100644 --- a/Core/MIPS/x86/JitCache.cpp +++ b/Core/MIPS/x86/JitCache.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/x86/JitCache.h b/Core/MIPS/x86/JitCache.h index 163194b1d3..976080bd79 100644 --- a/Core/MIPS/x86/JitCache.h +++ b/Core/MIPS/x86/JitCache.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/x86/RegCache.cpp b/Core/MIPS/x86/RegCache.cpp index 041c04a933..2cc65533da 100644 --- a/Core/MIPS/x86/RegCache.cpp +++ b/Core/MIPS/x86/RegCache.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MIPS/x86/RegCache.h b/Core/MIPS/x86/RegCache.h index a3c31ca26d..32e9ed4fd2 100644 --- a/Core/MIPS/x86/RegCache.h +++ b/Core/MIPS/x86/RegCache.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/MemMap.cpp b/Core/MemMap.cpp index 79bc5903ab..38a5027173 100644 --- a/Core/MemMap.cpp +++ b/Core/MemMap.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -45,6 +45,7 @@ u8 *m_pScratchPad; u8 *m_pVRAM; u8 *m_pPhysicalScratchPad; +u8 *m_pUncachedScratchPad; // 64-bit: Pointers to high-mem mirrors // 32-bit: Same as above u8 *m_pPhysicalRAM; @@ -59,6 +60,7 @@ u8 *m_pUncachedVRAM; static const MemoryView views[] = { {&m_pScratchPad, &m_pPhysicalScratchPad, 0x00010000, SCRATCHPAD_SIZE, 0}, + {NULL, &m_pUncachedScratchPad, 0x40010000, SCRATCHPAD_SIZE, MV_MIRROR_PREVIOUS}, {&m_pVRAM, &m_pPhysicalVRAM, 0x04000000, 0x00800000, 0}, {NULL, &m_pUncachedVRAM, 0x44000000, 0x00800000, MV_MIRROR_PREVIOUS}, {&m_pRAM, &m_pPhysicalRAM, 0x08000000, RAM_SIZE, 0}, // only from 0x08800000 is it usable (last 24 megs) @@ -149,7 +151,7 @@ void Memset(const u32 _Address, const u8 _iValue, const u32 _iLength) else { for (size_t i = 0; i < _iLength; i++) - Write_U8(_iValue, _Address + i); + Write_U8(_iValue, (u32)(_Address + i)); } } diff --git a/Core/MemMap.h b/Core/MemMap.h index 62fb8c5ca1..6afd44e118 100644 --- a/Core/MemMap.h +++ b/Core/MemMap.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -211,12 +211,15 @@ void Memcpy(const u32 _Address, const void *_Data, const u32 _iLength); template void ReadStruct(u32 address, T *ptr) { - memcpy(ptr, GetPointer(address), sizeof(*ptr)); + size_t sz = sizeof(*ptr); + memcpy(ptr, GetPointer(address), sz); } + template void WriteStruct(u32 address, T *ptr) { - memcpy(GetPointer(address), ptr, sizeof(*ptr)); + size_t sz = sizeof(*ptr); + memcpy(GetPointer(address), ptr, sz); } const char *GetAddressName(u32 address); diff --git a/Core/MemMapFunctions.cpp b/Core/MemMapFunctions.cpp index 6aa36380df..78f8262f0e 100644 --- a/Core/MemMapFunctions.cpp +++ b/Core/MemMapFunctions.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -48,9 +48,9 @@ u8 *GetPointer(const u32 address) { return m_pVRAM + (address & VRAM_MASK); } - else if ((address & 0xFFFF0000) == 0x00010000) + else if ((address & 0xBFFF0000) == 0x00010000) { - return m_pScratchPad + (address & VRAM_MASK); + return m_pScratchPad + (address & SCRATCHPAD_MASK); } else { @@ -75,14 +75,14 @@ inline void ReadFromHardware(T &var, const u32 address) { var = *((const T*)&m_pVRAM[address & VRAM_MASK]); } - else if ((address & 0xFFFF0000) == 0x00010000) + else if ((address & 0xBFFF0000) == 0x00010000) { // Scratchpad var = *((const T*)&m_pScratchPad[address & SCRATCHPAD_MASK]); } else { - WARN_LOG(MEMMAP, "ReadFromHardware: Invalid address %08x PC %08x LR %08x", address, currentMIPS->pc, currentMIPS->r[MIPS_REG_RA]); + WARN_LOG(MEMMAP, "ReadFromHardware: Invalid address %08x PC %08x PPC %08x LR %08x", address, currentMIPS->pc, currentMIPS->prevPC, currentMIPS->r[MIPS_REG_RA]); if (!g_Config.bIgnoreBadMemAccess) { // TODO: Not sure what the best way to crash is... exit(0); @@ -104,7 +104,7 @@ inline void WriteToHardware(u32 address, const T data) { *(T*)&m_pVRAM[address & VRAM_MASK] = data; } - else if ((address & 0xFFFF0000) == 0x00010000) + else if ((address & 0xBFFF0000) == 0x00010000) { *(T*)&m_pScratchPad[address & SCRATCHPAD_MASK] = data; } @@ -130,7 +130,7 @@ bool IsValidAddress(const u32 address) { return true; } - else if ((address & 0xFFFF0000) == 0x00010000) + else if ((address & 0xBFFF0000) == 0x00010000) { return true; } diff --git a/Core/PSPLoaders.cpp b/Core/PSPLoaders.cpp index 6508c9999e..49750d3fbc 100644 --- a/Core/PSPLoaders.cpp +++ b/Core/PSPLoaders.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -64,8 +64,26 @@ bool Load_PSP_ISO(const char *filename, std::string *error_string) pspFileSystem.Mount("UMD1:", umd2); pspFileSystem.Mount("DISC0:", umd2); - std::string bootpath("disc0:/PSP_GAME/SYSDIR/BOOT.BIN"); - //std::string bootpath("/PSP_GAME/USRDIR/locoroco/locoroco.prx"); + std::string bootpath("disc0:/PSP_GAME/SYSDIR/EBOOT.BIN"); + // bypass patchers + if (pspFileSystem.GetFileInfo("disc0:/PSP_GAME/SYSDIR/EBOOT.OLD").exists) { + bootpath = "disc0:/PSP_GAME/SYSDIR/EBOOT.OLD"; + } + bool hasEncrypted = false; + u32 fd; + if ((fd = pspFileSystem.OpenFile(bootpath, FILEACCESS_READ)) != 0) + { + u8 head[4]; + pspFileSystem.ReadFile(fd, head, 4); + if (memcmp(head, "~PSP", 4) == 0 || memcmp(head, "\x7F""ELF", 4) == 0) { + hasEncrypted = true; + } + } + if (!hasEncrypted) + { + // try unencrypted BOOT.BIN + bootpath = "disc0:/PSP_GAME/SYSDIR/BOOT.BIN"; + } INFO_LOG(LOADER,"Loading %s...", bootpath.c_str()); return __KernelLoadExec(bootpath.c_str(), 0, error_string); diff --git a/Core/PSPLoaders.h b/Core/PSPLoaders.h index 0de7838a32..4de0f2cb3e 100644 --- a/Core/PSPLoaders.h +++ b/Core/PSPLoaders.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/PSPMixer.cpp b/Core/PSPMixer.cpp index cdb1e43f36..30e3e5764f 100644 --- a/Core/PSPMixer.cpp +++ b/Core/PSPMixer.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/PSPMixer.h b/Core/PSPMixer.h index 4e0f562172..240d073552 100644 --- a/Core/PSPMixer.h +++ b/Core/PSPMixer.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/System.cpp b/Core/System.cpp index e575aba3ee..0a6f1c8f9c 100644 --- a/Core/System.cpp +++ b/Core/System.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,7 +19,7 @@ #include "MIPS/MIPS.h" -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include "MIPS/ARM/Jit.h" #else #include "MIPS/x86/Jit.h" @@ -84,6 +84,7 @@ bool PSP_Init(const CoreParameter &coreParam, std::string *error_string) { DisplayDrawer_Init(); } + shaderManager.DirtyShader(); shaderManager.DirtyUniform(DIRTY_ALL); diff --git a/Core/System.h b/Core/System.h index a3fc5ba360..352897e640 100644 --- a/Core/System.h +++ b/Core/System.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Core/Util/BlockAllocator.cpp b/Core/Util/BlockAllocator.cpp index 2379f71ef7..27183cbff8 100644 --- a/Core/Util/BlockAllocator.cpp +++ b/Core/Util/BlockAllocator.cpp @@ -1,8 +1,9 @@ +#include "Log.h" #include "BlockAllocator.h" // Slow freaking thing but works (eventually) :) -BlockAllocator::BlockAllocator() +BlockAllocator::BlockAllocator(int grain) : grain_(grain) { blocks.clear(); } @@ -12,27 +13,34 @@ BlockAllocator::~BlockAllocator() Shutdown(); } -void BlockAllocator::Init(u32 _rangeStart, u32 _rangeSize) +void BlockAllocator::Init(u32 rangeStart, u32 rangeSize) { Shutdown(); + rangeStart_ = rangeStart; + rangeSize_ = rangeSize; //Initial block, covering everything - blocks.push_back(Block(_rangeStart, _rangeSize, false)); + blocks.push_back(Block(rangeStart_, rangeSize_, false)); } - void BlockAllocator::Shutdown() { blocks.clear(); } -u32 BlockAllocator::Alloc(u32 &size, bool fromEnd, const char *tag) +u32 BlockAllocator::Alloc(u32 &size, bool fromTop, const char *tag) { - //upalign size - size = (size+15) & ~15; + // Sanity check + if (size == 0 || size > rangeSize_) { + ERROR_LOG(HLE, "Clearly bogus size: %08x - failing allocation", size); + return 0; + } - if (!fromEnd) + // upalign size to grain + size = (size + grain_ - 1) & ~(grain_ - 1); + + if (!fromTop) { - //Allocate from start of mem + //Allocate from bottom of mem for (std::list::iterator iter = blocks.begin(); iter != blocks.end(); iter++) { BlockAllocator::Block &b = *iter; @@ -58,6 +66,7 @@ u32 BlockAllocator::Alloc(u32 &size, bool fromEnd, const char *tag) } else { + // Allocate from top of mem. for (std::list::reverse_iterator iter = blocks.rbegin(); iter != blocks.rend(); ++iter) { std::list::reverse_iterator hey = iter; @@ -92,8 +101,20 @@ u32 BlockAllocator::Alloc(u32 &size, bool fromEnd, const char *tag) u32 BlockAllocator::AllocAt(u32 position, u32 size, const char *tag) { - //upalign size - size=(size+15) & ~15; + CheckBlocks(); + if (size > rangeSize_) { + ERROR_LOG(HLE, "Clearly bogus size: %08x - failing allocation", size); + return 0; + } + + // upalign size to grain + size = (size + grain_ - 1) & ~(grain_ - 1); + + // check that position is aligned + if (position & (grain_ - 1)) { + ERROR_LOG(HLE, "Position %08x does not align to grain. Grain will be off.", position); + } + std::list::iterator iter = GetBlockIterFromAddress(position); if (iter != blocks.end()) { @@ -112,6 +133,7 @@ u32 BlockAllocator::AllocAt(u32 position, u32 size, const char *tag) b.taken = true; b.size = size; b.SetTag(tag); + CheckBlocks(); return position; } else @@ -145,44 +167,54 @@ u32 BlockAllocator::AllocAt(u32 position, u32 size, const char *tag) void BlockAllocator::MergeFreeBlocks() { - bool found; - do +restart: + DEBUG_LOG(HLE, "Merging Blocks"); + std::list::iterator iter1, iter2; + iter1 = blocks.begin(); + iter2 = blocks.begin(); + iter2++; + while (iter2 != blocks.end()) { - found = false; - std::list::iterator iter1, iter2; - iter1 = blocks.begin(); - iter2 = blocks.begin(); - iter2++; - while (iter2 != blocks.end()) - { - BlockAllocator::Block &b1 = *iter1; - BlockAllocator::Block &b2 = *iter2; + BlockAllocator::Block &b1 = *iter1; + BlockAllocator::Block &b2 = *iter2; - if (b1.taken == false && b2.taken == false) - { - DEBUG_LOG(HLE, "Block Alloc found adjacent free blocks - merging"); - b1.size += b2.size; - blocks.erase(iter2); - found = true; - break; //iterators now invalid - we have to restart our search - } - iter1++; - iter2++; + if (b1.taken == false && b2.taken == false) + { + DEBUG_LOG(HLE, "Block Alloc found adjacent free blocks - merging"); + b1.size += b2.size; + blocks.erase(iter2); + CheckBlocks(); + goto restart; //iterators now invalid - we have to restart our search } - } while (found); + iter1++; + iter2++; + } } -void BlockAllocator::Free(u32 position) +bool BlockAllocator::Free(u32 position) { BlockAllocator::Block *b = GetBlockFromAddress(position); - if (b) + if (b && b->taken) { b->taken = false; MergeFreeBlocks(); + return true; } else { ERROR_LOG(HLE, "BlockAllocator : invalid free %08x", position); + return false; + } +} + +void BlockAllocator::CheckBlocks() +{ + for (std::list::iterator iter = blocks.begin(); iter != blocks.end(); iter++) + { + BlockAllocator::Block &b = *iter; + if (b.start > 0xc0000000) { // probably free'd debug values + ERROR_LOG(HLE, "Bogus block in allocator"); + } } } @@ -209,7 +241,6 @@ BlockAllocator::Block *BlockAllocator::GetBlockFromAddress(u32 addr) return &(*iter); } - u32 BlockAllocator::GetBlockStartFromAddress(u32 addr) { Block *b = GetBlockFromAddress(addr); @@ -228,7 +259,6 @@ u32 BlockAllocator::GetBlockSizeFromAddress(u32 addr) return -1; } - void BlockAllocator::ListBlocks() { INFO_LOG(HLE,"-----------"); @@ -254,7 +284,6 @@ u32 BlockAllocator::GetLargestFreeBlockSize() return maxFreeBlock; } - u32 BlockAllocator::GetTotalFreeBytes() { u32 sum = 0; diff --git a/Core/Util/BlockAllocator.h b/Core/Util/BlockAllocator.h index 7974b67331..7ed26d3fc6 100644 --- a/Core/Util/BlockAllocator.h +++ b/Core/Util/BlockAllocator.h @@ -13,31 +13,8 @@ class BlockAllocator { - struct Block - { - Block(u32 _start, u32 _size, bool _taken) : start(_start), size(_size), taken(_taken) - { - strcpy(tag, "Empty"); - } - void SetTag(const char *_tag) { - if (_tag) - strcpy(tag, _tag); - else - strcpy(tag, "---"); - } - u32 start; - u32 size; - bool taken; - char tag[16]; - }; - - std::list blocks; - - Block *GetBlockFromAddress(u32 addr); - std::list::iterator GetBlockIterFromAddress(u32 addr); - public: - BlockAllocator(); + BlockAllocator(int grain = 16); // 16 byte granularity by default. ~BlockAllocator(); void Init(u32 _rangeStart, u32 _rangeSize); @@ -46,10 +23,10 @@ public: void ListBlocks(); // WARNING: size can be modified upwards! - u32 Alloc(u32 &size, bool fromEnd = false, const char *tag = 0); + u32 Alloc(u32 &size, bool fromTop = false, const char *tag = 0); u32 AllocAt(u32 position, u32 size, const char *tag = 0); - void Free(u32 position); + bool Free(u32 position); bool IsBlockFree(u32 position) { Block *b = GetBlockFromAddress(position); if (b) @@ -64,4 +41,35 @@ public: u32 GetBlockSizeFromAddress(u32 addr); u32 GetLargestFreeBlockSize(); u32 GetTotalFreeBytes(); + +private: + void CheckBlocks(); + + struct Block + { + Block(u32 _start, u32 _size, bool _taken) : start(_start), size(_size), taken(_taken) + { + strcpy(tag, "(untitled)"); + } + void SetTag(const char *_tag) { + if (_tag) + strncpy(tag, _tag, 32); + else + strncpy(tag, "---", 32); + tag[31] = 0; + } + u32 start; + u32 size; + bool taken; + char tag[32]; + }; + + std::list blocks; + u32 rangeStart_; + u32 rangeSize_; + + u32 grain_; + + Block *GetBlockFromAddress(u32 addr); + std::list::iterator GetBlockIterFromAddress(u32 addr); }; diff --git a/GPU/CMakeLists.txt b/GPU/CMakeLists.txt index d898bc3a04..dc8f31dd4d 100644 --- a/GPU/CMakeLists.txt +++ b/GPU/CMakeLists.txt @@ -9,6 +9,7 @@ set(SRCS GLES/TransformPipeline.cpp GLES/VertexDecoder.cpp GLES/VertexShaderGenerator.cpp + Null/NullGpu.cpp ) set(SRCS ${SRCS}) diff --git a/GPU/GLES/DisplayListInterpreter.cpp b/GPU/GLES/DisplayListInterpreter.cpp index 234298da3c..e70bd6b6fb 100644 --- a/GPU/GLES/DisplayListInterpreter.cpp +++ b/GPU/GLES/DisplayListInterpreter.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -15,7 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include #include #else @@ -76,7 +76,7 @@ bool finished; u8 bezierBuf[16000]; -bool ProcessDLQueue() +bool GLES_GPU::ProcessDLQueue() { std::vector::iterator iter = dlQueue.begin(); while (!(iter == dlQueue.end())) @@ -85,7 +85,7 @@ bool ProcessDLQueue() dcontext.pc = l.listpc; dcontext.stallAddr = l.stall; // DEBUG_LOG(G3D,"Okay, starting DL execution at %08 - stall = %08x", context.pc, stallAddr); - if (!GPU::InterpretList()) + if (!InterpretList()) { l.listpc = dcontext.pc; l.stall = dcontext.stallAddr; @@ -102,7 +102,7 @@ bool ProcessDLQueue() return true; //no more lists! } -u32 GPU::EnqueueList(u32 listpc, u32 stall) +u32 GLES_GPU::EnqueueList(u32 listpc, u32 stall) { DisplayList dl; dl.id = dlIdGenerator++; @@ -115,7 +115,7 @@ u32 GPU::EnqueueList(u32 listpc, u32 stall) return 0; } -void GPU::UpdateStall(int listid, u32 newstall) +void GLES_GPU::UpdateStall(int listid, u32 newstall) { // this needs improvement.... for (std::vector::iterator iter = dlQueue.begin(); iter != dlQueue.end(); iter++) @@ -130,6 +130,11 @@ void GPU::UpdateStall(int listid, u32 newstall) ProcessDLQueue(); } +void GLES_GPU::DrawSync(int mode) +{ + +} + // Just to get something on the screen, we'll just not subdivide correctly. void drawBezier(int ucount, int vcount) { @@ -224,7 +229,7 @@ void SetBlendModePSP(u32 data) GL_FUNC_ADD, GL_FUNC_SUBTRACT, GL_FUNC_REVERSE_SUBTRACT, -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) GL_FUNC_ADD, GL_FUNC_ADD, #else @@ -241,7 +246,7 @@ void SetBlendModePSP(u32 data) } -void GPU::ExecuteOp(u32 op, u32 diff) +void GLES_GPU::ExecuteOp(u32 op, u32 diff) { u32 cmd = op >> 24; u32 data = op & 0xFFFFFF; @@ -250,15 +255,16 @@ void GPU::ExecuteOp(u32 op, u32 diff) switch (cmd) { case GE_CMD_BASE: + DEBUG_LOG(G3D,"DL BASE: %06x", data); break; case GE_CMD_VADDR: /// <<8???? - gstate.vertexAddr = (gstate.base<<8)|data; + gstate.vertexAddr = ((gstate.base & 0x00FF0000) << 8)|data; DEBUG_LOG(G3D,"DL VADDR: %06x", gstate.vertexAddr); break; case GE_CMD_IADDR: - gstate.indexAddr = (gstate.base<<8)|data; + gstate.indexAddr = ((gstate.base & 0x00FF0000) << 8)|data; DEBUG_LOG(G3D,"DL IADDR: %06x", gstate.indexAddr); break; @@ -275,8 +281,7 @@ void GPU::ExecuteOp(u32 op, u32 diff) "TRIANGLE_FAN=5,", "RECTANGLES=6,", }; - DEBUG_LOG(G3D, "DrawPrim type: %s count: %i", type<7 ? types[type] : "INVALID", count); - DEBUG_LOG(G3D, "DrawPrim vaddr= %08x, iaddr= %08x", gstate.vertexAddr, gstate.indexAddr); + DEBUG_LOG(G3D, "DL DrawPrim type: %s count: %i vaddr= %08x, iaddr= %08x", type<7 ? types[type] : "INVALID", count, gstate.vertexAddr, gstate.indexAddr); LinkedShader *linkedShader = shaderManager.ApplyShader(); // TODO: Split this so that we can collect sequences of primitives, can greatly speed things up @@ -292,23 +297,27 @@ void GPU::ExecuteOp(u32 op, u32 diff) // The arrow and other rotary items in Puzbob are bezier patches, strangely enough. case GE_CMD_BEZIER: { - drawBezier(data & 0xFF, (data >> 8) & 0xFF); + int bz_ucount = data & 0xFF; + int bz_vcount = (data >> 8) & 0xFF; + drawBezier(bz_ucount, bz_vcount); + DEBUG_LOG(G3D,"DL DRAW BEZIER: %i x %i", bz_ucount, bz_vcount); } break; case GE_CMD_SPLINE: { - //int sp_ucount = data & 0xFF; - //int sp_vcount = (data >> 8) & 0xFF; - //int sp_utype = (data >> 16) & 0x3; - //int sp_vtype = (data >> 18) & 0x3; + int sp_ucount = data & 0xFF; + int sp_vcount = (data >> 8) & 0xFF; + int sp_utype = (data >> 16) & 0x3; + int sp_vtype = (data >> 18) & 0x3; //drawSpline(sp_ucount, sp_vcount, sp_utype, sp_vtype); + DEBUG_LOG(G3D,"DL DRAW SPLINE: %i x %i, %i x %i", sp_ucount, sp_vcount, sp_utype, sp_vtype); } break; case GE_CMD_JUMP: { - u32 target = ((gstate.base << 8) | (op & 0xFFFFFC)) & 0x0FFFFFFF; + u32 target = (((gstate.base & 0x00FF0000) << 8) | (op & 0xFFFFFC)) & 0x0FFFFFFF; DEBUG_LOG(G3D,"DL CMD JUMP - %08x to %08x", dcontext.pc, target); dcontext.pc = target - 4; // pc will be increased after we return, counteract that } @@ -318,7 +327,7 @@ void GPU::ExecuteOp(u32 op, u32 diff) { u32 retval = dcontext.pc + 4; stack[stackptr++] = retval; - u32 target = ((gstate.base << 8) | (op & 0xFFFFFC)) & 0xFFFFFFF; + u32 target = (((gstate.base & 0x00FF0000) << 8) | (op & 0xFFFFFC)) & 0xFFFFFFF; DEBUG_LOG(G3D,"DL CMD CALL - %08x to %08x, ret=%08x", dcontext.pc, target, retval); dcontext.pc = target - 4; // pc will be increased after we return, counteract that } @@ -334,29 +343,23 @@ void GPU::ExecuteOp(u32 op, u32 diff) break; case GE_CMD_SIGNAL: - ERROR_LOG(G3D, "GE_CMD_SIGNAL %08x", data & 0xFFFFFF); { - // int behaviour = (data >> 16) & 0xFF; - // int signal = data & 0xFFFF; + ERROR_LOG(G3D, "DL GE_CMD_SIGNAL %08x", data & 0xFFFFFF); + int behaviour = (data >> 16) & 0xFF; + int signal = data & 0xFFFF; + + __TriggerInterruptWithArg(PSP_GE_INTR, PSP_GE_SUBINTR_SIGNAL, signal); } - - // This should generate a GE Interrupt - // __TriggerInterrupt(PSP_GE_INTR); - - // Apparently, these callbacks should be done in a special interrupt way. - //for (size_t i = 0; i < signalCallbacks.size(); i++) - //{ - // __KernelNotifyCallback(-1, signalCallbacks[i].first, signal); - //} - break; case GE_CMD_BJUMP: // bounding box jump. Let's just not jump, for now. + ERROR_LOG(G3D,"DL BBOX JUMP - unimplemented"); break; case GE_CMD_BOUNDINGBOX: // bounding box test. Let's do nothing. + ERROR_LOG(G3D,"DL BBOX TEST - unimplemented"); break; case GE_CMD_ORIGIN: @@ -372,6 +375,10 @@ void GPU::ExecuteOp(u32 op, u32 diff) if (data & GE_VTYPE_THROUGH) { glDisable(GL_CULL_FACE); } + else { + // this might get spammy + glEnDis(GL_CULL_FACE, gstate.cullfaceEnable & 1); + } // This sets through-mode or not, as well. break; @@ -379,18 +386,9 @@ void GPU::ExecuteOp(u32 op, u32 diff) // offsetAddr = data<<8; break; - case GE_CMD_FINISH: DEBUG_LOG(G3D,"DL CMD FINISH"); - // Trigger the finish callbacks - { - // Apparently, these callbacks should be done in a special interrupt way. - - //for (size_t i = 0; i < finishCallbacks.size(); i++) - //{ - // __KernelNotifyCallback(-1, finishCallbacks[i].first, 0); - //} - } + __TriggerInterruptWithArg(PSP_GE_INTR, PSP_GE_SUBINTR_FINISH, 0); break; case GE_CMD_END: @@ -430,79 +428,83 @@ void GPU::ExecuteOp(u32 op, u32 diff) break; case GE_CMD_CLIPENABLE: + DEBUG_LOG(G3D, "DL Clip Enable: %i (ignoring)", data); //we always clip, this is opengl break; case GE_CMD_CULLFACEENABLE: + DEBUG_LOG(G3D, "DL CullFace Enable: %i (ignoring)", data); glEnDis(GL_CULL_FACE, data&1); break; case GE_CMD_TEXTUREMAPENABLE: - DEBUG_LOG(G3D, "Texture map enable: %i", data); + DEBUG_LOG(G3D, "DL Texture map enable: %i", data); glEnDis(GL_TEXTURE_2D, data&1); break; case GE_CMD_LIGHTINGENABLE: - DEBUG_LOG(G3D, "Lighting enable: %i", data); + DEBUG_LOG(G3D, "DL Lighting enable: %i", data); data += 1; //We don't use OpenGL lighting break; case GE_CMD_FOGENABLE: - DEBUG_LOG(G3D, "Fog Enable: %i", gstate.fogEnable); + DEBUG_LOG(G3D, "DL Fog Enable: %i", gstate.fogEnable); break; case GE_CMD_DITHERENABLE: - DEBUG_LOG(G3D, "Dither Enable: %i", gstate.ditherEnable); + DEBUG_LOG(G3D, "DL Dither Enable: %i", gstate.ditherEnable); break; case GE_CMD_OFFSETX: - DEBUG_LOG(G3D, "Offset X: %i", gstate.offsetx); + DEBUG_LOG(G3D, "DL Offset X: %i", gstate.offsetx); break; case GE_CMD_OFFSETY: - DEBUG_LOG(G3D, "Offset Y: %i", gstate.offsety); + DEBUG_LOG(G3D, "DL Offset Y: %i", gstate.offsety); break; case GE_CMD_TEXSCALEU: gstate.uScale = getFloat24(data); - DEBUG_LOG(G3D, "Texture U Scale: %f", gstate.uScale); + DEBUG_LOG(G3D, "DL Texture U Scale: %f", gstate.uScale); break; case GE_CMD_TEXSCALEV: gstate.vScale = getFloat24(data); - DEBUG_LOG(G3D, "Texture V Scale: %f", gstate.vScale); + DEBUG_LOG(G3D, "DL Texture V Scale: %f", gstate.vScale); break; case GE_CMD_TEXOFFSETU: gstate.uOff = getFloat24(data); - DEBUG_LOG(G3D, "Texture U Offset: %f", gstate.uOff); + DEBUG_LOG(G3D, "DL Texture U Offset: %f", gstate.uOff); break; case GE_CMD_TEXOFFSETV: gstate.vOff = getFloat24(data); - DEBUG_LOG(G3D, "Texture V Offset: %f", gstate.vOff); + DEBUG_LOG(G3D, "DL Texture V Offset: %f", gstate.vOff); break; case GE_CMD_SCISSOR1: { int x1 = data & 0x3ff; int y1 = data >> 10; - DEBUG_LOG(G3D, "Scissor TL: %i, %i", x1,y1); + DEBUG_LOG(G3D, "DL Scissor TL: %i, %i", x1,y1); } break; case GE_CMD_SCISSOR2: { int x2 = data & 0x3ff; int y2 = data >> 10; - DEBUG_LOG(G3D, "Scissor BR: %i, %i", x2, y2); + DEBUG_LOG(G3D, "DL Scissor BR: %i, %i", x2, y2); } break; case GE_CMD_MINZ: + DEBUG_LOG(G3D, "DL MinZ: %i", data); break; case GE_CMD_MAXZ: + DEBUG_LOG(G3D, "DL MaxZ: %i", data); break; case GE_CMD_FRAMEBUFPTR: @@ -523,7 +525,7 @@ void GPU::ExecuteOp(u32 op, u32 diff) break; case GE_CMD_TEXADDR0: - gstate.textureChanged=true; + gstate.textureChanged = true; case GE_CMD_TEXADDR1: case GE_CMD_TEXADDR2: case GE_CMD_TEXADDR3: @@ -535,7 +537,7 @@ void GPU::ExecuteOp(u32 op, u32 diff) break; case GE_CMD_TEXBUFWIDTH0: - gstate.textureChanged=true; + gstate.textureChanged = true; case GE_CMD_TEXBUFWIDTH1: case GE_CMD_TEXBUFWIDTH2: case GE_CMD_TEXBUFWIDTH3: @@ -551,7 +553,7 @@ void GPU::ExecuteOp(u32 op, u32 diff) break; case GE_CMD_CLUTADDRUPPER: - DEBUG_LOG(G3D,"CLUT addr: %08x", ((gstate.clutaddrupper & 0xFF0000)<<8) | (gstate.clutaddr & 0xFFFFFF)); + DEBUG_LOG(G3D,"DL CLUT addr: %08x", ((gstate.clutaddrupper & 0xFF0000)<<8) | (gstate.clutaddr & 0xFFFFFF)); break; case GE_CMD_LOADCLUT: @@ -564,11 +566,11 @@ void GPU::ExecuteOp(u32 op, u32 diff) int numColors = 16 * (data&0x3F); memcpy(&gstate.paletteMem[0], clut, numColors * 2); } - DEBUG_LOG(G3D,"Clut load: %i palettes", data); + DEBUG_LOG(G3D,"DL Clut load: %i palettes", data); } else { - DEBUG_LOG(G3D,"Empty Clut load"); + DEBUG_LOG(G3D,"DL Empty Clut load"); } // Should hash and invalidate all paletted textures on use } @@ -597,7 +599,7 @@ void GPU::ExecuteOp(u32 op, u32 diff) { u32 x = (data & 1023)+1; u32 y = ((data>>10) & 1023)+1; - DEBUG_LOG(G3D,"Block Transfer Src Rect TL: %i, %i", x, y); + DEBUG_LOG(G3D, "DL Block Transfer Src Rect TL: %i, %i", x, y); break; } @@ -605,7 +607,7 @@ void GPU::ExecuteOp(u32 op, u32 diff) { u32 x = (data & 1023)+1; u32 y = ((data>>10) & 1023)+1; - DEBUG_LOG(G3D,"Block Transfer Dest Rect TL: %i, %i", x, y); + DEBUG_LOG(G3D, "DL Block Transfer Dest Rect TL: %i, %i", x, y); break; } @@ -613,13 +615,16 @@ void GPU::ExecuteOp(u32 op, u32 diff) { u32 w = (data & 1023)+1; u32 h = ((data>>10) & 1023)+1; - DEBUG_LOG(G3D,"Block Transfer Rect Size: %i x %i", w, h); + DEBUG_LOG(G3D, "DL Block Transfer Rect Size: %i x %i", w, h); break; } case GE_CMD_TRANSFERSTART: { - DEBUG_LOG(G3D,"Texture Transfer Start: PixFormat %i", data); + DEBUG_LOG(G3D, "DL Texture Transfer Start: PixFormat %i", data); + // TODO: Here we should check if the transfer overlaps a framebuffer or any textures, + // and take appropriate action. If not, this should just be a block transfer within + // GPU memory which could be implemented by a copy loop. break; } @@ -738,9 +743,9 @@ void GPU::ExecuteOp(u32 op, u32 diff) case GE_CMD_LDC0:case GE_CMD_LDC1:case GE_CMD_LDC2:case GE_CMD_LDC3: case GE_CMD_LSC0:case GE_CMD_LSC1:case GE_CMD_LSC2:case GE_CMD_LSC3: { - float r = (float)(data>>16)/255.0f; + float r = (float)(data & 0xff)/255.0f; float g = (float)((data>>8) & 0xff)/255.0f; - float b = (float)(data & 0xff)/255.0f; + float b = (float)(data>>16)/255.0f; int l = (cmd - GE_CMD_LAC0) / 3; int t = (cmd - GE_CMD_LAC0) % 3; @@ -766,7 +771,8 @@ void GPU::ExecuteOp(u32 op, u32 diff) break; case GE_CMD_CULL: DEBUG_LOG(G3D,"DL cull: %06x", data); - glCullFace(data ? GL_BACK : GL_FRONT); + glCullFace(data & 1 ? GL_FRONT : GL_BACK); + //glCullFace(data & 1 ? GL_BACK : GL_FRONT); break; case GE_CMD_LMODE: @@ -776,6 +782,7 @@ void GPU::ExecuteOp(u32 op, u32 diff) case GE_CMD_PATCHDIVISION: gstate.patch_div_s = data & 0xFF; gstate.patch_div_t = (data >> 8) & 0xFF; + DEBUG_LOG(G3D, "DL Patch subdivision: %i x %i", gstate.patch_div_s, gstate.patch_div_t); break; case GE_CMD_MATERIALUPDATE: @@ -896,7 +903,12 @@ void GPU::ExecuteOp(u32 op, u32 diff) case GE_CMD_MORPHWEIGHT5: case GE_CMD_MORPHWEIGHT6: case GE_CMD_MORPHWEIGHT7: - gstate.morphWeights[cmd-GE_CMD_MORPHWEIGHT0] = getFloat24(data); + { + int index = cmd - GE_CMD_MORPHWEIGHT0; + float weight = getFloat24(data); + DEBUG_LOG(G3D,"DL MorphWeight %i = %f", index, weight); + gstate.morphWeights[index] = weight; + } break; case GE_CMD_DITH0: @@ -965,7 +977,7 @@ void GPU::ExecuteOp(u32 op, u32 diff) } } -bool GPU::InterpretList() +bool GLES_GPU::InterpretList() { // Reset stackptr for safety stackptr = 0; @@ -974,6 +986,10 @@ bool GPU::InterpretList() finished = false; while (!finished) { + if (!Memory::IsValidAddress(dcontext.pc)) { + ERROR_LOG(G3D, "DL PC = %08x WTF!!!!", dcontext.pc); + return true; + } if (dcontext.pc == dcontext.stallAddr) return false; diff --git a/GPU/GLES/DisplayListInterpreter.h b/GPU/GLES/DisplayListInterpreter.h index bc01e1095b..179655e519 100644 --- a/GPU/GLES/DisplayListInterpreter.h +++ b/GPU/GLES/DisplayListInterpreter.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -17,15 +17,18 @@ #pragma once -#include "../../Globals.h" +#include "../GPUInterface.h" class ShaderManager; -class GPU +class GLES_GPU : public GPUInterface { public: - static u32 EnqueueList(u32 listpc, u32 stall); - static void UpdateStall(int listid, u32 newstall); - static void ExecuteOp(u32 op, u32 diff); - static bool InterpretList(); + virtual u32 EnqueueList(u32 listpc, u32 stall); + virtual void UpdateStall(int listid, u32 newstall); + virtual void ExecuteOp(u32 op, u32 diff); + virtual bool InterpretList(); + virtual void DrawSync(int mode); +private: + bool ProcessDLQueue(); }; diff --git a/GPU/GLES/FragmentShaderGenerator.cpp b/GPU/GLES/FragmentShaderGenerator.cpp index ae24e3e246..8b1e0b2575 100644 --- a/GPU/GLES/FragmentShaderGenerator.cpp +++ b/GPU/GLES/FragmentShaderGenerator.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -15,7 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #define GLSL_ES_1_0 #else #define GLSL_1_3 @@ -73,13 +73,15 @@ char *GenerateFragmentShader() WRITE(p, "#version 130\n"); #endif + int lmode = gstate.lmode & 1; + if (gstate.textureMapEnable & 1) WRITE(p, "uniform sampler2D tex;\n"); if (gstate.alphaTestEnable & 1) WRITE(p, "uniform vec4 u_alpharef;\n"); WRITE(p, "uniform vec4 u_texenv;\n"); WRITE(p, "varying vec4 v_color0;\n"); - if (gstate.lmode & 1) + if (lmode) WRITE(p, "varying vec4 v_color1;\n"); WRITE(p, "varying vec2 v_texcoord;\n"); @@ -92,9 +94,12 @@ char *GenerateFragmentShader() else { const char *secondary = ""; - if (gstate.lmode & 1) { - WRITE(p, " vec4 s = vec4(0.0, 0.0, 0.0, 0.0);\n"); // Secondary color, TODO + if (lmode) { + WRITE(p, "vec4 s = v_color1;"); secondary = " + s"; + } else { + WRITE(p, " vec4 s = vec4(0.0, 0.0, 0.0, 0.0);\n"); // Secondary color, TODO + secondary = ""; } if (gstate.textureMapEnable & 1) { @@ -103,8 +108,8 @@ char *GenerateFragmentShader() WRITE(p, " vec4 p = clamp(v_color0, 0.0, 1.0);\n"); } else { // No texture mapping - WRITE(p, " vec4 t = v_color0;\n"); //, secondary); - WRITE(p, " vec4 p = t;\n"); // , secondary); + WRITE(p, " vec4 t = vec4(1.0, 1.0, 1.0, 1.0);\n"); //, secondary); + WRITE(p, " vec4 p = clamp(v_color0, 0.0, 1.0);\n"); // , secondary); } // Color doubling diff --git a/GPU/GLES/FragmentShaderGenerator.h b/GPU/GLES/FragmentShaderGenerator.h index 6b6b0dd093..75b8b2e17e 100644 --- a/GPU/GLES/FragmentShaderGenerator.h +++ b/GPU/GLES/FragmentShaderGenerator.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/GPU/GLES/Framebuffer.cpp b/GPU/GLES/Framebuffer.cpp index 23ffa55c42..d3477958a1 100644 --- a/GPU/GLES/Framebuffer.cpp +++ b/GPU/GLES/Framebuffer.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -15,7 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include #include #else @@ -72,7 +72,7 @@ const char basic_vs[] = void DisplayDrawer_Init() { -#ifndef ANDROID +#if !defined(ANDROID) && !defined(BLACKBERRY) // Old OpenGL stuff that probably has no effect glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); //GL_FILL); diff --git a/GPU/GLES/Framebuffer.h b/GPU/GLES/Framebuffer.h index d8b894262e..68fb487fee 100644 --- a/GPU/GLES/Framebuffer.h +++ b/GPU/GLES/Framebuffer.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/GPU/GLES/ShaderManager.cpp b/GPU/GLES/ShaderManager.cpp index 72ba973ba7..ec0e375ec9 100644 --- a/GPU/GLES/ShaderManager.cpp +++ b/GPU/GLES/ShaderManager.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -15,7 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include #include #else diff --git a/GPU/GLES/ShaderManager.h b/GPU/GLES/ShaderManager.h index 475efb8a4e..d4709ee46b 100644 --- a/GPU/GLES/ShaderManager.h +++ b/GPU/GLES/ShaderManager.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/GPU/GLES/TextureCache.cpp b/GPU/GLES/TextureCache.cpp index 1d0a32cf74..6cc852b6ce 100644 --- a/GPU/GLES/TextureCache.cpp +++ b/GPU/GLES/TextureCache.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -15,7 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include #include #else @@ -41,6 +41,10 @@ struct TexCacheEntry u32 hash; u32 frameCounter; u32 numMips; + u32 format; + u32 clutaddr; + u32 clutformat; + u32 cluthash; int dim; GLuint texture; }; @@ -48,7 +52,14 @@ struct TexCacheEntry typedef std::map TexCache; static TexCache cache; -u8 *tempArea; +u32 tmpTexBuf32[1024 * 1024]; +u16 tmpTexBuf16[1024 * 1024]; + +u16 tmpTexBufRearrange[1024 * 1024]; + + +u32 clutBuf32[4096]; +u16 clutBuf16[4096]; void TextureCache_Clear(bool delete_them) { @@ -66,54 +77,290 @@ void TextureCache_Clear(bool delete_them) } } -u32 PaletteLoad(int index) +u32 GetClutAddr(u32 clutEntrySize) { - int pf = gstate.clutformat & 3; - int shift = (gstate.clutformat >> 2) & 31; - int mask = (gstate.clutformat >> 8) & 255; - int start = ((gstate.clutformat >> 16) & 31) * 16; - - if (pf<3) - { - //16-bit - u16 *p = (u16*)gstate.paletteMem; - u16 col = p[((start+index)>>shift) & mask]; - int r,g,b,a; - - // TODO: properly expand the lower bits. - switch (pf) - { - case 0: - r = (col&0x1f)*8; - g = ((col>>5)&0x3f)*4; - b = ((col>>11)&0x1f)*8; - a = 255; - break; - case 1: - r = (col&0x1f)*8; - g = ((col>>5)&0x1f)*8; - b = ((col>>10)&0x1f)*8; - a = (col>>15)*255; - break; - case 2: - r = (col&0xf)*16; - g = ((col>>4)&0xf)*16; - b = ((col>>8)&0xf)*16; - a = ((col>>12)&0xF)*16; - break; - } - - // We now use OpenGL ES 2.0 style colors. - return (a << 24) | (b<<16) | (g<<8) | (r<<0); - } - else - { - u32 *p = (u32*)gstate.paletteMem; - u32 col = p[((start + index) >> shift) & mask]; - return col; - } + return ((gstate.clutaddr & 0xFFFFFF) | ((gstate.clutaddrupper << 8) & 0x0F000000)) + ((gstate.clutformat >> 16) & 0x1f) * clutEntrySize; } +u32 GetClutIndex(u32 index) +{ + return ((((gstate.clutformat >> 16) & 0x1f) + index) >> ((gstate.clutformat >> 2) & 0x1f)) & ((gstate.clutformat >> 8) & 0xff); +} + +u16 *ReadClut16() +{ + u32 clutNumEntries = (gstate.loadclut & 0x3f) * 16; + u32 clutAddr = GetClutAddr(2); + for (u32 i = ((gstate.clutformat >> 16) & 0x1f); i < clutNumEntries; i++) + clutBuf16[i] = Memory::Read_U16(clutAddr + i * 2); + return clutBuf16; +} + +u32 *ReadClut32() +{ + u32 clutNumEntries = (gstate.loadclut & 0x3f) * 8; + u32 clutAddr = GetClutAddr(4); + for (u32 i = ((gstate.clutformat >> 16) & 0x1f); i < clutNumEntries; i++) + clutBuf32[i] = Memory::Read_U32(clutAddr + i * 4); + return clutBuf32; +} + +void *UnswizzleFromMem(u32 texaddr, u32 bytesPerPixel, u32 level) +{ + u32 addr = texaddr; + u32 rowWidth = (bytesPerPixel > 0) ? ((gstate.texbufwidth[level] & 0x3FF) * bytesPerPixel) : ((gstate.texbufwidth[level] & 0x3FF) / 2); + u32 pitch = rowWidth / 4; + u32 bxc = rowWidth / 16; + u32 byc = ((1 << ((gstate.texsize[level] >> 8) & 0xf)) + 7) / 8; + if (byc == 0) + byc = 1; + + u32 ydest = 0; + + u32 by; + for (by = 0; by < byc; by++) + { + if (rowWidth >= 16) + { + u32 xdest = ydest; + u32 bx; + for (bx = 0; bx < bxc; bx++) + { + u32 dest = xdest; + u8 n; + for (n = 0; n < 8; n++) + { + u32 k; + for (k = 0; k < 4; k++) { + tmpTexBuf32[dest + k] = Memory::Read_U32(addr); + addr += 4; + } + dest += pitch; + } + xdest += 4; + } + ydest += (rowWidth * 8) / 4; + } + else if (rowWidth == 8) + { + u32 n; + for (n = 0; n < 8; n++, ydest += 2) + { + tmpTexBuf32[ydest + 0] = Memory::Read_U32(addr + 0); + tmpTexBuf32[ydest + 1] = Memory::Read_U32(addr + 4); + addr += 16; // skip two u32 + } + } + else if (rowWidth == 4) + { + u32 n; + for (n = 0; n < 8; n++, ydest++) { + tmpTexBuf32[ydest] = Memory::Read_U32(addr); + addr += 16; + } + } + else if (rowWidth == 2) + { + u32 n; + for (n = 0; n < 4; n++, ydest++) + { + u16 n1 = Memory::Read_U32(addr + 0) & 0xffff; + u16 n2 = Memory::Read_U32(addr + 16) & 0xffff; + tmpTexBuf32[ydest] = (u32)n1 | ((u32)n2 << 16); + addr += 32; + } + } + else if (rowWidth == 1) + { + u32 n; + for (n = 0; n < 2; n++, ydest++) + { + u8 n1 = Memory::Read_U32(addr + 0) & 0xf; + u8 n2 = Memory::Read_U32(addr + 16) & 0xf; + u8 n3 = Memory::Read_U32(addr + 32) & 0xf; + u8 n4 = Memory::Read_U32(addr + 48) & 0xf; + + tmpTexBuf32[ydest] = (u32)n1 | ((u32)n2 << 8) | ((u32)n3 << 16) | ((u32)n4 << 24); + } + } + } + return tmpTexBuf32; +} + +void *readIndexedTex(u32 level, u32 texaddr, u32 bytesPerIndex) +{ + u32 length = (gstate.texbufwidth[level] & 0x3FF) * (1 << ((gstate.texsize[level] >> 8) & 0xf)); + void *buf = NULL; + + switch ((gstate.clutformat & 3)) + { + case GE_CMODE_16BIT_BGR5650: + case GE_CMODE_16BIT_ABGR5551: + case GE_CMODE_16BIT_ABGR4444: + { + u16 *clut = ReadClut16(); + if (!(gstate.texmode & 1)) + { + u32 i; + switch (bytesPerIndex) + { + case 1: + for (i = 0; i < length; i++) { + u8 index = Memory::Read_U8(texaddr + i); + tmpTexBuf16[i] = clut[GetClutIndex(index)]; + } + break; + + case 2: + for (i = 0; i < length; i++) { + u16 index = Memory::Read_U16(texaddr + i * 2); + tmpTexBuf16[i] = clut[GetClutIndex(index)]; + } + break; + + case 4: + for (i = 0; i < length; i++) { + u32 index = Memory::Read_U32(texaddr + i * 4); + tmpTexBuf16[i] = clut[GetClutIndex(index)]; + } + break; + } + } + else + { + u32 i, j; + UnswizzleFromMem(texaddr, bytesPerIndex, level); + switch (bytesPerIndex) + { + case 1: + for (i = 0, j = 0; i < length; i += 4, j++) + { + u32 n = tmpTexBuf32[j]; + u32 k; + for (k = 0; k < 4; k++) { + u8 index = (n >> (k * 4)) & 0xff; + tmpTexBuf16[i + k] = clut[GetClutIndex(index)]; + } + } + break; + + case 2: + for (i = 0, j = 0; i < length; i += 2, j++) + { + u32 n = tmpTexBuf32[j]; + tmpTexBuf16[i + 0] = clut[GetClutIndex(n & 0xffff)]; + tmpTexBuf16[i + 1] = clut[GetClutIndex(n >> 16)]; + } + break; + + case 4: + for (i = 0; i < length; i++) { + u32 n = tmpTexBuf32[i]; + tmpTexBuf16[i] = clut[GetClutIndex(n)]; + } + break; + } + } + buf = tmpTexBuf16; + } + break; + + case GE_CMODE_32BIT_ABGR8888: + { + u32 *clut = ReadClut32(); + if (!(gstate.texmode & 1)) + { + u32 i; + switch (bytesPerIndex) + { + case 1: + for (i = 0; i < length; i++) { + u8 index = Memory::Read_U8(texaddr + i); + tmpTexBuf32[i] = clut[GetClutIndex(index)]; + } + break; + + case 2: + for (i = 0; i < length; i++) { + u16 index = Memory::Read_U16(texaddr + i * 2); + tmpTexBuf32[i] = clut[GetClutIndex(index)]; + } + break; + + case 4: + for (i = 0; i < length; i++) { + u32 index = Memory::Read_U32(texaddr + i * 4); + tmpTexBuf32[i] = clut[GetClutIndex(index)]; + } + break; + } + } + else + { + u32 j; + s32 i; + UnswizzleFromMem(texaddr, bytesPerIndex, level); + switch (bytesPerIndex) + { + case 1: + for (i = length - 4, j = (length / 4) - 1; i >= 0; i -= 4, j--) + { + u32 n = tmpTexBuf32[j]; + u32 k; + for (k = 0; k < 4; k++) { + u32 index = (n >> (k * 8)) & 0xff; + tmpTexBuf32[i + k] = clut[GetClutIndex(index)]; + } + } + break; + + case 2: + for (i = length - 2, j = (length / 2) - 1; i >= 0; i -= 2, j--) + { + u32 n = tmpTexBuf32[j]; + tmpTexBuf32[i + 0] = clut[GetClutIndex(n & 0xffff)]; + tmpTexBuf32[i + 1] = clut[GetClutIndex(n >> 16)]; + } + break; + + case 4: + for (i = 0; (u32)i < length; i++) { + u32 n = tmpTexBuf32[i]; + tmpTexBuf32[i] = clut[GetClutIndex(n)]; + } + break; + } + } + buf = tmpTexBuf32; + } + break; + + default: + ERROR_LOG(G3D, "Unhandled clut texture mode %d!!!", (gstate.clutformat & 3)); + break; + } + + return buf; +} + +GLenum getClutDestFormat(GEPaletteFormat format) +{ + switch (format) + { + case GE_CMODE_16BIT_ABGR4444: + return GL_UNSIGNED_SHORT_4_4_4_4; + case GE_CMODE_16BIT_ABGR5551: + return GL_UNSIGNED_SHORT_5_5_5_1; + case GE_CMODE_16BIT_BGR5650: + return GL_UNSIGNED_SHORT_5_6_5; + case GE_CMODE_32BIT_ABGR8888: + return GL_UNSIGNED_BYTE; + } + return 0; +} + +u32 texByteAlignMap[] = {2, 2, 2, 4}; + // This should not have to be done per texture! OpenGL is silly yo // TODO: Dirty-check this against the current texture. void UpdateSamplingParams() @@ -133,7 +380,7 @@ void UpdateSamplingParams() // Convert from PSP bit order to GLES bit order u16 convert565(u16 c) { - return (c >> 11) | (c & 0x07E0) | (c << 11); + return (c >> 11) | (c & 0x07E0) | (c << 11); } // Convert from PSP bit order to GLES bit order @@ -146,7 +393,6 @@ u16 convert5551(u16 c) { return ((c & 0x8000) >> 15) | (c << 1); } - struct DXT1Block { u8 lines[4]; @@ -154,18 +400,6 @@ struct DXT1Block u16 color2; }; -inline u8 Convert5To8(u8 v) -{ - // Swizzle bits: 00012345 -> 12345123 - return (v << 3) | (v >> 2); -} - -inline u8 Convert6To8(u8 v) -{ - // Swizzle bits: 00123456 -> 12345612 - return (v << 2) | (v >> 4); -} - inline u32 makecol(int r, int g, int b, int a) { return (a << 24)|(r << 16)|(g << 8)|b; @@ -192,7 +426,7 @@ void decodeDXT1Block(u32 *dst, const DXT1Block *src, int pitch) int green3 = ((green2 - green1) >> 1) - ((green2 - green1) >> 3); int red3 = ((red2 - red1) >> 1) - ((red2 - red1) >> 3); colors[2] = makecol(red1 + red3, green1 + green3, blue1 + blue3, 255); - colors[3] = makecol(red2 - red3, green2 - green3, blue2 - blue3, 255); + colors[3] = makecol(red2 - red3, green2 - green3, blue2 - blue3, 255); } else { @@ -203,7 +437,7 @@ void decodeDXT1Block(u32 *dst, const DXT1Block *src, int pitch) } for (int y = 0; y < 4; y++) - { + { int val = src->lines[y]; for (int x = 0; x < 4; x++) { @@ -214,16 +448,58 @@ void decodeDXT1Block(u32 *dst, const DXT1Block *src, int pitch) } } +void convertColors(u8 *finalBuf, GLuint dstFmt, int numPixels) +{ + switch (dstFmt) { + case GL_UNSIGNED_SHORT_4_4_4_4: + { + u16 *p = (u16 *)finalBuf; + for (int i = 0; i < numPixels; i++) { + u16 c = p[i]; + p[i] = (c >> 12) | ((c >> 4) & 0xF0) | ((c << 4) & 0xF00) | (c << 12); + } + } + break; + case GL_UNSIGNED_SHORT_5_5_5_1: + { + u16 *p = (u16 *)finalBuf; + for (int i = 0; i < numPixels; i++) { + u16 c = p[i]; + p[i] = ((c & 0x8000) >> 15) | ((c >> 9) & 0x3E) | ((c << 1) & 0x7C0) | ((c << 11) & 0xF800); + } + } + break; + case GL_UNSIGNED_SHORT_5_6_5: + { + u16 *p = (u16 *)finalBuf; + for (int i = 0; i < numPixels; i++) { + u16 c = p[i]; + p[i] = (c >> 11) | (c & 0x07E0) | (c << 11); + } + } + break; + default: + { + //u32 *p = (u32 *)finalBuf; + //for (int i = 0; i < numPixels; i++) { + // p[i] = _byteswap_ulong(p[i]); + //} + } + break; + } +} + void PSPSetTexture() { - if (!tempArea) - tempArea = new u8[512*512*4*4]; // PSP maximum texture size - u32 texaddr = (gstate.texaddr[0] & 0xFFFFF0) | ((gstate.texbufwidth[0]<<8) & 0xFF000000); texaddr &= 0xFFFFFFF; if (!texaddr) return; + u8 level = 0; + int format = gstate.texformat & 0xF; + int clutformat = gstate.clutformat & 3; + DEBUG_LOG(G3D,"Texture at %08x",texaddr); u8 *texptr = Memory::GetPointer(texaddr); @@ -234,8 +510,20 @@ void PSPSetTexture() TexCacheEntry &entry = iter->second; int dim = gstate.texsize[0] & 0xF0F; + bool match = true; - if (dim == entry.dim && entry.hash == *(u32*)texptr) + //TODO: Check more texture parameters, compute real texture hash + if(dim != entry.dim || entry.hash != *(u32*)texptr || entry.format != format) + match = false; + + //TODO: Check more clut parameters, compute clut hash + if(match && (format >= GE_TFMT_CLUT4 && format <= GE_TFMT_CLUT32) && + (entry.clutformat != clutformat || + entry.clutaddr != GetClutAddr(clutformat == GE_CMODE_32BIT_ABGR8888 ? 4 : 2) || + entry.cluthash != Memory::Read_U32(entry.clutaddr))) + match = false; + + if (match) { //got one! glBindTexture(GL_TEXTURE_2D, entry.texture); @@ -266,21 +554,37 @@ void PSPSetTexture() entry.addr = texaddr; entry.hash = *(u32*)texptr; + entry.format = format; + + if(format >= GE_TFMT_CLUT4 && format <= GE_TFMT_CLUT32) + { + entry.clutformat = clutformat; + entry.clutaddr = GetClutAddr(clutformat == GE_CMODE_32BIT_ABGR8888 ? 4 : 2); + entry.cluthash = Memory::Read_U32(entry.clutaddr); + } + else + { + entry.clutaddr = 0; + } + glGenTextures(1, &entry.texture); NOTICE_LOG(G3D, "Creating texture %i", entry.texture); glBindTexture(GL_TEXTURE_2D, entry.texture); - int bufw = gstate.texbufwidth[0] & 0x3ff; + u32 bufw = gstate.texbufwidth[0] & 0x3ff; entry.dim = gstate.texsize[0] & 0xF0F; - int w = 1 << (gstate.texsize[0] & 0xf); - int h = 1 << ((gstate.texsize[0]>>8) & 0xf); + u32 w = 1 << (gstate.texsize[0] & 0xf); + u32 h = 1 << ((gstate.texsize[0]>>8) & 0xf); gstate.curTextureHeight=h; gstate.curTextureWidth=w; - int format = gstate.texformat & 0xF; + GLenum dstFmt = 0; + u32 texByteAlign = 1; + + void *finalBuf = NULL; DEBUG_LOG(G3D,"Texture Width %04x Height %04x Bufw %d Fmt %d", w, h, bufw, format); @@ -288,202 +592,213 @@ void PSPSetTexture() switch (format) { + case GE_TFMT_CLUT4: + dstFmt = getClutDestFormat((GEPaletteFormat)(gstate.clutformat & 3)); + switch (clutformat) + { + case GE_CMODE_16BIT_BGR5650: + case GE_CMODE_16BIT_ABGR5551: + case GE_CMODE_16BIT_ABGR4444: + { + u16 *clut = ReadClut16(); + u32 clutSharingOff = 0;//gstate.mipmapShareClut ? 0 : level * 16; + texByteAlign = 2; + if (!(gstate.texmode & 1)) + { + u32 i; + u32 addr = texaddr; + for (i = 0; i < bufw * h; i += 2) + { + u32 index = Memory::Read_U32(addr); + tmpTexBuf16[i + 0] = clut[GetClutIndex((index >> 0) & 0xf) + clutSharingOff]; + tmpTexBuf16[i + 1] = clut[GetClutIndex((index >> 4) & 0xf) + clutSharingOff]; + addr++; + } + } + else + { + u32 i, j; + UnswizzleFromMem(texaddr, 0, level); + for (i = 0, j = 0; i < bufw * h; i += 8, j++) + { + u32 n = tmpTexBuf32[j]; + u32 k, index; + for (k = 0; k < 8; k++) { + index = (n >> (k * 4)) & 0xf; + tmpTexBuf16[i + k] = clut[GetClutIndex(index) + clutSharingOff]; + } + } + } + finalBuf = tmpTexBuf16; + } + break; + + case GE_CMODE_32BIT_ABGR8888: + { + u32 *clut = ReadClut32(); + u32 clutSharingOff = 0;//gstate.mipmapShareClut ? 0 : level * 16; + if (!(gstate.texmode & 1)) + { + u32 i; + u32 addr = texaddr; + for (i = 0; i < bufw * h; i += 2) + { + u32 index = Memory::Read_U32(addr); + tmpTexBuf32[i + 0] = clut[GetClutIndex((index >> 0) & 0xf) + clutSharingOff]; + tmpTexBuf32[i + 1] = clut[GetClutIndex((index >> 4) & 0xf) + clutSharingOff]; + addr++; + } + } + else + { + s32 i; + u32 j; + u32 pixels = bufw * h; + UnswizzleFromMem(texaddr, 0, level); + for (i = pixels - 8, j = (pixels / 8) - 1; i >= 0; i -= 8, j--) + { + u32 n = tmpTexBuf32[j]; + u32 k, index; + for (k = 0; k < 8; k++) { + index = (n >> (k * 4)) & 0xf; + tmpTexBuf32[i + k] = clut[GetClutIndex(index) + clutSharingOff]; + } + } + } + finalBuf = tmpTexBuf32; + } + break; + + default: + ERROR_LOG(G3D, "Unknown CLUT4 texture mode %d", (gstate.clutformat & 3)); + return; + } + break; + + case GE_TFMT_CLUT8: + finalBuf = readIndexedTex(level, texaddr, 1); + dstFmt = getClutDestFormat((GEPaletteFormat)(gstate.clutformat & 3)); + texByteAlign = texByteAlignMap[(gstate.clutformat & 3)]; + break; + + case GE_TFMT_CLUT16: + finalBuf = readIndexedTex(level, texaddr, 2); + dstFmt = getClutDestFormat((GEPaletteFormat)(gstate.clutformat & 3)); + texByteAlign = texByteAlignMap[(gstate.clutformat & 3)]; + break; + + case GE_TFMT_CLUT32: + finalBuf = readIndexedTex(level, texaddr, 4); + dstFmt = getClutDestFormat((GEPaletteFormat)(gstate.clutformat & 3)); + texByteAlign = texByteAlignMap[(gstate.clutformat & 3)]; + break; + case GE_TFMT_4444: case GE_TFMT_5551: case GE_TFMT_5650: + if (format == GE_TFMT_4444) + dstFmt = GL_UNSIGNED_SHORT_4_4_4_4; + else if (format == GE_TFMT_5551) + dstFmt = GL_UNSIGNED_SHORT_5_5_5_1; + else if (format == GE_TFMT_5650) + dstFmt = GL_UNSIGNED_SHORT_5_6_5; + texByteAlign = 2; + + if (!(gstate.texmode & 1)) { - u16 *dst = (u16*)tempArea; - u16 *src = (u16*)texptr; - - int fmt = GL_UNSIGNED_SHORT_5_6_5; - int internal_format = GL_RGBA; - u16 (*convFunc)(u16); - switch (format) - { - case GE_TFMT_4444: fmt = GL_UNSIGNED_SHORT_4_4_4_4; convFunc = &convert4444; break; - case GE_TFMT_5551: fmt = GL_UNSIGNED_SHORT_5_5_5_1; convFunc = &convert5551; break; - case GE_TFMT_5650: fmt = GL_UNSIGNED_SHORT_5_6_5; convFunc = &convert565; internal_format = GL_RGB; break; - } - - if (gstate.texmode & 1) //Swizzled! - { - for (int y=0; y>=4; else idx&=0xF; - dst[(y*8+yy)*w + x*32 + xx] = PaletteLoad(idx); - } - } - } - } - } - else - { - for (int y=0; y>= 4; else idx &= 0xF; - dst[x] = PaletteLoad(idx); - if (x&1) - src++; - } - src -= w/2; - src += bufw/2; - dst += w; - } - } - int fmt = GL_UNSIGNED_BYTE; - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, fmt, (GLvoid*)tempArea); - break; - } - - case GE_TFMT_CLUT8: - { - u32 *dst = (u32*)tempArea; - u8 *src = (u8*)texptr; - if (gstate.texmode & 1) //Swizzled! - { - for (int y=0; y w ? bufw : w) * h; + u32 i; + for (i = 0; i < len; i++) + tmpTexBuf16[i] = Memory::Read_U16(texaddr + i * 2); + finalBuf = tmpTexBuf16; } + else + finalBuf = UnswizzleFromMem(texaddr, 2, level); + break; case GE_TFMT_8888: + dstFmt = GL_UNSIGNED_BYTE; + if (!(gstate.texmode & 1)) { - u32 *dst = (u32*)tempArea; - u32 *src = (u32*)texptr; - if (gstate.texmode & 1) //Swizzled! - { - for (int y=0; y bufw) { + write = (u8 *)tmpTexBufRearrange; + finalBuf = tmpTexBufRearrange; + } else { + write = (u8 *)finalBuf; + } + for (int y = 0; y < h; y++) { + memmove(write, read, outRowBytes); + read += inRowBytes; + write += outRowBytes; + } + } + + // Can restore these and remove the above fixup on some platforms. + //glPixelStorei(GL_UNPACK_ROW_LENGTH, bufw); + glPixelStorei(GL_UNPACK_ALIGNMENT, texByteAlign); + //glPixelStorei(GL_PACK_ROW_LENGTH, bufw); + glPixelStorei(GL_PACK_ALIGNMENT, texByteAlign); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, dstFmt, finalBuf); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); @@ -492,5 +807,10 @@ void PSPSetTexture() // glGenerateMipmap(GL_TEXTURE_2D); UpdateSamplingParams(); + //glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + //glPixelStorei(GL_PACK_ROW_LENGTH, 0); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + cache[texaddr] = entry; } diff --git a/GPU/GLES/TextureCache.h b/GPU/GLES/TextureCache.h index 61035fba7a..5abdce5f1d 100644 --- a/GPU/GLES/TextureCache.h +++ b/GPU/GLES/TextureCache.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/GPU/GLES/TransformPipeline.cpp b/GPU/GLES/TransformPipeline.cpp index 22ba5c584c..ec3291ef23 100644 --- a/GPU/GLES/TransformPipeline.cpp +++ b/GPU/GLES/TransformPipeline.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -15,7 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include #include #else @@ -48,81 +48,96 @@ GLuint glprim[8] = GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, - GL_TRIANGLES, // With OpenGL ES we have to expand into triangles, tripling the data instead of doubling. sigh. OpenGL ES, Y U NO SUPPORT GL_QUADS? + GL_TRIANGLES, // With OpenGL ES we have to expand sprites into triangles, tripling the data instead of doubling. sigh. OpenGL ES, Y U NO SUPPORT GL_QUADS? }; DecodedVertex decoded[65536]; TransformedVertex transformed[65536]; +TransformedVertex transformedExpanded[65536]; uint16_t indexBuffer[65536]; // Unused -void Light(float colorOut[4], const float colorIn[4], Vec3 pos, Vec3 normal, float dots[4]) -{ - // could cache a lot of stuff, such as ambient, across vertices... +// TODO: This should really return 2 colors, one for specular and one for diffuse. - bool doShadeMapping = (gstate.texmapmode & 0x3) == 2; - if (!doShadeMapping && !(gstate.lightEnable[0]&1) && !(gstate.lightEnable[1]&1) && !(gstate.lightEnable[2]&1) && !(gstate.lightEnable[3]&1)) - { - memcpy(colorOut, colorIn, sizeof(float) * 4); - return; - } +// Convenient way to do precomputation to save the parts of the lighting calculation +// that's common between the many vertices of a draw call. +class Lighter { +public: + Lighter(); + void Light(float colorOut0[4], float colorOut1[4], const float colorIn[4], Vec3 pos, Vec3 normal, float dots[4]); - Color4 emissive; - emissive.GetFromRGB(gstate.materialemissive); +private: + bool disabled_; Color4 globalAmbient; + Color4 materialEmissive; + Color4 materialAmbient; + Color4 materialDiffuse; + Color4 materialSpecular; + float specCoef_; + Vec3 viewer_; + bool doShadeMapping_; + int materialUpdate_; +}; + +Lighter::Lighter() { + disabled_ = false; + doShadeMapping_ = (gstate.texmapmode & 0x3) == 2; + if (!doShadeMapping_ && !(gstate.lightEnable[0]&1) && !(gstate.lightEnable[1]&1) && !(gstate.lightEnable[2]&1) && !(gstate.lightEnable[3]&1)) + { + disabled_ = true; + } + materialEmissive.GetFromRGB(gstate.materialemissive); + materialEmissive.a = 0.0f; globalAmbient.GetFromRGB(gstate.ambientcolor); globalAmbient.GetFromA(gstate.ambientalpha); + materialAmbient.GetFromRGB(gstate.materialambient); + materialAmbient.a = 1.0f; + materialDiffuse.GetFromRGB(gstate.materialdiffuse); + materialDiffuse.a = 1.0f; + materialSpecular.GetFromRGB(gstate.materialspecular); + materialSpecular.a = 1.0f; + specCoef_ = getFloat24(gstate.materialspecularcoef); + viewer_ = Vec3(-gstate.viewMatrix[9], -gstate.viewMatrix[10], -gstate.viewMatrix[11]); + materialUpdate_ = gstate.materialupdate & 7; +} + +void Lighter::Light(float colorOut0[4], float colorOut1[4], const float colorIn[4], Vec3 pos, Vec3 normal, float dots[4]) +{ + if (disabled_) { + memcpy(colorOut0, colorIn, sizeof(float) * 4); + memset(colorOut1, 0, sizeof(float) * 4); + return; + } Vec3 norm = normal.Normalized(); Color4 in(colorIn); - Color4 ambient; - if (gstate.materialupdate & 1) - { - ambient = in; - } + const Color4 *ambient; + if (materialUpdate_ & 1) + ambient = ∈ else - { - ambient.GetFromRGB(gstate.materialambient); - ambient.a=1.0f; - } + ambient = &materialAmbient; - Color4 diffuse; - if (gstate.materialupdate & 2) - { - diffuse = in; - } + const Color4 *diffuse; + if (materialUpdate_ & 2) + diffuse = ∈ else - { - diffuse.GetFromRGB(gstate.materialdiffuse); - diffuse.a=1.0f; - } + diffuse = &materialDiffuse; - Color4 specular; - if (gstate.materialupdate & 4) - { - specular = in; - } + const Color4 *specular; + if (materialUpdate_ & 4) + specular = ∈ else - { - specular.GetFromRGB(gstate.materialspecular); - specular.a=1.0f; - } - - float specCoef = getFloat24(gstate.materialspecularcoef); - - norm.Normalize(); - - Vec3 viewer(gstate.viewMatrix[8], gstate.viewMatrix[9], gstate.viewMatrix[10]); - - Color4 lightSum = globalAmbient * ambient + emissive; - + specular = &materialSpecular; + + Color4 lightSum0 = globalAmbient * *ambient + materialEmissive; + Color4 lightSum1(0,0,0,0); // Try lights.elf - there's something wrong with the lighting for (int l = 0; l < 4; l++) { // can we skip this light? - if ((gstate.lightEnable[l] & 1) == 0) // && !doShadeMapping) + if ((gstate.lightEnable[l] & 1) == 0 && !doShadeMapping_) continue; GELightComputation comp = (GELightComputation)(gstate.ltype[l]&3); @@ -130,22 +145,19 @@ void Light(float colorOut[4], const float colorIn[4], Vec3 pos, Vec3 normal, flo Vec3 toLight; if (type == GE_LIGHTTYPE_DIRECTIONAL) - toLight = Vec3(gstate.lightpos[l]); + toLight = Vec3(gstate.lightpos[l]); // lightdir is for spotlights else toLight = Vec3(gstate.lightpos[l]) - pos; - Vec3 dir = Vec3(gstate.lightdir[l]); - bool doSpecular = (comp != GE_LIGHTCOMP_ONLYDIFFUSE); bool poweredDiffuse = comp == GE_LIGHTCOMP_BOTHWITHPOWDIFFUSE; - float distance = toLight.Normalize(); - float lightScale = 1.0f; if (type != GE_LIGHTTYPE_DIRECTIONAL) { + float distance = toLight.Normalize(); lightScale = 1.0f / (gstate.lightatt[l][0] + gstate.lightatt[l][1]*distance + gstate.lightatt[l][2]*distance*distance); - if (lightScale>1.0f) lightScale=1.0f; + if (lightScale > 1.0f) lightScale = 1.0f; } float dot = toLight * norm; @@ -154,40 +166,52 @@ void Light(float colorOut[4], const float colorIn[4], Vec3 pos, Vec3 normal, flo if (dot < 0.0f) dot = 0.0f; if (poweredDiffuse) - dot = powf(dot, specCoef); + dot = powf(dot, specCoef_); - Color4 diff = (gstate.lightColor[1][l] * diffuse) * (dot*lightScale); - Color4 spec(0,0,0,0); + Color4 diff = (gstate.lightColor[1][l] * *diffuse) * (dot * lightScale); + + // Real PSP specular + Vec3 toViewer(0,0,1); + // Better specular + //Vec3 toViewer = (viewer - pos).Normalized(); if (doSpecular) { Vec3 halfVec = toLight; - halfVec += viewer.Normalized(); + halfVec += toViewer; halfVec.Normalize(); dot = halfVec * norm; if (dot >= 0) { - spec += (gstate.lightColor[2][l] * specular * (powf(dot, specCoef)*lightScale)); + lightSum1 += (gstate.lightColor[2][l] * *specular * (powf(dot, specCoef_)*lightScale)); } } dots[l] = dot; if (gstate.lightEnable[l] & 1) { - lightSum += gstate.lightColor[0][l]*ambient + diff + spec; + lightSum0 += gstate.lightColor[0][l] * *ambient + diff; } } - for (int i = 0; i < 3; i++) - colorOut[i] = lightSum[i]; + // 4? + for (int i = 0; i < 4; i++) { + colorOut0[i] = lightSum0[i] > 1.0f ? 1.0f : lightSum0[i]; + colorOut1[i] = lightSum1[i] > 1.0f ? 1.0f : lightSum1[i]; + } } +// This is the software transform pipeline, which is necessary for supporting RECT +// primitives correctly. Other primitives are possible to transform and light in hardware +// using vertex shader, which will be way, way faster, especially on mobile. This has +// not yet been implemented though. void TransformAndDrawPrim(void *verts, void *inds, int prim, int vertexCount, LinkedShader *program, float *customUV, int forceIndexType) { + int indexLowerBound, indexUpperBound; // First, decode the verts and apply morphing VertexDecoder dec; dec.SetVertexType(gstate.vertType); - dec.DecodeVerts(decoded, verts, inds, prim, vertexCount); + dec.DecodeVerts(decoded, verts, inds, prim, vertexCount, &indexLowerBound, &indexUpperBound); bool useTexCoord = false; @@ -218,44 +242,23 @@ void TransformAndDrawPrim(void *verts, void *inds, int prim, int vertexCount, Li float v2[3] = {0}; float uv2[2] = {0}; - int numTrans = 0; - TransformedVertex *trans = &transformed[0]; - // TODO: Could use glDrawElements in some cases, see below. - // TODO: Split up into multiple draw calls for Android where you can't guarantee support for more than 0x10000 verts. - int i = 0; -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) if (vertexCount > 0x10000/3) vertexCount = 0x10000/3; #endif - for (int i = 0; i < vertexCount; i++) + Lighter lighter; + + for (int index = indexLowerBound; index <= indexUpperBound; index++) { - int indexType = (gstate.vertType & GE_VTYPE_IDX_MASK); - if (forceIndexType != -1) { - indexType = forceIndexType; - } - - int index; - if (indexType == GE_VTYPE_IDX_8BIT) - { - index = ((u8*)inds)[i]; - } - else if (indexType == GE_VTYPE_IDX_16BIT) - { - index = ((u16*)inds)[i]; - } - else - { - index = i; - } - - float v[3] = {0,0,0}; - float c[4] = {1,1,1,1}; - float uv[2] = {0,0}; + float v[3] = {0, 0, 0}; + float c0[4] = {1, 1, 1, 1}; + float c1[4] = {0, 0, 0, 0}; + float uv[2] = {0, 0}; if (gstate.vertType & GE_VTYPE_THROUGH_MASK) { @@ -263,17 +266,19 @@ void TransformAndDrawPrim(void *verts, void *inds, int prim, int vertexCount, Li for (int j=0; j<3; j++) v[j] = decoded[index].pos[j]; // TODO : check if has color - for (int j=0; j<4; j++) - c[j] = decoded[index].color[j]; + for (int j=0; j<4; j++) { + c0[j] = decoded[index].color[j] / 255.0f; + c1[j] = 0.0f; + } + // TODO : check if has uv for (int j=0; j<2; j++) uv[j] = decoded[index].uv[j]; - - //Rescale UV? + // Rescale UV? } else { - //We do software T&L for now + // We do software T&L for now float out[3], norm[3]; if ((gstate.vertType & GE_VTYPE_WEIGHT_MASK) == GE_VTYPE_WEIGHT_NONE) { @@ -282,45 +287,72 @@ void TransformAndDrawPrim(void *verts, void *inds, int prim, int vertexCount, Li } else { + // Skinning Vec3 psum(0,0,0); Vec3 nsum(0,0,0); - int nweights = (gstate.vertType & GE_VTYPE_WEIGHT_MASK) >> GE_VTYPE_WEIGHT_SHIFT; + int nweights = ((gstate.vertType & GE_VTYPE_WEIGHTCOUNT_MASK) >> GE_VTYPE_WEIGHTCOUNT_SHIFT) + 1; for (int i = 0; i < nweights; i++) { - Vec3ByMatrix43(out, decoded[index].pos, gstate.boneMatrix+i*12); - Norm3ByMatrix43(norm, decoded[index].normal, gstate.boneMatrix+i*12); - Vec3 tpos(out), tnorm(norm); - psum += tpos*decoded[index].weights[i]; - nsum += tnorm*decoded[index].weights[i]; + if (decoded[index].weights[i] != 0.0f) { + Vec3ByMatrix43(out, decoded[index].pos, gstate.boneMatrix+i*12); + Norm3ByMatrix43(norm, decoded[index].normal, gstate.boneMatrix+i*12); + Vec3 tpos(out), tnorm(norm); + psum += tpos*decoded[index].weights[i]; + nsum += tnorm*decoded[index].weights[i]; + } } + nsum.Normalize(); - psum.Write(out); - nsum.Write(norm); + + Vec3ByMatrix43(out, psum.v, gstate.worldMatrix); + Norm3ByMatrix43(norm, nsum.v, gstate.worldMatrix); } // Perform lighting here if enabled. don't need to check through, it's checked above. float dots[4] = {0,0,0,0}; if (program->a_color0 != -1) { - //c[1] = norm[1]; - float litColor[4] = {0,0,0,0}; - Light(litColor, decoded[index].color, out, norm, dots); + float unlitColor[4]; + for (int j = 0; j < 4; j++) { + unlitColor[j] = decoded[index].color[j] / 255.0f; + } + float litColor0[4]; + float litColor1[4]; + lighter.Light(litColor0, litColor1, unlitColor, out, norm, dots); + if (gstate.lightingEnable & 1) { - memcpy(c, litColor, sizeof(litColor)); + // TODO: don't ignore gstate.lmode - we should send two colors in that case + if (gstate.lmode & 1) { + // Separate colors + for (int j = 0; j < 4; j++) { + c0[j] = litColor0[j]; + c1[j] = litColor1[j]; + } + } else { + // Summed color into c0 + for (int j = 0; j < 4; j++) { + c0[j] = litColor0[j] + litColor1[j]; + c1[j] = 0.0f; + } + } } else { // no lighting? copy the color. - for (int j=0; j<4; j++) - c[j] = decoded[index].color[j]; + for (int j = 0; j < 4; j++) { + c0[j] = unlitColor[j]; + c1[j] = 0.0f; + } } } else { // no color in the fragment program??? - for (int j=0; j<4; j++) - c[j] = decoded[index].color[j]; + for (int j = 0; j < 4; j++) { + c0[j] = decoded[index].color[j] / 255.0f; + c1[j] = 0.0f; + } } if (customUV) { @@ -374,91 +406,139 @@ void TransformAndDrawPrim(void *verts, void *inds, int prim, int vertexCount, Li break; } } - // Transform the coord by the view matrix. Should this be done before or after texcoord generation? + + // Transform the coord by the view matrix. + // We only really need to do it here for RECTANGLES drawing. However, + // there's no point in optimizing it out because all other primitives + // will be moved to hardware transform anyway. Vec3ByMatrix43(v, out, gstate.viewMatrix); } + memcpy(&transformed[index].x, v, 3 * sizeof(float)); + memcpy(&transformed[index].uv, uv, 2 * sizeof(float)); + memcpy(&transformed[index].color0, c0, 4 * sizeof(float)); + memcpy(&transformed[index].color1, c1, 4 * sizeof(float)); + } - // We need to tesselate axis-aligned rectangles, as they're only specified by two coordinates. - if (prim == GE_PRIM_RECTANGLES) - { + // Step 2: Expand using the index buffer, and expand rectangles. + + const TransformedVertex *drawBuffer = transformed; + int numTrans = 0; + + int indexType = (gstate.vertType & GE_VTYPE_IDX_MASK); + if (forceIndexType != -1) { + indexType = forceIndexType; + } + + bool drawIndexed = false; + GLuint glIndexType = 0; + + if (prim != GE_PRIM_RECTANGLES) { + // We can simply draw the unexpanded buffer. + numTrans = vertexCount; + switch (indexType) { + case GE_VTYPE_IDX_8BIT: + drawIndexed = true; + glIndexType = GL_UNSIGNED_BYTE; + break; + case GE_VTYPE_IDX_16BIT: + drawIndexed = true; + glIndexType = GL_UNSIGNED_SHORT; + break; + default: + drawIndexed = false; + break; + } + } else { + numTrans = 0; + drawBuffer = transformedExpanded; + TransformedVertex *trans = &transformedExpanded[0]; + TransformedVertex saved; + for (int i = 0; i < vertexCount; i++) { + int index; + if (indexType == GE_VTYPE_IDX_8BIT) + { + index = ((u8*)inds)[i]; + } + else if (indexType == GE_VTYPE_IDX_16BIT) + { + index = ((u16*)inds)[i]; + } + else + { + index = i; + } + + TransformedVertex &transVtx = transformed[index]; if ((i & 1) == 0) { // Save this vertex so we can generate when we get the next one. Color is taken from the last vertex. - memcpy(v2, v, sizeof(float)*3); - memcpy(uv2,uv,sizeof(float)*2); + saved = transVtx; } else { // We have to turn the rectangle into two triangles, so 6 points. Sigh. // top left - trans->x = v[0]; trans->y = v[1]; - trans->z = v[2]; - trans->uv[0] = uv[0]; trans->uv[1] = uv[1]; - memcpy(trans->color, c, 4*sizeof(float)); + *trans = transVtx; + trans++; + + // bottom right + *trans = transVtx; + trans->x = saved.x; + trans->uv[0] = saved.uv[0]; + trans->y = saved.y; + trans->uv[1] = saved.uv[1]; trans++; // top right - trans->x = v2[0]; trans->y = v[1]; - trans->z = v[2]; - trans->uv[0] = uv2[0]; trans->uv[1] = uv[1]; - memcpy(trans->color, c, 4*sizeof(float)); - trans++; - - // bottom right - trans->x = v2[0]; trans->y = v2[1]; - trans->z = v[2]; - trans->uv[0] = uv2[0]; trans->uv[1] = uv2[1]; - memcpy(trans->color, c, 4*sizeof(float)); + *trans = transVtx; + trans->x = saved.x; + trans->uv[0] = saved.uv[0]; trans++; // bottom left - trans->x = v[0]; trans->y = v2[1]; - trans->z = v[2]; - trans->uv[0] = uv[0]; trans->uv[1] = uv2[1]; - memcpy(trans->color, c, 4*sizeof(float)); - trans++; - - // top left - trans->x = v[0]; trans->y = v[1]; - trans->z = v[2]; - trans->uv[0] = uv[0]; trans->uv[1] = uv[1]; - memcpy(trans->color, c, 4*sizeof(float)); + *trans = transVtx; + trans->y = saved.y; + trans->uv[1] = saved.uv[1]; trans++; // bottom right - trans->x = v2[0]; trans->y = v2[1]; - trans->z = v[2]; - trans->uv[0] = uv2[0]; trans->uv[1] = uv2[1]; - memcpy(trans->color, c, 4*sizeof(float)); + *trans = transVtx; + trans->x = saved.x; + trans->uv[0] = saved.uv[0]; + trans->y = saved.y; + trans->uv[1] = saved.uv[1]; + trans++; + + // top left + *trans = transVtx; trans++; numTrans += 6; } } - else - { - memcpy(&trans->x, v, 3*sizeof(float)); - memcpy(trans->color, c, 4*sizeof(float)); - memcpy(trans->uv, uv, 2*sizeof(float)); - trans++; - numTrans++; - } } glEnableVertexAttribArray(program->a_position); if (useTexCoord && program->a_texcoord != -1) glEnableVertexAttribArray(program->a_texcoord); if (program->a_color0 != -1) glEnableVertexAttribArray(program->a_color0); - const int vertexSize = sizeof(*trans); - glVertexAttribPointer(program->a_position, 3, GL_FLOAT, GL_FALSE, vertexSize, transformed); - if (useTexCoord && program->a_texcoord != -1) glVertexAttribPointer(program->a_texcoord, 2, GL_FLOAT, GL_FALSE, vertexSize, ((uint8_t*)transformed) + 3 * 4); - if (program->a_color0 != -1) glVertexAttribPointer(program->a_color0, 4, GL_FLOAT, GL_FALSE, vertexSize, ((uint8_t*)transformed) + 5 * 4); + if (program->a_color1 != -1) glEnableVertexAttribArray(program->a_color1); + const int vertexSize = sizeof(transformed[0]); + glVertexAttribPointer(program->a_position, 3, GL_FLOAT, GL_FALSE, vertexSize, drawBuffer); + if (useTexCoord && program->a_texcoord != -1) glVertexAttribPointer(program->a_texcoord, 2, GL_FLOAT, GL_FALSE, vertexSize, ((uint8_t*)drawBuffer) + 3 * 4); + if (program->a_color0 != -1) glVertexAttribPointer(program->a_color0, 4, GL_FLOAT, GL_FALSE, vertexSize, ((uint8_t*)drawBuffer) + 5 * 4); + if (program->a_color1 != -1) glVertexAttribPointer(program->a_color1, 4, GL_FLOAT, GL_FALSE, vertexSize, ((uint8_t*)drawBuffer) + 9 * 4); // NOTICE_LOG(G3D,"DrawPrimitive: %i", numTrans); - glDrawArrays(glprim[prim], 0, numTrans); + if (drawIndexed) { + glDrawElements(glprim[prim], numTrans, glIndexType, (GLvoid *)inds); + } else { + glDrawArrays(glprim[prim], 0, numTrans); + } glDisableVertexAttribArray(program->a_position); if (useTexCoord && program->a_texcoord != -1) glDisableVertexAttribArray(program->a_texcoord); if (program->a_color0 != -1) glDisableVertexAttribArray(program->a_color0); + if (program->a_color1 != -1) glDisableVertexAttribArray(program->a_color1); /* if (((gstate.vertType ) & GE_VTYPE_IDX_MASK) == GE_VTYPE_IDX_8BIT) diff --git a/GPU/GLES/TransformPipeline.h b/GPU/GLES/TransformPipeline.h index fc9b4218e7..330921778b 100644 --- a/GPU/GLES/TransformPipeline.h +++ b/GPU/GLES/TransformPipeline.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -19,4 +19,5 @@ struct LinkedShader; + void TransformAndDrawPrim(void *verts, void *inds, int prim, int count, LinkedShader *shader, float *customUV = 0, int forceIndexType = -1); diff --git a/GPU/GLES/VertexDecoder.cpp b/GPU/GLES/VertexDecoder.cpp index 2997aebb50..ef6104fd63 100644 --- a/GPU/GLES/VertexDecoder.cpp +++ b/GPU/GLES/VertexDecoder.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -15,7 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include #include #else @@ -46,8 +46,6 @@ inline int align(int n, int align) return (n+(align-1)) & ~(align-1); } -static int onesize; - void VertexDecoder::SetVertexType(u32 fmt) { fmt = fmt; @@ -80,13 +78,13 @@ void VertexDecoder::SetVertexType(u32 fmt) size = align(size, tcalign[tc]); tcoff = size; size += tcsize[tc]; - if (tcalign[tc]>biggest) - biggest=tcalign[tc]; + if (tcalign[tc] > biggest) + biggest = tcalign[tc]; } if (col) { - size = align(size,colalign[col]); + size = align(size, colalign[col]); coloff = size; size += colsize[col]; if (colalign[col] > biggest) @@ -96,55 +94,70 @@ void VertexDecoder::SetVertexType(u32 fmt) { coloff = 0; } + if (nrm) { - size = align(size,nrmalign[nrm]); + size = align(size, nrmalign[nrm]); nrmoff = size; size += nrmsize[nrm]; if (nrmalign[nrm] > biggest) biggest = nrmalign[nrm]; } - //if (pos) + //if (pos) - there's always a position { - size = align(size,posalign[pos]); + size = align(size, posalign[pos]); posoff = size; size += possize[pos]; if (posalign[pos] > biggest) biggest = posalign[pos]; } - size = align(size,biggest); - onesize = size; + size = align(size, biggest); + onesize_ = size; size *= morphcount; DEBUG_LOG(G3D,"SVT : size = %i, aligned to biggest %i", size, biggest); } -void VertexDecoder::DecodeVerts(DecodedVertex *decoded, const void *verts, const void *inds, int prim, int count) const +void VertexDecoder::DecodeVerts(DecodedVertex *decoded, const void *verts, const void *inds, int prim, int count, int *indexLowerBound, int *indexUpperBound) const { if (morphcount == 1) gstate.morphWeights[0] = 1.0f; char *ptr = (char *)verts; - for (int i = 0; i < count; i++) - { - int index; - if (idx == (GE_VTYPE_IDX_8BIT >> 11)) - { - index = ((u8*)inds)[i]; - } - else if (idx == (GE_VTYPE_IDX_16BIT >> 11)) - { - index = ((u16*)inds)[i]; + // Find index bounds. Could cache this in display lists. + int lowerBound = 0x7FFFFFFF; + int upperBound = 0; + if (idx == (GE_VTYPE_IDX_8BIT >> GE_VTYPE_IDX_SHIFT)) { + const u8 *ind8 = (const u8 *)inds; + for (int i = 0; i < count; i++) { + if (ind8[i] < lowerBound) + lowerBound = ind8[i]; + if (ind8[i] > upperBound) + upperBound = ind8[i]; } - else - { - index = i; + } else if (idx == (GE_VTYPE_IDX_16BIT >> GE_VTYPE_IDX_SHIFT)) { + const u16 *ind16 = (const u16*)inds; + for (int i = 0; i < count; i++) { + if (ind16[i] < lowerBound) + lowerBound = ind16[i]; + if (ind16[i] > upperBound) + upperBound = ind16[i]; } + } else { + lowerBound = 0; + upperBound = count - 1; + } + *indexLowerBound = lowerBound; + *indexUpperBound = upperBound; + // Decode the vertices within the found bounds, once each (unlike the previous way..) + for (int index = lowerBound; index <= upperBound; index++) + { ptr = (char*)verts + (index * size); + // TODO: Should weights be morphed? float *wt = decoded[index].weights; switch (weighttype) { @@ -153,29 +166,30 @@ void VertexDecoder::DecodeVerts(DecodedVertex *decoded, const void *verts, const case GE_VTYPE_WEIGHT_8BIT >> 9: { - u8 *wdata = (u8*)(ptr); - for (int j=0; j> 9: { - u16 *wdata = (u16*)(ptr); - for (int j=0; j> 9: { - float *wdata = (float*)(ptr+0); - for (int j=0; j>2: + case GE_VTYPE_COL_4444 >> 2: { u16 cdata = *(u16*)(ptr + coloff); for (int j = 0; j < 4; j++) - c[j] = (float)(cdata>>(j * 4) & 0xF) / 15.0f; + c[j] = Convert4To8((cdata >> (j * 4)) & 0xF); } break; - case GE_VTYPE_COL_565>>2: + case GE_VTYPE_COL_565 >> 2: { u16 cdata = *(u16*)(ptr + coloff); - c[0] = (float)(cdata & 0x1f) / 31.0f; - c[1] = (float)((cdata>>5) & 0x3f) / 63.0f; - c[2] = (float)((cdata>>11) & 0x1f) / 31.0f; + c[0] = Convert5To8(cdata & 0x1f); + c[1] = Convert6To8((cdata>>5) & 0x3f); + c[2] = Convert5To8((cdata>>11) & 0x1f); c[3] = 1.0f; } break; - case GE_VTYPE_COL_5551>>2: + case GE_VTYPE_COL_5551 >> 2: { u16 cdata = *(u16*)(ptr + coloff); - c[0] = (float)(cdata & 0x1f) / 31.0f; - c[1] = (float)((cdata>>5) & 0x1f) / 31.0f; - c[2] = (float)((cdata>>10) & 0x1f) / 31.0f; - c[3] = (float)(cdata>>15); + c[0] = Convert5To8(cdata & 0x1f); + c[1] = Convert5To8((cdata>>5) & 0x1f); + c[2] = Convert5To8((cdata>>10) & 0x1f); + c[3] = (cdata>>15) ? 255 : 0; } break; - case GE_VTYPE_COL_8888>>2: + case GE_VTYPE_COL_8888 >> 2: { + // TODO: speedup u8 *cdata = (u8*)(ptr + coloff); - for (int j=0; j<4; j++) - c[j] = (float)cdata[j] / 255.0f; + for (int j = 0; j < 4; j++) + c[j] = cdata[j]; } break; default: - c[0]=1.0f; c[1]=1.0f; c[2]=1.0f; c[3]=1.0f; + c[0]=255; c[1]=255; c[2]=255; c[3]=255; break; } - float *normal = decoded[index].normal; - memset(normal,0,sizeof(float)*3); - for (int n=0; n>5: + case GE_VTYPE_NRM_FLOAT >> 5: { - float *fv = (float*)(ptr + onesize*n + nrmoff); - for (int j=0; j<3; j++) - normal[j] += fv[j] * gstate.morphWeights[n]; + const float *fv = (const float*)(ptr + onesize_*n + nrmoff); + for (int j = 0; j < 3; j++) + normal[j] += fv[j] * multiplier; } break; - case GE_VTYPE_NRM_16BIT>>5: + case GE_VTYPE_NRM_16BIT >> 5: { - short *sv = (short*)(ptr + onesize*n + nrmoff); - for (int j=0; j<3; j++) - normal[j] += (sv[j]/32767.0f) * gstate.morphWeights[n]; + const short *sv = (const short*)(ptr + onesize_*n + nrmoff); + for (int j = 0; j < 3; j++) + normal[j] += (sv[j]/32767.0f) * multiplier; } break; @@ -294,38 +313,78 @@ void VertexDecoder::DecodeVerts(DecodedVertex *decoded, const void *verts, const } } - if (gstate.reversenormals) - { - for (int j = 0; j < 3; j++) - normal[j] = -normal[j]; - } - float *v = decoded[index].pos; - memset(v, 0, sizeof(float)*3); - for (int n = 0; n < morphcount; n++) - { + + if (morphcount == 1) { switch (pos) { - case GE_VTYPE_POS_FLOAT>>7: + case GE_VTYPE_POS_FLOAT >> 7: { - float *fv = (float*)(ptr + onesize*n + posoff); - for (int j=0; j<3; j++) - v[j] += fv[j] * gstate.morphWeights[n]; + const float *fv = (const float*)(ptr + posoff); + for (int j = 0; j < 3; j++) + v[j] = fv[j]; } break; - case GE_VTYPE_POS_16BIT>>7: + case GE_VTYPE_POS_16BIT >> 7: { - short *sv = (short*)(ptr + onesize*n + posoff); + float multiplier = 1.0f / 32767.0f; + if (throughmode) multiplier = 1.0f; + const short *sv = (const short*)(ptr + posoff); for (int j = 0; j < 3; j++) - v[j] += sv[j] * gstate.morphWeights[n]; + v[j] = sv[j] * multiplier; + } + break; + + case GE_VTYPE_POS_8BIT >> 7: + { + const s8 *sv = (const s8*)(ptr + posoff); + for (int j = 0; j < 3; j++) + v[j] = sv[j] / 127.f; } break; default: - DEBUG_LOG(G3D,"Unknown position format %i",pos); + ERROR_LOG(G3D,"Unknown position format %i",pos); break; } + } else { + memset(v, 0, sizeof(float) * 3); + for (int n = 0; n < morphcount; n++) + { + switch (pos) + { + case GE_VTYPE_POS_FLOAT >> 7: + { + const float *fv = (const float*)(ptr + onesize_*n + posoff); + for (int j = 0; j < 3; j++) + v[j] += fv[j] * gstate.morphWeights[n]; + } + break; + + case GE_VTYPE_POS_16BIT >> 7: + { + float multiplier = 1.0f / 32767.0f; + if (throughmode) multiplier = 1.0f; + const short *sv = (const short*)(ptr + onesize_*n + posoff); + for (int j = 0; j < 3; j++) + v[j] += (sv[j] * multiplier) * gstate.morphWeights[n]; + } + break; + + case GE_VTYPE_POS_8BIT >> 7: + { + const s8 *sv = (const s8*)(ptr + onesize_*n + posoff); + for (int j = 0; j < 3; j++) + v[j] += (sv[j] / 127.f) * gstate.morphWeights[n]; + } + break; + + default: + ERROR_LOG(G3D,"Unknown position format %i",pos); + break; + } + } } } } diff --git a/GPU/GLES/VertexDecoder.h b/GPU/GLES/VertexDecoder.h index dac0d7ad92..615d3966c1 100644 --- a/GPU/GLES/VertexDecoder.h +++ b/GPU/GLES/VertexDecoder.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -24,15 +24,16 @@ struct DecodedVertex float pos[3]; // in case of morph, preblend during decode float normal[3]; // in case of morph, preblend during decode float uv[2]; // scaled by uscale, vscale, if there - float color[4]; // unlit - float weights[8]; + u8 color[4]; // unlit + float weights[8]; // ugh, expensive }; struct TransformedVertex { float x, y, z; // in case of morph, preblend during decode float uv[2]; // scaled by uscale, vscale, if there - float color[4]; // prelit + float color0[4]; // prelit + float color1[4]; // prelit }; @@ -44,22 +45,30 @@ struct TransformedVertex // - will compile into lighting fast specialized x86 // - will not bother translating components that can be read directly // by OpenGL ES. Will still have to translate 565 colors, and things -// like that. DecodedVertex will not be a fixed struct. +// like that. DecodedVertex will not be a fixed struct. Will have to +// do morphing here. // // We want 100% perf on 1Ghz even in vertex complex games! class VertexDecoder { +public: + VertexDecoder() : coloff(0), nrmoff(0), posoff(0) {} + ~VertexDecoder() {} + void SetVertexType(u32 fmt); + void DecodeVerts(DecodedVertex *decoded, const void *verts, const void *inds, int prim, int count, int *indexLowerBound, int *indexUpperBound) const; + +private: u32 fmt; bool throughmode; int biggest; + int size; + int onesize_; int weightoff; int tcoff; int coloff; int nrmoff; int posoff; - int size; - int oneSize; int tc; int col; @@ -70,11 +79,4 @@ class VertexDecoder int morphcount; int nweights; -public: - VertexDecoder() : coloff(0), nrmoff(0), posoff(0) {} - ~VertexDecoder() {} - void SetVertexType(u32 fmt); - void DecodeVerts(DecodedVertex *decoded, const void *verts, const void *inds, int prim, int count) const; - - // void DoGLVertexAttribPointer() }; diff --git a/GPU/GLES/VertexShaderGenerator.cpp b/GPU/GLES/VertexShaderGenerator.cpp index 1091f0bfe4..d48536f6a6 100644 --- a/GPU/GLES/VertexShaderGenerator.cpp +++ b/GPU/GLES/VertexShaderGenerator.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -53,25 +53,31 @@ void WriteLight(char *p, int l) { char *GenerateVertexShader() { char *p = buffer; -#if defined(ANDROID) +#if defined(ANDROID) || defined(BLACKBERRY) WRITE("precision highp float;"); #elif !defined(FORCE_OPENGL_2_0) WRITE("#version 130"); #endif + int lmode = gstate.lmode & 1; + WRITE("attribute vec4 a_position;"); WRITE("attribute vec2 a_texcoord;"); WRITE("attribute vec4 a_color0;"); + if (lmode) + WRITE("attribute vec4 a_color1;"); WRITE("uniform mat4 u_proj;"); WRITE("varying vec4 v_color0;"); - WRITE("varying vec4 v_color1;"); + if (lmode) + WRITE("varying vec4 v_color1;"); WRITE("varying vec2 v_texcoord;"); WRITE("void main() {"); WRITE("v_color0 = a_color0;"); - WRITE("v_color1 = a_color0;"); + if (lmode) + WRITE("v_color1 = a_color1;"); WRITE("v_texcoord = a_texcoord;"); WRITE("gl_Position = u_proj * a_position;"); WRITE("}"); diff --git a/GPU/GLES/VertexShaderGenerator.h b/GPU/GLES/VertexShaderGenerator.h index f148bc965a..10a1fd1e58 100644 --- a/GPU/GLES/VertexShaderGenerator.h +++ b/GPU/GLES/VertexShaderGenerator.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/GPU/GPU.vcxproj b/GPU/GPU.vcxproj index 1a5484df8f..07d90cf861 100644 --- a/GPU/GPU.vcxproj +++ b/GPU/GPU.vcxproj @@ -122,8 +122,10 @@ + + @@ -136,12 +138,16 @@ + {3fcdbae2-5103-4350-9a8e-848ce9c73195} + + + diff --git a/GPU/GPU.vcxproj.filters b/GPU/GPU.vcxproj.filters index 163f1d1b5c..fdf4719642 100644 --- a/GPU/GPU.vcxproj.filters +++ b/GPU/GPU.vcxproj.filters @@ -10,6 +10,9 @@ {21783292-4dd7-447b-af93-356cd2eaa4d6} + + {b31aa5a1-da08-47e6-9467-ab1d547b6ff3} + @@ -45,6 +48,12 @@ Common + + Common + + + Null + @@ -77,5 +86,11 @@ Common + + Null + + + + \ No newline at end of file diff --git a/GPU/GPUInterface.h b/GPU/GPUInterface.h new file mode 100644 index 0000000000..5e373b5d93 --- /dev/null +++ b/GPU/GPUInterface.h @@ -0,0 +1,30 @@ +// Copyright (c) 2012- PPSSPP Project. + +// 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, version 2.0 or later versions. + +// 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 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "../Globals.h" + +class GPUInterface +{ +public: + virtual u32 EnqueueList(u32 listpc, u32 stall) = 0; + virtual void UpdateStall(int listid, u32 newstall) = 0; + virtual void ExecuteOp(u32 op, u32 diff) = 0; + virtual bool InterpretList() = 0; + virtual void DrawSync(int mode) = 0; +}; diff --git a/GPU/GPUState.cpp b/GPU/GPUState.cpp index ae954bc039..801aa07f89 100644 --- a/GPU/GPUState.cpp +++ b/GPU/GPUState.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -15,7 +15,7 @@ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include #include #else @@ -31,8 +31,12 @@ #include "GPUState.h" #include "GLES/ShaderManager.h" #include "GLES/DisplayListInterpreter.h" +#include "Null/NullGpu.h" +#include "../Core/CoreParameter.h" +#include "../Core/System.h" GPUgstate gstate; +GPUInterface *gpu; void InitGfxState() { @@ -60,6 +64,21 @@ void InitGfxState() for (int i = 0; i < 8; i++) { memcpy(gstate.boneMatrix + i * 12, identity4x3, 12 * sizeof(float)); } + + switch (PSP_CoreParameter().gpuCore) { + case GPU_NULL: + gpu = new NullGPU(); + break; + case GPU_GLES: + gpu = new GLES_GPU(); + break; + } +} + +void ShutdownGfxState() +{ + delete gpu; + gpu = NULL; } // When you have changed state outside the psp gfx core, @@ -69,13 +88,13 @@ void ReapplyGfxState() // ShaderManager_DirtyShader(); // The commands are embedded in the command memory so we can just reexecute the words. Convenient. // To be safe we pass 0xFFFFFFF as the diff. - GPU::ExecuteOp(gstate.cmdmem[GE_CMD_ALPHABLENDENABLE], 0xFFFFFFFF); - GPU::ExecuteOp(gstate.cmdmem[GE_CMD_ALPHATESTENABLE], 0xFFFFFFFF); - GPU::ExecuteOp(gstate.cmdmem[GE_CMD_BLENDMODE], 0xFFFFFFFF); - GPU::ExecuteOp(gstate.cmdmem[GE_CMD_ZTEST], 0xFFFFFFFF); - GPU::ExecuteOp(gstate.cmdmem[GE_CMD_ZTESTENABLE], 0xFFFFFFFF); - GPU::ExecuteOp(gstate.cmdmem[GE_CMD_CULL], 0xFFFFFFFF); - GPU::ExecuteOp(gstate.cmdmem[GE_CMD_CULLFACEENABLE], 0xFFFFFFFF); - GPU::ExecuteOp(gstate.cmdmem[GE_CMD_SCISSOR1], 0xFFFFFFFF); - GPU::ExecuteOp(gstate.cmdmem[GE_CMD_SCISSOR2], 0xFFFFFFFF); + gpu->ExecuteOp(gstate.cmdmem[GE_CMD_ALPHABLENDENABLE], 0xFFFFFFFF); + gpu->ExecuteOp(gstate.cmdmem[GE_CMD_ALPHATESTENABLE], 0xFFFFFFFF); + gpu->ExecuteOp(gstate.cmdmem[GE_CMD_BLENDMODE], 0xFFFFFFFF); + gpu->ExecuteOp(gstate.cmdmem[GE_CMD_ZTEST], 0xFFFFFFFF); + gpu->ExecuteOp(gstate.cmdmem[GE_CMD_ZTESTENABLE], 0xFFFFFFFF); + gpu->ExecuteOp(gstate.cmdmem[GE_CMD_CULL], 0xFFFFFFFF); + gpu->ExecuteOp(gstate.cmdmem[GE_CMD_CULLFACEENABLE], 0xFFFFFFFF); + gpu->ExecuteOp(gstate.cmdmem[GE_CMD_SCISSOR1], 0xFFFFFFFF); + gpu->ExecuteOp(gstate.cmdmem[GE_CMD_SCISSOR2], 0xFFFFFFFF); } diff --git a/GPU/GPUState.h b/GPU/GPUState.h index df3a4ac093..312f24d13d 100644 --- a/GPU/GPUState.h +++ b/GPU/GPUState.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -258,6 +258,7 @@ struct GPUgstate }; void InitGfxState(); +void ShutdownGfxState(); void ReapplyGfxState(); @@ -278,4 +279,7 @@ inline unsigned int toFloat24(float f) { return i; } +class GPUInterface; + extern GPUgstate gstate; +extern GPUInterface *gpu; \ No newline at end of file diff --git a/GPU/Math3D.cpp b/GPU/Math3D.cpp index 5a107cbf24..da896c28ea 100644 --- a/GPU/Math3D.cpp +++ b/GPU/Math3D.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/GPU/Math3D.h b/GPU/Math3D.h index 68c743b62e..c1bf12eae3 100644 --- a/GPU/Math3D.h +++ b/GPU/Math3D.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/GPU/Null/NullDisplayListInterpreter.cpp b/GPU/Null/NullDisplayListInterpreter.cpp new file mode 100644 index 0000000000..fa8bead636 --- /dev/null +++ b/GPU/Null/NullDisplayListInterpreter.cpp @@ -0,0 +1,1010 @@ +// Copyright (c) 2012- PPSSPP Project. + +// 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, version 2.0 or later versions. + +// 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 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#if defined(ANDROID) || defined(BLACKBERRY) +#include +#include +#else +#include +#if defined(__APPLE__) +#include +#else +#include +#endif +#endif + + +#include "../../Core/MemMap.h" +#include "../../Core/Host.h" + +#include "../GPUState.h" +#include "../ge_constants.h" + +#include "ShaderManager.h" +#include "DisplayListInterpreter.h" +#include "TransformPipeline.h" + +#include "../../Core/HLE/sceKernelThread.h" +#include "../../Core/HLE/sceKernelInterrupt.h" + +inline void glEnDis(GLuint cmd, int value) +{ + (value ? glEnable : glDisable)(cmd); +} + +struct DisplayState +{ + u32 pc; + u32 stallAddr; +}; + +static DisplayState dcontext; +ShaderManager shaderManager; + +extern u32 curTextureWidth; +extern u32 curTextureHeight; + +int dlIdGenerator = 1; + +struct DisplayList +{ + int id; + u32 listpc; + u32 stall; +}; + +std::vector dlQueue; + +static u32 prev; +u32 stack[2]; +u32 stackptr = 0; +bool finished; + +u8 bezierBuf[16000]; + +bool ProcessDLQueue() +{ + std::vector::iterator iter = dlQueue.begin(); + while (!(iter == dlQueue.end())) + { + DisplayList &l = *iter; + dcontext.pc = l.listpc; + dcontext.stallAddr = l.stall; +// DEBUG_LOG(G3D,"Okay, starting DL execution at %08 - stall = %08x", context.pc, stallAddr); + if (!GPU::InterpretList()) + { + l.listpc = dcontext.pc; + l.stall = dcontext.stallAddr; + return false; + } + else + { + //At the end, we can remove it from the queue and continue + dlQueue.erase(iter); + //this invalidated the iterator, let's fix it + iter = dlQueue.begin(); + } + } + return true; //no more lists! +} + +u32 GPU::EnqueueList(u32 listpc, u32 stall) +{ + DisplayList dl; + dl.id = dlIdGenerator++; + dl.listpc = listpc&0xFFFFFFF; + dl.stall = stall&0xFFFFFFF; + dlQueue.push_back(dl); + if (!ProcessDLQueue()) + return dl.id; + else + return 0; +} + +void GPU::UpdateStall(int listid, u32 newstall) +{ + // this needs improvement.... + for (std::vector::iterator iter = dlQueue.begin(); iter != dlQueue.end(); iter++) + { + DisplayList &l = *iter; + if (l.id == listid) + { + l.stall = newstall & 0xFFFFFFF; + } + } + + ProcessDLQueue(); +} + +// Just to get something on the screen, we'll just not subdivide correctly. +void drawBezier(int ucount, int vcount) +{ + u16 indices[3 * 3 * 6]; + float customUV[32]; + int c = 0; + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + indices[c++] = y * 4 + x; + indices[c++] = y * 4 + x + 1; + indices[c++] = (y + 1) * 4 + x + 1; + indices[c++] = (y + 1) * 4 + x + 1; + indices[c++] = (y + 1) * 4 + x; + indices[c++] = y * 4 + x; + } + } + + for (int y = 0; y < 4; y++) { + for (int x = 0; x < 4; x++) { + customUV[(y * 4 + x) * 2 + 0] = (float)x/3.0f; + customUV[(y * 4 + x) * 2 + 1] = (float)y/3.0f; + } + } + + LinkedShader *linkedShader = shaderManager.ApplyShader(); + TransformAndDrawPrim(Memory::GetPointer(gstate.vertexAddr), &indices[0], GE_PRIM_TRIANGLES, 3 * 3 * 6, linkedShader, customUV, GE_VTYPE_IDX_16BIT); +} + + +void EnterClearMode(u32 data) +{ + bool colMask = (data >> 8) & 1; + bool alphaMask = (data >> 9) & 1; + bool updateZ = (data >> 10) & 1; + glColorMask(colMask, colMask, colMask, alphaMask); + glDepthMask(updateZ); // Update Z or not + // Note that depth test must be enabled for depth writes to go through! So we use GL_ALWAYS + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_ALWAYS); + glDisable(GL_CULL_FACE); // ?? +} + +void LeaveClearMode() +{ + // We have to reset the following state as per the state of the command registers: + // Back face culling + // Texture map enable (meh) + // Fogging + // Antialiasing + // Alpha test + glDepthMask(1); + glColorMask(1,1,1,1); + glEnDis(GL_DEPTH_TEST, gstate.zTestEnable & 1); + glDepthFunc(GL_LEQUAL); // TODO + + // dirtyshader? +} + +void SetBlendModePSP(u32 data) +{ + // This can't be done exactly as there are several PSP blend modes that are impossible to do on OpenGL ES 2.0, and some even on regular OpenGL for desktop. + + // HOWEVER - we should be able to approximate the 2x modes in the shader, although they will clip wrongly. + + const GLint aLookup[] = { + GL_DST_COLOR, + GL_ONE_MINUS_DST_COLOR, + GL_SRC_ALPHA, + GL_ONE_MINUS_SRC_ALPHA, + GL_DST_ALPHA, + GL_ONE_MINUS_DST_ALPHA, + GL_SRC_ALPHA, // should be 2x + GL_ONE_MINUS_SRC_ALPHA, // should be 2x + GL_DST_ALPHA, // should be 2x + GL_ONE_MINUS_DST_ALPHA, // should be 2x - and COLOR? + GL_SRC_ALPHA, // should be FIXA + }; + const GLint bLookup[] = { + GL_SRC_COLOR, + GL_ONE_MINUS_SRC_COLOR, + GL_SRC_ALPHA, + GL_ONE_MINUS_SRC_ALPHA, + GL_DST_ALPHA, + GL_ONE_MINUS_DST_ALPHA, + GL_SRC_ALPHA, // should be 2x + GL_ONE_MINUS_SRC_ALPHA, // should be 2x + GL_DST_ALPHA, // should be 2x + GL_ONE_MINUS_DST_ALPHA, // should be 2x + GL_SRC_ALPHA, // should be FIXB + }; + const GLint eqLookup[] = { + GL_FUNC_ADD, + GL_FUNC_SUBTRACT, + GL_FUNC_REVERSE_SUBTRACT, +#if defined(ANDROID) || defined(BLACKBERRY) + GL_FUNC_ADD, + GL_FUNC_ADD, +#else + GL_MIN, + GL_MAX, +#endif + GL_FUNC_ADD, // should be abs(diff) + }; + int a = data & 0xF; + int b = (data >> 4) & 0xF; + int eq = (data >> 8) & 0x7; + glBlendFunc(aLookup[a], bLookup[b]); + glBlendEquation(eqLookup[eq]); +} + + +void GPU::ExecuteOp(u32 op, u32 diff) +{ + u32 cmd = op >> 24; + u32 data = op & 0xFFFFFF; + + // Handle control and drawing commands here directly. The others we delegate. + switch (cmd) + { + case GE_CMD_BASE: + DEBUG_LOG(G3D,"DL BASE: %06x", data); + break; + + case GE_CMD_VADDR: /// <<8???? + gstate.vertexAddr = (gstate.base<<8)|data; + DEBUG_LOG(G3D,"DL VADDR: %06x", gstate.vertexAddr); + break; + + case GE_CMD_IADDR: + gstate.indexAddr = (gstate.base<<8)|data; + DEBUG_LOG(G3D,"DL IADDR: %06x", gstate.indexAddr); + break; + + case GE_CMD_PRIM: + { + u32 count = data & 0xFFFF; + u32 type = data >> 16; + static const char* types[7] = { + "POINTS=0,", + "LINES=1,", + "LINE_STRIP=2,", + "TRIANGLES=3,", + "TRIANGLE_STRIP=4,", + "TRIANGLE_FAN=5,", + "RECTANGLES=6,", + }; + DEBUG_LOG(G3D, "DL DrawPrim type: %s count: %i vaddr= %08x, iaddr= %08x", type<7 ? types[type] : "INVALID", count, gstate.vertexAddr, gstate.indexAddr); + + LinkedShader *linkedShader = shaderManager.ApplyShader(); + // TODO: Split this so that we can collect sequences of primitives, can greatly speed things up + // on platforms where draw calls are expensive like mobile and D3D + void *verts = Memory::GetPointer(gstate.vertexAddr); + void *inds = 0; + if ((gstate.vertType & GE_VTYPE_IDX_MASK) != GE_VTYPE_IDX_NONE) + inds = Memory::GetPointer(gstate.indexAddr); + TransformAndDrawPrim(verts, inds, type, count, linkedShader); + } + break; + + // The arrow and other rotary items in Puzbob are bezier patches, strangely enough. + case GE_CMD_BEZIER: + { + int bz_ucount = data & 0xFF; + int bz_vcount = (data >> 8) & 0xFF; + drawBezier(bz_ucount, bz_vcount); + DEBUG_LOG(G3D,"DL DRAW BEZIER: %i x %i", bz_ucount, bz_vcount); + } + break; + + case GE_CMD_SPLINE: + { + int sp_ucount = data & 0xFF; + int sp_vcount = (data >> 8) & 0xFF; + int sp_utype = (data >> 16) & 0x3; + int sp_vtype = (data >> 18) & 0x3; + //drawSpline(sp_ucount, sp_vcount, sp_utype, sp_vtype); + DEBUG_LOG(G3D,"DL DRAW SPLINE: %i x %i, %i x %i", sp_ucount, sp_vcount, sp_utype, sp_vtype); + } + break; + + case GE_CMD_JUMP: + { + u32 target = ((gstate.base << 8) | (op & 0xFFFFFC)) & 0x0FFFFFFF; + DEBUG_LOG(G3D,"DL CMD JUMP - %08x to %08x", dcontext.pc, target); + dcontext.pc = target - 4; // pc will be increased after we return, counteract that + } + break; + + case GE_CMD_CALL: + { + u32 retval = dcontext.pc + 4; + stack[stackptr++] = retval; + u32 target = ((gstate.base << 8) | (op & 0xFFFFFC)) & 0xFFFFFFF; + DEBUG_LOG(G3D,"DL CMD CALL - %08x to %08x, ret=%08x", dcontext.pc, target, retval); + dcontext.pc = target - 4; // pc will be increased after we return, counteract that + } + break; + + case GE_CMD_RET: + //TODO : debug! + { + u32 target = stack[--stackptr] & 0xFFFFFFF; + DEBUG_LOG(G3D,"DL CMD RET - from %08x to %08x", dcontext.pc, target); + dcontext.pc = target - 4; + } + break; + + case GE_CMD_SIGNAL: + ERROR_LOG(G3D, "DL GE_CMD_SIGNAL %08x", data & 0xFFFFFF); + { + // int behaviour = (data >> 16) & 0xFF; + // int signal = data & 0xFFFF; + } + + // This should generate a GE Interrupt + // __TriggerInterrupt(PSP_GE_INTR); + + // Apparently, these callbacks should be done in a special interrupt way. + //for (size_t i = 0; i < signalCallbacks.size(); i++) + //{ + // __KernelNotifyCallback(-1, signalCallbacks[i].first, signal); + //} + + break; + + case GE_CMD_BJUMP: + // bounding box jump. Let's just not jump, for now. + DEBUG_LOG(G3D,"DL BBOX JUMP - unimplemented"); + break; + + case GE_CMD_BOUNDINGBOX: + // bounding box test. Let's do nothing. + DEBUG_LOG(G3D,"DL BBOX TEST - unimplemented"); + break; + + case GE_CMD_ORIGIN: + gstate.offsetAddr = dcontext.pc & 0xFFFFFF; + break; + + case GE_CMD_VERTEXTYPE: + DEBUG_LOG(G3D,"DL SetVertexType: %06x", data); + if (diff & GE_VTYPE_THROUGH) { + // Throughmode changed, let's make the proj matrix dirty. + shaderManager.DirtyUniform(DIRTY_PROJMATRIX); + } + if (data & GE_VTYPE_THROUGH) { + glDisable(GL_CULL_FACE); + } + // This sets through-mode or not, as well. + break; + + case GE_CMD_OFFSETADDR: + // offsetAddr = data<<8; + break; + + + case GE_CMD_FINISH: + DEBUG_LOG(G3D,"DL CMD FINISH"); + // Trigger the finish callbacks + { + // Apparently, these callbacks should be done in a special interrupt way. + + //for (size_t i = 0; i < finishCallbacks.size(); i++) + //{ + // __KernelNotifyCallback(-1, finishCallbacks[i].first, 0); + //} + } + break; + + case GE_CMD_END: + DEBUG_LOG(G3D,"DL CMD END"); + { + switch (prev >> 24) + { + case GE_CMD_FINISH: + finished = true; + break; + default: + DEBUG_LOG(G3D,"Ah, not finished: %06x", prev & 0xFFFFFF); + break; + } + } + + // This should generate a Reading Ended interrupt + // __TriggerInterrupt(PSP_GE_INTR); + + break; + + case GE_CMD_REGION1: + { + int x1 = data & 0x3ff; + int y1 = data >> 10; + //topleft + DEBUG_LOG(G3D,"DL Region TL: %d %d", x1, y1); + } + break; + + case GE_CMD_REGION2: + { + int x2 = data & 0x3ff; + int y2 = data >> 10; + DEBUG_LOG(G3D,"DL Region BR: %d %d", x2, y2); + } + break; + + case GE_CMD_CLIPENABLE: + DEBUG_LOG(G3D, "DL Clip Enable: %i (ignoring)", data); + //we always clip, this is opengl + break; + + case GE_CMD_CULLFACEENABLE: + DEBUG_LOG(G3D, "DL CullFace Enable: %i (ignoring)", data); + glEnDis(GL_CULL_FACE, data&1); + break; + + case GE_CMD_TEXTUREMAPENABLE: + DEBUG_LOG(G3D, "DL Texture map enable: %i", data); + glEnDis(GL_TEXTURE_2D, data&1); + break; + + case GE_CMD_LIGHTINGENABLE: + DEBUG_LOG(G3D, "DL Lighting enable: %i", data); + data += 1; + //We don't use OpenGL lighting + break; + + case GE_CMD_FOGENABLE: + DEBUG_LOG(G3D, "DL Fog Enable: %i", gstate.fogEnable); + break; + + case GE_CMD_DITHERENABLE: + DEBUG_LOG(G3D, "DL Dither Enable: %i", gstate.ditherEnable); + break; + + case GE_CMD_OFFSETX: + DEBUG_LOG(G3D, "DL Offset X: %i", gstate.offsetx); + break; + + case GE_CMD_OFFSETY: + DEBUG_LOG(G3D, "DL Offset Y: %i", gstate.offsety); + break; + + case GE_CMD_TEXSCALEU: + gstate.uScale = getFloat24(data); + DEBUG_LOG(G3D, "DL Texture U Scale: %f", gstate.uScale); + break; + + case GE_CMD_TEXSCALEV: + gstate.vScale = getFloat24(data); + DEBUG_LOG(G3D, "DL Texture V Scale: %f", gstate.vScale); + break; + + case GE_CMD_TEXOFFSETU: + gstate.uOff = getFloat24(data); + DEBUG_LOG(G3D, "DL Texture U Offset: %f", gstate.uOff); + break; + + case GE_CMD_TEXOFFSETV: + gstate.vOff = getFloat24(data); + DEBUG_LOG(G3D, "DL Texture V Offset: %f", gstate.vOff); + break; + + case GE_CMD_SCISSOR1: + { + int x1 = data & 0x3ff; + int y1 = data >> 10; + DEBUG_LOG(G3D, "DL Scissor TL: %i, %i", x1,y1); + } + break; + case GE_CMD_SCISSOR2: + { + int x2 = data & 0x3ff; + int y2 = data >> 10; + DEBUG_LOG(G3D, "DL Scissor BR: %i, %i", x2, y2); + } + break; + + case GE_CMD_MINZ: + DEBUG_LOG(G3D, "DL MinZ: %i", data); + break; + + case GE_CMD_MAXZ: + DEBUG_LOG(G3D, "DL MaxZ: %i", data); + break; + + case GE_CMD_FRAMEBUFPTR: + { + u32 ptr = op & 0xFFE000; + DEBUG_LOG(G3D, "DL FramebufPtr: %08x", ptr); + } + break; + + case GE_CMD_FRAMEBUFWIDTH: + { + u32 w = data & 0xFFFFFF; + DEBUG_LOG(G3D, "DL FramebufWidth: %i", w); + } + break; + + case GE_CMD_FRAMEBUFPIXFORMAT: + break; + + case GE_CMD_TEXADDR0: + gstate.textureChanged=true; + case GE_CMD_TEXADDR1: + case GE_CMD_TEXADDR2: + case GE_CMD_TEXADDR3: + case GE_CMD_TEXADDR4: + case GE_CMD_TEXADDR5: + case GE_CMD_TEXADDR6: + case GE_CMD_TEXADDR7: + DEBUG_LOG(G3D,"DL Texture address %i: %06x", cmd-GE_CMD_TEXADDR0, data); + break; + + case GE_CMD_TEXBUFWIDTH0: + gstate.textureChanged=true; + case GE_CMD_TEXBUFWIDTH1: + case GE_CMD_TEXBUFWIDTH2: + case GE_CMD_TEXBUFWIDTH3: + case GE_CMD_TEXBUFWIDTH4: + case GE_CMD_TEXBUFWIDTH5: + case GE_CMD_TEXBUFWIDTH6: + case GE_CMD_TEXBUFWIDTH7: + DEBUG_LOG(G3D,"DL Texture BUFWIDTHess %i: %06x", cmd-GE_CMD_TEXBUFWIDTH0, data); + break; + + case GE_CMD_CLUTADDR: + //DEBUG_LOG(G3D,"CLUT base addr: %06x", data); + break; + + case GE_CMD_CLUTADDRUPPER: + DEBUG_LOG(G3D,"DL CLUT addr: %08x", ((gstate.clutaddrupper & 0xFF0000)<<8) | (gstate.clutaddr & 0xFFFFFF)); + break; + + case GE_CMD_LOADCLUT: + { + u32 clutAttr = ((gstate.clutaddrupper & 0xFF0000)<<8) | (gstate.clutaddr & 0xFFFFFF); + if (clutAttr) + { + u16 *clut = (u16*)Memory::GetPointer(clutAttr); + if (clut) { + int numColors = 16 * (data&0x3F); + memcpy(&gstate.paletteMem[0], clut, numColors * 2); + } + DEBUG_LOG(G3D,"DL Clut load: %i palettes", data); + } + else + { + DEBUG_LOG(G3D,"DL Empty Clut load"); + } + // Should hash and invalidate all paletted textures on use + } + break; + +// case GE_CMD_TRANSFERSRC: + + case GE_CMD_TRANSFERSRCW: + { + u32 xferSrc = gstate.transfersrc | ((data&0xFF0000)<<8); + u32 xferSrcW = gstate.transfersrcw & 1023; + DEBUG_LOG(G3D,"Block Transfer Src: %08x W: %i", xferSrc, xferSrcW); + break; + } +// case GE_CMD_TRANSFERDST: + + case GE_CMD_TRANSFERDSTW: + { + u32 xferDst= gstate.transferdst | ((data&0xFF0000)<<8); + u32 xferDstW = gstate.transferdstw & 1023; + DEBUG_LOG(G3D,"Block Transfer Dest: %08x W: %i", xferDst, xferDstW); + break; + } + + case GE_CMD_TRANSFERSRCPOS: + { + u32 x = (data & 1023)+1; + u32 y = ((data>>10) & 1023)+1; + DEBUG_LOG(G3D, "DL Block Transfer Src Rect TL: %i, %i", x, y); + break; + } + + case GE_CMD_TRANSFERDSTPOS: + { + u32 x = (data & 1023)+1; + u32 y = ((data>>10) & 1023)+1; + DEBUG_LOG(G3D, "DL Block Transfer Dest Rect TL: %i, %i", x, y); + break; + } + + case GE_CMD_TRANSFERSIZE: + { + u32 w = (data & 1023)+1; + u32 h = ((data>>10) & 1023)+1; + DEBUG_LOG(G3D, "DL Block Transfer Rect Size: %i x %i", w, h); + break; + } + + case GE_CMD_TRANSFERSTART: + { + DEBUG_LOG(G3D, "DL Texture Transfer Start: PixFormat %i", data); + // TODO: Here we should check if the transfer overlaps a framebuffer or any textures, + // and take appropriate action. If not, this should just be a block transfer within + // GPU memory which could be implemented by a copy loop. + break; + } + + case GE_CMD_TEXSIZE0: + gstate.textureChanged=true; + gstate.curTextureWidth = 1 << (gstate.texsize[0] & 0xf); + gstate.curTextureHeight = 1 << ((gstate.texsize[0]>>8) & 0xf); + //fall thru - ignoring the mipmap sizes for now + case GE_CMD_TEXSIZE1: + case GE_CMD_TEXSIZE2: + case GE_CMD_TEXSIZE3: + case GE_CMD_TEXSIZE4: + case GE_CMD_TEXSIZE5: + case GE_CMD_TEXSIZE6: + case GE_CMD_TEXSIZE7: + DEBUG_LOG(G3D,"DL Texture Size: %06x", data); + break; + + case GE_CMD_ZBUFPTR: + { + u32 ptr = op & 0xFFE000; + DEBUG_LOG(G3D,"Zbuf Ptr: %06x", ptr); + } + break; + + case GE_CMD_ZBUFWIDTH: + { + u32 w = data & 0xFFFFFF; + DEBUG_LOG(G3D,"Zbuf Width: %i", w); + } + break; + + case GE_CMD_AMBIENTCOLOR: + DEBUG_LOG(G3D,"DL Ambient Color: %06x", data); + break; + + case GE_CMD_AMBIENTALPHA: + DEBUG_LOG(G3D,"DL Ambient Alpha: %06x", data); + break; + + case GE_CMD_MATERIALAMBIENT: + DEBUG_LOG(G3D,"DL Material Ambient Color: %06x", data); + break; + + case GE_CMD_MATERIALDIFFUSE: + DEBUG_LOG(G3D,"DL Material Diffuse Color: %06x", data); + break; + + case GE_CMD_MATERIALEMISSIVE: + DEBUG_LOG(G3D,"DL Material Emissive Color: %06x", data); + break; + + case GE_CMD_MATERIALSPECULAR: + DEBUG_LOG(G3D,"DL Material Specular Color: %06x", data); + break; + + case GE_CMD_MATERIALALPHA: + DEBUG_LOG(G3D,"DL Material Alpha Color: %06x", data); + break; + + case GE_CMD_MATERIALSPECULARCOEF: + DEBUG_LOG(G3D,"DL Material specular coef: %f", getFloat24(data)); + break; + + case GE_CMD_LIGHTTYPE0: + case GE_CMD_LIGHTTYPE1: + case GE_CMD_LIGHTTYPE2: + case GE_CMD_LIGHTTYPE3: + DEBUG_LOG(G3D,"DL Light %i type: %06x", cmd-GE_CMD_LIGHTTYPE0, data); + break; + + case GE_CMD_LX0:case GE_CMD_LY0:case GE_CMD_LZ0: + case GE_CMD_LX1:case GE_CMD_LY1:case GE_CMD_LZ1: + case GE_CMD_LX2:case GE_CMD_LY2:case GE_CMD_LZ2: + case GE_CMD_LX3:case GE_CMD_LY3:case GE_CMD_LZ3: + { + int n = cmd - GE_CMD_LX0; + int l = n / 3; + int c = n % 3; + float val = getFloat24(data); + DEBUG_LOG(G3D,"DL Light %i %c pos: %f", l, c+'X', val); + gstate.lightpos[l][c] = val; + } + break; + + case GE_CMD_LDX0:case GE_CMD_LDY0:case GE_CMD_LDZ0: + case GE_CMD_LDX1:case GE_CMD_LDY1:case GE_CMD_LDZ1: + case GE_CMD_LDX2:case GE_CMD_LDY2:case GE_CMD_LDZ2: + case GE_CMD_LDX3:case GE_CMD_LDY3:case GE_CMD_LDZ3: + { + int n = cmd - GE_CMD_LDX0; + int l = n / 3; + int c = n % 3; + float val = getFloat24(data); + DEBUG_LOG(G3D,"DL Light %i %c dir: %f", l, c+'X', val); + gstate.lightdir[l][c] = val; + } + break; + + case GE_CMD_LKA0:case GE_CMD_LKB0:case GE_CMD_LKC0: + case GE_CMD_LKA1:case GE_CMD_LKB1:case GE_CMD_LKC1: + case GE_CMD_LKA2:case GE_CMD_LKB2:case GE_CMD_LKC2: + case GE_CMD_LKA3:case GE_CMD_LKB3:case GE_CMD_LKC3: + { + int n = cmd - GE_CMD_LKA0; + int l = n / 3; + int c = n % 3; + float val = getFloat24(data); + DEBUG_LOG(G3D,"DL Light %i %c att: %f", l, c+'X', val); + gstate.lightatt[l][c] = val; + } + break; + + + case GE_CMD_LAC0:case GE_CMD_LAC1:case GE_CMD_LAC2:case GE_CMD_LAC3: + case GE_CMD_LDC0:case GE_CMD_LDC1:case GE_CMD_LDC2:case GE_CMD_LDC3: + case GE_CMD_LSC0:case GE_CMD_LSC1:case GE_CMD_LSC2:case GE_CMD_LSC3: + { + float r = (float)(data>>16)/255.0f; + float g = (float)((data>>8) & 0xff)/255.0f; + float b = (float)(data & 0xff)/255.0f; + + int l = (cmd - GE_CMD_LAC0) / 3; + int t = (cmd - GE_CMD_LAC0) % 3; + gstate.lightColor[t][l].r = r; + gstate.lightColor[t][l].g = g; + gstate.lightColor[t][l].b = b; + } + break; + + case GE_CMD_VIEWPORTX1: + case GE_CMD_VIEWPORTY1: + case GE_CMD_VIEWPORTZ1: + case GE_CMD_VIEWPORTX2: + case GE_CMD_VIEWPORTY2: + case GE_CMD_VIEWPORTZ2: + DEBUG_LOG(G3D,"DL Viewport param %i: %f", cmd-GE_CMD_VIEWPORTX1, getFloat24(data)); + break; + case GE_CMD_LIGHTENABLE0: + case GE_CMD_LIGHTENABLE1: + case GE_CMD_LIGHTENABLE2: + case GE_CMD_LIGHTENABLE3: + DEBUG_LOG(G3D,"DL Light %i enable: %d", cmd-GE_CMD_LIGHTENABLE0, data); + break; + case GE_CMD_CULL: + DEBUG_LOG(G3D,"DL cull: %06x", data); + glCullFace(data ? GL_BACK : GL_FRONT); + break; + + case GE_CMD_LMODE: + DEBUG_LOG(G3D,"DL Shade mode: %06x", data); + break; + + case GE_CMD_PATCHDIVISION: + gstate.patch_div_s = data & 0xFF; + gstate.patch_div_t = (data >> 8) & 0xFF; + DEBUG_LOG(G3D, "DL Patch subdivision: %i x %i", gstate.patch_div_s, gstate.patch_div_t); + break; + + case GE_CMD_MATERIALUPDATE: + DEBUG_LOG(G3D,"DL Material Update: %d", data); + break; + + + ////////////////////////////////////////////////////////////////// + // CLEARING + ////////////////////////////////////////////////////////////////// + case GE_CMD_CLEARMODE: + // If it becomes a performance problem, check diff&1 + if (data & 1) + EnterClearMode(data); + else + LeaveClearMode(); + DEBUG_LOG(G3D,"DL Clear mode: %06x", data); + break; + + + ////////////////////////////////////////////////////////////////// + // ALPHA BLENDING + ////////////////////////////////////////////////////////////////// + case GE_CMD_ALPHABLENDENABLE: + DEBUG_LOG(G3D,"DL Alpha blend enable: %d", data); + glEnDis(GL_BLEND, data); + break; + + case GE_CMD_BLENDMODE: + DEBUG_LOG(G3D,"DL Blend mode: %06x", data); + SetBlendModePSP(data); + break; + + case GE_CMD_BLENDFIXEDA: + DEBUG_LOG(G3D,"DL Blend fix A: %06x", data); + break; + + case GE_CMD_BLENDFIXEDB: + DEBUG_LOG(G3D,"DL Blend fix B: %06x", data); + break; + + case GE_CMD_ALPHATESTENABLE: + DEBUG_LOG(G3D,"DL Alpha test enable: %d", data); + // This is done in the shader. + break; + + case GE_CMD_ALPHATEST: + DEBUG_LOG(G3D,"DL Alpha test settings"); + shaderManager.DirtyUniform(DIRTY_ALPHAREF); + break; + + case GE_CMD_TEXFUNC: + { + DEBUG_LOG(G3D,"DL TexFunc %i", data&7); + /* + int m=GL_MODULATE; + switch (data & 7) + { + case 0: m=GL_MODULATE; break; + case 1: m=GL_DECAL; break; + case 2: m=GL_BLEND; break; + case 3: m=GL_REPLACE; break; + case 4: m=GL_ADD; break; + }*/ + + /* + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_CONSTANT); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE, 1); + + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, m); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE);*/ + break; + } + case GE_CMD_TEXFILTER: + { + int min = data & 7; + int mag = (data >> 8) & 1; + DEBUG_LOG(G3D,"DL TexFilter min: %i mag: %i", min, mag); + } + + break; + ////////////////////////////////////////////////////////////////// + // Z/STENCIL TESTING + ////////////////////////////////////////////////////////////////// + + case GE_CMD_ZTESTENABLE: + glEnDis(GL_DEPTH_TEST, data & 1); + DEBUG_LOG(G3D,"DL Z test enable: %d", data & 1); + break; + + case GE_CMD_STENCILTESTENABLE: + DEBUG_LOG(G3D,"DL Stencil test enable: %d", data); + break; + + case GE_CMD_ZTEST: + { + static const GLuint ztests[8] = + { + GL_NEVER, GL_ALWAYS, GL_EQUAL, GL_NOTEQUAL, + GL_LESS, GL_LEQUAL, GL_GREATER, GL_GEQUAL + }; + //glDepthFunc(ztests[data&7]); + glDepthFunc(GL_LEQUAL); + DEBUG_LOG(G3D,"DL Z test mode: %i", data); + } + break; + + case GE_CMD_MORPHWEIGHT0: + case GE_CMD_MORPHWEIGHT1: + case GE_CMD_MORPHWEIGHT2: + case GE_CMD_MORPHWEIGHT3: + case GE_CMD_MORPHWEIGHT4: + case GE_CMD_MORPHWEIGHT5: + case GE_CMD_MORPHWEIGHT6: + case GE_CMD_MORPHWEIGHT7: + { + int index = cmd - GE_CMD_MORPHWEIGHT0; + float weight = getFloat24(data); + DEBUG_LOG(G3D,"DL MorphWeight %i = %f", index, weight); + gstate.morphWeights[index] = weight; + } + break; + + case GE_CMD_DITH0: + case GE_CMD_DITH1: + case GE_CMD_DITH2: + case GE_CMD_DITH3: + DEBUG_LOG(G3D,"DL DitherMatrix %i = %06x",cmd-GE_CMD_DITH0,data); + break; + + case GE_CMD_WORLDMATRIXNUMBER: + DEBUG_LOG(G3D,"DL World matrix # %i", data); + gstate.worldmtxnum = data&0xF; + break; + + case GE_CMD_WORLDMATRIXDATA: + DEBUG_LOG(G3D,"DL World matrix data # %f", getFloat24(data)); + gstate.worldMatrix[gstate.worldmtxnum++] = getFloat24(data); + break; + + case GE_CMD_VIEWMATRIXNUMBER: + DEBUG_LOG(G3D,"DL VIEW matrix # %i", data); + gstate.viewmtxnum = data&0xF; + break; + + case GE_CMD_VIEWMATRIXDATA: + DEBUG_LOG(G3D,"DL VIEW matrix data # %f", getFloat24(data)); + gstate.viewMatrix[gstate.viewmtxnum++] = getFloat24(data); + break; + + case GE_CMD_PROJMATRIXNUMBER: + DEBUG_LOG(G3D,"DL PROJECTION matrix # %i", data); + gstate.projmtxnum = data&0xF; + break; + + case GE_CMD_PROJMATRIXDATA: + DEBUG_LOG(G3D,"DL PROJECTION matrix data # %f", getFloat24(data)); + gstate.projMatrix[gstate.projmtxnum++] = getFloat24(data); + shaderManager.DirtyUniform(DIRTY_PROJMATRIX); + break; + + case GE_CMD_TGENMATRIXNUMBER: + DEBUG_LOG(G3D,"DL TGEN matrix # %i", data); + gstate.texmtxnum = data&0xF; + break; + + case GE_CMD_TGENMATRIXDATA: + DEBUG_LOG(G3D,"DL TGEN matrix data # %f", getFloat24(data)); + gstate.tgenMatrix[gstate.texmtxnum++] = getFloat24(data); + break; + + case GE_CMD_BONEMATRIXNUMBER: + DEBUG_LOG(G3D,"DL BONE matrix #%i", data); + gstate.boneMatrixNumber = data; + break; + + case GE_CMD_BONEMATRIXDATA: + DEBUG_LOG(G3D,"DL BONE matrix data #%i %f", gstate.boneMatrixNumber, getFloat24(data)); + gstate.boneMatrix[gstate.boneMatrixNumber++] = getFloat24(data); + break; + + default: + DEBUG_LOG(G3D,"DL Unknown: %08x @ %08x", op, dcontext.pc); + break; + + //ETC... + } +} + +bool GPU::InterpretList() +{ + // Reset stackptr for safety + stackptr = 0; + u32 op = 0; + prev = 0; + finished = false; + while (!finished) + { + if (dcontext.pc == dcontext.stallAddr) + return false; + + op = Memory::ReadUnchecked_U32(dcontext.pc); //read from memory + u32 cmd = op >> 24; + u32 diff = op ^ gstate.cmdmem[cmd]; + gstate.cmdmem[cmd] = op; // crashes if I try to put the whole op there?? + + ExecuteOp(op, diff); + + dcontext.pc += 4; + prev = op; + } + return true; +} diff --git a/Core/HLE/sceKernelCallback.h b/GPU/Null/NullDisplayListInterpreter.h similarity index 57% rename from Core/HLE/sceKernelCallback.h rename to GPU/Null/NullDisplayListInterpreter.h index c7bc779e1c..dc83dacb59 100644 --- a/Core/HLE/sceKernelCallback.h +++ b/GPU/Null/NullDisplayListInterpreter.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -17,17 +17,15 @@ #pragma once -#include "Action.h" +#include "../../Globals.h" -// Internal access - used by sceSetGeCallback -u32 __KernelCreateCallback(const char *name, u32 entrypoint, u32 signalArg, Action *actionAfter = 0); +class ShaderManager; -void sceKernelCreateCallback(); -void sceKernelDeleteCallback(); -void sceKernelNotifyCallback(); -void sceKernelCancelCallback(); -void sceKernelGetCallbackCount(); -void _sceKernelReturnFromCallback(); -void sceKernelCheckCallback(); -void sceKernelGetCallbackCount(); -void sceKernelReferCallbackStatus(); \ No newline at end of file +class GPU +{ +public: + static u32 EnqueueList(u32 listpc, u32 stall); + static void UpdateStall(int listid, u32 newstall); + static void ExecuteOp(u32 op, u32 diff); + static bool InterpretList(); +}; diff --git a/GPU/Null/NullGpu.cpp b/GPU/Null/NullGpu.cpp new file mode 100644 index 0000000000..c9cff19f3c --- /dev/null +++ b/GPU/Null/NullGpu.cpp @@ -0,0 +1,827 @@ +// Copyright (c) 2012- PPSSPP Project. + +// 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, version 2.0 or later versions. + +// 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 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + + +#include "NullGpu.h" +#include "../GPUState.h" +#include "../ge_constants.h" +#include "../../Core/MemMap.h" +#include "../../Core/HLE/sceKernelInterrupt.h" + +struct DisplayState +{ + u32 pc; + u32 stallAddr; +}; + +static DisplayState dcontext; + +struct DisplayList +{ + int id; + u32 listpc; + u32 stall; +}; + +static std::vector dlQueue; + +static u32 prev; +static u32 stack[2]; +static u32 stackptr = 0; +static bool finished; + +static int dlIdGenerator = 1; + +bool NullGPU::ProcessDLQueue() +{ + std::vector::iterator iter = dlQueue.begin(); + while (!(iter == dlQueue.end())) + { + DisplayList &l = *iter; + dcontext.pc = l.listpc; + dcontext.stallAddr = l.stall; +// DEBUG_LOG(G3D,"Okay, starting DL execution at %08 - stall = %08x", context.pc, stallAddr); + if (!InterpretList()) + { + l.listpc = dcontext.pc; + l.stall = dcontext.stallAddr; + return false; + } + else + { + //At the end, we can remove it from the queue and continue + dlQueue.erase(iter); + //this invalidated the iterator, let's fix it + iter = dlQueue.begin(); + } + } + return true; //no more lists! +} + +u32 NullGPU::EnqueueList(u32 listpc, u32 stall) +{ + DisplayList dl; + dl.id = dlIdGenerator++; + dl.listpc = listpc&0xFFFFFFF; + dl.stall = stall&0xFFFFFFF; + dlQueue.push_back(dl); + if (!ProcessDLQueue()) + return dl.id; + else + return 0; +} + +void NullGPU::UpdateStall(int listid, u32 newstall) +{ + // this needs improvement.... + for (std::vector::iterator iter = dlQueue.begin(); iter != dlQueue.end(); iter++) + { + DisplayList &l = *iter; + if (l.id == listid) + { + l.stall = newstall & 0xFFFFFFF; + } + } + + ProcessDLQueue(); +} + +void NullGPU::DrawSync(int mode) +{ + if (mode == 0) // Wait for completion + { + __RunOnePendingInterrupt(); + } +} + +void NullGPU::ExecuteOp(u32 op, u32 diff) +{ + u32 cmd = op >> 24; + u32 data = op & 0xFFFFFF; + + // Handle control and drawing commands here directly. The others we delegate. + switch (cmd) + { + case GE_CMD_BASE: + DEBUG_LOG(G3D,"DL BASE: %06x", data); + break; + + case GE_CMD_VADDR: /// <<8???? + gstate.vertexAddr = ((gstate.base & 0x00FF0000) << 8)|data; + DEBUG_LOG(G3D,"DL VADDR: %06x", gstate.vertexAddr); + break; + + case GE_CMD_IADDR: + gstate.indexAddr = ((gstate.base & 0x00FF0000) << 8)|data; + DEBUG_LOG(G3D,"DL IADDR: %06x", gstate.indexAddr); + break; + + case GE_CMD_PRIM: + { + u32 count = data & 0xFFFF; + u32 type = data >> 16; + static const char* types[7] = { + "POINTS=0,", + "LINES=1,", + "LINE_STRIP=2,", + "TRIANGLES=3,", + "TRIANGLE_STRIP=4,", + "TRIANGLE_FAN=5,", + "RECTANGLES=6,", + }; + DEBUG_LOG(G3D, "DL DrawPrim type: %s count: %i vaddr= %08x, iaddr= %08x", type<7 ? types[type] : "INVALID", count, gstate.vertexAddr, gstate.indexAddr); + } + break; + + // The arrow and other rotary items in Puzbob are bezier patches, strangely enough. + case GE_CMD_BEZIER: + { + int bz_ucount = data & 0xFF; + int bz_vcount = (data >> 8) & 0xFF; + DEBUG_LOG(G3D,"DL DRAW BEZIER: %i x %i", bz_ucount, bz_vcount); + } + break; + + case GE_CMD_SPLINE: + { + int sp_ucount = data & 0xFF; + int sp_vcount = (data >> 8) & 0xFF; + int sp_utype = (data >> 16) & 0x3; + int sp_vtype = (data >> 18) & 0x3; + //drawSpline(sp_ucount, sp_vcount, sp_utype, sp_vtype); + DEBUG_LOG(G3D,"DL DRAW SPLINE: %i x %i, %i x %i", sp_ucount, sp_vcount, sp_utype, sp_vtype); + } + break; + + case GE_CMD_JUMP: + { + u32 target = (((gstate.base & 0x00FF0000) << 8) | (op & 0xFFFFFC)) & 0x0FFFFFFF; + DEBUG_LOG(G3D,"DL CMD JUMP - %08x to %08x", dcontext.pc, target); + dcontext.pc = target - 4; // pc will be increased after we return, counteract that + } + break; + + case GE_CMD_CALL: + { + u32 retval = dcontext.pc + 4; + stack[stackptr++] = retval; + u32 target = (((gstate.base & 0x00FF0000) << 8) | (op & 0xFFFFFC)) & 0xFFFFFFF; + DEBUG_LOG(G3D,"DL CMD CALL - %08x to %08x, ret=%08x", dcontext.pc, target, retval); + dcontext.pc = target - 4; // pc will be increased after we return, counteract that + } + break; + + case GE_CMD_RET: + //TODO : debug! + { + u32 target = stack[--stackptr] & 0xFFFFFFF; + DEBUG_LOG(G3D,"DL CMD RET - from %08x to %08x", dcontext.pc, target); + dcontext.pc = target - 4; + } + break; + + case GE_CMD_SIGNAL: + { + ERROR_LOG(G3D, "DL GE_CMD_SIGNAL %08x", data & 0xFFFFFF); + int behaviour = (data >> 16) & 0xFF; + int signal = data & 0xFFFF; + + __TriggerInterruptWithArg(PSP_GE_INTR, PSP_GE_SUBINTR_SIGNAL, signal); + } + break; + + case GE_CMD_BJUMP: + // bounding box jump. Let's just not jump, for now. + DEBUG_LOG(G3D,"DL BBOX JUMP - unimplemented"); + break; + + case GE_CMD_BOUNDINGBOX: + // bounding box test. Let's do nothing. + DEBUG_LOG(G3D,"DL BBOX TEST - unimplemented"); + break; + + case GE_CMD_ORIGIN: + gstate.offsetAddr = dcontext.pc & 0xFFFFFF; + break; + + case GE_CMD_VERTEXTYPE: + DEBUG_LOG(G3D,"DL SetVertexType: %06x", data); + // This sets through-mode or not, as well. + break; + + case GE_CMD_OFFSETADDR: + // offsetAddr = data<<8; + break; + + + case GE_CMD_FINISH: + DEBUG_LOG(G3D,"DL CMD FINISH"); + __TriggerInterruptWithArg(PSP_GE_INTR, PSP_GE_SUBINTR_FINISH, 0); + break; + + case GE_CMD_END: + DEBUG_LOG(G3D,"DL CMD END"); + { + switch (prev >> 24) + { + case GE_CMD_FINISH: + finished = true; + break; + default: + DEBUG_LOG(G3D,"Ah, not finished: %06x", prev & 0xFFFFFF); + break; + } + } + + // This should generate a Reading Ended interrupt + // __TriggerInterrupt(PSP_GE_INTR); + + break; + + case GE_CMD_REGION1: + { + int x1 = data & 0x3ff; + int y1 = data >> 10; + //topleft + DEBUG_LOG(G3D,"DL Region TL: %d %d", x1, y1); + } + break; + + case GE_CMD_REGION2: + { + int x2 = data & 0x3ff; + int y2 = data >> 10; + DEBUG_LOG(G3D,"DL Region BR: %d %d", x2, y2); + } + break; + + case GE_CMD_CLIPENABLE: + DEBUG_LOG(G3D, "DL Clip Enable: %i (ignoring)", data); + //we always clip, this is opengl + break; + + case GE_CMD_CULLFACEENABLE: + DEBUG_LOG(G3D, "DL CullFace Enable: %i (ignoring)", data); + break; + + case GE_CMD_TEXTUREMAPENABLE: + DEBUG_LOG(G3D, "DL Texture map enable: %i", data); + break; + + case GE_CMD_LIGHTINGENABLE: + DEBUG_LOG(G3D, "DL Lighting enable: %i", data); + data += 1; + //We don't use OpenGL lighting + break; + + case GE_CMD_FOGENABLE: + DEBUG_LOG(G3D, "DL Fog Enable: %i", gstate.fogEnable); + break; + + case GE_CMD_DITHERENABLE: + DEBUG_LOG(G3D, "DL Dither Enable: %i", gstate.ditherEnable); + break; + + case GE_CMD_OFFSETX: + DEBUG_LOG(G3D, "DL Offset X: %i", gstate.offsetx); + break; + + case GE_CMD_OFFSETY: + DEBUG_LOG(G3D, "DL Offset Y: %i", gstate.offsety); + break; + + case GE_CMD_TEXSCALEU: + gstate.uScale = getFloat24(data); + DEBUG_LOG(G3D, "DL Texture U Scale: %f", gstate.uScale); + break; + + case GE_CMD_TEXSCALEV: + gstate.vScale = getFloat24(data); + DEBUG_LOG(G3D, "DL Texture V Scale: %f", gstate.vScale); + break; + + case GE_CMD_TEXOFFSETU: + gstate.uOff = getFloat24(data); + DEBUG_LOG(G3D, "DL Texture U Offset: %f", gstate.uOff); + break; + + case GE_CMD_TEXOFFSETV: + gstate.vOff = getFloat24(data); + DEBUG_LOG(G3D, "DL Texture V Offset: %f", gstate.vOff); + break; + + case GE_CMD_SCISSOR1: + { + int x1 = data & 0x3ff; + int y1 = data >> 10; + DEBUG_LOG(G3D, "DL Scissor TL: %i, %i", x1,y1); + } + break; + case GE_CMD_SCISSOR2: + { + int x2 = data & 0x3ff; + int y2 = data >> 10; + DEBUG_LOG(G3D, "DL Scissor BR: %i, %i", x2, y2); + } + break; + + case GE_CMD_MINZ: + DEBUG_LOG(G3D, "DL MinZ: %i", data); + break; + + case GE_CMD_MAXZ: + DEBUG_LOG(G3D, "DL MaxZ: %i", data); + break; + + case GE_CMD_FRAMEBUFPTR: + { + u32 ptr = op & 0xFFE000; + DEBUG_LOG(G3D, "DL FramebufPtr: %08x", ptr); + } + break; + + case GE_CMD_FRAMEBUFWIDTH: + { + u32 w = data & 0xFFFFFF; + DEBUG_LOG(G3D, "DL FramebufWidth: %i", w); + } + break; + + case GE_CMD_FRAMEBUFPIXFORMAT: + break; + + case GE_CMD_TEXADDR0: + gstate.textureChanged=true; + case GE_CMD_TEXADDR1: + case GE_CMD_TEXADDR2: + case GE_CMD_TEXADDR3: + case GE_CMD_TEXADDR4: + case GE_CMD_TEXADDR5: + case GE_CMD_TEXADDR6: + case GE_CMD_TEXADDR7: + DEBUG_LOG(G3D,"DL Texture address %i: %06x", cmd-GE_CMD_TEXADDR0, data); + break; + + case GE_CMD_TEXBUFWIDTH0: + gstate.textureChanged=true; + case GE_CMD_TEXBUFWIDTH1: + case GE_CMD_TEXBUFWIDTH2: + case GE_CMD_TEXBUFWIDTH3: + case GE_CMD_TEXBUFWIDTH4: + case GE_CMD_TEXBUFWIDTH5: + case GE_CMD_TEXBUFWIDTH6: + case GE_CMD_TEXBUFWIDTH7: + DEBUG_LOG(G3D,"DL Texture BUFWIDTHess %i: %06x", cmd-GE_CMD_TEXBUFWIDTH0, data); + break; + + case GE_CMD_CLUTADDR: + //DEBUG_LOG(G3D,"CLUT base addr: %06x", data); + break; + + case GE_CMD_CLUTADDRUPPER: + DEBUG_LOG(G3D,"DL CLUT addr: %08x", ((gstate.clutaddrupper & 0xFF0000)<<8) | (gstate.clutaddr & 0xFFFFFF)); + break; + + case GE_CMD_LOADCLUT: + { + u32 clutAttr = ((gstate.clutaddrupper & 0xFF0000)<<8) | (gstate.clutaddr & 0xFFFFFF); + if (clutAttr) + { + u16 *clut = (u16*)Memory::GetPointer(clutAttr); + if (clut) { + int numColors = 16 * (data&0x3F); + memcpy(&gstate.paletteMem[0], clut, numColors * 2); + } + DEBUG_LOG(G3D,"DL Clut load: %i palettes", data); + } + else + { + DEBUG_LOG(G3D,"DL Empty Clut load"); + } + // Should hash and invalidate all paletted textures on use + } + break; + +// case GE_CMD_TRANSFERSRC: + + case GE_CMD_TRANSFERSRCW: + { + u32 xferSrc = gstate.transfersrc | ((data&0xFF0000)<<8); + u32 xferSrcW = gstate.transfersrcw & 1023; + DEBUG_LOG(G3D,"Block Transfer Src: %08x W: %i", xferSrc, xferSrcW); + break; + } +// case GE_CMD_TRANSFERDST: + + case GE_CMD_TRANSFERDSTW: + { + u32 xferDst= gstate.transferdst | ((data&0xFF0000)<<8); + u32 xferDstW = gstate.transferdstw & 1023; + DEBUG_LOG(G3D,"Block Transfer Dest: %08x W: %i", xferDst, xferDstW); + break; + } + + case GE_CMD_TRANSFERSRCPOS: + { + u32 x = (data & 1023)+1; + u32 y = ((data>>10) & 1023)+1; + DEBUG_LOG(G3D, "DL Block Transfer Src Rect TL: %i, %i", x, y); + break; + } + + case GE_CMD_TRANSFERDSTPOS: + { + u32 x = (data & 1023)+1; + u32 y = ((data>>10) & 1023)+1; + DEBUG_LOG(G3D, "DL Block Transfer Dest Rect TL: %i, %i", x, y); + break; + } + + case GE_CMD_TRANSFERSIZE: + { + u32 w = (data & 1023)+1; + u32 h = ((data>>10) & 1023)+1; + DEBUG_LOG(G3D, "DL Block Transfer Rect Size: %i x %i", w, h); + break; + } + + case GE_CMD_TRANSFERSTART: + { + DEBUG_LOG(G3D, "DL Texture Transfer Start: PixFormat %i", data); + // TODO: Here we should check if the transfer overlaps a framebuffer or any textures, + // and take appropriate action. If not, this should just be a block transfer within + // GPU memory which could be implemented by a copy loop. + break; + } + + case GE_CMD_TEXSIZE0: + gstate.textureChanged=true; + gstate.curTextureWidth = 1 << (gstate.texsize[0] & 0xf); + gstate.curTextureHeight = 1 << ((gstate.texsize[0]>>8) & 0xf); + //fall thru - ignoring the mipmap sizes for now + case GE_CMD_TEXSIZE1: + case GE_CMD_TEXSIZE2: + case GE_CMD_TEXSIZE3: + case GE_CMD_TEXSIZE4: + case GE_CMD_TEXSIZE5: + case GE_CMD_TEXSIZE6: + case GE_CMD_TEXSIZE7: + DEBUG_LOG(G3D,"DL Texture Size: %06x", data); + break; + + case GE_CMD_ZBUFPTR: + { + u32 ptr = op & 0xFFE000; + DEBUG_LOG(G3D,"Zbuf Ptr: %06x", ptr); + } + break; + + case GE_CMD_ZBUFWIDTH: + { + u32 w = data & 0xFFFFFF; + DEBUG_LOG(G3D,"Zbuf Width: %i", w); + } + break; + + case GE_CMD_AMBIENTCOLOR: + DEBUG_LOG(G3D,"DL Ambient Color: %06x", data); + break; + + case GE_CMD_AMBIENTALPHA: + DEBUG_LOG(G3D,"DL Ambient Alpha: %06x", data); + break; + + case GE_CMD_MATERIALAMBIENT: + DEBUG_LOG(G3D,"DL Material Ambient Color: %06x", data); + break; + + case GE_CMD_MATERIALDIFFUSE: + DEBUG_LOG(G3D,"DL Material Diffuse Color: %06x", data); + break; + + case GE_CMD_MATERIALEMISSIVE: + DEBUG_LOG(G3D,"DL Material Emissive Color: %06x", data); + break; + + case GE_CMD_MATERIALSPECULAR: + DEBUG_LOG(G3D,"DL Material Specular Color: %06x", data); + break; + + case GE_CMD_MATERIALALPHA: + DEBUG_LOG(G3D,"DL Material Alpha Color: %06x", data); + break; + + case GE_CMD_MATERIALSPECULARCOEF: + DEBUG_LOG(G3D,"DL Material specular coef: %f", getFloat24(data)); + break; + + case GE_CMD_LIGHTTYPE0: + case GE_CMD_LIGHTTYPE1: + case GE_CMD_LIGHTTYPE2: + case GE_CMD_LIGHTTYPE3: + DEBUG_LOG(G3D,"DL Light %i type: %06x", cmd-GE_CMD_LIGHTTYPE0, data); + break; + + case GE_CMD_LX0:case GE_CMD_LY0:case GE_CMD_LZ0: + case GE_CMD_LX1:case GE_CMD_LY1:case GE_CMD_LZ1: + case GE_CMD_LX2:case GE_CMD_LY2:case GE_CMD_LZ2: + case GE_CMD_LX3:case GE_CMD_LY3:case GE_CMD_LZ3: + { + int n = cmd - GE_CMD_LX0; + int l = n / 3; + int c = n % 3; + float val = getFloat24(data); + DEBUG_LOG(G3D,"DL Light %i %c pos: %f", l, c+'X', val); + gstate.lightpos[l][c] = val; + } + break; + + case GE_CMD_LDX0:case GE_CMD_LDY0:case GE_CMD_LDZ0: + case GE_CMD_LDX1:case GE_CMD_LDY1:case GE_CMD_LDZ1: + case GE_CMD_LDX2:case GE_CMD_LDY2:case GE_CMD_LDZ2: + case GE_CMD_LDX3:case GE_CMD_LDY3:case GE_CMD_LDZ3: + { + int n = cmd - GE_CMD_LDX0; + int l = n / 3; + int c = n % 3; + float val = getFloat24(data); + DEBUG_LOG(G3D,"DL Light %i %c dir: %f", l, c+'X', val); + gstate.lightdir[l][c] = val; + } + break; + + case GE_CMD_LKA0:case GE_CMD_LKB0:case GE_CMD_LKC0: + case GE_CMD_LKA1:case GE_CMD_LKB1:case GE_CMD_LKC1: + case GE_CMD_LKA2:case GE_CMD_LKB2:case GE_CMD_LKC2: + case GE_CMD_LKA3:case GE_CMD_LKB3:case GE_CMD_LKC3: + { + int n = cmd - GE_CMD_LKA0; + int l = n / 3; + int c = n % 3; + float val = getFloat24(data); + DEBUG_LOG(G3D,"DL Light %i %c att: %f", l, c+'X', val); + gstate.lightatt[l][c] = val; + } + break; + + + case GE_CMD_LAC0:case GE_CMD_LAC1:case GE_CMD_LAC2:case GE_CMD_LAC3: + case GE_CMD_LDC0:case GE_CMD_LDC1:case GE_CMD_LDC2:case GE_CMD_LDC3: + case GE_CMD_LSC0:case GE_CMD_LSC1:case GE_CMD_LSC2:case GE_CMD_LSC3: + { + float r = (float)(data>>16)/255.0f; + float g = (float)((data>>8) & 0xff)/255.0f; + float b = (float)(data & 0xff)/255.0f; + + int l = (cmd - GE_CMD_LAC0) / 3; + int t = (cmd - GE_CMD_LAC0) % 3; + gstate.lightColor[t][l].r = r; + gstate.lightColor[t][l].g = g; + gstate.lightColor[t][l].b = b; + } + break; + + case GE_CMD_VIEWPORTX1: + case GE_CMD_VIEWPORTY1: + case GE_CMD_VIEWPORTZ1: + case GE_CMD_VIEWPORTX2: + case GE_CMD_VIEWPORTY2: + case GE_CMD_VIEWPORTZ2: + DEBUG_LOG(G3D,"DL Viewport param %i: %f", cmd-GE_CMD_VIEWPORTX1, getFloat24(data)); + break; + case GE_CMD_LIGHTENABLE0: + case GE_CMD_LIGHTENABLE1: + case GE_CMD_LIGHTENABLE2: + case GE_CMD_LIGHTENABLE3: + DEBUG_LOG(G3D,"DL Light %i enable: %d", cmd-GE_CMD_LIGHTENABLE0, data); + break; + case GE_CMD_CULL: + DEBUG_LOG(G3D,"DL cull: %06x", data); + break; + + case GE_CMD_LMODE: + DEBUG_LOG(G3D,"DL Shade mode: %06x", data); + break; + + case GE_CMD_PATCHDIVISION: + gstate.patch_div_s = data & 0xFF; + gstate.patch_div_t = (data >> 8) & 0xFF; + DEBUG_LOG(G3D, "DL Patch subdivision: %i x %i", gstate.patch_div_s, gstate.patch_div_t); + break; + + case GE_CMD_MATERIALUPDATE: + DEBUG_LOG(G3D,"DL Material Update: %d", data); + break; + + + ////////////////////////////////////////////////////////////////// + // CLEARING + ////////////////////////////////////////////////////////////////// + case GE_CMD_CLEARMODE: + // If it becomes a performance problem, check diff&1 + DEBUG_LOG(G3D,"DL Clear mode: %06x", data); + break; + + + ////////////////////////////////////////////////////////////////// + // ALPHA BLENDING + ////////////////////////////////////////////////////////////////// + case GE_CMD_ALPHABLENDENABLE: + DEBUG_LOG(G3D,"DL Alpha blend enable: %d", data); + break; + + case GE_CMD_BLENDMODE: + DEBUG_LOG(G3D,"DL Blend mode: %06x", data); + break; + + case GE_CMD_BLENDFIXEDA: + DEBUG_LOG(G3D,"DL Blend fix A: %06x", data); + break; + + case GE_CMD_BLENDFIXEDB: + DEBUG_LOG(G3D,"DL Blend fix B: %06x", data); + break; + + case GE_CMD_ALPHATESTENABLE: + DEBUG_LOG(G3D,"DL Alpha test enable: %d", data); + // This is done in the shader. + break; + + case GE_CMD_ALPHATEST: + DEBUG_LOG(G3D,"DL Alpha test settings"); + break; + + case GE_CMD_TEXFUNC: + { + DEBUG_LOG(G3D,"DL TexFunc %i", data&7); + /* + int m=GL_MODULATE; + switch (data & 7) + { + case 0: m=GL_MODULATE; break; + case 1: m=GL_DECAL; break; + case 2: m=GL_BLEND; break; + case 3: m=GL_REPLACE; break; + case 4: m=GL_ADD; break; + }*/ + + /* + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_CONSTANT); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_TEXTURE); + glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); + glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE, 1); + + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, m); + glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE);*/ + break; + } + case GE_CMD_TEXFILTER: + { + int min = data & 7; + int mag = (data >> 8) & 1; + DEBUG_LOG(G3D,"DL TexFilter min: %i mag: %i", min, mag); + } + + break; + ////////////////////////////////////////////////////////////////// + // Z/STENCIL TESTING + ////////////////////////////////////////////////////////////////// + + case GE_CMD_ZTESTENABLE: + DEBUG_LOG(G3D,"DL Z test enable: %d", data & 1); + break; + + case GE_CMD_STENCILTESTENABLE: + DEBUG_LOG(G3D,"DL Stencil test enable: %d", data); + break; + + case GE_CMD_ZTEST: + { + //glDepthFunc(ztests[data&7]); + DEBUG_LOG(G3D,"DL Z test mode: %i", data); + } + break; + + case GE_CMD_MORPHWEIGHT0: + case GE_CMD_MORPHWEIGHT1: + case GE_CMD_MORPHWEIGHT2: + case GE_CMD_MORPHWEIGHT3: + case GE_CMD_MORPHWEIGHT4: + case GE_CMD_MORPHWEIGHT5: + case GE_CMD_MORPHWEIGHT6: + case GE_CMD_MORPHWEIGHT7: + { + int index = cmd - GE_CMD_MORPHWEIGHT0; + float weight = getFloat24(data); + DEBUG_LOG(G3D,"DL MorphWeight %i = %f", index, weight); + gstate.morphWeights[index] = weight; + } + break; + + case GE_CMD_DITH0: + case GE_CMD_DITH1: + case GE_CMD_DITH2: + case GE_CMD_DITH3: + DEBUG_LOG(G3D,"DL DitherMatrix %i = %06x",cmd-GE_CMD_DITH0,data); + break; + + case GE_CMD_WORLDMATRIXNUMBER: + DEBUG_LOG(G3D,"DL World matrix # %i", data); + gstate.worldmtxnum = data&0xF; + break; + + case GE_CMD_WORLDMATRIXDATA: + DEBUG_LOG(G3D,"DL World matrix data # %f", getFloat24(data)); + gstate.worldMatrix[gstate.worldmtxnum++] = getFloat24(data); + break; + + case GE_CMD_VIEWMATRIXNUMBER: + DEBUG_LOG(G3D,"DL VIEW matrix # %i", data); + gstate.viewmtxnum = data&0xF; + break; + + case GE_CMD_VIEWMATRIXDATA: + DEBUG_LOG(G3D,"DL VIEW matrix data # %f", getFloat24(data)); + gstate.viewMatrix[gstate.viewmtxnum++] = getFloat24(data); + break; + + case GE_CMD_PROJMATRIXNUMBER: + DEBUG_LOG(G3D,"DL PROJECTION matrix # %i", data); + gstate.projmtxnum = data&0xF; + break; + + case GE_CMD_PROJMATRIXDATA: + DEBUG_LOG(G3D,"DL PROJECTION matrix data # %f", getFloat24(data)); + gstate.projMatrix[gstate.projmtxnum++] = getFloat24(data); + break; + + case GE_CMD_TGENMATRIXNUMBER: + DEBUG_LOG(G3D,"DL TGEN matrix # %i", data); + gstate.texmtxnum = data&0xF; + break; + + case GE_CMD_TGENMATRIXDATA: + DEBUG_LOG(G3D,"DL TGEN matrix data # %f", getFloat24(data)); + gstate.tgenMatrix[gstate.texmtxnum++] = getFloat24(data); + break; + + case GE_CMD_BONEMATRIXNUMBER: + DEBUG_LOG(G3D,"DL BONE matrix #%i", data); + gstate.boneMatrixNumber = data; + break; + + case GE_CMD_BONEMATRIXDATA: + DEBUG_LOG(G3D,"DL BONE matrix data #%i %f", gstate.boneMatrixNumber, getFloat24(data)); + gstate.boneMatrix[gstate.boneMatrixNumber++] = getFloat24(data); + break; + + default: + DEBUG_LOG(G3D,"DL Unknown: %08x @ %08x", op, dcontext.pc); + break; + + //ETC... + } +} + +bool NullGPU::InterpretList() +{ + // Reset stackptr for safety + stackptr = 0; + u32 op = 0; + prev = 0; + finished = false; + while (!finished) + { + if (dcontext.pc == dcontext.stallAddr) + return false; + + op = Memory::ReadUnchecked_U32(dcontext.pc); //read from memory + u32 cmd = op >> 24; + u32 diff = op ^ gstate.cmdmem[cmd]; + gstate.cmdmem[cmd] = op; // crashes if I try to put the whole op there?? + + ExecuteOp(op, diff); + + dcontext.pc += 4; + prev = op; + } + return true; +} + diff --git a/GPU/Null/NullGpu.h b/GPU/Null/NullGpu.h new file mode 100644 index 0000000000..26e49c53cb --- /dev/null +++ b/GPU/Null/NullGpu.h @@ -0,0 +1,34 @@ +// Copyright (c) 2012- PPSSPP Project. + +// 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, version 2.0 or later versions. + +// 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 2.0 for more details. + +// A copy of the GPL 2.0 should have been included with the program. +// If not, see http://www.gnu.org/licenses/ + +// Official git repository and contact information can be found at +// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. + +#pragma once + +#include "../GPUInterface.h" + +class ShaderManager; + +class NullGPU : public GPUInterface +{ +public: + virtual u32 EnqueueList(u32 listpc, u32 stall); + virtual void UpdateStall(int listid, u32 newstall); + virtual void ExecuteOp(u32 op, u32 diff); + virtual bool InterpretList(); + virtual void DrawSync(int mode); +private: + bool ProcessDLQueue(); +}; diff --git a/GPU/ge_constants.h b/GPU/ge_constants.h index 08dac08535..be9caab1dc 100644 --- a/GPU/ge_constants.h +++ b/GPU/ge_constants.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -289,6 +289,12 @@ enum GEBufferFormat #define GE_VTYPE_WEIGHT_MASK (3<<9) #define GE_VTYPE_WEIGHT_SHIFT 9 +#define GE_VTYPE_WEIGHTCOUNT_MASK (7<<14) +#define GE_VTYPE_WEIGHTCOUNT_SHIFT 14 + +#define GE_VTYPE_MORPHCOUNT_MASK (7<<18) +#define GE_VTYPE_MORPHCOUNT_SHIFT 18 + #define GE_VTYPE_IDX_NONE (0<<11) #define GE_VTYPE_IDX_8BIT (1<<11) #define GE_VTYPE_IDX_16BIT (2<<11) @@ -444,5 +450,12 @@ enum GELogicOp GE_LOGIC_DRAWINVERTED = 12, }; +enum GEPaletteFormat +{ + GE_CMODE_16BIT_BGR5650, + GE_CMODE_16BIT_ABGR5551, + GE_CMODE_16BIT_ABGR4444, + GE_CMODE_32BIT_ABGR8888 +}; -#endif \ No newline at end of file +#endif diff --git a/Globals.cpp b/Globals.cpp index 3286d499d3..be86385206 100644 --- a/Globals.cpp +++ b/Globals.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Globals.h b/Globals.h index 4bb2984829..a07fb66554 100644 --- a/Globals.h +++ b/Globals.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -17,8 +17,10 @@ #pragma once +#include #include #include +#include #include "Log.h" @@ -33,6 +35,24 @@ inline u32 _byteswap_ulong(u32 data) #endif +inline u8 Convert4To8(u8 v) +{ + // Swizzle bits: 00012345 -> 12345123 + return (v << 4) | (v); +} + +inline u8 Convert5To8(u8 v) +{ + // Swizzle bits: 00012345 -> 12345123 + return (v << 3) | (v >> 2); +} + +inline u8 Convert6To8(u8 v) +{ + // Swizzle bits: 00123456 -> 12345612 + return (v << 2) | (v >> 4); +} + #ifndef DISALLOW_COPY_AND_ASSIGN #define DISALLOW_COPY_AND_ASSIGN(t) \ private: \ diff --git a/LICENSE.TXT b/LICENSE.TXT index cc7a22eda6..1c3210d9d1 100644 --- a/LICENSE.TXT +++ b/LICENSE.TXT @@ -29,20 +29,15 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - - - - - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 + 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 + Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public @@ -92,7 +87,7 @@ 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 + GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains @@ -291,7 +286,7 @@ 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 + 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 @@ -313,9 +308,9 @@ 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 + END OF TERMS AND CONDITIONS - How to Apply These Terms to Your New Programs + 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 @@ -373,4 +368,3 @@ 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/README.md b/README.md index 2fd5811040..3424a21d22 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,10 @@ BASIC BUILD INSTRUCTIONS First of all, after having checked out the source, don't forget to run: -git submodule init -git submodule update + git submodule init + git submodule update + in order to get the "native" library. Now, the actual building: diff --git a/SDL/CMakeLists.txt b/SDL/CMakeLists.txt index 278d825dd0..73b6dcbe50 100644 --- a/SDL/CMakeLists.txt +++ b/SDL/CMakeLists.txt @@ -3,7 +3,6 @@ cmake_minimum_required(VERSION 2.6) project (PPSSPP) find_package(PkgConfig) - find_package(PNG REQUIRED) pkg_check_modules(SDL sdl) @@ -12,37 +11,43 @@ if (APPLE) include_directories(/usr/X11/include) endif() +# TODO: Rely on compiler define instead. __QNX__ __QNXNTO__ ? +if (BLACKBERRY) + add_definitions(-DBLACKBERRY) + if (NOT BLACKBERRY LESS 10.0) + add_definitions(-DBLACKBERRY10) + endif() +endif() + +# TODO: Desktop can use GLES too. -D USING_GLES2 ? +if (NOT ARM) + include(FindOpenGL) +endif() -include(FindOpenGL) include(FindSDL) +#add_definitions(-O2) add_definitions(-g) -# add_definitions(-O2) -add_definitions(-Wall) -add_definitions(-DSDL) -add_definitions(-Wno-multichar) -add_definitions(-fno-strict-aliasing) add_definitions(-DUSE_PROFILER) add_definitions(-D_DEBUG) +add_definitions(-DSDL) -if (UNIX) - if (NOT APPLE) # can't build the SDL .m file with -std=gnu++0x - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++0x") - endif() +# Apple can't build the SDL .m file with -std=gnu++0x +if (UNIX AND NOT APPLE) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++0x") endif() include_directories(..) include_directories(../Common) include_directories(../native) include_directories(../native/ext/libzip) -include_directories(/opt/local/include) -include_directories(/usr/local/include) include_directories(${SDL_INCLUDE_DIR}) include_directories(${PNG_INCLUDE_DIR}) -link_directories(/usr/local/lib) -link_directories(/opt/local/lib) -link_directories(/usr/X11/lib) +if (UNIX AND NOT ARM) + include_directories(/opt/local/include /usr/local/include) + link_directories(/usr/local/lib /opt/local/lib /usr/X11/lib) +endif() add_subdirectory(../native/base base) add_subdirectory(../native/gfx gfx) @@ -61,11 +66,20 @@ add_subdirectory(../native/ext/vjson vjson) add_subdirectory(../native/ext/stb_vorbis stb_vorbis) add_subdirectory(../native/ext/stb_image stb_image) add_subdirectory(../native/ext/sha1 sha1) +add_subdirectory(../ext/libkirk kirk) add_subdirectory(../Common Common) add_subdirectory(../GPU GPU) add_subdirectory(../Core Core) -set(LIBS ${LIBS} ${SDL_LIBRARY} ${OPENGL_LIBRARIES} GLEW file lin ${PNG_LIBRARY} z gfx gfx_es2 etcdec image stb_image mixer net ui profiler timeutil file zip base lin vjson stb_vorbis sha1 jsonwriter common core gpu) +set(LIBS ${LIBS} ${SDL_LIBRARY} ${PNG_LIBRARY} z gfx gfx_es2 image stb_image mixer net ui profiler timeutil file zip base lin vjson stb_vorbis sha1 jsonwriter common core gpu kirk) + +if(BLACKBERRY) + set(LIBS ${LIBS} bps screen socket EGL GLESv2) +else() + set(LIBS ${LIBS} ${OPENGL_LIBRARIES} GLEW etcdec) +endif() + +# TODO: Why is cross-platform UI in ../android/jni? set(FILES ../android/jni/NativeApp.cpp ../android/jni/EmuScreen.cpp @@ -73,12 +87,17 @@ set(FILES ../android/jni/GamepadEmu.cpp ../android/jni/UIShader.cpp ../android/jni/ui_atlas.cpp - ../native/base/PCMain.cpp ) -if (APPLE) - SET(FILES ${FILES} SDLMain.m) -endif (APPLE) +# Platform setup +if(BLACKBERRY) + set(FILES ${FILES} ../native/base/BlackberryMain.cpp) +else() + set(FILES ${FILES} ../native/base/PCMain.cpp) + if(APPLE) + set(FILES ${FILES} SDLMain.m) + endif(APPLE) +endif() add_executable(ppsspp ${FILES}) diff --git a/SDL/bar-descriptor.xml b/SDL/bar-descriptor.xml new file mode 100644 index 0000000000..3ce9c914df --- /dev/null +++ b/SDL/bar-descriptor.xml @@ -0,0 +1,32 @@ + + + com.Qtness.PPSSPP + PPSSPP + ppsspp + 0.2 + 1 + Playstation portable emulator. + + Qtness + gYAAgGE4qaHzBnzEAu8JKe4G1OI + + + landscape + false + none + false + + + core.games + + icon-114.png + + + + + run_native + access_shared + play_audio + + + diff --git a/SDL/blackberry_build.sh b/SDL/blackberry_build.sh new file mode 100755 index 0000000000..f89ab23d3c --- /dev/null +++ b/SDL/blackberry_build.sh @@ -0,0 +1,83 @@ +#!/bin/bash + +BUILD_TYPE=Release + +if [ -f ${QNX_TARGET}/usr/include/bps/vibration.h ]; then + BB_OS=10.0 +elif [ -f ${QNX_TARGET}/usr/include/bps/virtualkeyboard.h ]; then + BB_OS=2.1 +else + echo "Could not find your Blackberry NDK. Please source bbndk-env.sh" + exit 1 +fi +echo "Building for Blackberry ${BB_OS}" + + +if [ -z "$PPSSPP_ROOT" ]; then + PPSSPP_ROOT=${PWD}/.. +fi +if [ -z "$PROJECT_ROOT" ]; then + PROJECT_ROOT=${PPSSPP_ROOT}/.. +fi +PKG_CONFIG_PATH=${PROJECT_ROOT}/install/lib/pkgconfig +PKG_CONFIG_LIBDIR=${PROJECT_ROOT}/install/lib/pkgconfig + +SDL_PROJECT=${PROJECT_ROOT}/SDL + +while true; do + case "$1" in + -h | --help ) + echo "Build script for BlackBerry PlayBook" + echo "For normal usage, please use the NDK to build." + echo + echo "Options: " + echo " -d, --debug Create a debug build. (default is release)" + echo " -h, --help Show this help message." + echo " -r, --root PATH Specify the root directory of PPSSPP. (default is PWD parent)" + echo " -p, --project-root PATH Specify the root directory containing all projects. (default is root dirs parent)" + echo " If specific projects are in different directories, you can specify them below." + echo " --pkg-config PATH Specify the pkgconfig directory. (default is PPSSPP_ROOT/../install/lib/pkgconfig)" + echo + echo "Dependency Paths (defaults are under project root): " + echo " --sdl PATH SDL 1.2 project directory (default is SDL)" + echo " --tco PATH TouchControlOverlay project directory (default is TouchControlOverlay)" + exit 0 + ;; + -d | --debug ) BUILD_TYPE=Debug; shift ;; + -r | --root ) PPSSPP_ROOT="$2"; shift 2 ;; + -p | --project-root ) PROJECT_ROOT="$2"; shift 2 ;; + --pkg-config ) PKG_CONFIG_PATH="$2"; PKG_CONFIG_LIBDIR="$2"; shift 2 ;; + --sdl ) SDL_PROJECT="$2"; shift 2 ;; + --tco ) TCO_PROJECT="$2"; shift 2 ;; + -- ) shift; break ;; + * ) break ;; + esac +done + +if [ -z "$SDL_PROJECT" ]; then + SDL_PROJECT="$PROJECT_ROOT/SDL" +fi +if [ -z "$TCO_PROJECT" ]; then + TCO_PROJECT="$PROJECT_ROOT/TouchControlOverlay" +fi + +export PKG_CONFIG_PATH +export PKG_CONFIG_LIBDIR + +echo "Build type: ${BUILD_TYPE}" + +cmake \ +-DCMAKE_BUILD_TYPE=${BUILD_TYPE} \ +-DCMAKE_SYSTEM_NAME=QNX \ +-DCMAKE_C_COMPILER="${QNX_HOST}/usr/bin/ntoarmv7-gcc" \ +-DCMAKE_CXX_COMPILER="${QNX_HOST}/usr/bin/ntoarmv7-g++" \ +-DSDL_INCLUDE_DIR="${SDL_PROJECT}/include" \ +-DSDL_LIBRARY="${SDL_PROJECT}/Device-${BUILD_TYPE}/libSDL12.so;${TCO_PROJECT}/Device-${BUILD_TYPE}/libTouchControlOverlay.so" \ +-DSDL_FOUND=ON \ +-DPNG_LIBRARY="${QNX_TARGET}/armle-v7/usr/lib/libpng.so" \ +-DPNG_PNG_INCLUDE_DIR="${QNX_TARGET}/usr/include" \ +-DBLACKBERRY=${BB_OS} \ +-DARM=7 \ +${PWD} + +make -j4 diff --git a/SDL/blackberry_package.sh b/SDL/blackberry_package.sh new file mode 100755 index 0000000000..cdac8adeab --- /dev/null +++ b/SDL/blackberry_package.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +TYPE=Device-Release +PPSSPP_ROOT=${PWD}/.. +WORKSPACE=${PPSSPP_ROOT}/.. +blackberry-nativepackager -package PPSSPP.bar bar-descriptor.xml ppsspp \ +-e icon-114.png icon-114.png \ +-devMode -debugToken ~/debugtoken.bar \ +-e ../android/assets assets \ +-e ${WORKSPACE}/SDL12/${TYPE}/libSDL12.so lib/libSDL12.so \ +-e ${WORKSPACE}/TouchControlOverlay/${TYPE}/libTouchControlOverlay.so lib/libTouchControlOverlay.so \ +-e ${WORKSPACE}/SDL_mixer/${TYPE}/libSDL_mixer.so lib/libSDL_mixer.so diff --git a/SDL/icon-114.png b/SDL/icon-114.png new file mode 100755 index 0000000000..bef28a2504 Binary files /dev/null and b/SDL/icon-114.png differ diff --git a/Windows/EmuThread.cpp b/Windows/EmuThread.cpp index 8439fc30a8..d03fb4806c 100644 --- a/Windows/EmuThread.cpp +++ b/Windows/EmuThread.cpp @@ -104,10 +104,11 @@ DWORD TheThread(LPVOID x) host->PrepareShutdown(); -shutdown: PSP_Shutdown(); +shutdown: + host->ShutdownGL(); //The CPU should return when a game is stopped and cleanup should be done here, diff --git a/Windows/InputDevice.cpp b/Windows/InputDevice.cpp new file mode 100644 index 0000000000..ad882a2c73 --- /dev/null +++ b/Windows/InputDevice.cpp @@ -0,0 +1,13 @@ +#include "InputDevice.h" +#include "XinputDevice.h" +#include "KeyboardDevice.h" +#include +#include + +#define PUSH_BACK(Cls) do { list.push_back(std::shared_ptr(new Cls())); } while (0) +std::list> getInputDevices() { + std::list> list; + PUSH_BACK(XinputDevice); + PUSH_BACK(KeyboardDevice); + return list; +} diff --git a/Windows/InputDevice.h b/Windows/InputDevice.h new file mode 100644 index 0000000000..8c50214dfc --- /dev/null +++ b/Windows/InputDevice.h @@ -0,0 +1,13 @@ +#include "../Common/CommonTypes.h" +#include "../Core/HLE/sceCtrl.h" + +#pragma once +class InputDevice +{ +public: + virtual int UpdateState() = 0; +}; + +#include +#include +std::list> getInputDevices(); diff --git a/Windows/KeyboardDevice.cpp b/Windows/KeyboardDevice.cpp new file mode 100644 index 0000000000..c69f97b90c --- /dev/null +++ b/Windows/KeyboardDevice.cpp @@ -0,0 +1,46 @@ +#include "KeyboardDevice.h" +#include "../Common/CommonTypes.h" +#include "../Core/HLE/sceCtrl.h" +#include "WinUser.h" + +static const unsigned short key_ctrl_map[] = { + VK_SPACE, CTRL_START, + 'V', CTRL_SELECT, + 'A', CTRL_SQUARE, + 'S', CTRL_TRIANGLE, + 'X', CTRL_CIRCLE, + 'Z', CTRL_CROSS, + 'Q', CTRL_LTRIGGER, + 'W', CTRL_RTRIGGER, + VK_UP, CTRL_UP, + VK_DOWN, CTRL_DOWN, + VK_LEFT, CTRL_LEFT, + VK_RIGHT, CTRL_RIGHT, +}; +int KeyboardDevice::UpdateState() { + float analogX = 0; + float analogY = 0; + for (int i = 0; i < sizeof(key_ctrl_map)/sizeof(key_ctrl_map[0]); i += 2) { + if (!GetAsyncKeyState(key_ctrl_map[i])) + __CtrlButtonUp(key_ctrl_map[i+1]); + else { + __CtrlButtonDown(key_ctrl_map[i+1]); + switch (key_ctrl_map[i]) { + case VK_UP: + analogY -= .8f; + break; + case VK_DOWN: + analogY += .8f; + break; + case VK_LEFT: + analogX -= .8f; + break; + case VK_RIGHT: + analogX += .8f; + break; + } + } + } + __CtrlSetAnalog(analogX, analogY); + return 0; +} \ No newline at end of file diff --git a/Windows/KeyboardDevice.h b/Windows/KeyboardDevice.h new file mode 100644 index 0000000000..79d238348c --- /dev/null +++ b/Windows/KeyboardDevice.h @@ -0,0 +1,7 @@ +#pragma once +#include "InputDevice.h" + +class KeyboardDevice : public InputDevice { +public: + virtual int UpdateState(); +}; diff --git a/Windows/OpenGLBase.cpp b/Windows/OpenGLBase.cpp index 4edf1c6bec..706d3c17e8 100644 --- a/Windows/OpenGLBase.cpp +++ b/Windows/OpenGLBase.cpp @@ -1,6 +1,6 @@ // NOTE: Apologies for the quality of this code, this is really from pre-opensource Dolphin - that is, 2003. -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) #include #include #else @@ -41,8 +41,11 @@ void setVSync(int interval=1) wglSwapIntervalEXT(interval); } } -GLvoid ResizeGLScene() // Resize And Initialize The GL Window + +void GL_Resized() // Resize And Initialize The GL Window { + if (!hWnd) + return; RECT rc; GetWindowRect(hWnd,&rc); xres=rc.right-rc.left; //account for border :P @@ -136,7 +139,7 @@ bool GL_Init(HWND window) glewInit(); - ResizeGLScene(); // Set Up Our Perspective GL Screen + GL_Resized(); // Set Up Our Perspective GL Screen return true; // Success } @@ -162,4 +165,5 @@ void GL_Shutdown() MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); hDC=NULL; // Set DC To NULL } + hWnd = NULL; } diff --git a/Windows/OpenGLBase.h b/Windows/OpenGLBase.h index 173d68102b..50a154089f 100644 --- a/Windows/OpenGLBase.h +++ b/Windows/OpenGLBase.h @@ -5,5 +5,6 @@ bool GL_Init(HWND window); void GL_Shutdown(); +void GL_Resized(); void GL_BeginFrame(); void GL_EndFrame(); diff --git a/Windows/PPSSPP.sln b/Windows/PPSSPP.sln index 79dba78398..0ee6604d92 100644 --- a/Windows/PPSSPP.sln +++ b/Windows/PPSSPP.sln @@ -1,5 +1,5 @@ -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PPSSPPWindows", "PPSSPP.vcxproj", "{567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}" ProjectSection(ProjectDependencies) = postProject {E8B58922-9827-493D-81E0-4B6E6BD77171} = {E8B58922-9827-493D-81E0-4B6E6BD77171} @@ -10,7 +10,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PPSSPPWindows", "PPSSPP.vcx EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Common", "..\Common\Common.vcxproj", "{3FCDBAE2-5103-4350-9A8E-848CE9C73195}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlib", "..\zlib\zlib.vcxproj", "{F761046E-6C38-4428-A5F1-38391A37BB34}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlib", "..\ext\zlib\zlib.vcxproj", "{F761046E-6C38-4428-A5F1-38391A37BB34}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GPU", "..\GPU\GPU.vcxproj", "{457F45D2-556F-47BC-A31D-AFF0D15BEAED}" ProjectSection(ProjectDependencies) = postProject @@ -29,12 +29,12 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "native", "..\native\native. EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PPSSPPHeadless", "..\headless\Headless.vcxproj", "{EE9BD869-CAA3-447D-8328-294D90DE2C1F}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libkirk", "..\ext\libkirk\libkirk.vcxproj", "{3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 - DebugFast|Win32 = DebugFast|Win32 - DebugFast|x64 = DebugFast|x64 Release|Win32 = Release|Win32 Release|x64 = Release|x64 EndGlobalSection @@ -43,10 +43,6 @@ Global {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug|Win32.Build.0 = Debug|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug|x64.ActiveCfg = Debug|x64 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Debug|x64.Build.0 = Debug|x64 - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.DebugFast|Win32.ActiveCfg = DebugFast|Win32 - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.DebugFast|Win32.Build.0 = DebugFast|Win32 - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.DebugFast|x64.ActiveCfg = Debug|x64 - {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.DebugFast|x64.Build.0 = Debug|x64 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release|Win32.ActiveCfg = Release|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release|Win32.Build.0 = Release|Win32 {567AF8DB-42C1-4D08-96CD-D70A2DFEFC6B}.Release|x64.ActiveCfg = Release|x64 @@ -55,10 +51,6 @@ Global {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug|Win32.Build.0 = Debug|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug|x64.ActiveCfg = Debug|x64 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Debug|x64.Build.0 = Debug|x64 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.DebugFast|Win32.ActiveCfg = Debug|Win32 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.DebugFast|Win32.Build.0 = Debug|Win32 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.DebugFast|x64.ActiveCfg = Debug|x64 - {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.DebugFast|x64.Build.0 = Debug|x64 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release|Win32.ActiveCfg = Release|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release|Win32.Build.0 = Release|Win32 {3FCDBAE2-5103-4350-9A8E-848CE9C73195}.Release|x64.ActiveCfg = Release|x64 @@ -67,10 +59,6 @@ Global {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug|Win32.Build.0 = Debug|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug|x64.ActiveCfg = Debug|x64 {F761046E-6C38-4428-A5F1-38391A37BB34}.Debug|x64.Build.0 = Debug|x64 - {F761046E-6C38-4428-A5F1-38391A37BB34}.DebugFast|Win32.ActiveCfg = Debug|Win32 - {F761046E-6C38-4428-A5F1-38391A37BB34}.DebugFast|Win32.Build.0 = Debug|Win32 - {F761046E-6C38-4428-A5F1-38391A37BB34}.DebugFast|x64.ActiveCfg = Debug|x64 - {F761046E-6C38-4428-A5F1-38391A37BB34}.DebugFast|x64.Build.0 = Debug|x64 {F761046E-6C38-4428-A5F1-38391A37BB34}.Release|Win32.ActiveCfg = Release|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Release|Win32.Build.0 = Release|Win32 {F761046E-6C38-4428-A5F1-38391A37BB34}.Release|x64.ActiveCfg = Release|x64 @@ -79,10 +67,6 @@ Global {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug|Win32.Build.0 = Debug|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug|x64.ActiveCfg = Debug|x64 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Debug|x64.Build.0 = Debug|x64 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.DebugFast|Win32.ActiveCfg = Debug|Win32 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.DebugFast|Win32.Build.0 = Debug|Win32 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.DebugFast|x64.ActiveCfg = Debug|x64 - {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.DebugFast|x64.Build.0 = Debug|x64 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release|Win32.ActiveCfg = Release|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release|Win32.Build.0 = Release|Win32 {457F45D2-556F-47BC-A31D-AFF0D15BEAED}.Release|x64.ActiveCfg = Release|x64 @@ -91,10 +75,6 @@ Global {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug|Win32.Build.0 = Debug|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug|x64.ActiveCfg = Debug|x64 {533F1D30-D04D-47CC-AD71-20F658907E36}.Debug|x64.Build.0 = Debug|x64 - {533F1D30-D04D-47CC-AD71-20F658907E36}.DebugFast|Win32.ActiveCfg = Debug|Win32 - {533F1D30-D04D-47CC-AD71-20F658907E36}.DebugFast|Win32.Build.0 = Debug|Win32 - {533F1D30-D04D-47CC-AD71-20F658907E36}.DebugFast|x64.ActiveCfg = Debug|x64 - {533F1D30-D04D-47CC-AD71-20F658907E36}.DebugFast|x64.Build.0 = Debug|x64 {533F1D30-D04D-47CC-AD71-20F658907E36}.Release|Win32.ActiveCfg = Release|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Release|Win32.Build.0 = Release|Win32 {533F1D30-D04D-47CC-AD71-20F658907E36}.Release|x64.ActiveCfg = Release|x64 @@ -103,10 +83,6 @@ Global {E8B58922-9827-493D-81E0-4B6E6BD77171}.Debug|Win32.Build.0 = Debug|Win32 {E8B58922-9827-493D-81E0-4B6E6BD77171}.Debug|x64.ActiveCfg = Debug|x64 {E8B58922-9827-493D-81E0-4B6E6BD77171}.Debug|x64.Build.0 = Debug|x64 - {E8B58922-9827-493D-81E0-4B6E6BD77171}.DebugFast|Win32.ActiveCfg = Debug|Win32 - {E8B58922-9827-493D-81E0-4B6E6BD77171}.DebugFast|Win32.Build.0 = Debug|Win32 - {E8B58922-9827-493D-81E0-4B6E6BD77171}.DebugFast|x64.ActiveCfg = Debug|x64 - {E8B58922-9827-493D-81E0-4B6E6BD77171}.DebugFast|x64.Build.0 = Debug|x64 {E8B58922-9827-493D-81E0-4B6E6BD77171}.Release|Win32.ActiveCfg = Release|Win32 {E8B58922-9827-493D-81E0-4B6E6BD77171}.Release|Win32.Build.0 = Release|Win32 {E8B58922-9827-493D-81E0-4B6E6BD77171}.Release|x64.ActiveCfg = Release|x64 @@ -115,14 +91,18 @@ Global {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug|Win32.Build.0 = Debug|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug|x64.ActiveCfg = Debug|x64 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Debug|x64.Build.0 = Debug|x64 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.DebugFast|Win32.ActiveCfg = Debug|Win32 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.DebugFast|Win32.Build.0 = Debug|Win32 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.DebugFast|x64.ActiveCfg = Debug|x64 - {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.DebugFast|x64.Build.0 = Debug|x64 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release|Win32.ActiveCfg = Release|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release|Win32.Build.0 = Release|Win32 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release|x64.ActiveCfg = Release|x64 {EE9BD869-CAA3-447D-8328-294D90DE2C1F}.Release|x64.Build.0 = Release|x64 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|Win32.ActiveCfg = Debug|Win32 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|Win32.Build.0 = Debug|Win32 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|x64.ActiveCfg = Debug|x64 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Debug|x64.Build.0 = Debug|x64 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release|Win32.ActiveCfg = Release|Win32 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release|Win32.Build.0 = Release|Win32 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release|x64.ActiveCfg = Release|x64 + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Windows/PPSSPP.vcxproj b/Windows/PPSSPP.vcxproj index 100c48192c..b5a069f277 100644 --- a/Windows/PPSSPP.vcxproj +++ b/Windows/PPSSPP.vcxproj @@ -1,14 +1,6 @@  - - DebugFast - Win32 - - - DebugFast - x64 - Debug Win32 @@ -33,11 +25,6 @@ PPSSPPWindows - - Application - MultiByte - false - Application MultiByte @@ -47,11 +34,6 @@ Application MultiByte - - Application - MultiByte - false - Application MultiByte @@ -64,10 +46,6 @@ - - - - @@ -76,10 +54,6 @@ - - - - @@ -102,18 +76,6 @@ $(Platform)\$(Configuration)\ $(Platform)\$(Configuration)\ false - ..\ - $(Configuration)\ - false - $(Platform)\$(Configuration)\ - $(Platform)\$(Configuration)\ - false - AllRules.ruleset - - - AllRules.ruleset - - AllRules.ruleset @@ -136,12 +98,12 @@ Use Level3 EditAndContinue - ../common;..;../native;../native/ext/glew;../zlib + ../common;..;../native;../native/ext/glew;../ext/zlib stdafx.h MultiThreadedDebugDLL - Winmm.lib;Ws2_32.lib;opengl32.lib;glu32.lib;comctl32.lib;dsound.lib;%(AdditionalDependencies) + XInput.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;glu32.lib;comctl32.lib;dsound.lib;xinput.lib;%(AdditionalDependencies) true $(OutDir)$(ProjectName).pdb Windows @@ -164,12 +126,12 @@ Use Level3 ProgramDatabase - ../common;..;../native;../native/ext/glew;../zlib + ../common;..;../native;../native/ext/glew;../ext/zlib stdafx.h MultiThreadedDebugDLL - Winmm.lib;Ws2_32.lib;opengl32.lib;glu32.lib;comctl32.lib;dsound.lib;%(AdditionalDependencies) + XInput.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;glu32.lib;comctl32.lib;dsound.lib;%(AdditionalDependencies) true $(OutDir)$(ProjectName).pdb Windows @@ -195,14 +157,14 @@ Use Level3 ProgramDatabase - ../common;..;../native;../native/ext/glew;../zlib + ../common;..;../native;../native/ext/glew;../ext/zlib stdafx.h stdafx.h - Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;comctl32.lib;%(AdditionalDependencies) + XInput.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;comctl32.lib;%(AdditionalDependencies) $(OutDir)$(TargetName)$(TargetExt) - ../elfio/release;%(AdditionalLibraryDirectories) + %(AdditionalLibraryDirectories) true Windows true @@ -230,12 +192,12 @@ Use Level3 ProgramDatabase - ../common;..;../native;../native/ext/glew;../zlib + ../common;..;../native;../native/ext/glew;../ext/zlib stdafx.h - Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;comctl32.lib;%(AdditionalDependencies) - ../elfio/release;%(AdditionalLibraryDirectories) + XInput.lib;Winmm.lib;Ws2_32.lib;opengl32.lib;dsound.lib;glu32.lib;comctl32.lib;%(AdditionalDependencies) + %(AdditionalLibraryDirectories) true Windows true @@ -246,94 +208,34 @@ true - - - WIN32;NDEBUG;_WINDOWS;LOGGING;_DEBUG;%(PreprocessorDefinitions) - Sync - MultiThreadedDebugDLL - false - Use - - - Level3 - ProgramDatabase - ../common;..;../native;../native/ext/glew;../zlib - stdafx.h - - - Ws2_32.lib;comctl32.lib;../zlib/zdll.lib;imgdecoder.lib;opengl32.lib;dsound.lib;glu32.lib;%(AdditionalDependencies) - $(OutDir)$(TargetName)$(TargetExt) - ../elfio/release;%(AdditionalLibraryDirectories) - true - Windows - true - true - MachineX86 - - - - - X64 - - - WIN32;NDEBUG;_WINDOWS;LOGGING;_DEBUG;%(PreprocessorDefinitions) - Sync - MultiThreadedDebugDLL - false - Use - Level3 - ProgramDatabase - ../common;..;../native;../native/ext/glew;../zlib - - - imgdecoder.lib;opengl32.lib;dsound.lib;glu32.lib;comctl32.lib;%(AdditionalDependencies) - $(OutDir)DaShDebugFast.exe - ../elfio/release;%(AdditionalLibraryDirectories) - true - Windows - true - true - MachineX64 - - - true true true - true true true - true true true - true true true - true true true - true true true - true true true - true true true - true true true - true true true @@ -344,12 +246,6 @@ NotUsing - NotUsing - - - NotUsing - - NotUsing @@ -364,10 +260,10 @@ + + - $(IntDir)%(Filename)2.obj - $(IntDir)%(Filename)2.obj $(IntDir)%(Filename)2.obj $(IntDir)%(Filename)2.obj $(IntDir)%(Filename)2.obj @@ -383,13 +279,12 @@ - Create - Create Create Create Create Create + @@ -403,6 +298,8 @@ + + @@ -417,6 +314,7 @@ + @@ -437,13 +335,16 @@ {533f1d30-d04d-47cc-ad71-20f658907e36} + + {3baae095-e0ab-4b0e-b5df-ce39c8ae31de} + {457f45d2-556f-47bc-a31d-aff0d15beaed} {e8b58922-9827-493d-81e0-4b6e6bd77171} - + {f761046e-6c38-4428-a5f1-38391a37bb34} diff --git a/Windows/PPSSPP.vcxproj.filters b/Windows/PPSSPP.vcxproj.filters index b7769f3b28..7df8759760 100644 --- a/Windows/PPSSPP.vcxproj.filters +++ b/Windows/PPSSPP.vcxproj.filters @@ -23,6 +23,9 @@ {d53d0871-8572-4393-822e-d14db0a88dab} + + {a1963305-bf88-43ef-8ba2-bb3933584b38} + @@ -92,6 +95,15 @@ Android + + Windows\Input + + + Windows\Input + + + Windows\Input + @@ -161,6 +173,15 @@ Android + + Windows\Input + + + Windows\Input + + + Windows\Input + diff --git a/Windows/WindowsHost.cpp b/Windows/WindowsHost.cpp index 580b1e12ec..1ae42e6b08 100644 --- a/Windows/WindowsHost.cpp +++ b/Windows/WindowsHost.cpp @@ -85,6 +85,9 @@ void WindowsHost::SetDebugMode(bool mode) void WindowsHost::BeginFrame() { + for (auto iter = this->input.begin(); iter != this->input.end(); iter++) + if ((*iter)->UpdateState() == 0) + break; // *iter is std::shared_ptr, **iter is InputDevice GL_BeginFrame(); } void WindowsHost::EndFrame() diff --git a/Windows/WindowsHost.h b/Windows/WindowsHost.h index 3e7728d552..adbb24a876 100644 --- a/Windows/WindowsHost.h +++ b/Windows/WindowsHost.h @@ -1,4 +1,7 @@ #include "../Core/Host.h" +#include "InputDevice.h" +#include +#include class WindowsHost : public Host { @@ -6,6 +9,7 @@ public: WindowsHost(HWND _displayWindow) { displayWindow = _displayWindow; + input = getInputDevices(); } void UpdateMemView(); void UpdateDisassembly(); @@ -30,4 +34,5 @@ public: private: HWND displayWindow; + std::list> input; }; \ No newline at end of file diff --git a/Windows/WndMainWindow.cpp b/Windows/WndMainWindow.cpp index 8883ec51ef..c91f146cd0 100644 --- a/Windows/WndMainWindow.cpp +++ b/Windows/WndMainWindow.cpp @@ -1,7 +1,7 @@ // NOTE: Apologies for the quality of this code, this is really from pre-opensource Dolphin - that is, 2003. -#define programname "PPSSPP v0.1" +#define programname "PPSSPP v0.2" #include @@ -11,7 +11,7 @@ #include "commctrl.h" #include "../Core/Debugger/SymbolMap.h" - +#include "OpenGLBase.h" #include "Debugger/Debugger_Disasm.h" #include "Debugger/Debugger_MemoryDlg.h" #include "main.h" @@ -96,34 +96,36 @@ namespace MainWindow RegisterClassEx(&wcex); } - void RequestWindowSize(int w, int h) - { - RECT rc; - rc.left=20; - rc.top=100; + void GetWindowRectAtZoom(int zoom, RECT &rcInner, RECT &rcOuter) { + rcInner.left=20; + rcInner.top=100; - rc.right=w+rc.left;//+client edge - rc.bottom=h+rc.top; //+client edge + rcInner.right=480*zoom + rcInner.left;//+client edge + rcInner.bottom=272*zoom + rcInner.top; //+client edge - AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, TRUE); - SetWindowPos(hwndMain,0,0,0,rc.right-rc.left,rc.bottom-rc.top,SWP_NOMOVE|SWP_NOZORDER); + rcOuter=rcInner; + AdjustWindowRect(&rcOuter, WS_OVERLAPPEDWINDOW, TRUE); + } + + void SetZoom(int zoom) { + g_Config.iWindowZoom = zoom; + RECT rc, rcOuter; + GetWindowRectAtZoom(zoom, rc, rcOuter); + MoveWindow(hwndMain, rcOuter.left, rcOuter.top, rcOuter.right - rcOuter.left, rcOuter.bottom - rcOuter.top, TRUE); + MoveWindow(hwndDisplay, 0, 0, rc.right - rc.left, rc.bottom - rc.top, TRUE); + GL_Resized(); } BOOL Show(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // Store instance handle in our global variable + int zoom = g_Config.iWindowZoom; + if (zoom < 1) zoom = 1; + if (zoom > 4) zoom = 4; + RECT rc,rcOrig; - rc.left=20; - rc.top=100; - - int zoom = 1; - - rc.right=480*zoom+rc.left;//+client edge - rc.bottom=272*zoom+rc.top; //+client edge - - rcOrig=rc; - AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, TRUE); + GetWindowRectAtZoom(zoom, rcOrig, rc); u32 style = skinMode ? WS_POPUP : WS_OVERLAPPEDWINDOW; @@ -170,7 +172,7 @@ namespace MainWindow filter += "PSP"; filter += "|"; - filter += "*.pbp;*.elf;*.iso;*.cso;"; + filter += "*.pbp;*.elf;*.iso;*.cso;*.prx"; filter += "|"; filter += "|"; for (int i=0; i<(int)filter.length(); i++) @@ -317,6 +319,23 @@ namespace MainWindow } break; + case ID_OPTIONS_SCREEN1X: + SetZoom(1); + UpdateMenus(); + break; + case ID_OPTIONS_SCREEN2X: + SetZoom(2); + UpdateMenus(); + break; + case ID_OPTIONS_SCREEN3X: + SetZoom(3); + UpdateMenus(); + break; + case ID_OPTIONS_SCREEN4X: + SetZoom(4); + UpdateMenus(); + break; + case ID_FILE_EXIT: DestroyWindow(hWnd); break; @@ -590,6 +609,16 @@ namespace MainWindow EnableMenuItem(menu,ID_EMULATION_STOP,!enable); EnableMenuItem(menu,ID_OPTIONS_SETTINGS,enable); EnableMenuItem(menu,ID_PLUGINS_CHOOSEPLUGINS,enable); + + const int zoomitems[4] = { + ID_OPTIONS_SCREEN1X, + ID_OPTIONS_SCREEN2X, + ID_OPTIONS_SCREEN3X, + ID_OPTIONS_SCREEN4X, + }; + for (int i = 0; i < 4; i++) { + CheckMenuItem(menu, zoomitems[i], MF_BYCOMMAND | ((i == g_Config.iWindowZoom - 1) ? MF_CHECKED : MF_UNCHECKED)); + } } diff --git a/Windows/WndMainWindow.h b/Windows/WndMainWindow.h index d126e87552..2db48c759a 100644 --- a/Windows/WndMainWindow.h +++ b/Windows/WndMainWindow.h @@ -13,5 +13,4 @@ namespace MainWindow HINSTANCE GetHInstance(); HWND GetDisplayHWND(); void SetPlaying(const char*text); - void RequestWindowSize(int w, int h); } diff --git a/Windows/XinputDevice.cpp b/Windows/XinputDevice.cpp new file mode 100644 index 0000000000..86fc0dab64 --- /dev/null +++ b/Windows/XinputDevice.cpp @@ -0,0 +1,115 @@ +#include "stdafx.h" +#include "XinputDevice.h" +#include +#include + +#ifndef XUSER_MAX_COUNT +#define XUSER_MAX_COUNT 4 +#endif + +XinputDevice::XinputDevice() { + ZeroMemory( &this->prevState, sizeof(this->prevState) ); + this->check_delay = 0; + this->gamepad_idx = -1; +} + +struct Stick { + float x; + float y; +}; +static Stick NormalizedDeadzoneFilter(XINPUT_STATE &state); + +int XinputDevice::UpdateState() { + if (this->check_delay-- > 0) return -1; + XINPUT_STATE state; + ZeroMemory( &state, sizeof(XINPUT_STATE) ); + + DWORD dwResult; + if (this->gamepad_idx >= 0) + dwResult = XInputGetState( this->gamepad_idx, &state ); + else { + // use the first gamepad that responds + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + dwResult = XInputGetState( i, &state ); + if (dwResult == ERROR_SUCCESS) { + this->gamepad_idx = i; + break; + } + } + } + + if ( dwResult == ERROR_SUCCESS ) { + this->ApplyDiff(state); + Stick left = NormalizedDeadzoneFilter(state); + __CtrlSetAnalog(left.x, left.y); + this->prevState = state; + this->check_delay = 0; + return 0; + } else { + // wait check_delay frames before polling the controller again + this->gamepad_idx = -1; + this->check_delay = 100; + return -1; + } +} + +// We only filter the left stick since PSP has no analog triggers or right stick +static Stick NormalizedDeadzoneFilter(XINPUT_STATE &state) { + static const short DEADZONE = XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE; + Stick left; + left.x = state.Gamepad.sThumbLX; + left.y = state.Gamepad.sThumbLY; + + float magnitude = sqrt(left.x*left.x + left.y*left.y); + + Stick norm; + norm.x = left.x / magnitude; + norm.y = left.y / magnitude; + + if (magnitude > DEADZONE) { + if (magnitude > 32767) magnitude = 32767; + // normalize the magnitude + magnitude -= DEADZONE; + magnitude /= (32767 - DEADZONE); + + // normalize the axis + left.x = norm.x * magnitude; + left.y = norm.y * magnitude; + } else { + left.x = left.y = 0; + } + + return left; +} + +static const unsigned short xinput_ctrl_map[] = { + XINPUT_GAMEPAD_DPAD_UP, CTRL_UP, + XINPUT_GAMEPAD_DPAD_DOWN, CTRL_DOWN, + XINPUT_GAMEPAD_DPAD_LEFT, CTRL_LEFT, + XINPUT_GAMEPAD_DPAD_RIGHT, CTRL_RIGHT, + XINPUT_GAMEPAD_START, CTRL_START, + XINPUT_GAMEPAD_BACK, CTRL_SELECT, + XINPUT_GAMEPAD_LEFT_SHOULDER, CTRL_LTRIGGER, + XINPUT_GAMEPAD_RIGHT_SHOULDER, CTRL_RTRIGGER, + XINPUT_GAMEPAD_A, CTRL_CROSS, + XINPUT_GAMEPAD_B, CTRL_CIRCLE, + XINPUT_GAMEPAD_X, CTRL_SQUARE, + XINPUT_GAMEPAD_Y, CTRL_TRIANGLE, +}; +static inline u32 CtrlForXinput(int xinput) { + for (int i = 0; i < sizeof(xinput_ctrl_map)/sizeof(xinput_ctrl_map[0]); i += 2) + if (xinput_ctrl_map[i] == xinput) return (u32) xinput_ctrl_map[i+1]; + return 0; +} + +void XinputDevice::ApplyDiff(XINPUT_STATE &state) { + unsigned short pressed = state.Gamepad.wButtons & ~this->prevState.Gamepad.wButtons; + unsigned short released = ~state.Gamepad.wButtons & this->prevState.Gamepad.wButtons; + + for (int i = 1; i < USHRT_MAX; i <<= 1) { + if (pressed & i) + __CtrlButtonDown(CtrlForXinput(i)); + if (released & i) + __CtrlButtonUp(CtrlForXinput(i)); + } +} \ No newline at end of file diff --git a/Windows/XinputDevice.h b/Windows/XinputDevice.h new file mode 100644 index 0000000000..71a31becfe --- /dev/null +++ b/Windows/XinputDevice.h @@ -0,0 +1,17 @@ +#pragma once +#include "InputDevice.h" +#include "Xinput.h" + +class XinputDevice : + public InputDevice +{ +public: + XinputDevice(); + virtual int UpdateState(); +private: + void ApplyDiff(XINPUT_STATE &state); + int gamepad_idx; + int check_delay; + XINPUT_STATE prevState; +}; + diff --git a/Windows/main.h b/Windows/main.h index b8793abab6..07cae40cb6 100644 --- a/Windows/main.h +++ b/Windows/main.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/Windows/ppsspp.rc b/Windows/ppsspp.rc index 48374c020b..c75d227f82 100644 --- a/Windows/ppsspp.rc +++ b/Windows/ppsspp.rc @@ -214,6 +214,11 @@ BEGIN MENUITEM "&Toggle Full Screen\tAlt+Enter", ID_OPTIONS_FULLSCREEN, GRAYED MENUITEM "&Display raw framebuffer", ID_OPTIONS_DISPLAYRAWFRAMEBUFFER MENUITEM SEPARATOR + MENUITEM "Screen &1x", ID_OPTIONS_SCREEN1X + MENUITEM "Screen &2x", ID_OPTIONS_SCREEN2X + MENUITEM "Screen &3x", ID_OPTIONS_SCREEN3X + MENUITEM "Screen &4x", ID_OPTIONS_SCREEN4X + MENUITEM SEPARATOR MENUITEM "&Ignore illegal reads/writes", ID_OPTIONS_IGNOREILLEGALREADS END POPUP "&Help" @@ -369,7 +374,7 @@ BEGIN BEGIN VALUE "Comments", "PPSSPP PSP emulator" VALUE "CompanyName", "Henrik Rydgård Inc." - VALUE "FileDescription", "PPSPP PSP emulator" + VALUE "FileDescription", "PPSSPP" VALUE "FileVersion", "1, 0, 0, 0" VALUE "InternalName", "s" VALUE "LegalCopyright", "Copyright (C) 2006-2012 by Henrik Rydgård" diff --git a/Windows/resource.h b/Windows/resource.h index 85e7774f9e..382a6dbec2 100644 --- a/Windows/resource.h +++ b/Windows/resource.h @@ -233,13 +233,18 @@ #define ID_OPTIONS_DISPLAYRAWFRAMEBUFFER 40110 #define ID_HELP_OPENHTTP 40111 #define ID_HELP_OPENWEBSITE 40112 +#define ID_OPTIONS_SCREEN1X 40113 +#define ID_OPTIONS_MENUEDITOR 40114 +#define ID_OPTIONS_SCREEN3X 40115 +#define ID_OPTIONS_SCREEN4X 40116 +#define ID_OPTIONS_SCREEN2X 40117 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 232 -#define _APS_NEXT_COMMAND_VALUE 40113 +#define _APS_NEXT_COMMAND_VALUE 40118 #define _APS_NEXT_CONTROL_VALUE 1162 #define _APS_NEXT_SYMED_VALUE 101 #endif diff --git a/Windows/rt_manif.bin b/Windows/rt_manif.bin new file mode 100644 index 0000000000..51c266b25d --- /dev/null +++ b/Windows/rt_manif.bin @@ -0,0 +1,22 @@ + + + + PPSSPP + + + + + + diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml index c6ced2ce58..4ddf4a2f95 100644 --- a/android/AndroidManifest.xml +++ b/android/AndroidManifest.xml @@ -2,7 +2,7 @@ + android:versionName="0.2" > diff --git a/android/CMakeLists.txt b/android/CMakeLists.txt index 2a9de4eaa4..19378678b3 100644 --- a/android/CMakeLists.txt +++ b/android/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 2.6) -project (Rollerball) +project (PPSSPP) find_package(PkgConfig) diff --git a/android/jni/Android.mk b/android/jni/Android.mk index f94cdb3161..025c73a38b 100644 --- a/android/jni/Android.mk +++ b/android/jni/Android.mk @@ -5,7 +5,7 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := native_audio -LOCAL_CFLAGS := -O2 -fsigned-char -Wall -Wno-multichar -Wno-psabi -std=gnu++0x +LOCAL_CFLAGS := -O2 -fsigned-char -ffast-math -Wall -Wno-multichar -Wno-psabi -std=gnu++0x NATIVE := ../../native LOCAL_SRC_FILES := \ $(NATIVE)/android/native-audio-so.cpp @@ -24,7 +24,7 @@ LOCAL_MODULE := ppsspp_jni NATIVE := ../../native SRC := ../.. -LOCAL_CFLAGS := -DUSE_PROFILER -DGL_GLEXT_PROTOTYPES -O2 -fsigned-char -Wall -Wno-multichar -Wno-psabi -std=gnu++0x -Wno-unused-variable -fno-strict-aliasing +LOCAL_CFLAGS := -DUSE_PROFILER -DGL_GLEXT_PROTOTYPES -O2 -fsigned-char -Wall -Wno-multichar -Wno-psabi -std=gnu++0x -Wno-unused-variable -fno-strict-aliasing -ffast-math LOCAL_CPPFLAGS := LOCAL_C_INCLUDES := \ $(LOCAL_PATH)/../../Common \ @@ -48,6 +48,11 @@ LOCAL_SRC_FILES := \ GamepadEmu.cpp \ ui_atlas.cpp \ $(SRC)/native/android/app-android.cpp \ + $(SRC)/ext/libkirk/AES.c \ + $(SRC)/ext/libkirk/SHA1.c \ + $(SRC)/ext/libkirk/bn.c \ + $(SRC)/ext/libkirk/ec.c \ + $(SRC)/ext/libkirk/kirk_engine.c \ $(SRC)/Globals.cpp \ $(SRC)/Common/ArmABI.cpp \ $(SRC)/Common/ArmEmitter.cpp \ @@ -71,7 +76,10 @@ LOCAL_SRC_FILES := \ $(SRC)/GPU/GLES/ShaderManager.cpp \ $(SRC)/GPU/GLES/VertexShaderGenerator.cpp \ $(SRC)/GPU/GLES/FragmentShaderGenerator.cpp \ + $(SRC)/GPU/Null/NullGpu.cpp \ $(SRC)/Core/ELF/ElfReader.cpp \ + $(SRC)/Core/ELF/PrxDecrypter.cpp \ + $(SRC)/Core/HW/MemoryStick.cpp \ $(SRC)/Core/Core.cpp \ $(SRC)/Core/Config.cpp \ $(SRC)/Core/CoreTiming.cpp \ @@ -96,10 +104,10 @@ LOCAL_SRC_FILES := \ $(SRC)/Core/HLE/sceGe.cpp \ $(SRC)/Core/HLE/sceHprm.cpp \ $(SRC)/Core/HLE/sceHttp.cpp \ + $(SRC)/Core/HLE/sceImpose.cpp \ $(SRC)/Core/HLE/sceIo.cpp \ $(SRC)/Core/HLE/sceKernel.cpp \ $(SRC)/Core/HLE/sceKernelAlarm.cpp \ - $(SRC)/Core/HLE/sceKernelCallback.cpp \ $(SRC)/Core/HLE/sceKernelEventFlag.cpp \ $(SRC)/Core/HLE/sceKernelInterrupt.cpp \ $(SRC)/Core/HLE/sceKernelMemory.cpp \ diff --git a/android/jni/EmuScreen.cpp b/android/jni/EmuScreen.cpp index 74645f9a6f..01575562ae 100644 --- a/android/jni/EmuScreen.cpp +++ b/android/jni/EmuScreen.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -175,10 +175,10 @@ void EmuScreen::render() } // Tiled renderers like PowerVR should benefit greatly from this. However - seems I can't call it? -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) bool hasDiscard = false; // TODO if (hasDiscard) { - //glDiscardFramebufferEXT(GL_COLOR_EXT | GL_DEPTH_EXT | GL_STENCIL_EXT); + //glDiscardFramebuffer(GL_COLOR_EXT | GL_DEPTH_EXT | GL_STENCIL_EXT); } #endif } diff --git a/android/jni/EmuScreen.h b/android/jni/EmuScreen.h index 78fabd4eec..1f13d46590 100644 --- a/android/jni/EmuScreen.h +++ b/android/jni/EmuScreen.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/android/jni/GamepadEmu.cpp b/android/jni/GamepadEmu.cpp index 6e7ba15ac4..49ce14a09c 100644 --- a/android/jni/GamepadEmu.cpp +++ b/android/jni/GamepadEmu.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/android/jni/GamepadEmu.h b/android/jni/GamepadEmu.h index 0be3f82e35..85a79b7266 100644 --- a/android/jni/GamepadEmu.h +++ b/android/jni/GamepadEmu.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/android/jni/MenuScreens.cpp b/android/jni/MenuScreens.cpp index 12ab45656d..86531d590c 100644 --- a/android/jni/MenuScreens.cpp +++ b/android/jni/MenuScreens.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -147,7 +147,7 @@ void MenuScreen::render() { ui_draw2d.DrawTextShadow(UBUNTU48, "PPSSPP", dp_xres + xoff - w/2, 80, 0xFFFFFFFF, ALIGN_HCENTER | ALIGN_BOTTOM); ui_draw2d.SetFontScale(0.7f, 0.7f); - ui_draw2d.DrawTextShadow(UBUNTU24, "V0.1", dp_xres + xoff, 80, 0xFFFFFFFF, ALIGN_RIGHT | ALIGN_BOTTOM); + ui_draw2d.DrawTextShadow(UBUNTU24, "V0.2", dp_xres + xoff, 80, 0xFFFFFFFF, ALIGN_RIGHT | ALIGN_BOTTOM); ui_draw2d.SetFontScale(1.0f, 1.0f); VLinear vlinear(dp_xres + xoff, 95, 20); @@ -155,7 +155,7 @@ void MenuScreen::render() { if (UIButton(GEN_ID, vlinear, w, "Load...", ALIGN_RIGHT)) { FileSelectScreenOptions options; options.allowChooseDirectory = true; - options.filter = "iso:cso:pbp:elf:"; + options.filter = "iso:cso:pbp:elf:prx:"; options.folderIcon = I_ICON_FOLDER; options.iconMapping["iso"] = I_ICON_UMD; options.iconMapping["cso"] = I_ICON_UMD; @@ -290,7 +290,7 @@ FileSelectScreen::FileSelectScreen(const FileSelectScreenOptions &options) : opt void FileSelectScreen::updateListing() { listing_.clear(); - getFilesInDir(currentDirectory_.c_str(), &listing_, options_.filter.c_str()); + getFilesInDir(currentDirectory_.c_str(), &listing_, options_.filter); g_Config.currentDirectory = currentDirectory_; list_.contentChanged(); } @@ -353,7 +353,7 @@ void CreditsScreen::update(InputState &input_state) { static const char *credits[] = { - "PPSSPP v0.1", + "PPSSPP v0.2", "", "", "A fast and portable PSP emulator", @@ -379,7 +379,7 @@ static const char *credits[] = "", "", "Also check out Dolphin, the best Wii/GC emu around:", - "http://code.google.com/p/dolphin-emu/", + "http://www.dolphin-emu.org", "", "", "PPSSPP is intended for educational purposes only.", diff --git a/android/jni/MenuScreens.h b/android/jni/MenuScreens.h index c265367f35..cc76264e13 100644 --- a/android/jni/MenuScreens.h +++ b/android/jni/MenuScreens.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -68,7 +68,7 @@ public: struct FileSelectScreenOptions { - std::string filter; // Enforced extension filter. Case insensitive, extensions separated by ":". + char* filter; // Enforced extension filter. Case insensitive, extensions separated by ":". bool allowChooseDirectory; int folderIcon; std::map iconMapping; diff --git a/android/jni/NativeApp.cpp b/android/jni/NativeApp.cpp index e88744575f..6b11be8e0a 100644 --- a/android/jni/NativeApp.cpp +++ b/android/jni/NativeApp.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -152,7 +152,12 @@ void NativeInit(int argc, const char *argv[], const char *savegame_directory, co std::string user_data_path = savegame_directory; // We want this to be FIRST. +#ifdef BLACKBERRY + // Packed assets are included in app/native/ dir + VFSRegister("", new DirectoryAssetReader("app/native/assets/")); +#else VFSRegister("", new DirectoryAssetReader("assets/")); +#endif VFSRegister("", new DirectoryAssetReader(user_data_path.c_str())); host = new NativeHost(); @@ -188,7 +193,7 @@ void NativeInit(int argc, const char *argv[], const char *savegame_directory, co g_Config.Load(config_filename.c_str()); if (g_Config.currentDirectory == "") { -#ifdef ANDROID +#if defined(ANDROID) || defined(BLACKBERRY) g_Config.currentDirectory = external_directory; #else g_Config.currentDirectory = getenv("HOME"); diff --git a/android/jni/UIShader.cpp b/android/jni/UIShader.cpp index f26241497c..0ec0d6cd15 100644 --- a/android/jni/UIShader.cpp +++ b/android/jni/UIShader.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/android/jni/UIShader.h b/android/jni/UIShader.h index 7421277dc9..6edb962c3d 100644 --- a/android/jni/UIShader.h +++ b/android/jni/UIShader.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/android/project.properties b/android/project.properties index c82ac47fcf..924a2616fc 100644 --- a/android/project.properties +++ b/android/project.properties @@ -12,4 +12,4 @@ # Project target. target=android-8 -android.library.reference.1=../../../../workspace/native/android +android.library.reference.1=../native/android diff --git a/android/res/drawable-hdpi/ic_launcher.png b/android/res/drawable-hdpi/ic_launcher.png index abeaeb03d1..99e96d00e2 100644 Binary files a/android/res/drawable-hdpi/ic_launcher.png and b/android/res/drawable-hdpi/ic_launcher.png differ diff --git a/android/res/drawable-ldpi/ic_launcher.png b/android/res/drawable-ldpi/ic_launcher.png deleted file mode 100644 index 99238729d8..0000000000 Binary files a/android/res/drawable-ldpi/ic_launcher.png and /dev/null differ diff --git a/android/res/drawable-mdpi/ic_launcher.png b/android/res/drawable-mdpi/ic_launcher.png index ca22624667..75f936ed1d 100644 Binary files a/android/res/drawable-mdpi/ic_launcher.png and b/android/res/drawable-mdpi/ic_launcher.png differ diff --git a/android/res/drawable-xhdpi/ic_launcher.png b/android/res/drawable-xhdpi/ic_launcher.png index 23c28c112a..d59290c61b 100644 Binary files a/android/res/drawable-xhdpi/ic_launcher.png and b/android/res/drawable-xhdpi/ic_launcher.png differ diff --git a/android/res/drawable-xxhdpi/ic_launcher.png b/android/res/drawable-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000..3fe685c43e Binary files /dev/null and b/android/res/drawable-xxhdpi/ic_launcher.png differ diff --git a/android/src/org/ppsspp/ppsspp/PpssppActivity.java b/android/src/org/ppsspp/ppsspp/PpssppActivity.java index 975765a049..fbab3e664b 100644 --- a/android/src/org/ppsspp/ppsspp/PpssppActivity.java +++ b/android/src/org/ppsspp/ppsspp/PpssppActivity.java @@ -11,7 +11,6 @@ public class PpssppActivity extends NativeActivity { super(); } - @Override public boolean overrideKeys() { return false; diff --git a/ext/libkirk/AES.c b/ext/libkirk/AES.c new file mode 100644 index 0000000000..fc80f348b9 --- /dev/null +++ b/ext/libkirk/AES.c @@ -0,0 +1,1464 @@ +/* $OpenBSD: rijndael.c,v 1.19 2008/06/09 07:49:45 djm Exp $ */ + +/** + * rijndael-alg-fst.c + * + * @version 3.0 (December 2000) + * + * Optimised ANSI C code for the Rijndael cipher (now AES) + * + * @author Vincent Rijmen + * @author Antoon Bosselaers + * @author Paulo Barreto + * + * This code is hereby placed in the public domain. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include + +#include "AES.h" + +#undef FULL_UNROLL + + +//CMAC GLOBS +#define AES_128 0 +unsigned char const_Rb[16] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87 +}; +unsigned char const_Zero[16] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; +//END + +/* +Te0[x] = S [x].[02, 01, 01, 03]; +Te1[x] = S [x].[03, 02, 01, 01]; +Te2[x] = S [x].[01, 03, 02, 01]; +Te3[x] = S [x].[01, 01, 03, 02]; +Te4[x] = S [x].[01, 01, 01, 01]; + +Td0[x] = Si[x].[0e, 09, 0d, 0b]; +Td1[x] = Si[x].[0b, 0e, 09, 0d]; +Td2[x] = Si[x].[0d, 0b, 0e, 09]; +Td3[x] = Si[x].[09, 0d, 0b, 0e]; +Td4[x] = Si[x].[01, 01, 01, 01]; +*/ + +static const u32 Te0[256] = { + 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU, + 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U, + 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU, + 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU, + 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U, + 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU, + 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU, + 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU, + 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU, + 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU, + 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U, + 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU, + 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU, + 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U, + 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU, + 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU, + 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU, + 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU, + 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU, + 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U, + 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU, + 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU, + 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU, + 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU, + 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U, + 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U, + 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U, + 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U, + 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU, + 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U, + 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U, + 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU, + 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU, + 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U, + 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U, + 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U, + 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU, + 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U, + 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU, + 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U, + 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU, + 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U, + 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U, + 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU, + 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U, + 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U, + 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U, + 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U, + 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U, + 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U, + 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U, + 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U, + 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU, + 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U, + 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U, + 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U, + 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U, + 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U, + 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U, + 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU, + 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U, + 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U, + 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U, + 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU, +}; +static const u32 Te1[256] = { + 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU, + 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U, + 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU, + 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U, + 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU, + 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U, + 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU, + 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U, + 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U, + 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU, + 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U, + 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U, + 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U, + 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU, + 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U, + 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U, + 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU, + 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U, + 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U, + 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U, + 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU, + 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU, + 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U, + 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU, + 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU, + 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U, + 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU, + 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U, + 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU, + 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U, + 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U, + 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U, + 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU, + 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U, + 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU, + 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U, + 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU, + 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U, + 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U, + 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU, + 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU, + 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU, + 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U, + 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U, + 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU, + 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U, + 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU, + 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U, + 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU, + 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U, + 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU, + 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU, + 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U, + 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU, + 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U, + 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU, + 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U, + 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U, + 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U, + 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU, + 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU, + 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U, + 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU, + 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U, +}; +static const u32 Te2[256] = { + 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU, + 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U, + 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU, + 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U, + 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU, + 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U, + 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU, + 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U, + 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U, + 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU, + 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U, + 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U, + 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U, + 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU, + 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U, + 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U, + 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU, + 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U, + 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U, + 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U, + 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU, + 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU, + 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U, + 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU, + 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU, + 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U, + 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU, + 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U, + 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU, + 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U, + 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U, + 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U, + 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU, + 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U, + 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU, + 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U, + 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU, + 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U, + 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U, + 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU, + 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU, + 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU, + 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U, + 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U, + 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU, + 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U, + 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU, + 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U, + 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU, + 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U, + 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU, + 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU, + 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U, + 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU, + 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U, + 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU, + 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U, + 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U, + 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U, + 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU, + 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU, + 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U, + 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU, + 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U, +}; +static const u32 Te3[256] = { + 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U, + 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U, + 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U, + 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU, + 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU, + 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU, + 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U, + 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU, + 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU, + 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U, + 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U, + 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU, + 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU, + 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU, + 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU, + 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU, + 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U, + 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU, + 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU, + 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U, + 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U, + 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U, + 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U, + 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U, + 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU, + 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U, + 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU, + 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU, + 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U, + 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U, + 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U, + 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU, + 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U, + 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU, + 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU, + 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U, + 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U, + 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU, + 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U, + 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU, + 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U, + 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U, + 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U, + 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U, + 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU, + 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U, + 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU, + 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U, + 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU, + 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U, + 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU, + 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU, + 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU, + 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU, + 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U, + 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U, + 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U, + 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U, + 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U, + 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U, + 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU, + 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U, + 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU, + 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU, +}; +static const u32 Te4[256] = { + 0x63636363U, 0x7c7c7c7cU, 0x77777777U, 0x7b7b7b7bU, + 0xf2f2f2f2U, 0x6b6b6b6bU, 0x6f6f6f6fU, 0xc5c5c5c5U, + 0x30303030U, 0x01010101U, 0x67676767U, 0x2b2b2b2bU, + 0xfefefefeU, 0xd7d7d7d7U, 0xababababU, 0x76767676U, + 0xcacacacaU, 0x82828282U, 0xc9c9c9c9U, 0x7d7d7d7dU, + 0xfafafafaU, 0x59595959U, 0x47474747U, 0xf0f0f0f0U, + 0xadadadadU, 0xd4d4d4d4U, 0xa2a2a2a2U, 0xafafafafU, + 0x9c9c9c9cU, 0xa4a4a4a4U, 0x72727272U, 0xc0c0c0c0U, + 0xb7b7b7b7U, 0xfdfdfdfdU, 0x93939393U, 0x26262626U, + 0x36363636U, 0x3f3f3f3fU, 0xf7f7f7f7U, 0xccccccccU, + 0x34343434U, 0xa5a5a5a5U, 0xe5e5e5e5U, 0xf1f1f1f1U, + 0x71717171U, 0xd8d8d8d8U, 0x31313131U, 0x15151515U, + 0x04040404U, 0xc7c7c7c7U, 0x23232323U, 0xc3c3c3c3U, + 0x18181818U, 0x96969696U, 0x05050505U, 0x9a9a9a9aU, + 0x07070707U, 0x12121212U, 0x80808080U, 0xe2e2e2e2U, + 0xebebebebU, 0x27272727U, 0xb2b2b2b2U, 0x75757575U, + 0x09090909U, 0x83838383U, 0x2c2c2c2cU, 0x1a1a1a1aU, + 0x1b1b1b1bU, 0x6e6e6e6eU, 0x5a5a5a5aU, 0xa0a0a0a0U, + 0x52525252U, 0x3b3b3b3bU, 0xd6d6d6d6U, 0xb3b3b3b3U, + 0x29292929U, 0xe3e3e3e3U, 0x2f2f2f2fU, 0x84848484U, + 0x53535353U, 0xd1d1d1d1U, 0x00000000U, 0xededededU, + 0x20202020U, 0xfcfcfcfcU, 0xb1b1b1b1U, 0x5b5b5b5bU, + 0x6a6a6a6aU, 0xcbcbcbcbU, 0xbebebebeU, 0x39393939U, + 0x4a4a4a4aU, 0x4c4c4c4cU, 0x58585858U, 0xcfcfcfcfU, + 0xd0d0d0d0U, 0xefefefefU, 0xaaaaaaaaU, 0xfbfbfbfbU, + 0x43434343U, 0x4d4d4d4dU, 0x33333333U, 0x85858585U, + 0x45454545U, 0xf9f9f9f9U, 0x02020202U, 0x7f7f7f7fU, + 0x50505050U, 0x3c3c3c3cU, 0x9f9f9f9fU, 0xa8a8a8a8U, + 0x51515151U, 0xa3a3a3a3U, 0x40404040U, 0x8f8f8f8fU, + 0x92929292U, 0x9d9d9d9dU, 0x38383838U, 0xf5f5f5f5U, + 0xbcbcbcbcU, 0xb6b6b6b6U, 0xdadadadaU, 0x21212121U, + 0x10101010U, 0xffffffffU, 0xf3f3f3f3U, 0xd2d2d2d2U, + 0xcdcdcdcdU, 0x0c0c0c0cU, 0x13131313U, 0xececececU, + 0x5f5f5f5fU, 0x97979797U, 0x44444444U, 0x17171717U, + 0xc4c4c4c4U, 0xa7a7a7a7U, 0x7e7e7e7eU, 0x3d3d3d3dU, + 0x64646464U, 0x5d5d5d5dU, 0x19191919U, 0x73737373U, + 0x60606060U, 0x81818181U, 0x4f4f4f4fU, 0xdcdcdcdcU, + 0x22222222U, 0x2a2a2a2aU, 0x90909090U, 0x88888888U, + 0x46464646U, 0xeeeeeeeeU, 0xb8b8b8b8U, 0x14141414U, + 0xdedededeU, 0x5e5e5e5eU, 0x0b0b0b0bU, 0xdbdbdbdbU, + 0xe0e0e0e0U, 0x32323232U, 0x3a3a3a3aU, 0x0a0a0a0aU, + 0x49494949U, 0x06060606U, 0x24242424U, 0x5c5c5c5cU, + 0xc2c2c2c2U, 0xd3d3d3d3U, 0xacacacacU, 0x62626262U, + 0x91919191U, 0x95959595U, 0xe4e4e4e4U, 0x79797979U, + 0xe7e7e7e7U, 0xc8c8c8c8U, 0x37373737U, 0x6d6d6d6dU, + 0x8d8d8d8dU, 0xd5d5d5d5U, 0x4e4e4e4eU, 0xa9a9a9a9U, + 0x6c6c6c6cU, 0x56565656U, 0xf4f4f4f4U, 0xeaeaeaeaU, + 0x65656565U, 0x7a7a7a7aU, 0xaeaeaeaeU, 0x08080808U, + 0xbabababaU, 0x78787878U, 0x25252525U, 0x2e2e2e2eU, + 0x1c1c1c1cU, 0xa6a6a6a6U, 0xb4b4b4b4U, 0xc6c6c6c6U, + 0xe8e8e8e8U, 0xddddddddU, 0x74747474U, 0x1f1f1f1fU, + 0x4b4b4b4bU, 0xbdbdbdbdU, 0x8b8b8b8bU, 0x8a8a8a8aU, + 0x70707070U, 0x3e3e3e3eU, 0xb5b5b5b5U, 0x66666666U, + 0x48484848U, 0x03030303U, 0xf6f6f6f6U, 0x0e0e0e0eU, + 0x61616161U, 0x35353535U, 0x57575757U, 0xb9b9b9b9U, + 0x86868686U, 0xc1c1c1c1U, 0x1d1d1d1dU, 0x9e9e9e9eU, + 0xe1e1e1e1U, 0xf8f8f8f8U, 0x98989898U, 0x11111111U, + 0x69696969U, 0xd9d9d9d9U, 0x8e8e8e8eU, 0x94949494U, + 0x9b9b9b9bU, 0x1e1e1e1eU, 0x87878787U, 0xe9e9e9e9U, + 0xcecececeU, 0x55555555U, 0x28282828U, 0xdfdfdfdfU, + 0x8c8c8c8cU, 0xa1a1a1a1U, 0x89898989U, 0x0d0d0d0dU, + 0xbfbfbfbfU, 0xe6e6e6e6U, 0x42424242U, 0x68686868U, + 0x41414141U, 0x99999999U, 0x2d2d2d2dU, 0x0f0f0f0fU, + 0xb0b0b0b0U, 0x54545454U, 0xbbbbbbbbU, 0x16161616U, +}; +static const u32 Td0[256] = { + 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U, + 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U, + 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U, + 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU, + 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U, + 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U, + 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU, + 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U, + 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU, + 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U, + 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U, + 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U, + 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U, + 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU, + 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U, + 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU, + 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U, + 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU, + 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U, + 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U, + 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U, + 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU, + 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U, + 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU, + 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U, + 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU, + 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U, + 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU, + 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU, + 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U, + 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU, + 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U, + 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU, + 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U, + 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U, + 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U, + 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU, + 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U, + 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U, + 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU, + 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U, + 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U, + 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U, + 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U, + 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U, + 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU, + 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U, + 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U, + 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U, + 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U, + 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U, + 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU, + 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU, + 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU, + 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU, + 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U, + 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U, + 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU, + 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU, + 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U, + 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU, + 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U, + 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U, + 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U, +}; +static const u32 Td1[256] = { + 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU, + 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U, + 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU, + 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U, + 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U, + 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U, + 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U, + 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U, + 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U, + 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU, + 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU, + 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU, + 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U, + 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU, + 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U, + 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U, + 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U, + 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU, + 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU, + 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U, + 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU, + 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U, + 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU, + 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU, + 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U, + 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U, + 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U, + 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU, + 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U, + 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU, + 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U, + 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U, + 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U, + 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU, + 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U, + 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U, + 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U, + 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U, + 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U, + 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U, + 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU, + 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU, + 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U, + 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU, + 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U, + 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU, + 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU, + 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U, + 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU, + 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U, + 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U, + 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U, + 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U, + 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U, + 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U, + 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U, + 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU, + 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U, + 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U, + 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU, + 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U, + 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U, + 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U, + 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U, +}; +static const u32 Td2[256] = { + 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U, + 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U, + 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U, + 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U, + 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU, + 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U, + 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U, + 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U, + 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U, + 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU, + 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U, + 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U, + 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU, + 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U, + 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U, + 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U, + 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U, + 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U, + 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U, + 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU, + 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U, + 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U, + 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U, + 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U, + 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U, + 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU, + 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU, + 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U, + 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU, + 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U, + 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU, + 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU, + 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU, + 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU, + 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U, + 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U, + 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U, + 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U, + 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U, + 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U, + 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U, + 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU, + 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU, + 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U, + 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U, + 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU, + 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU, + 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U, + 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U, + 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U, + 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U, + 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U, + 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U, + 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U, + 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU, + 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U, + 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U, + 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U, + 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U, + 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U, + 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U, + 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU, + 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U, + 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U, +}; +static const u32 Td3[256] = { + 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU, + 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU, + 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U, + 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U, + 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU, + 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU, + 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U, + 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU, + 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U, + 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU, + 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U, + 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U, + 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U, + 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U, + 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U, + 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU, + 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU, + 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U, + 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U, + 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU, + 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU, + 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U, + 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U, + 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U, + 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U, + 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU, + 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U, + 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U, + 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU, + 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU, + 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U, + 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U, + 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U, + 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU, + 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U, + 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U, + 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U, + 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U, + 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U, + 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U, + 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U, + 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU, + 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U, + 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U, + 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU, + 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU, + 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U, + 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU, + 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U, + 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U, + 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U, + 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U, + 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U, + 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U, + 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU, + 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU, + 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU, + 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU, + 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U, + 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U, + 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U, + 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU, + 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U, + 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U, +}; +static const u32 Td4[256] = { + 0x52525252U, 0x09090909U, 0x6a6a6a6aU, 0xd5d5d5d5U, + 0x30303030U, 0x36363636U, 0xa5a5a5a5U, 0x38383838U, + 0xbfbfbfbfU, 0x40404040U, 0xa3a3a3a3U, 0x9e9e9e9eU, + 0x81818181U, 0xf3f3f3f3U, 0xd7d7d7d7U, 0xfbfbfbfbU, + 0x7c7c7c7cU, 0xe3e3e3e3U, 0x39393939U, 0x82828282U, + 0x9b9b9b9bU, 0x2f2f2f2fU, 0xffffffffU, 0x87878787U, + 0x34343434U, 0x8e8e8e8eU, 0x43434343U, 0x44444444U, + 0xc4c4c4c4U, 0xdedededeU, 0xe9e9e9e9U, 0xcbcbcbcbU, + 0x54545454U, 0x7b7b7b7bU, 0x94949494U, 0x32323232U, + 0xa6a6a6a6U, 0xc2c2c2c2U, 0x23232323U, 0x3d3d3d3dU, + 0xeeeeeeeeU, 0x4c4c4c4cU, 0x95959595U, 0x0b0b0b0bU, + 0x42424242U, 0xfafafafaU, 0xc3c3c3c3U, 0x4e4e4e4eU, + 0x08080808U, 0x2e2e2e2eU, 0xa1a1a1a1U, 0x66666666U, + 0x28282828U, 0xd9d9d9d9U, 0x24242424U, 0xb2b2b2b2U, + 0x76767676U, 0x5b5b5b5bU, 0xa2a2a2a2U, 0x49494949U, + 0x6d6d6d6dU, 0x8b8b8b8bU, 0xd1d1d1d1U, 0x25252525U, + 0x72727272U, 0xf8f8f8f8U, 0xf6f6f6f6U, 0x64646464U, + 0x86868686U, 0x68686868U, 0x98989898U, 0x16161616U, + 0xd4d4d4d4U, 0xa4a4a4a4U, 0x5c5c5c5cU, 0xccccccccU, + 0x5d5d5d5dU, 0x65656565U, 0xb6b6b6b6U, 0x92929292U, + 0x6c6c6c6cU, 0x70707070U, 0x48484848U, 0x50505050U, + 0xfdfdfdfdU, 0xededededU, 0xb9b9b9b9U, 0xdadadadaU, + 0x5e5e5e5eU, 0x15151515U, 0x46464646U, 0x57575757U, + 0xa7a7a7a7U, 0x8d8d8d8dU, 0x9d9d9d9dU, 0x84848484U, + 0x90909090U, 0xd8d8d8d8U, 0xababababU, 0x00000000U, + 0x8c8c8c8cU, 0xbcbcbcbcU, 0xd3d3d3d3U, 0x0a0a0a0aU, + 0xf7f7f7f7U, 0xe4e4e4e4U, 0x58585858U, 0x05050505U, + 0xb8b8b8b8U, 0xb3b3b3b3U, 0x45454545U, 0x06060606U, + 0xd0d0d0d0U, 0x2c2c2c2cU, 0x1e1e1e1eU, 0x8f8f8f8fU, + 0xcacacacaU, 0x3f3f3f3fU, 0x0f0f0f0fU, 0x02020202U, + 0xc1c1c1c1U, 0xafafafafU, 0xbdbdbdbdU, 0x03030303U, + 0x01010101U, 0x13131313U, 0x8a8a8a8aU, 0x6b6b6b6bU, + 0x3a3a3a3aU, 0x91919191U, 0x11111111U, 0x41414141U, + 0x4f4f4f4fU, 0x67676767U, 0xdcdcdcdcU, 0xeaeaeaeaU, + 0x97979797U, 0xf2f2f2f2U, 0xcfcfcfcfU, 0xcecececeU, + 0xf0f0f0f0U, 0xb4b4b4b4U, 0xe6e6e6e6U, 0x73737373U, + 0x96969696U, 0xacacacacU, 0x74747474U, 0x22222222U, + 0xe7e7e7e7U, 0xadadadadU, 0x35353535U, 0x85858585U, + 0xe2e2e2e2U, 0xf9f9f9f9U, 0x37373737U, 0xe8e8e8e8U, + 0x1c1c1c1cU, 0x75757575U, 0xdfdfdfdfU, 0x6e6e6e6eU, + 0x47474747U, 0xf1f1f1f1U, 0x1a1a1a1aU, 0x71717171U, + 0x1d1d1d1dU, 0x29292929U, 0xc5c5c5c5U, 0x89898989U, + 0x6f6f6f6fU, 0xb7b7b7b7U, 0x62626262U, 0x0e0e0e0eU, + 0xaaaaaaaaU, 0x18181818U, 0xbebebebeU, 0x1b1b1b1bU, + 0xfcfcfcfcU, 0x56565656U, 0x3e3e3e3eU, 0x4b4b4b4bU, + 0xc6c6c6c6U, 0xd2d2d2d2U, 0x79797979U, 0x20202020U, + 0x9a9a9a9aU, 0xdbdbdbdbU, 0xc0c0c0c0U, 0xfefefefeU, + 0x78787878U, 0xcdcdcdcdU, 0x5a5a5a5aU, 0xf4f4f4f4U, + 0x1f1f1f1fU, 0xddddddddU, 0xa8a8a8a8U, 0x33333333U, + 0x88888888U, 0x07070707U, 0xc7c7c7c7U, 0x31313131U, + 0xb1b1b1b1U, 0x12121212U, 0x10101010U, 0x59595959U, + 0x27272727U, 0x80808080U, 0xececececU, 0x5f5f5f5fU, + 0x60606060U, 0x51515151U, 0x7f7f7f7fU, 0xa9a9a9a9U, + 0x19191919U, 0xb5b5b5b5U, 0x4a4a4a4aU, 0x0d0d0d0dU, + 0x2d2d2d2dU, 0xe5e5e5e5U, 0x7a7a7a7aU, 0x9f9f9f9fU, + 0x93939393U, 0xc9c9c9c9U, 0x9c9c9c9cU, 0xefefefefU, + 0xa0a0a0a0U, 0xe0e0e0e0U, 0x3b3b3b3bU, 0x4d4d4d4dU, + 0xaeaeaeaeU, 0x2a2a2a2aU, 0xf5f5f5f5U, 0xb0b0b0b0U, + 0xc8c8c8c8U, 0xebebebebU, 0xbbbbbbbbU, 0x3c3c3c3cU, + 0x83838383U, 0x53535353U, 0x99999999U, 0x61616161U, + 0x17171717U, 0x2b2b2b2bU, 0x04040404U, 0x7e7e7e7eU, + 0xbabababaU, 0x77777777U, 0xd6d6d6d6U, 0x26262626U, + 0xe1e1e1e1U, 0x69696969U, 0x14141414U, 0x63636363U, + 0x55555555U, 0x21212121U, 0x0c0c0c0cU, 0x7d7d7d7dU, +}; +static const u32 rcon[] = { + 0x01000000, 0x02000000, 0x04000000, 0x08000000, + 0x10000000, 0x20000000, 0x40000000, 0x80000000, + 0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */ +}; + +#define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3])) +#define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); } + +/** + * Expand the cipher key into the encryption key schedule. + * + * @return the number of rounds for the given cipher key size. + */ +int +rijndaelKeySetupEnc(u32 rk[/*4*(Nr + 1)*/], const u8 cipherKey[], int keyBits) +{ + int i = 0; + u32 temp; + + rk[0] = GETU32(cipherKey ); + rk[1] = GETU32(cipherKey + 4); + rk[2] = GETU32(cipherKey + 8); + rk[3] = GETU32(cipherKey + 12); + if (keyBits == 128) { + for (;;) { + temp = rk[3]; + rk[4] = rk[0] ^ + (Te4[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te4[(temp ) & 0xff] & 0x0000ff00) ^ + (Te4[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[5] = rk[1] ^ rk[4]; + rk[6] = rk[2] ^ rk[5]; + rk[7] = rk[3] ^ rk[6]; + if (++i == 10) { + return 10; + } + rk += 4; + } + } + rk[4] = GETU32(cipherKey + 16); + rk[5] = GETU32(cipherKey + 20); + if (keyBits == 192) { + for (;;) { + temp = rk[ 5]; + rk[ 6] = rk[ 0] ^ + (Te4[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te4[(temp ) & 0xff] & 0x0000ff00) ^ + (Te4[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[ 7] = rk[ 1] ^ rk[ 6]; + rk[ 8] = rk[ 2] ^ rk[ 7]; + rk[ 9] = rk[ 3] ^ rk[ 8]; + if (++i == 8) { + return 12; + } + rk[10] = rk[ 4] ^ rk[ 9]; + rk[11] = rk[ 5] ^ rk[10]; + rk += 6; + } + } + rk[6] = GETU32(cipherKey + 24); + rk[7] = GETU32(cipherKey + 28); + if (keyBits == 256) { + for (;;) { + temp = rk[ 7]; + rk[ 8] = rk[ 0] ^ + (Te4[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te4[(temp ) & 0xff] & 0x0000ff00) ^ + (Te4[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[ 9] = rk[ 1] ^ rk[ 8]; + rk[10] = rk[ 2] ^ rk[ 9]; + rk[11] = rk[ 3] ^ rk[10]; + if (++i == 7) { + return 14; + } + temp = rk[11]; + rk[12] = rk[ 4] ^ + (Te4[(temp >> 24) ] & 0xff000000) ^ + (Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^ + (Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^ + (Te4[(temp ) & 0xff] & 0x000000ff); + rk[13] = rk[ 5] ^ rk[12]; + rk[14] = rk[ 6] ^ rk[13]; + rk[15] = rk[ 7] ^ rk[14]; + rk += 8; + } + } + return 0; +} + +/** + * Expand the cipher key into the decryption key schedule. + * + * @return the number of rounds for the given cipher key size. + */ +int +rijndaelKeySetupDec(u32 rk[/*4*(Nr + 1)*/], const u8 cipherKey[], int keyBits) +{ + int Nr, i, j; + u32 temp; + + /* expand the cipher key: */ + Nr = rijndaelKeySetupEnc(rk, cipherKey, keyBits); + + /* invert the order of the round keys: */ + for (i = 0, j = 4*Nr; i < j; i += 4, j -= 4) { + temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp; + temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp; + temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp; + temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp; + } + /* apply the inverse MixColumn transform to all round keys but the first and the last: */ + for (i = 1; i < Nr; i++) { + rk += 4; + rk[0] = + Td0[Te4[(rk[0] >> 24) ] & 0xff] ^ + Td1[Te4[(rk[0] >> 16) & 0xff] & 0xff] ^ + Td2[Te4[(rk[0] >> 8) & 0xff] & 0xff] ^ + Td3[Te4[(rk[0] ) & 0xff] & 0xff]; + rk[1] = + Td0[Te4[(rk[1] >> 24) ] & 0xff] ^ + Td1[Te4[(rk[1] >> 16) & 0xff] & 0xff] ^ + Td2[Te4[(rk[1] >> 8) & 0xff] & 0xff] ^ + Td3[Te4[(rk[1] ) & 0xff] & 0xff]; + rk[2] = + Td0[Te4[(rk[2] >> 24) ] & 0xff] ^ + Td1[Te4[(rk[2] >> 16) & 0xff] & 0xff] ^ + Td2[Te4[(rk[2] >> 8) & 0xff] & 0xff] ^ + Td3[Te4[(rk[2] ) & 0xff] & 0xff]; + rk[3] = + Td0[Te4[(rk[3] >> 24) ] & 0xff] ^ + Td1[Te4[(rk[3] >> 16) & 0xff] & 0xff] ^ + Td2[Te4[(rk[3] >> 8) & 0xff] & 0xff] ^ + Td3[Te4[(rk[3] ) & 0xff] & 0xff]; + } + return Nr; +} + +void +rijndaelEncrypt(const u32 rk[/*4*(Nr + 1)*/], int Nr, const u8 pt[16], + u8 ct[16]) +{ + u32 s0, s1, s2, s3, t0, t1, t2, t3; +#ifndef FULL_UNROLL + int r; +#endif /* ?FULL_UNROLL */ + + /* + * map byte array block to cipher state + * and add initial round key: + */ + s0 = GETU32(pt ) ^ rk[0]; + s1 = GETU32(pt + 4) ^ rk[1]; + s2 = GETU32(pt + 8) ^ rk[2]; + s3 = GETU32(pt + 12) ^ rk[3]; +#ifdef FULL_UNROLL + /* round 1: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7]; + /* round 2: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11]; + /* round 3: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15]; + /* round 4: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19]; + /* round 5: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23]; + /* round 6: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27]; + /* round 7: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31]; + /* round 8: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35]; + /* round 9: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39]; + if (Nr > 10) { + /* round 10: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43]; + /* round 11: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47]; + if (Nr > 12) { + /* round 12: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51]; + /* round 13: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55]; + } + } + rk += Nr << 2; +#else /* !FULL_UNROLL */ + /* + * Nr - 1 full rounds: + */ + r = Nr >> 1; + for (;;) { + t0 = + Te0[(s0 >> 24) ] ^ + Te1[(s1 >> 16) & 0xff] ^ + Te2[(s2 >> 8) & 0xff] ^ + Te3[(s3 ) & 0xff] ^ + rk[4]; + t1 = + Te0[(s1 >> 24) ] ^ + Te1[(s2 >> 16) & 0xff] ^ + Te2[(s3 >> 8) & 0xff] ^ + Te3[(s0 ) & 0xff] ^ + rk[5]; + t2 = + Te0[(s2 >> 24) ] ^ + Te1[(s3 >> 16) & 0xff] ^ + Te2[(s0 >> 8) & 0xff] ^ + Te3[(s1 ) & 0xff] ^ + rk[6]; + t3 = + Te0[(s3 >> 24) ] ^ + Te1[(s0 >> 16) & 0xff] ^ + Te2[(s1 >> 8) & 0xff] ^ + Te3[(s2 ) & 0xff] ^ + rk[7]; + + rk += 8; + if (--r == 0) { + break; + } + + s0 = + Te0[(t0 >> 24) ] ^ + Te1[(t1 >> 16) & 0xff] ^ + Te2[(t2 >> 8) & 0xff] ^ + Te3[(t3 ) & 0xff] ^ + rk[0]; + s1 = + Te0[(t1 >> 24) ] ^ + Te1[(t2 >> 16) & 0xff] ^ + Te2[(t3 >> 8) & 0xff] ^ + Te3[(t0 ) & 0xff] ^ + rk[1]; + s2 = + Te0[(t2 >> 24) ] ^ + Te1[(t3 >> 16) & 0xff] ^ + Te2[(t0 >> 8) & 0xff] ^ + Te3[(t1 ) & 0xff] ^ + rk[2]; + s3 = + Te0[(t3 >> 24) ] ^ + Te1[(t0 >> 16) & 0xff] ^ + Te2[(t1 >> 8) & 0xff] ^ + Te3[(t2 ) & 0xff] ^ + rk[3]; + } +#endif /* ?FULL_UNROLL */ + /* + * apply last round and + * map cipher state to byte array block: + */ + s0 = + (Te4[(t0 >> 24) ] & 0xff000000) ^ + (Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^ + (Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^ + (Te4[(t3 ) & 0xff] & 0x000000ff) ^ + rk[0]; + PUTU32(ct , s0); + s1 = + (Te4[(t1 >> 24) ] & 0xff000000) ^ + (Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^ + (Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^ + (Te4[(t0 ) & 0xff] & 0x000000ff) ^ + rk[1]; + PUTU32(ct + 4, s1); + s2 = + (Te4[(t2 >> 24) ] & 0xff000000) ^ + (Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^ + (Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^ + (Te4[(t1 ) & 0xff] & 0x000000ff) ^ + rk[2]; + PUTU32(ct + 8, s2); + s3 = + (Te4[(t3 >> 24) ] & 0xff000000) ^ + (Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^ + (Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^ + (Te4[(t2 ) & 0xff] & 0x000000ff) ^ + rk[3]; + PUTU32(ct + 12, s3); +} + +static void +rijndaelDecrypt(const u32 rk[/*4*(Nr + 1)*/], int Nr, const u8 ct[16], + u8 pt[16]) +{ + u32 s0, s1, s2, s3, t0, t1, t2, t3; +#ifndef FULL_UNROLL + int r; +#endif /* ?FULL_UNROLL */ + + /* + * map byte array block to cipher state + * and add initial round key: + */ + s0 = GETU32(ct ) ^ rk[0]; + s1 = GETU32(ct + 4) ^ rk[1]; + s2 = GETU32(ct + 8) ^ rk[2]; + s3 = GETU32(ct + 12) ^ rk[3]; +#ifdef FULL_UNROLL + /* round 1: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[ 4]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[ 5]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[ 6]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[ 7]; + /* round 2: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[ 8]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[ 9]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11]; + /* round 3: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15]; + /* round 4: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19]; + /* round 5: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23]; + /* round 6: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27]; + /* round 7: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31]; + /* round 8: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35]; + /* round 9: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39]; + if (Nr > 10) { + /* round 10: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43]; + /* round 11: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47]; + if (Nr > 12) { + /* round 12: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51]; + /* round 13: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55]; + } + } + rk += Nr << 2; +#else /* !FULL_UNROLL */ + /* + * Nr - 1 full rounds: + */ + r = Nr >> 1; + for (;;) { + t0 = + Td0[(s0 >> 24) ] ^ + Td1[(s3 >> 16) & 0xff] ^ + Td2[(s2 >> 8) & 0xff] ^ + Td3[(s1 ) & 0xff] ^ + rk[4]; + t1 = + Td0[(s1 >> 24) ] ^ + Td1[(s0 >> 16) & 0xff] ^ + Td2[(s3 >> 8) & 0xff] ^ + Td3[(s2 ) & 0xff] ^ + rk[5]; + t2 = + Td0[(s2 >> 24) ] ^ + Td1[(s1 >> 16) & 0xff] ^ + Td2[(s0 >> 8) & 0xff] ^ + Td3[(s3 ) & 0xff] ^ + rk[6]; + t3 = + Td0[(s3 >> 24) ] ^ + Td1[(s2 >> 16) & 0xff] ^ + Td2[(s1 >> 8) & 0xff] ^ + Td3[(s0 ) & 0xff] ^ + rk[7]; + + rk += 8; + if (--r == 0) { + break; + } + + s0 = + Td0[(t0 >> 24) ] ^ + Td1[(t3 >> 16) & 0xff] ^ + Td2[(t2 >> 8) & 0xff] ^ + Td3[(t1 ) & 0xff] ^ + rk[0]; + s1 = + Td0[(t1 >> 24) ] ^ + Td1[(t0 >> 16) & 0xff] ^ + Td2[(t3 >> 8) & 0xff] ^ + Td3[(t2 ) & 0xff] ^ + rk[1]; + s2 = + Td0[(t2 >> 24) ] ^ + Td1[(t1 >> 16) & 0xff] ^ + Td2[(t0 >> 8) & 0xff] ^ + Td3[(t3 ) & 0xff] ^ + rk[2]; + s3 = + Td0[(t3 >> 24) ] ^ + Td1[(t2 >> 16) & 0xff] ^ + Td2[(t1 >> 8) & 0xff] ^ + Td3[(t0 ) & 0xff] ^ + rk[3]; + } +#endif /* ?FULL_UNROLL */ + /* + * apply last round and + * map cipher state to byte array block: + */ + s0 = + (Td4[(t0 >> 24) ] & 0xff000000) ^ + (Td4[(t3 >> 16) & 0xff] & 0x00ff0000) ^ + (Td4[(t2 >> 8) & 0xff] & 0x0000ff00) ^ + (Td4[(t1 ) & 0xff] & 0x000000ff) ^ + rk[0]; + PUTU32(pt , s0); + s1 = + (Td4[(t1 >> 24) ] & 0xff000000) ^ + (Td4[(t0 >> 16) & 0xff] & 0x00ff0000) ^ + (Td4[(t3 >> 8) & 0xff] & 0x0000ff00) ^ + (Td4[(t2 ) & 0xff] & 0x000000ff) ^ + rk[1]; + PUTU32(pt + 4, s1); + s2 = + (Td4[(t2 >> 24) ] & 0xff000000) ^ + (Td4[(t1 >> 16) & 0xff] & 0x00ff0000) ^ + (Td4[(t0 >> 8) & 0xff] & 0x0000ff00) ^ + (Td4[(t3 ) & 0xff] & 0x000000ff) ^ + rk[2]; + PUTU32(pt + 8, s2); + s3 = + (Td4[(t3 >> 24) ] & 0xff000000) ^ + (Td4[(t2 >> 16) & 0xff] & 0x00ff0000) ^ + (Td4[(t1 >> 8) & 0xff] & 0x0000ff00) ^ + (Td4[(t0 ) & 0xff] & 0x000000ff) ^ + rk[3]; + PUTU32(pt + 12, s3); +} + +/* setup key context for encryption only */ +int +rijndael_set_key_enc_only(rijndael_ctx *ctx, const u8 *key, int bits) +{ + int rounds; + + rounds = rijndaelKeySetupEnc(ctx->ek, key, bits); + if (rounds == 0) + return -1; + + ctx->Nr = rounds; + ctx->enc_only = 1; + + return 0; +} + +/* setup key context for both encryption and decryption */ +int +rijndael_set_key(rijndael_ctx *ctx, const u8 *key, int bits) +{ + int rounds; + + rounds = rijndaelKeySetupEnc(ctx->ek, key, bits); + if (rounds == 0) + return -1; + if (rijndaelKeySetupDec(ctx->dk, key, bits) != rounds) + return -1; + + ctx->Nr = rounds; + ctx->enc_only = 0; + + return 0; +} + +void +rijndael_decrypt(rijndael_ctx *ctx, const u8 *src, u8 *dst) +{ + rijndaelDecrypt(ctx->dk, ctx->Nr, src, dst); +} + +void +rijndael_encrypt(rijndael_ctx *ctx, const u8 *src, u8 *dst) +{ + rijndaelEncrypt(ctx->ek, ctx->Nr, src, dst); +} + +int AES_set_key(AES_ctx *ctx, const u8 *key, int bits) +{ + return rijndael_set_key((rijndael_ctx *)ctx, key, bits); +} + +void AES_decrypt(AES_ctx *ctx, const u8 *src, u8 *dst) +{ + rijndaelDecrypt(ctx->dk, ctx->Nr, src, dst); +} + +void AES_encrypt(AES_ctx *ctx, const u8 *src, u8 *dst) +{ + rijndaelEncrypt(ctx->ek, ctx->Nr, src, dst); +} + +void xor_128(unsigned char *a, unsigned char *b, unsigned char *out) +{ + int i; + for (i=0;i<16; i++) + { + out[i] = a[i] ^ b[i]; + } +} + +//No IV support! +void AES_cbc_encrypt(AES_ctx *ctx, u8 *src, u8 *dst, int size) +{ + u8 block_buff[16]; + + int i; + for(i = 0; i < size; i+=16) + { + //step 1: copy block to dst + memcpy(dst, src, 16); + //step 2: XOR with previous block + if(i) xor_128(dst, block_buff, dst); + //step 3: encrypt the block -> it land in block buffer + AES_encrypt(ctx, dst, block_buff); + //step 4: copy back the encrypted block to destination + memcpy(dst, block_buff, 16); + + dst += 16; + src += 16; + } +} + +void AES_cbc_decrypt(AES_ctx *ctx, u8 *src, u8 *dst, int size) +{ + u8 block_buff[16]; + u8 block_buff_previous[16]; + int i; + + memcpy(block_buff, src, 16); + memcpy(block_buff_previous, src, 16); + AES_decrypt(ctx, src, dst); + + dst += 16; + src += 16; + + + for(i = 16; i < size; i+=16) + { + //step1: backup current block for next block decrypt + memcpy(block_buff, src, 16); + //step2: copy current block to destination + memcpy(dst, src, 16); + //step3: decrypt current buffer in place + AES_decrypt(ctx, dst, dst); + //step4: XOR current buffer with previous buffer + xor_128(dst, block_buff_previous, dst); + //step5: swap buffers + memcpy(block_buff_previous, block_buff, 16); + + dst += 16; + src += 16; + } +} + +/* AES-CMAC Generation Function */ + +void leftshift_onebit(unsigned char *input,unsigned char *output) +{ + int i; + unsigned char overflow = 0; + + for ( i=15; i>=0; i-- ) + { + output[i] = input[i] << 1; + output[i] |= overflow; + overflow = (input[i] & 0x80)?1:0; + } +} + +void generate_subkey(AES_ctx *ctx, unsigned char *K1, unsigned char *K2) +{ + unsigned char L[16]; + unsigned char Z[16]; + unsigned char tmp[16]; + int i; + + for ( i=0; i<16; i++ ) Z[i] = 0; + + + AES_encrypt(ctx, Z, L); + + if ( (L[0] & 0x80) == 0 ) /* If MSB(L) = 0, then K1 = L << 1 */ + { + leftshift_onebit(L,K1); + } else { /* Else K1 = ( L << 1 ) (+) Rb */ + leftshift_onebit(L,tmp); + xor_128(tmp,const_Rb,K1); + } + + if ( (K1[0] & 0x80) == 0 ) + { + leftshift_onebit(K1,K2); + } else { + leftshift_onebit(K1,tmp); + xor_128(tmp,const_Rb,K2); + } +} + +void padding ( unsigned char *lastb, unsigned char *pad, int length ) +{ + int j; + + /* original last block */ + for ( j=0; j<16; j++ ) + { + if ( j < length ) + { + pad[j] = lastb[j]; + } else if ( j == length ) { + pad[j] = 0x80; + } else { + pad[j] = 0x00; + } + } +} + +void AES_CMAC (AES_ctx *ctx, unsigned char *input, int length, unsigned char *mac ) +{ + unsigned char X[16],Y[16], M_last[16], padded[16]; + unsigned char K1[16], K2[16]; + int n, i, flag; + generate_subkey(ctx,K1,K2); + + n = (length+15) / 16; /* n is number of rounds */ + + if ( n == 0 ) + { + n = 1; + flag = 0; + } else { + if ( (length%16) == 0 ) { /* last block is a complete block */ + flag = 1; + } else { /* last block is not complete block */ + flag = 0; + } + + } + + if ( flag ) { /* last block is complete block */ + xor_128(&input[16*(n-1)],K1,M_last); + } else { + padding(&input[16*(n-1)],padded,length%16); + xor_128(padded,K2,M_last); + } + + for ( i=0; i<16; i++ ) X[i] = 0; + for ( i=0; i + + Adapted from code in the Python Cryptography Toolkit, + version 1.0.0 by A.M. Kuchling 1995. +*/ + +/* AM Kuchling's posting:- + Based on SHA code originally posted to sci.crypt by Peter Gutmann + in message <30ajo5$oe8@ccu2.auckland.ac.nz>. + Modified to test for endianness on creation of SHA objects by AMK. + Also, the original specification of SHA was found to have a weakness + by NSA/NIST. This code implements the fixed version of SHA. +*/ + +/* Here's the first paragraph of Peter Gutmann's posting: + +The following is my SHA (FIPS 180) code updated to allow use of the "fixed" +SHA, thanks to Jim Gillogly and an anonymous contributor for the information on +what's changed in the new version. The fix is a simple change which involves +adding a single rotate in the initial expansion function. It is unknown +whether this is an optimal solution to the problem which was discovered in the +SHA or whether it's simply a bandaid which fixes the problem with a minimum of +effort (for example the reengineering of a great many Capstone chips). +*/ + +/* h files included here to make this just one file ... */ + +/* global.h */ + + + +/* sha.c */ +#include "SHA1.h" + +#include +#include + +static void SHAtoByte(BYTE *output, UINT4 *input, unsigned int len); + +/* The SHS block size and message digest sizes, in bytes */ + +#define SHS_DATASIZE 64 +#define SHS_DIGESTSIZE 20 + + +/* The SHS f()-functions. The f1 and f3 functions can be optimized to + save one boolean operation each - thanks to Rich Schroeppel, + rcs@cs.arizona.edu for discovering this */ + +/*#define f1(x,y,z) ( ( x & y ) | ( ~x & z ) ) // Rounds 0-19 */ +#define f1(x,y,z) ( z ^ ( x & ( y ^ z ) ) ) /* Rounds 0-19 */ +#define f2(x,y,z) ( x ^ y ^ z ) /* Rounds 20-39 */ +/*#define f3(x,y,z) ( ( x & y ) | ( x & z ) | ( y & z ) ) // Rounds 40-59 */ +#define f3(x,y,z) ( ( x & y ) | ( z & ( x | y ) ) ) /* Rounds 40-59 */ +#define f4(x,y,z) ( x ^ y ^ z ) /* Rounds 60-79 */ + +/* The SHS Mysterious Constants */ + +#define K1 0x5A827999L /* Rounds 0-19 */ +#define K2 0x6ED9EBA1L /* Rounds 20-39 */ +#define K3 0x8F1BBCDCL /* Rounds 40-59 */ +#define K4 0xCA62C1D6L /* Rounds 60-79 */ + +/* SHS initial values */ + +#define h0init 0x67452301L +#define h1init 0xEFCDAB89L +#define h2init 0x98BADCFEL +#define h3init 0x10325476L +#define h4init 0xC3D2E1F0L + +/* Note that it may be necessary to add parentheses to these macros if they + are to be called with expressions as arguments */ +/* 32-bit rotate left - kludged with shifts */ + +#define ROTL(n,X) ( ( ( X ) << n ) | ( ( X ) >> ( 32 - n ) ) ) + +/* The initial expanding function. The hash function is defined over an + 80-UINT2 expanded input array W, where the first 16 are copies of the input + data, and the remaining 64 are defined by + + W[ i ] = W[ i - 16 ] ^ W[ i - 14 ] ^ W[ i - 8 ] ^ W[ i - 3 ] + + This implementation generates these values on the fly in a circular + buffer - thanks to Colin Plumb, colin@nyx10.cs.du.edu for this + optimization. + + The updated SHS changes the expanding function by adding a rotate of 1 + bit. Thanks to Jim Gillogly, jim@rand.org, and an anonymous contributor + for this information */ + +#define expand(W,i) ( W[ i & 15 ] = ROTL( 1, ( W[ i & 15 ] ^ W[ (i - 14) & 15 ] ^ \ + W[ (i - 8) & 15 ] ^ W[ (i - 3) & 15 ] ) ) ) + + +/* The prototype SHS sub-round. The fundamental sub-round is: + + a' = e + ROTL( 5, a ) + f( b, c, d ) + k + data; + b' = a; + c' = ROTL( 30, b ); + d' = c; + e' = d; + + but this is implemented by unrolling the loop 5 times and renaming the + variables ( e, a, b, c, d ) = ( a', b', c', d', e' ) each iteration. + This code is then replicated 20 times for each of the 4 functions, using + the next 20 values from the W[] array each time */ + +#define subRound(a, b, c, d, e, f, k, data) \ + ( e += ROTL( 5, a ) + f( b, c, d ) + k + data, b = ROTL( 30, b ) ) + +/* Initialize the SHS values */ + +void SHAInit(SHA_CTX *shsInfo) +{ + endianTest(&shsInfo->Endianness); + /* Set the h-vars to their initial values */ + shsInfo->digest[ 0 ] = h0init; + shsInfo->digest[ 1 ] = h1init; + shsInfo->digest[ 2 ] = h2init; + shsInfo->digest[ 3 ] = h3init; + shsInfo->digest[ 4 ] = h4init; + + /* Initialise bit count */ + shsInfo->countLo = shsInfo->countHi = 0; +} + + +/* Perform the SHS transformation. Note that this code, like MD5, seems to + break some optimizing compilers due to the complexity of the expressions + and the size of the basic block. It may be necessary to split it into + sections, e.g. based on the four subrounds + + Note that this corrupts the shsInfo->data area */ + +static void SHSTransform( digest, data ) + UINT4 *digest, *data ; + { + UINT4 A, B, C, D, E; /* Local vars */ + UINT4 eData[ 16 ]; /* Expanded data */ + + /* Set up first buffer and local data buffer */ + A = digest[ 0 ]; + B = digest[ 1 ]; + C = digest[ 2 ]; + D = digest[ 3 ]; + E = digest[ 4 ]; + memcpy( (POINTER)eData, (POINTER)data, SHS_DATASIZE ); + + /* Heavy mangling, in 4 sub-rounds of 20 interations each. */ + subRound( A, B, C, D, E, f1, K1, eData[ 0 ] ); + subRound( E, A, B, C, D, f1, K1, eData[ 1 ] ); + subRound( D, E, A, B, C, f1, K1, eData[ 2 ] ); + subRound( C, D, E, A, B, f1, K1, eData[ 3 ] ); + subRound( B, C, D, E, A, f1, K1, eData[ 4 ] ); + subRound( A, B, C, D, E, f1, K1, eData[ 5 ] ); + subRound( E, A, B, C, D, f1, K1, eData[ 6 ] ); + subRound( D, E, A, B, C, f1, K1, eData[ 7 ] ); + subRound( C, D, E, A, B, f1, K1, eData[ 8 ] ); + subRound( B, C, D, E, A, f1, K1, eData[ 9 ] ); + subRound( A, B, C, D, E, f1, K1, eData[ 10 ] ); + subRound( E, A, B, C, D, f1, K1, eData[ 11 ] ); + subRound( D, E, A, B, C, f1, K1, eData[ 12 ] ); + subRound( C, D, E, A, B, f1, K1, eData[ 13 ] ); + subRound( B, C, D, E, A, f1, K1, eData[ 14 ] ); + subRound( A, B, C, D, E, f1, K1, eData[ 15 ] ); + subRound( E, A, B, C, D, f1, K1, expand( eData, 16 ) ); + subRound( D, E, A, B, C, f1, K1, expand( eData, 17 ) ); + subRound( C, D, E, A, B, f1, K1, expand( eData, 18 ) ); + subRound( B, C, D, E, A, f1, K1, expand( eData, 19 ) ); + + subRound( A, B, C, D, E, f2, K2, expand( eData, 20 ) ); + subRound( E, A, B, C, D, f2, K2, expand( eData, 21 ) ); + subRound( D, E, A, B, C, f2, K2, expand( eData, 22 ) ); + subRound( C, D, E, A, B, f2, K2, expand( eData, 23 ) ); + subRound( B, C, D, E, A, f2, K2, expand( eData, 24 ) ); + subRound( A, B, C, D, E, f2, K2, expand( eData, 25 ) ); + subRound( E, A, B, C, D, f2, K2, expand( eData, 26 ) ); + subRound( D, E, A, B, C, f2, K2, expand( eData, 27 ) ); + subRound( C, D, E, A, B, f2, K2, expand( eData, 28 ) ); + subRound( B, C, D, E, A, f2, K2, expand( eData, 29 ) ); + subRound( A, B, C, D, E, f2, K2, expand( eData, 30 ) ); + subRound( E, A, B, C, D, f2, K2, expand( eData, 31 ) ); + subRound( D, E, A, B, C, f2, K2, expand( eData, 32 ) ); + subRound( C, D, E, A, B, f2, K2, expand( eData, 33 ) ); + subRound( B, C, D, E, A, f2, K2, expand( eData, 34 ) ); + subRound( A, B, C, D, E, f2, K2, expand( eData, 35 ) ); + subRound( E, A, B, C, D, f2, K2, expand( eData, 36 ) ); + subRound( D, E, A, B, C, f2, K2, expand( eData, 37 ) ); + subRound( C, D, E, A, B, f2, K2, expand( eData, 38 ) ); + subRound( B, C, D, E, A, f2, K2, expand( eData, 39 ) ); + + subRound( A, B, C, D, E, f3, K3, expand( eData, 40 ) ); + subRound( E, A, B, C, D, f3, K3, expand( eData, 41 ) ); + subRound( D, E, A, B, C, f3, K3, expand( eData, 42 ) ); + subRound( C, D, E, A, B, f3, K3, expand( eData, 43 ) ); + subRound( B, C, D, E, A, f3, K3, expand( eData, 44 ) ); + subRound( A, B, C, D, E, f3, K3, expand( eData, 45 ) ); + subRound( E, A, B, C, D, f3, K3, expand( eData, 46 ) ); + subRound( D, E, A, B, C, f3, K3, expand( eData, 47 ) ); + subRound( C, D, E, A, B, f3, K3, expand( eData, 48 ) ); + subRound( B, C, D, E, A, f3, K3, expand( eData, 49 ) ); + subRound( A, B, C, D, E, f3, K3, expand( eData, 50 ) ); + subRound( E, A, B, C, D, f3, K3, expand( eData, 51 ) ); + subRound( D, E, A, B, C, f3, K3, expand( eData, 52 ) ); + subRound( C, D, E, A, B, f3, K3, expand( eData, 53 ) ); + subRound( B, C, D, E, A, f3, K3, expand( eData, 54 ) ); + subRound( A, B, C, D, E, f3, K3, expand( eData, 55 ) ); + subRound( E, A, B, C, D, f3, K3, expand( eData, 56 ) ); + subRound( D, E, A, B, C, f3, K3, expand( eData, 57 ) ); + subRound( C, D, E, A, B, f3, K3, expand( eData, 58 ) ); + subRound( B, C, D, E, A, f3, K3, expand( eData, 59 ) ); + + subRound( A, B, C, D, E, f4, K4, expand( eData, 60 ) ); + subRound( E, A, B, C, D, f4, K4, expand( eData, 61 ) ); + subRound( D, E, A, B, C, f4, K4, expand( eData, 62 ) ); + subRound( C, D, E, A, B, f4, K4, expand( eData, 63 ) ); + subRound( B, C, D, E, A, f4, K4, expand( eData, 64 ) ); + subRound( A, B, C, D, E, f4, K4, expand( eData, 65 ) ); + subRound( E, A, B, C, D, f4, K4, expand( eData, 66 ) ); + subRound( D, E, A, B, C, f4, K4, expand( eData, 67 ) ); + subRound( C, D, E, A, B, f4, K4, expand( eData, 68 ) ); + subRound( B, C, D, E, A, f4, K4, expand( eData, 69 ) ); + subRound( A, B, C, D, E, f4, K4, expand( eData, 70 ) ); + subRound( E, A, B, C, D, f4, K4, expand( eData, 71 ) ); + subRound( D, E, A, B, C, f4, K4, expand( eData, 72 ) ); + subRound( C, D, E, A, B, f4, K4, expand( eData, 73 ) ); + subRound( B, C, D, E, A, f4, K4, expand( eData, 74 ) ); + subRound( A, B, C, D, E, f4, K4, expand( eData, 75 ) ); + subRound( E, A, B, C, D, f4, K4, expand( eData, 76 ) ); + subRound( D, E, A, B, C, f4, K4, expand( eData, 77 ) ); + subRound( C, D, E, A, B, f4, K4, expand( eData, 78 ) ); + subRound( B, C, D, E, A, f4, K4, expand( eData, 79 ) ); + + /* Build message digest */ + digest[ 0 ] += A; + digest[ 1 ] += B; + digest[ 2 ] += C; + digest[ 3 ] += D; + digest[ 4 ] += E; + } + +/* When run on a little-endian CPU we need to perform byte reversal on an + array of long words. */ + +static void longReverse(UINT4 *buffer, int byteCount, int Endianness ) +{ + UINT4 value; + + if (Endianness==TRUE) return; + byteCount /= sizeof( UINT4 ); + while( byteCount-- ) + { + value = *buffer; + value = ( ( value & 0xFF00FF00L ) >> 8 ) | \ + ( ( value & 0x00FF00FFL ) << 8 ); + *buffer++ = ( value << 16 ) | ( value >> 16 ); + } +} + +/* Update SHS for a block of data */ + +void SHAUpdate(SHA_CTX *shsInfo, BYTE *buffer, int count) +{ + UINT4 tmp; + int dataCount; + + /* Update bitcount */ + tmp = shsInfo->countLo; + if ( ( shsInfo->countLo = tmp + ( ( UINT4 ) count << 3 ) ) < tmp ) + shsInfo->countHi++; /* Carry from low to high */ + shsInfo->countHi += count >> 29; + + /* Get count of bytes already in data */ + dataCount = ( int ) ( tmp >> 3 ) & 0x3F; + + /* Handle any leading odd-sized chunks */ + if( dataCount ) + { + BYTE *p = ( BYTE * ) shsInfo->data + dataCount; + + dataCount = SHS_DATASIZE - dataCount; + if( count < dataCount ) + { + memcpy( p, buffer, count ); + return; + } + memcpy( p, buffer, dataCount ); + longReverse( shsInfo->data, SHS_DATASIZE, shsInfo->Endianness); + SHSTransform( shsInfo->digest, shsInfo->data ); + buffer += dataCount; + count -= dataCount; + } + + /* Process data in SHS_DATASIZE chunks */ + while( count >= SHS_DATASIZE ) + { + memcpy( (POINTER)shsInfo->data, (POINTER)buffer, SHS_DATASIZE ); + longReverse( shsInfo->data, SHS_DATASIZE, shsInfo->Endianness ); + SHSTransform( shsInfo->digest, shsInfo->data ); + buffer += SHS_DATASIZE; + count -= SHS_DATASIZE; + } + + /* Handle any remaining bytes of data. */ + memcpy( (POINTER)shsInfo->data, (POINTER)buffer, count ); + } + +/* Final wrapup - pad to SHS_DATASIZE-byte boundary with the bit pattern + 1 0* (64-bit count of bits processed, MSB-first) */ + +void SHAFinal(BYTE *output, SHA_CTX *shsInfo) +{ + int count; + BYTE *dataPtr; + + /* Compute number of bytes mod 64 */ + count = ( int ) shsInfo->countLo; + count = ( count >> 3 ) & 0x3F; + + /* Set the first char of padding to 0x80. This is safe since there is + always at least one byte free */ + dataPtr = ( BYTE * ) shsInfo->data + count; + *dataPtr++ = 0x80; + + /* Bytes of padding needed to make 64 bytes */ + count = SHS_DATASIZE - 1 - count; + + /* Pad out to 56 mod 64 */ + if( count < 8 ) + { + /* Two lots of padding: Pad the first block to 64 bytes */ + memset( dataPtr, 0, count ); + longReverse( shsInfo->data, SHS_DATASIZE, shsInfo->Endianness ); + SHSTransform( shsInfo->digest, shsInfo->data ); + + /* Now fill the next block with 56 bytes */ + memset( (POINTER)shsInfo->data, 0, SHS_DATASIZE - 8 ); + } + else + /* Pad block to 56 bytes */ + memset( dataPtr, 0, count - 8 ); + + /* Append length in bits and transform */ + shsInfo->data[ 14 ] = shsInfo->countHi; + shsInfo->data[ 15 ] = shsInfo->countLo; + + longReverse( shsInfo->data, SHS_DATASIZE - 8, shsInfo->Endianness ); + SHSTransform( shsInfo->digest, shsInfo->data ); + + /* Output to an array of bytes */ + SHAtoByte(output, shsInfo->digest, SHS_DIGESTSIZE); + + /* Zeroise sensitive stuff */ + memset((POINTER)shsInfo, 0, sizeof(shsInfo)); +} + +static void SHAtoByte(BYTE *output, UINT4 *input, unsigned int len) +{ /* Output SHA digest in byte array */ + unsigned int i, j; + + for(i = 0, j = 0; j < len; i++, j += 4) + { + output[j+3] = (BYTE)( input[i] & 0xff); + output[j+2] = (BYTE)((input[i] >> 8 ) & 0xff); + output[j+1] = (BYTE)((input[i] >> 16) & 0xff); + output[j ] = (BYTE)((input[i] >> 24) & 0xff); + } +} + + + + +/* endian.c */ + +void endianTest(int *endian_ness) +{ + if((*(unsigned short *) ("#S") >> 8) == '#') + { + /* printf("Big endian = no change\n"); */ + *endian_ness = !(0); + } + else + { + /* printf("Little endian = swap\n"); */ + *endian_ness = 0; + } +} diff --git a/ext/libkirk/SHA1.h b/ext/libkirk/SHA1.h new file mode 100644 index 0000000000..ff0eba22ae --- /dev/null +++ b/ext/libkirk/SHA1.h @@ -0,0 +1,52 @@ +#ifndef _GLOBAL_H_ +#define _GLOBAL_H_ 1 + +/* POINTER defines a generic pointer type */ +typedef unsigned char *POINTER; + +/* UINT4 defines a four byte word */ +typedef unsigned int UINT4; + +/* BYTE defines a unsigned character */ +typedef unsigned char BYTE; + +#ifndef TRUE + #define FALSE 0 + #define TRUE ( !FALSE ) +#endif /* TRUE */ + +#endif /* end _GLOBAL_H_ */ + +/* sha.h */ + +#ifndef _SHA_H_ +#define _SHA_H_ 1 + +/* #include "global.h" */ + +/* The structure for storing SHS info */ + +typedef struct +{ + UINT4 digest[ 5 ]; /* Message digest */ + UINT4 countLo, countHi; /* 64-bit bit count */ + UINT4 data[ 16 ]; /* SHS data buffer */ + int Endianness; +} SHA_CTX; + +/* Message digest functions */ + +void SHAInit(SHA_CTX *); +void SHAUpdate(SHA_CTX *, BYTE *buffer, int count); +void SHAFinal(BYTE *output, SHA_CTX *); + +#endif /* end _SHA_H_ */ + +/* endian.h */ + +#ifndef _ENDIAN_H_ +#define _ENDIAN_H_ 1 + +void endianTest(int *endianness); + +#endif /* end _ENDIAN_H_ */ diff --git a/ext/libkirk/bn.c b/ext/libkirk/bn.c new file mode 100644 index 0000000000..0e42820342 --- /dev/null +++ b/ext/libkirk/bn.c @@ -0,0 +1,202 @@ +// Copyright 2007,2008,2010 Segher Boessenkool +// Licensed under the terms of the GNU GPL, version 2 +// http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt +// Updated and simplified for use by Kirk Engine - July 2011 + +#include +#include + +// Include definitions from kirk header +#include "kirk_engine.h" + +void bn_print(char *name, u8 *a, u32 n) +{ + u32 i; + + printf("%s = ", name); + + for (i = 0; i < n; i++) + printf("%02x", a[i]); + + printf("\n"); +} + +static void bn_zero(u8 *d, u32 n) +{ + memset(d, 0, n); +} + +void bn_copy(u8 *d, u8 *a, u32 n) +{ + memcpy(d, a, n); +} + +int bn_compare(u8 *a, u8 *b, u32 n) +{ + u32 i; + + for (i = 0; i < n; i++) { + if (a[i] < b[i]) + return -1; + if (a[i] > b[i]) + return 1; + } + + return 0; +} + +static u8 bn_add_1(u8 *d, u8 *a, u8 *b, u32 n) +{ + u32 i; + u32 dig; + u8 c; + + c = 0; + for (i = n - 1; i < n; i--) { + dig = a[i] + b[i] + c; + c = dig >> 8; + d[i] = dig; + } + + return c; +} + +static u8 bn_sub_1(u8 *d, u8 *a, u8 *b, u32 n) +{ + u32 i; + u32 dig; + u8 c; + + c = 1; + for (i = n - 1; i < n; i--) { + dig = a[i] + 255 - b[i] + c; + c = dig >> 8; + d[i] = dig; + } + + return 1 - c; +} + +void bn_reduce(u8 *d, u8 *N, u32 n) +{ + if (bn_compare(d, N, n) >= 0) + bn_sub_1(d, d, N, n); +} + +void bn_add(u8 *d, u8 *a, u8 *b, u8 *N, u32 n) +{ + if (bn_add_1(d, a, b, n)) + bn_sub_1(d, d, N, n); + + bn_reduce(d, N, n); +} + +void bn_sub(u8 *d, u8 *a, u8 *b, u8 *N, u32 n) +{ + if (bn_sub_1(d, a, b, n)) + bn_add_1(d, d, N, n); +} + +static const u8 inv256[0x80] = { + 0x01, 0xab, 0xcd, 0xb7, 0x39, 0xa3, 0xc5, 0xef, + 0xf1, 0x1b, 0x3d, 0xa7, 0x29, 0x13, 0x35, 0xdf, + 0xe1, 0x8b, 0xad, 0x97, 0x19, 0x83, 0xa5, 0xcf, + 0xd1, 0xfb, 0x1d, 0x87, 0x09, 0xf3, 0x15, 0xbf, + 0xc1, 0x6b, 0x8d, 0x77, 0xf9, 0x63, 0x85, 0xaf, + 0xb1, 0xdb, 0xfd, 0x67, 0xe9, 0xd3, 0xf5, 0x9f, + 0xa1, 0x4b, 0x6d, 0x57, 0xd9, 0x43, 0x65, 0x8f, + 0x91, 0xbb, 0xdd, 0x47, 0xc9, 0xb3, 0xd5, 0x7f, + 0x81, 0x2b, 0x4d, 0x37, 0xb9, 0x23, 0x45, 0x6f, + 0x71, 0x9b, 0xbd, 0x27, 0xa9, 0x93, 0xb5, 0x5f, + 0x61, 0x0b, 0x2d, 0x17, 0x99, 0x03, 0x25, 0x4f, + 0x51, 0x7b, 0x9d, 0x07, 0x89, 0x73, 0x95, 0x3f, + 0x41, 0xeb, 0x0d, 0xf7, 0x79, 0xe3, 0x05, 0x2f, + 0x31, 0x5b, 0x7d, 0xe7, 0x69, 0x53, 0x75, 0x1f, + 0x21, 0xcb, 0xed, 0xd7, 0x59, 0xc3, 0xe5, 0x0f, + 0x11, 0x3b, 0x5d, 0xc7, 0x49, 0x33, 0x55, 0xff, +}; + +static void bn_mon_muladd_dig(u8 *d, u8 *a, u8 b, u8 *N, u32 n) +{ + u32 dig; + u32 i; + + u8 z = -(d[n-1] + a[n-1]*b) * inv256[N[n-1]/2]; + + dig = d[n-1] + a[n-1]*b + N[n-1]*z; + dig >>= 8; + + for (i = n - 2; i < n; i--) { + dig += d[i] + a[i]*b + N[i]*z; + d[i+1] = dig; + dig >>= 8; + } + + d[0] = dig; + dig >>= 8; + + if (dig) + bn_sub_1(d, d, N, n); + + bn_reduce(d, N, n); +} + +void bn_mon_mul(u8 *d, u8 *a, u8 *b, u8 *N, u32 n) +{ + u8 t[512]; + u32 i; + + bn_zero(t, n); + + for (i = n - 1; i < n; i--) + bn_mon_muladd_dig(t, a, b[i], N, n); + + bn_copy(d, t, n); +} + +void bn_to_mon(u8 *d, u8 *N, u32 n) +{ + u32 i; + + for (i = 0; i < 8*n; i++) + bn_add(d, d, d, N, n); +} + +void bn_from_mon(u8 *d, u8 *N, u32 n) +{ + u8 t[512]; + + bn_zero(t, n); + t[n-1] = 1; + bn_mon_mul(d, d, t, N, n); +} + +static void bn_mon_exp(u8 *d, u8 *a, u8 *N, u32 n, u8 *e, u32 en) +{ + u8 t[512]; + u32 i; + u8 mask; + + bn_zero(d, n); + d[n-1] = 1; + bn_to_mon(d, N, n); + + for (i = 0; i < en; i++) + for (mask = 0x80; mask != 0; mask >>= 1) { + bn_mon_mul(t, d, d, N, n); + if ((e[i] & mask) != 0) + bn_mon_mul(d, t, a, N, n); + else + bn_copy(d, t, n); + } +} + +void bn_mon_inv(u8 *d, u8 *a, u8 *N, u32 n) +{ + u8 t[512], s[512]; + + bn_zero(s, n); + s[n-1] = 2; + bn_sub_1(t, N, s, n); + bn_mon_exp(d, a, N, n, t, n); +} diff --git a/ext/libkirk/cmd b/ext/libkirk/cmd new file mode 100644 index 0000000000..9593e32fa9 --- /dev/null +++ b/ext/libkirk/cmd @@ -0,0 +1,92 @@ +/usr/bin/c++ +-std=gnu++0x +CMakeFiles/ppsspp.dir/home/artart78/prog/psp/ppsspp/android/jni/NativeApp.cpp.o +CMakeFiles/ppsspp.dir/home/artart78/prog/psp/ppsspp/android/jni/EmuScreen.cpp.o +CMakeFiles/ppsspp.dir/home/artart78/prog/psp/ppsspp/android/jni/MenuScreens.cpp.o +CMakeFiles/ppsspp.dir/home/artart78/prog/psp/ppsspp/android/jni/GamepadEmu.cpp.o +CMakeFiles/ppsspp.dir/home/artart78/prog/psp/ppsspp/android/jni/UIShader.cpp.o +CMakeFiles/ppsspp.dir/home/artart78/prog/psp/ppsspp/android/jni/ui_atlas.cpp.o +CMakeFiles/ppsspp.dir/home/artart78/prog/psp/ppsspp/native/base/PCMain.cpp.o +-o +ppsspp +-rdynamic +-L/usr/local/lib +-L/opt/local/lib +-L/usr/X11/lib +-Wl,-Bstatic +-lSDLmain +-Wl,-Bdynamic +-lSDL +-lpthread +-lGLU +-lGL +-lSM +-lICE +-lX11 +-lXext +-lGLEW +kirk/libkirk.a +file/libfile.a +kirk/libkirk.a +math/liblin.a +kirk/libkirk.a +-lpng +kirk/libkirk.a +-lz +kirk/libkirk.a +gfx/libgfx.a +kirk/libkirk.a +gfx_es2/libgfx_es2.a +kirk/libkirk.a +etcpack/libetcdec.a +kirk/libkirk.a +image/libimage.a +kirk/libkirk.a +stb_image/libstb_image.a +kirk/libkirk.a +audio/libmixer.a +kirk/libkirk.a +net/libnet.a +kirk/libkirk.a +ui/libui.a +kirk/libkirk.a +profiler/libprofiler.a +kirk/libkirk.a +base/libtimeutil.a +kirk/libkirk.a +libzip/libzip.a +kirk/libkirk.a +base/libbase.a +kirk/libkirk.a +math/liblin.a +kirk/libkirk.a +vjson/libvjson.a +kirk/libkirk.a +stb_vorbis/libstb_vorbis.a +kirk/libkirk.a +sha1/libsha1.a +kirk/libkirk.a +jsonwriter/libjsonwriter.a +kirk/libkirk.a +Common/libcommon.a +kirk/libkirk.a +Core/libcore.a +kirk/libkirk.a +GPU/libgpu.a +kirk/libkirk.a +base/libbase.a +kirk/libkirk.a +Common/libcommon.a +kirk/libkirk.a +math/liblin.a +kirk/libkirk.a +gfx_es2/libgfx_es2.a +kirk/libkirk.a +file/libfile.a +kirk/libkirk.a +libzip/libzip.a +kirk/libkirk.a +gfx/libgfx.a +kirk/libkirk.a +-Wl,-rpath,/usr/local/lib:/opt/local/lib:/usr/X11/lib + diff --git a/ext/libkirk/ec.c b/ext/libkirk/ec.c new file mode 100644 index 0000000000..89892ddf0f --- /dev/null +++ b/ext/libkirk/ec.c @@ -0,0 +1,463 @@ +// Copyright 2007,2008,2010 Segher Boessenkool +// Licensed under the terms of the GNU GPL, version 2 +// http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt + + +// Modified for Kirk engine by setting single curve and internal function +// to support Kirk elliptic curve options.- July 2011 + +#include +#include + +// Include definitions from kirk header +#include "kirk_engine.h" + +struct point { + u8 x[20]; + u8 y[20]; +}; +// Simplified for use by Kirk Engine since it has only 1 curve + +u8 ec_p[20]; +u8 ec_a[20]; +u8 ec_b[20]; +u8 ec_N[21]; +struct point ec_G; // mon +struct point ec_Q; // mon +u8 ec_k[21]; + + + +void hex_dump(char *str, u8 *buf, int size) +{ + int i; + + if(str) + printf("%s:", str); + + for(i=0; ix, ec_p, 20); + bn_to_mon(p->y, ec_p, 20); +} + +static void point_from_mon(struct point *p) +{ + bn_from_mon(p->x, ec_p, 20); + bn_from_mon(p->y, ec_p, 20); +} + +#if 0 +static int point_is_on_curve(u8 *p) +{ + u8 s[20], t[20]; + u8 *x, *y; + + x = p; + y = p + 20; + + elt_square(t, x); + elt_mul(s, t, x); + + elt_mul(t, x, ec_a); + elt_add(s, s, t); + + elt_add(s, s, ec_b); + + elt_square(t, y); + elt_sub(s, s, t); + + return elt_is_zero(s); +} +#endif + +static void point_zero(struct point *p) +{ + elt_zero(p->x); + elt_zero(p->y); +} + +static int point_is_zero(struct point *p) +{ + return elt_is_zero(p->x) && elt_is_zero(p->y); +} + +static void point_double(struct point *r, struct point *p) +{ + u8 s[20], t[20]; + struct point pp; + u8 *px, *py, *rx, *ry; + + pp = *p; + + px = pp.x; + py = pp.y; + rx = r->x; + ry = r->y; + + if (elt_is_zero(py)) { + point_zero(r); + return; + } + + elt_square(t, px); // t = px*px + elt_add(s, t, t); // s = 2*px*px + elt_add(s, s, t); // s = 3*px*px + elt_add(s, s, ec_a); // s = 3*px*px + a + elt_add(t, py, py); // t = 2*py + elt_inv(t, t); // t = 1/(2*py) + elt_mul(s, s, t); // s = (3*px*px+a)/(2*py) + + elt_square(rx, s); // rx = s*s + elt_add(t, px, px); // t = 2*px + elt_sub(rx, rx, t); // rx = s*s - 2*px + + elt_sub(t, px, rx); // t = -(rx-px) + elt_mul(ry, s, t); // ry = -s*(rx-px) + elt_sub(ry, ry, py); // ry = -s*(rx-px) - py +} + +static void point_add(struct point *r, struct point *p, struct point *q) +{ + u8 s[20], t[20], u[20]; + u8 *px, *py, *qx, *qy, *rx, *ry; + struct point pp, qq; + + pp = *p; + qq = *q; + + px = pp.x; + py = pp.y; + qx = qq.x; + qy = qq.y; + rx = r->x; + ry = r->y; + + if (point_is_zero(&pp)) { + elt_copy(rx, qx); + elt_copy(ry, qy); + return; + } + + if (point_is_zero(&qq)) { + elt_copy(rx, px); + elt_copy(ry, py); + return; + } + + elt_sub(u, qx, px); + + if (elt_is_zero(u)) { + elt_sub(u, qy, py); + if (elt_is_zero(u)) + point_double(r, &pp); + else + point_zero(r); + + return; + } + + elt_inv(t, u); // t = 1/(qx-px) + elt_sub(u, qy, py); // u = qy-py + elt_mul(s, t, u); // s = (qy-py)/(qx-px) + + elt_square(rx, s); // rx = s*s + elt_add(t, px, qx); // t = px+qx + elt_sub(rx, rx, t); // rx = s*s - (px+qx) + + elt_sub(t, px, rx); // t = -(rx-px) + elt_mul(ry, s, t); // ry = -s*(rx-px) + elt_sub(ry, ry, py); // ry = -s*(rx-px) - py +} + +static void point_mul(struct point *d, u8 *a, struct point *b) // a is bignum +{ + u32 i; + u8 mask; + + point_zero(d); + + for (i = 0; i < 21; i++) + for (mask = 0x80; mask != 0; mask >>= 1) { + point_double(d, d); + if ((a[i] & mask) != 0) + point_add(d, d, b); + } +} +// Modified from original to support kirk engine use - July 2011 +// Added call to Kirk Random number generator rather than /dev/random + +static void generate_ecdsa(u8 *outR, u8 *outS, u8 *k, u8 *hash) +{ + u8 e[21]; + u8 kk[21]; + u8 m[21]; + u8 R[21]; + u8 S[21]; + u8 minv[21]; + struct point mG; + + e[0] = 0;R[0] = 0;S[0] = 0; + memcpy(e + 1, hash, 20); + bn_reduce(e, ec_N, 21); + + // Original removed for portability +//try_again: + //fp = fopen("/dev/random", "rb"); + //if (fread(m, sizeof m, 1, fp) != 1) + //fail("reading random"); + //fclose(fp); + //m[0] = 0; + //if (bn_compare(m, ec_N, 21) >= 0) + //goto try_again; + + // R = (mG).x + + // Added call back to kirk PRNG - July 2011 + kirk_CMD14(m+1, 20); + m[0] = 0; + + point_mul(&mG, m, &ec_G); + point_from_mon(&mG); + R[0] = 0; + elt_copy(R+1, mG.x); + + // S = m**-1*(e + Rk) (mod N) + + bn_copy(kk, k, 21); + bn_reduce(kk, ec_N, 21); + bn_to_mon(m, ec_N, 21); + bn_to_mon(e, ec_N, 21); + bn_to_mon(R, ec_N, 21); + bn_to_mon(kk, ec_N, 21); + + bn_mon_mul(S, R, kk, ec_N, 21); + bn_add(kk, S, e, ec_N, 21); + bn_mon_inv(minv, m, ec_N, 21); + bn_mon_mul(S, minv, kk, ec_N, 21); + + bn_from_mon(R, ec_N, 21); + bn_from_mon(S, ec_N, 21); + memcpy(outR,R+1,0x20); + memcpy(outS,S+1,0x20); +} + + // Signing = + // r = k *G; + // s = x*r+m / k + + // Verify = + // r/s * P = m/s * G + +// Slightly modified to support kirk compatible signature input - July 2011 +static int check_ecdsa(struct point *Q, u8 *inR, u8 *inS, u8 *hash) +{ + u8 Sinv[21]; + u8 e[21], R[21], S[21]; + u8 w1[21], w2[21]; + struct point r1, r2; + u8 rr[21]; + + e[0] = 0; + memcpy(e + 1, hash, 20); + bn_reduce(e, ec_N, 21); + R[0] = 0; + memcpy(R + 1, inR, 20); + bn_reduce(R, ec_N, 21); + S[0] = 0; + memcpy(S + 1, inS, 20); + bn_reduce(S, ec_N, 21); + + bn_to_mon(R, ec_N, 21); + bn_to_mon(S, ec_N, 21); + bn_to_mon(e, ec_N, 21); + // make Sinv = 1/S + bn_mon_inv(Sinv, S, ec_N, 21); + // w1 = m * Sinv + bn_mon_mul(w1, e, Sinv, ec_N, 21); + // w2 = r * Sinv + bn_mon_mul(w2, R, Sinv, ec_N, 21); + + // mod N both + bn_from_mon(w1, ec_N, 21); + bn_from_mon(w2, ec_N, 21); + + // r1 = m/s * G + point_mul(&r1, w1, &ec_G); + // r2 = r/s * P + point_mul(&r2, w2, Q); + + //r1 = r1 + r2 + point_add(&r1, &r1, &r2); + + point_from_mon(&r1); + + rr[0] = 0; + memcpy(rr + 1, r1.x, 20); + bn_reduce(rr, ec_N, 21); + + bn_from_mon(R, ec_N, 21); + bn_from_mon(S, ec_N, 21); + + return (bn_compare(rr, R, 21) == 0); +} + + +// Modified from original to support kirk engine use - July 2011 +void ec_priv_to_pub(u8 *k, u8 *Q) +{ + struct point ec_temp; + bn_to_mon(k, ec_N, 21); + point_mul(&ec_temp, k, &ec_G); + point_from_mon(&ec_temp); + //bn_from_mon(k, ec_N, 21); + memcpy(Q,ec_temp.x,20); + memcpy(Q+20,ec_temp.y,20); +} + +// Modified from original to support kirk engine use - July 2011 +void ec_pub_mult(u8 *k, u8 *Q) +{ + struct point ec_temp; + //bn_to_mon(k, ec_N, 21); + point_mul(&ec_temp, k, &ec_Q); + point_from_mon(&ec_temp); + //bn_from_mon(k, ec_N, 21); + memcpy(Q,ec_temp.x,20); + memcpy(Q+20,ec_temp.y,20); +} + + +// Simplified for use by Kirk Engine - NO LONGER COMPATIABLE WITH ORIGINAL VERSION - July 2011 +int ecdsa_set_curve(u8* p,u8* a,u8* b,u8* N,u8* Gx,u8* Gy) +{ + memcpy(ec_p,p,20); + memcpy(ec_a,a,20); + memcpy(ec_b,b,20); + memcpy(ec_N,N,21); + + bn_to_mon(ec_a, ec_p, 20); + bn_to_mon(ec_b, ec_p, 20); + + memcpy(ec_G.x, Gx, 20); + memcpy(ec_G.y, Gy, 20); + point_to_mon(&ec_G); + + return 0; +} + +void ecdsa_set_pub(u8 *Q) +{ + memcpy(ec_Q.x, Q, 20); + memcpy(ec_Q.y, Q+20, 20); + point_to_mon(&ec_Q); +} + +void ecdsa_set_priv(u8 *ink) +{ + u8 k[21]; + k[0]=0; + memcpy(k+1,ink,20); + bn_reduce(k, ec_N, 21); + + memcpy(ec_k, k, sizeof ec_k); +} + +int ecdsa_verify(u8 *hash, u8 *R, u8 *S) +{ + return check_ecdsa(&ec_Q, R, S, hash); +} + +void ecdsa_sign(u8 *hash, u8 *R, u8 *S) +{ + generate_ecdsa(R, S, ec_k, hash); +} + +int point_is_on_curve(u8 *p) +{ + u8 s[20], t[20]; + u8 *x, *y; + + x = p; + y = p + 20; + + elt_square(t, x); + elt_mul(s, t, x);// s = x^3 + + elt_mul(t, x, ec_a); + elt_add(s, s, t); //s = x^3 + a *x + + elt_add(s, s, ec_b);//s = x^3 + a *x + b + + elt_square(t, y); //t = y^2 + elt_sub(s, s, t); // is s - t = 0? + hex_dump("S", s, 20); + hex_dump("T", t,20); + return elt_is_zero(s); +} + +void dump_ecc(void) { + hex_dump("P", ec_p, 20); + hex_dump("a", ec_a, 20); + hex_dump("b", ec_b, 20); + hex_dump("N", ec_N, 21); + hex_dump("Gx", ec_G.x, 20); + hex_dump("Gy", ec_G.y, 20); +} diff --git a/ext/libkirk/kirk_engine.c b/ext/libkirk/kirk_engine.c new file mode 100644 index 0000000000..9b7e910d57 --- /dev/null +++ b/ext/libkirk/kirk_engine.c @@ -0,0 +1,640 @@ +/* + Draan proudly presents: + + With huge help from community: + coyotebean, Davee, hitchhikr, kgsws, liquidzigong, Mathieulh, Proxima, SilverSpring + + ******************** KIRK-ENGINE ******************** + An Open-Source implementation of KIRK (PSP crypto engine) algorithms and keys. + Includes also additional routines for hash forging. + + ******************** + + 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 3 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, see . +*/ + +#include +#include +#include +#include +#include "kirk_engine.h" +#include "AES.h" +#include "SHA1.h" + +/* ------------------------- KEY VAULT ------------------------- */ + +u8 kirk1_key[] = {0x98, 0xC9, 0x40, 0x97, 0x5C, 0x1D, 0x10, 0xE8, 0x7F, 0xE6, 0x0E, 0xA3, 0xFD, 0x03, 0xA8, 0xBA}; + +u8 kirk7_key03[] = {0x98, 0x02, 0xC4, 0xE6, 0xEC, 0x9E, 0x9E, 0x2F, 0xFC, 0x63, 0x4C, 0xE4, 0x2F, 0xBB, 0x46, 0x68}; +u8 kirk7_key04[] = {0x99, 0x24, 0x4C, 0xD2, 0x58, 0xF5, 0x1B, 0xCB, 0xB0, 0x61, 0x9C, 0xA7, 0x38, 0x30, 0x07, 0x5F}; +u8 kirk7_key05[] = {0x02, 0x25, 0xD7, 0xBA, 0x63, 0xEC, 0xB9, 0x4A, 0x9D, 0x23, 0x76, 0x01, 0xB3, 0xF6, 0xAC, 0x17}; +u8 kirk7_key0C[] = {0x84, 0x85, 0xC8, 0x48, 0x75, 0x08, 0x43, 0xBC, 0x9B, 0x9A, 0xEC, 0xA7, 0x9C, 0x7F, 0x60, 0x18}; +u8 kirk7_key0D[] = {0xB5, 0xB1, 0x6E, 0xDE, 0x23, 0xA9, 0x7B, 0x0E, 0xA1, 0x7C, 0xDB, 0xA2, 0xDC, 0xDE, 0xC4, 0x6E}; +u8 kirk7_key0E[] = {0xC8, 0x71, 0xFD, 0xB3, 0xBC, 0xC5, 0xD2, 0xF2, 0xE2, 0xD7, 0x72, 0x9D, 0xDF, 0x82, 0x68, 0x82}; +u8 kirk7_key0F[] = {0x0A, 0xBB, 0x33, 0x6C, 0x96, 0xD4, 0xCD, 0xD8, 0xCB, 0x5F, 0x4B, 0xE0, 0xBA, 0xDB, 0x9E, 0x03}; +u8 kirk7_key10[] = {0x32, 0x29, 0x5B, 0xD5, 0xEA, 0xF7, 0xA3, 0x42, 0x16, 0xC8, 0x8E, 0x48, 0xFF, 0x50, 0xD3, 0x71}; +u8 kirk7_key11[] = {0x46, 0xF2, 0x5E, 0x8E, 0x4D, 0x2A, 0xA5, 0x40, 0x73, 0x0B, 0xC4, 0x6E, 0x47, 0xEE, 0x6F, 0x0A}; +u8 kirk7_key12[] = {0x5D, 0xC7, 0x11, 0x39, 0xD0, 0x19, 0x38, 0xBC, 0x02, 0x7F, 0xDD, 0xDC, 0xB0, 0x83, 0x7D, 0x9D}; +u8 kirk7_key38[] = {0x12, 0x46, 0x8D, 0x7E, 0x1C, 0x42, 0x20, 0x9B, 0xBA, 0x54, 0x26, 0x83, 0x5E, 0xB0, 0x33, 0x03}; +u8 kirk7_key39[] = {0xC4, 0x3B, 0xB6, 0xD6, 0x53, 0xEE, 0x67, 0x49, 0x3E, 0xA9, 0x5F, 0xBC, 0x0C, 0xED, 0x6F, 0x8A}; +u8 kirk7_key3A[] = {0x2C, 0xC3, 0xCF, 0x8C, 0x28, 0x78, 0xA5, 0xA6, 0x63, 0xE2, 0xAF, 0x2D, 0x71, 0x5E, 0x86, 0xBA}; +u8 kirk7_key4B[] = {0x0C, 0xFD, 0x67, 0x9A, 0xF9, 0xB4, 0x72, 0x4F, 0xD7, 0x8D, 0xD6, 0xE9, 0x96, 0x42, 0x28, 0x8B}; //1.xx game eboot.bin +u8 kirk7_key53[] = {0xAF, 0xFE, 0x8E, 0xB1, 0x3D, 0xD1, 0x7E, 0xD8, 0x0A, 0x61, 0x24, 0x1C, 0x95, 0x92, 0x56, 0xB6}; +u8 kirk7_key57[] = {0x1C, 0x9B, 0xC4, 0x90, 0xE3, 0x06, 0x64, 0x81, 0xFA, 0x59, 0xFD, 0xB6, 0x00, 0xBB, 0x28, 0x70}; +u8 kirk7_key5D[] = {0x11, 0x5A, 0x5D, 0x20, 0xD5, 0x3A, 0x8D, 0xD3, 0x9C, 0xC5, 0xAF, 0x41, 0x0F, 0x0F, 0x18, 0x6F}; +u8 kirk7_key63[] = {0x9C, 0x9B, 0x13, 0x72, 0xF8, 0xC6, 0x40, 0xCF, 0x1C, 0x62, 0xF5, 0xD5, 0x92, 0xDD, 0xB5, 0x82}; +u8 kirk7_key64[] = {0x03, 0xB3, 0x02, 0xE8, 0x5F, 0xF3, 0x81, 0xB1, 0x3B, 0x8D, 0xAA, 0x2A, 0x90, 0xFF, 0x5E, 0x61}; + +u8 kirk16_key[] = {0x47, 0x5E, 0x09, 0xF4, 0xA2, 0x37, 0xDA, 0x9B, 0xEF, 0xFF, 0x3B, 0xC0, 0x77, 0x14, 0x3D, 0x8A}; + +/* ECC Curves for Kirk 1 and Kirk 0x11 */ +// Common Curve paramters p and a +static u8 ec_p[20] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; +static u8 ec_a[20] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC}; // mon + +// Kirk 0xC,0xD,0x10,0x11,(likely 0x12)- Unique curve parameters for b, N, and base point G for Kirk 0xC,0xD,0x10,0x11,(likely 0x12) service +// Since public key is variable, it is not specified here +static u8 ec_b2[20] = {0xA6, 0x8B, 0xED, 0xC3, 0x34, 0x18, 0x02, 0x9C, 0x1D, 0x3C, 0xE3, 0x3B, 0x9A, 0x32, 0x1F, 0xCC, 0xBB, 0x9E, 0x0F, 0x0B};// mon +static u8 ec_N2[21] = {0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xB5, 0xAE, 0x3C, 0x52, 0x3E, 0x63, 0x94, 0x4F, 0x21, 0x27}; +static u8 Gx2[20] = {0x12, 0x8E, 0xC4, 0x25, 0x64, 0x87, 0xFD, 0x8F, 0xDF, 0x64, 0xE2, 0x43, 0x7B, 0xC0, 0xA1, 0xF6, 0xD5, 0xAF, 0xDE, 0x2C }; +static u8 Gy2[20] = {0x59, 0x58, 0x55, 0x7E, 0xB1, 0xDB, 0x00, 0x12, 0x60, 0x42, 0x55, 0x24, 0xDB, 0xC3, 0x79, 0xD5, 0xAC, 0x5F, 0x4A, 0xDF }; + +// KIRK 1 - Unique curve parameters for b, N, and base point G +// Since public key is hard coded, it is also included + +static u8 ec_b1[20] = {0x65, 0xD1, 0x48, 0x8C, 0x03, 0x59, 0xE2, 0x34, 0xAD, 0xC9, 0x5B, 0xD3, 0x90, 0x80, 0x14, 0xBD, 0x91, 0xA5, 0x25, 0xF9}; +static u8 ec_N1[21] = {0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01, 0xB5, 0xC6, 0x17, 0xF2, 0x90, 0xEA, 0xE1, 0xDB, 0xAD, 0x8F}; +static u8 Gx1[20] = {0x22, 0x59, 0xAC, 0xEE, 0x15, 0x48, 0x9C, 0xB0, 0x96, 0xA8, 0x82, 0xF0, 0xAE, 0x1C, 0xF9, 0xFD, 0x8E, 0xE5, 0xF8, 0xFA }; +static u8 Gy1[20] = {0x60, 0x43, 0x58, 0x45, 0x6D, 0x0A, 0x1C, 0xB2, 0x90, 0x8D, 0xE9, 0x0F, 0x27, 0xD7, 0x5C, 0x82, 0xBE, 0xC1, 0x08, 0xC0 }; + +static u8 Px1[20] = {0xED, 0x9C, 0xE5, 0x82, 0x34, 0xE6, 0x1A, 0x53, 0xC6, 0x85, 0xD6, 0x4D, 0x51, 0xD0, 0x23, 0x6B, 0xC3, 0xB5, 0xD4, 0xB9 }; +static u8 Py1[20] = {0x04, 0x9D, 0xF1, 0xA0, 0x75, 0xC0, 0xE0, 0x4F, 0xB3, 0x44, 0x85, 0x8B, 0x61, 0xB7, 0x9B, 0x69, 0xA6, 0x3D, 0x2C, 0x39 }; + +/* ------------------------- KEY VAULT END ------------------------- */ + +/* ------------------------- INTERNAL STUFF ------------------------- */ +typedef struct blah +{ + u8 fuseid[8]; //0 + u8 mesh[0x40]; //0x8 +} kirk16_data; //0x48 + +typedef struct header_keys +{ + u8 AES[16]; + u8 CMAC[16]; +}header_keys; //small struct for temporary keeping AES & CMAC key from CMD1 header + + +u32 g_fuse90; // This is to match FuseID HW at BC100090 and BC100094 +u32 g_fuse94; + +AES_ctx aes_kirk1; //global +u8 PRNG_DATA[0x14]; + +char is_kirk_initialized; //"init" emulation + +/* ------------------------- INTERNAL STUFF END ------------------------- */ + + +/* ------------------------- IMPLEMENTATION ------------------------- */ + +int kirk_CMD0(u8* outbuff, u8* inbuff, int size, int generate_trash) +{ + KIRK_CMD1_HEADER* header = (KIRK_CMD1_HEADER*)outbuff; + header_keys *keys = (header_keys *)outbuff; //0-15 AES key, 16-31 CMAC key + int chk_size; + AES_ctx k1; + AES_ctx cmac_key; + u8 cmac_header_hash[16]; + u8 cmac_data_hash[16]; + + if(is_kirk_initialized == 0) return KIRK_NOT_INITIALIZED; + + memcpy(outbuff, inbuff, size); + + if(header->mode != KIRK_MODE_CMD1) return KIRK_INVALID_MODE; + + //FILL PREDATA WITH RANDOM DATA + if(generate_trash) kirk_CMD14(outbuff+sizeof(KIRK_CMD1_HEADER), header->data_offset); + + //Make sure data is 16 aligned + chk_size = header->data_size; + if(chk_size % 16) chk_size += 16 - (chk_size % 16); + + //ENCRYPT DATA + AES_set_key(&k1, keys->AES, 128); + AES_cbc_encrypt(&k1, inbuff+sizeof(KIRK_CMD1_HEADER)+header->data_offset, (u8*)outbuff+sizeof(KIRK_CMD1_HEADER)+header->data_offset, chk_size); + + //CMAC HASHES + AES_set_key(&cmac_key, keys->CMAC, 128); + AES_CMAC(&cmac_key, outbuff+0x60, 0x30, cmac_header_hash); + AES_CMAC(&cmac_key, outbuff+0x60, 0x30 + chk_size + header->data_offset, cmac_data_hash); + + memcpy(header->CMAC_header_hash, cmac_header_hash, 16); + memcpy(header->CMAC_data_hash, cmac_data_hash, 16); + + //ENCRYPT KEYS + AES_cbc_encrypt(&aes_kirk1, inbuff, outbuff, 16*2); + return KIRK_OPERATION_SUCCESS; +} + +int kirk_CMD1(u8* outbuff, u8* inbuff, int size) +{ + KIRK_CMD1_HEADER* header = (KIRK_CMD1_HEADER*)inbuff; + header_keys keys; //0-15 AES key, 16-31 CMAC key + AES_ctx k1; + + if(size < 0x90) return KIRK_INVALID_SIZE; + if(is_kirk_initialized == 0) return KIRK_NOT_INITIALIZED; + if(header->mode != KIRK_MODE_CMD1) return KIRK_INVALID_MODE; + + AES_cbc_decrypt(&aes_kirk1, inbuff, (u8*)&keys, 16*2); //decrypt AES & CMAC key to temp buffer + + if(header->ecdsa_hash == 1) + { + SHA_CTX sha; + KIRK_CMD1_ECDSA_HEADER* eheader = (KIRK_CMD1_ECDSA_HEADER*) inbuff; + u8 kirk1_pub[40]; + u8 header_hash[20];u8 data_hash[20]; + ecdsa_set_curve(ec_p,ec_a,ec_b1,ec_N1,Gx1,Gy1); + memcpy(kirk1_pub,Px1,20); + memcpy(kirk1_pub+20,Py1,20); + ecdsa_set_pub(kirk1_pub); + //Hash the Header + SHAInit(&sha); + SHAUpdate(&sha, (u8*)eheader+0x60, 0x30); + SHAFinal(header_hash, &sha); + + if(!ecdsa_verify(header_hash,eheader->header_sig_r,eheader->header_sig_s)) { + return KIRK_HEADER_HASH_INVALID; + } + SHAInit(&sha); + SHAUpdate(&sha, (u8*)eheader+0x60, size-0x60); + SHAFinal(data_hash, &sha); + + if(!ecdsa_verify(data_hash,eheader->data_sig_r,eheader->data_sig_s)) { + return KIRK_DATA_HASH_INVALID; + } + + } else { + int ret = kirk_CMD10(inbuff, size); + if(ret != KIRK_OPERATION_SUCCESS) return ret; + } + + AES_set_key(&k1, keys.AES, 128); + AES_cbc_decrypt(&k1, inbuff+sizeof(KIRK_CMD1_HEADER)+header->data_offset, outbuff, header->data_size); + + return KIRK_OPERATION_SUCCESS; +} + +int kirk_CMD4(u8* outbuff, u8* inbuff, int size) +{ + KIRK_AES128CBC_HEADER *header = (KIRK_AES128CBC_HEADER*)inbuff; + u8* key; + AES_ctx aesKey; + + if(is_kirk_initialized == 0) return KIRK_NOT_INITIALIZED; + if(header->mode != KIRK_MODE_ENCRYPT_CBC) return KIRK_INVALID_MODE; + if(header->data_size == 0) return KIRK_DATA_SIZE_ZERO; + + key = kirk_4_7_get_key(header->keyseed); + if(key == (u8*)KIRK_INVALID_SIZE) return KIRK_INVALID_SIZE; + + //Set the key + AES_set_key(&aesKey, key, 128); + AES_cbc_encrypt(&aesKey, inbuff+sizeof(KIRK_AES128CBC_HEADER), outbuff+sizeof(KIRK_AES128CBC_HEADER), size); + + return KIRK_OPERATION_SUCCESS; +} + +int kirk_CMD7(u8* outbuff, u8* inbuff, int size) +{ + KIRK_AES128CBC_HEADER *header = (KIRK_AES128CBC_HEADER*)inbuff; + u8* key; + AES_ctx aesKey; + + if(is_kirk_initialized == 0) return KIRK_NOT_INITIALIZED; + if(header->mode != KIRK_MODE_DECRYPT_CBC) return KIRK_INVALID_MODE; + if(header->data_size == 0) return KIRK_DATA_SIZE_ZERO; + + key = kirk_4_7_get_key(header->keyseed); + if(key == (u8*)KIRK_INVALID_SIZE) return KIRK_INVALID_SIZE; + + //Set the key + AES_set_key(&aesKey, key, 128); + AES_cbc_decrypt(&aesKey, inbuff+sizeof(KIRK_AES128CBC_HEADER), outbuff, size); + + return KIRK_OPERATION_SUCCESS; +} + +int kirk_CMD10(u8* inbuff, int insize) +{ + KIRK_CMD1_HEADER* header = (KIRK_CMD1_HEADER*)inbuff; + header_keys keys; //0-15 AES key, 16-31 CMAC key + u8 cmac_header_hash[16]; + u8 cmac_data_hash[16]; + AES_ctx cmac_key; + int chk_size; + + if(is_kirk_initialized == 0) return KIRK_NOT_INITIALIZED; + if(!(header->mode == KIRK_MODE_CMD1 || header->mode == KIRK_MODE_CMD2 || header->mode == KIRK_MODE_CMD3)) return KIRK_INVALID_MODE; + if(header->data_size == 0) return KIRK_DATA_SIZE_ZERO; + + if(header->mode == KIRK_MODE_CMD1) + { + AES_cbc_decrypt(&aes_kirk1, inbuff, (u8*)&keys, 32); //decrypt AES & CMAC key to temp buffer + AES_set_key(&cmac_key, keys.CMAC, 128); + AES_CMAC(&cmac_key, inbuff+0x60, 0x30, cmac_header_hash); + + //Make sure data is 16 aligned + chk_size = header->data_size; + if(chk_size % 16) chk_size += 16 - (chk_size % 16); + AES_CMAC(&cmac_key, inbuff+0x60, 0x30 + chk_size + header->data_offset, cmac_data_hash); + + if(memcmp(cmac_header_hash, header->CMAC_header_hash, 16) != 0) return KIRK_HEADER_HASH_INVALID; + if(memcmp(cmac_data_hash, header->CMAC_data_hash, 16) != 0) return KIRK_DATA_HASH_INVALID; + + return KIRK_OPERATION_SUCCESS; + } + return KIRK_SIG_CHECK_INVALID; //Checks for cmd 2 & 3 not included right now +} + +int kirk_CMD11(u8* outbuff, u8* inbuff, int size) +{ + KIRK_SHA1_HEADER *header = (KIRK_SHA1_HEADER *)inbuff; + SHA_CTX sha; + if(is_kirk_initialized == 0) return KIRK_NOT_INITIALIZED; + if(header->data_size == 0 || size == 0) return KIRK_DATA_SIZE_ZERO; + + SHAInit(&sha); + SHAUpdate(&sha, inbuff+sizeof(KIRK_SHA1_HEADER), header->data_size); + SHAFinal(outbuff, &sha); + return KIRK_OPERATION_SUCCESS; +} + +// Generate an ECDSA Key pair +// offset 0 = private key (0x14 len) +// offset 0x14 = public key point (0x28 len) +int kirk_CMD12(u8 * outbuff, int outsize) { + u8 k[0x15]; + KIRK_CMD12_BUFFER * keypair = (KIRK_CMD12_BUFFER *) outbuff; + + if(outsize != 0x3C) return KIRK_INVALID_SIZE; + ecdsa_set_curve(ec_p,ec_a,ec_b2,ec_N2,Gx2,Gy2); + k[0] = 0; + kirk_CMD14(k+1,0x14); + ec_priv_to_pub(k, (u8*)keypair->public_key.x); + memcpy(keypair->private_key,k+1,0x14); + + return KIRK_OPERATION_SUCCESS; +} +// Point multiplication +// offset 0 = mulitplication value (0x14 len) +// offset 0x14 = point to multiply (0x28 len) +int kirk_CMD13(u8 * outbuff, int outsize,u8 * inbuff, int insize) { + u8 k[0x15]; + KIRK_CMD13_BUFFER * pointmult = (KIRK_CMD13_BUFFER *) inbuff; + k[0]=0; + if(outsize != 0x28) return KIRK_INVALID_SIZE; + if(insize != 0x3C) return KIRK_INVALID_SIZE; + ecdsa_set_curve(ec_p,ec_a,ec_b2,ec_N2,Gx2,Gy2); + ecdsa_set_pub((u8*)pointmult->public_key.x); + memcpy(k+1,pointmult->multiplier,0x14); + ec_pub_mult(k, outbuff); + return KIRK_OPERATION_SUCCESS; +} + +int kirk_CMD14(u8 * outbuff, int outsize) { + u8 temp[0x104]; + KIRK_SHA1_HEADER *header = (KIRK_SHA1_HEADER *) temp; + + // Some randomly selected data for a "key" to add to each randomization + u8 key[0x10] = { 0xA7, 0x2E, 0x4C, 0xB6, 0xC3, 0x34, 0xDF, 0x85, 0x70, 0x01, 0x49, 0xFC, 0xC0, 0x87, 0xC4, 0x77 }; + u32 curtime; + //if(outsize != 0x14) return KIRK_INVALID_SIZE; // Need real error code + if(outsize <=0) return KIRK_OPERATION_SUCCESS; + + memcpy(temp+4, PRNG_DATA,0x14); + // This uses the standard C time function for portability. + curtime=time(0); + temp[0x18] = curtime &0xFF; + temp[0x19] = (curtime>>8) &0xFF; + temp[0x1A] = (curtime>>16) &0xFF; + temp[0x1B] = (curtime>>24) &0xFF; + memcpy(&temp[0x1C], key, 0x10); + //This leaves the remainder of the 0x100 bytes in temp to whatever remains on the stack + // in an uninitialized state. This should add unpredicableness to the results as well + header->data_size=0x100; + kirk_CMD11(PRNG_DATA, temp, 0x104); + while(outsize) + { + int blockrem= outsize %0x14; + int block = outsize /0x14; + + if(block) + { + memcpy(outbuff, PRNG_DATA, 0x14); + outbuff+=0x14; + outsize -= 0x14; + kirk_CMD14(outbuff, outsize); + } else { + if(blockrem) + { + memcpy(outbuff, PRNG_DATA, blockrem); + outsize -= blockrem; + } + } + + } + return KIRK_OPERATION_SUCCESS; +} + +void decrypt_kirk16_private(u8 *dA_out, u8 *dA_enc) +{ + int i, k; + kirk16_data keydata; + u8 subkey_1[0x10], subkey_2[0x10]; + rijndael_ctx aes_ctx; + + keydata.fuseid[7] = g_fuse90 &0xFF; + keydata.fuseid[6] = (g_fuse90>>8) &0xFF; + keydata.fuseid[5] = (g_fuse90>>16) &0xFF; + keydata.fuseid[4] = (g_fuse90>>24) &0xFF; + keydata.fuseid[3] = g_fuse94 &0xFF; + keydata.fuseid[2] = (g_fuse94>>8) &0xFF; + keydata.fuseid[1] = (g_fuse94>>16) &0xFF; + keydata.fuseid[0] = (g_fuse94>>24) &0xFF; + + /* set encryption key */ + rijndael_set_key(&aes_ctx, kirk16_key, 128); + + /* set the subkeys */ + for (i = 0; i < 0x10; i++) + { + /* set to the fuseid */ + subkey_2[i] = subkey_1[i] = keydata.fuseid[i % 8]; + } + + /* do aes crypto */ + for (i = 0; i < 3; i++) + { + /* encrypt + decrypt */ + rijndael_encrypt(&aes_ctx, subkey_1, subkey_1); + rijndael_decrypt(&aes_ctx, subkey_2, subkey_2); + } + + /* set new key */ + rijndael_set_key(&aes_ctx, subkey_1, 128); + + /* now lets make the key mesh */ + for (i = 0; i < 3; i++) + { + /* do encryption in group of 3 */ + for (k = 0; k < 3; k++) + { + /* crypto */ + rijndael_encrypt(&aes_ctx, subkey_2, subkey_2); + } + + /* copy to out block */ + memcpy(&keydata.mesh[i * 0x10], subkey_2, 0x10); + } + + /* set the key to the mesh */ + rijndael_set_key(&aes_ctx, &keydata.mesh[0x20], 128); + + /* do the encryption routines for the aes key */ + for (i = 0; i < 2; i++) + { + /* encrypt the data */ + rijndael_encrypt(&aes_ctx, &keydata.mesh[0x10], &keydata.mesh[0x10]); + } + + /* set the key to that mesh shit */ + rijndael_set_key(&aes_ctx, &keydata.mesh[0x10], 128); + + /* cbc decrypt the dA */ + AES_cbc_decrypt((AES_ctx *)&aes_ctx, dA_enc, dA_out, 0x20); +} + +void encrypt_kirk16_private(u8 *dA_out, u8 *dA_dec) +{ + int i, k; + kirk16_data keydata; + u8 subkey_1[0x10], subkey_2[0x10]; + rijndael_ctx aes_ctx; + + + keydata.fuseid[7] = g_fuse90 &0xFF; + keydata.fuseid[6] = (g_fuse90>>8) &0xFF; + keydata.fuseid[5] = (g_fuse90>>16) &0xFF; + keydata.fuseid[4] = (g_fuse90>>24) &0xFF; + keydata.fuseid[3] = g_fuse94 &0xFF; + keydata.fuseid[2] = (g_fuse94>>8) &0xFF; + keydata.fuseid[1] = (g_fuse94>>16) &0xFF; + keydata.fuseid[0] = (g_fuse94>>24) &0xFF; + /* set encryption key */ + rijndael_set_key(&aes_ctx, kirk16_key, 128); + + /* set the subkeys */ + for (i = 0; i < 0x10; i++) + { + /* set to the fuseid */ + subkey_2[i] = subkey_1[i] = keydata.fuseid[i % 8]; + } + + /* do aes crypto */ + for (i = 0; i < 3; i++) + { + /* encrypt + decrypt */ + rijndael_encrypt(&aes_ctx, subkey_1, subkey_1); + rijndael_decrypt(&aes_ctx, subkey_2, subkey_2); + } + + /* set new key */ + rijndael_set_key(&aes_ctx, subkey_1, 128); + + /* now lets make the key mesh */ + for (i = 0; i < 3; i++) + { + /* do encryption in group of 3 */ + for (k = 0; k < 3; k++) + { + /* crypto */ + rijndael_encrypt(&aes_ctx, subkey_2, subkey_2); + } + + /* copy to out block */ + memcpy(&keydata.mesh[i * 0x10], subkey_2, 0x10); + } + + /* set the key to the mesh */ + rijndael_set_key(&aes_ctx, &keydata.mesh[0x20], 128); + + /* do the encryption routines for the aes key */ + for (i = 0; i < 2; i++) + { + /* encrypt the data */ + rijndael_encrypt(&aes_ctx, &keydata.mesh[0x10], &keydata.mesh[0x10]); + } + + /* set the key to that mesh shit */ + rijndael_set_key(&aes_ctx, &keydata.mesh[0x10], 128); + + /* cbc encrypt the dA */ + AES_cbc_encrypt((AES_ctx *)&aes_ctx, dA_dec, dA_out, 0x20); +} + +int kirk_CMD16(u8 * outbuff, int outsize, u8 * inbuff, int insize) { + u8 dec_private[0x20]; + KIRK_CMD16_BUFFER * signbuf = (KIRK_CMD16_BUFFER *) inbuff; + ECDSA_SIG * sig = (ECDSA_SIG *) outbuff; + if(insize != 0x34) return KIRK_INVALID_SIZE; + if(outsize != 0x28) return KIRK_INVALID_SIZE; + decrypt_kirk16_private(dec_private,signbuf->enc_private); + // Clear out the padding for safety + memset(&dec_private[0x14], 0, 0xC); + ecdsa_set_curve(ec_p,ec_a,ec_b2,ec_N2,Gx2,Gy2); + ecdsa_set_priv(dec_private); + ecdsa_sign(signbuf->message_hash,sig->r, sig->s); + return KIRK_OPERATION_SUCCESS; +} + +// ECDSA Verify +// inbuff structure: +// 00 = public key (0x28 length) +// 28 = message hash (0x14 length) +// 3C = signature R (0x14 length) +// 50 = signature S (0x14 length) +int kirk_CMD17(u8 * inbuff, int insize) { + KIRK_CMD17_BUFFER * sig = (KIRK_CMD17_BUFFER *) inbuff; + if(insize != 0x64) return KIRK_INVALID_SIZE; + ecdsa_set_curve(ec_p,ec_a,ec_b2,ec_N2,Gx2,Gy2); + ecdsa_set_pub(sig->public_key.x); + // ecdsa_verify(u8 *hash, u8 *R, u8 *S) + if(ecdsa_verify(sig->message_hash,sig->signature.r,sig->signature.s)) { + return KIRK_OPERATION_SUCCESS; + } else { + return KIRK_SIG_CHECK_INVALID; + } +} + + + +int kirk_init() +{ + return kirk_init2((u8*)"Lazy Dev should have initialized!",33,0xBABEF00D, 0xDEADBEEF );; +} + +int kirk_init2(u8 * rnd_seed, u32 seed_size, u32 fuseid_90, u32 fuseid_94) { + u8 temp[0x104]; + + KIRK_SHA1_HEADER *header = (KIRK_SHA1_HEADER *) temp; + // Another randomly selected data for a "key" to add to each randomization + u8 key[0x10] = {0x07, 0xAB, 0xEF, 0xF8, 0x96, 0x8C, 0xF3, 0xD6, 0x14, 0xE0, 0xEB, 0xB2, 0x9D, 0x8B, 0x4E, 0x74}; + u32 curtime; + + //Set PRNG_DATA initially, otherwise use what ever uninitialized data is in the buffer + if(seed_size > 0) { + u8 * seedbuf; + KIRK_SHA1_HEADER *seedheader;; + seedbuf=(u8*)malloc(seed_size+4); + seedheader= (KIRK_SHA1_HEADER *) seedbuf; + seedheader->data_size = seed_size; + kirk_CMD11(PRNG_DATA, seedbuf, seed_size+4); + free(seedbuf); + } + memcpy(temp+4, PRNG_DATA,0x14); + // This uses the standard C time function for portability. + curtime=time(0); + temp[0x18] = curtime &0xFF; + temp[0x19] = (curtime>>8) &0xFF; + temp[0x1A] = (curtime>>16) &0xFF; + temp[0x1B] = (curtime>>24) &0xFF; + memcpy(&temp[0x1C], key, 0x10); + //This leaves the remainder of the 0x100 bytes in temp to whatever remains on the stack + // in an uninitialized state. This should add unpredicableness to the results as well + header->data_size=0x100; + kirk_CMD11(PRNG_DATA, temp, 0x104); + + //Set Fuse ID + g_fuse90=fuseid_90; + g_fuse94=fuseid_94; + + //Set KIRK1 main key + AES_set_key(&aes_kirk1, kirk1_key, 128); + + + is_kirk_initialized = 1; + return 0; +} +u8* kirk_4_7_get_key(int key_type) +{ + switch(key_type) + { + case(0x03): return kirk7_key03; break; + case(0x04): return kirk7_key04; break; + case(0x05): return kirk7_key05; break; + case(0x0C): return kirk7_key0C; break; + case(0x0D): return kirk7_key0D; break; + case(0x0E): return kirk7_key0E; break; + case(0x0F): return kirk7_key0F; break; + case(0x10): return kirk7_key10; break; + case(0x11): return kirk7_key11; break; + case(0x12): return kirk7_key12; break; + case(0x38): return kirk7_key38; break; + case(0x39): return kirk7_key39; break; + case(0x3A): return kirk7_key3A; break; + case(0x4B): return kirk7_key4B; break; + case(0x53): return kirk7_key53; break; + case(0x57): return kirk7_key57; break; + case(0x5D): return kirk7_key5D; break; + case(0x63): return kirk7_key63; break; + case(0x64): return kirk7_key64; break; + default: return (u8*)KIRK_INVALID_SIZE; break; //need to get the real error code for that, placeholder now :) + } +} + +int kirk_CMD1_ex(u8* outbuff, u8* inbuff, int size, KIRK_CMD1_HEADER* header) +{ + u8* buffer = (u8*)malloc(size); + int ret; + + memcpy(buffer, header, sizeof(KIRK_CMD1_HEADER)); + memcpy(buffer+sizeof(KIRK_CMD1_HEADER), inbuff, header->data_size); + + ret = kirk_CMD1(outbuff, buffer, size); + free(buffer); + return ret; +} + + +int sceUtilsBufferCopyWithRange(u8* outbuff, int outsize, u8* inbuff, int insize, int cmd) +{ + switch(cmd) + { + case KIRK_CMD_DECRYPT_PRIVATE: return kirk_CMD1(outbuff, inbuff, insize); break; + case KIRK_CMD_ENCRYPT_IV_0: return kirk_CMD4(outbuff, inbuff, insize); break; + case KIRK_CMD_DECRYPT_IV_0: return kirk_CMD7(outbuff, inbuff, insize); break; + case KIRK_CMD_PRIV_SIGN_CHECK: return kirk_CMD10(inbuff, insize); break; + case KIRK_CMD_SHA1_HASH: return kirk_CMD11(outbuff, inbuff, insize); break; + case KIRK_CMD_ECDSA_GEN_KEYS: return kirk_CMD12(outbuff,outsize); break; + case KIRK_CMD_ECDSA_MULTIPLY_POINT: return kirk_CMD13(outbuff,outsize, inbuff, insize); break; + case KIRK_CMD_PRNG: return kirk_CMD14(outbuff,outsize); break; + case KIRK_CMD_ECDSA_SIGN: return kirk_CMD16(outbuff, outsize, inbuff, insize); break; + case KIRK_CMD_ECDSA_VERIFY: return kirk_CMD17(inbuff, insize); break; + } + return -1; +} diff --git a/ext/libkirk/kirk_engine.h b/ext/libkirk/kirk_engine.h new file mode 100644 index 0000000000..e89fa54689 --- /dev/null +++ b/ext/libkirk/kirk_engine.h @@ -0,0 +1,246 @@ +/* + Draan proudly presents: + + With huge help from community: + coyotebean, Davee, hitchhikr, kgsws, liquidzigong, Mathieulh, Proxima, SilverSpring + + ******************** KIRK-ENGINE ******************** + An Open-Source implementation of KIRK (PSP crypto engine) algorithms and keys. + Includes also additional routines for hash forging. + + ******************** + + 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 3 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, see . +*/ + +#ifndef KIRK_ENGINE +#define KIRK_ENGINE +typedef unsigned char u8; +typedef unsigned short int u16; +typedef unsigned int u32; + +//Kirk return values +#define KIRK_OPERATION_SUCCESS 0 +#define KIRK_NOT_ENABLED 1 +#define KIRK_INVALID_MODE 2 +#define KIRK_HEADER_HASH_INVALID 3 +#define KIRK_DATA_HASH_INVALID 4 +#define KIRK_SIG_CHECK_INVALID 5 +#define KIRK_UNK_1 6 +#define KIRK_UNK_2 7 +#define KIRK_UNK_3 8 +#define KIRK_UNK_4 9 +#define KIRK_UNK_5 0xA +#define KIRK_UNK_6 0xB +#define KIRK_NOT_INITIALIZED 0xC +#define KIRK_INVALID_OPERATION 0xD +#define KIRK_INVALID_SEED_CODE 0xE +#define KIRK_INVALID_SIZE 0xF +#define KIRK_DATA_SIZE_ZERO 0x10 + +typedef struct +{ + int mode; //0 + int unk_4; //4 + int unk_8; //8 + int keyseed; //C + int data_size; //10 +} KIRK_AES128CBC_HEADER; //0x14 + +typedef struct +{ + u8 AES_key[16]; //0 + u8 CMAC_key[16]; //10 + u8 CMAC_header_hash[16]; //20 + u8 CMAC_data_hash[16]; //30 + u8 unused[32]; //40 + u32 mode; //60 + u8 ecdsa_hash; //64 + u8 unk3[11]; //65 + u32 data_size; //70 + u32 data_offset; //74 + u8 unk4[8]; //78 + u8 unk5[16]; //80 +} KIRK_CMD1_HEADER; //0x90 + +typedef struct +{ + u8 AES_key[16]; //0 + u8 header_sig_r[20]; //10 + u8 header_sig_s[20]; //24 + u8 data_sig_r[20]; //38 + u8 data_sig_s[20]; //4C + u32 mode; //60 + u8 ecdsa_hash; //64 + u8 unk3[11]; //65 + u32 data_size; //70 + u32 data_offset; //74 + u8 unk4[8]; //78 + u8 unk5[16]; //80 +} KIRK_CMD1_ECDSA_HEADER; //0x90 + + +typedef struct +{ + u8 r[0x14]; + u8 s[0x14]; +} ECDSA_SIG; //0x28 +typedef struct +{ + u8 x[0x14]; + u8 y[0x14]; +} ECDSA_POINT; //0x28 + +typedef struct +{ + u32 data_size; //0 +} KIRK_SHA1_HEADER; //4 + +typedef struct +{ + u8 private_key[0x14]; + ECDSA_POINT public_key; +} KIRK_CMD12_BUFFER; + +typedef struct +{ + u8 multiplier[0x14]; + ECDSA_POINT public_key; +} KIRK_CMD13_BUFFER; + + +typedef struct +{ + u8 enc_private[0x20]; //0 + u8 message_hash[0x14]; //20 +} KIRK_CMD16_BUFFER;//0x34 + +typedef struct +{ + ECDSA_POINT public_key; //0 + u8 message_hash[0x14]; //28 + ECDSA_SIG signature; //3C +} KIRK_CMD17_BUFFER;//0x64 + +//mode passed to sceUtilsBufferCopyWithRange +#define KIRK_CMD_DECRYPT_PRIVATE 1 +#define KIRK_CMD_2 2 +#define KIRK_CMD_3 3 +#define KIRK_CMD_ENCRYPT_IV_0 4 +#define KIRK_CMD_ENCRYPT_IV_FUSE 5 +#define KIRK_CMD_ENCRYPT_IV_USER 6 +#define KIRK_CMD_DECRYPT_IV_0 7 +#define KIRK_CMD_DECRYPT_IV_FUSE 8 +#define KIRK_CMD_DECRYPT_IV_USER 9 +#define KIRK_CMD_PRIV_SIGN_CHECK 10 +#define KIRK_CMD_SHA1_HASH 11 +#define KIRK_CMD_ECDSA_GEN_KEYS 12 +#define KIRK_CMD_ECDSA_MULTIPLY_POINT 13 +#define KIRK_CMD_PRNG 14 +#define KIRK_CMD_15 15 +#define KIRK_CMD_ECDSA_SIGN 16 +#define KIRK_CMD_ECDSA_VERIFY 17 + +//"mode" in header +#define KIRK_MODE_CMD1 1 +#define KIRK_MODE_CMD2 2 +#define KIRK_MODE_CMD3 3 +#define KIRK_MODE_ENCRYPT_CBC 4 +#define KIRK_MODE_DECRYPT_CBC 5 + +//sceUtilsBufferCopyWithRange errors +#define SUBCWR_NOT_16_ALGINED 0x90A +#define SUBCWR_HEADER_HASH_INVALID 0x920 +#define SUBCWR_BUFFER_TOO_SMALL 0x1000 + +/* + // Private Sig + Cipher + 0x01: Super-Duper decryption (no inverse) + 0x02: Encrypt Operation (inverse of 0x03) + 0x03: Decrypt Operation (inverse of 0x02) + + // Cipher + 0x04: Encrypt Operation (inverse of 0x07) (IV=0) + 0x05: Encrypt Operation (inverse of 0x08) (IV=FuseID) + 0x06: Encrypt Operation (inverse of 0x09) (IV=UserDefined) + 0x07: Decrypt Operation (inverse of 0x04) + 0x08: Decrypt Operation (inverse of 0x05) + 0x09: Decrypt Operation (inverse of 0x06) + + // Sig Gens + 0x0A: Private Signature Check (checks for private SCE sig) + 0x0B: SHA1 Hash + 0x0C: Mul1 + 0x0D: Mul2 + 0x0E: Random Number Gen + 0x0F: (absolutely no idea – could be KIRK initialization) + 0x10: Signature Gen + // Sig Checks + 0x11: Signature Check (checks for generated sigs) + 0x12: Certificate Check (idstorage signatures) +*/ + +//kirk-like funcs +int kirk_CMD0(u8* outbuff, u8* inbuff, int size, int generate_trash); +int kirk_CMD1(u8* outbuff, u8* inbuff, int size); + +int kirk_CMD4(u8* outbuff, u8* inbuff, int size); +int kirk_CMD7(u8* outbuff, u8* inbuff, int size); +int kirk_CMD10(u8* inbuff, int insize); +int kirk_CMD11(u8* outbuff, u8* inbuff, int size); +int kirk_CMD12(u8* outbuff, int outsize); +int kirk_CMD13(u8* outbuff, int outsize,u8* inbuff, int insize); +int kirk_CMD14(u8* outbuff, int outsize); +int kirk_CMD16(u8* outbuff, int outsize,u8* inbuff, int insize); +int kirk_CMD17(u8* inbuff, int insize); + +int kirk_init(); //CMD 0xF? +int kirk_init2(u8 *, u32, u32, u32); + +//helper funcs +u8* kirk_4_7_get_key(int key_type); + +//kirk "ex" functions +int kirk_CMD1_ex(u8* outbuff, u8* inbuff, int size, KIRK_CMD1_HEADER* header); + +//sce-like funcs +int sceUtilsSetFuseID(u8*fuse); +int sceUtilsBufferCopyWithRange(u8* outbuff, int outsize, u8* inbuff, int insize, int cmd); +void decrypt_kirk16_private(u8 *dA_out, u8 *dA_enc); +void encrypt_kirk16_private(u8 *dA_out, u8 *dA_dec); + +// Prototypes for the Elliptic Curve and Big Number functions +int ecdsa_get_params(u32 type, u8 *p, u8 *a, u8 *b, u8 *N, u8 *Gx, u8 *Gy); +int ecdsa_set_curve(u8* p,u8* a,u8* b,u8* N,u8* Gx,u8* Gy); +void ecdsa_set_pub(u8 *Q); +void ecdsa_set_priv(u8 *k); +int ecdsa_verify(u8 *hash, u8 *R, u8 *S); +void ecdsa_sign(u8 *hash, u8 *R, u8 *S); +void ec_priv_to_pub(u8 *k, u8 *Q); +void ec_pub_mult(u8 *k, u8 *Q); +void bn_copy(u8 *d, u8 *a, u32 n); +int bn_compare(u8 *a, u8 *b, u32 n); +void bn_reduce(u8 *d, u8 *N, u32 n); +void bn_add(u8 *d, u8 *a, u8 *b, u8 *N, u32 n); +void bn_sub(u8 *d, u8 *a, u8 *b, u8 *N, u32 n); +void bn_to_mon(u8 *d, u8 *N, u32 n); +void bn_from_mon(u8 *d, u8 *N, u32 n); +void bn_mon_mul(u8 *d, u8 *a, u8 *b, u8 *N, u32 n); +void bn_mon_inv(u8 *d, u8 *a, u8 *N, u32 n); +void hex_dump(char *str, u8 *buf, int size); + +#define round_up(x,n) (-(-(x) & -(n))) + +#define array_size(x) (sizeof(x) / sizeof(*(x))) +#endif diff --git a/ext/libkirk/libkirk.vcxproj b/ext/libkirk/libkirk.vcxproj new file mode 100644 index 0000000000..03cc26bc5c --- /dev/null +++ b/ext/libkirk/libkirk.vcxproj @@ -0,0 +1,132 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {3BAAE095-E0AB-4B0E-B5DF-CE39C8AE31DE} + libkirk + + + + StaticLibrary + true + v100 + MultiByte + + + StaticLibrary + true + v100 + MultiByte + + + StaticLibrary + false + v100 + true + MultiByte + + + StaticLibrary + false + v100 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + Default + + + true + + + + + Level3 + Disabled + + + true + + + + + Level3 + MaxSpeed + true + true + + + true + true + true + + + + + Level3 + MaxSpeed + true + true + + + true + true + true + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ext/libkirk/libkirk.vcxproj.filters b/ext/libkirk/libkirk.vcxproj.filters new file mode 100644 index 0000000000..b43b401d6d --- /dev/null +++ b/ext/libkirk/libkirk.vcxproj.filters @@ -0,0 +1,48 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + + + + \ No newline at end of file diff --git a/zlib/CMakeLists.txt b/ext/zlib/CMakeLists.txt similarity index 100% rename from zlib/CMakeLists.txt rename to ext/zlib/CMakeLists.txt diff --git a/zlib/adler32.c b/ext/zlib/adler32.c similarity index 100% rename from zlib/adler32.c rename to ext/zlib/adler32.c diff --git a/zlib/compress.c b/ext/zlib/compress.c similarity index 100% rename from zlib/compress.c rename to ext/zlib/compress.c diff --git a/zlib/crc32.c b/ext/zlib/crc32.c similarity index 100% rename from zlib/crc32.c rename to ext/zlib/crc32.c diff --git a/zlib/crc32.h b/ext/zlib/crc32.h similarity index 100% rename from zlib/crc32.h rename to ext/zlib/crc32.h diff --git a/zlib/deflate.c b/ext/zlib/deflate.c similarity index 100% rename from zlib/deflate.c rename to ext/zlib/deflate.c diff --git a/zlib/deflate.h b/ext/zlib/deflate.h similarity index 100% rename from zlib/deflate.h rename to ext/zlib/deflate.h diff --git a/zlib/gzclose.c b/ext/zlib/gzclose.c similarity index 100% rename from zlib/gzclose.c rename to ext/zlib/gzclose.c diff --git a/zlib/gzguts.h b/ext/zlib/gzguts.h similarity index 100% rename from zlib/gzguts.h rename to ext/zlib/gzguts.h diff --git a/zlib/gzlib.c b/ext/zlib/gzlib.c similarity index 100% rename from zlib/gzlib.c rename to ext/zlib/gzlib.c diff --git a/zlib/gzread.c b/ext/zlib/gzread.c similarity index 100% rename from zlib/gzread.c rename to ext/zlib/gzread.c diff --git a/zlib/gzwrite.c b/ext/zlib/gzwrite.c similarity index 100% rename from zlib/gzwrite.c rename to ext/zlib/gzwrite.c diff --git a/zlib/infback.c b/ext/zlib/infback.c similarity index 100% rename from zlib/infback.c rename to ext/zlib/infback.c diff --git a/zlib/inffast.c b/ext/zlib/inffast.c similarity index 100% rename from zlib/inffast.c rename to ext/zlib/inffast.c diff --git a/zlib/inffast.h b/ext/zlib/inffast.h similarity index 100% rename from zlib/inffast.h rename to ext/zlib/inffast.h diff --git a/zlib/inffixed.h b/ext/zlib/inffixed.h similarity index 100% rename from zlib/inffixed.h rename to ext/zlib/inffixed.h diff --git a/zlib/inflate.c b/ext/zlib/inflate.c similarity index 100% rename from zlib/inflate.c rename to ext/zlib/inflate.c diff --git a/zlib/inflate.h b/ext/zlib/inflate.h similarity index 100% rename from zlib/inflate.h rename to ext/zlib/inflate.h diff --git a/zlib/inftrees.c b/ext/zlib/inftrees.c similarity index 100% rename from zlib/inftrees.c rename to ext/zlib/inftrees.c diff --git a/zlib/inftrees.h b/ext/zlib/inftrees.h similarity index 100% rename from zlib/inftrees.h rename to ext/zlib/inftrees.h diff --git a/zlib/make_vms.com b/ext/zlib/make_vms.com similarity index 100% rename from zlib/make_vms.com rename to ext/zlib/make_vms.com diff --git a/zlib/trees.c b/ext/zlib/trees.c similarity index 100% rename from zlib/trees.c rename to ext/zlib/trees.c diff --git a/zlib/trees.h b/ext/zlib/trees.h similarity index 100% rename from zlib/trees.h rename to ext/zlib/trees.h diff --git a/zlib/uncompr.c b/ext/zlib/uncompr.c similarity index 100% rename from zlib/uncompr.c rename to ext/zlib/uncompr.c diff --git a/zlib/zconf.h b/ext/zlib/zconf.h similarity index 100% rename from zlib/zconf.h rename to ext/zlib/zconf.h diff --git a/zlib/zlib.h b/ext/zlib/zlib.h similarity index 100% rename from zlib/zlib.h rename to ext/zlib/zlib.h diff --git a/zlib/zlib.vcxproj b/ext/zlib/zlib.vcxproj similarity index 100% rename from zlib/zlib.vcxproj rename to ext/zlib/zlib.vcxproj diff --git a/zlib/zlib.vcxproj.filters b/ext/zlib/zlib.vcxproj.filters similarity index 100% rename from zlib/zlib.vcxproj.filters rename to ext/zlib/zlib.vcxproj.filters diff --git a/zlib/zutil.c b/ext/zlib/zutil.c similarity index 100% rename from zlib/zutil.c rename to ext/zlib/zutil.c diff --git a/zlib/zutil.h b/ext/zlib/zutil.h similarity index 100% rename from zlib/zutil.h rename to ext/zlib/zutil.h diff --git a/gentest.py b/gentest.py new file mode 100644 index 0000000000..0d819ec2e8 --- /dev/null +++ b/gentest.py @@ -0,0 +1,77 @@ +# Utility to make it slightly easier to get the results from a test back +# and put it as an "expected" file. +# I can't seem to get pspsh to automatically wait for the psp app to exit, +# unfortunately. + +import sys +import io +import os +import subprocess +import shutil +import time + +PSPSH = "pspsh" +TEST_ROOT = "pspautotests/tests/" +PORT = 3000 +TEST = "cpu/cpu/cpu" +OUTFILE = "__testoutput.txt" +OUTFILE2 = "__testerror.txt" + + +tests_to_generate = [ + "cpu/cpu/cpu", + "cpu/icache/icache", + "cpu/lsu/lsu", + "cpu/fpu/fpu", +] + + +def gen_test(test): + print("Running test " + test + " on the PSP...") + + if os.path.exists(OUTFILE): + os.unlink(OUTFILE) + if os.path.exists(OUTFILE2): + os.unlink(OUTFILE2) + + prx_path = TEST_ROOT + test + ".prx" + expected_path = TEST_ROOT + test + ".expected" + + if not os.path.exists(prx_path): + print "You must compile the test into a PRX first (" + prx_path + ")" + return + + # First, write a command file for PSPSH + + f = open("cmdfile.txt", "w") + f.write(prx_path) + f.close() + + os.system("pspsh -p %i cmdfile.txt" % (PORT,)) + + # Allow the test a second to execute - TODO: tweak + time.sleep(1) + + if os.path.exists(OUTFILE): + # Should check for size as well... + shutil.copyfile(OUTFILE, expected_path) + print "Expected file written: " + expected_path + else: + print "ERROR: No " + OUTFILE + " was written, can't write .expected" + + os.unlink("cmdfile.txt") + + # Allow the system a couple of seconds to reconnect to the PSP + time.sleep(2) + +def main(): + args = sys.argv[1:] + + tests = tests_to_generate + if len(args): + tests = args + + for test in tests: + gen_test(test) + +main() diff --git a/headless/Headless.cpp b/headless/Headless.cpp index 0660fba417..e33039e918 100644 --- a/headless/Headless.cpp +++ b/headless/Headless.cpp @@ -4,6 +4,7 @@ #include +#include "../Core/Config.h" #include "../Core/Core.h" #include "../Core/CoreTiming.h" #include "../Core/System.h" @@ -41,6 +42,33 @@ public: virtual bool AttemptLoadSymbolMap() {return false;} }; +class PrintfLogger : public LogListener +{ +public: + void Log(LogTypes::LOG_LEVELS level, const char *msg) + { + switch (level) + { + case LogTypes::LDEBUG: + printf("D %s", msg); + break; + case LogTypes::LINFO: + printf("I %s", msg); + break; + case LogTypes::LERROR: + printf("E %s", msg); + break; + case LogTypes::LWARNING: + printf("W %s", msg); + break; + case LogTypes::LNOTICE: + default: + printf("N %s", msg); + break; + } + } +}; + void printUsage() { fprintf(stderr, "PPSSPP Headless\n"); @@ -87,12 +115,14 @@ int main(int argc, const char* argv[]) LogManager::Init(); LogManager *logman = LogManager::GetInstance(); + PrintfLogger *printfLogger = new PrintfLogger(); + for (int i = 0; i < LogTypes::NUMBER_OF_LOGS; i++) { LogTypes::LOG_TYPE type = (LogTypes::LOG_TYPE)i; logman->SetEnable(type, fullLog); logman->SetLogLevel(type, LogTypes::LDEBUG); - // logman->AddListener(type, logger); + logman->AddListener(type, printfLogger); } CoreParameter coreParameter; @@ -103,11 +133,17 @@ int main(int argc, const char* argv[]) coreParameter.gpuCore = GPU_NULL; coreParameter.enableSound = false; coreParameter.headLess = true; + coreParameter.printfEmuLog = true; + + g_Config.bEnableSound = false; + g_Config.bFirstRun = false; + g_Config.bIgnoreBadMemAccess = true; std::string error_string; if (!PSP_Init(coreParameter, &error_string)) { - fprintf(stderr, "Failed to start PSP executable. Error: %s\n", error_string.c_str()); + fprintf(stderr, "Failed to start %s. Error: %s\n", coreParameter.fileToStart.c_str(), error_string.c_str()); + printf("TESTERROR\n"); return 1; } diff --git a/headless/Headless.vcxproj b/headless/Headless.vcxproj index 3a8fb87f81..083b005eb1 100644 --- a/headless/Headless.vcxproj +++ b/headless/Headless.vcxproj @@ -82,6 +82,7 @@ Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) ../Common;..;../Core;../native/ext/glew; + Default Console @@ -158,17 +159,20 @@ {533f1d30-d04d-47cc-ad71-20f658907e36} + + {3baae095-e0ab-4b0e-b5df-ce39c8ae31de} + {457f45d2-556f-47bc-a31d-aff0d15beaed} {e8b58922-9827-493d-81e0-4b6e6bd77171} - + {f761046e-6c38-4428-a5f1-38391a37bb34} - + \ No newline at end of file diff --git a/main.cpp b/main.cpp index 6957b68c07..b42684bd2e 100644 --- a/main.cpp +++ b/main.cpp @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/native b/native index b80e99726b..2703289d45 160000 --- a/native +++ b/native @@ -1 +1 @@ -Subproject commit b80e99726b5bda47f4a3165111295dc35337870d +Subproject commit 2703289d456bf22e80eafbce0aa0307389a51dc6 diff --git a/pspautotests b/pspautotests new file mode 160000 index 0000000000..89b53612e4 --- /dev/null +++ b/pspautotests @@ -0,0 +1 @@ +Subproject commit 89b53612e405e1b8a92f730c8078ade26d4c703d diff --git a/stdafx.h b/stdafx.h index c7ea4146ac..813826ea7f 100644 --- a/stdafx.h +++ b/stdafx.h @@ -2,7 +2,7 @@ // 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, version 2.0. +// the Free Software Foundation, version 2.0 or later versions. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of diff --git a/test.py b/test.py new file mode 100644 index 0000000000..7485b53694 --- /dev/null +++ b/test.py @@ -0,0 +1,242 @@ +# Automated script to run the pspautotests test suite in PPSSPP. + +import sys +import io +import os +import subprocess + + +PPSSPP_EXECUTABLES = [ "Windows\\Release\\PPSSPPHeadless.exe", "SDL/build/ppsspp-headless" ] +PPSSPP_EXE = None +TEST_ROOT = "pspautotests/tests/" +teamcity_mode = False + +# Test names are the C files without the .c extension. +# These have worked and should keep working always - regression tests. +tests_good = [ + "cpu/cpu/cpu", + "cpu/vfpu/base/vfpu", + "cpu/vfpu/convert/vfpu_convert", + "cpu/vfpu/prefixes/vfpu_prefixes", + "cpu/vfpu/colors/vfpu_colors", + "cpu/icache/icache", + "cpu/lsu/lsu", + "cpu/fpu/fpu", + + "display/display", + "dmac/dmactest", + "intr/intr", + "intr/vblank/vblank", + "misc/testgp", + "string/string", + "gpu/callbacks/ge_callbacks", + "threads/mbx/mbx", + "threads/semaphores/semaphores", + "threads/semaphores/cancel/cancel", + "threads/semaphores/create/create", + "threads/semaphores/delete/delete", + "threads/semaphores/poll/poll", + "threads/semaphores/refer/refer", + "threads/semaphores/signal/signal", + "power/power", + "rtc/rtc", + "umd/callbacks/umd", + "io/directory/directory", +] + +tests_next = [ + "malloc/malloc", +# These are the next tests up for fixing. These run by default. + "threads/fpl/fpl", + "threads/msgpipe/msgpipe", + "threads/mutex/mutex", + "threads/scheduling/scheduling", + "threads/semaphores/priority/priority", + "threads/semaphores/wait/wait", + "threads/threads/threads", + "threads/vpl/vpl", + "threads/vtimers/vtimer", + "threads/wakeup/wakeup", + "audio/sascore/sascore", + "ctrl/ctrl", + "gpu/simple/simple", + "gpu/triangle/triangle", + "hle/check_not_used_uids", + "font/fonttest", + "io/cwd/cwd", + "io/io/io", + "io/iodrv/iodrv", + "modules/loadexec/loader", + "threads/k0/k0", + "threads/fpl/fpl", + "threads/msgpipe/msgpipe", + "threads/mutex/mutex", + "threads/scheduling/scheduling", + "threads/threads/threads", + "threads/vpl/vpl", + "threads/vtimers/vtimers", + "threads/wakeup/wakeup", + "umd/io/umd_io", + "umd/raw_access/raw_acess", + "utility/systemparam/systemparam", + "video/pmf", + "video/pmf_simple", +] + +# These should be fixed, but currently hang or crash and are thus inconvenient to have +# in the general test. +tests_hang = [ + "threads/events/events", + "audio/atrac/atractest", +] + +# These don't even run (or run correctly) on the real PSP +test_broken = [ + "sysmem/sysmem", + "mstick/mstick", +] + + +# These are the tests we ignore (not important, or impossible to run) +tests_ignored = [ + "kirk/kirk", + "me/me", + + "umd/umd", # mostly fixed but output seems broken? (first retval of unregister...) +] + + + +def init(): + global PPSSPP_EXE + if not os.path.exists("pspautotests"): + print "Please run git submodule init; git submodule update;" + sys.exit(1) + + if not os.path.exists(TEST_ROOT + "cpu/cpu/cpu.prx"): + print "Please install the pspsdk and run make in common/ and in all the tests" + sys.exit(1) + + for p in PPSSPP_EXECUTABLES: + if os.path.exists(p): + PPSSPP_EXE = p + break + + if not PPSSPP_EXE: + print "PPSSPP executable missing, please build one." + sys.exit(1) + +def tcprint(arg): + global teamcity_mode + if teamcity_mode: + print arg + +def run_tests(test_list, args): + global PPSSPP_EXE + tests_passed = [] + tests_failed = [] + + for test in test_list: + # Try prx first + expected_filename = TEST_ROOT + test + ".expected" + + elf_filename = TEST_ROOT + test + ".prx" + print elf_filename + + if not os.path.exists(elf_filename): + print "WARNING: no prx, trying elf" + elf_filename = TEST_ROOT + test + ".elf" + + if not os.path.exists(elf_filename): + print("ERROR: PRX/ELF file missing, failing test: " + test) + tests_failed.append(test) + tcprint("##teamcity[testIgnored name='%s' message='PRX/ELF missing']" % test) + continue + + if not os.path.exists(expected_filename): + print("WARNING: expects file missing, failing test: " + test) + tests_failed.append(test) + tcprint("##teamcity[testIgnored name='%s' message='Expects file missing']" % test) + continue + + expected_output = open(expected_filename).read() + + tcprint("##teamcity[testStarted name='%s' captureStandardOutput='true']" % test) + + cmdline = PPSSPP_EXE + " " + elf_filename + " " + " ".join(args) + #print "Cmdline: " + cmdline + proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) + + output = proc.stdout.read().strip() + if output.startswith("TESTERROR"): + print "Failed to run test " + elf_filename + "!" + tests_failed.append(test) + tcprint("##teamcity[testFailed name='%s' message='Failed to run test']" % test) + tcprint("##teamcity[testFinished name='%s']" % test) + continue + + different = False + expected_lines = expected_output.splitlines() + output_lines = output.splitlines() + + for i in range(0, min(len(output_lines), len(expected_lines))): + if output_lines[i] != expected_lines[i]: + print "%i < %s" % (i, output_lines[i]) + print "%i > %s" % (i, expected_lines[i]) + different = True + + if len(output_lines) != len(expected_lines): + print "*** Different number of lines!" + different = True + + if not different: + if '-v' in args: + print "++++++++++++++ The Equal Output +++++++++++++" + print "\n".join(output_lines) + print "+++++++++++++++++++++++++++++++++++++++++++++" + print " " + test + " - passed!" + tests_passed.append(test) + tcprint("##teamcity[testFinished name='%s']" % test) + else: + if '-v' in args: + print "============== output from failed " + test + " :" + print output + print "============== expected output:" + print expected_output + print "===============================" + tests_failed.append(test) + tcprint("##teamcity[testFailed name='%s' message='Output different from expected file']" % test) + tcprint("##teamcity[testFinished name='%s']" % test) + + print "%i tests passed, %i tests failed." % ( + len(tests_passed), len(tests_failed)) + + if len(tests_failed): + print "Failed tests:" + for t in tests_failed: + print " " + t + print "Ran " + PPSSPP_EXE + + +def main(): + global teamcity_mode + init() + tests = [] + args = [] + for arg in sys.argv[1:]: + if arg == '--teamcity': + teamcity_mode = True + elif arg[0] == '-': + args.append(arg) + else: + tests.append(arg) + + if not tests: + if '-g' in args: + tests = tests_good + else: + tests = tests_next + tests_good + + run_tests(tests, args) + +main()