diff --git a/source/graphics/ColladaManager.cpp b/source/graphics/ColladaManager.cpp index dcc2dc9fa2..723023f1f6 100644 --- a/source/graphics/ColladaManager.cpp +++ b/source/graphics/ColladaManager.cpp @@ -147,7 +147,7 @@ public: // logic warns when asked to load such. if(writeBuffer.Size()) { - LibError ret = g_VFS->CreateFile(pmdFilename, writeBuffer.Data(), writeBuffer.Size()); + Status ret = g_VFS->CreateFile(pmdFilename, writeBuffer.Data(), writeBuffer.Size()); ENSURE(ret == INFO::OK); } @@ -241,7 +241,7 @@ VfsPath CColladaManager::GetLoadableFilename(const VfsPath& pathnameNoExtension, // realDaePath_ is "[..]/mods/whatever/art/meshes/whatever.dae" OsPath realDaePath_; - LibError ret = g_VFS->GetRealPath(dae, realDaePath_); + Status ret = g_VFS->GetRealPath(dae, realDaePath_); ENSURE(ret == INFO::OK); wchar_t realDaeBuf[PATH_MAX]; wcscpy_s(realDaeBuf, ARRAY_SIZE(realDaeBuf), realDaePath_.string().c_str()); diff --git a/source/graphics/MapGenerator.cpp b/source/graphics/MapGenerator.cpp index 1db363ee76..3ca405ef86 100644 --- a/source/graphics/MapGenerator.cpp +++ b/source/graphics/MapGenerator.cpp @@ -220,7 +220,7 @@ bool CMapGeneratorWorker::LoadScripts(const std::wstring& libraryName) return true; } -LibError CMapGeneratorWorker::PreloadScript(const VfsPath& pathname, const FileInfo& UNUSED(fileInfo), const uintptr_t cbData) +Status CMapGeneratorWorker::PreloadScript(const VfsPath& pathname, const FileInfo& UNUSED(fileInfo), const uintptr_t cbData) { CMapGeneratorWorker* self = (CMapGeneratorWorker*)cbData; diff --git a/source/graphics/MapGenerator.h b/source/graphics/MapGenerator.h index 411b0da954..729778d944 100644 --- a/source/graphics/MapGenerator.h +++ b/source/graphics/MapGenerator.h @@ -139,7 +139,7 @@ private: ScriptFilesMap m_ScriptFiles; // callback for VFS preloading - static LibError PreloadScript(const VfsPath& pathname, const FileInfo& fileInfo, const uintptr_t cbData); + static Status PreloadScript(const VfsPath& pathname, const FileInfo& fileInfo, const uintptr_t cbData); // Thread static void* RunThread(void* data); diff --git a/source/graphics/ObjectManager.cpp b/source/graphics/ObjectManager.cpp index 9b560691af..d75832df0f 100644 --- a/source/graphics/ObjectManager.cpp +++ b/source/graphics/ObjectManager.cpp @@ -53,7 +53,7 @@ bool CObjectManager::ObjectKey::operator< (const CObjectManager::ObjectKey& a) c return ActorVariation < a.ActorVariation; } -static LibError ReloadChangedFileCB(void* param, const VfsPath& path) +static Status ReloadChangedFileCB(void* param, const VfsPath& path) { return static_cast(param)->ReloadChangedFile(path); } @@ -191,7 +191,7 @@ void CObjectManager::UnloadObjects() m_ObjectBases.clear(); } -LibError CObjectManager::ReloadChangedFile(const VfsPath& path) +Status CObjectManager::ReloadChangedFile(const VfsPath& path) { // Mark old entries as outdated so we don't reload them from the cache for (std::map::iterator it = m_Objects.begin(); it != m_Objects.end(); ++it) diff --git a/source/graphics/ObjectManager.h b/source/graphics/ObjectManager.h index e687ea3950..cb2a53d4cf 100644 --- a/source/graphics/ObjectManager.h +++ b/source/graphics/ObjectManager.h @@ -83,7 +83,7 @@ public: * Reload any scripts that were loaded from the given filename. * (This is used to implement hotloading.) */ - LibError ReloadChangedFile(const VfsPath& path); + Status ReloadChangedFile(const VfsPath& path); private: CMeshManager& m_MeshManager; diff --git a/source/graphics/ParticleManager.cpp b/source/graphics/ParticleManager.cpp index b98f0f17fe..b30adbf661 100644 --- a/source/graphics/ParticleManager.cpp +++ b/source/graphics/ParticleManager.cpp @@ -23,7 +23,7 @@ #include "ps/Profile.h" #include "renderer/Scene.h" -static LibError ReloadChangedFileCB(void* param, const VfsPath& path) +static Status ReloadChangedFileCB(void* param, const VfsPath& path) { return static_cast(param)->ReloadChangedFile(path); } @@ -88,7 +88,7 @@ void CParticleManager::RenderSubmit(SceneCollector& collector, const CFrustum& U collector.Submit(it->get()); } -LibError CParticleManager::ReloadChangedFile(const VfsPath& path) +Status CParticleManager::ReloadChangedFile(const VfsPath& path) { m_EmitterTypes.erase(path); return INFO::OK; diff --git a/source/graphics/ParticleManager.h b/source/graphics/ParticleManager.h index b709e13685..729daba1c3 100644 --- a/source/graphics/ParticleManager.h +++ b/source/graphics/ParticleManager.h @@ -46,7 +46,7 @@ public: float GetCurrentTime() const { return m_CurrentTime; } - LibError ReloadChangedFile(const VfsPath& path); + Status ReloadChangedFile(const VfsPath& path); /// Random number generator shared between all particle emitters. boost::mt19937 m_RNG; diff --git a/source/graphics/ShaderManager.cpp b/source/graphics/ShaderManager.cpp index 84576169f1..1444fe92b9 100644 --- a/source/graphics/ShaderManager.cpp +++ b/source/graphics/ShaderManager.cpp @@ -187,12 +187,12 @@ bool CShaderManager::NewProgram(const char* name, const std::map& ba return PSRETURN_OK; } -/*static*/ LibError CShaderManager::ReloadChangedFileCB(void* param, const VfsPath& path) +/*static*/ Status CShaderManager::ReloadChangedFileCB(void* param, const VfsPath& path) { return static_cast(param)->ReloadChangedFile(path); } -LibError CShaderManager::ReloadChangedFile(const VfsPath& path) +Status CShaderManager::ReloadChangedFile(const VfsPath& path) { // Find all shaders using this file HotloadFilesMap::iterator files = m_HotloadFiles.find(path); diff --git a/source/graphics/ShaderManager.h b/source/graphics/ShaderManager.h index 70e7cf3a01..73118fb61f 100644 --- a/source/graphics/ShaderManager.h +++ b/source/graphics/ShaderManager.h @@ -49,8 +49,8 @@ public: private: bool NewProgram(const char* name, const std::map& defines, CShaderProgramPtr& program); - static LibError ReloadChangedFileCB(void* param, const VfsPath& path); - LibError ReloadChangedFile(const VfsPath& path); + static Status ReloadChangedFileCB(void* param, const VfsPath& path); + Status ReloadChangedFile(const VfsPath& path); struct CacheKey { diff --git a/source/graphics/TextureManager.cpp b/source/graphics/TextureManager.cpp index 4fc717ca0b..2344d12787 100644 --- a/source/graphics/TextureManager.cpp +++ b/source/graphics/TextureManager.cpp @@ -251,7 +251,7 @@ public: PrepareCacheKey(texture, hash, version); VfsPath loadPath; - LibError ret = m_CacheLoader.TryLoadingCached(texture->m_Properties.m_Path, hash, version, loadPath); + Status ret = m_CacheLoader.TryLoadingCached(texture->m_Properties.m_Path, hash, version, loadPath); if (ret == INFO::OK) { @@ -443,12 +443,12 @@ public: } } - static LibError ReloadChangedFileCB(void* param, const VfsPath& path) + static Status ReloadChangedFileCB(void* param, const VfsPath& path) { return static_cast(param)->ReloadChangedFile(path); } - LibError ReloadChangedFile(const VfsPath& path) + Status ReloadChangedFile(const VfsPath& path) { // Uncache settings file, if this is one m_SettingsFiles.erase(path); diff --git a/source/gui/GUIManager.cpp b/source/gui/GUIManager.cpp index b327d3114c..f18298d1b6 100644 --- a/source/gui/GUIManager.cpp +++ b/source/gui/GUIManager.cpp @@ -163,7 +163,7 @@ void CGUIManager::LoadPage(SGUIPage& page) m_CurrentGUI = oldGUI; } -LibError CGUIManager::ReloadChangedFiles(const VfsPath& path) +Status CGUIManager::ReloadChangedFiles(const VfsPath& path) { for (PageStackType::iterator it = m_PageStack.begin(); it != m_PageStack.end(); ++it) { diff --git a/source/gui/GUIManager.h b/source/gui/GUIManager.h index f1c996ece6..a3a3a8959d 100644 --- a/source/gui/GUIManager.h +++ b/source/gui/GUIManager.h @@ -82,7 +82,7 @@ public: /** * Call when a file has bee modified, to hotload pages if their .xml files changed. */ - LibError ReloadChangedFiles(const VfsPath& path); + Status ReloadChangedFiles(const VfsPath& path); /** * Pass input events to the currently active GUI page. diff --git a/source/lib/alignment.h b/source/lib/alignment.h index 9c7cdd6b84..dd3e270590 100644 --- a/source/lib/alignment.h +++ b/source/lib/alignment.h @@ -24,11 +24,11 @@ inline size_t Align(size_t n) static const size_t vectorSize = 16; -#define VERIFY_VECTOR_MULTIPLE(size)\ - VERIFY(IsAligned(size, vectorSize)) +#define ASSERT_VECTOR_MULTIPLE(size)\ + ASSERT(IsAligned(size, vectorSize)) -#define VERIFY_VECTOR_ALIGNED(pointer)\ - VERIFY_VECTOR_MULTIPLE(pointer);\ +#define ASSERT_VECTOR_ALIGNED(pointer)\ + ASSERT_VECTOR_MULTIPLE(pointer);\ ASSUME_ALIGNED(pointer, vectorSize) diff --git a/source/lib/allocators/bucket.cpp b/source/lib/allocators/bucket.cpp index c458d5ad4e..5326a51048 100644 --- a/source/lib/allocators/bucket.cpp +++ b/source/lib/allocators/bucket.cpp @@ -35,7 +35,7 @@ const size_t bucketSize = 4000; -LibError bucket_create(Bucket* b, size_t el_size) +Status bucket_create(Bucket* b, size_t el_size) { b->freelist = mem_freelist_Sentinel(); b->el_size = Align(el_size); diff --git a/source/lib/allocators/bucket.h b/source/lib/allocators/bucket.h index bcd7315ecc..80ccacda60 100644 --- a/source/lib/allocators/bucket.h +++ b/source/lib/allocators/bucket.h @@ -73,9 +73,9 @@ struct Bucket * @param el_size 0 to allow variable-sized allocations (which cannot be * freed individually); otherwise, it specifies the number of bytes that * will be returned by bucket_alloc (whose size parameter is then ignored). - * @return LibError. + * @return Status. **/ -LIB_API LibError bucket_create(Bucket* b, size_t el_size); +LIB_API Status bucket_create(Bucket* b, size_t el_size); /** * free all memory that ensued from \. diff --git a/source/lib/allocators/dynarray.cpp b/source/lib/allocators/dynarray.cpp index c8fb6f38a5..1055841131 100644 --- a/source/lib/allocators/dynarray.cpp +++ b/source/lib/allocators/dynarray.cpp @@ -36,7 +36,7 @@ // stored in da->prot to reduce size; doesn't conflict with any PROT_* flags. const int DA_NOT_OUR_MEM = 0x40000000; -static LibError validate_da(DynArray* da) +static Status validate_da(DynArray* da) { if(!da) WARN_RETURN(ERR::INVALID_PARAM); @@ -63,16 +63,16 @@ static LibError validate_da(DynArray* da) return INFO::OK; } -#define CHECK_DA(da) RETURN_ERR(validate_da(da)) +#define CHECK_DA(da) RETURN_STATUS_IF_ERR(validate_da(da)) -LibError da_alloc(DynArray* da, size_t max_size) +Status da_alloc(DynArray* da, size_t max_size) { const size_t max_size_pa = Align(max_size); u8* p = 0; if(max_size_pa) // (avoid mmap failure) - RETURN_ERR(mem_Reserve(max_size_pa, &p)); + RETURN_STATUS_IF_ERR(mem_Reserve(max_size_pa, &p)); da->base = p; da->max_size_pa = max_size_pa; @@ -85,7 +85,7 @@ LibError da_alloc(DynArray* da, size_t max_size) } -LibError da_free(DynArray* da) +Status da_free(DynArray* da) { CHECK_DA(da); @@ -101,12 +101,12 @@ LibError da_free(DynArray* da) // (i.e. it doesn't actually own any memory). don't complain; // da_free is supposed to be called even in the above case. if(!was_wrapped && size_pa) - RETURN_ERR(mem_Release(p, size_pa)); + RETURN_STATUS_IF_ERR(mem_Release(p, size_pa)); return INFO::OK; } -LibError da_set_size(DynArray* da, size_t new_size) +Status da_set_size(DynArray* da, size_t new_size) { CHECK_DA(da); @@ -127,10 +127,10 @@ LibError da_set_size(DynArray* da, size_t new_size) u8* end = da->base + cur_size_pa; // expanding if(size_delta_pa > 0) - RETURN_ERR(mem_Commit(end, size_delta_pa, da->prot)); + RETURN_STATUS_IF_ERR(mem_Commit(end, size_delta_pa, da->prot)); // shrinking else if(size_delta_pa < 0) - RETURN_ERR(mem_Decommit(end+size_delta_pa, -size_delta_pa)); + RETURN_STATUS_IF_ERR(mem_Decommit(end+size_delta_pa, -size_delta_pa)); // else: no change in page count, e.g. if going from size=1 to 2 // (we don't want mem_* to have to handle size=0) @@ -141,16 +141,16 @@ LibError da_set_size(DynArray* da, size_t new_size) } -LibError da_reserve(DynArray* da, size_t size) +Status da_reserve(DynArray* da, size_t size) { if(da->pos+size > da->cur_size_pa) - RETURN_ERR(da_set_size(da, da->cur_size_pa+size)); + RETURN_STATUS_IF_ERR(da_set_size(da, da->cur_size_pa+size)); da->cur_size = std::max(da->cur_size, da->pos+size); return INFO::OK; } -LibError da_set_prot(DynArray* da, int prot) +Status da_set_prot(DynArray* da, int prot) { CHECK_DA(da); @@ -160,14 +160,14 @@ LibError da_set_prot(DynArray* da, int prot) WARN_RETURN(ERR::LOGIC); da->prot = prot; - RETURN_ERR(mem_Protect(da->base, da->cur_size_pa, prot)); + RETURN_STATUS_IF_ERR(mem_Protect(da->base, da->cur_size_pa, prot)); CHECK_DA(da); return INFO::OK; } -LibError da_wrap_fixed(DynArray* da, u8* p, size_t size) +Status da_wrap_fixed(DynArray* da, u8* p, size_t size) { da->base = p; da->max_size_pa = Align(size); @@ -180,7 +180,7 @@ LibError da_wrap_fixed(DynArray* da, u8* p, size_t size) } -LibError da_read(DynArray* da, void* data, size_t size) +Status da_read(DynArray* da, void* data, size_t size) { // make sure we have enough data to read if(da->pos+size > da->cur_size) @@ -192,9 +192,9 @@ LibError da_read(DynArray* da, void* data, size_t size) } -LibError da_append(DynArray* da, const void* data, size_t size) +Status da_append(DynArray* da, const void* data, size_t size) { - RETURN_ERR(da_reserve(da, size)); + RETURN_STATUS_IF_ERR(da_reserve(da, size)); memcpy(da->base+da->pos, data, size); da->pos += size; return INFO::OK; diff --git a/source/lib/allocators/dynarray.h b/source/lib/allocators/dynarray.h index 5ebd23e4db..91d576c0d1 100644 --- a/source/lib/allocators/dynarray.h +++ b/source/lib/allocators/dynarray.h @@ -61,9 +61,9 @@ struct DynArray * @param max_size size [bytes] of address space to reserve (*); * the DynArray can never expand beyond this. * (* rounded up to next page size multiple) - * @return LibError. + * @return Status. **/ -LIB_API LibError da_alloc(DynArray* da, size_t max_size); +LIB_API Status da_alloc(DynArray* da, size_t max_size); /** * free all memory (address space + physical) that constitutes the @@ -72,9 +72,9 @@ LIB_API LibError da_alloc(DynArray* da, size_t max_size); * use-after-free is impossible because the memory is unmapped. * * @param da DynArray* zeroed afterwards. - * @return LibError + * @return Status **/ -LIB_API LibError da_free(DynArray* da); +LIB_API Status da_free(DynArray* da); /** * expand or shrink the array: changes the amount of currently committed @@ -83,9 +83,9 @@ LIB_API LibError da_free(DynArray* da); * @param da DynArray. * @param new_size target size (rounded up to next page multiple). * pages are added/removed until this is met. - * @return LibError. + * @return Status. **/ -LIB_API LibError da_set_size(DynArray* da, size_t new_size); +LIB_API Status da_set_size(DynArray* da, size_t new_size); /** * Make sure at least \ bytes starting at da->pos are committed and @@ -93,9 +93,9 @@ LIB_API LibError da_set_size(DynArray* da, size_t new_size); * * @param da DynArray* * @param size Minimum amount to guarantee [bytes] - * @return LibError + * @return Status **/ -LIB_API LibError da_reserve(DynArray* da, size_t size); +LIB_API Status da_reserve(DynArray* da, size_t size); /** * change access rights of the array memory. @@ -105,9 +105,9 @@ LIB_API LibError da_reserve(DynArray* da, size_t size); * * @param da DynArray. * @param prot a combination of the PROT_* values used with mprotect. - * @return LibError. + * @return Status. **/ -LIB_API LibError da_set_prot(DynArray* da, int prot); +LIB_API Status da_set_prot(DynArray* da, int prot); /** * "wrap" (i.e. store information about) the given buffer in a DynArray. @@ -120,9 +120,9 @@ LIB_API LibError da_set_prot(DynArray* da, int prot); * change the underlying memory (e.g. da_set_size) will fail. * @param p target memory (no alignment/padding requirements) * @param size maximum size (no alignment requirements) - * @return LibError. + * @return Status. **/ -LIB_API LibError da_wrap_fixed(DynArray* da, u8* p, size_t size); +LIB_API Status da_wrap_fixed(DynArray* da, u8* p, size_t size); /** * "read" from array, i.e. copy into the given buffer. @@ -132,9 +132,9 @@ LIB_API LibError da_wrap_fixed(DynArray* da, u8* p, size_t size); * @param da DynArray. * @param data_dst destination memory * @param size [bytes] to copy - * @return LibError. + * @return Status. **/ -LIB_API LibError da_read(DynArray* da, void* data_dst, size_t size); +LIB_API Status da_read(DynArray* da, void* data_dst, size_t size); /** * "write" to array, i.e. copy from the given buffer. @@ -144,8 +144,8 @@ LIB_API LibError da_read(DynArray* da, void* data_dst, size_t size); * @param da DynArray. * @param data_src source memory * @param size [bytes] to copy - * @return LibError. + * @return Status. **/ -LIB_API LibError da_append(DynArray* da, const void* data_src, size_t size); +LIB_API Status da_append(DynArray* da, const void* data_src, size_t size); #endif // #ifndef INCLUDED_ALLOCATORS_DYNARRAY diff --git a/source/lib/allocators/page_aligned.cpp b/source/lib/allocators/page_aligned.cpp index 8cd1912113..26c84c9333 100644 --- a/source/lib/allocators/page_aligned.cpp +++ b/source/lib/allocators/page_aligned.cpp @@ -29,11 +29,11 @@ //----------------------------------------------------------------------------- -static inline LibError LibError_from_mmap(void* ret, bool warn_if_failed = true) +static inline Status StatusFromMap(void* ret) { if(ret != MAP_FAILED) return INFO::OK; - return LibError_from_errno(warn_if_failed); + WARN_RETURN(StatusFromErrno()); } // "anonymous" effectively means mapping /dev/zero, but is more efficient. @@ -46,22 +46,23 @@ static inline LibError LibError_from_mmap(void* ret, bool warn_if_failed = true) static const int mmap_flags = MAP_PRIVATE|MAP_ANONYMOUS; -LibError mem_Reserve(size_t size, u8** pp) +Status mem_Reserve(size_t size, u8** pp) { errno = 0; void* ret = mmap(0, size, PROT_NONE, mmap_flags|MAP_NORESERVE, -1, 0); *pp = (u8*)ret; - return LibError_from_mmap(ret); + return StatusFromMap(ret); } -LibError mem_Release(u8* p, size_t size) +Status mem_Release(u8* p, size_t size) { errno = 0; - int ret = munmap(p, size); - return LibError_from_posix(ret); + if(munmap(p, size) != 0) + WARN_RETURN(StatusFromErrno()); + return 0; } -LibError mem_Commit(u8* p, size_t size, int prot) +Status mem_Commit(u8* p, size_t size, int prot) { // avoid misinterpretation by mmap. if(prot == PROT_NONE) @@ -69,21 +70,23 @@ LibError mem_Commit(u8* p, size_t size, int prot) errno = 0; void* ret = mmap(p, size, prot, mmap_flags|MAP_FIXED, -1, 0); - return LibError_from_mmap(ret); + return StatusFromMap(ret); } -LibError mem_Decommit(u8* p, size_t size) +Status mem_Decommit(u8* p, size_t size) { errno = 0; void* ret = mmap(p, size, PROT_NONE, mmap_flags|MAP_NORESERVE|MAP_FIXED, -1, 0); - return LibError_from_mmap(ret); + return StatusFromMap(ret); } -LibError mem_Protect(u8* p, size_t size, int prot) +Status mem_Protect(u8* p, size_t size, int prot) { errno = 0; - int ret = mprotect(p, size, prot); - return LibError_from_posix(ret); + if(mprotect(p, size, prot) != 0) + WARN_RETURN(StatusFromErrno()); + return 0; + } @@ -93,8 +96,8 @@ void* page_aligned_alloc(size_t size) { const size_t alignedSize = Align(size); u8* p = 0; - RETURN0_IF_ERR(mem_Reserve(alignedSize, &p)); - RETURN0_IF_ERR(mem_Commit(p, alignedSize, PROT_READ|PROT_WRITE)); + RETURN_0_IF_ERR(mem_Reserve(alignedSize, &p)); + RETURN_0_IF_ERR(mem_Commit(p, alignedSize, PROT_READ|PROT_WRITE)); return p; } diff --git a/source/lib/allocators/page_aligned.h b/source/lib/allocators/page_aligned.h index a06aec7d63..3c6dfc7657 100644 --- a/source/lib/allocators/page_aligned.h +++ b/source/lib/allocators/page_aligned.h @@ -27,11 +27,11 @@ // very thin wrapper on top of sys/mman.h that makes the intent more obvious // (its commit/decommit semantics are difficult to tell apart) -LIB_API LibError mem_Reserve(size_t size, u8** pp); -LIB_API LibError mem_Release(u8* p, size_t size); -LIB_API LibError mem_Commit(u8* p, size_t size, int prot); -LIB_API LibError mem_Decommit(u8* p, size_t size); -LIB_API LibError mem_Protect(u8* p, size_t size, int prot); +LIB_API Status mem_Reserve(size_t size, u8** pp); +LIB_API Status mem_Release(u8* p, size_t size); +LIB_API Status mem_Commit(u8* p, size_t size, int prot); +LIB_API Status mem_Decommit(u8* p, size_t size); +LIB_API Status mem_Protect(u8* p, size_t size, int prot); /** diff --git a/source/lib/allocators/pool.cpp b/source/lib/allocators/pool.cpp index 35255b4e06..384db1b875 100644 --- a/source/lib/allocators/pool.cpp +++ b/source/lib/allocators/pool.cpp @@ -35,19 +35,19 @@ TIMER_ADD_CLIENT(tc_pool_alloc); -LibError pool_create(Pool* p, size_t max_size, size_t el_size) +Status pool_create(Pool* p, size_t max_size, size_t el_size) { if(el_size == POOL_VARIABLE_ALLOCS) p->el_size = 0; else p->el_size = Align(el_size); p->freelist = mem_freelist_Sentinel(); - RETURN_ERR(da_alloc(&p->da, max_size)); + RETURN_STATUS_IF_ERR(da_alloc(&p->da, max_size)); return INFO::OK; } -LibError pool_destroy(Pool* p) +Status pool_destroy(Pool* p) { // don't be picky and complain if the freelist isn't empty; // we don't care since it's all part of the da anyway. diff --git a/source/lib/allocators/pool.h b/source/lib/allocators/pool.h index fecfe2d5c4..b60196b860 100644 --- a/source/lib/allocators/pool.h +++ b/source/lib/allocators/pool.h @@ -71,9 +71,9 @@ const size_t POOL_VARIABLE_ALLOCS = ~(size_t)0u; * @param el_size Number of bytes that will be returned by each * pool_alloc (whose size parameter is then ignored). Can be 0 to * allow variable-sized allocations, but pool_free is then unusable. - * @return LibError + * @return Status **/ -LIB_API LibError pool_create(Pool* p, size_t max_size, size_t el_size); +LIB_API Status pool_create(Pool* p, size_t max_size, size_t el_size); /** * free all memory (address space + physical) that constitutes the @@ -85,9 +85,9 @@ LIB_API LibError pool_create(Pool* p, size_t max_size, size_t el_size); * (* no matter if in freelist or unused or "allocated" to user) * * @param p Pool* - * @return LibError. + * @return Status. **/ -LIB_API LibError pool_destroy(Pool* p); +LIB_API Status pool_destroy(Pool* p); /** * indicate whether a pointer was allocated from the given pool. diff --git a/source/lib/allocators/shared_ptr.h b/source/lib/allocators/shared_ptr.h index e41997166c..0d81d640e8 100644 --- a/source/lib/allocators/shared_ptr.h +++ b/source/lib/allocators/shared_ptr.h @@ -63,7 +63,7 @@ struct AlignedDeleter }; template -static inline LibError AllocateAligned(shared_ptr& p, size_t size, size_t alignment = cacheLineSize) +static inline Status AllocateAligned(shared_ptr& p, size_t size, size_t alignment = cacheLineSize) { void* mem = rtl_AllocateAligned(size, alignment); if(!mem) diff --git a/source/lib/code_annotation.h b/source/lib/code_annotation.h index 0dc31c49e2..1dedb94d54 100644 --- a/source/lib/code_annotation.h +++ b/source/lib/code_annotation.h @@ -96,9 +96,9 @@ // compiler supports ASSUME_UNREACHABLE => allow it to assume the code is // never reached (improves optimization at the cost of undefined behavior // if the annotation turns out to be incorrect). -#if HAVE_ASSUME_UNREACHABLE && !CONFIG_PARANOIA +#if HAVE_ASSUME_UNREACHABLE && !CONFIG_ENABLE_CHECKS # define UNREACHABLE ASSUME_UNREACHABLE -// otherwise (or if CONFIG_PARANOIA is set), add a user-visible +// otherwise (or if CONFIG_ENABLE_CHECKS is set), add a user-visible // warning if the code is reached. note that abort() fails to stop // ICC from warning about the lack of a return statement, so we // use an infinite loop instead. diff --git a/source/lib/config.h b/source/lib/config.h index 67144f5c5e..79d0a0daf9 100644 --- a/source/lib/config.h +++ b/source/lib/config.h @@ -56,14 +56,9 @@ # define CONFIG_DISABLE_EXCEPTIONS 0 #endif -// enable additional debug checks (very slow). -#ifndef CONFIG_PARANOIA -# define CONFIG_PARANOIA 0 -#endif - -// final release; disables some safety checks. -#ifndef CONFIG_FINAL -# define CONFIG_FINAL 0 +// enable additional debug checks (potentially rather slow). +#ifndef CONFIG_ENABLE_CHECKS +# define CONFIG_ENABLE_CHECKS 0 #endif // static type checking with Dehydra diff --git a/source/lib/debug.cpp b/source/lib/debug.cpp index dae58e2e8b..a985edf05e 100644 --- a/source/lib/debug.cpp +++ b/source/lib/debug.cpp @@ -43,16 +43,16 @@ #endif -ERROR_ASSOCIATE(ERR::SYM_NO_STACK_FRAMES_FOUND, L"No stack frames found", -1); -ERROR_ASSOCIATE(ERR::SYM_UNRETRIEVABLE_STATIC, L"Value unretrievable (stored in external module)", -1); -ERROR_ASSOCIATE(ERR::SYM_UNRETRIEVABLE, L"Value unretrievable", -1); -ERROR_ASSOCIATE(ERR::SYM_TYPE_INFO_UNAVAILABLE, L"Error getting type_info", -1); -ERROR_ASSOCIATE(ERR::SYM_INTERNAL_ERROR, L"Exception raised while processing a symbol", -1); -ERROR_ASSOCIATE(ERR::SYM_UNSUPPORTED, L"Symbol type not (fully) supported", -1); -ERROR_ASSOCIATE(ERR::SYM_CHILD_NOT_FOUND, L"Symbol does not have the given child", -1); -ERROR_ASSOCIATE(ERR::SYM_NESTING_LIMIT, L"Symbol nesting too deep or infinite recursion", -1); -ERROR_ASSOCIATE(ERR::SYM_SINGLE_SYMBOL_LIMIT, L"Symbol has produced too much output", -1); -ERROR_ASSOCIATE(INFO::SYM_SUPPRESS_OUTPUT, L"Symbol was suppressed", -1); +STATUS_DEFINE(ERR, SYM_NO_STACK_FRAMES_FOUND, L"No stack frames found", -1); +STATUS_DEFINE(ERR, SYM_UNRETRIEVABLE_STATIC, L"Value unretrievable (stored in external module)", -1); +STATUS_DEFINE(ERR, SYM_UNRETRIEVABLE, L"Value unretrievable", -1); +STATUS_DEFINE(ERR, SYM_TYPE_INFO_UNAVAILABLE, L"Error getting type_info", -1); +STATUS_DEFINE(ERR, SYM_INTERNAL_ERROR, L"Exception raised while processing a symbol", -1); +STATUS_DEFINE(ERR, SYM_UNSUPPORTED, L"Symbol type not (fully) supported", -1); +STATUS_DEFINE(ERR, SYM_CHILD_NOT_FOUND, L"Symbol does not have the given child", -1); +STATUS_DEFINE(ERR, SYM_NESTING_LIMIT, L"Symbol nesting too deep or infinite recursion", -1); +STATUS_DEFINE(ERR, SYM_SINGLE_SYMBOL_LIMIT, L"Symbol has produced too much output", -1); +STATUS_DEFINE(INFO, SYM_SUPPRESS_OUTPUT, L"Symbol was suppressed", -1); // need to shoehorn printf-style variable params into @@ -154,7 +154,7 @@ void debug_printf(const wchar_t* fmt, ...) //----------------------------------------------------------------------------- -LibError debug_WriteCrashlog(const wchar_t* text) +Status debug_WriteCrashlog(const wchar_t* text) { // (avoid infinite recursion and/or reentering this function if it // fails/reports an error) @@ -284,7 +284,7 @@ fail: } // append stack trace - LibError ret = debug_DumpStack(writer.Position(), writer.CharsLeft(), context, lastFuncToSkip); + Status ret = debug_DumpStack(writer.Position(), writer.CharsLeft(), context, lastFuncToSkip); if(ret == ERR::REENTERED) { if(!writer( @@ -299,7 +299,7 @@ fail: wchar_t description_buf[100] = {'?'}; if(!writer( L"(error while dumping stack: %ls)", - error_description_r(ret, description_buf, ARRAY_SIZE(description_buf)) + StatusDescription(ret, description_buf, ARRAY_SIZE(description_buf)) )) goto fail; } @@ -311,11 +311,11 @@ fail: // append OS error (just in case it happens to be relevant - // it's usually still set from unrelated operations) wchar_t description_buf[100] = L"?"; - LibError errno_equiv = LibError_from_errno(false); + Status errno_equiv = StatusFromErrno(); // NOWARN if(errno_equiv != ERR::FAIL) // meaningful translation - error_description_r(errno_equiv, description_buf, ARRAY_SIZE(description_buf)); + StatusDescription(errno_equiv, description_buf, ARRAY_SIZE(description_buf)); wchar_t os_error[100] = L"?"; - sys_error_description_r(0, os_error, ARRAY_SIZE(os_error)); + sys_StatusDescription(0, os_error, ARRAY_SIZE(os_error)); if(!writer( L"\r\n" L"errno = %d (%ls)\r\n" @@ -480,10 +480,10 @@ enum SkipStatus INVALID, VALID, BUSY }; static intptr_t skipStatus = INVALID; -static LibError errorToSkip; +static Status errorToSkip; static size_t numSkipped; -void debug_SkipErrors(LibError err) +void debug_SkipErrors(Status err) { if(cpu_CAS(&skipStatus, INVALID, BUSY)) { @@ -512,7 +512,7 @@ size_t debug_StopSkippingErrors() } } -static bool ShouldSkipError(LibError err) +static bool ShouldSkipError(Status err) { if(cpu_CAS(&skipStatus, VALID, BUSY)) { @@ -526,7 +526,7 @@ static bool ShouldSkipError(LibError err) } -ErrorReaction debug_OnError(LibError err, atomic_bool* suppress, const wchar_t* file, int line, const char* func) +ErrorReaction debug_OnError(Status err, atomic_bool* suppress, const wchar_t* file, int line, const char* func) { if(ShouldSkipError(err)) return ER_CONTINUE; @@ -534,8 +534,8 @@ ErrorReaction debug_OnError(LibError err, atomic_bool* suppress, const wchar_t* void* context = 0; const wchar_t* lastFuncToSkip = L"debug_OnError"; wchar_t buf[400]; - wchar_t err_buf[200]; error_description_r(err, err_buf, ARRAY_SIZE(err_buf)); - swprintf_s(buf, ARRAY_SIZE(buf), L"Function call failed: return value was %ld (%ls)", err, err_buf); + wchar_t err_buf[200]; StatusDescription(err, err_buf, ARRAY_SIZE(err_buf)); + swprintf_s(buf, ARRAY_SIZE(buf), L"Function call failed: return value was %lld (%ls)", err, err_buf); return debug_DisplayError(buf, DE_MANUAL_BREAK, context, lastFuncToSkip, file,line,func, suppress); } diff --git a/source/lib/debug.h b/source/lib/debug.h index 9facc20118..02dd727d58 100644 --- a/source/lib/debug.h +++ b/source/lib/debug.h @@ -36,7 +36,9 @@ // - the output routines make for platform-independent logging and // crashlogs with "last-known activity" reporting. -#include "lib/lib_errors.h" +#include "lib/lib_api.h" +#include "lib/types.h" // intptr_t +#include "lib/status.h" #include "lib/code_annotation.h" #include "lib/code_generation.h" @@ -253,10 +255,10 @@ LIB_API bool debug_filter_allows(const wchar_t* text); * @param text description of the error (including stack trace); * typically generated by debug_BuildErrorMessage. * - * @return LibError; ERR::REENTERED if reentered via recursion or + * @return Status; ERR::REENTERED if reentered via recursion or * multithreading (not allowed since an infinite loop may result). **/ -LIB_API LibError debug_WriteCrashlog(const wchar_t* text); +LIB_API Status debug_WriteCrashlog(const wchar_t* text); //----------------------------------------------------------------------------- @@ -318,14 +320,14 @@ LIB_API LibError debug_WriteCrashlog(const wchar_t* text); /** * display the error dialog with text corresponding to the given error code. - * used by CHECK_ERR et al., which wrap function calls and automatically + * used by WARN_RETURN_STATUS_IF_ERR et al., which wrap function calls and automatically * raise warnings and return to the caller. **/ -#define DEBUG_WARN_ERR(err)\ +#define DEBUG_WARN_ERR(status)\ do\ {\ static atomic_bool suppress__;\ - switch(debug_OnError(err, &suppress__, WIDEN(__FILE__), __LINE__, __func__))\ + switch(debug_OnError(status, &suppress__, WIDEN(__FILE__), __LINE__, __func__))\ {\ case ER_CONTINUE:\ break;\ @@ -354,30 +356,30 @@ LIB_API ErrorReaction debug_OnAssertionFailure(const wchar_t* assert_expr, atomi * called when a DEBUG_WARN_ERR indicates an error occurred; * notifies the user via debug_DisplayError. * - * @param err LibError value indicating the error that occurred + * @param err Status value indicating the error that occurred * @param suppress see debug_DisplayError. * @param file, line source file name and line number of the spot that failed * @param func name of the function containing it * @return ErrorReaction (user's choice: continue running or stop?) **/ -LIB_API ErrorReaction debug_OnError(LibError err, atomic_bool* suppress, const wchar_t* file, int line, const char* func); +LIB_API ErrorReaction debug_OnError(Status err, atomic_bool* suppress, const wchar_t* file, int line, const char* func); /** * suppress (prevent from showing) the error dialog from subsequent - * debug_OnError for the given LibError. + * debug_OnError for the given Status. * * rationale: for edge cases in some functions, warnings are raised in * addition to returning an error code. self-tests deliberately trigger * these cases and check for the latter but shouldn't cause the former. * we therefore need to squelch them. * - * @param err the LibError to skip. + * @param err the Status to skip. * * note: only one concurrent skip request is allowed; call * debug_StopSkippingErrors before the next debug_SkipErrors. */ -LIB_API void debug_SkipErrors(LibError err); +LIB_API void debug_SkipErrors(Status err); /** * @return how many errors were skipped since the call to debug_SkipErrors() @@ -391,18 +393,18 @@ LIB_API size_t debug_StopSkippingErrors(); namespace ERR { - const LibError SYM_NO_STACK_FRAMES_FOUND = -100400; - const LibError SYM_UNRETRIEVABLE_STATIC = -100401; - const LibError SYM_UNRETRIEVABLE = -100402; - const LibError SYM_TYPE_INFO_UNAVAILABLE = -100403; - const LibError SYM_INTERNAL_ERROR = -100404; - const LibError SYM_UNSUPPORTED = -100405; - const LibError SYM_CHILD_NOT_FOUND = -100406; + const Status SYM_NO_STACK_FRAMES_FOUND = -100400; + const Status SYM_UNRETRIEVABLE_STATIC = -100401; + const Status SYM_UNRETRIEVABLE = -100402; + const Status SYM_TYPE_INFO_UNAVAILABLE = -100403; + const Status SYM_INTERNAL_ERROR = -100404; + const Status SYM_UNSUPPORTED = -100405; + const Status SYM_CHILD_NOT_FOUND = -100406; // this limit is to prevent infinite recursion. - const LibError SYM_NESTING_LIMIT = -100407; + const Status SYM_NESTING_LIMIT = -100407; // this limit is to prevent large symbols (e.g. arrays or linked lists) // from taking up all available output space. - const LibError SYM_SINGLE_SYMBOL_LIMIT = -100408; + const Status SYM_SINGLE_SYMBOL_LIMIT = -100408; } namespace INFO @@ -410,7 +412,7 @@ namespace INFO // one of the dump_sym* functions decided not to output anything at // all (e.g. for member functions in UDTs - we don't want those). // therefore, skip any post-symbol formatting (e.g. ) as well. - const LibError SYM_SUPPRESS_OUTPUT = +100409; + const Status SYM_SUPPRESS_OUTPUT = +100409; } @@ -436,10 +438,10 @@ const size_t DBG_FILE_LEN = 100; * * note: all of the output parameters are optional; we pass back as much * information as is available and desired. - * @return LibError; INFO::OK iff any information was successfully + * @return Status; INFO::OK iff any information was successfully * retrieved and stored. **/ -LIB_API LibError debug_ResolveSymbol(void* ptr_of_interest, wchar_t* sym_name, wchar_t* file, int* line); +LIB_API Status debug_ResolveSymbol(void* ptr_of_interest, wchar_t* sym_name, wchar_t* file, int* line); /** * write a complete stack trace (including values of local variables) into @@ -456,10 +458,10 @@ LIB_API LibError debug_ResolveSymbol(void* ptr_of_interest, wchar_t* sym_name, w * matching of stdcall-decorated names). * Rationale: this is safer than specifying a fixed number of frames, * which can be incorrect due to inlining. - * @return LibError; ERR::REENTERED if reentered via recursion or + * @return Status; ERR::REENTERED if reentered via recursion or * multithreading (not allowed since static data is used). **/ -LIB_API LibError debug_DumpStack(wchar_t* buf, size_t maxChars, void* context, const wchar_t* lastFuncToSkip); +LIB_API Status debug_DumpStack(wchar_t* buf, size_t maxChars, void* context, const wchar_t* lastFuncToSkip); //----------------------------------------------------------------------------- diff --git a/source/lib/debug_stl.cpp b/source/lib/debug_stl.cpp index d44b4637bd..8e0b9451a4 100644 --- a/source/lib/debug_stl.cpp +++ b/source/lib/debug_stl.cpp @@ -36,8 +36,8 @@ #include "lib/regex.h" -ERROR_ASSOCIATE(ERR::STL_CNT_UNKNOWN, L"Unknown STL container type_name", -1); -ERROR_ASSOCIATE(ERR::STL_CNT_INVALID, L"Container type is known but contents are invalid", -1); +STATUS_DEFINE(ERR, STL_CNT_UNKNOWN, L"Unknown STL container type_name", -1); +STATUS_DEFINE(ERR, STL_CNT_INVALID, L"Container type is known but contents are invalid", -1); // used in debug_stl_simplify_name. @@ -541,7 +541,7 @@ template bool get_container_info(const T& t, size_t size, size_t el_siz // return number of elements and an iterator (any data it needs is stored in // it_mem, which must hold DEBUG_STL_MAX_ITERATOR_SIZE bytes). // returns 0 on success or an StlContainerError. -LibError debug_stl_get_container_info(const wchar_t* type_name, const u8* p, size_t size, +Status debug_stl_get_container_info(const wchar_t* type_name, const u8* p, size_t size, size_t el_size, size_t* el_count, DebugStlIterator* el_iterator, void* it_mem) { #if MSC_VERSION >= 1400 diff --git a/source/lib/debug_stl.h b/source/lib/debug_stl.h index b58f871837..1d3699b97c 100644 --- a/source/lib/debug_stl.h +++ b/source/lib/debug_stl.h @@ -30,9 +30,9 @@ namespace ERR { - const LibError STL_CNT_UNKNOWN = -100500; + const Status STL_CNT_UNKNOWN = -100500; // likely causes: not yet initialized or memory corruption. - const LibError STL_CNT_INVALID = -100501; + const Status STL_CNT_INVALID = -100501; } @@ -77,9 +77,9 @@ const size_t DEBUG_STL_MAX_ITERATOR_SIZE = 64; * @param el_iterator out; callback function that acts as an iterator * @param it_mem out; buffer holding the iterator state. must be * at least DEBUG_STL_MAX_ITERATOR_SIZE bytes. - * @return LibError (ERR::STL_*) + * @return Status (ERR::STL_*) **/ -extern LibError debug_stl_get_container_info(const wchar_t* type_name, const u8* p, size_t size, +extern Status debug_stl_get_container_info(const wchar_t* type_name, const u8* p, size_t size, size_t el_size, size_t* el_count, DebugStlIterator* el_iterator, void* it_mem); #endif // #ifndef INCLUDED_DEBUG_STL diff --git a/source/lib/external_libraries/openmp.h b/source/lib/external_libraries/openmp.h new file mode 100644 index 0000000000..3ccb51ac1c --- /dev/null +++ b/source/lib/external_libraries/openmp.h @@ -0,0 +1,41 @@ +#ifndef INCLUDED_EXTERNAL_LIBRARIES_OPENMP +#define INCLUDED_EXTERNAL_LIBRARIES_OPENMP + +// allows removing all OpenMP-related code via #define ENABLE_OPENMP 0 +// before including this header. (useful during debugging, because the +// VC debugger isn't able to display OpenMP private variables) +#ifdef ENABLE_OPENMP +# if ENABLE_OPENMP && !defined(_OPENMP) +# error "either enable OpenMP in the compiler settings or don't set ENABLE_OPENMP to 1" +# endif +#else // no user preference; default to compiler setting +# ifdef _OPENMP +# define ENABLE_OPENMP 1 +# else +# define ENABLE_OPENMP 0 +# endif +#endif + +#if ENABLE_OPENMP +# include +#else +# define omp_get_num_threads() 1 +# define omp_get_thread_num() 0 +# define omp_in_parallel() 0 +#endif + +// wrapper macro that evaluates to nothing if !ENABLE_OPENMP +// (much more convenient than individual #if ENABLE_OPENMP) +#if ENABLE_OPENMP +# if MSC_VERSION +# define OMP(args) __pragma(omp args) +# elif GCC_VERSION +# define OMP _Pragma("omp " #args) +# else +# error "port" +# endif +#else +# define OMP(args) +#endif + +#endif // #ifndef INCLUDED_EXTERNAL_LIBRARIES_OPENMP diff --git a/source/lib/file/archive/archive.cpp b/source/lib/file/archive/archive.cpp index 8695f129be..315e850618 100644 --- a/source/lib/file/archive/archive.cpp +++ b/source/lib/file/archive/archive.cpp @@ -27,8 +27,8 @@ #include "precompiled.h" #include "lib/file/archive/archive.h" -ERROR_ASSOCIATE(ERR::ARCHIVE_UNKNOWN_FORMAT, L"Unknown archive format", -1); -ERROR_ASSOCIATE(ERR::ARCHIVE_UNKNOWN_METHOD, L"Unknown compression method", -1); +STATUS_DEFINE(ERR, ARCHIVE_UNKNOWN_FORMAT, L"Unknown archive format", -1); +STATUS_DEFINE(ERR, ARCHIVE_UNKNOWN_METHOD, L"Unknown compression method", -1); IArchiveReader::~IArchiveReader() { diff --git a/source/lib/file/archive/archive.h b/source/lib/file/archive/archive.h index 2d29fa9087..620a4dad37 100644 --- a/source/lib/file/archive/archive.h +++ b/source/lib/file/archive/archive.h @@ -37,8 +37,8 @@ namespace ERR { - const LibError ARCHIVE_UNKNOWN_FORMAT = -110400; - const LibError ARCHIVE_UNKNOWN_METHOD = -110401; + const Status ARCHIVE_UNKNOWN_FORMAT = -110400; + const Status ARCHIVE_UNKNOWN_METHOD = -110401; } struct IArchiveFile : public IFileLoader @@ -56,7 +56,7 @@ struct IArchiveReader * @param pathname full pathname of entry; only valid during the callback. **/ typedef void (*ArchiveEntryCallback)(const VfsPath& pathname, const FileInfo& fileInfo, PIArchiveFile archiveFile, uintptr_t cbData); - virtual LibError ReadEntries(ArchiveEntryCallback cb, uintptr_t cbData) = 0; + virtual Status ReadEntries(ArchiveEntryCallback cb, uintptr_t cbData) = 0; }; typedef shared_ptr PIArchiveReader; @@ -91,7 +91,7 @@ struct IArchiveWriter * @param pathname the actual file to add * @param pathnameInArchive the name to store in the archive **/ - virtual LibError AddFile(const OsPath& pathname, const Path& pathameInArchive) = 0; + virtual Status AddFile(const OsPath& pathname, const Path& pathameInArchive) = 0; }; typedef shared_ptr PIArchiveWriter; diff --git a/source/lib/file/archive/archive_builder.cpp b/source/lib/file/archive/archive_builder.cpp index 373ab0e0e3..1caa619c96 100644 --- a/source/lib/file/archive/archive_builder.cpp +++ b/source/lib/file/archive/archive_builder.cpp @@ -175,7 +175,7 @@ public: // note: use this instead of resize because FileNode doesn't have // a default ctor. NB: this is how resize is implemented anyway. file_nodes.erase(file_nodes.begin() + MAX_IDS, file_nodes.end()); - WARN_ERR(ERR::LIMIT); + WARN_IF_ERR(ERR::LIMIT); } } }; @@ -306,10 +306,10 @@ class ConnectionBuilder } public: - LibError run(const char* trace_filename, Connections& connections) + Status run(const char* trace_filename, Connections& connections) { Trace t; - RETURN_ERR(trace_read_from_file(trace_filename, &t)); + RETURN_STATUS_IF_ERR(trace_read_from_file(trace_filename, &t)); // reserve memory for worst-case amount of connections (happens if // all accesses are unique). this is necessary because we store @@ -560,7 +560,7 @@ public: } }; -static LibError vfs_opt_init(const char* trace_filename, const char* archive_fn_fmt, bool force_build) +static Status vfs_opt_init(const char* trace_filename, const char* archive_fn_fmt, bool force_build) { Filesystem_Posix fsPosix; @@ -575,7 +575,7 @@ static LibError vfs_opt_init(const char* trace_filename, const char* archive_fn_ { char dir[PATH_MAX]; path_dir_only(archive_fn_fmt, dir); - RETURN_ERR(dir_GatherSortedEntries(&fsPosix, dir, existing_archives)); + RETURN_STATUS_IF_ERR(dir_GatherSortedEntries(&fsPosix, dir, existing_archives)); DirEntIt new_end = std::remove_if(existing_archives.begin(), existing_archives.end(), IsArchive(archive_fn)); existing_archives.erase(new_end, existing_archives.end()); } @@ -597,7 +597,7 @@ static LibError vfs_opt_init(const char* trace_filename, const char* archive_fn_ // are defined by trace entries. Connections connections; ConnectionBuilder cbuilder; - RETURN_ERR(cbuilder.run(trace_filename, connections)); + RETURN_STATUS_IF_ERR(cbuilder.run(trace_filename, connections)); // create output filename list by first adding the above edges (most // frequent first) and then adding the rest sequentially. @@ -605,7 +605,7 @@ static LibError vfs_opt_init(const char* trace_filename, const char* archive_fn_ fn_vector.push_back(0); // 0-terminate for use as Filenames Filenames V_fns = &fn_vector[0]; - RETURN_ERR(archive_build_init(archive_fn, V_fns, &ab)); + RETURN_STATUS_IF_ERR(archive_build_init(archive_fn, V_fns, &ab)); return INFO::OK; } @@ -660,7 +660,7 @@ static bool should_build_mini_archive(const char* UNUSED(mini_archive_fn_fmt)) return false; } -static LibError build_mini_archive(const char* mini_archive_fn_fmt) +static Status build_mini_archive(const char* mini_archive_fn_fmt) { if(!should_build_mini_archive(mini_archive_fn_fmt)) return INFO::SKIPPED; @@ -676,7 +676,7 @@ static LibError build_mini_archive(const char* mini_archive_fn_fmt) Filesystem_Posix fsPosix; dir_NextNumberedFilename(&fsPosix, mini_archive_fn_fmt, &nfi, mini_archive_fn); - RETURN_ERR(archive_build(mini_archive_fn, V_fns)); + RETURN_STATUS_IF_ERR(archive_build(mini_archive_fn, V_fns)); delete[] V_fns; return INFO::OK; #else @@ -712,7 +712,7 @@ struct ArchiveBuildState // create an archive (overwriting previous file) and fill it with the given // files. compression method is chosen based on extension. -LibError archive_build_init(const char* P_archive_filename, Filenames V_fns, ArchiveBuildState* ab) +Status archive_build_init(const char* P_archive_filename, Filenames V_fns, ArchiveBuildState* ab) { ab->archiveBuilder = CreateArchiveBuilder_Zip(P_archive_filename); @@ -779,14 +779,14 @@ void archive_build_cancel(ArchiveBuildState* ab) } -LibError archive_build(const char* P_archive_filename, Filenames V_fns) +Status archive_build(const char* P_archive_filename, Filenames V_fns) { ArchiveBuildState ab; - RETURN_ERR(archive_build_init(P_archive_filename, V_fns, &ab)); + RETURN_STATUS_IF_ERR(archive_build_init(P_archive_filename, V_fns, &ab)); for(;;) { int ret = archive_build_continue(&ab); - RETURN_ERR(ret); + RETURN_STATUS_IF_ERR(ret); if(ret == INFO::OK) return INFO::OK; } @@ -835,7 +835,7 @@ int vfs_opt_auto_build(const char* trace_filename, else { // create mini-archive (if needed) - RETURN_ERR(build_mini_archive(mini_archive_fn_fmt)); + RETURN_STATUS_IF_ERR(build_mini_archive(mini_archive_fn_fmt)); state = NOP; return INFO::OK; // "finished" @@ -854,12 +854,12 @@ int vfs_opt_auto_build(const char* trace_filename, UNREACHABLE; } -LibError vfs_opt_rebuild_main_archive(const char* trace_filename, const char* archive_fn_fmt) +Status vfs_opt_rebuild_main_archive(const char* trace_filename, const char* archive_fn_fmt) { for(;;) { int ret = vfs_opt_auto_build(trace_filename, archive_fn_fmt, 0, true); - RETURN_ERR(ret); + RETURN_STATUS_IF_ERR(ret); if(ret == INFO::OK) return INFO::OK; } @@ -912,8 +912,8 @@ struct Trace }; extern void trace_get(Trace* t); -extern LibError trace_write_to_file(const char* trace_filename); -extern LibError trace_read_from_file(const char* trace_filename, Trace* t); +extern Status trace_write_to_file(const char* trace_filename); +extern Status trace_read_from_file(const char* trace_filename, Trace* t); // simulate carrying out the entry's TraceOp to determine @@ -922,7 +922,7 @@ extern bool trace_entry_causes_io(const TraceEntry* ent); // carry out all operations specified in the trace. -extern LibError trace_run(const char* trace_filename); +extern Status trace_run(const char* trace_filename); @@ -1108,10 +1108,10 @@ bool trace_entry_causes_io(FileCache& simulatedCache, const TraceEntry* ent) -LibError trace_run(const char* osPathname) +Status trace_run(const char* osPathname) { Trace trace; - RETURN_ERR(trace.Load(osPathname)); + RETURN_STATUS_IF_ERR(trace.Load(osPathname)); for(size_t i = 0; i < trace.NumEntries(); i++) trace.Entries()[i]->Run(); return INFO::OK; diff --git a/source/lib/file/archive/archive_builder.h b/source/lib/file/archive/archive_builder.h index 64030b4ea6..d5fe6cb247 100644 --- a/source/lib/file/archive/archive_builder.h +++ b/source/lib/file/archive/archive_builder.h @@ -29,7 +29,7 @@ #define INCLUDED_VFS_OPTIMIZER -extern LibError vfs_opt_rebuild_main_archive(const char* trace_filename, const char* archive_fn_fmt); +extern Status vfs_opt_rebuild_main_archive(const char* trace_filename, const char* archive_fn_fmt); extern void vfs_opt_auto_build_cancel(); diff --git a/source/lib/file/archive/archive_zip.cpp b/source/lib/file/archive/archive_zip.cpp index a3009529d8..f0a8337ec3 100644 --- a/source/lib/file/archive/archive_zip.cpp +++ b/source/lib/file/archive/archive_zip.cpp @@ -314,7 +314,7 @@ public: return m_file->Pathname(); } - virtual LibError Load(const OsPath& UNUSED(name), const shared_ptr& buf, size_t size) const + virtual Status Load(const OsPath& UNUSED(name), const shared_ptr& buf, size_t size) const { AdjustOffset(); @@ -335,8 +335,8 @@ public: stream.SetOutputBuffer(buf.get(), size); io::Operation op(*m_file.get(), 0, m_csize, m_ofs); StreamFeeder streamFeeder(stream); - RETURN_ERR(io::Run(op, io::Parameters(), streamFeeder)); - RETURN_ERR(stream.Finish()); + RETURN_STATUS_IF_ERR(io::Run(op, io::Parameters(), streamFeeder)); + RETURN_STATUS_IF_ERR(stream.Finish()); #if CODEC_COMPUTE_CHECKSUM ENSURE(m_checksum == stream.Checksum()); #endif @@ -374,7 +374,7 @@ private: // rationale: this allows using temp buffers for zip_fixup_lfh, // which avoids involving the file buffer manager and thus // avoids cluttering the trace and cache contents. - LibError operator()(const u8* block, size_t size) const + Status operator()(const u8* block, size_t size) const { ENSURE(size <= lfh_bytes_remaining); memcpy(lfh_dst, block, size); @@ -441,17 +441,17 @@ public: ENSURE(m_fileSize >= off_t(minFileSize)); } - virtual LibError ReadEntries(ArchiveEntryCallback cb, uintptr_t cbData) + virtual Status ReadEntries(ArchiveEntryCallback cb, uintptr_t cbData) { // locate and read Central Directory off_t cd_ofs = 0; size_t cd_numEntries = 0; size_t cd_size = 0; - RETURN_ERR(LocateCentralDirectory(m_file, m_fileSize, cd_ofs, cd_numEntries, cd_size)); + RETURN_STATUS_IF_ERR(LocateCentralDirectory(m_file, m_fileSize, cd_ofs, cd_numEntries, cd_size)); UniqueRange buf(RVALUE(io::Allocate(cd_size))); io::Operation op(*m_file.get(), buf.get(), cd_size, cd_ofs); - RETURN_ERR(io::Run(op)); + RETURN_STATUS_IF_ERR(io::Run(op)); // iterate over Central Directory const u8* pos = (const u8*)buf.get(); @@ -511,7 +511,7 @@ private: // search for ECDR in the last bytes of the file. // if found, fill with a copy of the (little-endian) ECDR and // return INFO::OK, otherwise IO error or ERR::CORRUPTED. - static LibError ScanForEcdr(const PFile& file, off_t fileSize, u8* buf, size_t maxScanSize, size_t& cd_numEntries, off_t& cd_ofs, size_t& cd_size) + static Status ScanForEcdr(const PFile& file, off_t fileSize, u8* buf, size_t maxScanSize, size_t& cd_numEntries, off_t& cd_ofs, size_t& cd_size) { // don't scan more than the entire file const size_t scanSize = std::min(maxScanSize, size_t(fileSize)); @@ -519,7 +519,7 @@ private: // read desired chunk of file into memory const off_t ofs = fileSize - off_t(scanSize); io::Operation op(*file.get(), buf, scanSize, ofs); - RETURN_ERR(io::Run(op)); + RETURN_STATUS_IF_ERR(io::Run(op)); // look for ECDR in buffer const ECDR* ecdr = (const ECDR*)FindRecord(buf, scanSize, buf, ecdr_magic, sizeof(ECDR)); @@ -530,13 +530,13 @@ private: return INFO::OK; } - static LibError LocateCentralDirectory(const PFile& file, off_t fileSize, off_t& cd_ofs, size_t& cd_numEntries, size_t& cd_size) + static Status LocateCentralDirectory(const PFile& file, off_t fileSize, off_t& cd_ofs, size_t& cd_numEntries, size_t& cd_size) { const size_t maxScanSize = 66000u; // see below UniqueRange buf(RVALUE(io::Allocate(maxScanSize))); // expected case: ECDR at EOF; no file comment - LibError ret = ScanForEcdr(file, fileSize, (u8*)buf.get(), sizeof(ECDR), cd_numEntries, cd_ofs, cd_size); + Status ret = ScanForEcdr(file, fileSize, (u8*)buf.get(), sizeof(ECDR), cd_numEntries, cd_ofs, cd_size); if(ret == INFO::OK) return INFO::OK; // worst case: ECDR precedes 64 KiB of file comment @@ -546,7 +546,7 @@ private: // both ECDR scans failed - this is not a valid Zip file. io::Operation op(*file.get(), buf.get(), sizeof(LFH)); - RETURN_ERR(io::Run(op)); + RETURN_STATUS_IF_ERR(io::Run(op)); // the Zip file has an LFH but lacks an ECDR. this can happen if // the user hard-exits while an archive is being written. // notes: @@ -583,7 +583,7 @@ public: : m_file(new File(archivePathname, LIO_WRITE)), m_fileSize(0) , m_numEntries(0), m_noDeflate(noDeflate) { - THROW_ERR(pool_create(&m_cdfhPool, 10*MiB, 0)); + THROW_STATUS_IF_ERR(pool_create(&m_cdfhPool, 10*MiB, 0)); } ~ArchiveWriter_Zip() @@ -603,10 +603,10 @@ public: (void)pool_destroy(&m_cdfhPool); } - LibError AddFile(const OsPath& pathname, const OsPath& pathnameInArchive) + Status AddFile(const OsPath& pathname, const OsPath& pathnameInArchive) { FileInfo fileInfo; - RETURN_ERR(GetFileInfo(pathname, &fileInfo)); + RETURN_STATUS_IF_ERR(GetFileInfo(pathname, &fileInfo)); const off_t usize = fileInfo.Size(); // skip 0-length files. // rationale: zip.cpp needs to determine whether a CDFH entry is @@ -620,7 +620,7 @@ public: return INFO::SKIPPED; PFile file(new File); - RETURN_ERR(file->Open(pathname, LIO_READ)); + RETURN_STATUS_IF_ERR(file->Open(pathname, LIO_READ)); const size_t pathnameLength = pathnameInArchive.string().length(); @@ -650,8 +650,8 @@ public: stream.SetOutputBuffer(cdata, csizeMax); io::Operation op(*file.get(), 0, usize); StreamFeeder streamFeeder(stream); - RETURN_ERR(io::Run(op, io::Parameters(), streamFeeder)); - RETURN_ERR(stream.Finish()); + RETURN_STATUS_IF_ERR(io::Run(op, io::Parameters(), streamFeeder)); + RETURN_STATUS_IF_ERR(stream.Finish()); csize = stream.OutSize(); checksum = stream.Checksum(); } diff --git a/source/lib/file/archive/codec.h b/source/lib/file/archive/codec.h index 813a281b38..b67fc5d346 100644 --- a/source/lib/file/archive/codec.h +++ b/source/lib/file/archive/codec.h @@ -53,7 +53,7 @@ public: * efficient since it avoids reallocating a considerable amount of * memory (about 200KB for LZ). **/ - virtual LibError Reset() = 0; + virtual Status Reset() = 0; /** * process (i.e. compress or decompress) data. @@ -66,7 +66,7 @@ public: * output buffers were used. either or both of these can be zero if * the input size is small or there's not enough output space. **/ - virtual LibError Process(const u8* in, size_t inSize, u8* out, size_t outSize, size_t& inConsumed, size_t& outProduced) = 0; + virtual Status Process(const u8* in, size_t inSize, u8* out, size_t outSize, size_t& inConsumed, size_t& outProduced) = 0; /** * Flush buffers and make sure all output has been produced. @@ -75,7 +75,7 @@ public: * @param outProduced * @return error status for the entire operation. **/ - virtual LibError Finish(u32& checksum, size_t& outProduced) = 0; + virtual Status Finish(u32& checksum, size_t& outProduced) = 0; /** * update a checksum to reflect the contents of a buffer. diff --git a/source/lib/file/archive/codec_zlib.cpp b/source/lib/file/archive/codec_zlib.cpp index 4b58e6f2d9..72beebe894 100644 --- a/source/lib/file/archive/codec_zlib.cpp +++ b/source/lib/file/archive/codec_zlib.cpp @@ -76,13 +76,13 @@ public: return inSize; } - virtual LibError Reset() + virtual Status Reset() { m_checksum = InitializeChecksum(); return INFO::OK; } - virtual LibError Process(const u8* in, size_t inSize, u8* out, size_t outSize, size_t& inConsumed, size_t& outProduced) + virtual Status Process(const u8* in, size_t inSize, u8* out, size_t outSize, size_t& inConsumed, size_t& outProduced) { const size_t transferSize = std::min(inSize, outSize); memcpy(out, in, transferSize); @@ -91,7 +91,7 @@ public: return INFO::OK; } - virtual LibError Finish(u32& checksum, size_t& outProduced) + virtual Status Finish(u32& checksum, size_t& outProduced) { outProduced = 0; checksum = m_checksum; @@ -114,7 +114,7 @@ protected: m_checksum = InitializeChecksum(); } - static LibError LibError_from_zlib(int zlib_ret) + static Status LibError_from_zlib(int zlib_ret) { switch(zlib_ret) { @@ -140,7 +140,7 @@ protected: typedef int ZEXPORT (*ZLibFunc)(z_streamp strm, int flush); - LibError CallStreamFunc(ZLibFunc func, int flush, const u8* in, const size_t inSize, u8* out, const size_t outSize, size_t& inConsumed, size_t& outProduced) + Status CallStreamFunc(ZLibFunc func, int flush, const u8* in, const size_t inSize, u8* out, const size_t outSize, size_t& inConsumed, size_t& outProduced) { m_zs.next_in = (Byte*)in; m_zs.avail_in = (uInt)inSize; @@ -184,14 +184,8 @@ public: // note: with Z_BEST_COMPRESSION, 78% percent of // archive builder CPU time is spent in ZLib, even though // that is interleaved with IO; everything else is negligible. - // we therefore enable this only in final builds; during - // development, 1.5% bigger archives are definitely worth much - // faster build time. -#if CONFIG_FINAL - const int level = Z_BEST_COMPRESSION; -#else + // we prefer faster speed at the cost of 1.5% larger archives. const int level = Z_BEST_SPEED; -#endif const int windowBits = -MAX_WBITS; // max window size; omit ZLib header const int memLevel = 9; // max speed; total mem ~= 384KiB const int strategy = Z_DEFAULT_STRATEGY; // normal data - not RLE @@ -210,20 +204,20 @@ public: return (size_t)deflateBound(&m_zs, (uLong)inSize); } - virtual LibError Reset() + virtual Status Reset() { m_checksum = InitializeChecksum(); const int ret = deflateReset(&m_zs); return LibError_from_zlib(ret); } - virtual LibError Process(const u8* in, size_t inSize, u8* out, size_t outSize, size_t& inConsumed, size_t& outProduced) + virtual Status Process(const u8* in, size_t inSize, u8* out, size_t outSize, size_t& inConsumed, size_t& outProduced) { m_checksum = UpdateChecksum(m_checksum, in, inSize); return CodecZLibStream::CallStreamFunc(deflate, 0, in, inSize, out, outSize, inConsumed, outProduced); } - virtual LibError Finish(u32& checksum, size_t& outProduced) + virtual Status Finish(u32& checksum, size_t& outProduced) { const uInt availOut = m_zs.avail_out; @@ -269,21 +263,21 @@ public: return inSize*1032; // see http://www.zlib.org/zlib_tech.html } - virtual LibError Reset() + virtual Status Reset() { m_checksum = InitializeChecksum(); const int ret = inflateReset(&m_zs); return LibError_from_zlib(ret); } - virtual LibError Process(const u8* in, size_t inSize, u8* out, size_t outSize, size_t& inConsumed, size_t& outProduced) + virtual Status Process(const u8* in, size_t inSize, u8* out, size_t outSize, size_t& inConsumed, size_t& outProduced) { - const LibError ret = CodecZLibStream::CallStreamFunc(inflate, Z_SYNC_FLUSH, in, inSize, out, outSize, inConsumed, outProduced); + const Status ret = CodecZLibStream::CallStreamFunc(inflate, Z_SYNC_FLUSH, in, inSize, out, outSize, inConsumed, outProduced); m_checksum = UpdateChecksum(m_checksum, out, outProduced); return ret; } - virtual LibError Finish(u32& checksum, size_t& outProduced) + virtual Status Finish(u32& checksum, size_t& outProduced) { // no action needed - decompression always flushes immediately. outProduced = 0; diff --git a/source/lib/file/archive/stream.cpp b/source/lib/file/archive/stream.cpp index ab6fa2ed4e..705d7264ce 100644 --- a/source/lib/file/archive/stream.cpp +++ b/source/lib/file/archive/stream.cpp @@ -113,7 +113,7 @@ void Stream::SetOutputBuffer(u8* out, size_t outSize) } -LibError Stream::Feed(const u8* in, size_t inSize) +Status Stream::Feed(const u8* in, size_t inSize) { if(m_outProduced == m_outputBufferManager.Size()) // output buffer full; must not call Process return INFO::OK; @@ -121,7 +121,7 @@ LibError Stream::Feed(const u8* in, size_t inSize) size_t inConsumed, outProduced; u8* const out = m_outputBufferManager.Buffer() + m_outProduced; const size_t outSize = m_outputBufferManager.Size() - m_outProduced; - RETURN_ERR(m_codec->Process(in, inSize, out, outSize, inConsumed, outProduced)); + RETURN_STATUS_IF_ERR(m_codec->Process(in, inSize, out, outSize, inConsumed, outProduced)); m_inConsumed += inConsumed; m_outProduced += outProduced; @@ -129,10 +129,10 @@ LibError Stream::Feed(const u8* in, size_t inSize) } -LibError Stream::Finish() +Status Stream::Finish() { size_t outProduced; - RETURN_ERR(m_codec->Finish(m_checksum, outProduced)); + RETURN_STATUS_IF_ERR(m_codec->Finish(m_checksum, outProduced)); m_outProduced += outProduced; return INFO::OK; } diff --git a/source/lib/file/archive/stream.h b/source/lib/file/archive/stream.h index 0ef4d1aefa..dd5a000a01 100644 --- a/source/lib/file/archive/stream.h +++ b/source/lib/file/archive/stream.h @@ -87,9 +87,9 @@ public: /** * 'feed' the codec with a data block. **/ - LibError Feed(const u8* in, size_t inSize); + Status Feed(const u8* in, size_t inSize); - LibError Finish(); + Status Finish(); size_t OutSize() const { @@ -121,7 +121,7 @@ public: { } - LibError operator()(const u8* data, size_t size) const + Status operator()(const u8* data, size_t size) const { return stream.Feed(data, size); } diff --git a/source/lib/file/common/file_loader.h b/source/lib/file/common/file_loader.h index 23923c91f8..5cb5ab4290 100644 --- a/source/lib/file/common/file_loader.h +++ b/source/lib/file/common/file_loader.h @@ -33,7 +33,7 @@ struct IFileLoader virtual wchar_t LocationCode() const = 0; virtual OsPath Path() const = 0; - virtual LibError Load(const OsPath& name, const shared_ptr& buf, size_t size) const = 0; + virtual Status Load(const OsPath& name, const shared_ptr& buf, size_t size) const = 0; }; typedef shared_ptr PIFileLoader; diff --git a/source/lib/file/common/real_directory.cpp b/source/lib/file/common/real_directory.cpp index b6c03e37b6..7f6d2816fa 100644 --- a/source/lib/file/common/real_directory.cpp +++ b/source/lib/file/common/real_directory.cpp @@ -46,13 +46,13 @@ RealDirectory::RealDirectory(const OsPath& path, size_t priority, size_t flags) } -/*virtual*/ LibError RealDirectory::Load(const OsPath& name, const shared_ptr& buf, size_t size) const +/*virtual*/ Status RealDirectory::Load(const OsPath& name, const shared_ptr& buf, size_t size) const { return io::Load(m_path / name, buf.get(), size); } -LibError RealDirectory::Store(const OsPath& name, const shared_ptr& fileContents, size_t size) +Status RealDirectory::Store(const OsPath& name, const shared_ptr& fileContents, size_t size) { return io::Store(m_path / name, fileContents.get(), size); } diff --git a/source/lib/file/common/real_directory.h b/source/lib/file/common/real_directory.h index e1b4af9cc5..acf54316cc 100644 --- a/source/lib/file/common/real_directory.h +++ b/source/lib/file/common/real_directory.h @@ -49,9 +49,9 @@ public: { return m_path; } - virtual LibError Load(const OsPath& name, const shared_ptr& buf, size_t size) const; + virtual Status Load(const OsPath& name, const shared_ptr& buf, size_t size) const; - LibError Store(const OsPath& name, const shared_ptr& fileContents, size_t size); + Status Store(const OsPath& name, const shared_ptr& fileContents, size_t size); void Watch(); diff --git a/source/lib/file/common/trace.cpp b/source/lib/file/common/trace.cpp index 042a1c31b5..a038de89ab 100644 --- a/source/lib/file/common/trace.cpp +++ b/source/lib/file/common/trace.cpp @@ -112,12 +112,12 @@ public: { } - virtual LibError Load(const OsPath& UNUSED(pathname)) + virtual Status Load(const OsPath& UNUSED(pathname)) { return INFO::OK; } - virtual LibError Store(const OsPath& UNUSED(pathname)) const + virtual Status Store(const OsPath& UNUSED(pathname)) const { return INFO::OK; } @@ -165,14 +165,14 @@ public: new(Allocate()) TraceEntry(TraceEntry::Store, pathname, size); } - virtual LibError Load(const OsPath& pathname) + virtual Status Load(const OsPath& pathname) { pool_free_all(&m_pool); errno = 0; FILE* file = sys_OpenFile(pathname, "rt"); if(!file) - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); for(;;) { @@ -186,12 +186,12 @@ public: return INFO::OK; } - virtual LibError Store(const OsPath& pathname) const + virtual Status Store(const OsPath& pathname) const { errno = 0; FILE* file = sys_OpenFile(pathname, "at"); if(!file) - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); for(size_t i = 0; i < NumEntries(); i++) { std::wstring text = Entries()[i].EncodeAsText(); diff --git a/source/lib/file/common/trace.h b/source/lib/file/common/trace.h index 8ecfe058da..f9f5482105 100644 --- a/source/lib/file/common/trace.h +++ b/source/lib/file/common/trace.h @@ -105,7 +105,7 @@ struct ITrace * because storing filename strings in a binary format would be a * bit awkward. **/ - virtual LibError Store(const OsPath& pathname) const = 0; + virtual Status Store(const OsPath& pathname) const = 0; /** * load entries from file. @@ -114,7 +114,7 @@ struct ITrace * * replaces any existing entries. **/ - virtual LibError Load(const OsPath& pathname) = 0; + virtual Status Load(const OsPath& pathname) = 0; virtual const TraceEntry* Entries() const = 0; virtual size_t NumEntries() const = 0; diff --git a/source/lib/file/file.cpp b/source/lib/file/file.cpp index dac19eb92a..068d346862 100644 --- a/source/lib/file/file.cpp +++ b/source/lib/file/file.cpp @@ -31,11 +31,11 @@ #include "lib/file/common/file_stats.h" -ERROR_ASSOCIATE(ERR::FILE_ACCESS, L"Insufficient access rights to open file", EACCES); -ERROR_ASSOCIATE(ERR::FILE_NOT_FOUND, L"No such file or directory", ENOENT); +STATUS_DEFINE(ERR, FILE_ACCESS, L"Insufficient access rights to open file", EACCES); +STATUS_DEFINE(ERR, FILE_NOT_FOUND, L"No such file or directory", ENOENT); -LibError FileOpen(const OsPath& pathname, int opcode, int& fd) +Status FileOpen(const OsPath& pathname, int opcode, int& fd) { int oflag = 0; switch(opcode) @@ -58,7 +58,7 @@ LibError FileOpen(const OsPath& pathname, int opcode, int& fd) const mode_t mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH; // 0644 fd = wopen(pathname, oflag, mode); if(fd < 0) - return LibError_from_errno(false); + return StatusFromErrno(); // NOWARN stats_open(); return INFO::OK; diff --git a/source/lib/file/file.h b/source/lib/file/file.h index f395459d06..f1e8bb4dc9 100644 --- a/source/lib/file/file.h +++ b/source/lib/file/file.h @@ -32,11 +32,11 @@ namespace ERR { - const LibError FILE_ACCESS = -110300; - const LibError FILE_NOT_FOUND = -110301; + const Status FILE_ACCESS = -110300; + const Status FILE_NOT_FOUND = -110301; } -LIB_API LibError FileOpen(const OsPath& pathname, int opcode, int& fd); +LIB_API Status FileOpen(const OsPath& pathname, int opcode, int& fd); LIB_API void FileClose(int& fd); class File @@ -57,9 +57,9 @@ public: Close(); } - LibError Open(const OsPath& pathname, int opcode) + Status Open(const OsPath& pathname, int opcode) { - RETURN_ERR(FileOpen(pathname, opcode, fd)); + RETURN_STATUS_IF_ERR(FileOpen(pathname, opcode, fd)); this->pathname = pathname; this->opcode = opcode; return INFO::OK; diff --git a/source/lib/file/file_system.cpp b/source/lib/file/file_system.cpp index 8028948923..4f427889d5 100644 --- a/source/lib/file/file_system.cpp +++ b/source/lib/file/file_system.cpp @@ -38,13 +38,13 @@ struct DirDeleter } }; -LibError GetDirectoryEntries(const OsPath& path, FileInfos* files, DirectoryNames* subdirectoryNames) +Status GetDirectoryEntries(const OsPath& path, FileInfos* files, DirectoryNames* subdirectoryNames) { // open directory errno = 0; WDIR* pDir = wopendir(path); if(!pDir) - return LibError_from_errno(false); + return StatusFromErrno(); // NOWARN shared_ptr osDir(pDir, DirDeleter()); for(;;) @@ -56,24 +56,24 @@ LibError GetDirectoryEntries(const OsPath& path, FileInfos* files, DirectoryName // no error, just no more entries to return if(!errno) return INFO::OK; - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); } for(size_t i = 0; osEnt->d_name[i] != '\0'; i++) - RETURN_ERR(Path::Validate(osEnt->d_name[i])); + RETURN_STATUS_IF_ERR(Path::Validate(osEnt->d_name[i])); const OsPath name(osEnt->d_name); // get file information (mode, size, mtime) struct stat s; #if OS_WIN // .. return wdirent directly (much faster than calling stat). - RETURN_ERR(wreaddir_stat_np(osDir.get(), &s)); + RETURN_STATUS_IF_ERR(wreaddir_stat_np(osDir.get(), &s)); #else // .. call regular stat(). errno = 0; const OsPath pathname = path / name; if(wstat(pathname, &s) != 0) - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); #endif if(files && S_ISREG(s.st_mode)) @@ -84,20 +84,20 @@ LibError GetDirectoryEntries(const OsPath& path, FileInfos* files, DirectoryName } -LibError GetFileInfo(const OsPath& pathname, FileInfo* pfileInfo) +Status GetFileInfo(const OsPath& pathname, FileInfo* pfileInfo) { errno = 0; struct stat s; memset(&s, 0, sizeof(s)); if(wstat(pathname, &s) != 0) - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); *pfileInfo = FileInfo(pathname.Filename(), s.st_size, s.st_mtime); return INFO::OK; } -LibError CreateDirectories(const OsPath& path, mode_t mode) +Status CreateDirectories(const OsPath& path, mode_t mode) { if(path.empty()) return INFO::OK; @@ -115,23 +115,23 @@ LibError CreateDirectories(const OsPath& path, mode_t mode) if(path.IsDirectory()) return CreateDirectories(path.Parent(), mode); - RETURN_ERR(CreateDirectories(path.Parent(), mode)); + RETURN_STATUS_IF_ERR(CreateDirectories(path.Parent(), mode)); errno = 0; if(wmkdir(path, mode) != 0) - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); return INFO::OK; } -LibError DeleteDirectory(const OsPath& path) +Status DeleteDirectory(const OsPath& path) { // note: we have to recursively empty the directory before it can // be deleted (required by Windows and POSIX rmdir()). FileInfos files; DirectoryNames subdirectoryNames; - RETURN_ERR(GetDirectoryEntries(path, &files, &subdirectoryNames)); + RETURN_STATUS_IF_ERR(GetDirectoryEntries(path, &files, &subdirectoryNames)); // delete files for(size_t i = 0; i < files.size(); i++) @@ -139,16 +139,16 @@ LibError DeleteDirectory(const OsPath& path) const OsPath pathname = path / files[i].Name(); errno = 0; if(wunlink(pathname) != 0) - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); } // recurse over subdirectoryNames for(size_t i = 0; i < subdirectoryNames.size(); i++) - RETURN_ERR(DeleteDirectory(path / subdirectoryNames[i])); + RETURN_STATUS_IF_ERR(DeleteDirectory(path / subdirectoryNames[i])); errno = 0; if(wrmdir(path) != 0) - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); return INFO::OK; } diff --git a/source/lib/file/file_system.h b/source/lib/file/file_system.h index d1b8fdce0c..0993b7cc8f 100644 --- a/source/lib/file/file_system.h +++ b/source/lib/file/file_system.h @@ -60,17 +60,17 @@ private: time_t mtime; }; -extern LibError GetFileInfo(const OsPath& pathname, FileInfo* fileInfo); +extern Status GetFileInfo(const OsPath& pathname, FileInfo* fileInfo); typedef std::vector FileInfos; typedef std::vector DirectoryNames; -extern LibError GetDirectoryEntries(const OsPath& path, FileInfos* files, DirectoryNames* subdirectoryNames); +extern Status GetDirectoryEntries(const OsPath& path, FileInfos* files, DirectoryNames* subdirectoryNames); // same as boost::filesystem::create_directories, except that mkdir is invoked with // instead of 0755. -extern LibError CreateDirectories(const OsPath& path, mode_t mode); +extern Status CreateDirectories(const OsPath& path, mode_t mode); -extern LibError DeleteDirectory(const OsPath& dirPath); +extern Status DeleteDirectory(const OsPath& dirPath); #endif // #ifndef INCLUDED_FILE_SYSTEM diff --git a/source/lib/file/file_system_util.cpp b/source/lib/file/file_system_util.cpp index 72e75a472a..f073b62ec5 100644 --- a/source/lib/file/file_system_util.cpp +++ b/source/lib/file/file_system_util.cpp @@ -65,10 +65,10 @@ u64 FileSize(const OsPath& pathname) } -LibError GetPathnames(const PIVFS& fs, const VfsPath& path, const wchar_t* filter, VfsPaths& pathnames) +Status GetPathnames(const PIVFS& fs, const VfsPath& path, const wchar_t* filter, VfsPaths& pathnames) { std::vector files; - RETURN_ERR(fs->GetDirectoryEntries(path, &files, 0)); + RETURN_STATUS_IF_ERR(fs->GetDirectoryEntries(path, &files, 0)); pathnames.clear(); pathnames.reserve(files.size()); @@ -83,7 +83,7 @@ LibError GetPathnames(const PIVFS& fs, const VfsPath& path, const wchar_t* filte } -LibError ForEachFile(const PIVFS& fs, const VfsPath& startPath, FileCallback cb, uintptr_t cbData, const wchar_t* pattern, size_t flags) +Status ForEachFile(const PIVFS& fs, const VfsPath& startPath, FileCallback cb, uintptr_t cbData, const wchar_t* pattern, size_t flags) { // (declare here to avoid reallocations) FileInfos files; DirectoryNames subdirectoryNames; @@ -96,7 +96,7 @@ LibError ForEachFile(const PIVFS& fs, const VfsPath& startPath, FileCallback cb, { const VfsPath& path = pendingDirectories.front(); - RETURN_ERR(fs->GetDirectoryEntries(path, &files, &subdirectoryNames)); + RETURN_STATUS_IF_ERR(fs->GetDirectoryEntries(path, &files, &subdirectoryNames)); for(size_t i = 0; i < files.size(); i++) { diff --git a/source/lib/file/file_system_util.h b/source/lib/file/file_system_util.h index 2130076466..eba7e36d96 100644 --- a/source/lib/file/file_system_util.h +++ b/source/lib/file/file_system_util.h @@ -37,7 +37,7 @@ LIB_API bool FileExists(const OsPath& pathname); LIB_API u64 FileSize(const OsPath& pathname); -extern LibError GetPathnames(const PIVFS& fs, const VfsPath& path, const wchar_t* filter, VfsPaths& pathnames); +extern Status GetPathnames(const PIVFS& fs, const VfsPath& path, const wchar_t* filter, VfsPaths& pathnames); /** * called for files in a directory. @@ -51,7 +51,7 @@ extern LibError GetPathnames(const PIVFS& fs, const VfsPath& path, const wchar_t * CAVEAT: pathname and fileInfo are only valid until the function * returns! **/ -typedef LibError (*FileCallback)(const VfsPath& pathname, const FileInfo& fileInfo, const uintptr_t cbData); +typedef Status (*FileCallback)(const VfsPath& pathname, const FileInfo& fileInfo, const uintptr_t cbData); enum DirFlags { @@ -68,9 +68,9 @@ enum DirFlags * @param pattern that file names must match. '*' and '&' wildcards * are allowed. 0 matches everything. * @param flags @ref DirFlags - * @return LibError + * @return Status **/ -extern LibError ForEachFile(const PIVFS& fs, const VfsPath& path, FileCallback cb, uintptr_t cbData, const wchar_t* pattern = 0, size_t flags = 0); +extern Status ForEachFile(const PIVFS& fs, const VfsPath& path, FileCallback cb, uintptr_t cbData, const wchar_t* pattern = 0, size_t flags = 0); /** diff --git a/source/lib/file/io/io.cpp b/source/lib/file/io/io.cpp index acf79a20da..77119fc227 100644 --- a/source/lib/file/io/io.cpp +++ b/source/lib/file/io/io.cpp @@ -25,7 +25,7 @@ #include "lib/sysdep/rtl.h" -ERROR_ASSOCIATE(ERR::IO, L"Error during IO", EIO); +STATUS_DEFINE(ERR, IO, L"Error during IO", EIO); namespace io { @@ -45,13 +45,14 @@ UniqueRange Allocate(size_t size, size_t alignment) // note that the Windows aio implementation requires buffers, sizes and // offsets to be sector-aligned. -LibError Issue(aiocb& cb, size_t queueDepth) +Status Issue(aiocb& cb, size_t queueDepth) { #if CONFIG2_FILE_ENABLE_AIO if(queueDepth > 1) { const int ret = (cb.aio_lio_opcode == LIO_WRITE)? aio_write(&cb): aio_read(&cb); - RETURN_ERR(LibError_from_posix(ret)); + if(ret != 0) + WARN_RETURN(StatusFromErrno()); } else #else @@ -63,7 +64,7 @@ LibError Issue(aiocb& cb, size_t queueDepth) void* buf = (void*)cb.aio_buf; // cast from volatile void* const ssize_t bytesTransferred = (cb.aio_lio_opcode == LIO_WRITE)? write(cb.aio_fildes, buf, cb.aio_nbytes) : read(cb.aio_fildes, buf, cb.aio_nbytes); if(bytesTransferred < 0) - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); cb.aio_nbytes = (size_t)bytesTransferred; } @@ -72,7 +73,7 @@ LibError Issue(aiocb& cb, size_t queueDepth) } -LibError WaitUntilComplete(aiocb& cb, size_t queueDepth) +Status WaitUntilComplete(aiocb& cb, size_t queueDepth) { #if CONFIG2_FILE_ENABLE_AIO if(queueDepth > 1) @@ -86,7 +87,7 @@ SUSPEND_AGAIN: { if(errno == EINTR) // interrupted by signal goto SUSPEND_AGAIN; - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); } const int err = aio_error(&cb); @@ -95,7 +96,7 @@ SUSPEND_AGAIN: if(bytesTransferred == -1) // transfer failed { errno = err; - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); } cb.aio_nbytes = (size_t)bytesTransferred; } diff --git a/source/lib/file/io/io.h b/source/lib/file/io/io.h index ffd2fcb813..2a7a0c9f8e 100644 --- a/source/lib/file/io/io.h +++ b/source/lib/file/io/io.h @@ -38,7 +38,7 @@ namespace ERR { - const LibError IO = -110301; + const Status IO = -110301; } namespace io { @@ -152,7 +152,7 @@ struct DefaultCompletedHook * allows progress notification and processing data while waiting for * previous I/Os to complete. **/ - LibError operator()(const u8* UNUSED(block), size_t UNUSED(blockSize)) const + Status operator()(const u8* UNUSED(block), size_t UNUSED(blockSize)) const { return INFO::CB_CONTINUE; } @@ -170,7 +170,7 @@ struct DefaultIssueHook * allows generating the data to write while waiting for * previous I/Os to complete. **/ - LibError operator()(aiocb& UNUSED(cb)) const + Status operator()(aiocb& UNUSED(cb)) const { return INFO::CB_CONTINUE; } @@ -215,8 +215,8 @@ private: #pragma pack(pop) -LIB_API LibError Issue(aiocb& cb, size_t queueDepth); -LIB_API LibError WaitUntilComplete(aiocb& cb, size_t queueDepth); +LIB_API Status Issue(aiocb& cb, size_t queueDepth); +LIB_API Status WaitUntilComplete(aiocb& cb, size_t queueDepth); //----------------------------------------------------------------------------- @@ -225,7 +225,7 @@ LIB_API LibError WaitUntilComplete(aiocb& cb, size_t queueDepth); // (hooks must be passed by const reference to allow passing rvalues. // functors with non-const member data can mark them as mutable.) template -static inline LibError Run(const Operation& op, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook(), const IssueHook& issueHook = IssueHook()) +static inline Status Run(const Operation& op, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook(), const IssueHook& issueHook = IssueHook()) { op.Validate(); p.Validate(op); @@ -246,11 +246,11 @@ static inline LibError Run(const Operation& op, const Parameters& p = Parameters RETURN_IF_NOT_CONTINUE(issueHook(cb)); - RETURN_ERR(Issue(cb, p.queueDepth)); + RETURN_STATUS_IF_ERR(Issue(cb, p.queueDepth)); } aiocb& cb = controlBlockRingBuffer[blocksCompleted]; - RETURN_ERR(WaitUntilComplete(cb, p.queueDepth)); + RETURN_STATUS_IF_ERR(WaitUntilComplete(cb, p.queueDepth)); RETURN_IF_NOT_CONTINUE(completedHook((u8*)cb.aio_buf, cb.aio_nbytes)); } @@ -260,12 +260,12 @@ static inline LibError Run(const Operation& op, const Parameters& p = Parameters // (overloads allow omitting parameters without requiring a template argument list) template -static inline LibError Run(const Operation& op, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook()) +static inline Status Run(const Operation& op, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook()) { return Run(op, p, completedHook, DefaultIssueHook()); } -static inline LibError Run(const Operation& op, const Parameters& p = Parameters()) +static inline Status Run(const Operation& op, const Parameters& p = Parameters()) { return Run(op, p, DefaultCompletedHook(), DefaultIssueHook()); } @@ -278,32 +278,32 @@ static inline LibError Run(const Operation& op, const Parameters& p = Parameters // padded to the sector size and needs to be truncated afterwards. // this function takes care of both. template -static inline LibError Store(const OsPath& pathname, const void* data, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook(), const IssueHook& issueHook = IssueHook()) +static inline Status Store(const OsPath& pathname, const void* data, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook(), const IssueHook& issueHook = IssueHook()) { File file; - CHECK_ERR(file.Open(pathname, LIO_WRITE)); + WARN_RETURN_STATUS_IF_ERR(file.Open(pathname, LIO_WRITE)); io::Operation op(file, (void*)data, size); #if OS_WIN && CONFIG2_FILE_ENABLE_AIO (void)waio_Preallocate(op.fd, (off_t)size); #endif - RETURN_ERR(io::Run(op, p, completedHook, issueHook)); + RETURN_STATUS_IF_ERR(io::Run(op, p, completedHook, issueHook)); file.Close(); // (required by wtruncate) - RETURN_ERR(wtruncate(pathname, size)); + RETURN_STATUS_IF_ERR(wtruncate(pathname, size)); return INFO::OK; } template -static inline LibError Store(const OsPath& pathname, const void* data, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook()) +static inline Status Store(const OsPath& pathname, const void* data, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook()) { return Store(pathname, data, size, p, completedHook, DefaultIssueHook()); } -static inline LibError Store(const OsPath& pathname, const void* data, size_t size, const Parameters& p = Parameters()) +static inline Status Store(const OsPath& pathname, const void* data, size_t size, const Parameters& p = Parameters()) { return Store(pathname, data, size, p, DefaultCompletedHook(), DefaultIssueHook()); } @@ -314,21 +314,21 @@ static inline LibError Store(const OsPath& pathname, const void* data, size_t si // convenience function provided for symmetry with Store template -static inline LibError Load(const OsPath& pathname, void* buf, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook(), const IssueHook& issueHook = IssueHook()) +static inline Status Load(const OsPath& pathname, void* buf, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook(), const IssueHook& issueHook = IssueHook()) { File file; - RETURN_ERR(file.Open(pathname, LIO_READ)); + RETURN_STATUS_IF_ERR(file.Open(pathname, LIO_READ)); io::Operation op(file, buf, size); return io::Run(op, p, completedHook, issueHook); } template -static inline LibError Load(const OsPath& pathname, void* buf, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook()) +static inline Status Load(const OsPath& pathname, void* buf, size_t size, const Parameters& p = Parameters(), const CompletedHook& completedHook = CompletedHook()) { return Load(pathname, buf, size, p, completedHook, DefaultIssueHook()); } -static inline LibError Load(const OsPath& pathname, void* buf, size_t size, const Parameters& p = Parameters()) +static inline Status Load(const OsPath& pathname, void* buf, size_t size, const Parameters& p = Parameters()) { return Load(pathname, buf, size, p, DefaultCompletedHook(), DefaultIssueHook()); } diff --git a/source/lib/file/io/write_buffer.cpp b/source/lib/file/io/write_buffer.cpp index c4ccc44e65..e81d0ef16b 100644 --- a/source/lib/file/io/write_buffer.cpp +++ b/source/lib/file/io/write_buffer.cpp @@ -73,7 +73,7 @@ UnalignedWriter::UnalignedWriter(const PFile& file, off_t ofs) if(misalignment) { io::Operation op(*m_file.get(), m_alignedBuf.get(), BLOCK_SIZE, m_alignedOfs); - THROW_ERR(io::Run(op)); + THROW_STATUS_IF_ERR(io::Run(op)); } m_bytesUsed = misalignment; } @@ -85,7 +85,7 @@ UnalignedWriter::~UnalignedWriter() } -LibError UnalignedWriter::Append(const u8* data, size_t size) const +Status UnalignedWriter::Append(const u8* data, size_t size) const { while(size != 0) { @@ -94,7 +94,7 @@ LibError UnalignedWriter::Append(const u8* data, size_t size) const if(m_bytesUsed == 0 && IsAligned(data, maxSectorSize) && alignedSize != 0) { io::Operation op(*m_file.get(), (void*)data, alignedSize, m_alignedOfs); - RETURN_ERR(io::Run(op)); + RETURN_STATUS_IF_ERR(io::Run(op)); m_alignedOfs += (off_t)alignedSize; data += alignedSize; size -= alignedSize; @@ -107,7 +107,7 @@ LibError UnalignedWriter::Append(const u8* data, size_t size) const size -= chunkSize; if(m_bytesUsed == BLOCK_SIZE) - RETURN_ERR(WriteBlock()); + RETURN_STATUS_IF_ERR(WriteBlock()); } return INFO::OK; @@ -124,10 +124,10 @@ void UnalignedWriter::Flush() const } -LibError UnalignedWriter::WriteBlock() const +Status UnalignedWriter::WriteBlock() const { io::Operation op(*m_file.get(), m_alignedBuf.get(), BLOCK_SIZE, m_alignedOfs); - RETURN_ERR(io::Run(op)); + RETURN_STATUS_IF_ERR(io::Run(op)); m_alignedOfs += BLOCK_SIZE; m_bytesUsed = 0; return INFO::OK; diff --git a/source/lib/file/io/write_buffer.h b/source/lib/file/io/write_buffer.h index c73138acde..67b43b3f51 100644 --- a/source/lib/file/io/write_buffer.h +++ b/source/lib/file/io/write_buffer.h @@ -61,7 +61,7 @@ public: /** * add data to the align buffer, writing it out to disk if full. **/ - LibError Append(const u8* data, size_t size) const; + Status Append(const u8* data, size_t size) const; /** * zero-initialize any remaining space in the align buffer and write @@ -70,7 +70,7 @@ public: void Flush() const; private: - LibError WriteBlock() const; + Status WriteBlock() const; PFile m_file; shared_ptr m_alignedBuf; diff --git a/source/lib/file/vfs/vfs.cpp b/source/lib/file/vfs/vfs.cpp index 59d52cb995..c69cbb95da 100644 --- a/source/lib/file/vfs/vfs.cpp +++ b/source/lib/file/vfs/vfs.cpp @@ -35,9 +35,9 @@ #include "lib/file/vfs/vfs_populate.h" #include "lib/file/vfs/file_cache.h" -ERROR_ASSOCIATE(ERR::VFS_DIR_NOT_FOUND, L"VFS directory not found", -1); -ERROR_ASSOCIATE(ERR::VFS_FILE_NOT_FOUND, L"VFS file not found", -1); -ERROR_ASSOCIATE(ERR::VFS_ALREADY_MOUNTED, L"VFS path already mounted", -1); +STATUS_DEFINE(ERR, VFS_DIR_NOT_FOUND, L"VFS directory not found", -1); +STATUS_DEFINE(ERR, VFS_FILE_NOT_FOUND, L"VFS file not found", -1); +STATUS_DEFINE(ERR, VFS_ALREADY_MOUNTED, L"VFS path already mounted", -1); static pthread_mutex_t vfs_mutex = PTHREAD_MUTEX_INITIALIZER; struct ScopedLock @@ -55,7 +55,7 @@ public: { } - virtual LibError Mount(const VfsPath& mountPoint, const OsPath& path, size_t flags /* = 0 */, size_t priority /* = 0 */) + virtual Status Mount(const VfsPath& mountPoint, const OsPath& path, size_t flags /* = 0 */, size_t priority /* = 0 */) { ScopedLock s; if(!fs_util::DirectoryExists(path)) @@ -63,43 +63,43 @@ public: if(flags & VFS_MOUNT_MUST_EXIST) return ERR::VFS_DIR_NOT_FOUND; // NOWARN else - RETURN_ERR(CreateDirectories(path, 0700)); + RETURN_STATUS_IF_ERR(CreateDirectories(path, 0700)); } VfsDirectory* directory; - CHECK_ERR(vfs_Lookup(mountPoint, &m_rootDirectory, directory, 0, VFS_LOOKUP_ADD|VFS_LOOKUP_SKIP_POPULATE)); + WARN_RETURN_STATUS_IF_ERR(vfs_Lookup(mountPoint, &m_rootDirectory, directory, 0, VFS_LOOKUP_ADD|VFS_LOOKUP_SKIP_POPULATE)); PRealDirectory realDirectory(new RealDirectory(path, priority, flags)); - RETURN_ERR(vfs_Attach(directory, realDirectory)); + RETURN_STATUS_IF_ERR(vfs_Attach(directory, realDirectory)); return INFO::OK; } - virtual LibError GetFileInfo(const VfsPath& pathname, FileInfo* pfileInfo) const + virtual Status GetFileInfo(const VfsPath& pathname, FileInfo* pfileInfo) const { ScopedLock s; VfsDirectory* directory; VfsFile* file; - LibError ret = vfs_Lookup(pathname, &m_rootDirectory, directory, &file); + Status ret = vfs_Lookup(pathname, &m_rootDirectory, directory, &file); if(!pfileInfo) // just indicate if the file exists without raising warnings. return ret; - CHECK_ERR(ret); + WARN_RETURN_STATUS_IF_ERR(ret); *pfileInfo = FileInfo(file->Name(), file->Size(), file->MTime()); return INFO::OK; } - virtual LibError GetFilePriority(const VfsPath& pathname, size_t* ppriority) const + virtual Status GetFilePriority(const VfsPath& pathname, size_t* ppriority) const { ScopedLock s; VfsDirectory* directory; VfsFile* file; - RETURN_ERR(vfs_Lookup(pathname, &m_rootDirectory, directory, &file)); + RETURN_STATUS_IF_ERR(vfs_Lookup(pathname, &m_rootDirectory, directory, &file)); *ppriority = file->Priority(); return INFO::OK; } - virtual LibError GetDirectoryEntries(const VfsPath& path, FileInfos* fileInfos, DirectoryNames* subdirectoryNames) const + virtual Status GetDirectoryEntries(const VfsPath& path, FileInfos* fileInfos, DirectoryNames* subdirectoryNames) const { ScopedLock s; VfsDirectory* directory; - CHECK_ERR(vfs_Lookup(path, &m_rootDirectory, directory, 0)); + WARN_RETURN_STATUS_IF_ERR(vfs_Lookup(path, &m_rootDirectory, directory, 0)); if(fileInfos) { @@ -125,15 +125,15 @@ public: return INFO::OK; } - virtual LibError CreateFile(const VfsPath& pathname, const shared_ptr& fileContents, size_t size) + virtual Status CreateFile(const VfsPath& pathname, const shared_ptr& fileContents, size_t size) { ScopedLock s; VfsDirectory* directory; - CHECK_ERR(vfs_Lookup(pathname, &m_rootDirectory, directory, 0, VFS_LOOKUP_ADD|VFS_LOOKUP_CREATE)); + WARN_RETURN_STATUS_IF_ERR(vfs_Lookup(pathname, &m_rootDirectory, directory, 0, VFS_LOOKUP_ADD|VFS_LOOKUP_CREATE)); const PRealDirectory& realDirectory = directory->AssociatedDirectory(); const OsPath name = pathname.Filename(); - RETURN_ERR(realDirectory->Store(name, fileContents, size)); + RETURN_STATUS_IF_ERR(realDirectory->Store(name, fileContents, size)); // wipe out any cached blocks. this is necessary to cover the (rare) case // of file cache contents predating the file write. @@ -146,7 +146,7 @@ public: return INFO::OK; } - virtual LibError LoadFile(const VfsPath& pathname, shared_ptr& fileContents, size_t& size) + virtual Status LoadFile(const VfsPath& pathname, shared_ptr& fileContents, size_t& size) { ScopedLock s; const bool isCacheHit = m_fileCache.Retrieve(pathname, fileContents, size); @@ -156,7 +156,7 @@ public: // per 2010-05-01 meeting, this shouldn't raise 'scary error // dialogs', which might fail to display the culprit pathname // instead, callers should log the error, including pathname. - RETURN_ERR(vfs_Lookup(pathname, &m_rootDirectory, directory, &file)); + RETURN_STATUS_IF_ERR(vfs_Lookup(pathname, &m_rootDirectory, directory, &file)); size = file->Size(); // safely handle zero-length files @@ -164,13 +164,13 @@ public: fileContents = DummySharedPtr((u8*)0); else if(size > m_cacheSize) { - RETURN_ERR(AllocateAligned(fileContents, size, maxSectorSize)); - RETURN_ERR(file->Loader()->Load(file->Name(), fileContents, file->Size())); + RETURN_STATUS_IF_ERR(AllocateAligned(fileContents, size, maxSectorSize)); + RETURN_STATUS_IF_ERR(file->Loader()->Load(file->Name(), fileContents, file->Size())); } else { fileContents = m_fileCache.Reserve(size); - RETURN_ERR(file->Loader()->Load(file->Name(), fileContents, file->Size())); + RETURN_STATUS_IF_ERR(file->Loader()->Load(file->Name(), fileContents, file->Size())); m_fileCache.Add(pathname, fileContents, size); } } @@ -191,32 +191,32 @@ public: return textRepresentation; } - virtual LibError GetRealPath(const VfsPath& pathname, OsPath& realPathname) + virtual Status GetRealPath(const VfsPath& pathname, OsPath& realPathname) { ScopedLock s; VfsDirectory* directory; VfsFile* file; - CHECK_ERR(vfs_Lookup(pathname, &m_rootDirectory, directory, &file)); + WARN_RETURN_STATUS_IF_ERR(vfs_Lookup(pathname, &m_rootDirectory, directory, &file)); realPathname = file->Loader()->Path() / pathname.Filename(); return INFO::OK; } - virtual LibError GetVirtualPath(const OsPath& realPathname, VfsPath& pathname) + virtual Status GetVirtualPath(const OsPath& realPathname, VfsPath& pathname) { ScopedLock s; const OsPath realPath = realPathname.Parent()/""; VfsPath path; - RETURN_ERR(FindRealPathR(realPath, m_rootDirectory, L"", path)); + RETURN_STATUS_IF_ERR(FindRealPathR(realPath, m_rootDirectory, L"", path)); pathname = path / realPathname.Filename(); return INFO::OK; } - virtual LibError Invalidate(const VfsPath& pathname) + virtual Status Invalidate(const VfsPath& pathname) { ScopedLock s; m_fileCache.Remove(pathname); VfsDirectory* directory; - RETURN_ERR(vfs_Lookup(pathname, &m_rootDirectory, directory, 0)); + RETURN_STATUS_IF_ERR(vfs_Lookup(pathname, &m_rootDirectory, directory, 0)); const OsPath name = pathname.Filename(); directory->Invalidate(name); @@ -230,7 +230,7 @@ public: } private: - LibError FindRealPathR(const OsPath& realPath, const VfsDirectory& directory, const VfsPath& curPath, VfsPath& path) + Status FindRealPathR(const OsPath& realPath, const VfsDirectory& directory, const VfsPath& curPath, VfsPath& path) { PRealDirectory realDirectory = directory.AssociatedDirectory(); if(realDirectory && realDirectory->Path() == realPath) @@ -244,7 +244,7 @@ private: { const OsPath& subdirectoryName = it->first; const VfsDirectory& subdirectory = it->second; - LibError ret = FindRealPathR(realPath, subdirectory, curPath / subdirectoryName/"", path); + Status ret = FindRealPathR(realPath, subdirectory, curPath / subdirectoryName/"", path); if(ret == INFO::OK) return INFO::OK; } diff --git a/source/lib/file/vfs/vfs.h b/source/lib/file/vfs/vfs.h index a8ee7216df..89573df948 100644 --- a/source/lib/file/vfs/vfs.h +++ b/source/lib/file/vfs/vfs.h @@ -33,9 +33,9 @@ namespace ERR { - const LibError VFS_DIR_NOT_FOUND = -110100; - const LibError VFS_FILE_NOT_FOUND = -110101; - const LibError VFS_ALREADY_MOUNTED = -110102; + const Status VFS_DIR_NOT_FOUND = -110100; + const Status VFS_FILE_NOT_FOUND = -110101; + const Status VFS_ALREADY_MOUNTED = -110102; } // (recursive mounting and mounting archives are no longer optional since they don't hurt) @@ -73,7 +73,7 @@ struct IVFS * @param path real directory path * @param flags * @param priority - * @return LibError. + * @return Status. * * if files are encountered that already exist in the VFS (sub)directories, * the most recent / highest priority/precedence version is preferred. @@ -81,7 +81,7 @@ struct IVFS * if files with archive extensions are seen, their contents are added * as well. **/ - virtual LibError Mount(const VfsPath& mountPoint, const OsPath& path, size_t flags = 0, size_t priority = 0) = 0; + virtual Status Mount(const VfsPath& mountPoint, const OsPath& path, size_t flags = 0, size_t priority = 0) = 0; /** * Retrieve information about a file (similar to POSIX stat). @@ -90,9 +90,9 @@ struct IVFS * @param pfileInfo receives information about the file. Passing NULL * suppresses warnings if the file doesn't exist. * - * @return LibError. + * @return Status. **/ - virtual LibError GetFileInfo(const VfsPath& pathname, FileInfo* pfileInfo) const = 0; + virtual Status GetFileInfo(const VfsPath& pathname, FileInfo* pfileInfo) const = 0; /** * Retrieve mount priority for a file. @@ -100,14 +100,14 @@ struct IVFS * @param pathname * @param ppriority receives priority value, if the file can be found. * - * @return LibError. + * @return Status. **/ - virtual LibError GetFilePriority(const VfsPath& pathname, size_t* ppriority) const = 0; + virtual Status GetFilePriority(const VfsPath& pathname, size_t* ppriority) const = 0; /** * Retrieve lists of all files and subdirectories in a directory. * - * @return LibError. + * @return Status. * * Rationale: * - this interface avoids having to lock the directory while an @@ -115,19 +115,19 @@ struct IVFS * - we cannot efficiently provide routines for returning files and * subdirectories separately due to the underlying POSIX interface. **/ - virtual LibError GetDirectoryEntries(const VfsPath& path, FileInfos* fileInfos, DirectoryNames* subdirectoryNames) const = 0; + virtual Status GetDirectoryEntries(const VfsPath& path, FileInfos* fileInfos, DirectoryNames* subdirectoryNames) const = 0; /** * Create a file with the given contents. * @param pathname * @param fileContents * @param size [bytes] of the contents, will match that of the file. - * @return LibError. + * @return Status. * * rationale: disallowing partial writes simplifies file cache coherency * (we need only invalidate cached data when closing a newly written file). **/ - virtual LibError CreateFile(const VfsPath& pathname, const shared_ptr& fileContents, size_t size) = 0; + virtual Status CreateFile(const VfsPath& pathname, const shared_ptr& fileContents, size_t size) = 0; /** * Read an entire file into memory. @@ -139,9 +139,9 @@ struct IVFS * provision for Copy-on-Write, which means that such buffers * must not be modified (this is enforced via mprotect). * @param size receives the size [bytes] of the file contents. - * @return LibError. + * @return Status. **/ - virtual LibError LoadFile(const VfsPath& pathname, shared_ptr& fileContents, size_t& size) = 0; + virtual Status LoadFile(const VfsPath& pathname, shared_ptr& fileContents, size_t& size) = 0; /** * @return a string representation of all files and directories. @@ -153,7 +153,7 @@ struct IVFS * * this is useful for passing paths to external libraries. **/ - virtual LibError GetRealPath(const VfsPath& pathname, OsPath& realPathname) = 0; + virtual Status GetRealPath(const VfsPath& pathname, OsPath& realPathname) = 0; /** * retrieve the VFS pathname that corresponds to a real file. @@ -164,13 +164,13 @@ struct IVFS * number of directories; this could be accelerated by only checking * directories below a mount point with a matching real path. **/ - virtual LibError GetVirtualPath(const OsPath& realPathname, VfsPath& pathname) = 0; + virtual Status GetVirtualPath(const OsPath& realPathname, VfsPath& pathname) = 0; /** * indicate that a file has changed; remove its data from the cache and * arrange for its directory to be updated. **/ - virtual LibError Invalidate(const VfsPath& pathname) = 0; + virtual Status Invalidate(const VfsPath& pathname) = 0; /** * empty the contents of the filesystem. diff --git a/source/lib/file/vfs/vfs_lookup.cpp b/source/lib/file/vfs/vfs_lookup.cpp index 8203d6eaad..0bdf7dd7d9 100644 --- a/source/lib/file/vfs/vfs_lookup.cpp +++ b/source/lib/file/vfs/vfs_lookup.cpp @@ -37,7 +37,7 @@ #include "lib/timer.h" -static LibError CreateDirectory(const OsPath& path) +static Status CreateDirectory(const OsPath& path) { { const mode_t mode = S_IRWXU; // 0700 as prescribed by XDG basedir @@ -64,11 +64,11 @@ static LibError CreateDirectory(const OsPath& path) // unexpected failure debug_printf(L"wmkdir failed with errno=%d\n", errno); ENSURE(0); - return LibError_from_errno(); + WARN_RETURN(StatusFromErrno()); } -LibError vfs_Lookup(const VfsPath& pathname, VfsDirectory* startDirectory, VfsDirectory*& directory, VfsFile** pfile, size_t flags) +Status vfs_Lookup(const VfsPath& pathname, VfsDirectory* startDirectory, VfsDirectory*& directory, VfsFile** pfile, size_t flags) { // extract and validate flags (ensure no unknown bits are set) const bool addMissingDirectories = (flags & VFS_LOOKUP_ADD) != 0; @@ -81,7 +81,7 @@ LibError vfs_Lookup(const VfsPath& pathname, VfsDirectory* startDirectory, VfsDi *pfile = 0; if(!skipPopulate) - RETURN_ERR(vfs_Populate(directory)); + RETURN_STATUS_IF_ERR(vfs_Populate(directory)); // early-out for pathname == "" when mounting into VFS root if(pathname.empty()) // (prevent iterator error in loop end condition) @@ -118,14 +118,14 @@ LibError vfs_Lookup(const VfsPath& pathname, VfsDirectory* startDirectory, VfsDi currentPath = directory->AssociatedDirectory()->Path(); currentPath = currentPath / subdirectoryName; - RETURN_ERR(CreateDirectory(currentPath)); + RETURN_STATUS_IF_ERR(CreateDirectory(currentPath)); PRealDirectory realDirectory(new RealDirectory(currentPath, 0, 0)); - RETURN_ERR(vfs_Attach(subdirectory, realDirectory)); + RETURN_STATUS_IF_ERR(vfs_Attach(subdirectory, realDirectory)); } if(!skipPopulate) - RETURN_ERR(vfs_Populate(subdirectory)); + RETURN_STATUS_IF_ERR(vfs_Populate(subdirectory)); directory = subdirectory; } diff --git a/source/lib/file/vfs/vfs_lookup.h b/source/lib/file/vfs/vfs_lookup.h index fdad1128cb..3a369a378c 100644 --- a/source/lib/file/vfs/vfs_lookup.h +++ b/source/lib/file/vfs/vfs_lookup.h @@ -61,10 +61,10 @@ enum VfsLookupFlags * @param pfile File is set to 0 if there is no name component, otherwise the * corresponding file. * @param flags @see VfsLookupFlags. - * @return LibError (INFO::OK if all components in pathname exist). + * @return Status (INFO::OK if all components in pathname exist). * * to allow noiseless file-existence queries, this does not raise warnings. **/ -extern LibError vfs_Lookup(const VfsPath& pathname, VfsDirectory* startDirectory, VfsDirectory*& directory, VfsFile** pfile, size_t flags = 0); +extern Status vfs_Lookup(const VfsPath& pathname, VfsDirectory* startDirectory, VfsDirectory*& directory, VfsFile** pfile, size_t flags = 0); #endif // #ifndef INCLUDED_VFS_LOOKUP diff --git a/source/lib/file/vfs/vfs_populate.cpp b/source/lib/file/vfs/vfs_populate.cpp index 910f1f4afe..7e09c58d93 100644 --- a/source/lib/file/vfs/vfs_populate.cpp +++ b/source/lib/file/vfs/vfs_populate.cpp @@ -50,7 +50,7 @@ public: { } - LibError AddEntries() const + Status AddEntries() const { #if ENABLE_ARCHIVE_STATS s_looseFiles.reserve(10000); @@ -58,9 +58,9 @@ public: FileInfos files; files.reserve(500); DirectoryNames subdirectoryNames; subdirectoryNames.reserve(50); - RETURN_ERR(GetDirectoryEntries(m_realDirectory->Path(), &files, &subdirectoryNames)); + RETURN_STATUS_IF_ERR(GetDirectoryEntries(m_realDirectory->Path(), &files, &subdirectoryNames)); - RETURN_ERR(AddFiles(files)); + RETURN_STATUS_IF_ERR(AddFiles(files)); AddSubdirectories(subdirectoryNames); return INFO::OK; @@ -93,7 +93,7 @@ private: // don't always place directory entries before their files) const size_t flags = VFS_LOOKUP_ADD|VFS_LOOKUP_SKIP_POPULATE; VfsDirectory* directory; - WARN_ERR(vfs_Lookup(pathname, this_->m_directory, directory, 0, flags)); + WARN_IF_ERR(vfs_Lookup(pathname, this_->m_directory, directory, 0, flags)); const VfsFile file(fileInfo.Name(), (size_t)fileInfo.Size(), fileInfo.MTime(), this_->m_realDirectory->Priority(), archiveFile); directory->AddFile(file); #if ENABLE_ARCHIVE_STATS @@ -101,7 +101,7 @@ private: #endif } - LibError AddFiles(const FileInfos& files) const + Status AddFiles(const FileInfos& files) const { const OsPath path(m_realDirectory->Path()); @@ -111,7 +111,7 @@ private: if(pathname.Extension() == L".zip") { PIArchiveReader archiveReader = CreateArchiveReader_Zip(pathname); - RETURN_ERR(archiveReader->ReadEntries(AddArchiveFile, (uintptr_t)this)); + RETURN_STATUS_IF_ERR(archiveReader->ReadEntries(AddArchiveFile, (uintptr_t)this)); } else // regular (non-archive) file AddFile(files[i]); @@ -140,7 +140,7 @@ private: }; -LibError vfs_Populate(VfsDirectory* directory) +Status vfs_Populate(VfsDirectory* directory) { if(!directory->ShouldPopulate()) return INFO::OK; @@ -151,15 +151,15 @@ LibError vfs_Populate(VfsDirectory* directory) realDirectory->Watch(); PopulateHelper helper(directory, realDirectory); - RETURN_ERR(helper.AddEntries()); + RETURN_STATUS_IF_ERR(helper.AddEntries()); return INFO::OK; } -LibError vfs_Attach(VfsDirectory* directory, const PRealDirectory& realDirectory) +Status vfs_Attach(VfsDirectory* directory, const PRealDirectory& realDirectory) { - RETURN_ERR(vfs_Populate(directory)); + RETURN_STATUS_IF_ERR(vfs_Populate(directory)); directory->SetAssociatedDirectory(realDirectory); return INFO::OK; } diff --git a/source/lib/file/vfs/vfs_populate.h b/source/lib/file/vfs/vfs_populate.h index 8a14fd5482..1211019c44 100644 --- a/source/lib/file/vfs/vfs_populate.h +++ b/source/lib/file/vfs/vfs_populate.h @@ -42,7 +42,7 @@ class VfsDirectory; * note: the most recently attached real directory will be used when * creating files in the VFS directory. **/ -extern LibError vfs_Attach(VfsDirectory* directory, const PRealDirectory& realDirectory); +extern Status vfs_Attach(VfsDirectory* directory, const PRealDirectory& realDirectory); /** * populate the directory from the attached real directory. @@ -52,6 +52,6 @@ extern LibError vfs_Attach(VfsDirectory* directory, const PRealDirectory& realDi * * has no effect if no directory has been attached since the last populate. **/ -extern LibError vfs_Populate(VfsDirectory* directory); +extern Status vfs_Populate(VfsDirectory* directory); #endif // #ifndef INCLUDED_VFS_POPULATE diff --git a/source/lib/input.cpp b/source/lib/input.cpp index 4c018ef65b..e652682845 100644 --- a/source/lib/input.cpp +++ b/source/lib/input.cpp @@ -41,7 +41,7 @@ void in_add_handler(InHandler handler) ENSURE(handler); if(handler_stack_top >= MAX_HANDLERS) - WARN_ERR_RETURN(ERR::LIMIT); + WARN_IF_ERR(ERR::LIMIT); handler_stack[handler_stack_top++] = handler; } diff --git a/source/lib/lib_api.h b/source/lib/lib_api.h index ceb74f1444..c54ace7c94 100644 --- a/source/lib/lib_api.h +++ b/source/lib/lib_api.h @@ -20,6 +20,9 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +#ifndef INCLUDED_LIB_API +#define INCLUDED_LIB_API + #include "lib/sysdep/compiler.h" // note: EXTERN_C cannot be used because shared_ptr is often returned @@ -49,3 +52,5 @@ # error "Don't know how to define LIB_API for this compiler" # endif #endif + +#endif // #ifndef INCLUDED_LIB_API diff --git a/source/lib/lib_errors.cpp b/source/lib/lib_errors.cpp deleted file mode 100644 index c98949d349..0000000000 --- a/source/lib/lib_errors.cpp +++ /dev/null @@ -1,197 +0,0 @@ -/* Copyright (c) 2010 Wildfire Games - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/* - * error handling system: defines error codes, associates them with - * descriptive text, simplifies error notification. - */ - -// note: this is called lib_errors.cpp because we have another -// errors.cpp; the MS linker isn't smart enough to deal with -// object files of the same name but in different paths. - -#include "precompiled.h" -#include "lib/lib_errors.h" - -#include -#include // abs -#include -#include - -#include "lib/posix/posix_errno.h" -#include "lib/sysdep/sysdep.h" - -// linked list (most recent first) -// note: no memory is allocated, all nodes are static instances. -// -// rationale: don't use a std::map. we don't care about lookup speed, -// dynamic allocation would be ugly, and returning a local static object -// from a function doesn't work, either (the compiler generates calls to -// atexit, which leads to disaster since we're sometimes called by -// winit functions before the CRT has initialized) -static LibErrorAssociation* associations; - -int error_AddAssociation(LibErrorAssociation* lea) -{ - // insert at front of list - lea->next = associations; - associations = lea; - - return 0; // stored in dummy variable -} - -static const LibErrorAssociation* AssociationFromLibError(LibError err) -{ - for(const LibErrorAssociation* lea = associations; lea; lea = lea->next) - { - if(lea->err == err) - return lea; - } - - return 0; -} - -static const LibErrorAssociation* AssociationFromErrno(int errno_equivalent) -{ - for(const LibErrorAssociation* lea = associations; lea; lea = lea->next) - { - if(lea->errno_equivalent == errno_equivalent) - return lea; - } - - return 0; -} - - -wchar_t* error_description_r(LibError err, wchar_t* buf, size_t max_chars) -{ - // lib error - const LibErrorAssociation* lea = AssociationFromLibError(err); - if(lea) - { - wcscpy_s(buf, max_chars, lea->description); - return buf; - } - - // unknown - swprintf_s(buf, max_chars, L"Unknown error (%d, 0x%X)", (int)err, (unsigned int)err); - return buf; -} - - -LibError LibError_from_errno(bool warn_if_failed) -{ - LibError ret = ERR::FAIL; - - const LibErrorAssociation* lea = AssociationFromErrno(errno); - if(lea) - ret = lea->err; - - if(warn_if_failed) - DEBUG_WARN_ERR(ret); - return ret; -} - - -LibError LibError_from_posix(int ret, bool warn_if_failed) -{ - ENSURE(ret == 0 || ret == -1); - if(ret == 0) - return INFO::OK; - return LibError_from_errno(warn_if_failed); -} - - -// return the errno.h equivalent of . -// does not assign to errno (this simplifies code by allowing direct return) -static int return_errno_from_LibError(LibError err) -{ - const LibErrorAssociation* lea = AssociationFromLibError(err); - if(lea && lea->errno_equivalent != -1) - return lea->errno_equivalent; - - // somewhat of a quandary: the set of errnos in wposix.h doesn't - // have an "unknown error". we pick EPERM because we don't expect - // that to come up often otherwise. - return EPERM; -} - -void LibError_set_errno(LibError err) -{ - errno = return_errno_from_LibError(err); -} - - -//----------------------------------------------------------------------------- - -// INFO::OK doesn't really need a string because calling error_description_r(0) should never happen, but go the safe route. -ERROR_ASSOCIATE(INFO::OK, L"(but return value was 0 which indicates success)", -1); -ERROR_ASSOCIATE(ERR::FAIL, L"Function failed (no details available)", -1); - -ERROR_ASSOCIATE(INFO::CB_CONTINUE, L"Continue (not an error)", -1); -ERROR_ASSOCIATE(INFO::SKIPPED, L"Skipped (not an error)", -1); -ERROR_ASSOCIATE(INFO::CANNOT_HANDLE, L"Cannot handle (not an error)", -1); -ERROR_ASSOCIATE(INFO::ALL_COMPLETE, L"All complete (not an error)", -1); -ERROR_ASSOCIATE(INFO::ALREADY_EXISTS, L"Already exists (not an error)", -1); - -ERROR_ASSOCIATE(ERR::LOGIC, L"Logic error in code", -1); -ERROR_ASSOCIATE(ERR::TIMED_OUT, L"Timed out", -1); -ERROR_ASSOCIATE(ERR::REENTERED, L"Single-call function was reentered", -1); -ERROR_ASSOCIATE(ERR::CORRUPTED, L"File/memory data is corrupted", -1); - -ERROR_ASSOCIATE(ERR::INVALID_PARAM, L"Invalid function argument", EINVAL); -ERROR_ASSOCIATE(ERR::INVALID_HANDLE, L"Invalid Handle (argument)", -1); -ERROR_ASSOCIATE(ERR::BUF_SIZE, L"Buffer argument too small", -1); -ERROR_ASSOCIATE(ERR::AGAIN, L"Try again later", -1); -ERROR_ASSOCIATE(ERR::LIMIT, L"Fixed limit exceeded", -1); -ERROR_ASSOCIATE(ERR::NO_SYS, L"OS doesn't provide a required API", -1); -ERROR_ASSOCIATE(ERR::NOT_IMPLEMENTED, L"Feature currently not implemented", ENOSYS); -ERROR_ASSOCIATE(ERR::NOT_SUPPORTED, L"Feature isn't and won't be supported", -1); -ERROR_ASSOCIATE(ERR::NO_MEM, L"Not enough memory", ENOMEM); - -ERROR_ASSOCIATE(ERR::_1, L"Case 1", -1); -ERROR_ASSOCIATE(ERR::_2, L"Case 2", -1); -ERROR_ASSOCIATE(ERR::_3, L"Case 3", -1); -ERROR_ASSOCIATE(ERR::_4, L"Case 4", -1); -ERROR_ASSOCIATE(ERR::_5, L"Case 5", -1); -ERROR_ASSOCIATE(ERR::_6, L"Case 6", -1); -ERROR_ASSOCIATE(ERR::_7, L"Case 7", -1); -ERROR_ASSOCIATE(ERR::_8, L"Case 8", -1); -ERROR_ASSOCIATE(ERR::_9, L"Case 9", -1); -ERROR_ASSOCIATE(ERR::_11, L"Case 11", -1); -ERROR_ASSOCIATE(ERR::_12, L"Case 12", -1); -ERROR_ASSOCIATE(ERR::_13, L"Case 13", -1); -ERROR_ASSOCIATE(ERR::_14, L"Case 14", -1); -ERROR_ASSOCIATE(ERR::_15, L"Case 15", -1); -ERROR_ASSOCIATE(ERR::_16, L"Case 16", -1); -ERROR_ASSOCIATE(ERR::_17, L"Case 17", -1); -ERROR_ASSOCIATE(ERR::_18, L"Case 18", -1); -ERROR_ASSOCIATE(ERR::_19, L"Case 19", -1); -ERROR_ASSOCIATE(ERR::_21, L"Case 21", -1); -ERROR_ASSOCIATE(ERR::_22, L"Case 22", -1); -ERROR_ASSOCIATE(ERR::_23, L"Case 23", -1); -ERROR_ASSOCIATE(ERR::_24, L"Case 24", -1); -ERROR_ASSOCIATE(ERR::_25, L"Case 25", -1); -ERROR_ASSOCIATE(ERR::_26, L"Case 26", -1); -ERROR_ASSOCIATE(ERR::_27, L"Case 27", -1); -ERROR_ASSOCIATE(ERR::_28, L"Case 28", -1); -ERROR_ASSOCIATE(ERR::_29, L"Case 29", -1); diff --git a/source/lib/lib_errors.h b/source/lib/lib_errors.h deleted file mode 100644 index 0a6cef4a37..0000000000 --- a/source/lib/lib_errors.h +++ /dev/null @@ -1,496 +0,0 @@ -/* Copyright (c) 2010 Wildfire Games - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/* - * error handling system: defines error codes, associates them with - * descriptive text, simplifies error notification. - */ - -/** - -Error handling system - - -Introduction ------------- - -This module defines error codes, translates them to/from other systems -(e.g. errno), provides several macros that simplify returning errors / -checking if a function failed, and associates codes with descriptive text. - - -Why Error Codes? ----------------- - -To convey information about what failed, the alternatives are unique -integral codes and direct pointers to descriptive text. Both occupy the -same amount of space, but codes are easier to internationalize. - - -Method of Propagating Errors ----------------------------- - -When a low-level function has failed, this must be conveyed to the -higher-level application logic across several functions on the call stack. -There are two alternatives: -1) check at each call site whether a function failed; - if so, return to the caller. -2) throw an exception. - -We will discuss the advantages and disadvantages of exceptions, -which mirror those of call site checking. -- performance: they shouldn't be used in time-critical code. -- predictability: exceptions can come up almost anywhere, - so it is hard to say what execution path will be taken. -- interoperability: not compatible with other languages. -+ readability: cleans up code by separating application logic and - error handling. however, this is also a disadvantage because it - may be difficult to see at a glance if a piece of code does - error checking at all. -+ visibility: errors are more likely to be seen than relying on - callers to check return codes; less reliant on discipline. - -Both have their place. Our recommendation is to throw error code -exceptions when checking call sites and propagating errors becomes tedious. -However, inter-module boundaries should always return error codes for -interoperability with other languages. - - -Simplifying Call-Site Checking ------------------------------- - -As mentioned above, this approach requires discipline. We provide -macros to simplify this task: function calls can be wrapped in an -"enforcer" that checks whether they succeeded and can take action -(e.g. returning to caller or warning user) as appropriate. - -Consider the following example: - LibError ret = doWork(); - if(ret != INFO::OK) { warnUser(ret); return ret; } -This can be replaced by: - CHECK_ERR(doWork()); - -This provides a visible sign that the code handles errors, -automatically propagates errors back to the caller, and most importantly, -allows warning the user whenever an error occurs. -Thus, no errors can be swept under the carpet by failing to -check return value or catch(...) all exceptions. - - -When to warn the user? ----------------------- - -When a function fails, there are 2 places we can raise a warning: -as soon as the error condition is known, or in the higher-level caller. -The former is the WARN_RETURN(ERR::FAIL) approach, while the latter -corresponds to the example above. - -We prefer the former because it is easier to ensure that all -possible return paths have been covered: search for all "return ERR::*" -that are not followed by a "// NOWARN" comment. Also, the latter approach -raises the question of where exactly to issue the warning. -Clearly API-level routines must raise the warning, but sometimes they will -want to call each other. Multiple warnings along the call stack ensuing -from the same root cause are not nice. - -Note the special case of "validator" functions that e.g. verify the -state of an object: we now discuss pros/cons of just returning errors -without warning, and having their callers take care of that. -+ they typically have many return paths (-> increased code size) -- this is balanced by validators that have many call sites. -- we want all return statements wrapped for consistency and - easily checking if any were forgotten -- adding // NOWARN to each validator return statement would be tedious. -- there is no advantage to checking at the call site; call stack indicates - which caller of the validator failed anyway. -Validator functions should therefore also use WARN_RETURN. - - -Numbering Scheme ----------------- - -Each module header defines its own error codes to avoid a full rebuild -whenever a new code is added. - -Error codes start at -100000 (warnings are positive, but reserves a -negative value; absolute values are unique). This avoids collisions -with all known error code schemes. - -Each header gets 100 possible values; the tens value may be -used to denote groups within that header. - -The subsystem is denoted by the ten-thousands digit: -0 lib -1 file -2 res (resource management) -3 sysdep (system-dependent) -4 win (Windows-specific) - -To summarize: +/-1SHHCC (S=subsystem, HH=header, CC=code number) - -10 lib - 00CC lib_errors - 03CC path - 04CC debug - 05CC debug_stl - 06CC secure_crt - 07CC wchar - -11 file - 01CC vfs - 03CC file - 04CC archive - -12 res - 01CC tex - 02CC ogl_shader - -13 sysdep - 00CC cpu - 01CC os_cpu - -14 win - 00CC whrt - -Notes: -- file is called lib_errors.h because 0ad has another errors.cpp and - the MS linker isn't smart enough to deal with object files - of the same name but in different paths. -**/ - -#ifndef INCLUDED_LIB_ERRORS -#define INCLUDED_LIB_ERRORS - -#include "lib/code_annotation.h" -#include "lib/code_generation.h" - -// note: this loses compiler type safety (being able to prevent -// return 1 when a LibError is the return value), but allows splitting -// up the error namespace into separate headers. -// Lint's 'strong type' checking can be used to find errors. -typedef long LibError; - -// opaque - do not access its fields! -// note: must be defined here because clients instantiate them; -// fields cannot be made private due to POD requirement. -struct LibErrorAssociation -{ - LibError err; - - // must remain valid until end of program. - const wchar_t* description; - - // POSIX errno, or -1 - int errno_equivalent; - - LibErrorAssociation* next; -}; - -/** - * associate a LibError with a description and errno equivalent. - * @return dummy integer to allow calling via static initializer. - **/ -extern int error_AddAssociation(LibErrorAssociation*); - -// associate a LibError with a description and errno equivalent. -// Invoke this at file or function scope. -#define ERROR_ASSOCIATE(err, description, errno_equivalent)\ - static LibErrorAssociation UID__ = { err, description, errno_equivalent, NULL };\ - static int UID2__ = error_AddAssociation(&UID__) - - -/** - * generate textual description of an error code. - * - * @param err LibError to be translated. if despite type checking we - * get an invalid enum value, the string will be something like - * "Unknown error (65536, 0x10000)". - * @param buf destination buffer - * @param max_chars size of buffer [characters] - * @return buf (allows using this function in expressions) - **/ -LIB_API wchar_t* error_description_r(LibError err, wchar_t* buf, size_t max_chars); - -//----------------------------------------------------------------------------- - -// conversion to/from other error code definitions. -// note: other conversion routines (e.g. to/from Win32) are implemented in -// the corresponding modules to keep this header portable. - -/** - * translate errno to LibError. - * - * should only be called directly after a POSIX function indicates failure; - * errno may otherwise still be set from another error cause. - * - * @param warn_if_failed if set, raise a warning when returning an error - * (i.e. ERR::*, but not INFO::OK). this avoids having to wrap all - * call sites in WARN_ERR etc. - * @return LibError equivalent of errno, or ERR::FAIL if there's no equal. - **/ -extern LibError LibError_from_errno(bool warn_if_failed = true); - -/** - * translate a POSIX function's return/error indication to LibError. - * - * you should set errno to 0 before calling the POSIX function to - * make sure we do not return any stale errors. typical usage: - * errno = 0; - * int ret = posix_func(..); - * return LibError_from_posix(ret); - * - * @param ret return value of a POSIX function: 0 indicates success, - * -1 is error. - * @param warn_if_failed if set, raise a warning when returning an error - * (i.e. ERR::*, but not INFO::OK). this avoids having to wrap all - * call sites in WARN_ERR etc. - * @return INFO::OK if the POSIX function succeeded, else the LibError - * equivalent of errno, or ERR::FAIL if there's no equal. - **/ -extern LibError LibError_from_posix(int ret, bool warn_if_failed = true); - -/** - * set errno to the equivalent of a LibError. - * - * used in wposix - underlying functions return LibError but must be - * translated to errno at e.g. the mmap interface level. higher-level code - * that calls mmap will in turn convert back to LibError. - * - * @param err error code to set - **/ -extern void LibError_set_errno(LibError err); - - -//----------------------------------------------------------------------------- - -// be careful here. the given expression (e.g. variable or -// function return value) may be a Handle (=i64), so it needs to be -// stored and compared as such. (very large but legitimate Handle values -// casted to int can end up negative) -// all functions using this return LibError (instead of i64) for -// efficiency and simplicity. if the input was negative, it is an -// error code and is therefore known to fit; we still mask with -// UINT_MAX to avoid VC cast-to-smaller-type warnings. - -// if expression evaluates to a negative error code, warn user and -// return the number. -#define CHECK_ERR(expression)\ -STMT(\ - i64 err64__ = (i64)(expression);\ - if(err64__ < 0)\ - {\ - LibError err__ = (LibError)(err64__ & ULONG_MAX);\ - DEBUG_WARN_ERR(err__);\ - return (LibError)(err__ & ULONG_MAX);\ - }\ -) - -// just pass on errors without any kind of annoying warning -// (useful for functions that can legitimately fail). -#define RETURN_ERR(expression)\ -STMT(\ - i64 err64__ = (i64)(expression);\ - if(err64__ < 0)\ - {\ - LibError err__ = (LibError)(err64__ & ULONG_MAX);\ - return err__;\ - }\ -) - - -// if expression evaluates to a negative error code, return 0. -#define RETURN_IF_NOT_CONTINUE(expression)\ -STMT(\ - i64 err64__ = (i64)(expression);\ - if(err64__ != INFO::CB_CONTINUE)\ - return err64__;\ -) - -// return an error and warn about it (replaces debug_warn+return) -#define WARN_RETURN(err)\ -STMT(\ - DEBUG_WARN_ERR(err);\ - return err;\ -) - -// if expression evaluates to a negative error code, warn user and -// throw that number. -#define THROW_ERR(expression)\ -STMT(\ - i64 err64__ = (i64)(expression);\ - if(err64__ < 0)\ - {\ - LibError err__ = (LibError)(err64__ & ULONG_MAX);\ - DEBUG_WARN_ERR(err__);\ - throw err__;\ - }\ -) - -// if expression evaluates to a negative error code, warn user and just return -// (useful for void functions that must bail and complain) -#define WARN_ERR_RETURN(expression)\ -STMT(\ - i64 err64__ = (i64)(expression);\ - if(err64__ < 0)\ - {\ - LibError err__ = (LibError)(err64__ & ULONG_MAX);\ - DEBUG_WARN_ERR(err__);\ - return;\ - }\ -) - -// if expression evaluates to a negative error code, warn user -// (this is similar to ENSURE but also works in release mode) -#define WARN_ERR(expression)\ -STMT(\ - i64 err64__ = (i64)(expression);\ - if(err64__ < 0)\ - {\ - LibError err__ = (LibError)(err64__ & ULONG_MAX);\ - DEBUG_WARN_ERR(err__);\ - }\ -) - - -// if expression evaluates to a negative error code, return 0. -#define RETURN0_IF_ERR(expression)\ -STMT(\ - i64 err64__ = (i64)(expression);\ - if(err64__ < 0)\ - return 0;\ -) - -// if ok evaluates to false or FALSE, warn user and return -1. -#define WARN_RETURN_IF_FALSE(ok)\ -STMT(\ - if(!(ok))\ - {\ - debug_warn(L"FYI: WARN_RETURN_IF_FALSE reports that a function failed. "\ - L"Feel free to ignore or suppress this warning.");\ - return ERR::FAIL;\ - }\ -) - -// if ok evaluates to false or FALSE, return -1. -#define RETURN_IF_FALSE(ok)\ -STMT(\ - if(!(ok))\ - return ERR::FAIL;\ -) - -// if ok evaluates to false or FALSE, warn user. -#define WARN_IF_FALSE(ok)\ -STMT(\ - if(!(ok))\ - debug_warn(L"FYI: WARN_IF_FALSE reports that a function failed. "\ - L"Feel free to ignore or suppress this warning.");\ -) - - -//----------------------------------------------------------------------------- - -namespace INFO -{ -const LibError OK = 0; - -// note: these values are > 100 to allow multiplexing them with -// coroutine return values, which return completion percentage. - -// function is a callback and indicates that it can (but need not -// necessarily) be called again. -const LibError CB_CONTINUE = +100000; -// notify caller that nothing was done. -const LibError SKIPPED = +100001; -// function is incapable of doing the requested task with the given inputs. -// this implies SKIPPED, but also conveys a bit more information. -const LibError CANNOT_HANDLE = +100002; -// function is meant to be called repeatedly, and now indicates that -// all jobs are complete. -const LibError ALL_COMPLETE = +100003; -// (returned e.g. when inserting into container) -const LibError ALREADY_EXISTS = +100004; -} - -namespace ERR -{ -const LibError FAIL = -1; - -// general -const LibError LOGIC = -100010; -const LibError TIMED_OUT = -100011; -const LibError REENTERED = -100012; -const LibError CORRUPTED = -100013; -const LibError VERSION = -100014; - -// function arguments -const LibError INVALID_PARAM = -100020; -const LibError INVALID_HANDLE = -100021; -const LibError BUF_SIZE = -100022; - -// system limitations -const LibError AGAIN = -100030; -const LibError LIMIT = -100031; -const LibError NO_SYS = -100032; -const LibError NOT_IMPLEMENTED = -100033; -const LibError NOT_SUPPORTED = -100034; -const LibError NO_MEM = -100035; - -// these are for cases where we just want a distinct value to display and -// a symbolic name + string would be overkill (e.g. the various -// test cases in a validate() call). they are shared between multiple -// functions; when something fails, the stack trace will show in which -// one it was => these errors are unambiguous. -// there are 3 tiers - 1..9 are used in most functions, 11..19 are -// used in a function that calls another validator and 21..29 are -// for for functions that call 2 other validators (this avoids -// ambiguity as to which error actually happened where) -const LibError _1 = -100101; -const LibError _2 = -100102; -const LibError _3 = -100103; -const LibError _4 = -100104; -const LibError _5 = -100105; -const LibError _6 = -100106; -const LibError _7 = -100107; -const LibError _8 = -100108; -const LibError _9 = -100109; -const LibError _11 = -100111; -const LibError _12 = -100112; -const LibError _13 = -100113; -const LibError _14 = -100114; -const LibError _15 = -100115; -const LibError _16 = -100116; -const LibError _17 = -100117; -const LibError _18 = -100118; -const LibError _19 = -100119; -const LibError _21 = -100121; -const LibError _22 = -100122; -const LibError _23 = -100123; -const LibError _24 = -100124; -const LibError _25 = -100125; -const LibError _26 = -100126; -const LibError _27 = -100127; -const LibError _28 = -100128; -const LibError _29 = -100129; - -} // namespace ERR - -#endif // #ifndef INCLUDED_LIB_ERRORS diff --git a/source/lib/module_init.cpp b/source/lib/module_init.cpp index afe677ebb5..cd6cee2714 100644 --- a/source/lib/module_init.cpp +++ b/source/lib/module_init.cpp @@ -37,13 +37,13 @@ static const ModuleInitState BUSY = INFO::ALREADY_EXISTS; // never returned static const ModuleInitState INITIALIZED = INFO::SKIPPED; -LibError ModuleInit(volatile ModuleInitState* initState, LibError (*init)()) +Status ModuleInit(volatile ModuleInitState* initState, Status (*init)()) { for(;;) { if(cpu_CAS(initState, UNINITIALIZED, BUSY)) { - LibError ret = init(); + Status ret = init(); *initState = (ret == INFO::OK)? INITIALIZED : ret; COMPILER_FENCE; return ret; @@ -57,12 +57,12 @@ LibError ModuleInit(volatile ModuleInitState* initState, LibError (*init)()) } ENSURE(latchedInitState == INITIALIZED || latchedInitState < 0); - return (LibError)latchedInitState; + return (Status)latchedInitState; } } -LibError ModuleShutdown(volatile ModuleInitState* initState, void (*shutdown)()) +Status ModuleShutdown(volatile ModuleInitState* initState, void (*shutdown)()) { for(;;) { @@ -85,6 +85,6 @@ LibError ModuleShutdown(volatile ModuleInitState* initState, void (*shutdown)()) return INFO::SKIPPED; ENSURE(latchedInitState < 0); - return (LibError)latchedInitState; + return (Status)latchedInitState; } } diff --git a/source/lib/module_init.h b/source/lib/module_init.h index 4d3071c737..d1ee18a321 100644 --- a/source/lib/module_init.h +++ b/source/lib/module_init.h @@ -37,11 +37,11 @@ typedef intptr_t ModuleInitState; // intptr_t is required by cpu_CAS /** * calls a user-defined init function if initState is zero. * - * @return INFO::SKIPPED if already initialized, a LibError if the + * @return INFO::SKIPPED if already initialized, a Status if the * previous invocation failed, or the value returned by the callback. * * postcondition: initState is "initialized" if the callback returned - * INFO::OK, otherwise its LibError return value (which prevents + * INFO::OK, otherwise its Status return value (which prevents * shutdown from being called). * * thread-safe: subsequent callers spin until the callback returns @@ -50,15 +50,15 @@ typedef intptr_t ModuleInitState; // intptr_t is required by cpu_CAS * note that callbacks typically reference static data and thus do not * require a function argument, but that can later be added if necessary. **/ -LIB_API LibError ModuleInit(volatile ModuleInitState* initState, LibError (*init)()); +LIB_API Status ModuleInit(volatile ModuleInitState* initState, Status (*init)()); /** * calls a user-defined shutdown function if initState is "initialized". * * @return INFO::OK if shutdown occurred, INFO::SKIPPED if initState was - * zero (uninitialized), otherwise the LibError returned by ModuleInit. + * zero (uninitialized), otherwise the Status returned by ModuleInit. * - * postcondition: initState remains set to the LibError, or has been + * postcondition: initState remains set to the Status, or has been * reset to zero to allow multiple init/shutdown pairs, e.g. in self-tests. * * note: there is no provision for reference-counting because that @@ -69,6 +69,6 @@ LIB_API LibError ModuleInit(volatile ModuleInitState* initState, LibError (*init * cleanup is necessary (e.g. at exit before leak reporting) and * it is certain that the module is no longer in use. **/ -LIB_API LibError ModuleShutdown(volatile ModuleInitState* initState, void (*shutdown)()); +LIB_API Status ModuleShutdown(volatile ModuleInitState* initState, void (*shutdown)()); #endif // #ifndef INCLUDED_MODULE_INIT diff --git a/source/lib/ogl.cpp b/source/lib/ogl.cpp index 7dfb283772..ff706a26b4 100644 --- a/source/lib/ogl.cpp +++ b/source/lib/ogl.cpp @@ -448,7 +448,7 @@ GLint ogl_max_tex_units = -1; // limit on GL_TEXTUREn // // fails if OpenGL not ready for use. // gfx_card and gfx_drv_ver are unchanged on failure. -LibError ogl_get_gfx_info() +Status ogl_get_gfx_info() { const char* vendor = (const char*)glGetString(GL_VENDOR); const char* renderer = (const char*)glGetString(GL_RENDERER); diff --git a/source/lib/ogl.h b/source/lib/ogl.h index bcb92db440..7547c3d608 100644 --- a/source/lib/ogl.h +++ b/source/lib/ogl.h @@ -147,8 +147,8 @@ extern GLint ogl_max_tex_units; /// limit on GL_TEXTUREn * fails if OpenGL not ready for use. * gfx_card and gfx_drv_ver are unchanged on failure. * - * @return LibError + * @return Status **/ -extern LibError ogl_get_gfx_info(); +extern Status ogl_get_gfx_info(); #endif // #ifndef INCLUDED_OGL diff --git a/source/lib/path.cpp b/source/lib/path.cpp index f71430a1cf..3e9b79ffb7 100644 --- a/source/lib/path.cpp +++ b/source/lib/path.cpp @@ -30,9 +30,9 @@ #include #include -ERROR_ASSOCIATE(ERR::PATH_CHARACTER_ILLEGAL, L"illegal path character", -1); -ERROR_ASSOCIATE(ERR::PATH_CHARACTER_UNSAFE, L"unsafe path character", -1); -ERROR_ASSOCIATE(ERR::PATH_NOT_FOUND, L"path not found", -1); +STATUS_DEFINE(ERR, PATH_CHARACTER_ILLEGAL, L"illegal path character", -1); +STATUS_DEFINE(ERR, PATH_CHARACTER_UNSAFE, L"unsafe path character", -1); +STATUS_DEFINE(ERR, PATH_NOT_FOUND, L"path not found", -1); static bool path_is_dir_sep(wchar_t c) @@ -92,7 +92,7 @@ const wchar_t* path_name_only(const wchar_t* path) } -/*static*/ LibError Path::Validate(String::value_type c) +/*static*/ Status Path::Validate(String::value_type c) { if(c < 32) return ERR::PATH_CHARACTER_UNSAFE; diff --git a/source/lib/path.h b/source/lib/path.h index 97a62a00a8..d0b107a8dd 100644 --- a/source/lib/path.h +++ b/source/lib/path.h @@ -45,9 +45,9 @@ namespace ERR { - const LibError PATH_CHARACTER_ILLEGAL = -100300; - const LibError PATH_CHARACTER_UNSAFE = -100301; - const LibError PATH_NOT_FOUND = -100302; + const Status PATH_CHARACTER_ILLEGAL = -100300; + const Status PATH_CHARACTER_UNSAFE = -100301; + const Status PATH_NOT_FOUND = -100302; } /** @@ -179,7 +179,7 @@ public: return ret; } - static LibError Validate(String::value_type c); + static Status Validate(String::value_type c); private: String path; diff --git a/source/lib/pointer_typedefs.h b/source/lib/pointer_typedefs.h new file mode 100644 index 0000000000..0a55a32712 --- /dev/null +++ b/source/lib/pointer_typedefs.h @@ -0,0 +1,146 @@ +#ifndef INCLUDED_POINTER_TYPEDEFS +#define INCLUDED_POINTER_TYPEDEFS + +// convenience typedefs for shortening parameter lists. +// naming convention: [const] [restrict] pointer to [const] type +// supported types: void, signed/unsigned 8/16/32/64 integers, float, double, XMM + +// NB: `restrict' is not going into C++0x, so use __restrict to maintain compatibility +// with VC2010. + +typedef void* pVoid; +typedef void* const cpVoid; +typedef void* __restrict rpVoid; +typedef void* const __restrict crpVoid; +typedef const void* pcVoid; +typedef const void* const cpcVoid; +typedef const void* __restrict rpcVoid; +typedef const void* const __restrict crpcVoid; + +typedef int8_t* pI8; +typedef int8_t* const cpI8; +typedef int8_t* __restrict rpI8; +typedef int8_t* const __restrict crpI8; +typedef const int8_t* pcI8; +typedef const int8_t* const cpcI8; +typedef const int8_t* __restrict rpcI8; +typedef const int8_t* const __restrict crpcI8; + +typedef int16_t* pI16; +typedef int16_t* const cpI16; +typedef int16_t* __restrict rpI16; +typedef int16_t* const __restrict crpI16; +typedef const int16_t* pcI16; +typedef const int16_t* const cpcI16; +typedef const int16_t* __restrict rpcI16; +typedef const int16_t* const __restrict crpcI16; + +typedef int32_t* pI32; +typedef int32_t* const cpI32; +typedef int32_t* __restrict rpI32; +typedef int32_t* const __restrict crpI32; +typedef const int32_t* pcI32; +typedef const int32_t* const cpcI32; +typedef const int32_t* __restrict rpcI32; +typedef const int32_t* const __restrict crpcI32; + +typedef int64_t* pI64; +typedef int64_t* const cpI64; +typedef int64_t* __restrict rpI64; +typedef int64_t* const __restrict crpI64; +typedef const int64_t* pcI64; +typedef const int64_t* const cpcI64; +typedef const int64_t* __restrict rpcI64; +typedef const int64_t* const __restrict crpcI64; + +typedef uint8_t* pU8; +typedef uint8_t* const cpU8; +typedef uint8_t* __restrict rpU8; +typedef uint8_t* const __restrict crpU8; +typedef const uint8_t* pcU8; +typedef const uint8_t* const cpcU8; +typedef const uint8_t* __restrict rpcU8; +typedef const uint8_t* const __restrict crpcU8; + +typedef uint16_t* pU16; +typedef uint16_t* const cpU16; +typedef uint16_t* __restrict rpU16; +typedef uint16_t* const __restrict crpU16; +typedef const uint16_t* pcU16; +typedef const uint16_t* const cpcU16; +typedef const uint16_t* __restrict rpcU16; +typedef const uint16_t* const __restrict crpcU16; + +typedef uint32_t* pU32; +typedef uint32_t* const cpU32; +typedef uint32_t* __restrict rpU32; +typedef uint32_t* const __restrict crpU32; +typedef const uint32_t* pcU32; +typedef const uint32_t* const cpcU32; +typedef const uint32_t* __restrict rpcU32; +typedef const uint32_t* const __restrict crpcU32; + +typedef uint64_t* pU64; +typedef uint64_t* const cpU64; +typedef uint64_t* __restrict rpU64; +typedef uint64_t* const __restrict crpU64; +typedef const uint64_t* pcU64; +typedef const uint64_t* const cpcU64; +typedef const uint64_t* __restrict rpcU64; +typedef const uint64_t* const __restrict crpcU64; + +typedef float* pFloat; +typedef float* const cpFloat; +typedef float* __restrict rpFloat; +typedef float* const __restrict crpFloat; +typedef const float* pcFloat; +typedef const float* const cpcFloat; +typedef const float* __restrict rpcFloat; +typedef const float* const __restrict crpcFloat; + +typedef double* pDouble; +typedef double* const cpDouble; +typedef double* __restrict rpDouble; +typedef double* const __restrict crpDouble; +typedef const double* pcDouble; +typedef const double* const cpcDouble; +typedef const double* __restrict rpcDouble; +typedef const double* const __restrict crpcDouble; + +typedef __m128* pM128; +typedef __m128* const cpM128; +typedef __m128* __restrict rpM128; +typedef __m128* const __restrict crpM128; +typedef const __m128* pcM128; +typedef const __m128* const cpcM128; +typedef const __m128* __restrict rpcM128; +typedef const __m128* const __restrict crpcM128; + +typedef __m128i* pM128I; +typedef __m128i* const cpM128I; +typedef __m128i* __restrict rpM128I; +typedef __m128i* const __restrict crpM128I; +typedef const __m128i* pcM128I; +typedef const __m128i* const cpcM128I; +typedef const __m128i* __restrict rpcM128I; +typedef const __m128i* const __restrict crpcM128I; + +typedef __m128d* pM128D; +typedef __m128d* const cpM128D; +typedef __m128d* __restrict rpM128D; +typedef __m128d* const __restrict crpM128D; +typedef const __m128d* pcM128D; +typedef const __m128d* const cpcM128D; +typedef const __m128d* __restrict rpcM128D; +typedef const __m128d* const __restrict crpcM128D; + +typedef __m64* pM64; +typedef __m64* const cpM64; +typedef __m64* __restrict rpM64; +typedef __m64* const __restrict crpM64; +typedef const __m64* pcM64; +typedef const __m64* const cpcM64; +typedef const __m64* __restrict rpcM64; +typedef const __m64* const __restrict crpcM64; + +#endif // #ifndef INCLUDED_POINTER_TYPEDEFS diff --git a/source/lib/rand.cpp b/source/lib/rand.cpp index 789720c86c..d92b398a5a 100644 --- a/source/lib/rand.cpp +++ b/source/lib/rand.cpp @@ -56,7 +56,7 @@ size_t rand(size_t min_inclusive, size_t max_exclusive) // huge interval or min >= max if(range == 0 || range > XRAND_MAX) { - WARN_ERR(ERR::INVALID_PARAM); + WARN_IF_ERR(ERR::INVALID_PARAM); return 0; } diff --git a/source/lib/res/graphics/cursor.cpp b/source/lib/res/graphics/cursor.cpp index 7f183d9b94..95d8cb1ed1 100644 --- a/source/lib/res/graphics/cursor.cpp +++ b/source/lib/res/graphics/cursor.cpp @@ -46,7 +46,7 @@ #endif -static LibError load_sys_cursor(const PIVFS& vfs, const VfsPath& pathname, int hx, int hy, sys_cursor* cursor) +static Status load_sys_cursor(const PIVFS& vfs, const VfsPath& pathname, int hx, int hy, sys_cursor* cursor) { #if !ALLOW_SYS_CURSOR UNUSED2(vfs); @@ -58,19 +58,19 @@ static LibError load_sys_cursor(const PIVFS& vfs, const VfsPath& pathname, int h return ERR::FAIL; #else shared_ptr file; size_t fileSize; - RETURN_ERR(vfs->LoadFile(pathname, file, fileSize)); + RETURN_STATUS_IF_ERR(vfs->LoadFile(pathname, file, fileSize)); ScopedTex t; - RETURN_ERR(tex_decode(file, fileSize, &t)); + RETURN_STATUS_IF_ERR(tex_decode(file, fileSize, &t)); // convert to required BGRA format. const size_t flags = (t.flags | TEX_BGR) & ~TEX_DXT; - RETURN_ERR(tex_transform_to(&t, flags)); + RETURN_STATUS_IF_ERR(tex_transform_to(&t, flags)); void* bgra_img = tex_get_data(&t); if(!bgra_img) WARN_RETURN(ERR::FAIL); - RETURN_ERR(sys_cursor_create((int)t.w, (int)t.h, bgra_img, hx, hy, cursor)); + RETURN_STATUS_IF_ERR(sys_cursor_create((int)t.w, (int)t.h, bgra_img, hx, hy, cursor)); return INFO::OK; #endif } @@ -86,10 +86,10 @@ class GLCursor int hotspotx, hotspoty; public: - LibError create(const PIVFS& vfs, const VfsPath& pathname, int hotspotx_, int hotspoty_) + Status create(const PIVFS& vfs, const VfsPath& pathname, int hotspotx_, int hotspoty_) { ht = ogl_tex_load(vfs, pathname); - RETURN_ERR(ht); + RETURN_STATUS_IF_ERR(ht); size_t width, height; (void)ogl_tex_get_size(ht, &width, &height, 0); @@ -127,7 +127,7 @@ public: glEnd(); } - LibError validate() const + Status validate() const { const GLint A = 128; // no cursor is expected to get this big if(w > A || h > A || hotspotx > A || hotspoty > A) @@ -185,7 +185,7 @@ static void Cursor_dtor(Cursor* c) } } -static LibError Cursor_reload(Cursor* c, const PIVFS& vfs, const VfsPath& name, Handle) +static Status Cursor_reload(Cursor* c, const PIVFS& vfs, const VfsPath& name, Handle) { const VfsPath pathname(VfsPath(L"art/textures/cursors") / name); @@ -195,7 +195,7 @@ static LibError Cursor_reload(Cursor* c, const PIVFS& vfs, const VfsPath& name, { const VfsPath pathnameHotspot = pathname.ChangeExtension(L".txt"); shared_ptr buf; size_t size; - RETURN_ERR(vfs->LoadFile(pathnameHotspot, buf, size)); + RETURN_STATUS_IF_ERR(vfs->LoadFile(pathnameHotspot, buf, size)); std::wstringstream s(std::wstring((const wchar_t*)buf.get(), size)); s >> hotspotx >> hotspoty; } @@ -219,7 +219,7 @@ static LibError Cursor_reload(Cursor* c, const PIVFS& vfs, const VfsPath& name, return INFO::OK; } -static LibError Cursor_validate(const Cursor* c) +static Status Cursor_validate(const Cursor* c) { switch(c->kind) { @@ -232,7 +232,7 @@ static LibError Cursor_validate(const Cursor* c) break; case CK_OpenGL: - RETURN_ERR(c->gl_cursor.validate()); + RETURN_STATUS_IF_ERR(c->gl_cursor.validate()); break; default: @@ -243,7 +243,7 @@ static LibError Cursor_validate(const Cursor* c) return INFO::OK; } -static LibError Cursor_to_string(const Cursor* c, wchar_t* buf) +static Status Cursor_to_string(const Cursor* c, wchar_t* buf) { const wchar_t* type; switch(c->kind) @@ -282,13 +282,13 @@ static Handle cursor_load(const PIVFS& vfs, const VfsPath& name) return h_alloc(H_Cursor, vfs, name, 0); } -static LibError cursor_free(Handle& h) +static Status cursor_free(Handle& h) { return h_free(h, H_Cursor); } -LibError cursor_draw(const PIVFS& vfs, const wchar_t* name, int x, int y) +Status cursor_draw(const PIVFS& vfs, const wchar_t* name, int x, int y) { // hide the cursor if(!name) @@ -299,7 +299,7 @@ LibError cursor_draw(const PIVFS& vfs, const wchar_t* name, int x, int y) Handle hc = cursor_load(vfs, name); - RETURN_ERR(hc); // silently ignore failures + RETURN_STATUS_IF_ERR(hc); // silently ignore failures H_DEREF(hc, Cursor, c); diff --git a/source/lib/res/graphics/cursor.h b/source/lib/res/graphics/cursor.h index 5ed1b0b60c..9b034a4a39 100644 --- a/source/lib/res/graphics/cursor.h +++ b/source/lib/res/graphics/cursor.h @@ -43,6 +43,6 @@ * Uses a hardware mouse cursor where available, otherwise a * portable OpenGL implementation. **/ -extern LibError cursor_draw(const PIVFS& vfs, const wchar_t* name, int x, int y); +extern Status cursor_draw(const PIVFS& vfs, const wchar_t* name, int x, int y); #endif // #ifndef INCLUDED_GRAPHICS_CURSOR diff --git a/source/lib/res/graphics/ogl_shader.cpp b/source/lib/res/graphics/ogl_shader.cpp index 43b302c5eb..2c500a72e1 100644 --- a/source/lib/res/graphics/ogl_shader.cpp +++ b/source/lib/res/graphics/ogl_shader.cpp @@ -40,11 +40,11 @@ extern PIVFS vfs; -ERROR_ASSOCIATE(ERR::SHDR_CREATE, L"Shader creation failed", -1); -ERROR_ASSOCIATE(ERR::SHDR_COMPILE, L"Shader compile failed", -1); -ERROR_ASSOCIATE(ERR::SHDR_NO_SHADER, L"Invalid shader reference", -1); -ERROR_ASSOCIATE(ERR::SHDR_LINK, L"Shader linking failed", -1); -ERROR_ASSOCIATE(ERR::SHDR_NO_PROGRAM, L"Invalid shader program reference", -1); +STATUS_DEFINE(ERR, SHDR_CREATE, L"Shader creation failed", -1); +STATUS_DEFINE(ERR, SHDR_COMPILE, L"Shader compile failed", -1); +STATUS_DEFINE(ERR, SHDR_NO_SHADER, L"Invalid shader reference", -1); +STATUS_DEFINE(ERR, SHDR_LINK, L"Shader linking failed", -1); +STATUS_DEFINE(ERR, SHDR_NO_PROGRAM, L"Invalid shader program reference", -1); // Convert a shader object type into a descriptive string. @@ -109,15 +109,15 @@ TIMER_ADD_CLIENT(tc_linkProgram); // have absolutely no effect on a program object that contains these shaders // when the program object is already linked. // So, how can we inform the "parent object" (i.e. the program object) of our change? -static LibError Ogl_Shader_reload(Ogl_Shader* shdr, const PIVFS& vfs, const VfsPath& pathname, Handle UNUSED(h)) +static Status Ogl_Shader_reload(Ogl_Shader* shdr, const PIVFS& vfs, const VfsPath& pathname, Handle UNUSED(h)) { - LibError err = ERR::FAIL; + Status err = ERR::FAIL; if (shdr->id) return INFO::OK; shared_ptr file; size_t file_size; - RETURN_ERR(vfs->LoadFile(pathname, file, file_size)); + RETURN_STATUS_IF_ERR(vfs->LoadFile(pathname, file, file_size)); ogl_WarnIfError(); @@ -204,13 +204,13 @@ static void Ogl_Shader_dtor(Ogl_Shader* shdr) } } -static LibError Ogl_Shader_validate(const Ogl_Shader* UNUSED(shdr)) +static Status Ogl_Shader_validate(const Ogl_Shader* UNUSED(shdr)) { // TODO return INFO::OK; } -static LibError Ogl_Shader_to_string(const Ogl_Shader* shdr, wchar_t* buf) +static Status Ogl_Shader_to_string(const Ogl_Shader* shdr, wchar_t* buf) { swprintf_s(buf, H_STRING_LEN, L"Ogl_Shader %p", shdr); return INFO::OK; @@ -237,7 +237,7 @@ void ogl_shader_free(Handle& h) } // Attach a shader to the given OpenGL program. -LibError ogl_shader_attach(GLhandleARB program, Handle& h) +Status ogl_shader_attach(GLhandleARB program, Handle& h) { H_DEREF(h, Ogl_Shader, shdr); @@ -272,7 +272,7 @@ static void Ogl_Program_init(Ogl_Program* UNUSED(p), va_list UNUSED(args)) // Load the shader associated with one Shader element, // and attach it to our program object. -static LibError do_load_shader( +static Status do_load_shader( Ogl_Program* p, const VfsPath& pathname, Handle UNUSED(h), const CXeromyces& XeroFile, const XMBElement& Shader) { @@ -305,7 +305,7 @@ static LibError do_load_shader( } Handle hshader = ogl_shader_load(g_VFS, pathnameShader.FromUTF8(), shadertype); - RETURN_ERR(hshader); + RETURN_STATUS_IF_ERR(hshader); ogl_shader_attach(p->id, hshader); @@ -320,7 +320,7 @@ static LibError do_load_shader( // Reload the program object from the source file. -static LibError Ogl_Program_reload(Ogl_Program* p, const PIVFS& vfs, const VfsPath& pathname, Handle h) +static Status Ogl_Program_reload(Ogl_Program* p, const PIVFS& vfs, const VfsPath& pathname, Handle h) { if (p->id) return INFO::OK; @@ -380,7 +380,7 @@ static LibError Ogl_Program_reload(Ogl_Program* p, const PIVFS& vfs, const VfsPa WARN_RETURN(ERR::CORRUPTED); } - RETURN_ERR(do_load_shader(p, pathname, h, XeroFile, Shader)); + RETURN_STATUS_IF_ERR(do_load_shader(p, pathname, h, XeroFile, Shader)); } } else @@ -427,13 +427,13 @@ static void Ogl_Program_dtor(Ogl_Program* p) } } -static LibError Ogl_Program_validate(const Ogl_Program* UNUSED(p)) +static Status Ogl_Program_validate(const Ogl_Program* UNUSED(p)) { // TODO return INFO::OK; } -static LibError Ogl_Program_to_string(const Ogl_Program* p, wchar_t* buf) +static Status Ogl_Program_to_string(const Ogl_Program* p, wchar_t* buf) { swprintf_s(buf, H_STRING_LEN, L"Ogl_Program %p", p); return INFO::OK; @@ -459,7 +459,7 @@ void ogl_program_free(Handle& h) // Activate the program (glUseProgramObjectARB). // h may be 0, in which case program objects are disabled. -LibError ogl_program_use(Handle h) +Status ogl_program_use(Handle h) { if (!h) { diff --git a/source/lib/res/graphics/ogl_shader.h b/source/lib/res/graphics/ogl_shader.h index 69539acee3..02e24ed462 100644 --- a/source/lib/res/graphics/ogl_shader.h +++ b/source/lib/res/graphics/ogl_shader.h @@ -35,11 +35,11 @@ namespace ERR { - const LibError SHDR_CREATE = -120200; - const LibError SHDR_COMPILE = -120201; - const LibError SHDR_NO_SHADER = -120202; - const LibError SHDR_LINK = -120203; - const LibError SHDR_NO_PROGRAM = -120204; + const Status SHDR_CREATE = -120200; + const Status SHDR_COMPILE = -120201; + const Status SHDR_NO_SHADER = -120202; + const Status SHDR_LINK = -120203; + const Status SHDR_NO_PROGRAM = -120204; } /* @@ -69,7 +69,7 @@ void ogl_shader_free(Handle& h); /** * Attach a shader to the given OpenGL program. **/ -LibError ogl_shader_attach(GLhandleARB program, Handle& h); +Status ogl_shader_attach(GLhandleARB program, Handle& h); /* @@ -97,7 +97,7 @@ void ogl_program_free(Handle& h); * * @param h may be 0, in which case program objects are disabled. **/ -LibError ogl_program_use(Handle h); +Status ogl_program_use(Handle h); /** * Query uniform information diff --git a/source/lib/res/graphics/ogl_tex.cpp b/source/lib/res/graphics/ogl_tex.cpp index c21a684551..c6b18d11e2 100644 --- a/source/lib/res/graphics/ogl_tex.cpp +++ b/source/lib/res/graphics/ogl_tex.cpp @@ -426,7 +426,7 @@ static void OglTex_dtor(OglTex* ot) ot->flags &= ~OT_IS_UPLOADED; } -static LibError OglTex_reload(OglTex* ot, const PIVFS& vfs, const VfsPath& pathname, Handle h) +static Status OglTex_reload(OglTex* ot, const PIVFS& vfs, const VfsPath& pathname, Handle h) { // we're reusing a freed but still in-memory OglTex object if(ot->flags & OT_IS_UPLOADED) @@ -437,7 +437,7 @@ static LibError OglTex_reload(OglTex* ot, const PIVFS& vfs, const VfsPath& pathn if(!(ot->flags & OT_TEX_VALID)) { shared_ptr file; size_t fileSize; - RETURN_ERR(vfs->LoadFile(pathname, file, fileSize)); + RETURN_STATUS_IF_ERR(vfs->LoadFile(pathname, file, fileSize)); if(tex_decode(file, fileSize, &ot->t) >= 0) ot->flags |= OT_TEX_VALID; } @@ -452,11 +452,11 @@ static LibError OglTex_reload(OglTex* ot, const PIVFS& vfs, const VfsPath& pathn return INFO::OK; } -static LibError OglTex_validate(const OglTex* ot) +static Status OglTex_validate(const OglTex* ot) { if(ot->flags & OT_TEX_VALID) { - RETURN_ERR(tex_validate(&ot->t)); + RETURN_STATUS_IF_ERR(tex_validate(&ot->t)); // width, height // (note: this is done here because tex.cpp doesn't impose any @@ -497,7 +497,7 @@ static LibError OglTex_validate(const OglTex* ot) return INFO::OK; } -static LibError OglTex_to_string(const OglTex* ot, wchar_t* buf) +static Status OglTex_to_string(const OglTex* ot, wchar_t* buf) { swprintf_s(buf, H_STRING_LEN, L"OglTex id=%d flags=%lx", ot->id, ot->flags); return INFO::OK; @@ -550,7 +550,7 @@ Handle ogl_tex_wrap(Tex* t, const PIVFS& vfs, const VfsPath& pathname, size_t fl // free all resources associated with the texture and make further // use of it impossible. (subject to refcount) -LibError ogl_tex_free(Handle& ht) +Status ogl_tex_free(Handle& ht) { return h_free(ht, H_OglTex); } @@ -602,7 +602,7 @@ static void warn_if_uploaded(Handle ht, const OglTex* ot) // must be called before uploading (raises a warning if called afterwards). // filter is as defined by OpenGL; it is applied for both minification and // magnification (for rationale and details, see OglTexState) -LibError ogl_tex_set_filter(Handle ht, GLint filter) +Status ogl_tex_set_filter(Handle ht, GLint filter) { H_DEREF(ht, OglTex, ot); @@ -622,7 +622,7 @@ LibError ogl_tex_set_filter(Handle ht, GLint filter) // must be called before uploading (raises a warning if called afterwards). // wrap is as defined by OpenGL and applies to both S and T coordinates // (rationale: see OglTexState). -LibError ogl_tex_set_wrap(Handle ht, GLint wrap) +Status ogl_tex_set_wrap(Handle ht, GLint wrap) { H_DEREF(ht, OglTex, ot); @@ -640,7 +640,7 @@ LibError ogl_tex_set_wrap(Handle ht, GLint wrap) // override default anisotropy for this texture. // must be called before uploading (raises a warning if called afterwards). -LibError ogl_tex_set_anisotropy(Handle ht, GLfloat anisotropy) +Status ogl_tex_set_anisotropy(Handle ht, GLfloat anisotropy) { H_DEREF(ht, OglTex, ot); @@ -747,7 +747,7 @@ static void detect_gl_upload_caps() // whether mipmaps are needed and the quality settings). // returns 0 to indicate success; otherwise, caller must disable // mipmapping by switching filter to e.g. GL_LINEAR. -static LibError get_mipmaps(Tex* t, GLint filter, int q_flags, int* plevels_to_skip) +static Status get_mipmaps(Tex* t, GLint filter, int q_flags, int* plevels_to_skip) { // decisions: // .. does filter call for uploading mipmaps? @@ -788,7 +788,7 @@ static LibError get_mipmaps(Tex* t, GLint filter, int q_flags, int* plevels_to_s // we will generate mipmaps in software. else { - RETURN_ERR(tex_transform_to(t, t->flags|TEX_MIPMAPS)); + RETURN_STATUS_IF_ERR(tex_transform_to(t, t->flags|TEX_MIPMAPS)); *plevels_to_skip = 0; // t contains mipmaps } @@ -857,7 +857,7 @@ static void upload_impl(Tex* t, GLenum fmt, GLint int_fmt, int levels_to_skip) // side effects: // - enables texturing on TMU 0 and binds the texture to it; // - frees the texel data! see ogl_tex_get_data. -LibError ogl_tex_upload(const Handle ht, GLenum fmt_ovr, int q_flags_ovr, GLint int_fmt_ovr) +Status ogl_tex_upload(const Handle ht, GLenum fmt_ovr, int q_flags_ovr, GLint int_fmt_ovr) { ONCE(detect_gl_upload_caps()); @@ -889,7 +889,7 @@ LibError ogl_tex_upload(const Handle ht, GLenum fmt_ovr, int q_flags_ovr, GLint { // (note: we know ht is valid due to H_DEREF, but ogl_tex_bind can // fail in debug builds if OglTex.id isn't a valid texture name) - RETURN_ERR(ogl_tex_bind(ht, ot->tmu)); + RETURN_STATUS_IF_ERR(ogl_tex_bind(ht, ot->tmu)); int levels_to_skip; if(get_mipmaps(t, ot->state.filter, ot->q_flags, &levels_to_skip) < 0) // error => disable mipmapping @@ -927,7 +927,7 @@ LibError ogl_tex_upload(const Handle ht, GLenum fmt_ovr, int q_flags_ovr, GLint // retrieve texture dimensions and bits per pixel. // all params are optional and filled if non-NULL. -LibError ogl_tex_get_size(Handle ht, size_t* w, size_t* h, size_t* bpp) +Status ogl_tex_get_size(Handle ht, size_t* w, size_t* h, size_t* bpp) { H_DEREF(ht, OglTex, ot); @@ -944,7 +944,7 @@ LibError ogl_tex_get_size(Handle ht, size_t* w, size_t* h, size_t* bpp) // retrieve TexFlags and the corresponding OpenGL format. // the latter is determined during ogl_tex_upload and is 0 before that. // all params are optional and filled if non-NULL. -LibError ogl_tex_get_format(Handle ht, size_t* flags, GLenum* fmt) +Status ogl_tex_get_format(Handle ht, size_t* flags, GLenum* fmt) { H_DEREF(ht, OglTex, ot); @@ -966,7 +966,7 @@ LibError ogl_tex_get_format(Handle ht, size_t* flags, GLenum* fmt) // the function doesn't fail (negative return value) by design. // if you still need to get at the data, add a reference before // uploading it or read directly from OpenGL (discouraged). -LibError ogl_tex_get_data(Handle ht, u8** p) +Status ogl_tex_get_data(Handle ht, u8** p) { H_DEREF(ht, OglTex, ot); @@ -975,7 +975,7 @@ LibError ogl_tex_get_data(Handle ht, u8** p) } // retrieve colour of 1x1 mipmap level -extern LibError ogl_tex_get_average_colour(Handle ht, u32* p) +extern Status ogl_tex_get_average_colour(Handle ht, u32* p) { H_DEREF(ht, OglTex, ot); warn_if_uploaded(ht, ot); @@ -999,7 +999,7 @@ extern LibError ogl_tex_get_average_colour(Handle ht, u32* p) // - assumes multitexturing is available. // - not necessary before calling ogl_tex_upload! // - on error, the unit's texture state is unchanged; see implementation. -LibError ogl_tex_bind(Handle ht, size_t unit) +Status ogl_tex_bind(Handle ht, size_t unit) { // note: there are many call sites of glActiveTextureARB, so caching // those and ignoring redundant sets isn't feasible. @@ -1031,20 +1031,20 @@ LibError ogl_tex_bind(Handle ht, size_t unit) // apply the specified transforms (as in tex_transform) to the image. // must be called before uploading (raises a warning if called afterwards). -LibError ogl_tex_transform(Handle ht, size_t transforms) +Status ogl_tex_transform(Handle ht, size_t transforms) { H_DEREF(ht, OglTex, ot); - LibError ret = tex_transform(&ot->t, transforms); + Status ret = tex_transform(&ot->t, transforms); return ret; } // change the pixel format to that specified by . // (note: this is equivalent to ogl_tex_transform(ht, ht_flags^new_flags). -LibError ogl_tex_transform_to(Handle ht, size_t new_flags) +Status ogl_tex_transform_to(Handle ht, size_t new_flags) { H_DEREF(ht, OglTex, ot); - LibError ret = tex_transform_to(&ot->t, new_flags); + Status ret = tex_transform_to(&ot->t, new_flags); return ret; } diff --git a/source/lib/res/graphics/ogl_tex.h b/source/lib/res/graphics/ogl_tex.h index df0b403900..84dc8906b1 100644 --- a/source/lib/res/graphics/ogl_tex.h +++ b/source/lib/res/graphics/ogl_tex.h @@ -219,7 +219,7 @@ extern void ogl_tex_set_defaults(int q_flags, GLint filter); * @param vfs * @param pathname * @param flags h_alloc flags. -* @return Handle to texture or negative LibError +* @return Handle to texture or negative Status * for a list of supported formats, see tex.h's tex_load. */ extern Handle ogl_tex_load(const PIVFS& vfs, const VfsPath& pathname, size_t flags = 0); @@ -229,7 +229,7 @@ extern Handle ogl_tex_load(const PIVFS& vfs, const VfsPath& pathname, size_t fla * loaded and is still in memory. * * @param pathname fn VFS filename of texture. -* @return Handle to texture or negative LibError +* @return Handle to texture or negative Status */ extern Handle ogl_tex_find(const VfsPath& pathname); @@ -244,7 +244,7 @@ extern Handle ogl_tex_find(const VfsPath& pathname); * but would allow h_filename to return meaningful info for * purposes of debugging. * @param flags -* @return Handle to texture or negative LibError +* @return Handle to texture or negative Status * * note: because we cannot guarantee that callers will pass distinct * "filenames", caching is disabled for the created object. this avoids @@ -260,9 +260,9 @@ extern Handle ogl_tex_wrap(Tex* t, const PIVFS& vfs, const VfsPath& pathname, si * its associated resources are freed and further use made impossible. * * @param ht Texture handle. -* @return LibError +* @return Status */ -extern LibError ogl_tex_free(Handle& ht); +extern Status ogl_tex_free(Handle& ht); // @@ -279,11 +279,11 @@ extern LibError ogl_tex_free(Handle& ht); * @param ht Texture handle * @param filter OpenGL minification and magnification filter * (rationale: see {@link OglTexState}) -* @return LibError +* @return Status * * Must be called before uploading (raises a warning if called afterwards). */ -extern LibError ogl_tex_set_filter(Handle ht, GLint filter); +extern Status ogl_tex_set_filter(Handle ht, GLint filter); /** * Override default wrap mode (GL_REPEAT) for this texture. @@ -291,11 +291,11 @@ extern LibError ogl_tex_set_filter(Handle ht, GLint filter); * @param ht Texture handle * @param wrap OpenGL wrap mode (for both S and T coordinates) * (rationale: see {@link OglTexState}) -* @return LibError +* @return Status * * Must be called before uploading (raises a warning if called afterwards). */ -extern LibError ogl_tex_set_wrap(Handle ht, GLint wrap); +extern Status ogl_tex_set_wrap(Handle ht, GLint wrap); /** * Override default maximum anisotropic filtering for this texture. @@ -303,11 +303,11 @@ extern LibError ogl_tex_set_wrap(Handle ht, GLint wrap); * @param ht Texture handle * @param anisotropy Anisotropy value (must not be less than 1.0; should * usually be a power of two) -* @return LibError +* @return Status * * Must be called before uploading (raises a warning if called afterwards). */ -extern LibError ogl_tex_set_anisotropy(Handle ht, GLfloat anisotropy); +extern Status ogl_tex_set_anisotropy(Handle ht, GLfloat anisotropy); // @@ -346,13 +346,13 @@ extern void ogl_tex_override(OglTexOverrides what, OglTexAllow allow); * OglTexQualityFlags * @param int_fmt_ovr optional override for OpenGL internal format * (e.g. GL_RGB8), which is decided from fmt / q_flags. -* @return LibError. +* @return Status. * * Side Effects: * - enables texturing on TMU 0 and binds the texture to it; * - frees the texel data! see ogl_tex_get_data. */ -extern LibError ogl_tex_upload(const Handle ht, GLenum fmt_ovr = 0, int q_flags_ovr = 0, GLint int_fmt_ovr = 0); +extern Status ogl_tex_upload(const Handle ht, GLenum fmt_ovr = 0, int q_flags_ovr = 0, GLint int_fmt_ovr = 0); // @@ -366,9 +366,9 @@ extern LibError ogl_tex_upload(const Handle ht, GLenum fmt_ovr = 0, int q_flags_ * @param w optional; will be filled with width * @param h optional; will be filled with height * @param bpp optional; will be filled with bits per pixel -* @return LibError +* @return Status */ -extern LibError ogl_tex_get_size(Handle ht, size_t* w, size_t* h, size_t* bpp); +extern Status ogl_tex_get_size(Handle ht, size_t* w, size_t* h, size_t* bpp); /** * Retrieve pixel format of the texture. @@ -377,16 +377,16 @@ extern LibError ogl_tex_get_size(Handle ht, size_t* w, size_t* h, size_t* bpp); * @param flags optional; will be filled with TexFlags * @param fmt optional; will be filled with GL format * (it is determined during ogl_tex_upload and 0 before then) -* @return LibError +* @return Status */ -extern LibError ogl_tex_get_format(Handle ht, size_t* flags, GLenum* fmt); +extern Status ogl_tex_get_format(Handle ht, size_t* flags, GLenum* fmt); /** * Retrieve pixel data of the texture. * * @param ht Texture handle * @param p will be filled with pointer to texels. -* @return LibError +* @return Status * * Note: this memory is freed after a successful ogl_tex_upload for * this texture. After that, the pointer we retrieve is NULL but @@ -394,7 +394,7 @@ extern LibError ogl_tex_get_format(Handle ht, size_t* flags, GLenum* fmt); * If you still need to get at the data, add a reference before * uploading it or read directly from OpenGL (discouraged). */ -extern LibError ogl_tex_get_data(Handle ht, u8** p); +extern Status ogl_tex_get_data(Handle ht, u8** p); /** * Retrieve ARGB value of 1x1 mipmap level of the texture, @@ -402,11 +402,11 @@ extern LibError ogl_tex_get_data(Handle ht, u8** p); * * @param ht Texture handle * @param p will be filled with ARGB value (or 0 if texture does not have mipmaps) - * @return LibError + * @return Status * * Must be called before uploading (raises a warning if called afterwards). */ -extern LibError ogl_tex_get_average_colour(Handle ht, u32* p); +extern Status ogl_tex_get_average_colour(Handle ht, u32* p); // @@ -419,7 +419,7 @@ extern LibError ogl_tex_get_average_colour(Handle ht, u32* p); * * @param ht Texture handle. If 0, texturing is disabled on this unit. * @param unit Texture Mapping Unit number, typically 0 for the first. -* @return LibError +* @return Status * * Side Effects: * - changes the active texture unit; @@ -430,33 +430,33 @@ extern LibError ogl_tex_get_average_colour(Handle ht, u32* p); * - not necessary before calling ogl_tex_upload! * - on error, the unit's texture state is unchanged; see implementation. */ -extern LibError ogl_tex_bind(Handle ht, size_t unit = 0); +extern Status ogl_tex_bind(Handle ht, size_t unit = 0); /** * (partially) Transform pixel format of the texture. * * @param ht Texture handle. * @param flags the TexFlags that are to be @em changed. -* @return LibError +* @return Status * @see tex_transform * * Must be called before uploading (raises a warning if called afterwards). */ -extern LibError ogl_tex_transform(Handle ht, size_t flags); +extern Status ogl_tex_transform(Handle ht, size_t flags); /** * Transform pixel format of the texture. * * @param ht Texture handle. * @param new_flags Flags desired new TexFlags indicating pixel format. -* @return LibError +* @return Status * @see tex_transform * * Must be called before uploading (raises a warning if called afterwards). * * Note: this is equivalent to ogl_tex_transform(ht, ht_flags^new_flags). */ -extern LibError ogl_tex_transform_to(Handle ht, size_t new_flags); +extern Status ogl_tex_transform_to(Handle ht, size_t new_flags); /** * Return whether native S3TC texture compression support is available. diff --git a/source/lib/res/graphics/unifont.cpp b/source/lib/res/graphics/unifont.cpp index 33afa18172..4d3ed6c95c 100644 --- a/source/lib/res/graphics/unifont.cpp +++ b/source/lib/res/graphics/unifont.cpp @@ -72,7 +72,7 @@ static void UniFont_dtor(UniFont* f) // basename is e.g. "console"; the files are "fonts/console.fnt" and "fonts/console.png" // [10..70ms] -static LibError UniFont_reload(UniFont* f, const PIVFS& vfs, const VfsPath& basename, Handle UNUSED(h)) +static Status UniFont_reload(UniFont* f, const PIVFS& vfs, const VfsPath& basename, Handle UNUSED(h)) { // already loaded if(f->ht > 0) @@ -85,7 +85,7 @@ static LibError UniFont_reload(UniFont* f, const PIVFS& vfs, const VfsPath& base // Read font definition file into a stringstream shared_ptr buf; size_t size; const VfsPath fntName(basename.ChangeExtension(L".fnt")); - RETURN_ERR(vfs->LoadFile(path / fntName, buf, size)); // [cumulative for 12: 36ms] + RETURN_STATUS_IF_ERR(vfs->LoadFile(path / fntName, buf, size)); // [cumulative for 12: 36ms] std::istringstream FNTStream(std::string((const char*)buf.get(), size)); int Version; @@ -151,13 +151,13 @@ static LibError UniFont_reload(UniFont* f, const PIVFS& vfs, const VfsPath& base // [cumulative for 12: 20ms] const VfsPath imgName(basename.ChangeExtension(L".png")); Handle ht = ogl_tex_load(vfs, path / imgName); - RETURN_ERR(ht); + RETURN_STATUS_IF_ERR(ht); (void)ogl_tex_set_filter(ht, GL_NEAREST); // override is necessary because the GL format is chosen as LUMINANCE, // but we want ALPHA. there is no way of knowing what format // 8bpp textures are in - we could adopt a naming convention and // add some TEX_ flags, but that's overkill. - LibError err = ogl_tex_upload(ht, fmt_ovr); + Status err = ogl_tex_upload(ht, fmt_ovr); if(err < 0) { (void)ogl_tex_free(ht); @@ -169,7 +169,7 @@ static LibError UniFont_reload(UniFont* f, const PIVFS& vfs, const VfsPath& base return INFO::OK; } -static LibError UniFont_validate(const UniFont* f) +static Status UniFont_validate(const UniFont* f) { if(f->ht < 0) WARN_RETURN(ERR::_1); @@ -182,7 +182,7 @@ static LibError UniFont_validate(const UniFont* f) return INFO::OK; } -static LibError UniFont_to_string(const UniFont* f, wchar_t* buf) +static Status UniFont_to_string(const UniFont* f, wchar_t* buf) { if (f->ht) // not true if this is called after dtor (which it is) { @@ -201,7 +201,7 @@ Handle unifont_load(const PIVFS& vfs, const VfsPath& pathname, size_t flags) } -LibError unifont_unload(Handle& h) +Status unifont_unload(Handle& h) { H_DEREF(h, UniFont, f); @@ -214,7 +214,7 @@ LibError unifont_unload(Handle& h) } -LibError unifont_bind(const Handle h) +Status unifont_bind(const Handle h) { H_DEREF(h, UniFont, f); @@ -349,7 +349,7 @@ void glwprintf(const wchar_t* fmt, ...) } -LibError unifont_stringsize(const Handle h, const wchar_t* text, int& width, int& height) +Status unifont_stringsize(const Handle h, const wchar_t* text, int& width, int& height) { H_DEREF(h, UniFont, f); diff --git a/source/lib/res/graphics/unifont.h b/source/lib/res/graphics/unifont.h index 2172a95164..bdf5ce26dd 100644 --- a/source/lib/res/graphics/unifont.h +++ b/source/lib/res/graphics/unifont.h @@ -46,14 +46,14 @@ extern Handle unifont_load(const PIVFS& vfs, const VfsPath& pathname, size_t fla * Release a handle to a previously loaded font * (subject to reference counting). **/ -extern LibError unifont_unload(Handle& h); +extern Status unifont_unload(Handle& h); /** * Use a font for all subsequent glwprintf() calls. * * Must be called before any glwprintf(). **/ -extern LibError unifont_bind(Handle h); +extern Status unifont_bind(Handle h); /** * Output text at current OpenGL modelview pos. @@ -90,7 +90,7 @@ extern void glvwprintf(const wchar_t* fmt, va_list args) VWPRINTF_ARGS(1); * * note: This is intended for the GUI (hence Unicode). **/ -LibError unifont_stringsize(const Handle h, const wchar_t* text, int& width, int& height); +Status unifont_stringsize(const Handle h, const wchar_t* text, int& width, int& height); /** * @return height [pixels] of the font. diff --git a/source/lib/res/h_mgr.cpp b/source/lib/res/h_mgr.cpp index fbcc0202b0..8afeab7266 100644 --- a/source/lib/res/h_mgr.cpp +++ b/source/lib/res/h_mgr.cpp @@ -273,7 +273,7 @@ static HDATA* h_data_tag_type(const Handle h, const H_Type type) // idx and hd are undefined if we fail. // called by h_alloc only. -static LibError alloc_idx(ssize_t& idx, HDATA*& hd) +static Status alloc_idx(ssize_t& idx, HDATA*& hd) { // we already know the first free entry if(first_free != -1) @@ -326,7 +326,7 @@ have_idx:; } -static LibError free_idx(ssize_t idx) +static Status free_idx(ssize_t idx) { if(first_free == -1 || idx < first_free) first_free = idx; @@ -424,7 +424,7 @@ static void warn_if_invalid(HDATA* hd) // the others have no invariants we could check. // have the resource validate its user_data - LibError err = vtbl->validate(hd->user); + Status err = vtbl->validate(hd->user); ENSURE(err == INFO::OK); // make sure empty space in control block isn't touched @@ -439,7 +439,7 @@ static void warn_if_invalid(HDATA* hd) } -static LibError type_validate(H_Type type) +static Status type_validate(H_Type type) { if(!type) WARN_RETURN(ERR::INVALID_PARAM); @@ -498,9 +498,9 @@ static Handle reuse_existing_handle(uintptr_t key, H_Type type, size_t flags) } -static LibError call_init_and_reload(Handle h, H_Type type, HDATA* hd, const PIVFS& vfs, const VfsPath& pathname, va_list* init_args) +static Status call_init_and_reload(Handle h, H_Type type, HDATA* hd, const PIVFS& vfs, const VfsPath& pathname, va_list* init_args) { - LibError err = INFO::OK; + Status err = INFO::OK; H_VTbl* vtbl = type; // exact same thing but for clarity // init @@ -531,7 +531,7 @@ static Handle alloc_new_handle(H_Type type, const PIVFS& vfs, const VfsPath& pat { ssize_t idx; HDATA* hd; - RETURN_ERR(alloc_idx(idx, hd)); + RETURN_STATUS_IF_ERR(alloc_idx(idx, hd)); // (don't want to do this before the add-reference exit, // so as not to waste tags for often allocated handles.) @@ -552,7 +552,7 @@ static Handle alloc_new_handle(H_Type type, const PIVFS& vfs, const VfsPath& pat if(key && !hd->unique) key_add(key, h); - LibError err = call_init_and_reload(h, type, hd, vfs, pathname, init_args); + Status err = call_init_and_reload(h, type, hd, vfs, pathname, init_args); if(err < 0) goto fail; @@ -561,7 +561,7 @@ static Handle alloc_new_handle(H_Type type, const PIVFS& vfs, const VfsPath& pat fail: // reload failed; free the handle hd->keep_open = 0; // disallow caching (since contents are invalid) - (void)h_free(h, type); // (h_free already does WARN_ERR) + (void)h_free(h, type); // (h_free already does WARN_IF_ERR) // note: since some uses will always fail (e.g. loading sounds if // g_Quickstart), do not complain here. @@ -572,13 +572,13 @@ fail: // any further params are passed to type's init routine Handle h_alloc(H_Type type, const PIVFS& vfs, const VfsPath& pathname, size_t flags, ...) { - RETURN_ERR(type_validate(type)); + RETURN_STATUS_IF_ERR(type_validate(type)); const uintptr_t key = fnv_hash(pathname.string().c_str(), pathname.string().length()*sizeof(pathname.string()[0])); // see if we can reuse an existing handle Handle h = reuse_existing_handle(key, type, flags); - RETURN_ERR(h); + RETURN_STATUS_IF_ERR(h); // .. successfully reused the handle; refcount increased if(h > 0) return h; @@ -587,14 +587,14 @@ Handle h_alloc(H_Type type, const PIVFS& vfs, const VfsPath& pathname, size_t fl va_start(args, flags); h = alloc_new_handle(type, vfs, pathname, key, flags, &args); va_end(args); - return h; // alloc_new_handle already does CHECK_ERR + return h; // alloc_new_handle already does WARN_RETURN_STATUS_IF_ERR } //----------------------------------------------------------------------------- // currently cannot fail. -static LibError h_free_idx(ssize_t idx, HDATA* hd) +static Status h_free_idx(ssize_t idx, HDATA* hd) { // only decrement if refcount not already 0. if(hd->refs > 0) @@ -638,7 +638,7 @@ static LibError h_free_idx(ssize_t idx, HDATA* hd) } -LibError h_free(Handle& h, H_Type type) +Status h_free(Handle& h, H_Type type) { ssize_t idx = h_idx(h); HDATA* hd = h_data_tag_type(h, type); @@ -699,7 +699,7 @@ VfsPath h_filename(const Handle h) // TODO: what if iterating through all handles is too slow? -LibError h_reload(const PIVFS& vfs, const VfsPath& pathname) +Status h_reload(const PIVFS& vfs, const VfsPath& pathname) { const u32 key = fnv_hash(pathname.string().c_str(), pathname.string().length()*sizeof(pathname.string()[0])); @@ -715,7 +715,7 @@ LibError h_reload(const PIVFS& vfs, const VfsPath& pathname) hd->type->dtor(hd->user); } - LibError ret = INFO::OK; + Status ret = INFO::OK; // now reload all affected handles for(ssize_t i = 0; i <= last_in_use; i++) @@ -726,7 +726,7 @@ LibError h_reload(const PIVFS& vfs, const VfsPath& pathname) Handle h = handle(i, hd->tag); - LibError err = hd->type->reload(hd->user, vfs, hd->pathname, h); + Status err = hd->type->reload(hd->user, vfs, hd->pathname, h); // don't stop if an error is encountered - try to reload them all. if(err < 0) { @@ -755,7 +755,7 @@ Handle h_find(H_Type type, uintptr_t key) // to later close the object. // this is used when reinitializing the sound engine - // at that point, all (cached) OpenAL resources must be freed. -LibError h_force_free(Handle h, H_Type type) +Status h_force_free(Handle h, H_Type type) { // require valid index; ignore tag; type checked below. HDATA* hd = h_data_no_tag(h); @@ -807,7 +807,7 @@ int h_get_refcnt(Handle h) static ModuleInitState initState; -static LibError Init() +static Status Init() { return INFO::OK; } diff --git a/source/lib/res/h_mgr.h b/source/lib/res/h_mgr.h index 1e2ea4dd80..1e061fd457 100644 --- a/source/lib/res/h_mgr.h +++ b/source/lib/res/h_mgr.h @@ -133,7 +133,7 @@ reload: does all initialization of the resource that requires its source file. called after init; also after dtor every time the file is reloaded. -static LibError Type_reload(Res1* r, const VfsPath& pathname, Handle); +static Status Type_reload(Res1* r, const VfsPath& pathname, Handle); { // already loaded; done if(r->data) @@ -191,7 +191,7 @@ makes sure the resource control block is in a valid state. returns 0 if all is well, or a negative error code. called automatically when the Handle is dereferenced or freed. -static LibError Type_validate(const Res1* r); +static Status Type_validate(const Res1* r); { const int permissible_flags = 0x01; if(debug_IsPointerBogus(r->data)) @@ -209,7 +209,7 @@ Handle res1_load(const VfsPath& pathname, int my_flags) return h_alloc(H_Res1, pathname, 0, my_flags); } -LibError res1_free(Handle& h) +Status res1_free(Handle& h) { // control block is automatically zeroed after this. return h_free(h, H_Res1); @@ -296,10 +296,10 @@ but- has to handle variable params, a bit ugly struct H_VTbl { void (*init)(void* user, va_list); - LibError (*reload)(void* user, const PIVFS& vfs, const VfsPath& pathname, Handle); + Status (*reload)(void* user, const PIVFS& vfs, const VfsPath& pathname, Handle); void (*dtor)(void* user); - LibError (*validate)(const void* user); - LibError (*to_string)(const void* user, wchar_t* buf); + Status (*validate)(const void* user); + Status (*to_string)(const void* user, wchar_t* buf); size_t user_size; const wchar_t* name; }; @@ -309,17 +309,17 @@ typedef H_VTbl* H_Type; #define H_TYPE_DEFINE(type)\ /* forward decls */\ static void type##_init(type*, va_list);\ - static LibError type##_reload(type*, const PIVFS&, const VfsPath&, Handle);\ + static Status type##_reload(type*, const PIVFS&, const VfsPath&, Handle);\ static void type##_dtor(type*);\ - static LibError type##_validate(const type*);\ - static LibError type##_to_string(const type*, wchar_t* buf);\ + static Status type##_validate(const type*);\ + static Status type##_to_string(const type*, wchar_t* buf);\ static H_VTbl V_##type =\ {\ (void (*)(void*, va_list))type##_init,\ - (LibError (*)(void*, const PIVFS&, const VfsPath&, Handle))type##_reload,\ + (Status (*)(void*, const PIVFS&, const VfsPath&, Handle))type##_reload,\ (void (*)(void*))type##_dtor,\ - (LibError (*)(const void*))type##_validate,\ - (LibError (*)(const void*, wchar_t*))type##_to_string,\ + (Status (*)(const void*))type##_validate,\ + (Status (*)(const void*, wchar_t*))type##_to_string,\ sizeof(type), /* control block size */\ WIDEN(#type) /* name */\ };\ @@ -344,7 +344,7 @@ typedef H_VTbl* H_Type; /* h already indicates an error - return immediately to pass back*/\ /* that specific error, rather than only ERR::INVALID_HANDLE*/\ if(h < 0)\ - WARN_RETURN((LibError)h);\ + WARN_RETURN((Status)h);\ type* const var = H_USER_DATA(h, type);\ if(!var)\ WARN_RETURN(ERR::INVALID_HANDLE); @@ -395,7 +395,7 @@ const size_t H_STRING_LEN = 256; // dtor is associated with type and called when the object is freed. // handle data is initialized to 0; optionally, a pointer to it is returned. extern Handle h_alloc(H_Type type, const PIVFS& vfs, const VfsPath& pathname, size_t flags = 0, ...); -extern LibError h_free(Handle& h, H_Type type); +extern Status h_free(Handle& h, H_Type type); // find and return a handle by key (typically filename hash) @@ -413,7 +413,7 @@ extern void* h_user_data(Handle h, H_Type type); extern VfsPath h_filename(Handle h); -extern LibError h_reload(const PIVFS& vfs, const VfsPath& pathname); +extern Status h_reload(const PIVFS& vfs, const VfsPath& pathname); // force the resource to be freed immediately, even if cached. // tag is not checked - this allows the first Handle returned @@ -421,7 +421,7 @@ extern LibError h_reload(const PIVFS& vfs, const VfsPath& pathname); // to later close the object. // this is used when reinitializing the sound engine - // at that point, all (cached) OpenAL resources must be freed. -extern LibError h_force_free(Handle h, H_Type type); +extern Status h_force_free(Handle h, H_Type type); // increment Handle 's reference count. // only meant to be used for objects that free a Handle in their dtor, diff --git a/source/lib/res/sound/ogg.cpp b/source/lib/res/sound/ogg.cpp index 8f519654ef..ffe4e7e043 100644 --- a/source/lib/res/sound/ogg.cpp +++ b/source/lib/res/sound/ogg.cpp @@ -9,7 +9,7 @@ #include "lib/file/file_system_util.h" -static LibError LibErrorFromVorbis(int err) +static Status LibErrorFromVorbis(int err) { switch(err) { @@ -196,7 +196,7 @@ public: { } - LibError Open() + Status Open() { ov_callbacks callbacks; callbacks.read_func = Adapter::Read; @@ -225,7 +225,7 @@ public: return info->rate; } - virtual LibError GetNextChunk(u8* buffer, size_t size) + virtual Status GetNextChunk(u8* buffer, size_t size) { // we may have to call ov_read multiple times because it // treats the buffer size "as a limit and not a request" @@ -238,14 +238,14 @@ public: int bitstream; // unused const int ret = ov_read(&vf, (char*)buffer+bytesRead, int(size-bytesRead), isBigEndian, wordSize, isSigned, &bitstream); if(ret == 0) // EOF - return (LibError)bytesRead; + return (Status)bytesRead; else if(ret < 0) WARN_RETURN(LibErrorFromVorbis(ret)); else // success { bytesRead += ret; if(bytesRead == size) - return (LibError)bytesRead; + return (Status)bytesRead; } } } @@ -259,25 +259,25 @@ private: //----------------------------------------------------------------------------- -LibError OpenOggStream(const OsPath& pathname, OggStreamPtr& stream) +Status OpenOggStream(const OsPath& pathname, OggStreamPtr& stream) { PFile file(new File); - RETURN_ERR(file->Open(pathname, L'r')); + RETURN_STATUS_IF_ERR(file->Open(pathname, L'r')); shared_ptr > tmp(new OggStreamImpl(VorbisFileAdapter(file))); - RETURN_ERR(tmp->Open()); + RETURN_STATUS_IF_ERR(tmp->Open()); stream = tmp; return INFO::OK; } -LibError OpenOggNonstream(const PIVFS& vfs, const VfsPath& pathname, OggStreamPtr& stream) +Status OpenOggNonstream(const PIVFS& vfs, const VfsPath& pathname, OggStreamPtr& stream) { shared_ptr contents; size_t size; - RETURN_ERR(vfs->LoadFile(pathname, contents, size)); + RETURN_STATUS_IF_ERR(vfs->LoadFile(pathname, contents, size)); shared_ptr > tmp(new OggStreamImpl(VorbisBufferAdapter(contents, size))); - RETURN_ERR(tmp->Open()); + RETURN_STATUS_IF_ERR(tmp->Open()); stream = tmp; return INFO::OK; } diff --git a/source/lib/res/sound/ogg.h b/source/lib/res/sound/ogg.h index e561bc2b93..bd45940408 100644 --- a/source/lib/res/sound/ogg.h +++ b/source/lib/res/sound/ogg.h @@ -12,19 +12,19 @@ public: virtual ALsizei SamplingRate() = 0; /** - * @return bytes read (<= size) or a (negative) LibError + * @return bytes read (<= size) or a (negative) Status **/ - virtual LibError GetNextChunk(u8* buffer, size_t size) = 0; + virtual Status GetNextChunk(u8* buffer, size_t size) = 0; }; typedef shared_ptr OggStreamPtr; -extern LibError OpenOggStream(const OsPath& pathname, OggStreamPtr& stream); +extern Status OpenOggStream(const OsPath& pathname, OggStreamPtr& stream); /** * A non-streaming OggStream (reading the whole file in advance) * that can cope with archived/compressed files. */ -extern LibError OpenOggNonstream(const PIVFS& vfs, const VfsPath& pathname, OggStreamPtr& stream); +extern Status OpenOggNonstream(const PIVFS& vfs, const VfsPath& pathname, OggStreamPtr& stream); #endif // INCLUDED_OGG diff --git a/source/lib/res/sound/snd_mgr.cpp b/source/lib/res/sound/snd_mgr.cpp index 3baca70130..9046f28c17 100644 --- a/source/lib/res/sound/snd_mgr.cpp +++ b/source/lib/res/sound/snd_mgr.cpp @@ -98,11 +98,11 @@ static bool al_initialized = false; // used by snd_dev_set to reset OpenAL after device has been changed. -static LibError al_reinit(); +static Status al_reinit(); // used by al_shutdown to free all VSrc and SndData objects, respectively, // so that they release their OpenAL sources and buffers. -static LibError list_free_all(); +static Status list_free_all(); static void hsd_list_free_all(); @@ -147,7 +147,7 @@ static const char* alc_dev_name = 0; * tell OpenAL to use the specified device in future. * * @param alc_new_dev_name Device name. - * @return LibError + * @return Status * * name = 0 reverts to OpenAL's default choice, which will also * be used if this routine is never called. @@ -163,7 +163,7 @@ static const char* alc_dev_name = 0; * re-initialize with the new device. that's fairly time-consuming, * so preferably call this routine before sounds are loaded. */ -LibError snd_dev_set(const char* alc_new_dev_name) +Status snd_dev_set(const char* alc_new_dev_name) { // requesting a specific device if(alc_new_dev_name) @@ -216,11 +216,11 @@ static void alc_shutdown() /** * Ready OpenAL for use by setting up a device and context. * - * @return LibError + * @return Status */ -static LibError alc_init() +static Status alc_init() { - LibError ret = INFO::OK; + Status ret = INFO::OK; #if WIN_LOADLIBRARY_HACK HMODULE dlls[3]; @@ -329,9 +329,9 @@ static void al_listener_latch() * * @param gain Modifier: must be non-negative; * 1 -> unattenuated, 0.5 -> -6 dB, 0 -> silence. - * @return LibError + * @return Status */ -LibError snd_set_master_gain(float gain) +Status snd_set_master_gain(float gain) { if(gain < 0) WARN_RETURN(ERR::INVALID_PARAM); @@ -572,9 +572,9 @@ static void al_src_free(ALuint al_src) * implementation- defined ceiling anyway. * * @param limit max. number of sources - * @return LibError + * @return Status */ -LibError snd_set_max_voices(size_t limit) +Status snd_set_max_voices(size_t limit) { // valid if cap is legit (less than what we allocated in al_src_init), // or if al_src_init hasn't been called yet. note: we accept anything @@ -604,15 +604,15 @@ LibError snd_set_max_voices(size_t limit) * master OpenAL init; makes sure all subsystems are ready for use. * called from each snd_open; no harm if called more than once. * - * @return LibError + * @return Status */ -static LibError al_init() +static Status al_init() { // only take action on first call, OR when re-initializing. if(al_initialized) return INFO::OK; - RETURN_ERR(alc_init()); + RETURN_STATUS_IF_ERR(alc_init()); al_initialized = true; @@ -659,9 +659,9 @@ static void al_shutdown() /** * re-initialize OpenAL. currently only required for changing devices. * - * @return LibError + * @return Status */ -static LibError al_reinit() +static Status al_reinit() { // not yet initialized. settings have been saved, and will be // applied by the component init routines called from al_init. @@ -681,9 +681,9 @@ static bool snd_disabled = false; * extra layer on top of al_init that allows 'disabling' sound. * called from each snd_open. * - * @return LibError from al_init, or ERR::AGAIN if sound disabled + * @return Status from al_init, or ERR::AGAIN if sound disabled */ -static LibError snd_init() +static Status snd_init() { // (note: each VSrc_reload and therefore snd_open will fail) if(snd_disabled) @@ -693,7 +693,7 @@ static LibError snd_init() } -LibError snd_disable(bool disabled) +Status snd_disable(bool disabled) { snd_disabled = disabled; @@ -733,12 +733,12 @@ static const char* devs; * * may be called each time the device list is needed. * - * @return LibError; always successful unless the requisite device + * @return Status; always successful unless the requisite device * enumeration extension isn't available. in the latter case, * a "cannot enum device" message should be presented to the user, * and snd_dev_set need not be called; OpenAL will use its default device. */ -LibError snd_dev_prepare_enum() +Status snd_dev_prepare_enum() { if(alcIsExtensionPresent(0, (alcString)"ALC_ENUMERATION_EXT") != AL_TRUE) WARN_RETURN(ERR::NO_SYS); @@ -897,25 +897,25 @@ static void SndData_dtor(SndData* sd) sd->ogg.reset(); } -static LibError SndData_reload(SndData* sd, const PIVFS& vfs, const VfsPath& pathname, Handle hsd) +static Status SndData_reload(SndData* sd, const PIVFS& vfs, const VfsPath& pathname, Handle hsd) { #if 0 // HACK: streaming disabled because it breaks archives // (OGG streaming requires a real POSIX pathname - see OpenOggStream) fs::wpath real_pathname; - RETURN_ERR(vfs->GetRealPath(pathname, real_pathname)); + RETURN_STATUS_IF_ERR(vfs->GetRealPath(pathname, real_pathname)); // currently only supports OGG; WAV is no longer supported. writing our own loader is infeasible // due to a seriously watered down spec with many incompatible variants. // pulling in an external library (e.g. freealut) is deemed not worth the // effort - OGG should be better in all cases. - RETURN_ERR(OpenOggStream(real_pathname, sd->ogg)); + RETURN_STATUS_IF_ERR(OpenOggStream(real_pathname, sd->ogg)); const size_t size = fs::file_size(real_pathname); #else - RETURN_ERR(OpenOggNonstream(vfs, pathname, sd->ogg)); + RETURN_STATUS_IF_ERR(OpenOggNonstream(vfs, pathname, sd->ogg)); FileInfo fileInfo; - RETURN_ERR(vfs->GetFileInfo(pathname, &fileInfo)); + RETURN_STATUS_IF_ERR(vfs->GetFileInfo(pathname, &fileInfo)); const size_t size = fileInfo.Size(); #endif @@ -930,8 +930,8 @@ static LibError SndData_reload(SndData* sd, const PIVFS& vfs, const VfsPath& pat if(sd->type == SD_CLIP) { std::vector data(50*MiB); // max. size of any clip (anything larger should be streamed) - const LibError ret = sd->ogg->GetNextChunk(&data[0], data.size()); - RETURN_ERR(ret); + const Status ret = sd->ogg->GetNextChunk(&data[0], data.size()); + RETURN_STATUS_IF_ERR(ret); const size_t size = (size_t)ret; ENSURE(size != 0); // must have read something ENSURE(size != data.size()); // shouldn't be limited by buffer size @@ -949,7 +949,7 @@ static LibError SndData_reload(SndData* sd, const PIVFS& vfs, const VfsPath& pat return INFO::OK; } -static LibError SndData_validate(const SndData* sd) +static Status SndData_validate(const SndData* sd) { if(sd->al_fmt == 0) WARN_RETURN(ERR::_11); @@ -971,7 +971,7 @@ static LibError SndData_validate(const SndData* sd) } -static LibError SndData_to_string(const SndData* sd, wchar_t* buf) +static Status SndData_to_string(const SndData* sd, wchar_t* buf) { const wchar_t* type = (sd->type == SD_CLIP)? L"clip" : L"stream"; swprintf_s(buf, H_STRING_LEN, L"%ls; al_buf=%d", type, sd->al_buf); @@ -982,7 +982,7 @@ static LibError SndData_to_string(const SndData* sd, wchar_t* buf) /** * open and return a handle to a sound file's data. * - * @return Handle or LibError on failure + * @return Handle or Status on failure */ static Handle snd_data_load(const PIVFS& vfs, const VfsPath& pathname) { @@ -993,9 +993,9 @@ static Handle snd_data_load(const PIVFS& vfs, const VfsPath& pathname) * Free the sound. * * @param hsd Handle to SndData; set to 0 afterwards. - * @return LibError + * @return Status */ -static LibError snd_data_free(Handle& hsd) +static Status snd_data_free(Handle& hsd) { return h_free(hsd, H_SndData); } @@ -1008,11 +1008,11 @@ static LibError snd_data_free(Handle& hsd) * * @param hsd Handle to SndData. * @param al_buf buffer name. - * @return LibError, most commonly: + * @return Status, most commonly: * INFO::CB_CONTINUE = buffer has been returned; more are expected to be available. * INFO::OK = buffer has been returned but is the last one (EOF). */ -static LibError snd_data_buf_get(Handle hsd, ALuint& al_buf) +static Status snd_data_buf_get(Handle hsd, ALuint& al_buf) { H_DEREF(hsd, SndData, sd); if(sd->type == SD_CLIP) @@ -1024,8 +1024,8 @@ static LibError snd_data_buf_get(Handle hsd, ALuint& al_buf) if(!sd->ogg) WARN_RETURN(ERR::INVALID_HANDLE); u8 data[maxBufferSize]; - const LibError ret = sd->ogg->GetNextChunk(data, maxBufferSize); - RETURN_ERR(ret); + const Status ret = sd->ogg->GetNextChunk(data, maxBufferSize); + RETURN_STATUS_IF_ERR(ret); const size_t size = (size_t)ret; al_buf = al_buf_alloc(data, (ALsizei)size, sd->al_fmt, sd->al_freq); @@ -1038,9 +1038,9 @@ static LibError snd_data_buf_get(Handle hsd, ALuint& al_buf) * * @param hsd Handle to SndData. * @param al_buf buffer name - * @return LibError + * @return Status */ -static LibError snd_data_buf_free(Handle hsd, ALuint al_buf) +static Status snd_data_buf_free(Handle hsd, ALuint al_buf) { H_DEREF(hsd, SndData, sd); @@ -1265,7 +1265,7 @@ static void VSrc_init(VSrc* vs, va_list UNUSED(args)) } static void list_remove(VSrc* vs); -static LibError vsrc_reclaim(VSrc* vs); +static Status vsrc_reclaim(VSrc* vs); static void VSrc_dtor(VSrc* vs) { @@ -1281,16 +1281,16 @@ static void VSrc_dtor(VSrc* vs) (void)snd_data_free(vs->hsd); } -static LibError VSrc_reload(VSrc* vs, const PIVFS& vfs, const VfsPath& pathname, Handle hvs) +static Status VSrc_reload(VSrc* vs, const PIVFS& vfs, const VfsPath& pathname, Handle hvs) { // cannot wait till play(), need to init here: // must load OpenAL so that snd_data_load can check for OGG extension. - LibError err = snd_init(); + Status err = snd_init(); // .. don't complain if sound is disabled; fail silently. if(err == ERR::AGAIN) return err; // .. catch genuine errors during init. - RETURN_ERR(err); + RETURN_STATUS_IF_ERR(err); VfsPath dataPathname; @@ -1299,7 +1299,7 @@ static LibError VSrc_reload(VSrc* vs, const PIVFS& vfs, const VfsPath& pathname, if(pathname.Extension() == L".txt") { shared_ptr buf; size_t size; - RETURN_ERR(vfs->LoadFile(pathname, buf, size)); + RETURN_STATUS_IF_ERR(vfs->LoadFile(pathname, buf, size)); std::wistringstream def(std::wstring((wchar_t*)buf.get(), (int)size)); def >> dataPathname; @@ -1322,7 +1322,7 @@ static LibError VSrc_reload(VSrc* vs, const PIVFS& vfs, const VfsPath& pathname, vsrc_reclaim(vs); vs->hsd = snd_data_load(vfs, dataPathname); - RETURN_ERR(vs->hsd); + RETURN_STATUS_IF_ERR(vs->hsd); return INFO::OK; } @@ -1332,7 +1332,7 @@ static bool IsValidBoolean(ALboolean b) return (b == AL_FALSE || b == AL_TRUE); } -static LibError VSrc_validate(const VSrc* vs) +static Status VSrc_validate(const VSrc* vs) { // al_src can legitimately be 0 (if vs is low-pri) if(vs->flags & ~VS_ALL_FLAGS) @@ -1348,7 +1348,7 @@ static LibError VSrc_validate(const VSrc* vs) return INFO::OK; } -static LibError VSrc_to_string(const VSrc* vs, wchar_t* buf) +static Status VSrc_to_string(const VSrc* vs, wchar_t* buf) { swprintf_s(buf, H_STRING_LEN, L"al_src = %d", vs->al_src); return INFO::OK; @@ -1363,7 +1363,7 @@ static LibError VSrc_to_string(const VSrc* vs, wchar_t* buf) * sound file name and its gain (0.0 .. 1.0). * otherwise, it is taken to be the sound file name and * gain is set to the default of 1.0 (no attenuation). - * @return Handle or LibError on failure + * @return Handle or Status on failure */ Handle snd_open(const PIVFS& vfs, const VfsPath& pathname) { @@ -1379,9 +1379,9 @@ Handle snd_open(const PIVFS& vfs, const VfsPath& pathname) * this is provided for completeness only. * * @param hvs Handle to VSrc. will be set to 0 afterwards. - * @return LibError + * @return Status */ -LibError snd_free(Handle& hvs) +Status snd_free(Handle& hvs) { if(!hvs) return INFO::OK; @@ -1499,7 +1499,7 @@ static void vsrc_free(VSrc* vs) snd_free(vs->hvs); } -static LibError list_free_all() +static Status list_free_all() { list_foreach(vsrc_free); return INFO::OK; @@ -1612,7 +1612,7 @@ public: { } - LibError operator()(VSrc* vs) const + Status operator()(VSrc* vs) const { if(!vs->HasSource()) return INFO::OK; @@ -1649,8 +1649,8 @@ public: { // get next buffer ALuint al_buf; - LibError ret = snd_data_buf_get(vs->hsd, al_buf); - RETURN_ERR(ret); + Status ret = snd_data_buf_get(vs->hsd, al_buf); + RETURN_STATUS_IF_ERR(ret); if(ret == INFO::OK) // no further buffers will be forthcoming vs->flags |= VS_EOF; @@ -1676,9 +1676,9 @@ private: * Try to give the VSrc an AL source so that it can (re)start playing. * called by snd_play and voice management. * - * @return LibError (ERR::FAIL if no AL source is available) + * @return Status (ERR::FAIL if no AL source is available) */ -static LibError vsrc_grant(VSrc* vs) +static Status vsrc_grant(VSrc* vs) { if(vs->HasSource()) // already playing return INFO::OK; @@ -1709,7 +1709,7 @@ static LibError vsrc_grant(VSrc* vs) * called when closing the VSrc, or when voice management decides * this VSrc must yield to others of higher priority. */ -static LibError vsrc_reclaim(VSrc* vs) +static Status vsrc_reclaim(VSrc* vs) { if(!vs->HasSource()) return ERR::FAIL; // NOWARN @@ -1761,9 +1761,9 @@ static LibError vsrc_reclaim(VSrc* vs) * @param static_pri (min 0 .. max 1, default 0) indicates which sounds are * considered more important; this is attenuated by distance to the * listener (see snd_update). - * @return LibError + * @return Status */ -LibError snd_play(Handle hvs, float static_pri) +Status snd_play(Handle hvs, float static_pri) { H_DEREF(hvs, VSrc, vs); @@ -1792,9 +1792,9 @@ LibError snd_play(Handle hvs, float static_pri) * @param x,y,z coordinates (interpretation: see below) * @param relative if true, (x,y,z) is treated as relative to the listener; * otherwise, it is the position in world coordinates (default). - * @return LibError + * @return Status */ -LibError snd_set_pos(Handle hvs, float x, float y, float z, bool relative) +Status snd_set_pos(Handle hvs, float x, float y, float z, bool relative) { H_DEREF(hvs, VSrc, vs); @@ -1816,9 +1816,9 @@ LibError snd_set_pos(Handle hvs, float x, float y, float z, bool relative) * @param hvs Handle to VSrc * @param gain modifier; must be non-negative; * 1 -> unattenuated, 0.5 -> -6 dB, 0 -> silence. - * @return LibError + * @return Status */ -LibError snd_set_gain(Handle hvs, float gain) +Status snd_set_gain(Handle hvs, float gain) { H_DEREF(hvs, VSrc, vs); @@ -1847,9 +1847,9 @@ LibError snd_set_gain(Handle hvs, float gain) * @param hvs Handle to VSrc * @param pitch shift: 1.0 means no change; each doubling/halving equals a * pitch shift of +/-12 semitones (one octave). zero is invalid. - * @return LibError + * @return Status */ -LibError snd_set_pitch(Handle hvs, float pitch) +Status snd_set_pitch(Handle hvs, float pitch) { H_DEREF(hvs, VSrc, vs); @@ -1878,7 +1878,7 @@ LibError snd_set_pitch(Handle hvs, float pitch) * * @param hvs Handle to VSrc */ -LibError snd_set_loop(Handle hvs, bool loop) +Status snd_set_loop(Handle hvs, bool loop) { H_DEREF(hvs, VSrc, vs); @@ -1916,9 +1916,9 @@ LibError snd_set_loop(Handle hvs, bool loop) * http://www.transom.org/tools/editing_mixing/200309.stupidfadetricks.html * you can also pass FT_ABORT to stop fading (if in progress) and * set gain to the final_gain parameter passed here. - * @return LibError + * @return Status */ -LibError snd_fade(Handle hvs, float initial_gain, float final_gain, +Status snd_fade(Handle hvs, float initial_gain, float final_gain, float length, FadeType type) { H_DEREF(hvs, VSrc, vs); @@ -2026,7 +2026,7 @@ static void reclaim(VSrc* vs) * update voice management, i.e. recalculate priority and assign AL sources. * no-op if OpenAL not yet initialized. */ -static LibError vm_update() +static Status vm_update() { list_prune_removed(); @@ -2056,9 +2056,9 @@ static LibError vm_update() * world isn't initialized yet. * @param dir view direction * @param up up vector - * @return LibError + * @return Status */ -LibError snd_update(const float* pos, const float* dir, const float* up) +Status snd_update(const float* pos, const float* dir, const float* up) { // there's no sense in updating anything if we weren't initialized // yet (most notably, if sound is disabled). we check for this to diff --git a/source/lib/res/sound/snd_mgr.h b/source/lib/res/sound/snd_mgr.h index df6b0888c2..935610b919 100644 --- a/source/lib/res/sound/snd_mgr.h +++ b/source/lib/res/sound/snd_mgr.h @@ -99,11 +99,11 @@ terminology * snd_dev_next). * may be called each time the device list is needed. * - * @return LibError; fails iff the requisite OpenAL extension isn't available. + * @return Status; fails iff the requisite OpenAL extension isn't available. * in that case, a "cannot enum device" message should be displayed, but * snd_dev_set need not be called; OpenAL will use its default device. **/ -extern LibError snd_dev_prepare_enum(); +extern Status snd_dev_prepare_enum(); /** * get next device name in list. @@ -137,9 +137,9 @@ extern const char* snd_dev_next(); * re-initialize with the new device. that's fairly time-consuming, * so preferably call this routine before sounds are loaded. * - * @return LibError (the status returned by OpenAL re-init) + * @return Status (the status returned by OpenAL re-init) **/ -extern LibError snd_dev_set(const char* alc_new_dev_name); +extern Status snd_dev_set(const char* alc_new_dev_name); /** * Set maximum number of voices to play simultaneously; @@ -147,9 +147,9 @@ extern LibError snd_dev_set(const char* alc_new_dev_name); * * @param limit Maximum number of voices. Ignored if higher than * an implementation-defined limit anyway. - * @return LibError + * @return Status **/ -extern LibError snd_set_max_voices(size_t limit); +extern Status snd_set_max_voices(size_t limit); /** * set amplitude modifier, which is effectively applied to all sounds. @@ -157,9 +157,9 @@ extern LibError snd_set_max_voices(size_t limit); * * @param gain amplitude modifier. must be non-negative; * 1 -> unattenuated, 0.5 -> -6 dB, 0 -> silence. - * @return LibError + * @return Status **/ -extern LibError snd_set_master_gain(float gain); +extern Status snd_set_master_gain(float gain); // @@ -176,7 +176,7 @@ extern LibError snd_set_master_gain(float gain); * its gain (0.0 .. 1.0). * Otherwise, it is taken to be the sound file name and * gain is set to the default of 1.0 (no attenuation). - * @return Handle or LibError + * @return Handle or Status **/ extern Handle snd_open(const PIVFS& vfs, const VfsPath& pathname); @@ -187,9 +187,9 @@ extern Handle snd_open(const PIVFS& vfs, const VfsPath& pathname); * this API is provided for completeness only. * * @param hvs Handle to sound instance. Zeroed afterwards. - * @return LibError + * @return Status **/ -extern LibError snd_free(Handle& hvs); +extern Status snd_free(Handle& hvs); /** * Start playing the sound. @@ -206,9 +206,9 @@ extern LibError snd_free(Handle& hvs); * voices are available). the static priority is attenuated by * distance to the listener; see snd_update. * - * @return LibError + * @return Status **/ -extern LibError snd_play(Handle hvs, float static_pri = 0.0f); +extern Status snd_play(Handle hvs, float static_pri = 0.0f); /** * Change 3d position of the sound source. @@ -220,9 +220,9 @@ extern LibError snd_play(Handle hvs, float static_pri = 0.0f); * @param x,y,z * @param relative treat (x,y,z) as relative to the listener; * if false (the default), it is the position in world coordinates. - * @return LibError + * @return Status **/ -extern LibError snd_set_pos(Handle hvs, float x, float y, float z, bool relative = false); +extern Status snd_set_pos(Handle hvs, float x, float y, float z, bool relative = false); /** * change gain (amplitude modifier) of the sound source. @@ -233,9 +233,9 @@ extern LibError snd_set_pos(Handle hvs, float x, float y, float z, bool relative * * @param gain amplitude modifier. must be non-negative; * 1 -\> unattenuated, 0.5 -\> -6 dB, 0 -\> silence. - * @return LibError + * @return Status **/ -extern LibError snd_set_gain(Handle hs, float gain); +extern Status snd_set_gain(Handle hs, float gain); /** * change pitch shift of the sound source. @@ -245,9 +245,9 @@ extern LibError snd_set_gain(Handle hs, float gain); * * @param pitch shift: 1.0 means no change; each doubling/halving equals a * pitch shift of +/-12 semitones (one octave). zero is invalid. - * @return LibError + * @return Status **/ -extern LibError snd_set_pitch(Handle hs, float pitch); +extern Status snd_set_pitch(Handle hs, float pitch); /** * Enable/disable looping on the sound source. @@ -264,9 +264,9 @@ extern LibError snd_set_pitch(Handle hs, float pitch); * * @param hvs Handle to the sound. * @param loop Boolean to enable/disable lopping on the sound. - * @return LibError + * @return Status **/ -extern LibError snd_set_loop(Handle hvs, bool loop); +extern Status snd_set_loop(Handle hvs, bool loop); /// types of fade in/out operations enum FadeType @@ -312,9 +312,9 @@ enum FadeType * It is safe to start another fade on the same sound source while * one is already in progress; the old one will be discarded. * - * @return LibError + * @return Status **/ -extern LibError snd_fade(Handle hvs, float initial_gain, float final_gain, +extern Status snd_fade(Handle hvs, float initial_gain, float final_gain, float length, FadeType type); @@ -338,9 +338,9 @@ extern LibError snd_fade(Handle hvs, float initial_gain, float final_gain, * will be applied and subsequent sound load / play requests will work. * * @param disabled - * @return LibError + * @return Status **/ -extern LibError snd_disable(bool disabled); +extern Status snd_disable(bool disabled); /** * Perform housekeeping (e.g. streaming); call once a frame. @@ -351,9 +351,9 @@ extern LibError snd_disable(bool disabled); * @param pos listener's position * @param dir listener view direction * @param up listener's local up vector - * @return LibError + * @return Status **/ -extern LibError snd_update(const float* pos, const float* dir, const float* up); +extern Status snd_update(const float* pos, const float* dir, const float* up); /** * find out if a sound is still playing diff --git a/source/lib/secure_crt.cpp b/source/lib/secure_crt.cpp index 1b421c5015..2aca542827 100644 --- a/source/lib/secure_crt.cpp +++ b/source/lib/secure_crt.cpp @@ -35,7 +35,7 @@ // we were included from wsecure_crt.cpp; skip all stuff that // must only be done once. #ifndef WSECURE_CRT -ERROR_ASSOCIATE(ERR::STRING_NOT_TERMINATED, L"Invalid string (no 0 terminator found in buffer)", -1); +STATUS_DEFINE(ERR, STRING_NOT_TERMINATED, L"Invalid string (no 0 terminator found in buffer)", -1); #endif diff --git a/source/lib/secure_crt.h b/source/lib/secure_crt.h index 44a02b6b19..fb84c5ee76 100644 --- a/source/lib/secure_crt.h +++ b/source/lib/secure_crt.h @@ -29,11 +29,11 @@ #include -#include "lib/lib_errors.h" +#include "lib/status.h" namespace ERR { - const LibError STRING_NOT_TERMINATED = -100600; + const Status STRING_NOT_TERMINATED = -100600; } // if the platform lacks a secure CRT implementation, we'll provide one. diff --git a/source/lib/self_test.h b/source/lib/self_test.h index b48081661b..889616a99c 100644 --- a/source/lib/self_test.h +++ b/source/lib/self_test.h @@ -182,7 +182,7 @@ extern bool self_test_active; // for convenience, to avoid having to include all of these manually -#include "lib/lib_errors.h" +#include "lib/status.h" #include "lib/os_path.h" #include "lib/posix/posix.h" diff --git a/source/lib/status.cpp b/source/lib/status.cpp new file mode 100644 index 0000000000..88a94dcad6 --- /dev/null +++ b/source/lib/status.cpp @@ -0,0 +1,170 @@ +/* Copyright (c) 2011 Wildfire Games + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * error handling system: defines status codes, translates them to/from + * other schemes (e.g. errno), associates them with descriptive text, + * simplifies propagating errors / checking if functions failed. + */ + +#include "precompiled.h" +#include "lib/status.h" + +#include +#include + +#include "lib/posix/posix_errno.h" + + +// linked list (most recent first) +// note: no memory is allocated, all nodes are static instances. +// +// rationale: don't use a std::map. we don't care about lookup speed, +// dynamic allocation would be ugly, and returning a local static object +// from a function doesn't work, either (the compiler generates calls to +// atexit, which leads to disaster since we're sometimes called before +// the CRT has initialized) +static StatusDefinition* definitions; + +int StatusAddDefinition(StatusDefinition* def) +{ + // insert at front of list + def->next = definitions; + definitions = def; + + return 0; // stored in dummy variable +} + + +static const StatusDefinition* DefinitionFromStatus(Status status) +{ + for(const StatusDefinition* def = definitions; def; def = def->next) + { + if(def->status == status) + return def; + } + + return 0; +} + + +static const StatusDefinition* DefinitionFromErrno(int errno_equivalent) +{ + for(const StatusDefinition* def = definitions; def; def = def->next) + { + if(def->errno_equivalent == errno_equivalent) + return def; + } + + return 0; +} + + +wchar_t* StatusDescription(Status status, wchar_t* buf, size_t max_chars) +{ + const StatusDefinition* def = DefinitionFromStatus(status); + if(def) + { + wcscpy_s(buf, max_chars, def->description); + return buf; + } + + swprintf_s(buf, max_chars, L"Unknown error (%d, 0x%X)", (int)status, (unsigned int)status); + return buf; +} + + +int ErrnoFromStatus(Status status) +{ + const StatusDefinition* def = DefinitionFromStatus(status); + if(def && def->errno_equivalent != -1) + return def->errno_equivalent; + + // the set of errnos in wposix.h doesn't have an "unknown error". + // we use this one as a default because it's not expected to come up often. + return EPERM; +} + + +Status StatusFromErrno() +{ + const StatusDefinition* def = DefinitionFromErrno(errno); + return def? def->status : ERR::FAIL; +} + + +//----------------------------------------------------------------------------- + +// INFO::OK doesn't really need a string because calling StatusDescription(0) +// should never happen, but we'll play it safe. +STATUS_DEFINE(INFO, OK, L"(but return value was 0 which indicates success)", -1); +STATUS_DEFINE(ERR, FAIL, L"Function failed (no details available)", -1); + +STATUS_DEFINE(INFO, CB_CONTINUE, L"Continue (not an error)", -1); +STATUS_DEFINE(INFO, SKIPPED, L"Skipped (not an error)", -1); +STATUS_DEFINE(INFO, CANNOT_HANDLE, L"Cannot handle (not an error)", -1); +STATUS_DEFINE(INFO, ALL_COMPLETE, L"All complete (not an error)", -1); +STATUS_DEFINE(INFO, ALREADY_EXISTS, L"Already exists (not an error)", -1); + +STATUS_DEFINE(ERR, LOGIC, L"Logic error in code", -1); +STATUS_DEFINE(ERR, TIMED_OUT, L"Timed out", -1); +STATUS_DEFINE(ERR, REENTERED, L"Single-call function was reentered", -1); +STATUS_DEFINE(ERR, CORRUPTED, L"File/memory data is corrupted", -1); +STATUS_DEFINE(ERR, VERSION, L"Version mismatch", -1); + +STATUS_DEFINE(ERR, INVALID_PARAM, L"Invalid function argument", EINVAL); +STATUS_DEFINE(ERR, INVALID_HANDLE, L"Invalid Handle (argument)", -1); +STATUS_DEFINE(ERR, BUF_SIZE, L"Buffer argument too small", -1); +STATUS_DEFINE(ERR, AGAIN, L"Try again later", -1); +STATUS_DEFINE(ERR, LIMIT, L"Fixed limit exceeded", -1); +STATUS_DEFINE(ERR, NO_SYS, L"OS doesn't provide a required API", -1); +STATUS_DEFINE(ERR, NOT_IMPLEMENTED, L"Feature currently not implemented", ENOSYS); +STATUS_DEFINE(ERR, NOT_SUPPORTED, L"Feature isn't and won't be supported", -1); +STATUS_DEFINE(ERR, NO_MEM, L"Not enough memory", ENOMEM); + +STATUS_DEFINE(ERR, _1, L"Case 1", -1); +STATUS_DEFINE(ERR, _2, L"Case 2", -1); +STATUS_DEFINE(ERR, _3, L"Case 3", -1); +STATUS_DEFINE(ERR, _4, L"Case 4", -1); +STATUS_DEFINE(ERR, _5, L"Case 5", -1); +STATUS_DEFINE(ERR, _6, L"Case 6", -1); +STATUS_DEFINE(ERR, _7, L"Case 7", -1); +STATUS_DEFINE(ERR, _8, L"Case 8", -1); +STATUS_DEFINE(ERR, _9, L"Case 9", -1); +STATUS_DEFINE(ERR, _11, L"Case 11", -1); +STATUS_DEFINE(ERR, _12, L"Case 12", -1); +STATUS_DEFINE(ERR, _13, L"Case 13", -1); +STATUS_DEFINE(ERR, _14, L"Case 14", -1); +STATUS_DEFINE(ERR, _15, L"Case 15", -1); +STATUS_DEFINE(ERR, _16, L"Case 16", -1); +STATUS_DEFINE(ERR, _17, L"Case 17", -1); +STATUS_DEFINE(ERR, _18, L"Case 18", -1); +STATUS_DEFINE(ERR, _19, L"Case 19", -1); +STATUS_DEFINE(ERR, _21, L"Case 21", -1); +STATUS_DEFINE(ERR, _22, L"Case 22", -1); +STATUS_DEFINE(ERR, _23, L"Case 23", -1); +STATUS_DEFINE(ERR, _24, L"Case 24", -1); +STATUS_DEFINE(ERR, _25, L"Case 25", -1); +STATUS_DEFINE(ERR, _26, L"Case 26", -1); +STATUS_DEFINE(ERR, _27, L"Case 27", -1); +STATUS_DEFINE(ERR, _28, L"Case 28", -1); +STATUS_DEFINE(ERR, _29, L"Case 29", -1); diff --git a/source/lib/status.h b/source/lib/status.h new file mode 100644 index 0000000000..9ef5461dbd --- /dev/null +++ b/source/lib/status.h @@ -0,0 +1,430 @@ +/* Copyright (c) 2010 Wildfire Games + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * error handling system: defines status codes, translates them to/from + * other schemes (e.g. errno), associates them with descriptive text, + * simplifies propagating errors / checking if functions failed. + */ + +/** + +Error handling system + + +Why Error Codes? +---------------- + +To convey information about what failed, the alternatives are unique +integral codes and direct pointers to descriptive text. Both occupy the +same amount of space, but codes are easier to internationalize. + + +Method of Propagating Errors +---------------------------- + +When a low-level function has failed, this must be conveyed to the +higher-level application logic across several functions on the call stack. +There are two alternatives: +1) check at each call site whether a function failed; + if so, return to the caller. +2) throw an exception. + +We will discuss the advantages and disadvantages of exceptions, +which are the opposites of call site checking. +- performance: they shouldn't be used in time-critical code. +- predictability: exceptions can come up almost anywhere, + so it is hard to say what execution path will be taken. +- interoperability: not compatible with other languages. ++ readability: cleans up code by separating application logic and + error handling. however, this is also a disadvantage because it + may be difficult to see at a glance if a piece of code does + error checking at all. ++ visibility: errors are more likely to be seen than relying on + callers to check return codes; less reliant on discipline. + +Both have their place. Our recommendation is to throw error code +exceptions when checking call sites and propagating errors becomes tedious. +However, inter-module boundaries should always return error codes for +interoperability with other languages. + + +Simplifying Call-Site Checking +------------------------------ + +As mentioned above, this approach requires discipline. We provide +"enforcer" macros to simplify this task by propagating errors to +the calling function. + +Consider the following example: + Status status = doWork(); + if(status != INFO::OK) + return status; +This can be replaced by: + RETURN_STATUS_IF_ERR(doWork()); + +This provides a visible sign that the code handles errors but +reduces clutter. + + +When to warn the user? +---------------------- + +When a function fails, there are 2 places we can raise a warning: +as soon as the error condition is known, or higher on the call stack. + +We prefer the former because it is easier to ensure that all +possible return paths have been covered: search for all "return ERR::*" +or "return StatusFrom*" that are not followed by a "// NOWARN" comment. +The latter approach also risks multiple warnings along the +call stack for the same error. + +Note the special case of "validator" functions that e.g. verify the +state of an object: we now discuss pros/cons of just returning errors +without warning, and having their callers take care of that. ++ they typically have many return paths (-> increased code size) +- this is balanced by validators that have many call sites. +- we want all return statements wrapped for consistency and + easily checking if any were forgotten +- adding // NOWARN to each validator return statement would be tedious. +- there is no advantage to checking at the call site; the call stack + indicates which caller of the validator failed anyway. +Validator functions should therefore also use WARN_RETURN. + + +Numbering Scheme +---------------- + +Each module header defines its own error codes to avoid a full rebuild +whenever a new code is added. + +Error codes start at -100000 (warnings are positive, but the +corresponding negative value should not be used to avoid confusion). +This scheme avoids collisions with all other known error codes. + +Each header gets 100 possible values; the tens value may be +used to denote groups within that header. + +The subsystem is denoted by the ten-thousands digit: +0 general +1 file +2 res (resource management) +3 sysdep (system-dependent) +4 win (Windows-specific) + +To summarize: +/-1SHHCC (S=subsystem, HH=header, CC=code number) + +10 general + 00CC misc + 03CC path + 04CC debug + 05CC debug_stl + 06CC secure_crt + 07CC wchar + +11 file + 01CC vfs + 03CC file + 04CC archive + +12 res + 01CC tex + 02CC ogl_shader + +13 sysdep + 00CC cpu + 01CC os_cpu + +14 win + 00CC whrt +**/ + +#ifndef INCLUDED_STATUS +#define INCLUDED_STATUS + +#include "lib/lib_api.h" + +// an integral type allows defining error codes in individual headers, +// but is not as type-safe as an enum. use Lint's 'strong type' checking +// to catch errors such as Status Func() { return 1; }. +// this must be signed and 64-bit because some functions may multiplex +// file offsets/sizes and Status in their return value. +typedef i64 Status; + +// opaque - do not access its fields! +// note: must be defined here because clients instantiate them; +// fields cannot be made private due to POD requirements. +struct StatusDefinition // POD +{ + Status status; + + // must remain valid until end of program. + const wchar_t* description; + + StatusDefinition* next; + + int errno_equivalent; // (-1 if there is none) +}; + +/** + * associating a Status with a description and errno equivalent. + * @return dummy integer to allow calling via static initializer. + **/ +LIB_API int StatusAddDefinition(StatusDefinition*); + +// associate a Status with a description and errno equivalent. +// Invoke this at file or function scope. +#define STATUS_DEFINE(namespaceName, identifier, description, errno_equivalent)\ + static StatusDefinition identifier##_def = { namespaceName::identifier, description, NULL, errno_equivalent };\ + static int identifier##_dummy = StatusAddDefinition(&identifier##_def) + + +/** + * generate textual description of a Status. + * + * @param buf destination buffer (allows generating strings with + * the code's numerical value if no definition is found) + * @param max_chars size of buffer [characters] + * @return buf (allows using this function in expressions) + **/ +LIB_API wchar_t* StatusDescription(Status status, wchar_t* buf, size_t max_chars); + + +//----------------------------------------------------------------------------- + +// conversion to/from other error code definitions. +// note: other conversion routines (e.g. to/from Win32) are implemented in +// the corresponding modules to keep this header portable. + +/** + * @return the errno equivalent of a Status. + * + * used in wposix - underlying functions return Status but must be + * translated to errno at e.g. the mmap interface level. higher-level code + * that calls mmap will in turn convert back to Status. + **/ +extern int ErrnoFromStatus(Status status); + +/** + * @return Status equivalent of errno, or ERR::FAIL if there's no equivalent. + * should only be called directly after a POSIX function indicates failure; + * errno may otherwise still be set from another error cause. + **/ +extern Status StatusFromErrno(); + + +//----------------------------------------------------------------------------- + +// warn and return a status. use when an error is first detected to +// begin propagating it to callers. +#define WARN_RETURN(status)\ + do\ + {\ + DEBUG_WARN_ERR(status);\ + return status;\ + }\ + while(0) + +// warn if expression is negative, i.e. an error. +// (this macro is more convenient than ENSURE) +#define WARN_IF_ERR(expression)\ + do\ + {\ + const Status status_ = (expression);\ + if(status_ < 0)\ + DEBUG_WARN_ERR(status_);\ + }\ + while(0) + +// return expression if it is negative, i.e. pass on errors to +// the caller. use when failures are common/expected. +#define RETURN_STATUS_IF_ERR(expression)\ + do\ + {\ + const Status status_ = (expression);\ + if(status_ < 0)\ + return status_;\ + }\ + while(0) + +// warn and return expression if it is negative. +// use if a function doesn't raise warnings when it returns errors. +#define WARN_RETURN_STATUS_IF_ERR(expression)\ + do\ + {\ + const Status status_ = (expression);\ + if(status_ < 0)\ + {\ + DEBUG_WARN_ERR(status_);\ + return status_;\ + }\ + }\ + while(0) + +// warn and throw expression if it is negative. use to propagate +// errors from within constructors. +#define THROW_STATUS_IF_ERR(expression)\ + do\ + {\ + const Status status_ = (expression);\ + if(status_ < 0)\ + {\ + DEBUG_WARN_ERR(status_);\ + throw status_;\ + }\ + }\ + while(0) + +// return 0 if expression is negative. use in functions that return pointers. +#define RETURN_0_IF_ERR(expression)\ + do\ + {\ + const Status status_ = (expression);\ + if(status_ < 0)\ + return 0;\ + }\ + while(0) + +// return expression if it evaluates to something other than +// INFO::CB_CONTINUE. use when invoking callbacks. +#define RETURN_IF_NOT_CONTINUE(expression)\ + do\ + {\ + const Status status_ = (expression);\ + if(status_ != INFO::CB_CONTINUE)\ + return status_;\ + }\ + while(0) + +// warn if expression is false, i.e. zero. +#define WARN_IF_FALSE(expression)\ + do\ + {\ + if(!(expression))\ + debug_warn(L"FYI: WARN_IF_FALSE reports that a function failed. Feel free to ignore or suppress this warning.");\ + }\ + while(0) + +// warn and return 0 if expression is false, i.e. zero. +#define WARN_RETURN_0_IF_FALSE(expression)\ + do\ + {\ + if(!(expression))\ + {\ + debug_warn(L"FYI: WARN_RETURN_0_IF_FALSE reports that a function failed. Feel free to ignore or suppress this warning.");\ + return 0;\ + }\ + }\ + while(0) + + +//----------------------------------------------------------------------------- + +namespace INFO +{ + const Status OK = 0; + + // note: these values are > 100 to allow multiplexing them with + // coroutine return values, which return completion percentage. + + // function is a callback and indicates that it can (but need not + // necessarily) be called again. + const Status CB_CONTINUE = +100000; + + // notify caller that nothing was done. + const Status SKIPPED = +100001; + + // function is incapable of doing the requested task with the given inputs. + // this implies SKIPPED, but also conveys a bit more information. + const Status CANNOT_HANDLE = +100002; + + // function is meant to be called repeatedly, and now indicates that + // all jobs are complete. + const Status ALL_COMPLETE = +100003; + + // (returned e.g. when inserting into container) + const Status ALREADY_EXISTS = +100004; +} // namespace INFO + +namespace ERR +{ + const Status FAIL = -1; + + // general + const Status LOGIC = -100010; + const Status TIMED_OUT = -100011; + const Status REENTERED = -100012; + const Status CORRUPTED = -100013; + const Status VERSION = -100014; + + // function arguments + const Status INVALID_PARAM = -100020; + const Status INVALID_HANDLE = -100021; + const Status BUF_SIZE = -100022; + + // system limitations + const Status AGAIN = -100030; + const Status LIMIT = -100031; + const Status NO_SYS = -100032; + const Status NOT_IMPLEMENTED = -100033; + const Status NOT_SUPPORTED = -100034; + const Status NO_MEM = -100035; + + // these are for cases where we just want a distinct value to display and + // a symbolic name + string would be overkill (e.g. the various + // test cases in a validate() call). they are shared between multiple + // functions; when something fails, the stack trace will show in which + // one it was => these errors are unambiguous. + // there are 3 tiers - 1..9 are used in most functions, 11..19 are + // used in a function that calls another validator and 21..29 are + // for for functions that call 2 other validators (this avoids + // ambiguity as to which error actually happened where) + const Status _1 = -100101; + const Status _2 = -100102; + const Status _3 = -100103; + const Status _4 = -100104; + const Status _5 = -100105; + const Status _6 = -100106; + const Status _7 = -100107; + const Status _8 = -100108; + const Status _9 = -100109; + const Status _11 = -100111; + const Status _12 = -100112; + const Status _13 = -100113; + const Status _14 = -100114; + const Status _15 = -100115; + const Status _16 = -100116; + const Status _17 = -100117; + const Status _18 = -100118; + const Status _19 = -100119; + const Status _21 = -100121; + const Status _22 = -100122; + const Status _23 = -100123; + const Status _24 = -100124; + const Status _25 = -100125; + const Status _26 = -100126; + const Status _27 = -100127; + const Status _28 = -100128; + const Status _29 = -100129; +} // namespace ERR + +#endif // #ifndef INCLUDED_STATUS diff --git a/source/lib/sysdep/arch/ia32/ia32.cpp b/source/lib/sysdep/arch/ia32/ia32.cpp index 2ee21fcda9..78425882fb 100644 --- a/source/lib/sysdep/arch/ia32/ia32.cpp +++ b/source/lib/sysdep/arch/ia32/ia32.cpp @@ -95,7 +95,7 @@ static bool IsCall(void* ret_addr, void*& target) return false; } -LibError ia32_GetCallTarget(void* ret_addr, void*& target) +Status ia32_GetCallTarget(void* ret_addr, void*& target) { if(IsCall(ret_addr, target)) { diff --git a/source/lib/sysdep/arch/ia32/ia32.h b/source/lib/sysdep/arch/ia32/ia32.h index 43c199de3e..f8320a8e6b 100644 --- a/source/lib/sysdep/arch/ia32/ia32.h +++ b/source/lib/sysdep/arch/ia32/ia32.h @@ -41,6 +41,6 @@ * * this function is used for walking the call stack. **/ -LIB_API LibError ia32_GetCallTarget(void* ret_addr, void*& target); +LIB_API Status ia32_GetCallTarget(void* ret_addr, void*& target); #endif // #ifndef INCLUDED_IA32 diff --git a/source/lib/sysdep/arch/x86_x64/cache.cpp b/source/lib/sysdep/arch/x86_x64/cache.cpp index 97ded947af..73d9ea8e7d 100644 --- a/source/lib/sysdep/arch/x86_x64/cache.cpp +++ b/source/lib/sysdep/arch/x86_x64/cache.cpp @@ -602,7 +602,7 @@ static void DetectCacheAndTLB(size_t& descriptorFlags) } // namespace CPUID2 -static LibError DetectCacheAndTLB() +static Status DetectCacheAndTLB() { // ensure all cache entries are initialized (DetectCache* might not set them all) for(size_t idxLevel = 0; idxLevel < x86_x64_Cache::maxLevels; idxLevel++) diff --git a/source/lib/sysdep/arch/x86_x64/topology.cpp b/source/lib/sysdep/arch/x86_x64/topology.cpp index eb31cc9c79..543e41ce3b 100644 --- a/source/lib/sysdep/arch/x86_x64/topology.cpp +++ b/source/lib/sysdep/arch/x86_x64/topology.cpp @@ -147,7 +147,7 @@ static bool AreApicIdsUnique(u8* apicIds, size_t numIds) static u8 apicIdStorage[os_cpu_MaxProcessors]; static const u8* apicIds; // = apicIdStorage, or 0 if IDs invalid -static LibError InitApicIds() +static Status InitApicIds() { struct StoreEachProcessorsApicId { @@ -218,7 +218,7 @@ struct CpuTopology // POD static CpuTopology cpuTopology; static ModuleInitState cpuInitState; -static LibError InitCpuTopology() +static Status InitCpuTopology() { const size_t maxLogicalPerCore = MaxLogicalPerCore(); const size_t maxCoresPerPackage = MaxCoresPerPackage(); @@ -511,7 +511,7 @@ struct CacheTopology // POD static CacheTopology cacheTopology; static ModuleInitState cacheInitState; -static LibError InitCacheTopology() +static Status InitCacheTopology() { const u8* apicIds = ApicIds(); DetermineCachesProcessorMask(apicIds, cacheTopology.cachesProcessorMask, cacheTopology.numCaches); diff --git a/source/lib/sysdep/arch/x86_x64/x86_x64.cpp b/source/lib/sysdep/arch/x86_x64/x86_x64.cpp index 75c7b505cc..d066a6dab2 100644 --- a/source/lib/sysdep/arch/x86_x64/x86_x64.cpp +++ b/source/lib/sysdep/arch/x86_x64/x86_x64.cpp @@ -88,7 +88,7 @@ static void cpuid(x86_x64_CpuidRegs* regs) static u32 cpuid_maxFunction; static u32 cpuid_maxExtendedFunction; -static LibError InitCpuid() +static Status InitCpuid() { x86_x64_CpuidRegs regs = { 0 }; @@ -128,7 +128,7 @@ static u32 caps[4]; static ModuleInitState capsInitState; -static LibError InitCaps() +static Status InitCaps() { x86_x64_CpuidRegs regs = { 0 }; regs.eax = 1; @@ -177,7 +177,7 @@ void x86_x64_caps(u32* d0, u32* d1, u32* d2, u32* d3) static x86_x64_Vendors vendor; -static LibError InitVendor() +static Status InitVendor() { x86_x64_CpuidRegs regs = { 0 }; regs.eax = 0; @@ -220,7 +220,7 @@ static size_t model; static size_t family; static ModuleInitState signatureInitState; -static LibError InitSignature() +static Status InitSignature() { x86_x64_CpuidRegs regs = { 0 }; regs.eax = 1; @@ -287,7 +287,7 @@ private: // 3 calls x 4 registers x 4 bytes = 48 + 0-terminator static char identifierString[48+1]; -static LibError InitIdentifierString() +static Status InitIdentifierString() { // get brand string (if available) char* pos = identifierString; diff --git a/source/lib/sysdep/clipboard.h b/source/lib/sysdep/clipboard.h index 1d88d8a726..8a7485827a 100644 --- a/source/lib/sysdep/clipboard.h +++ b/source/lib/sysdep/clipboard.h @@ -21,7 +21,7 @@ */ // "copy" text into the clipboard. replaces previous contents. -extern LibError sys_clipboard_set(const wchar_t* text); +extern Status sys_clipboard_set(const wchar_t* text); // allow "pasting" from clipboard. returns the current contents if they // can be represented as text, otherwise 0. @@ -31,4 +31,4 @@ extern wchar_t* sys_clipboard_get(); // frees memory used by , which must have been returned by // sys_clipboard_get. see note above. -extern LibError sys_clipboard_free(wchar_t* copy); +extern Status sys_clipboard_free(wchar_t* copy); diff --git a/source/lib/sysdep/cpu.cpp b/source/lib/sysdep/cpu.cpp index c706504a2e..599e7a6529 100644 --- a/source/lib/sysdep/cpu.cpp +++ b/source/lib/sysdep/cpu.cpp @@ -27,9 +27,9 @@ #include "precompiled.h" #include "lib/sysdep/cpu.h" -ERROR_ASSOCIATE(ERR::CPU_FEATURE_MISSING, L"This CPU doesn't support a required feature", -1); -ERROR_ASSOCIATE(ERR::CPU_UNKNOWN_OPCODE, L"Disassembly failed", -1); -ERROR_ASSOCIATE(ERR::CPU_UNKNOWN_VENDOR, L"CPU vendor unknown", -1); +STATUS_DEFINE(ERR, CPU_FEATURE_MISSING, L"This CPU doesn't support a required feature", -1); +STATUS_DEFINE(ERR, CPU_UNKNOWN_OPCODE, L"Disassembly failed", -1); +STATUS_DEFINE(ERR, CPU_UNKNOWN_VENDOR, L"CPU vendor unknown", -1); // ensure the actual pointer size matches expectations on the most common diff --git a/source/lib/sysdep/cpu.h b/source/lib/sysdep/cpu.h index 09fefe9d53..c63add2b66 100644 --- a/source/lib/sysdep/cpu.h +++ b/source/lib/sysdep/cpu.h @@ -32,9 +32,9 @@ namespace ERR { - const LibError CPU_FEATURE_MISSING = -130000; - const LibError CPU_UNKNOWN_OPCODE = -130001; - const LibError CPU_UNKNOWN_VENDOR = -130002; + const Status CPU_FEATURE_MISSING = -130000; + const Status CPU_UNKNOWN_OPCODE = -130001; + const Status CPU_UNKNOWN_VENDOR = -130002; } diff --git a/source/lib/sysdep/cursor.h b/source/lib/sysdep/cursor.h index cd4b328158..573f8d036b 100644 --- a/source/lib/sysdep/cursor.h +++ b/source/lib/sysdep/cursor.h @@ -41,7 +41,7 @@ typedef void* sys_cursor; * @param cursor Is 0 if the return code indicates failure, otherwise * a valid cursor that must be sys_cursor_free-ed when no longer needed. **/ -extern LibError sys_cursor_create(int w, int h, void* bgra_img, int hx, int hy, sys_cursor* cursor); +extern Status sys_cursor_create(int w, int h, void* bgra_img, int hx, int hy, sys_cursor* cursor); /** * Create a transparent cursor (used to hide the system cursor). @@ -49,26 +49,26 @@ extern LibError sys_cursor_create(int w, int h, void* bgra_img, int hx, int hy, * @param cursor is 0 if the return code indicates failure, otherwise * a valid cursor that must be sys_cursor_free-ed when no longer needed. **/ -extern LibError sys_cursor_create_empty(sys_cursor* cursor); +extern Status sys_cursor_create_empty(sys_cursor* cursor); /** * override the current system cursor. * * @param cursor can be 0 to restore the default. **/ -extern LibError sys_cursor_set(sys_cursor cursor); +extern Status sys_cursor_set(sys_cursor cursor); /** * destroy the indicated cursor and frees its resources. * * @param cursor if currently in use, the default cursor is restored first. **/ -extern LibError sys_cursor_free(sys_cursor cursor); +extern Status sys_cursor_free(sys_cursor cursor); /** * reset any cached cursor data. * on some systems, this is needed when resetting the SDL video subsystem. **/ -extern LibError sys_cursor_reset(); +extern Status sys_cursor_reset(); #endif // #ifndef INCLUDED_SYSDEP_CURSOR diff --git a/source/lib/sysdep/dir_watch.h b/source/lib/sysdep/dir_watch.h index 007b8b509f..375748fc9c 100644 --- a/source/lib/sysdep/dir_watch.h +++ b/source/lib/sysdep/dir_watch.h @@ -49,7 +49,7 @@ typedef shared_ptr PDirWatch; * convenient to store PDirWatch there instead of creating a second * tree structure here. **/ -LIB_API LibError dir_watch_Add(const OsPath& path, PDirWatch& dirWatch); +LIB_API Status dir_watch_Add(const OsPath& path, PDirWatch& dirWatch); class DirWatchNotification { @@ -87,7 +87,7 @@ typedef std::vector DirWatchNotifications; * return all pending directory watch notifications. * * @param notifications receives any pending notifications in unspecified order. - * @return LibError (INFO::OK doesn't imply notifications were returned) + * @return Status (INFO::OK doesn't imply notifications were returned) * * note: the run time of this function is independent of the number of * directory watches and number of files. @@ -96,6 +96,6 @@ typedef std::vector DirWatchNotifications; * typically want to receive change notifications at a single point, * rather than deal with the complexity of asynchronous notifications. **/ -LIB_API LibError dir_watch_Poll(DirWatchNotifications& notifications); +LIB_API Status dir_watch_Poll(DirWatchNotifications& notifications); #endif // #ifndef INCLUDED_DIR_WATCH diff --git a/source/lib/sysdep/filesystem.h b/source/lib/sysdep/filesystem.h index 2935b4b817..1064f0d275 100644 --- a/source/lib/sysdep/filesystem.h +++ b/source/lib/sysdep/filesystem.h @@ -40,14 +40,13 @@ struct WDIR; struct wdirent { // note: SUSv3 describes this as a "char array" but of unspecified size. - // since that precludes using sizeof(), we may as well declare as a - // pointer to avoid copying in the implementation. + // we declare as a pointer to avoid having to copy the string. wchar_t* d_name; }; extern WDIR* wopendir(const OsPath& path); -extern struct wdirent* wreaddir(WDIR*); +extern wdirent* wreaddir(WDIR*); // return status for the file returned by the last successful // wreaddir call from the given directory stream. @@ -72,11 +71,6 @@ extern int wclosedir(WDIR*); // thus speeding up loading and reducing resource usage.) #define O_NO_AIO_NP 0x20000 -// POSIX flags not supported by the underlying Win32 _wsopen_s: -#if OS_WIN -#define O_NONBLOCK 0x1000000 -#endif - extern int wopen(const OsPath& pathname, int oflag); extern int wopen(const OsPath& pathname, int oflag, mode_t mode); extern int wclose(int fd); diff --git a/source/lib/sysdep/gfx.h b/source/lib/sysdep/gfx.h index 99db3c991b..15d4a35259 100644 --- a/source/lib/sysdep/gfx.h +++ b/source/lib/sysdep/gfx.h @@ -63,12 +63,12 @@ extern void gfx_detect(); * @param xres, yres (optional out) resolution [pixels] * @param bpp (optional out) bits per pixel * @param freq (optional out) vertical refresh rate [Hz] - * @return LibError; INFO::OK unless: some information was requested + * @return Status; INFO::OK unless: some information was requested * (i.e. pointer is non-NULL) but cannot be returned. * on failure, the outputs are all left unchanged (they are * assumed initialized to defaults) **/ -extern LibError gfx_get_video_mode(int* xres, int* yres, int* bpp, int* freq); +extern Status gfx_get_video_mode(int* xres, int* yres, int* bpp, int* freq); /** * get monitor dimensions. @@ -77,10 +77,10 @@ extern LibError gfx_get_video_mode(int* xres, int* yres, int* bpp, int* freq); * * @param width_mm (out) screen width [mm] * @param height_mm (out) screen height [mm] - * @return LibError. on failure, the outputs are all left unchanged + * @return Status. on failure, the outputs are all left unchanged * on failure, the outputs are all left unchanged (they are * assumed initialized to defaults) **/ -extern LibError gfx_get_monitor_size(int& width_mm, int& height_mm); +extern Status gfx_get_monitor_size(int& width_mm, int& height_mm); #endif // #ifndef INCLUDED_GFX diff --git a/source/lib/sysdep/os/win/mahaf.cpp b/source/lib/sysdep/os/win/mahaf.cpp index fa629bb5be..42550875d1 100644 --- a/source/lib/sysdep/os/win/mahaf.cpp +++ b/source/lib/sysdep/os/win/mahaf.cpp @@ -50,12 +50,8 @@ static u32 ReadPort(u16 port, u8 numBytes) DWORD bytesReturned; LPOVERLAPPED ovl = 0; // synchronous - BOOL ok = DeviceIoControl(hAken, (DWORD)IOCTL_AKEN_READ_PORT, &in, sizeof(in), &out, sizeof(out), &bytesReturned, ovl); - if(!ok) - { - WARN_WIN32_ERR; - return 0; - } + const BOOL ok = DeviceIoControl(hAken, (DWORD)IOCTL_AKEN_READ_PORT, &in, sizeof(in), &out, sizeof(out), &bytesReturned, ovl); + WARN_RETURN_0_IF_FALSE(ok); ENSURE(bytesReturned == sizeof(out)); return out.value; @@ -133,12 +129,8 @@ volatile void* mahaf_MapPhysicalMemory(uintptr_t physicalAddress, size_t numByte DWORD bytesReturned; LPOVERLAPPED ovl = 0; // synchronous - BOOL ok = DeviceIoControl(hAken, (DWORD)IOCTL_AKEN_MAP, &in, sizeof(in), &out, sizeof(out), &bytesReturned, ovl); - if(!ok) - { - WARN_WIN32_ERR; - return 0; - } + const BOOL ok = DeviceIoControl(hAken, (DWORD)IOCTL_AKEN_MAP, &in, sizeof(in), &out, sizeof(out), &bytesReturned, ovl); + WARN_RETURN_0_IF_FALSE(ok); ENSURE(bytesReturned == sizeof(out)); volatile void* virtualAddress = (volatile void*)(uintptr_t)out.virtualAddress; @@ -168,12 +160,8 @@ static u64 ReadRegister(DWORD ioctl, u64 reg) DWORD bytesReturned; LPOVERLAPPED ovl = 0; // synchronous - BOOL ok = DeviceIoControl(hAken, ioctl, &in, sizeof(in), &out, sizeof(out), &bytesReturned, ovl); - if(!ok) - { - WARN_WIN32_ERR; - return 0; - } + const BOOL ok = DeviceIoControl(hAken, ioctl, &in, sizeof(in), &out, sizeof(out), &bytesReturned, ovl); + WARN_RETURN_0_IF_FALSE(ok); ENSURE(bytesReturned == sizeof(out)); return out.value; @@ -338,7 +326,7 @@ static OsPath DriverPathname() //----------------------------------------------------------------------------- -static LibError Init() +static Status Init() { if(wutil_HasCommandLineArgument(L"-wNoMahaf")) return ERR::NOT_SUPPORTED; // NOWARN @@ -369,7 +357,7 @@ static void Shutdown() static ModuleInitState initState; -LibError mahaf_Init() +Status mahaf_Init() { return ModuleInit(&initState, Init); } diff --git a/source/lib/sysdep/os/win/mahaf.h b/source/lib/sysdep/os/win/mahaf.h index bea5a4fff3..e2134165a4 100644 --- a/source/lib/sysdep/os/win/mahaf.h +++ b/source/lib/sysdep/os/win/mahaf.h @@ -42,7 +42,7 @@ LIB_API bool mahaf_IsPhysicalMappingDangerous(); -LIB_API LibError mahaf_Init(); +LIB_API Status mahaf_Init(); LIB_API void mahaf_Shutdown(); LIB_API u8 mahaf_ReadPort8 (u16 port); diff --git a/source/lib/sysdep/os/win/tests/test_wdbg_sym.h b/source/lib/sysdep/os/win/tests/test_wdbg_sym.h index 65cb6a92cf..86aedb9def 100644 --- a/source/lib/sysdep/os/win/tests/test_wdbg_sym.h +++ b/source/lib/sysdep/os/win/tests/test_wdbg_sym.h @@ -42,7 +42,7 @@ static void* callers[100]; static size_t numCallers; -static LibError OnFrame(const _tagSTACKFRAME64* frame, uintptr_t UNUSED(cbData)) +static Status OnFrame(const _tagSTACKFRAME64* frame, uintptr_t UNUSED(cbData)) { callers[numCallers++] = (void*)frame->AddrPC.Offset; return INFO::CB_CONTINUE; @@ -293,7 +293,7 @@ public: for(size_t i = 0; i < 3; i++) { wchar_t func1[DBG_SYMBOL_LEN], func2[DBG_SYMBOL_LEN]; - LibError ret; + Status ret; ret = debug_ResolveSymbol(callers[i], func1, 0, 0); TS_ASSERT_OK(ret); ret = debug_ResolveSymbol(funcAddresses[i], func2, 0, 0); diff --git a/source/lib/sysdep/os/win/wclipboard.cpp b/source/lib/sysdep/os/win/wclipboard.cpp index 8a3eced7c1..862c314ddd 100644 --- a/source/lib/sysdep/os/win/wclipboard.cpp +++ b/source/lib/sysdep/os/win/wclipboard.cpp @@ -27,7 +27,7 @@ #include "lib/sysdep/os/win/wutil.h" // caller is responsible for freeing *hMem. -static LibError SetClipboardText(const wchar_t* text, HGLOBAL* hMem) +static Status SetClipboardText(const wchar_t* text, HGLOBAL* hMem) { const size_t numChars = wcslen(text); *hMem = GlobalAlloc(GMEM_MOVEABLE, (numChars+1) * sizeof(wchar_t)); @@ -48,7 +48,7 @@ static LibError SetClipboardText(const wchar_t* text, HGLOBAL* hMem) } // "copy" text into the clipboard. replaces previous contents. -LibError sys_clipboard_set(const wchar_t* text) +Status sys_clipboard_set(const wchar_t* text) { // note: MSDN claims that the window handle must not be 0; // that does actually work on WinXP, but we'll play it safe. @@ -57,7 +57,7 @@ LibError sys_clipboard_set(const wchar_t* text) EmptyClipboard(); HGLOBAL hMem; - LibError ret = SetClipboardText(text, &hMem); + Status ret = SetClipboardText(text, &hMem); CloseClipboard(); @@ -107,7 +107,7 @@ wchar_t* sys_clipboard_get() // frees memory used by , which must have been returned by // sys_clipboard_get. see note above. -LibError sys_clipboard_free(wchar_t* text) +Status sys_clipboard_free(wchar_t* text) { delete[] text; return INFO::OK; diff --git a/source/lib/sysdep/os/win/wcpu.cpp b/source/lib/sysdep/os/win/wcpu.cpp index fa3cff6916..3b8661fa5c 100644 --- a/source/lib/sysdep/os/win/wcpu.cpp +++ b/source/lib/sysdep/os/win/wcpu.cpp @@ -74,7 +74,7 @@ size_t os_cpu_NumProcessors() //----------------------------------------------------------------------------- -LibError wcpu_ReadFrequencyFromRegistry(u32& freqMhz) +Status wcpu_ReadFrequencyFromRegistry(u32& freqMhz) { HKEY hKey; if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS) @@ -151,7 +151,7 @@ size_t os_cpu_QueryMemorySize() // it's not considered available to the kernel. (the amount is // 528 KiB on a 512 MiB WinXP/Win2k machine). we'll round up // to the nearest megabyte to fix this. - memorySize = round_up(memorySize, DWORDLONG(1*MiB)); + memorySize = round_up(memorySize, DWORDLONG(1*MiB)); // (Align<> cannot compute DWORDLONG) return size_t(memorySize / MiB); } @@ -252,7 +252,7 @@ uintptr_t os_cpu_SetThreadAffinityMask(uintptr_t processorMask) } -LibError os_cpu_CallByEachCPU(OsCpuCallback cb, uintptr_t cbData) +Status os_cpu_CallByEachCPU(OsCpuCallback cb, uintptr_t cbData) { // abort if we can't run on all system processors DWORD_PTR processAffinity, systemAffinity; diff --git a/source/lib/sysdep/os/win/wcpu.h b/source/lib/sysdep/os/win/wcpu.h index c6e717a8b7..fd13d1af3f 100644 --- a/source/lib/sysdep/os/win/wcpu.h +++ b/source/lib/sysdep/os/win/wcpu.h @@ -29,7 +29,7 @@ #include "lib/sysdep/os/win/win.h" -extern LibError wcpu_ReadFrequencyFromRegistry(u32& freqMhz); +extern Status wcpu_ReadFrequencyFromRegistry(u32& freqMhz); // "affinity" and "processorNumber" are what Windows sees. // "processorMask" and "processor" are the idealized representation we expose diff --git a/source/lib/sysdep/os/win/wcursor.cpp b/source/lib/sysdep/os/win/wcursor.cpp index abf23392ce..e00cc5df72 100644 --- a/source/lib/sysdep/os/win/wcursor.cpp +++ b/source/lib/sysdep/os/win/wcursor.cpp @@ -48,7 +48,7 @@ static HCURSOR HCURSOR_from_cursor(sys_cursor cursor) } -LibError sys_cursor_create(int w, int h, void* bgra_img, int hx, int hy, sys_cursor* cursor) +Status sys_cursor_create(int w, int h, void* bgra_img, int hx, int hy, sys_cursor* cursor) { *cursor = 0; @@ -84,14 +84,14 @@ LibError sys_cursor_create(int w, int h, void* bgra_img, int hx, int hy, sys_cur } -LibError sys_cursor_create_empty(sys_cursor* cursor) +Status sys_cursor_create_empty(sys_cursor* cursor) { u8 bgra_img[] = {0, 0, 0, 0}; return sys_cursor_create(1, 1, bgra_img, 0, 0, cursor); } -LibError sys_cursor_set(sys_cursor cursor) +Status sys_cursor_set(sys_cursor cursor) { // restore default cursor. if(!cursor) @@ -104,7 +104,7 @@ LibError sys_cursor_set(sys_cursor cursor) } -LibError sys_cursor_free(sys_cursor cursor) +Status sys_cursor_free(sys_cursor cursor) { // bail now to prevent potential confusion below; there's nothing to do. if(!cursor) @@ -113,13 +113,14 @@ LibError sys_cursor_free(sys_cursor cursor) // if the cursor being freed is active, restore the default arrow // (just for safety). if(cursor_from_HCURSOR(GetCursor()) == cursor) - WARN_ERR(sys_cursor_set(0)); + WARN_IF_ERR(sys_cursor_set(0)); - BOOL ok = DestroyIcon(HICON_from_cursor(cursor)); - return LibError_from_win32(ok); + if(!DestroyIcon(HICON_from_cursor(cursor))) + WARN_RETURN(StatusFromWin()); + return INFO::OK; } -LibError sys_cursor_reset() +Status sys_cursor_reset() { return INFO::OK; } diff --git a/source/lib/sysdep/os/win/wdbg_heap.cpp b/source/lib/sysdep/os/win/wdbg_heap.cpp index cb9d9a0082..5ea96bc50c 100644 --- a/source/lib/sysdep/os/win/wdbg_heap.cpp +++ b/source/lib/sysdep/os/win/wdbg_heap.cpp @@ -46,7 +46,7 @@ void wdbg_heap_Enable(bool enable) { flags |= _CRTDBG_ALLOC_MEM_DF; // enable checks at deallocation time flags |= _CRTDBG_LEAK_CHECK_DF; // report leaks at exit -#if CONFIG_PARANOIA +#if CONFIG_ENABLE_CHECKS flags |= _CRTDBG_CHECK_ALWAYS_DF; // check during every heap operation (slow!) flags |= _CRTDBG_DELAY_FREE_MEM_DF; // blocks cannot be reused #endif @@ -335,7 +335,7 @@ public: m_knownCallers.RemoveDuplicates(); } - LibError NotifyOfCaller(uintptr_t pc) + Status NotifyOfCaller(uintptr_t pc) { if(!m_isRecordingKnownCallers) return INFO::SKIPPED; // do not affect the stack walk @@ -690,7 +690,7 @@ public: } private: - LibError OnFrame(const STACKFRAME64* frame) + Status OnFrame(const STACKFRAME64* frame) { const uintptr_t pc = frame->AddrPC.Offset; @@ -698,7 +698,7 @@ private: if(pc == 0) return INFO::CB_CONTINUE; - LibError ret = m_filter.NotifyOfCaller(pc); + Status ret = m_filter.NotifyOfCaller(pc); // (CallerFilter provokes stack traces of heap functions; if that is // what happened, then we must not continue) if(ret != INFO::SKIPPED) @@ -713,7 +713,7 @@ private: return INFO::CB_CONTINUE; } - static LibError OnFrame_Trampoline(const STACKFRAME64* frame, uintptr_t cbData) + static Status OnFrame_Trampoline(const STACKFRAME64* frame, uintptr_t cbData) { CallStack* this_ = (CallStack*)cbData; return this_->OnFrame(frame); @@ -851,7 +851,7 @@ static void PrintCallStack(const uintptr_t* callers, size_t numCallers) for(size_t i = 0; i < numCallers; i++) { wchar_t name[DBG_SYMBOL_LEN] = {'\0'}; wchar_t file[DBG_FILE_LEN] = {'\0'}; int line = -1; - LibError err = debug_ResolveSymbol((void*)callers[i], name, file, &line); + Status err = debug_ResolveSymbol((void*)callers[i], name, file, &line); wdbg_printf(L" "); if(err != INFO::OK) wdbg_printf(L"(error %d resolving PC=%p) ", err, callers[i]); @@ -938,7 +938,7 @@ intptr_t wdbg_heap_NumberOfAllocations() static AllocationTracker* s_tracker; #endif -static LibError wdbg_heap_Init() +static Status wdbg_heap_Init() { #if ENABLE_LEAK_INSTRUMENTATION FindCodeSegment(); @@ -959,7 +959,7 @@ static LibError wdbg_heap_Init() return INFO::OK; } -static LibError wdbg_heap_Shutdown() +static Status wdbg_heap_Shutdown() { #if ENABLE_LEAK_INSTRUMENTATION SAFE_DELETE(s_tracker); diff --git a/source/lib/sysdep/os/win/wdbg_sym.cpp b/source/lib/sysdep/os/win/wdbg_sym.cpp index 1e5f1ff067..e2f853c2cd 100644 --- a/source/lib/sysdep/os/win/wdbg_sym.cpp +++ b/source/lib/sysdep/os/win/wdbg_sym.cpp @@ -68,7 +68,7 @@ static uintptr_t mod_base; static WORD machine; #endif -static LibError InitDbghelp() +static Status InitDbghelp() { hProcess = GetCurrentProcess(); @@ -146,7 +146,7 @@ struct TI_FINDCHILDREN_PARAMS2 // actual implementation; made available so that functions already under // the lock don't have to unlock (slow) to avoid recursive locking. -static LibError ResolveSymbol_lk(void* ptr_of_interest, wchar_t* sym_name, wchar_t* file, int* line) +static Status ResolveSymbol_lk(void* ptr_of_interest, wchar_t* sym_name, wchar_t* file, int* line) { sym_init(); @@ -206,7 +206,7 @@ static LibError ResolveSymbol_lk(void* ptr_of_interest, wchar_t* sym_name, wchar // sym_name and file must hold at least the number of chars above; // file is the base name only, not path (see rationale in wdbg_sym). // the PDB implementation is rather slow (~500µs). -LibError debug_ResolveSymbol(void* ptr_of_interest, wchar_t* sym_name, wchar_t* file, int* line) +Status debug_ResolveSymbol(void* ptr_of_interest, wchar_t* sym_name, wchar_t* file, int* line) { WinScopedLock lock(WDBG_SYM_CS); return ResolveSymbol_lk(ptr_of_interest, sym_name, file, line); @@ -260,7 +260,7 @@ func2: #if IA32_STACK_WALK_ENABLED -static LibError ia32_walk_stack(_tagSTACKFRAME64* sf) +static Status ia32_walk_stack(_tagSTACKFRAME64* sf) { // read previous values from _tagSTACKFRAME64 void* prev_fp = (void*)(uintptr_t)sf->AddrFrame .Offset; @@ -284,8 +284,8 @@ static LibError ia32_walk_stack(_tagSTACKFRAME64* sf) return ERR::FAIL; // NOWARN (invalid address) void* target; - LibError err = ia32_GetCallTarget(ret_addr, target); - RETURN_ERR(err); + Status err = ia32_GetCallTarget(ret_addr, target); + RETURN_STATUS_IF_ERR(err); if(target) // were able to determine it from the call instruction { if(!debug_IsCodePointer(target)) @@ -308,7 +308,7 @@ static LibError ia32_walk_stack(_tagSTACKFRAME64* sf) // for debug_GetCaller), but wasn't known during development and // remains undocumented. -LibError wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData, const CONTEXT* pcontext, const wchar_t* lastFuncToSkip) +Status wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData, const CONTEXT* pcontext, const wchar_t* lastFuncToSkip) { // to function properly, StackWalk64 requires a CONTEXT on // non-x86 systems (documented) or when in release mode (observed). @@ -375,7 +375,7 @@ LibError wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData, const CONTE #endif // for each stack frame found: - LibError ret = ERR::SYM_NO_STACK_FRAMES_FOUND; + Status ret = ERR::SYM_NO_STACK_FRAMES_FOUND; for(;;) { // rationale: @@ -391,7 +391,7 @@ LibError wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData, const CONTE // of them fails: this needlessly complicates things. the ia32 // code is authoritative provided its prerequisite (FP not omitted) // is met, otherwise totally unusable. - LibError err; + Status err; #if IA32_STACK_WALK_ENABLED err = ia32_walk_stack(&sf); #else @@ -403,9 +403,7 @@ LibError wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData, const CONTE SetLastError(0); const HANDLE hThread = GetCurrentThread(); const BOOL ok = pStackWalk64(machine, hProcess, hThread, &sf, (PVOID)pcontext, 0, pSymFunctionTableAccess64, pSymGetModuleBase64, 0); - // note: don't use LibError_from_win32 because it raises a warning, - // and this "fails" commonly (when no stack frames are left). - err = ok? INFO::OK : ERR::FAIL; + err = ok? INFO::OK : ERR::FAIL; // NOWARN (no stack frames are left) } #endif @@ -448,7 +446,7 @@ LibError wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData, const CONTE // // called by wdbg_sym_WalkStack for each stack frame -static LibError nth_caller_cb(const _tagSTACKFRAME64* sf, uintptr_t cbData) +static Status nth_caller_cb(const _tagSTACKFRAME64* sf, uintptr_t cbData) { void** pfunc = (void**)cbData; @@ -460,7 +458,7 @@ static LibError nth_caller_cb(const _tagSTACKFRAME64* sf, uintptr_t cbData) void* debug_GetCaller(void* pcontext, const wchar_t* lastFuncToSkip) { void* func; - LibError ret = wdbg_sym_WalkStack(nth_caller_cb, (uintptr_t)&func, (const CONTEXT*)pcontext, lastFuncToSkip); + Status ret = wdbg_sym_WalkStack(nth_caller_cb, (uintptr_t)&func, (const CONTEXT*)pcontext, lastFuncToSkip); return (ret == INFO::OK)? func : 0; } @@ -589,7 +587,7 @@ static void out_latch_pos() // (see above) -static LibError out_check_limit() +static Status out_check_limit() { if(out_have_warned_of_limit) return INFO::SYM_SUPPRESS_OUTPUT; @@ -646,7 +644,7 @@ static bool is_string(const u8* p, size_t stride) // forward decl; called by dump_sequence and some of dump_sym_*. -static LibError dump_sym(DWORD id, const u8* p, DumpState state); +static Status dump_sym(DWORD id, const u8* p, DumpState state); // from cvconst.h // @@ -661,7 +659,7 @@ enum CV_HREG_e }; -static void dump_error(LibError err) +static void dump_error(Status err) { switch(err) { @@ -694,7 +692,7 @@ static void dump_error(LibError err) // split out of dump_sequence. -static LibError dump_string(const u8* p, size_t el_size) +static Status dump_string(const u8* p, size_t el_size) { // not char or wchar_t string if(el_size != sizeof(char) && el_size != sizeof(wchar_t)) @@ -753,7 +751,7 @@ static void seq_determine_formatting(size_t el_size, size_t el_count, bool* fits } -static LibError dump_sequence(DebugStlIterator el_iterator, void* internal, size_t el_count, DWORD el_type_id, size_t el_size, DumpState state) +static Status dump_sequence(DebugStlIterator el_iterator, void* internal, size_t el_count, DWORD el_type_id, size_t el_size, DumpState state) { const u8* el_p = 0; // avoid "uninitialized" warning @@ -764,7 +762,7 @@ static LibError dump_sequence(DebugStlIterator el_iterator, void* internal, size { el_p = el_iterator(internal, el_size); - LibError ret = dump_string(el_p, el_size); + Status ret = dump_string(el_p, el_size); if(ret == INFO::OK) return ret; } @@ -783,7 +781,7 @@ static LibError dump_sequence(DebugStlIterator el_iterator, void* internal, size if(!fits_on_one_line) INDENT; - LibError err = dump_sym(el_type_id, el_p, state); + Status err = dump_sym(el_type_id, el_p, state); el_p = el_iterator(internal, el_size); // there was no output for this child; undo its indentation (if any), @@ -825,7 +823,7 @@ static const u8* array_iterator(void* internal, size_t el_size) } -static LibError dump_array(const u8* p, size_t el_count, DWORD el_type_id, size_t el_size, DumpState state) +static Status dump_array(const u8* p, size_t el_count, DWORD el_type_id, size_t el_size, DumpState state) { const u8* iterator_internal_pos = p; return dump_sequence(array_iterator, &iterator_internal_pos, @@ -835,7 +833,7 @@ static LibError dump_array(const u8* p, size_t el_count, DWORD el_type_id, size_ static const _tagSTACKFRAME64* current_stackframe64; -static LibError CanHandleDataKind(DWORD dataKind) +static Status CanHandleDataKind(DWORD dataKind) { switch(dataKind) { @@ -896,15 +894,15 @@ static bool IsUnretrievable(DWORD flags) return false; } -static LibError DetermineSymbolAddress(DWORD id, const SYMBOL_INFOW* sym, const u8** pp) +static Status DetermineSymbolAddress(DWORD id, const SYMBOL_INFOW* sym, const u8** pp) { const _tagSTACKFRAME64* sf = current_stackframe64; DWORD dataKind; if(!pSymGetTypeInfo(hProcess, mod_base, id, TI_GET_DATAKIND, &dataKind)) WARN_RETURN(ERR::SYM_TYPE_INFO_UNAVAILABLE); - LibError ret = CanHandleDataKind(dataKind); - RETURN_ERR(ret); + Status ret = CanHandleDataKind(dataKind); + RETURN_STATUS_IF_ERR(ret); if(ret == INFO::SKIPPED) return INFO::OK; // pp is already correct @@ -952,7 +950,7 @@ static LibError DetermineSymbolAddress(DWORD id, const SYMBOL_INFOW* sym, const // will display the appropriate error message via dump_error. // called by dump_sym; lock is held. -static LibError dump_sym_array(DWORD type_id, const u8* p, DumpState state) +static Status dump_sym_array(DWORD type_id, const u8* p, DumpState state) { ULONG64 size_ = 0; if(!pSymGetTypeInfo(hProcess, mod_base, type_id, TI_GET_LENGTH, &size_)) @@ -993,7 +991,7 @@ static void AppendCharacterIfPrintable(u64 data) } -static LibError dump_sym_base_type(DWORD type_id, const u8* p, DumpState state) +static Status dump_sym_base_type(DWORD type_id, const u8* p, DumpState state) { DWORD base_type; if(!pSymGetTypeInfo(hProcess, mod_base, type_id, TI_GET_BASETYPE, &base_type)) @@ -1127,7 +1125,7 @@ display_as_hex: //----------------------------------------------------------------------------- -static LibError dump_sym_base_class(DWORD type_id, const u8* p, DumpState state) +static Status dump_sym_base_class(DWORD type_id, const u8* p, DumpState state) { DWORD base_class_type_id; if(!pSymGetTypeInfo(hProcess, mod_base, type_id, TI_GET_TYPEID, &base_class_type_id)) @@ -1146,18 +1144,18 @@ static LibError dump_sym_base_class(DWORD type_id, const u8* p, DumpState state) //----------------------------------------------------------------------------- -static LibError dump_sym_data(DWORD id, const u8* p, DumpState state) +static Status dump_sym_data(DWORD id, const u8* p, DumpState state) { SYMBOL_INFO_PACKAGEW2 sp; SYMBOL_INFOW* sym = &sp.si; if(!pSymFromIndexW(hProcess, mod_base, id, sym)) - RETURN_ERR(ERR::SYM_TYPE_INFO_UNAVAILABLE); + RETURN_STATUS_IF_ERR(ERR::SYM_TYPE_INFO_UNAVAILABLE); out(L"%ls = ", sym->Name); __try { - RETURN_ERR(DetermineSymbolAddress(id, sym, &p)); + RETURN_STATUS_IF_ERR(DetermineSymbolAddress(id, sym, &p)); // display value recursively return dump_sym(sym->TypeIndex, p, state); } @@ -1170,7 +1168,7 @@ static LibError dump_sym_data(DWORD id, const u8* p, DumpState state) //----------------------------------------------------------------------------- -static LibError dump_sym_enum(DWORD type_id, const u8* p, DumpState UNUSED(state)) +static Status dump_sym_enum(DWORD type_id, const u8* p, DumpState UNUSED(state)) { ULONG64 size_ = 0; if(!pSymGetTypeInfo(hProcess, mod_base, type_id, TI_GET_LENGTH, &size_)) @@ -1228,7 +1226,7 @@ static LibError dump_sym_enum(DWORD type_id, const u8* p, DumpState UNUSED(state //----------------------------------------------------------------------------- -static LibError dump_sym_function(DWORD UNUSED(type_id), const u8* UNUSED(p), DumpState UNUSED(state)) +static Status dump_sym_function(DWORD UNUSED(type_id), const u8* UNUSED(p), DumpState UNUSED(state)) { return INFO::SYM_SUPPRESS_OUTPUT; } @@ -1236,14 +1234,14 @@ static LibError dump_sym_function(DWORD UNUSED(type_id), const u8* UNUSED(p), Du //----------------------------------------------------------------------------- -static LibError dump_sym_function_type(DWORD UNUSED(type_id), const u8* p, DumpState state) +static Status dump_sym_function_type(DWORD UNUSED(type_id), const u8* p, DumpState state) { // this symbol gives class parent, return type, and parameter count. // unfortunately the one thing we care about, its name, // isn't exposed via TI_GET_SYMNAME, so we resolve it ourselves. wchar_t name[DBG_SYMBOL_LEN]; - LibError err = ResolveSymbol_lk((void*)p, name, 0, 0); + Status err = ResolveSymbol_lk((void*)p, name, 0, 0); if(state.indirection == 0) out(L"0x%p ", p); @@ -1304,7 +1302,7 @@ static bool ptr_already_visited(const u8* p) } -static LibError dump_sym_pointer(DWORD type_id, const u8* p, DumpState state) +static Status dump_sym_pointer(DWORD type_id, const u8* p, DumpState state) { ULONG64 size_ = 0; if(!pSymGetTypeInfo(hProcess, mod_base, type_id, TI_GET_LENGTH, &size_)) @@ -1347,7 +1345,7 @@ static LibError dump_sym_pointer(DWORD type_id, const u8* p, DumpState state) //----------------------------------------------------------------------------- -static LibError dump_sym_typedef(DWORD type_id, const u8* p, DumpState state) +static Status dump_sym_typedef(DWORD type_id, const u8* p, DumpState state) { if(!pSymGetTypeInfo(hProcess, mod_base, type_id, TI_GET_TYPEID, &type_id)) WARN_RETURN(ERR::SYM_TYPE_INFO_UNAVAILABLE); @@ -1361,7 +1359,7 @@ static LibError dump_sym_typedef(DWORD type_id, const u8* p, DumpState state) // determine type and size of the given child in a UDT. // useful for UDTs that contain typedefs describing their contents, // e.g. value_type in STL containers. -static LibError udt_get_child_type(const wchar_t* child_name, ULONG num_children, const DWORD* children, DWORD* el_type_id, size_t* el_size) +static Status udt_get_child_type(const wchar_t* child_name, ULONG num_children, const DWORD* children, DWORD* el_type_id, size_t* el_size) { const DWORD lastError = GetLastError(); @@ -1395,9 +1393,9 @@ static LibError udt_get_child_type(const wchar_t* child_name, ULONG num_children } -static LibError udt_dump_std(const wchar_t* type_name, const u8* p, size_t size, DumpState state, ULONG num_children, const DWORD* children) +static Status udt_dump_std(const wchar_t* type_name, const u8* p, size_t size, DumpState state, ULONG num_children, const DWORD* children) { - LibError err; + Status err; // not a C++ standard library object; can't handle it. if(wcsncmp(type_name, L"std::", 5) != 0) @@ -1507,7 +1505,7 @@ not_handle: } -static LibError udt_dump_suppressed(const wchar_t* type_name, const u8* UNUSED(p), size_t UNUSED(size), DumpState state, ULONG UNUSED(num_children), const DWORD* UNUSED(children)) +static Status udt_dump_suppressed(const wchar_t* type_name, const u8* UNUSED(p), size_t UNUSED(size), DumpState state, ULONG UNUSED(num_children), const DWORD* UNUSED(children)) { if(!udt_should_suppress(type_name)) return INFO::CANNOT_HANDLE; @@ -1559,7 +1557,7 @@ static bool udt_fits_on_one_line(const wchar_t* type_name, size_t child_count, s } -static LibError udt_dump_normal(const wchar_t* type_name, const u8* p, size_t size, DumpState state, ULONG num_children, const DWORD* children) +static Status udt_dump_normal(const wchar_t* type_name, const u8* p, size_t size, DumpState state, ULONG num_children, const DWORD* children) { const bool fits_on_one_line = udt_fits_on_one_line(type_name, num_children, size); @@ -1590,7 +1588,7 @@ static LibError udt_dump_normal(const wchar_t* type_name, const u8* p, size_t si INDENT; const u8* el_p = p+ofs; - LibError err = dump_sym(child_id, el_p, state); + Status err = dump_sym(child_id, el_p, state); // there was no output for this child; undo its indentation (if any), // skip everything below and proceed with the next child. @@ -1631,7 +1629,7 @@ static LibError udt_dump_normal(const wchar_t* type_name, const u8* p, size_t si } -static LibError dump_sym_udt(DWORD type_id, const u8* p, DumpState state) +static Status dump_sym_udt(DWORD type_id, const u8* p, DumpState state) { ULONG64 size_ = 0; if(!pSymGetTypeInfo(hProcess, mod_base, type_id, TI_GET_LENGTH, &size_)) @@ -1652,7 +1650,7 @@ static LibError dump_sym_udt(DWORD type_id, const u8* p, DumpState state) if(!pSymGetTypeInfo(hProcess, mod_base, type_id, TI_GET_SYMNAME, &type_name)) WARN_RETURN(ERR::SYM_TYPE_INFO_UNAVAILABLE); - LibError ret; + Status ret; // note: order is important (e.g. STL special-case must come before // suppressing UDTs, which tosses out most other C++ stdlib classes) @@ -1677,7 +1675,7 @@ done: //----------------------------------------------------------------------------- -static LibError dump_sym_vtable(DWORD UNUSED(type_id), const u8* UNUSED(p), DumpState UNUSED(state)) +static Status dump_sym_vtable(DWORD UNUSED(type_id), const u8* UNUSED(p), DumpState UNUSED(state)) { // unsupported (vtable internals are undocumented; too much work). return INFO::SYM_SUPPRESS_OUTPUT; @@ -1687,7 +1685,7 @@ static LibError dump_sym_vtable(DWORD UNUSED(type_id), const u8* UNUSED(p), Dump //----------------------------------------------------------------------------- -static LibError dump_sym_unknown(DWORD type_id, const u8* UNUSED(p), DumpState UNUSED(state)) +static Status dump_sym_unknown(DWORD type_id, const u8* UNUSED(p), DumpState UNUSED(state)) { // redundant (already done in dump_sym), but this is rare. DWORD type_tag; @@ -1705,9 +1703,9 @@ static LibError dump_sym_unknown(DWORD type_id, const u8* UNUSED(p), DumpState U // write name and value of the symbol to the output buffer. // delegates to dump_sym_* depending on the symbol's tag. -static LibError dump_sym(DWORD type_id, const u8* p, DumpState state) +static Status dump_sym(DWORD type_id, const u8* p, DumpState state) { - RETURN_ERR(out_check_limit()); + RETURN_STATUS_IF_ERR(out_check_limit()); DWORD type_tag; if(!pSymGetTypeInfo(hProcess, mod_base, type_id, TI_GET_SYMTAG, &type_tag)) @@ -1788,7 +1786,7 @@ static BOOL CALLBACK dump_sym_cb(SYMBOL_INFOW* sym, ULONG UNUSED(size), void* UN DumpState state; INDENT; - LibError err = dump_sym(sym->Index, p, state); + Status err = dump_sym(sym->Index, p, state); dump_error(err); if(err == INFO::SYM_SUPPRESS_OUTPUT) UNINDENT; @@ -1799,13 +1797,13 @@ static BOOL CALLBACK dump_sym_cb(SYMBOL_INFOW* sym, ULONG UNUSED(size), void* UN } // called by wdbg_sym_WalkStack for each stack frame -static LibError dump_frame_cb(const _tagSTACKFRAME64* sf, uintptr_t UNUSED(cbData)) +static Status dump_frame_cb(const _tagSTACKFRAME64* sf, uintptr_t UNUSED(cbData)) { current_stackframe64 = sf; void* func = (void*)(uintptr_t)sf->AddrPC.Offset; wchar_t func_name[DBG_SYMBOL_LEN]; wchar_t file[DBG_FILE_LEN]; int line; - LibError ret = ResolveSymbol_lk(func, func_name, file, &line); + Status ret = ResolveSymbol_lk(func, func_name, file, &line); if(ret == INFO::OK) { // don't trace back further than the app's entry point @@ -1840,7 +1838,7 @@ static LibError dump_frame_cb(const _tagSTACKFRAME64* sf, uintptr_t UNUSED(cbDat } -LibError debug_DumpStack(wchar_t* buf, size_t maxChars, void* pcontext, const wchar_t* lastFuncToSkip) +Status debug_DumpStack(wchar_t* buf, size_t maxChars, void* pcontext, const wchar_t* lastFuncToSkip) { static intptr_t busy; if(!cpu_CAS(&busy, 0, 1)) @@ -1849,7 +1847,7 @@ LibError debug_DumpStack(wchar_t* buf, size_t maxChars, void* pcontext, const wc out_init(buf, maxChars); ptr_reset_visited(); - LibError ret = wdbg_sym_WalkStack(dump_frame_cb, 0, (const CONTEXT*)pcontext, lastFuncToSkip); + Status ret = wdbg_sym_WalkStack(dump_frame_cb, 0, (const CONTEXT*)pcontext, lastFuncToSkip); busy = 0; COMPILER_FENCE; diff --git a/source/lib/sysdep/os/win/wdbg_sym.h b/source/lib/sysdep/os/win/wdbg_sym.h index a6954259f2..4321d90671 100644 --- a/source/lib/sysdep/os/win/wdbg_sym.h +++ b/source/lib/sysdep/os/win/wdbg_sym.h @@ -41,7 +41,7 @@ struct _EXCEPTION_POINTERS; * @return INFO::CB_CONTINUE to continue, anything else to stop immediately * and return that value to wdbg_sym_WalkStack's caller. **/ -typedef LibError (*StackFrameCallback)(const _tagSTACKFRAME64* frame, uintptr_t cbData); +typedef Status (*StackFrameCallback)(const _tagSTACKFRAME64* frame, uintptr_t cbData); /** * Iterate over a call stack, invoking a callback for each frame encountered. @@ -52,11 +52,11 @@ typedef LibError (*StackFrameCallback)(const _tagSTACKFRAME64* frame, uintptr_t * an exception record), or 0 to walk the current stack. * @param lastFuncToSkip * - * @note It is safe to use ENSURE/debug_warn/CHECK_ERR even during a + * @note It is safe to use ENSURE/debug_warn/WARN_RETURN_STATUS_IF_ERR even during a * stack trace (which is triggered by ENSURE et al. in app code) because * nested stack traces are ignored and only the error is displayed. **/ -extern LibError wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData = 0, const _CONTEXT* pcontext = 0, const wchar_t* lastFuncToSkip = 0); +extern Status wdbg_sym_WalkStack(StackFrameCallback cb, uintptr_t cbData = 0, const _CONTEXT* pcontext = 0, const wchar_t* lastFuncToSkip = 0); extern void wdbg_sym_WriteMinidump(_EXCEPTION_POINTERS* ep); diff --git a/source/lib/sysdep/os/win/wdir_watch.cpp b/source/lib/sysdep/os/win/wdir_watch.cpp index d00584872b..371ffc029e 100644 --- a/source/lib/sysdep/os/win/wdir_watch.cpp +++ b/source/lib/sysdep/os/win/wdir_watch.cpp @@ -138,7 +138,7 @@ public: return m_dirHandle; } - LibError Issue() + Status Issue() { if(m_dirHandle == INVALID_HANDLE_VALUE) WARN_RETURN(ERR::PATH_NOT_FOUND); @@ -307,7 +307,7 @@ public: CloseHandle(hIOCP); } - LibError Add(const OsPath& path, PDirWatch& dirWatch) + Status Add(const OsPath& path, PDirWatch& dirWatch) { ENSURE(path.IsDirectory()); @@ -326,17 +326,17 @@ public: PDirWatchRequest request(new DirWatchRequest(path)); AttachToCompletionPort(request->GetDirHandle(), hIOCP, (uintptr_t)request.get()); - RETURN_ERR(request->Issue()); + RETURN_STATUS_IF_ERR(request->Issue()); dirWatch.reset(new DirWatch(&m_sentinel, request)); return INFO::OK; } - LibError Poll(DirWatchNotifications& notifications) + Status Poll(DirWatchNotifications& notifications) { DWORD bytesTransferred; ULONG_PTR key; OVERLAPPED* ovl; for(;;) // skip notifications of canceled watches { - const LibError ret = PollCompletionPort(hIOCP, 0, bytesTransferred, key, ovl); + const Status ret = PollCompletionPort(hIOCP, 0, bytesTransferred, key, ovl); if(ret == INFO::OK) break; if(GetLastError() == ERROR_OPERATION_ABORTED) @@ -346,7 +346,7 @@ public: DirWatchRequest* request = (DirWatchRequest*)key; request->RetrieveNotifications(notifications); - RETURN_ERR(request->Issue()); // re-issue + RETURN_STATUS_IF_ERR(request->Issue()); // re-issue return INFO::OK; } @@ -360,13 +360,13 @@ static DirWatchManager* s_dirWatchManager; //----------------------------------------------------------------------------- -LibError dir_watch_Add(const OsPath& path, PDirWatch& dirWatch) +Status dir_watch_Add(const OsPath& path, PDirWatch& dirWatch) { WinScopedLock lock(WDIR_WATCH_CS); return s_dirWatchManager->Add(path, dirWatch); } -LibError dir_watch_Poll(DirWatchNotifications& notifications) +Status dir_watch_Poll(DirWatchNotifications& notifications) { WinScopedLock lock(WDIR_WATCH_CS); return s_dirWatchManager->Poll(notifications); @@ -375,13 +375,13 @@ LibError dir_watch_Poll(DirWatchNotifications& notifications) //----------------------------------------------------------------------------- -static LibError wdir_watch_Init() +static Status wdir_watch_Init() { s_dirWatchManager = new DirWatchManager; return INFO::OK; } -static LibError wdir_watch_Shutdown() +static Status wdir_watch_Shutdown() { SAFE_DELETE(s_dirWatchManager); return INFO::OK; diff --git a/source/lib/sysdep/os/win/wdll_delay_load.cpp b/source/lib/sysdep/os/win/wdll_delay_load.cpp index a183e7f203..cb85e734c3 100644 --- a/source/lib/sysdep/os/win/wdll_delay_load.cpp +++ b/source/lib/sysdep/os/win/wdll_delay_load.cpp @@ -38,7 +38,7 @@ WINIT_REGISTER_LATE_SHUTDOWN2(wdll_Shutdown); // last - DLLs are unloaded here #define FACILITY_VISUALCPP ((LONG)0x6d) -#define VcppException(sev,err) ((sev) | (FACILITY_VISUALCPP<<16) | err) +#define VcppException(sev,status) ((sev) | (FACILITY_VISUALCPP<<16) | status) typedef IMAGE_THUNK_DATA * PImgThunkData; typedef const IMAGE_THUNK_DATA * PCImgThunkData; @@ -466,7 +466,7 @@ static void UnloadAllDlls() //----------------------------------------------------------------------------- -static LibError wdll_Shutdown() +static Status wdll_Shutdown() { UnloadAllDlls(); return INFO::OK; diff --git a/source/lib/sysdep/os/win/wdll_delay_load.h b/source/lib/sysdep/os/win/wdll_delay_load.h index 055af3901c..2ffe7f99d9 100644 --- a/source/lib/sysdep/os/win/wdll_delay_load.h +++ b/source/lib/sysdep/os/win/wdll_delay_load.h @@ -31,7 +31,7 @@ struct WdllLoadNotify { const char* dll_name; - LibError (*func)(); + Status (*func)(); WdllLoadNotify* next; }; diff --git a/source/lib/sysdep/os/win/wdll_ver.cpp b/source/lib/sysdep/os/win/wdll_ver.cpp index f9cede4fe3..6769bb2cd5 100644 --- a/source/lib/sysdep/os/win/wdll_ver.cpp +++ b/source/lib/sysdep/os/win/wdll_ver.cpp @@ -42,7 +42,7 @@ //----------------------------------------------------------------------------- -static LibError ReadVersionString(const OsPath& modulePathname, wchar_t* out_ver, size_t out_ver_len) +static Status ReadVersionString(const OsPath& modulePathname, wchar_t* out_ver, size_t out_ver_len) { WinScopedPreserveLastError s; // GetFileVersion*, Ver* diff --git a/source/lib/sysdep/os/win/wgfx.cpp b/source/lib/sysdep/os/win/wgfx.cpp index 56569b8fe6..26e2b875ea 100644 --- a/source/lib/sysdep/os/win/wgfx.cpp +++ b/source/lib/sysdep/os/win/wgfx.cpp @@ -38,7 +38,7 @@ // useful for choosing a video mode. // if we fail, outputs are unchanged (assumed initialized to defaults) -LibError gfx_get_video_mode(int* xres, int* yres, int* bpp, int* freq) +Status gfx_get_video_mode(int* xres, int* yres, int* bpp, int* freq) { DEVMODEA dm; memset(&dm, 0, sizeof(dm)); @@ -70,7 +70,7 @@ LibError gfx_get_video_mode(int* xres, int* yres, int* bpp, int* freq) // useful for determining aspect ratio. // if we fail, outputs are unchanged (assumed initialized to defaults) -LibError gfx_get_monitor_size(int& width_mm, int& height_mm) +Status gfx_get_monitor_size(int& width_mm, int& height_mm) { // (DC for the primary monitor's entire screen) HDC dc = GetDC(0); @@ -83,17 +83,17 @@ LibError gfx_get_monitor_size(int& width_mm, int& height_mm) //----------------------------------------------------------------------------- -static LibError win_get_gfx_card() +static Status win_get_gfx_card() { WmiMap wmiMap; - RETURN_ERR(wmi_GetClass(L"Win32_VideoController", wmiMap)); + RETURN_STATUS_IF_ERR(wmi_GetClass(L"Win32_VideoController", wmiMap)); swprintf_s(gfx_card, GFX_CARD_LEN, L"%ls", wmiMap[L"Caption"].bstrVal); return INFO::OK; } // note: this implementation doesn't require OpenGL to be initialized. -static LibError AppendDriverVersionsFromRegistry(VersionList& versionList) +static Status AppendDriverVersionsFromRegistry(VersionList& versionList) { // rationale: // - we could easily determine the 2d driver via EnumDisplaySettings, @@ -191,9 +191,9 @@ static void AppendDriverVersionsFromKnownFiles(VersionList& versionList) } -LibError win_get_gfx_info() +Status win_get_gfx_info() { - LibError err = win_get_gfx_card(); + Status err = win_get_gfx_card(); VersionList versionList; if(AppendDriverVersionsFromRegistry(versionList) != INFO::OK) // (fails on Windows 7) diff --git a/source/lib/sysdep/os/win/wgfx.h b/source/lib/sysdep/os/win/wgfx.h index bb18a58605..50e0eebcf2 100644 --- a/source/lib/sysdep/os/win/wgfx.h +++ b/source/lib/sysdep/os/win/wgfx.h @@ -23,6 +23,6 @@ #ifndef INCLUDED_WGFX #define INCLUDED_WGFX -extern LibError win_get_gfx_info(); +extern Status win_get_gfx_info(); #endif // #ifndef INCLUDED_WGFX diff --git a/source/lib/sysdep/os/win/whrt/counter.h b/source/lib/sysdep/os/win/whrt/counter.h index 5fa04e8b70..0e269d8919 100644 --- a/source/lib/sysdep/os/win/whrt/counter.h +++ b/source/lib/sysdep/os/win/whrt/counter.h @@ -39,7 +39,7 @@ public: // Activate with an error return value is much cleaner+safer than // throwing exceptions in the ctor. - virtual LibError Activate() = 0; + virtual Status Activate() = 0; virtual void Shutdown() = 0; virtual bool IsSafe() const = 0; diff --git a/source/lib/sysdep/os/win/whrt/hpet.cpp b/source/lib/sysdep/os/win/whrt/hpet.cpp index 68566fc171..b37034b5cc 100644 --- a/source/lib/sysdep/os/win/whrt/hpet.cpp +++ b/source/lib/sysdep/os/win/whrt/hpet.cpp @@ -56,9 +56,9 @@ public: return L"HPET"; } - LibError Activate() + Status Activate() { - RETURN_ERR(MapRegisters(m_hpetRegisters)); + RETURN_STATUS_IF_ERR(MapRegisters(m_hpetRegisters)); // retrieve capabilities and ID { @@ -145,11 +145,11 @@ private: MAX_OFFSET = 0x3FF }; - static LibError MapRegisters(volatile void*& registers) + static Status MapRegisters(volatile void*& registers) { if(mahaf_IsPhysicalMappingDangerous()) return ERR::FAIL; // NOWARN (happens on Win2k) - RETURN_ERR(mahaf_Init()); // (fails without Administrator privileges) + RETURN_STATUS_IF_ERR(mahaf_Init()); // (fails without Administrator privileges) const HpetDescriptionTable* hpet = (const HpetDescriptionTable*)acpi_GetTable("HPET"); if(!hpet) diff --git a/source/lib/sysdep/os/win/whrt/pmt.cpp b/source/lib/sysdep/os/win/whrt/pmt.cpp index 50e6bae61d..dfbd8cc0ce 100644 --- a/source/lib/sysdep/os/win/whrt/pmt.cpp +++ b/source/lib/sysdep/os/win/whrt/pmt.cpp @@ -52,10 +52,10 @@ public: return L"PMT"; } - LibError Activate() + Status Activate() { // mahaf is needed for port I/O. - RETURN_ERR(mahaf_Init()); // (fails without Administrator privileges) + RETURN_STATUS_IF_ERR(mahaf_Init()); // (fails without Administrator privileges) // (note: it's called FADT, but the signature is "FACP") const FADT* fadt = (const FADT*)acpi_GetTable("FACP"); if(!fadt) diff --git a/source/lib/sysdep/os/win/whrt/qpc.cpp b/source/lib/sysdep/os/win/whrt/qpc.cpp index c5ac7c86d7..c7ebfbd120 100644 --- a/source/lib/sysdep/os/win/whrt/qpc.cpp +++ b/source/lib/sysdep/os/win/whrt/qpc.cpp @@ -49,7 +49,7 @@ public: return L"QPC"; } - LibError Activate() + Status Activate() { // note: QPC is observed to be universally supported, but the API // provides for failure, so play it safe. @@ -57,7 +57,8 @@ public: LARGE_INTEGER qpcFreq, qpcValue; const BOOL ok1 = QueryPerformanceFrequency(&qpcFreq); const BOOL ok2 = QueryPerformanceCounter(&qpcValue); - WARN_RETURN_IF_FALSE(ok1 && ok2); + if(!ok1 || !ok2) + WARN_RETURN(ERR::FAIL); if(!qpcFreq.QuadPart || !qpcValue.QuadPart) WARN_RETURN(ERR::FAIL); diff --git a/source/lib/sysdep/os/win/whrt/tgt.cpp b/source/lib/sysdep/os/win/whrt/tgt.cpp index a53f12a192..dd08e4574f 100644 --- a/source/lib/sysdep/os/win/whrt/tgt.cpp +++ b/source/lib/sysdep/os/win/whrt/tgt.cpp @@ -54,7 +54,7 @@ public: return L"TGT"; } - LibError Activate() + Status Activate() { // note: timeGetTime is always available and cannot fail. diff --git a/source/lib/sysdep/os/win/whrt/tsc.cpp b/source/lib/sysdep/os/win/whrt/tsc.cpp index 7ff4c66b45..1f0437a962 100644 --- a/source/lib/sysdep/os/win/whrt/tsc.cpp +++ b/source/lib/sysdep/os/win/whrt/tsc.cpp @@ -119,7 +119,7 @@ public: return L"TSC"; } - LibError Activate() + Status Activate() { #if ARCH_X86_X64 if(!x86_x64_cap(X86_X64_CAP_TSC)) diff --git a/source/lib/sysdep/os/win/whrt/whrt.cpp b/source/lib/sysdep/os/win/whrt/whrt.cpp index 0fe0797677..ef5cd495f0 100644 --- a/source/lib/sysdep/os/win/whrt/whrt.cpp +++ b/source/lib/sysdep/os/win/whrt/whrt.cpp @@ -43,7 +43,7 @@ WINIT_REGISTER_LATE_SHUTDOWN(whrt_Shutdown); namespace ERR { - const LibError WHRT_COUNTER_UNSAFE = 140000; + const Status WHRT_COUNTER_UNSAFE = 140000; } @@ -51,9 +51,9 @@ namespace ERR // choose best available safe counter // (moved into a separate function to simplify error handling) -static inline LibError ActivateCounter(ICounter* counter) +static inline Status ActivateCounter(ICounter* counter) { - RETURN_ERR(counter->Activate()); + RETURN_STATUS_IF_ERR(counter->Activate()); if(!counter->IsSafe()) return ERR::WHRT_COUNTER_UNSAFE; // NOWARN (happens often) @@ -74,7 +74,7 @@ static ICounter* GetNextBestSafeCounter() if(!counter) return 0; // tried all, none were safe - LibError err = ActivateCounter(counter); + Status err = ActivateCounter(counter); if(err == INFO::OK) { debug_printf(L"HRT| using name=%ls freq=%f\n", counter->Name(), counter->NominalFrequency()); @@ -83,7 +83,7 @@ static ICounter* GetNextBestSafeCounter() else { wchar_t buf[100]; - debug_printf(L"HRT| activating %ls failed: %ls\n", counter->Name(), error_description_r(err, buf, ARRAY_SIZE(buf))); + debug_printf(L"HRT| activating %ls failed: %ls\n", counter->Name(), StatusDescription(err, buf, ARRAY_SIZE(buf))); DestroyCounter(counter); } } @@ -259,7 +259,7 @@ static unsigned __stdcall UpdateThread(void* UNUSED(data)) return 0; } -static inline LibError InitUpdateThread() +static inline Status InitUpdateThread() { // make sure our interval isn't too long // (counterBits can be 64 => Bit() would overflow => calculate period/2) @@ -293,7 +293,7 @@ static inline void ShutdownUpdateThread() //----------------------------------------------------------------------------- -static LibError whrt_Init() +static Status whrt_Init() { InitCounter(); @@ -302,13 +302,13 @@ static LibError whrt_Init() UpdateTimerState(); // must come before InitUpdateThread to avoid race - RETURN_ERR(InitUpdateThread()); + RETURN_STATUS_IF_ERR(InitUpdateThread()); return INFO::OK; } -static LibError whrt_Shutdown() +static Status whrt_Shutdown() { ShutdownUpdateThread(); diff --git a/source/lib/sysdep/os/win/winit.cpp b/source/lib/sysdep/os/win/winit.cpp index 557e73e8e6..717966abe9 100644 --- a/source/lib/sysdep/os/win/winit.cpp +++ b/source/lib/sysdep/os/win/winit.cpp @@ -34,7 +34,7 @@ // // note: this module is kept distinct from the CRT's init/shutdown mechanism // to insulate against changes there. another advantage is that callbacks -// can return LibError instead of int. +// can return Status instead of int. // currently (2008-02-17) the init groups are populated as follows: // critical : wposix @@ -43,7 +43,7 @@ // main : waio, wsock, wtime, wdir_watch // late : wsdl -typedef LibError (*PfnLibError)(); +typedef Status (*PfnLibError)(); // pointers to start and end of function tables. // notes: diff --git a/source/lib/sysdep/os/win/winit.h b/source/lib/sysdep/os/win/winit.h index 7bfec21170..700ddc6946 100644 --- a/source/lib/sysdep/os/win/winit.h +++ b/source/lib/sysdep/os/win/winit.h @@ -133,29 +133,29 @@ Several methods of module init are possible: (see Large Scale C++ Design) // very early init; must not fail, since error handling code *crashes* // if called before these have completed. -#define WINIT_REGISTER_CRITICAL_INIT(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static LibError func(); EXTERN_C __declspec(allocate(".WINIT$I0")) LibError (*p##func)(void) = func +#define WINIT_REGISTER_CRITICAL_INIT(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static Status func(); EXTERN_C __declspec(allocate(".WINIT$I0")) Status (*p##func)(void) = func // meant for modules with dependents but whose init is complicated and may // raise error/warning messages (=> can't go in WINIT_REGISTER_CRITICAL_INIT) -#define WINIT_REGISTER_EARLY_INIT(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static LibError func(); EXTERN_C __declspec(allocate(".WINIT$I1")) LibError (*p##func)(void) = func +#define WINIT_REGISTER_EARLY_INIT(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static Status func(); EXTERN_C __declspec(allocate(".WINIT$I1")) Status (*p##func)(void) = func // available for dependents of WINIT_REGISTER_EARLY_INIT-modules that // must still come before WINIT_REGISTER_MAIN_INIT. -#define WINIT_REGISTER_EARLY_INIT2(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static LibError func(); EXTERN_C __declspec(allocate(".WINIT$I2")) LibError (*p##func)(void) = func +#define WINIT_REGISTER_EARLY_INIT2(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static Status func(); EXTERN_C __declspec(allocate(".WINIT$I2")) Status (*p##func)(void) = func // most modules will go here unless they are often used or // have many dependents. -#define WINIT_REGISTER_MAIN_INIT(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static LibError func(); EXTERN_C __declspec(allocate(".WINIT$I6")) LibError (*p##func)(void) = func +#define WINIT_REGISTER_MAIN_INIT(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static Status func(); EXTERN_C __declspec(allocate(".WINIT$I6")) Status (*p##func)(void) = func // available for any modules that may need to come after // WINIT_REGISTER_MAIN_INIT (unlikely) -#define WINIT_REGISTER_LATE_INIT(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static LibError func(); EXTERN_C __declspec(allocate(".WINIT$I7")) LibError (*p##func)(void) = func +#define WINIT_REGISTER_LATE_INIT(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static Status func(); EXTERN_C __declspec(allocate(".WINIT$I7")) Status (*p##func)(void) = func -#define WINIT_REGISTER_EARLY_SHUTDOWN(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static LibError func(); EXTERN_C __declspec(allocate(".WINIT$S0")) LibError (*p##func)(void) = func -#define WINIT_REGISTER_EARLY_SHUTDOWN2(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static LibError func(); EXTERN_C __declspec(allocate(".WINIT$S1")) LibError (*p##func)(void) = func -#define WINIT_REGISTER_MAIN_SHUTDOWN(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static LibError func(); EXTERN_C __declspec(allocate(".WINIT$S6")) LibError (*p##func)(void) = func -#define WINIT_REGISTER_LATE_SHUTDOWN(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static LibError func(); EXTERN_C __declspec(allocate(".WINIT$S7")) LibError (*p##func)(void) = func -#define WINIT_REGISTER_LATE_SHUTDOWN2(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static LibError func(); EXTERN_C __declspec(allocate(".WINIT$S8")) LibError (*p##func)(void) = func +#define WINIT_REGISTER_EARLY_SHUTDOWN(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static Status func(); EXTERN_C __declspec(allocate(".WINIT$S0")) Status (*p##func)(void) = func +#define WINIT_REGISTER_EARLY_SHUTDOWN2(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static Status func(); EXTERN_C __declspec(allocate(".WINIT$S1")) Status (*p##func)(void) = func +#define WINIT_REGISTER_MAIN_SHUTDOWN(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static Status func(); EXTERN_C __declspec(allocate(".WINIT$S6")) Status (*p##func)(void) = func +#define WINIT_REGISTER_LATE_SHUTDOWN(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static Status func(); EXTERN_C __declspec(allocate(".WINIT$S7")) Status (*p##func)(void) = func +#define WINIT_REGISTER_LATE_SHUTDOWN2(func) __pragma(comment(linker, "/include:" STRINGIZE(DECORATED_NAME(p##func)))) static Status func(); EXTERN_C __declspec(allocate(".WINIT$S8")) Status (*p##func)(void) = func //----------------------------------------------------------------------------- diff --git a/source/lib/sysdep/os/win/wiocp.cpp b/source/lib/sysdep/os/win/wiocp.cpp index bb6d056d4d..4696407cac 100644 --- a/source/lib/sysdep/os/win/wiocp.cpp +++ b/source/lib/sysdep/os/win/wiocp.cpp @@ -15,7 +15,7 @@ void AttachToCompletionPort(HANDLE hFile, HANDLE& hIOCP, ULONG_PTR key, DWORD nu } -LibError PollCompletionPort(HANDLE hIOCP, DWORD timeout, DWORD& bytesTransferred, ULONG_PTR& key, OVERLAPPED*& ovl) +Status PollCompletionPort(HANDLE hIOCP, DWORD timeout, DWORD& bytesTransferred, ULONG_PTR& key, OVERLAPPED*& ovl) { if(hIOCP == 0) return ERR::INVALID_HANDLE; // NOWARN (happens if called before the first Attach) diff --git a/source/lib/sysdep/os/win/wiocp.h b/source/lib/sysdep/os/win/wiocp.h index 60486ca7e6..dbb0499cbd 100644 --- a/source/lib/sysdep/os/win/wiocp.h +++ b/source/lib/sysdep/os/win/wiocp.h @@ -45,6 +45,6 @@ // @param hIOCP 0 to create a new port extern void AttachToCompletionPort(HANDLE hFile, HANDLE& hIOCP, ULONG_PTR key, DWORD numConcurrentThreads = 0); -extern LibError PollCompletionPort(HANDLE hIOCP, DWORD timeout, DWORD& bytesTransferred, ULONG_PTR& key, OVERLAPPED*& ovl); +extern Status PollCompletionPort(HANDLE hIOCP, DWORD timeout, DWORD& bytesTransferred, ULONG_PTR& key, OVERLAPPED*& ovl); #endif // #ifndef INCLUDED_WIOCP diff --git a/source/lib/sysdep/os/win/wmi.cpp b/source/lib/sysdep/os/win/wmi.cpp index ad4ddd4f96..0f325ac721 100644 --- a/source/lib/sysdep/os/win/wmi.cpp +++ b/source/lib/sysdep/os/win/wmi.cpp @@ -42,7 +42,7 @@ _COM_SMARTPTR_TYPEDEF(IEnumWbemClassObject, __uuidof(IEnumWbemClassObject)); static ModuleInitState initState; -static LibError Init() +static Status Init() { HRESULT hr; @@ -85,9 +85,9 @@ void wmi_Shutdown() } -LibError wmi_GetClass(const wchar_t* className, WmiMap& wmiMap) +Status wmi_GetClass(const wchar_t* className, WmiMap& wmiMap) { - RETURN_ERR(ModuleInit(&initState, Init)); + RETURN_STATUS_IF_ERR(ModuleInit(&initState, Init)); IEnumWbemClassObjectPtr pEnum = 0; wchar_t query[200]; diff --git a/source/lib/sysdep/os/win/wmi.h b/source/lib/sysdep/os/win/wmi.h index d3a7b8c812..9c95fa2ede 100644 --- a/source/lib/sysdep/os/win/wmi.h +++ b/source/lib/sysdep/os/win/wmi.h @@ -40,9 +40,9 @@ typedef std::map WmiMap; /** * return a map of name/value pairs of the WMI class members. - * @return LibError + * @return Status **/ -extern LibError wmi_GetClass(const wchar_t* className, WmiMap& wmiMap); +extern Status wmi_GetClass(const wchar_t* className, WmiMap& wmiMap); extern void wmi_Shutdown(); diff --git a/source/lib/sysdep/os/win/wnuma.cpp b/source/lib/sysdep/os/win/wnuma.cpp index de0b69bd95..7a532e1453 100644 --- a/source/lib/sysdep/os/win/wnuma.cpp +++ b/source/lib/sysdep/os/win/wnuma.cpp @@ -293,7 +293,7 @@ static void PopulateNodesFromProximityDomains(const ProximityDomains& proximityD static ModuleInitState initState; -static LibError InitTopology() +static Status InitTopology() { PopulateNodes(); @@ -429,7 +429,7 @@ static double MeasureRelativeDistance() static double relativeDistance; -static LibError InitRelativeDistance() +static Status InitRelativeDistance() { // early-out for non-NUMA systems (saves some time) if(numa_NumNodes() == 1) @@ -474,7 +474,7 @@ static bool IsMemoryInterleaved() static bool isMemoryInterleaved; -static LibError InitMemoryInterleaved() +static Status InitMemoryInterleaved() { isMemoryInterleaved = IsMemoryInterleaved(); return INFO::OK; diff --git a/source/lib/sysdep/os/win/wposix/waio.cpp b/source/lib/sysdep/os/win/wposix/waio.cpp index ea1baf9d39..26e352f5db 100644 --- a/source/lib/sysdep/os/win/wposix/waio.cpp +++ b/source/lib/sysdep/os/win/wposix/waio.cpp @@ -66,7 +66,7 @@ struct OvlAllocator // POD OVERLAPPED ovl; }; - LibError Init() + Status Init() { // the allocation must be naturally aligned to ensure it doesn't // overlap another page, which might prevent SetFileIoOverlappedRange @@ -183,7 +183,7 @@ struct FileControlBlock // POD OvlAllocator ovl; - LibError Init() + Status Init() { fd = FD_AVAILABLE; hFile = INVALID_HANDLE_VALUE; @@ -260,7 +260,7 @@ static FileControlBlock* FindFileControlBlock(int fd) static ModuleInitState waio_initState; -static LibError waio_Init() +static Status waio_Init() { for(size_t i = 0; i < ARRAY_SIZE(fileControlBlocks); i++) fileControlBlocks[i].Init(); @@ -281,7 +281,7 @@ static LibError waio_Init() } -static LibError waio_Shutdown() +static Status waio_Shutdown() { if(waio_initState == 0) // we were never initialized return INFO::OK; @@ -354,7 +354,7 @@ static DWORD FlagsAndAttributes() return flags|attributes; } -static LibError OpenFile(const OsPath& pathname, int oflag, HANDLE& hFile) +static Status OpenFile(const OsPath& pathname, int oflag, HANDLE& hFile) { WinScopedPreserveLastError s; @@ -364,7 +364,7 @@ static LibError OpenFile(const OsPath& pathname, int oflag, HANDLE& hFile) const DWORD flags = FlagsAndAttributes(); hFile = CreateFileW(OsString(pathname).c_str(), access, share, 0, create, flags, 0); if(hFile == INVALID_HANDLE_VALUE) - return LibError_from_GLE(); + WARN_RETURN(StatusFromWin()); return INFO::OK; } @@ -373,7 +373,7 @@ static LibError OpenFile(const OsPath& pathname, int oflag, HANDLE& hFile) //----------------------------------------------------------------------------- // Windows-only APIs -LibError waio_reopen(int fd, const OsPath& pathname, int oflag, ...) +Status waio_reopen(int fd, const OsPath& pathname, int oflag, ...) { ENSURE(fd > 2); ENSURE(!(oflag & O_APPEND)); // not supported @@ -381,10 +381,10 @@ LibError waio_reopen(int fd, const OsPath& pathname, int oflag, ...) if(oflag & O_NO_AIO_NP) return INFO::SKIPPED; - RETURN_ERR(ModuleInit(&waio_initState, waio_Init)); + RETURN_STATUS_IF_ERR(ModuleInit(&waio_initState, waio_Init)); HANDLE hFile; - RETURN_ERR(OpenFile(pathname, oflag, hFile)); + RETURN_STATUS_IF_ERR(OpenFile(pathname, oflag, hFile)); if(!AssociateFileControlBlock(fd, hFile)) { @@ -396,7 +396,7 @@ LibError waio_reopen(int fd, const OsPath& pathname, int oflag, ...) } -LibError waio_close(int fd) +Status waio_close(int fd) { FileControlBlock* fcb = FindFileControlBlock(fd); if(!fcb) @@ -412,7 +412,7 @@ LibError waio_close(int fd) } -LibError waio_Preallocate(int fd, off_t size) +Status waio_Preallocate(int fd, off_t size) { FileControlBlock* fcb = FindFileControlBlock(fd); if(!fcb) @@ -420,7 +420,7 @@ LibError waio_Preallocate(int fd, off_t size) const HANDLE hFile = fcb->hFile; // Windows requires sector alignment (see discussion in header) - const off_t alignedSize = round_up(size, (off_t)maxSectorSize); + const off_t alignedSize = round_up(size, (off_t)maxSectorSize); // (Align<> cannot compute off_t) // allocate all space up front to reduce fragmentation LARGE_INTEGER size64; size64.QuadPart = alignedSize; @@ -479,7 +479,9 @@ static int Issue(aiocb* cb) if(ok || GetLastError() == ERROR_IO_PENDING) return 0; // success - LibError_set_errno(LibError_from_GLE()); + const Status status = StatusFromWin(); + WARN_IF_ERR(status); + errno = ErrnoFromStatus(status); return -1; } @@ -562,7 +564,7 @@ int aio_suspend(const struct aiocb* const cbs[], int n, const struct timespec* t // is not desirable because POSIX doesn't require aio_suspend to be // called, which means notifications might pile up. const DWORD milliseconds = 1; // as short as possible (don't oversleep) - const LibError ret = PollCompletionPort(hIOCP, milliseconds, bytesTransferred, key, ovl); + const Status ret = PollCompletionPort(hIOCP, milliseconds, bytesTransferred, key, ovl); if(ret != INFO::OK && ret != ERR::AGAIN) // failed { ENSURE(0); @@ -621,7 +623,7 @@ int aio_cancel(int UNUSED(fd), struct aiocb* cb) const HANDLE hFile = ((const FileControlBlock*)cb->fcb)->hFile; if(hFile == INVALID_HANDLE_VALUE) { - WARN_ERR(ERR::INVALID_HANDLE); + WARN_IF_ERR(ERR::INVALID_HANDLE); errno = EINVAL; return -1; } @@ -637,7 +639,7 @@ int aio_cancel(int UNUSED(fd), struct aiocb* cb) int aio_fsync(int, struct aiocb*) { - WARN_ERR(ERR::NOT_IMPLEMENTED); + WARN_IF_ERR(ERR::NOT_IMPLEMENTED); errno = ENOSYS; return -1; } diff --git a/source/lib/sysdep/os/win/wposix/waio.h b/source/lib/sysdep/os/win/wposix/waio.h index 2cac058432..c2cc1465d3 100644 --- a/source/lib/sysdep/os/win/wposix/waio.h +++ b/source/lib/sysdep/os/win/wposix/waio.h @@ -27,7 +27,7 @@ #ifndef INCLUDED_WAIO #define INCLUDED_WAIO -#include "lib/lib_errors.h" +#include "lib/status.h" #include "lib/os_path.h" #include "lib/posix/posix_time.h" // timespec #include "lib/sysdep/os/win/wposix/wposix_types.h" @@ -122,10 +122,10 @@ extern int aio_fsync(int, struct aiocb*); // notified of the file descriptor, which means e.g. read and aio_read can // both be used. this function must have been called before any // other [w]aio_* functions are used. -extern LibError waio_reopen(int fd, const OsPath& pathname, int oflag, ...); +extern Status waio_reopen(int fd, const OsPath& pathname, int oflag, ...); // close our second aio-enabled handle to the file (called from wclose). -extern LibError waio_close(int fd); +extern Status waio_close(int fd); // call this before writing a large file to preallocate clusters, thus // reducing fragmentation. @@ -143,6 +143,6 @@ extern LibError waio_close(int fd); // note that this exposes the previous disk contents (possibly even to // other users since the waio_reopen design cannot deny file sharing) until // the application successfully writes to the file. -LIB_API LibError waio_Preallocate(int fd, off_t size); +LIB_API Status waio_Preallocate(int fd, off_t size); #endif // #ifndef INCLUDED_WAIO diff --git a/source/lib/sysdep/os/win/wposix/wdlfcn.cpp b/source/lib/sysdep/os/win/wposix/wdlfcn.cpp index b15902c6c1..c1b37b9e13 100644 --- a/source/lib/sysdep/os/win/wposix/wdlfcn.cpp +++ b/source/lib/sysdep/os/win/wposix/wdlfcn.cpp @@ -39,8 +39,7 @@ static void* void_from_HMODULE(HMODULE hModule) int dlclose(void* handle) { - BOOL ok = FreeLibrary(HMODULE_from_void(handle)); - WARN_RETURN_IF_FALSE(ok); + WARN_IF_FALSE(FreeLibrary(HMODULE_from_void(handle))); return 0; } diff --git a/source/lib/sysdep/os/win/wposix/wfilesystem.cpp b/source/lib/sysdep/os/win/wposix/wfilesystem.cpp index e03e88e074..bdd0cbdad3 100644 --- a/source/lib/sysdep/os/win/wposix/wfilesystem.cpp +++ b/source/lib/sysdep/os/win/wposix/wfilesystem.cpp @@ -24,7 +24,7 @@ #include "lib/sysdep/filesystem.h" #include "lib/sysdep/cpu.h" // cpu_CAS -#include "lib/sysdep/os/win/wutil.h" // LibError_from_GLE +#include "lib/sysdep/os/win/wutil.h" // StatusFromWin #include "lib/sysdep/os/win/wposix/waio.h" // waio_reopen #include "lib/sysdep/os/win/wposix/wtime_internal.h" // wtime_utc_filetime_to_time_t #include "lib/sysdep/os/win/wposix/crt_posix.h" // _close, _lseeki64 etc. @@ -128,12 +128,15 @@ WDIR* wopendir(const OsPath& path) if(GetLastError() == ERROR_NO_MORE_FILES) return d; // success, but directory is empty - LibError_set_errno(LibError_from_GLE()); + Status status = StatusFromWin(); // release the WDIR allocated above (this is preferable to // always copying the large WDIR or findData from a temporary) wdir_free(d); + WARN_IF_ERR(status); + errno = ErrnoFromStatus(status); + return 0; } @@ -154,7 +157,7 @@ struct wdirent* wreaddir(WDIR* d) if(!FindNextFileW(d->hFind, &d->findData)) { if(GetLastError() != ERROR_NO_MORE_FILES) // an actual error occurred - (void)LibError_from_GLE(); // raise warning + WARN_IF_ERR(StatusFromWin()); return 0; // end of directory or error } } @@ -224,12 +227,7 @@ int wopen(const OsPath& pathname, int oflag, mode_t mode_arg) if(waio_reopen(fd, pathname, oflag) != INFO::OK) return -1; - // CRT doesn't like more than 255 files open. - // warn now, so that we notice why so many are open. -#ifndef NDEBUG - if(fd > 256) - WARN_ERR(ERR::LIMIT); -#endif + ASSERT(fd < 256); // CRT limitation return fd; } diff --git a/source/lib/sysdep/os/win/wposix/wmman.cpp b/source/lib/sysdep/os/win/wposix/wmman.cpp index de36c0bdb7..63dcca5dde 100644 --- a/source/lib/sysdep/os/win/wposix/wmman.cpp +++ b/source/lib/sysdep/os/win/wposix/wmman.cpp @@ -65,16 +65,16 @@ static DWORD win32_prot(int prot) int mprotect(void* addr, size_t len, int prot) { - const DWORD flNewProtect = win32_prot(prot); - DWORD flOldProtect; // required by VirtualProtect - BOOL ok = VirtualProtect(addr, len, flNewProtect, &flOldProtect); - WARN_RETURN_IF_FALSE(ok); - return 0; + const DWORD newProtect = win32_prot(prot); + DWORD oldProtect; // required by VirtualProtect + const BOOL ok = VirtualProtect(addr, len, newProtect, &oldProtect); + WARN_IF_FALSE(ok); + return ok? 0 : -1; } // called when flags & MAP_ANONYMOUS -static LibError mmap_mem(void* start, size_t len, int prot, int flags, int fd, void** pp) +static Status mmap_mem(void* start, size_t len, int prot, int flags, int fd, void** pp) { // sanity checks. we don't care about these but enforce them to // ensure callers are compatible with mmap. @@ -91,7 +91,8 @@ static LibError mmap_mem(void* start, size_t len, int prot, int flags, int fd, v if(!want_commit && start != 0 && flags & MAP_FIXED) { MEMORY_BASIC_INFORMATION mbi; - WARN_RETURN_IF_FALSE(VirtualQuery(start, &mbi, sizeof(mbi))); + if(!VirtualQuery(start, &mbi, sizeof(mbi))) + WARN_RETURN(StatusFromWin()); if(mbi.State == MEM_COMMIT) { WARN_IF_FALSE(VirtualFree(start, len, MEM_DECOMMIT)); @@ -102,9 +103,9 @@ static LibError mmap_mem(void* start, size_t len, int prot, int flags, int fd, v } } - DWORD flAllocationType = want_commit? MEM_COMMIT : MEM_RESERVE; - DWORD flProtect = win32_prot(prot); - void* p = VirtualAlloc(start, len, flAllocationType, flProtect); + const DWORD allocationType = want_commit? MEM_COMMIT : MEM_RESERVE; + const DWORD protect = win32_prot(prot); + void* p = VirtualAlloc(start, len, allocationType, protect); if(!p) { debug_printf(L"wmman: VirtualAlloc(%p, 0x%I64X) failed\n", start, len); @@ -119,10 +120,10 @@ static LibError mmap_mem(void* start, size_t len, int prot, int flags, int fd, v // CreateFileMapping / MapViewOfFile. they only support read-only, // read/write and copy-on-write, so we dumb it down to that and later // set the correct (and more restrictive) permission via mprotect. -static LibError mmap_file_access(int prot, int flags, DWORD& flProtect, DWORD& dwAccess) +static Status mmap_file_access(int prot, int flags, DWORD& protect, DWORD& dwAccess) { // assume read-only; other cases handled below. - flProtect = PAGE_READONLY; + protect = PAGE_READONLY; dwAccess = FILE_MAP_READ; if(prot & PROT_WRITE) @@ -132,12 +133,12 @@ static LibError mmap_file_access(int prot, int flags, DWORD& flProtect, DWORD& d { // .. changes are written to file. case MAP_SHARED: - flProtect = PAGE_READWRITE; + protect = PAGE_READWRITE; dwAccess = FILE_MAP_WRITE; // read and write break; // .. copy-on-write mapping; writes do not affect the file. case MAP_PRIVATE: - flProtect = PAGE_WRITECOPY; + protect = PAGE_WRITECOPY; dwAccess = FILE_MAP_COPY; break; // .. either none or both of the flags are set. the latter is @@ -152,7 +153,7 @@ static LibError mmap_file_access(int prot, int flags, DWORD& flProtect, DWORD& d } -static LibError mmap_file(void* start, size_t len, int prot, int flags, int fd, off_t ofs, void** pp) +static Status mmap_file(void* start, size_t len, int prot, int flags, int fd, off_t ofs, void** pp) { WinScopedPreserveLastError s; @@ -170,11 +171,11 @@ static LibError mmap_file(void* start, size_t len, int prot, int flags, int fd, // choose protection and access rights for CreateFileMapping / // MapViewOfFile. these are weaker than what PROT_* allows and // are augmented below by subsequently mprotect-ing. - DWORD flProtect; DWORD dwAccess; - RETURN_ERR(mmap_file_access(prot, flags, flProtect, dwAccess)); + DWORD protect; DWORD dwAccess; + RETURN_STATUS_IF_ERR(mmap_file_access(prot, flags, protect, dwAccess)); // enough foreplay; now actually map. - const HANDLE hMap = CreateFileMapping(hFile, 0, flProtect, 0, 0, 0); + const HANDLE hMap = CreateFileMapping(hFile, 0, protect, 0, 0, 0); // .. create failed; bail now to avoid overwriting the last error value. if(!hMap) WARN_RETURN(ERR::NO_MEM); @@ -208,16 +209,15 @@ void* mmap(void* start, size_t len, int prot, int flags, int fd, off_t ofs) } void* p; - LibError err; + Status status; if(flags & MAP_ANONYMOUS) - err = mmap_mem(start, len, prot, flags, fd, &p); + status = mmap_mem(start, len, prot, flags, fd, &p); else - err = mmap_file(start, len, prot, flags, fd, ofs, &p); - if(err < 0) + status = mmap_file(start, len, prot, flags, fd, ofs, &p); + if(status < 0) { - WARN_ERR(err); - LibError_set_errno(err); - return MAP_FAILED; + errno = ErrnoFromStatus(status); + return MAP_FAILED; // NOWARN - already done } return p; @@ -232,9 +232,6 @@ int munmap(void* start, size_t UNUSED(len)) if(!ok) // VirtualFree requires dwSize to be 0 (entire region is released). ok = VirtualFree(start, 0, MEM_RELEASE); - - WARN_RETURN_IF_FALSE(ok); // both failed - return 0; + WARN_IF_FALSE(ok); + return ok? 0 : -1; } - - diff --git a/source/lib/sysdep/os/win/wposix/wpthread.cpp b/source/lib/sysdep/os/win/wposix/wpthread.cpp index ba5a92eb21..521efac4a1 100644 --- a/source/lib/sysdep/os/win/wposix/wpthread.cpp +++ b/source/lib/sysdep/os/win/wposix/wpthread.cpp @@ -147,7 +147,7 @@ int pthread_key_create(pthread_key_t* key, void (*dtor)(void*)) } // not enough slots; we have a valid key, but its dtor won't be called. - WARN_ERR(ERR::LIMIT); + WARN_IF_ERR(ERR::LIMIT); return -1; have_slot: @@ -187,7 +187,7 @@ void* pthread_getspecific(pthread_key_t key) SetLastError(last_err); } else - WARN_ERR(ERR::FAIL); + WARN_IF_ERR(ERR::FAIL); return data; } @@ -222,7 +222,7 @@ again: void* tls = pthread_getspecific(key); if(tls) { - WARN_ERR(pthread_setspecific(key, 0)); + WARN_IF_ERR(pthread_setspecific(key, 0)); dtor(tls); had_valid_tls = true; @@ -474,7 +474,7 @@ static DWORD calc_timeout_length_ms(const struct timespec* abs_timeout, // that's the Win32 INFINITE value. if(length_ms >= 0xFFFFFFFF) { - WARN_ERR(ERR::LIMIT); + WARN_IF_ERR(ERR::LIMIT); length_ms = 0xfffffffe; } return (DWORD)(length_ms & 0xFFFFFFFF); @@ -533,7 +533,7 @@ int sem_msgwait_np(sem_t* sem) else { errno = EINVAL; - WARN_ERR(ERR::FAIL); + WARN_IF_ERR(ERR::FAIL); } return -1; } @@ -604,7 +604,7 @@ int pthread_create(pthread_t* thread_id, const void* UNUSED(attr), void* (*func) FuncAndArg* func_and_arg = (FuncAndArg*)wutil_Allocate(sizeof(FuncAndArg)); if(!func_and_arg) { - WARN_ERR(ERR::NO_MEM); + WARN_IF_ERR(ERR::NO_MEM); return -1; } func_and_arg->func = func; @@ -616,7 +616,7 @@ int pthread_create(pthread_t* thread_id, const void* UNUSED(attr), void* (*func) const uintptr_t id = _beginthreadex(0, 0, thread_start, func_and_arg, 0, 0); if(!id) { - WARN_ERR(ERR::FAIL); + WARN_IF_ERR(ERR::FAIL); return -1; } @@ -646,7 +646,7 @@ int pthread_join(pthread_t thread, void** value_ptr) DWORD ret = WaitForSingleObject(hThread, INFINITE); if(ret != WAIT_OBJECT_0) { - WARN_ERR(ERR::FAIL); + WARN_IF_ERR(ERR::FAIL); return -1; } diff --git a/source/lib/sysdep/os/win/wposix/wsock.cpp b/source/lib/sysdep/os/win/wposix/wsock.cpp index be35c1ec8a..8fdb778935 100644 --- a/source/lib/sysdep/os/win/wposix/wsock.cpp +++ b/source/lib/sysdep/os/win/wposix/wsock.cpp @@ -114,7 +114,7 @@ static void ImportOptionalFunctions() //----------------------------------------------------------------------------- -static LibError Init() +static Status Init() { char d[1024]; int ret = WSAStartup(0x0002, d); // want 2.0 @@ -135,12 +135,12 @@ static ModuleInitState initState; // called from delay loader the first time a wsock function is called // (shortly before the actual wsock function is called). -static LibError OnLoad() +static Status OnLoad() { return ModuleInit(&initState, Init); } -static LibError wsock_Init() +static Status wsock_Init() { // trigger OnLoad when someone first calls a wsock function. static WdllLoadNotify loadNotify = { "ws2_32", OnLoad }; @@ -148,7 +148,7 @@ static LibError wsock_Init() return INFO::OK; } -static LibError wsock_Shutdown() +static Status wsock_Shutdown() { ModuleShutdown(&initState, Shutdown); return INFO::OK; diff --git a/source/lib/sysdep/os/win/wposix/wtime.cpp b/source/lib/sysdep/os/win/wposix/wtime.cpp index 8843c49ae3..9857d61102 100644 --- a/source/lib/sysdep/os/win/wposix/wtime.cpp +++ b/source/lib/sysdep/os/win/wposix/wtime.cpp @@ -615,7 +615,7 @@ strptime (const char *buf, const char *format, struct tm *timeptr) //----------------------------------------------------------------------------- -static LibError wtime_Init() +static Status wtime_Init() { LatchInitialSystemTime(); return INFO::OK; diff --git a/source/lib/sysdep/os/win/wprofiler.cpp b/source/lib/sysdep/os/win/wprofiler.cpp index 9047009017..e873bb4220 100644 --- a/source/lib/sysdep/os/win/wprofiler.cpp +++ b/source/lib/sysdep/os/win/wprofiler.cpp @@ -150,7 +150,7 @@ static void* prof_thread_func(void* UNUSED(data)) // call from thread that is to be profiled -LibError prof_start() +Status prof_start() { // we need a real HANDLE to the target thread for use with // Suspend|ResumeThread and GetThreadContext. @@ -168,7 +168,7 @@ LibError prof_start() return INFO::OK; } -LibError prof_shutdown() +Status prof_shutdown() { WARN_IF_FALSE(CloseHandle(prof_target_thread)); return INFO::OK; diff --git a/source/lib/sysdep/os/win/wsdl.cpp b/source/lib/sysdep/os/win/wsdl.cpp index 7a824f6cf2..b106e1d65b 100644 --- a/source/lib/sysdep/os/win/wsdl.cpp +++ b/source/lib/sysdep/os/win/wsdl.cpp @@ -1443,7 +1443,7 @@ void* SDL_GL_GetProcAddress(const char* name) // around ATI driver breakage) static ModuleInitState initState; -static LibError Init() +static Status Init() { key_Init(); return INFO::OK; @@ -1507,14 +1507,14 @@ static void RedirectStdout() if(f == 0) return; -#if CONFIG_PARANOIA +#if CONFIG_ENABLE_CHECKS // disable buffering, so that no writes are lost even if the program // crashes. only enabled in full debug mode because this is really slow! setvbuf(stdout, 0, _IONBF, 0); #endif } -static LibError wsdl_Init() +static Status wsdl_Init() { // note: SDL does this in its WinMain hook. doing so in SDL_Init would be // too late (we might miss some output), so we use winit. @@ -1524,7 +1524,7 @@ static LibError wsdl_Init() return INFO::OK; } -static LibError wsdl_Shutdown() +static Status wsdl_Shutdown() { // was redirected to stdout.txt; closing avoids a BoundsChecker warning. fclose(stdout); diff --git a/source/lib/sysdep/os/win/wsnd.cpp b/source/lib/sysdep/os/win/wsnd.cpp index 1c18a7ffd9..d9bfb059cb 100644 --- a/source/lib/sysdep/os/win/wsnd.cpp +++ b/source/lib/sysdep/os/win/wsnd.cpp @@ -124,7 +124,7 @@ static const OsPath& GetDirectSoundDriverPath() //----------------------------------------------------------------------------- -LibError win_get_snd_info() +Status win_get_snd_info() { WmiMap wmiMap; if(wmi_GetClass(L"Win32_SoundDevice", wmiMap) == INFO::OK) diff --git a/source/lib/sysdep/os/win/wsnd.h b/source/lib/sysdep/os/win/wsnd.h index b1e100b939..051a430182 100644 --- a/source/lib/sysdep/os/win/wsnd.h +++ b/source/lib/sysdep/os/win/wsnd.h @@ -23,6 +23,6 @@ #ifndef INCLUDED_WSND #define INCLUDED_WSND -extern LibError win_get_snd_info(); +extern Status win_get_snd_info(); #endif // #ifndef INCLUDED_WSND diff --git a/source/lib/sysdep/os/win/wsysdep.cpp b/source/lib/sysdep/os/win/wsysdep.cpp index aafeafb9e4..41fe85d7a4 100644 --- a/source/lib/sysdep/os/win/wsysdep.cpp +++ b/source/lib/sysdep/os/win/wsysdep.cpp @@ -331,7 +331,7 @@ ErrorReactionInternal sys_display_error(const wchar_t* text, size_t flags) // misc //----------------------------------------------------------------------------- -LibError sys_error_description_r(int user_err, wchar_t* buf, size_t max_chars) +Status sys_StatusDescription(int user_err, wchar_t* buf, size_t max_chars) { // validate user_err - Win32 doesn't have negative error numbers if(user_err < 0) @@ -364,25 +364,25 @@ LibError sys_error_description_r(int user_err, wchar_t* buf, size_t max_chars) } -static LibError GetModulePathname(HMODULE hModule, OsPath& pathname) +static Status GetModulePathname(HMODULE hModule, OsPath& pathname) { wchar_t pathnameBuf[32768]; // NTFS limit const DWORD length = (DWORD)ARRAY_SIZE(pathnameBuf); const DWORD charsWritten = GetModuleFileNameW(hModule, pathnameBuf, length); if(charsWritten == 0) // failed - return LibError_from_GLE(); + WARN_RETURN(StatusFromWin()); ENSURE(charsWritten < length); // why would the above buffer ever be exceeded? pathname = pathnameBuf; return INFO::OK; } -LibError sys_get_module_filename(void* addr, OsPath& pathname) +Status sys_get_module_filename(void* addr, OsPath& pathname) { MEMORY_BASIC_INFORMATION mbi; const SIZE_T bytesWritten = VirtualQuery(addr, &mbi, sizeof(mbi)); if(!bytesWritten) - return LibError_from_GLE(); + WARN_RETURN(StatusFromWin()); ENSURE(bytesWritten >= sizeof(mbi)); return GetModulePathname((HMODULE)mbi.AllocationBase, pathname); } @@ -420,7 +420,7 @@ static int CALLBACK BrowseCallback(HWND hWnd, unsigned int msg, LPARAM UNUSED(lP return 0; } -LibError sys_pick_directory(OsPath& path) +Status sys_pick_directory(OsPath& path) { // (must not use multi-threaded apartment due to BIF_NEWDIALOGSTYLE) const HRESULT hr = CoInitialize(0); @@ -454,11 +454,11 @@ LibError sys_pick_directory(OsPath& path) return INFO::OK; } - return LibError_from_GLE(); + WARN_RETURN(StatusFromWin()); } -LibError sys_open_url(const std::string& url) +Status sys_open_url(const std::string& url) { HINSTANCE r = ShellExecuteA(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL); if ((int)(intptr_t)r > 32) @@ -468,18 +468,18 @@ LibError sys_open_url(const std::string& url) } -LibError sys_generate_random_bytes(u8* buffer, size_t size) +Status sys_generate_random_bytes(u8* buffer, size_t size) { HCRYPTPROV hCryptProv = 0; if(!CryptAcquireContext(&hCryptProv, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) - return LibError_from_GLE(); + WARN_RETURN(StatusFromWin()); memset(buffer, 0, size); if(!CryptGenRandom(hCryptProv, (DWORD)size, (BYTE*)buffer)) - return LibError_from_GLE(); + WARN_RETURN(StatusFromWin()); if(!CryptReleaseContext(hCryptProv, 0)) - return LibError_from_GLE(); + WARN_RETURN(StatusFromWin()); return INFO::OK; } @@ -511,7 +511,7 @@ static std::wstring parse_proxy(const std::wstring& input) return L""; } -LibError sys_get_proxy_config(const std::wstring& url, std::wstring& proxy) +Status sys_get_proxy_config(const std::wstring& url, std::wstring& proxy) { WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions; memset(&autoProxyOptions, 0, sizeof(autoProxyOptions)); @@ -527,7 +527,7 @@ LibError sys_get_proxy_config(const std::wstring& url, std::wstring& proxy) HINTERNET hSession = NULL; - LibError err = INFO::SKIPPED; + Status err = INFO::SKIPPED; bool useAutoDetect; diff --git a/source/lib/sysdep/os/win/wutil.cpp b/source/lib/sysdep/os/win/wutil.cpp index bee30f3910..a8cce82d6e 100644 --- a/source/lib/sysdep/os/win/wutil.cpp +++ b/source/lib/sysdep/os/win/wutil.cpp @@ -123,59 +123,36 @@ static void ShutdownLocks() // error codes // only call after a Win32 function indicates failure. -LibError LibError_from_GLE(bool warn_if_failed) +Status StatusFromWin() { - LibError err = ERR::FAIL; switch(GetLastError()) { case ERROR_OUTOFMEMORY: case ERROR_NOT_ENOUGH_MEMORY: - err = ERR::NO_MEM; - break; + return ERR::NO_MEM; case ERROR_INVALID_HANDLE: case ERROR_INVALID_PARAMETER: case ERROR_BAD_ARGUMENTS: - err = ERR::INVALID_PARAM; - break; + return ERR::INVALID_PARAM; case ERROR_INSUFFICIENT_BUFFER: - err = ERR::BUF_SIZE; - break; + return ERR::BUF_SIZE; case ERROR_ACCESS_DENIED: - err = ERR::FILE_ACCESS; - break; + return ERR::FILE_ACCESS; case ERROR_NOT_SUPPORTED: - err = ERR::NOT_SUPPORTED; - break; + return ERR::NOT_SUPPORTED; case ERROR_CALL_NOT_IMPLEMENTED: - err = ERR::NOT_IMPLEMENTED; - break; + return ERR::NOT_IMPLEMENTED; case ERROR_PROC_NOT_FOUND: - err = ERR::NO_SYS; - break; + return ERR::NO_SYS; case ERROR_BUSY: - err = ERR::AGAIN; - break; + return ERR::AGAIN; case ERROR_FILE_NOT_FOUND: - err = ERR::VFS_FILE_NOT_FOUND; - break; + return ERR::VFS_FILE_NOT_FOUND; case ERROR_PATH_NOT_FOUND: - err = ERR::VFS_DIR_NOT_FOUND; - break; + return ERR::VFS_DIR_NOT_FOUND; default: - break; // err already set above + return ERR::FAIL; } - - if(warn_if_failed) - DEBUG_WARN_ERR(err); - return err; -} - - -LibError LibError_from_win32(DWORD ret, bool warn_if_failed) -{ - if(ret != FALSE) - return INFO::OK; - return LibError_from_GLE(warn_if_failed); } @@ -440,7 +417,7 @@ WinScopedDisableWow64Redirection::~WinScopedDisableWow64Redirection() //----------------------------------------------------------------------------- -LibError wutil_SetPrivilege(const wchar_t* privilege, bool enable) +Status wutil_SetPrivilege(const wchar_t* privilege, bool enable) { WinScopedPreserveLastError s; @@ -504,29 +481,21 @@ static HWND hAppWindow; static BOOL CALLBACK FindAppWindowByPid(HWND hWnd, LPARAM UNUSED(lParam)) { DWORD pid; - (void)GetWindowThreadProcessId(hWnd, &pid); // (function always succeeds) + DWORD tid = GetWindowThreadProcessId(hWnd, &pid); + UNUSED2(tid); if(pid == GetCurrentProcessId()) - { hAppWindow = hWnd; - return FALSE; // done - } return TRUE; // keep calling } - HWND wutil_AppWindow() { if(!hAppWindow) { - // to avoid wasting time, FindAppWindowByPid returns FALSE after - // finding the desired window, which causes EnumWindows to 'fail'. - // we detect actual errors by checking GetLastError. - WinScopedPreserveLastError s; - SetLastError(0); - (void)EnumWindows(FindAppWindowByPid, 0); // (see above) - ENSURE(GetLastError() == 0); + WARN_IF_FALSE(EnumWindows(FindAppWindowByPid, 0)); + ENSURE(hAppWindow != 0); } return hAppWindow; @@ -535,7 +504,7 @@ HWND wutil_AppWindow() //----------------------------------------------------------------------------- -static LibError wutil_Init() +static Status wutil_Init() { InitLocks(); @@ -554,7 +523,7 @@ static LibError wutil_Init() } -static LibError wutil_Shutdown() +static Status wutil_Shutdown() { FreeCommandLine(); diff --git a/source/lib/sysdep/os/win/wutil.h b/source/lib/sysdep/os/win/wutil.h index eca2046358..cf49e533af 100644 --- a/source/lib/sysdep/os/win/wutil.h +++ b/source/lib/sysdep/os/win/wutil.h @@ -137,22 +137,12 @@ private: /** - * @return the LibError equivalent of GetLastError(), or ERR::FAIL if + * @return the Status equivalent of GetLastError(), or ERR::FAIL if * there's no equivalent. - * you should SetLastError(0) before calling whatever will set ret - * to make sure we do not report any stale errors. - * - * @param warn_if_failed if set, raises an error dialog that reports - * the LibError. + * SetLastError(0) should be called before the Windows function to + * make sure no stale errors are returned. **/ -LibError LibError_from_GLE(bool warn_if_failed = true); - -#define WARN_WIN32_ERR (void)LibError_from_GLE(true) - -/** - * @return INFO::OK if ret != FALSE, else LibError_from_GLE(). - **/ -extern LibError LibError_from_win32(DWORD ret, bool warn_if_failed = true); +extern Status StatusFromWin(); //----------------------------------------------------------------------------- @@ -190,7 +180,7 @@ private: //----------------------------------------------------------------------------- -LIB_API LibError wutil_SetPrivilege(const wchar_t* privilege, bool enable); +LIB_API Status wutil_SetPrivilege(const wchar_t* privilege, bool enable); /** * @return module handle of lib code (that of the main EXE if diff --git a/source/lib/sysdep/os/win/wversion.cpp b/source/lib/sysdep/os/win/wversion.cpp index 0ff632dd2b..faa7299137 100644 --- a/source/lib/sysdep/os/win/wversion.cpp +++ b/source/lib/sysdep/os/win/wversion.cpp @@ -67,7 +67,7 @@ size_t wversion_Number() } -static LibError wversion_Init() +static Status wversion_Init() { // note: don't use GetVersion[Ex] because it gives the version of the // emulated OS when running an app with compatibility shims enabled. diff --git a/source/lib/sysdep/os_cpu.cpp b/source/lib/sysdep/os_cpu.cpp index 3df8101538..d062ef3a6d 100644 --- a/source/lib/sysdep/os_cpu.cpp +++ b/source/lib/sysdep/os_cpu.cpp @@ -35,7 +35,7 @@ #endif -ERROR_ASSOCIATE(ERR::OS_CPU_RESTRICTED_AFFINITY, L"Cannot set desired CPU affinity", -1); +STATUS_DEFINE(ERR, OS_CPU_RESTRICTED_AFFINITY, L"Cannot set desired CPU affinity", -1); double os_cpu_ClockFrequency() diff --git a/source/lib/sysdep/os_cpu.h b/source/lib/sysdep/os_cpu.h index a724987a10..0902e363c8 100644 --- a/source/lib/sysdep/os_cpu.h +++ b/source/lib/sysdep/os_cpu.h @@ -29,7 +29,7 @@ namespace ERR { - const LibError OS_CPU_RESTRICTED_AFFINITY = -130100; + const Status OS_CPU_RESTRICTED_AFFINITY = -130100; } @@ -154,6 +154,6 @@ typedef void (*OsCpuCallback)(size_t processor, uintptr_t cbData); * order of processor ID. * fails if process affinity prevents running on all processors. **/ -LIB_API LibError os_cpu_CallByEachCPU(OsCpuCallback cb, uintptr_t cbData); +LIB_API Status os_cpu_CallByEachCPU(OsCpuCallback cb, uintptr_t cbData); #endif // #ifndef INCLUDED_OS_CPU diff --git a/source/lib/sysdep/smbios.cpp b/source/lib/sysdep/smbios.cpp index 9a9150153c..4f8c759a57 100644 --- a/source/lib/sysdep/smbios.cpp +++ b/source/lib/sysdep/smbios.cpp @@ -44,7 +44,7 @@ namespace SMBIOS { #if OS_WIN -static LibError GetTable(wfirmware::Table& table) +static Status GetTable(wfirmware::Table& table) { // (MSDN mentions 'RSMB', but multi-character literals are implementation-defined.) const DWORD provider = FOURCC_BE('R','S','M','B'); @@ -341,28 +341,28 @@ template<> void Fixup(VoltageProbe& p) { p.location = (VoltageProbeLocation)bits(p.locationAndStatus, 0, 4); - p.status = (Status)bits(p.locationAndStatus, 5, 7); + p.status = (State)bits(p.locationAndStatus, 5, 7); } template<> void Fixup(CoolingDevice& p) { p.type = (CoolingDeviceType)bits(p.typeAndStatus, 0, 4); - p.status = (Status)bits(p.typeAndStatus, 5, 7); + p.status = (State)bits(p.typeAndStatus, 5, 7); } template<> void Fixup(TemperatureProbe& p) { p.location = (TemperatureProbeLocation)bits(p.locationAndStatus, 0, 4); - p.status = (Status)bits(p.locationAndStatus, 5, 7); + p.status = (State)bits(p.locationAndStatus, 5, 7); } template<> void Fixup(SystemPowerSupply& p) { p.type = (SystemPowerSupplyType)bits(p.characteristics, 10, 13); - p.status = (Status)bits(p.characteristics, 7, 9); + p.status = (State)bits(p.characteristics, 7, 9); p.inputSwitching = (SystemPowerSupplyInputSwitching)bits(p.characteristics, 3, 6); p.characteristics = bits(p.characteristics, 0, 2); } @@ -404,11 +404,11 @@ void AddStructure(const Header* header, const Strings& strings, Structure*& list } -static LibError InitStructures() +static Status InitStructures() { #if OS_WIN wfirmware::Table table; - RETURN_ERR(GetTable(table)); + RETURN_STATUS_IF_ERR(GetTable(table)); #else std::vector table; return ERR::NOT_IMPLEMENTED; @@ -681,7 +681,7 @@ void FieldStringizer::operator()(size_t flags, const char*& value, const Structures* GetStructures() { static ModuleInitState initState; - LibError ret = ModuleInit(&initState, InitStructures); + Status ret = ModuleInit(&initState, InitStructures); // (callers have to check if member pointers are nonzero anyway, so // we always return a valid pointer to simplify most use cases.) UNUSED2(ret); diff --git a/source/lib/sysdep/smbios.h b/source/lib/sysdep/smbios.h index 9eaeab5f1f..7f189597a6 100644 --- a/source/lib/sysdep/smbios.h +++ b/source/lib/sysdep/smbios.h @@ -34,7 +34,7 @@ namespace SMBIOS { // 2) define a _ENUMERATORS macro specifying its enumerators // (prefer lower case to avoid conflicts with macros) #define ENUMERATIONS\ - ENUMERATION(Status, u8)\ + ENUMERATION(State, u8)\ ENUMERATION(ECC, u8)\ ENUMERATION(BiosFlags, u32)\ ENUMERATION(BiosFlags1, u8)\ @@ -157,7 +157,7 @@ struct Handle }; -#define Status_ENUMERATORS\ +#define State_ENUMERATORS\ ENUM(other, 1)\ ENUM(unknown, 2)\ ENUM(ok, 3)\ @@ -351,9 +351,9 @@ struct Handle FIELD(0, const char*, version, "")\ FIELD(0, const char*, serialNumber, "")\ FIELD(0, const char*, assetTag, "")\ - FIELD(0, Status, state, "")\ - FIELD(0, Status, powerState, "")\ - FIELD(0, Status, thermalState, "")\ + FIELD(0, State, state, "")\ + FIELD(0, State, powerState, "")\ + FIELD(0, State, thermalState, "")\ FIELD(0, ChassisSecurityStatus, securityStatus, "")\ FIELD(0, u32, oemDefined, "")\ FIELD(0, u8, height, "U")\ @@ -957,7 +957,7 @@ struct Handle FIELD(0, u32, oemDefined, "")\ FIELD(0, i16, nominalValue, " mv")\ FIELD(F_DERIVED, VoltageProbeLocation, location, "")\ - FIELD(F_DERIVED, Status, status, "") + FIELD(F_DERIVED, State, status, "") //---------------------------------------------------------------------------- @@ -984,7 +984,7 @@ struct Handle FIELD(0, u16, nominalSpeed, " rpm")\ FIELD(0, const char*, description, "")\ FIELD(F_DERIVED, CoolingDeviceType, type, "")\ - FIELD(F_DERIVED, Status, status, "") + FIELD(F_DERIVED, State, status, "") //---------------------------------------------------------------------------- @@ -1018,7 +1018,7 @@ struct Handle FIELD(0, u32, oemDefined, "")\ FIELD(0, i16, nominalValue, " dDegC")\ FIELD(F_DERIVED, TemperatureProbeLocation, location, "")\ - FIELD(F_DERIVED, Status, status, "") + FIELD(F_DERIVED, State, status, "") //---------------------------------------------------------------------------- @@ -1136,7 +1136,7 @@ struct Handle FIELD(0, Handle, hCoolingDevice, "")\ FIELD(0, Handle, hCurrentProbe, "")\ FIELD(F_DERIVED, SystemPowerSupplyType, type, "")\ - FIELD(F_DERIVED, Status, status, "")\ + FIELD(F_DERIVED, State, status, "")\ FIELD(F_DERIVED, SystemPowerSupplyInputSwitching, inputSwitching, "")\ diff --git a/source/lib/sysdep/sysdep.h b/source/lib/sysdep/sysdep.h index 6f57ff4ea3..bbb032d5c3 100644 --- a/source/lib/sysdep/sysdep.h +++ b/source/lib/sysdep/sysdep.h @@ -100,18 +100,18 @@ extern int sys_vswprintf(wchar_t* buffer, size_t count, const wchar_t* format, v * rationale: it is expected to be rare that OS return/error codes are * actually seen by user code, but we leave the possibility open. **/ -extern LibError sys_error_description_r(int err, wchar_t* buf, size_t max_chars); +extern Status sys_StatusDescription(int err, wchar_t* buf, size_t max_chars); /** * determine filename of the module to whom an address belongs. * * @param addr * @param pathname Full path to module (unchanged unless INFO::OK is returned). - * @return LibError + * @return Status * * note: this is useful for handling exceptions in other modules. **/ -LibError sys_get_module_filename(void* addr, OsPath& pathname); +Status sys_get_module_filename(void* addr, OsPath& pathname); /** * @return full pathname of the current executable. @@ -134,12 +134,12 @@ extern std::wstring sys_get_user_name(); * faster browsing. if INFO::OK is returned, it receives * chosen directory path. **/ -extern LibError sys_pick_directory(OsPath& path); +extern Status sys_pick_directory(OsPath& path); /** * Open the user's default web browser to the given URL. **/ -extern LibError sys_open_url(const std::string& url); +extern Status sys_open_url(const std::string& url); /** * return the largest sector size [bytes] of any storage medium @@ -171,7 +171,7 @@ extern size_t sys_max_sector_size(); * this should only be used with small numbers of bytes, to avoid * hogging the system's entropy. **/ -LIB_API LibError sys_generate_random_bytes(u8* buf, size_t count); +LIB_API Status sys_generate_random_bytes(u8* buf, size_t count); /** * get the proxy address for accessing the given HTTP URL. @@ -180,7 +180,7 @@ LIB_API LibError sys_generate_random_bytes(u8* buf, size_t count); * * @return INFO::OK on success; INFO::SKIPPED if no proxy found. **/ -LIB_API LibError sys_get_proxy_config(const std::wstring& url, std::wstring& proxy); +LIB_API Status sys_get_proxy_config(const std::wstring& url, std::wstring& proxy); /** * open a file like with fopen (but taking an OsPath argument). diff --git a/source/lib/tests/test_wchar.h b/source/lib/tests/test_wchar.h index 92ca11d341..d3ee657b33 100644 --- a/source/lib/tests/test_wchar.h +++ b/source/lib/tests/test_wchar.h @@ -75,7 +75,7 @@ public: const std::string str_utf8(tests[i].utf8); const std::wstring str_utf16(tests[i].utf16); - LibError err; + Status err; const std::wstring str_utf8to16 = wstring_from_utf8(str_utf8, &err); TS_ASSERT_EQUALS(err, ERR::UTF8_INVALID_UTF8); TS_ASSERT_EQUALS(str_utf16.length(), str_utf8to16.length()); diff --git a/source/lib/tex/tex.cpp b/source/lib/tex/tex.cpp index b85455eabc..d38c8ae993 100644 --- a/source/lib/tex/tex.cpp +++ b/source/lib/tex/tex.cpp @@ -39,14 +39,14 @@ #include "tex_codec.h" -ERROR_ASSOCIATE(ERR::TEX_FMT_INVALID, L"Invalid/unsupported texture format", -1); -ERROR_ASSOCIATE(ERR::TEX_INVALID_COLOR_TYPE, L"Invalid color type", -1); -ERROR_ASSOCIATE(ERR::TEX_NOT_8BIT_PRECISION, L"Not 8-bit channel precision", -1); -ERROR_ASSOCIATE(ERR::TEX_INVALID_LAYOUT, L"Unsupported texel layout, e.g. right-to-left", -1); -ERROR_ASSOCIATE(ERR::TEX_COMPRESSED, L"Unsupported texture compression", -1); -ERROR_ASSOCIATE(WARN::TEX_INVALID_DATA, L"Warning: invalid texel data encountered", -1); -ERROR_ASSOCIATE(ERR::TEX_INVALID_SIZE, L"Texture size is incorrect", -1); -ERROR_ASSOCIATE(INFO::TEX_CODEC_CANNOT_HANDLE, L"Texture codec cannot handle the given format", -1); +STATUS_DEFINE(ERR, TEX_FMT_INVALID, L"Invalid/unsupported texture format", -1); +STATUS_DEFINE(ERR, TEX_INVALID_COLOR_TYPE, L"Invalid color type", -1); +STATUS_DEFINE(ERR, TEX_NOT_8BIT_PRECISION, L"Not 8-bit channel precision", -1); +STATUS_DEFINE(ERR, TEX_INVALID_LAYOUT, L"Unsupported texel layout, e.g. right-to-left", -1); +STATUS_DEFINE(ERR, TEX_COMPRESSED, L"Unsupported texture compression", -1); +STATUS_DEFINE(WARN, TEX_INVALID_DATA, L"Warning: invalid texel data encountered", -1); +STATUS_DEFINE(ERR, TEX_INVALID_SIZE, L"Texture size is incorrect", -1); +STATUS_DEFINE(INFO, TEX_CODEC_CANNOT_HANDLE, L"Texture codec cannot handle the given format", -1); //----------------------------------------------------------------------------- @@ -54,7 +54,7 @@ ERROR_ASSOCIATE(INFO::TEX_CODEC_CANNOT_HANDLE, L"Texture codec cannot handle the //----------------------------------------------------------------------------- // be careful not to use other tex_* APIs here because they call us. -LibError tex_validate(const Tex* t) +Status tex_validate(const Tex* t) { if(t->flags & TEX_UNDEFINED_FLAGS) WARN_RETURN(ERR::_1); @@ -88,14 +88,14 @@ LibError tex_validate(const Tex* t) return INFO::OK; } -#define CHECK_TEX(t) RETURN_ERR(tex_validate(t)) +#define CHECK_TEX(t) RETURN_STATUS_IF_ERR(tex_validate(t)) // check if the given texture format is acceptable: 8bpp grey, // 24bpp color or 32bpp color+alpha (BGR / upside down are permitted). // basically, this is the "plain" format understood by all codecs and // tex_codec_plain_transform. -LibError tex_validate_plain_format(size_t bpp, size_t flags) +Status tex_validate_plain_format(size_t bpp, size_t flags) { const bool alpha = (flags & TEX_ALPHA ) != 0; const bool grey = (flags & TEX_GREY ) != 0; @@ -247,7 +247,7 @@ static void create_level(size_t level, size_t level_w, size_t level_h, const u8* } -static LibError add_mipmaps(Tex* t, size_t w, size_t h, size_t bpp, void* newData, size_t data_size) +static Status add_mipmaps(Tex* t, size_t w, size_t h, size_t bpp, void* newData, size_t data_size) { // this code assumes the image is of POT dimension; we don't // go to the trouble of implementing image scaling because @@ -281,7 +281,7 @@ TIMER_ADD_CLIENT(tc_plain_transform); // but is much easier to maintain than providing all<->all conversion paths. // // somewhat optimized (loops are hoisted, cache associativity accounted for) -static LibError plain_transform(Tex* t, size_t transforms) +static Status plain_transform(Tex* t, size_t transforms) { TIMER_ACCRUE(tc_plain_transform); @@ -299,7 +299,7 @@ TIMER_ACCRUE(tc_plain_transform); if(transforms & ~(TEX_BGR|TEX_ORIENTATION|TEX_MIPMAPS|TEX_ALPHA)) return INFO::TEX_CODEC_CANNOT_HANDLE; // .. data is not in "plain" format - RETURN_ERR(tex_validate_plain_format(bpp, flags)); + RETURN_STATUS_IF_ERR(tex_validate_plain_format(bpp, flags)); // .. nothing to do if(!transforms) return INFO::OK; @@ -450,7 +450,7 @@ TIMER_ACCRUE(tc_plain_transform); t->ofs = 0; if(!(t->flags & TEX_MIPMAPS) && transforms & TEX_MIPMAPS) - RETURN_ERR(add_mipmaps(t, w, h, bpp, newData.get(), new_data_size)); + RETURN_STATUS_IF_ERR(add_mipmaps(t, w, h, bpp, newData.get(), new_data_size)); CHECK_TEX(t); return INFO::OK; @@ -461,7 +461,7 @@ TIMER_ADD_CLIENT(tc_transform); // change 's pixel format by flipping the state of all TEX_* flags // that are set in transforms. -LibError tex_transform(Tex* t, size_t transforms) +Status tex_transform(Tex* t, size_t transforms) { TIMER_ACCRUE(tc_transform); CHECK_TEX(t); @@ -475,20 +475,20 @@ LibError tex_transform(Tex* t, size_t transforms) if(remaining_transforms == 0) return INFO::OK; - LibError ret = tex_codec_transform(t, remaining_transforms); + Status ret = tex_codec_transform(t, remaining_transforms); if(ret != INFO::OK) break; } // last chance - RETURN_ERR(plain_transform(t, remaining_transforms)); + RETURN_STATUS_IF_ERR(plain_transform(t, remaining_transforms)); return INFO::OK; } // change 's pixel format to the new format specified by . // (note: this is equivalent to tex_transform(t, t->flags^new_flags). -LibError tex_transform_to(Tex* t, size_t new_flags) +Status tex_transform_to(Tex* t, size_t new_flags) { // tex_transform takes care of validating const size_t transforms = t->flags ^ new_flags; @@ -517,7 +517,7 @@ void tex_set_global_orientation(int o) static void flip_to_global_orientation(Tex* t) { // (can't use normal CHECK_TEX due to void return) - WARN_ERR(tex_validate(t)); + WARN_IF_ERR(tex_validate(t)); size_t orientation = t->flags & TEX_ORIENTATION; // if codec knows which way around the image is (i.e. not DDS): @@ -525,7 +525,7 @@ static void flip_to_global_orientation(Tex* t) { // flip image if necessary size_t transforms = orientation ^ global_orientation; - WARN_ERR(plain_transform(t, transforms)); + WARN_IF_ERR(plain_transform(t, transforms)); } // indicate image is at global orientation. this is still done even @@ -534,7 +534,7 @@ static void flip_to_global_orientation(Tex* t) t->flags = (t->flags & ~TEX_ORIENTATION) | global_orientation; // (can't use normal CHECK_TEX due to void return) - WARN_ERR(tex_validate(t)); + WARN_IF_ERR(tex_validate(t)); } @@ -587,7 +587,7 @@ bool tex_is_known_extension(const VfsPath& pathname) // // we need only add bookkeeping information and "wrap" it in // our Tex struct, hence the name. -LibError tex_wrap(size_t w, size_t h, size_t bpp, size_t flags, const shared_ptr& data, size_t ofs, Tex* t) +Status tex_wrap(size_t w, size_t h, size_t bpp, size_t flags, const shared_ptr& data, size_t ofs, Tex* t) { t->w = w; t->h = h; @@ -626,7 +626,7 @@ void tex_free(Tex* t) u8* tex_get_data(const Tex* t) { // (can't use normal CHECK_TEX due to u8* return value) - WARN_ERR(tex_validate(t)); + WARN_IF_ERR(tex_validate(t)); u8* p = t->data.get(); if(!p) @@ -656,7 +656,7 @@ u32 tex_get_average_colour(const Tex* t) basetex.ofs += size - last_level_size; // convert to BGRA - WARN_ERR(tex_transform_to(&basetex, TEX_BGR | TEX_ALPHA)); + WARN_IF_ERR(tex_transform_to(&basetex, TEX_BGR | TEX_ALPHA)); // extract components into u32 ENSURE(basetex.dataSize >= basetex.ofs+4); @@ -680,7 +680,7 @@ static void add_level_size(size_t UNUSED(level), size_t UNUSED(level_w), size_t size_t tex_img_size(const Tex* t) { // (can't use normal CHECK_TEX due to size_t return value) - WARN_ERR(tex_validate(t)); + WARN_IF_ERR(tex_validate(t)); const int levels_to_skip = (t->flags & TEX_MIPMAPS)? 0 : TEX_BASE_LEVEL_ONLY; const size_t data_padding = (t->flags & TEX_DXT)? 4 : 1; @@ -702,7 +702,7 @@ size_t tex_hdr_size(const VfsPath& filename) const TexCodecVTbl* c; const OsPath extension = filename.Extension(); - CHECK_ERR(tex_codec_for_filename(extension, &c)); + WARN_RETURN_STATUS_IF_ERR(tex_codec_for_filename(extension, &c)); return c->hdr_size(0); } @@ -711,10 +711,10 @@ size_t tex_hdr_size(const VfsPath& filename) // read/write from memory and disk //----------------------------------------------------------------------------- -LibError tex_decode(const shared_ptr& data, size_t data_size, Tex* t) +Status tex_decode(const shared_ptr& data, size_t data_size, Tex* t) { const TexCodecVTbl* c; - RETURN_ERR(tex_codec_for_header(data.get(), data_size, &c)); + RETURN_STATUS_IF_ERR(tex_codec_for_header(data.get(), data_size, &c)); // make sure the entire header is available const size_t min_hdr_size = c->hdr_size(0); @@ -731,9 +731,9 @@ LibError tex_decode(const shared_ptr& data, size_t data_size, Tex* t) // for orthogonality, encode and decode both receive the memory as a // DynArray. package data into one and free it again after decoding: DynArray da; - RETURN_ERR(da_wrap_fixed(&da, data.get(), data_size)); + RETURN_STATUS_IF_ERR(da_wrap_fixed(&da, data.get(), data_size)); - RETURN_ERR(c->decode(&da, t)); + RETURN_STATUS_IF_ERR(c->decode(&da, t)); // note: not reached if decode fails. that's not a problem; // this call just zeroes and could be left out. @@ -753,10 +753,10 @@ LibError tex_decode(const shared_ptr& data, size_t data_size, Tex* t) } -LibError tex_encode(Tex* t, const OsPath& extension, DynArray* da) +Status tex_encode(Tex* t, const OsPath& extension, DynArray* da) { CHECK_TEX(t); - CHECK_ERR(tex_validate_plain_format(t->bpp, t->flags)); + WARN_RETURN_STATUS_IF_ERR(tex_validate_plain_format(t->bpp, t->flags)); // we could be clever here and avoid the extra alloc if our current // memory block ensued from the same kind of texture file. this is @@ -764,13 +764,13 @@ LibError tex_encode(Tex* t, const OsPath& extension, DynArray* da) // this would make for zero-copy IO. const size_t max_out_size = tex_img_size(t)*4 + 256*KiB; - RETURN_ERR(da_alloc(da, max_out_size)); + RETURN_STATUS_IF_ERR(da_alloc(da, max_out_size)); const TexCodecVTbl* c; - CHECK_ERR(tex_codec_for_filename(extension, &c)); + WARN_RETURN_STATUS_IF_ERR(tex_codec_for_filename(extension, &c)); // encode into - LibError err = c->encode(t, da); + Status err = c->encode(t, da); if(err < 0) { (void)da_free(da); diff --git a/source/lib/tex/tex.h b/source/lib/tex/tex.h index 9b897a0e4a..317be3c800 100644 --- a/source/lib/tex/tex.h +++ b/source/lib/tex/tex.h @@ -112,24 +112,24 @@ library and IO layer. Read and write are zero-copy. namespace ERR { - const LibError TEX_UNKNOWN_FORMAT = -120100; - const LibError TEX_INCOMPLETE_HEADER = -120101; - const LibError TEX_FMT_INVALID = -120102; - const LibError TEX_INVALID_COLOR_TYPE = -120103; - const LibError TEX_NOT_8BIT_PRECISION = -120104; - const LibError TEX_INVALID_LAYOUT = -120105; - const LibError TEX_COMPRESSED = -120106; - const LibError TEX_INVALID_SIZE = -120107; + const Status TEX_UNKNOWN_FORMAT = -120100; + const Status TEX_INCOMPLETE_HEADER = -120101; + const Status TEX_FMT_INVALID = -120102; + const Status TEX_INVALID_COLOR_TYPE = -120103; + const Status TEX_NOT_8BIT_PRECISION = -120104; + const Status TEX_INVALID_LAYOUT = -120105; + const Status TEX_COMPRESSED = -120106; + const Status TEX_INVALID_SIZE = -120107; } namespace WARN { - const LibError TEX_INVALID_DATA = +120108; + const Status TEX_INVALID_DATA = +120108; } namespace INFO { - const LibError TEX_CODEC_CANNOT_HANDLE = +120109; + const Status TEX_CODEC_CANNOT_HANDLE = +120109; } @@ -239,9 +239,9 @@ struct Tex * Is the texture object valid and self-consistent? * * @param t - * @return LibError + * @return Status **/ -extern LibError tex_validate(const Tex* t); +extern Status tex_validate(const Tex* t); /** @@ -278,9 +278,9 @@ extern void tex_codec_unregister_all(); * @param data Input data. * @param data_size Its size [bytes]. * @param t Output texture object. - * @return LibError. + * @return Status. **/ -extern LibError tex_decode(const shared_ptr& data, size_t data_size, Tex* t); +extern Status tex_decode(const shared_ptr& data, size_t data_size, Tex* t); /** * encode a texture into a memory buffer in the desired file format. @@ -289,9 +289,9 @@ extern LibError tex_decode(const shared_ptr& data, size_t data_size, Tex* t) * @param extension (including '.'). * @param da Output memory array. Allocated here; caller must free it * when no longer needed. Invalid unless function succeeds. - * @return LibError + * @return Status **/ -extern LibError tex_encode(Tex* t, const OsPath& extension, DynArray* da); +extern Status tex_encode(Tex* t, const OsPath& extension, DynArray* da); /** * store the given image data into a Tex object; this will be as if @@ -315,16 +315,16 @@ extern LibError tex_encode(Tex* t, const OsPath& extension, DynArray* da); * @param data Img texture data. note: size is calculated from other params. * @param ofs * @param t output texture object. - * @return LibError + * @return Status **/ -extern LibError tex_wrap(size_t w, size_t h, size_t bpp, size_t flags, const shared_ptr& data, size_t ofs, Tex* t); +extern Status tex_wrap(size_t w, size_t h, size_t bpp, size_t flags, const shared_ptr& data, size_t ofs, Tex* t); /** * free all resources associated with the image and make further * use of it impossible. * * @param t texture object (note: not zeroed afterwards; see impl) - * @return LibError + * @return Status **/ extern void tex_free(Tex* t); @@ -338,9 +338,9 @@ extern void tex_free(Tex* t); * * @param t Input texture object. * @param transforms TexFlags that are to be flipped. - * @return LibError + * @return Status **/ -extern LibError tex_transform(Tex* t, size_t transforms); +extern Status tex_transform(Tex* t, size_t transforms); /** * Change \'s pixel format (2nd version) @@ -348,9 +348,9 @@ extern LibError tex_transform(Tex* t, size_t transforms); * * @param t Input texture object. * @param new_flags desired new value of TexFlags. - * @return LibError + * @return Status **/ -extern LibError tex_transform_to(Tex* t, size_t new_flags); +extern Status tex_transform_to(Tex* t, size_t new_flags); // diff --git a/source/lib/tex/tex_bmp.cpp b/source/lib/tex/tex_bmp.cpp index e415e56a55..b1a10f1a6a 100644 --- a/source/lib/tex/tex_bmp.cpp +++ b/source/lib/tex/tex_bmp.cpp @@ -60,7 +60,7 @@ struct BmpHeader #define BI_RGB 0 // biCompression -static LibError bmp_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) +static Status bmp_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) { return INFO::TEX_CODEC_CANNOT_HANDLE; } @@ -95,7 +95,7 @@ static size_t bmp_hdr_size(const u8* file) // requirements: uncompressed, direct colour, bottom up -static LibError bmp_decode(DynArray* RESTRICT da, Tex* RESTRICT t) +static Status bmp_decode(DynArray* RESTRICT da, Tex* RESTRICT t) { u8* file = da->base; @@ -126,7 +126,7 @@ static LibError bmp_decode(DynArray* RESTRICT da, Tex* RESTRICT t) } -static LibError bmp_encode(Tex* RESTRICT t, DynArray* RESTRICT da) +static Status bmp_encode(Tex* RESTRICT t, DynArray* RESTRICT da) { const size_t hdr_size = sizeof(BmpHeader); // needed for BITMAPFILEHEADER const size_t img_size = tex_img_size(t); diff --git a/source/lib/tex/tex_codec.cpp b/source/lib/tex/tex_codec.cpp index 7c8d04c566..c7e0a1e14e 100644 --- a/source/lib/tex/tex_codec.cpp +++ b/source/lib/tex/tex_codec.cpp @@ -62,7 +62,7 @@ void tex_codec_unregister_all() // or return ERR::TEX_UNKNOWN_FORMAT if unknown. // note: does not raise a warning because it is used by // tex_is_known_extension. -LibError tex_codec_for_filename(const OsPath& extension, const TexCodecVTbl** c) +Status tex_codec_for_filename(const OsPath& extension, const TexCodecVTbl** c) { for(*c = codecs; *c; *c = (*c)->next) { @@ -76,7 +76,7 @@ LibError tex_codec_for_filename(const OsPath& extension, const TexCodecVTbl** c) // find codec that recognizes the header's magic field -LibError tex_codec_for_header(const u8* file, size_t file_size, const TexCodecVTbl** c) +Status tex_codec_for_header(const u8* file, size_t file_size, const TexCodecVTbl** c) { // we guarantee at least 4 bytes for is_hdr to look at if(file_size < 4) @@ -104,14 +104,14 @@ const TexCodecVTbl* tex_codec_next(const TexCodecVTbl* prev_codec) } -LibError tex_codec_transform(Tex* t, size_t transforms) +Status tex_codec_transform(Tex* t, size_t transforms) { - LibError ret = INFO::TEX_CODEC_CANNOT_HANDLE; + Status ret = INFO::TEX_CODEC_CANNOT_HANDLE; // find codec that understands the data, and transform for(const TexCodecVTbl* c = codecs; c; c = c->next) { - LibError err = c->transform(t, transforms); + Status err = c->transform(t, transforms); // success if(err == INFO::OK) return INFO::OK; @@ -173,12 +173,12 @@ std::vector tex_codec_alloc_rows(const u8* data, size_t h, size_t pitch, } -LibError tex_codec_write(Tex* t, size_t transforms, const void* hdr, size_t hdr_size, DynArray* da) +Status tex_codec_write(Tex* t, size_t transforms, const void* hdr, size_t hdr_size, DynArray* da) { - RETURN_ERR(tex_transform(t, transforms)); + RETURN_STATUS_IF_ERR(tex_transform(t, transforms)); void* img_data = tex_get_data(t); const size_t img_size = tex_img_size(t); - RETURN_ERR(da_append(da, hdr, hdr_size)); - RETURN_ERR(da_append(da, img_data, img_size)); + RETURN_STATUS_IF_ERR(da_append(da, hdr, hdr_size)); + RETURN_STATUS_IF_ERR(da_append(da, img_data, img_size)); return INFO::OK; } diff --git a/source/lib/tex/tex_codec.h b/source/lib/tex/tex_codec.h index 96c87b0833..80f977e2fc 100644 --- a/source/lib/tex/tex_codec.h +++ b/source/lib/tex/tex_codec.h @@ -47,9 +47,9 @@ struct TexCodecVTbl * (usually enough to compare the header's "magic" field; * anyway, no legitimate file will be smaller) * @param t output texture object - * @return LibError + * @return Status **/ - LibError (*decode)(DynArray* RESTRICT da, Tex * RESTRICT t); + Status (*decode)(DynArray* RESTRICT da, Tex * RESTRICT t); /** @@ -61,9 +61,9 @@ struct TexCodecVTbl * rationale: some codecs cannot calculate the output size beforehand * (e.g. PNG output via libpng), so the output memory cannot be allocated * by the caller. - * @return LibError + * @return Status **/ - LibError (*encode)(Tex* RESTRICT t, DynArray * RESTRICT da); + Status (*encode)(Tex* RESTRICT t, DynArray * RESTRICT da); /** * transform the texture's pixel format. @@ -74,7 +74,7 @@ struct TexCodecVTbl * to its format; generic pixel format transforms are handled by * the caller. **/ - LibError (*transform)(Tex* t, size_t transforms); + Status (*transform)(Tex* t, size_t transforms); /** * indicate if the data appears to be an instance of this codec's header, @@ -166,11 +166,11 @@ extern int tex_codec_register(TexCodecVTbl* c); * * @param extension * @param c (out) vtbl of responsible codec - * @return LibError; ERR::RES_UNKNOWN_FORMAT (without warning, because this is + * @return Status; ERR::RES_UNKNOWN_FORMAT (without warning, because this is * called by tex_is_known_extension) if no codec indicates they can * handle the given extension. **/ -extern LibError tex_codec_for_filename(const OsPath& extension, const TexCodecVTbl** c); +extern Status tex_codec_for_filename(const OsPath& extension, const TexCodecVTbl** c); /** * find codec that recognizes the header's magic field. @@ -179,10 +179,10 @@ extern LibError tex_codec_for_filename(const OsPath& extension, const TexCodecVT * (first 4 bytes of) header. * @param data_size [bytes] * @param c (out) vtbl of responsible codec - * @return LibError; ERR::RES_UNKNOWN_FORMAT if no codec indicates they can + * @return Status; ERR::RES_UNKNOWN_FORMAT if no codec indicates they can * handle the given format (header). **/ -extern LibError tex_codec_for_header(const u8* data, size_t data_size, const TexCodecVTbl** c); +extern Status tex_codec_for_header(const u8* data, size_t data_size, const TexCodecVTbl** c); /** * enumerate all registered codecs. @@ -203,9 +203,9 @@ extern const TexCodecVTbl* tex_codec_next(const TexCodecVTbl* prev_codec); * @param t texture object * @param transforms: OR-ed combination of TEX_* flags that are to * be changed. - * @return LibError + * @return Status **/ -extern LibError tex_codec_transform(Tex* t, size_t transforms); +extern Status tex_codec_transform(Tex* t, size_t transforms); /** * allocate an array of row pointers that point into the given texture data. @@ -237,8 +237,8 @@ extern std::vector tex_codec_alloc_rows(const u8* data, size_t h, size_t * @param hdr header data * @param hdr_size [bytes] * @param da output data array (will be expanded as necessary) - * @return LibError + * @return Status **/ -extern LibError tex_codec_write(Tex* t, size_t transforms, const void* hdr, size_t hdr_size, DynArray* da); +extern Status tex_codec_write(Tex* t, size_t transforms, const void* hdr, size_t hdr_size, DynArray* da); #endif // #ifndef INCLUDED_TEX_CODEC diff --git a/source/lib/tex/tex_dds.cpp b/source/lib/tex/tex_dds.cpp index 1cd9d6e69c..9dfc6fe98b 100644 --- a/source/lib/tex/tex_dds.cpp +++ b/source/lib/tex/tex_dds.cpp @@ -271,7 +271,7 @@ static void s3tc_decompress_level(size_t UNUSED(level), size_t level_w, size_t l // decompress the given image (which is known to be stored as DXTn) // effectively in-place. updates Tex fields. -static LibError s3tc_decompress(Tex* t) +static Status s3tc_decompress(Tex* t) { // alloc new image memory // notes: @@ -387,7 +387,7 @@ static bool is_valid_dxt(size_t dxt) // pf points to the DDS file's header; all fields must be endian-converted // before use. // output parameters invalid on failure. -static LibError decode_pf(const DDS_PIXELFORMAT* pf, size_t& bpp, size_t& flags) +static Status decode_pf(const DDS_PIXELFORMAT* pf, size_t& bpp, size_t& flags) { bpp = 0; flags = 0; @@ -433,7 +433,7 @@ static LibError decode_pf(const DDS_PIXELFORMAT* pf, size_t& bpp, size_t& flags) WARN_RETURN(ERR::TEX_FMT_INVALID); } - RETURN_ERR(tex_validate_plain_format(bpp, (int)flags)); + RETURN_STATUS_IF_ERR(tex_validate_plain_format(bpp, (int)flags)); } // .. compressed else if(pf_flags & DDPF_FOURCC) @@ -476,7 +476,7 @@ static LibError decode_pf(const DDS_PIXELFORMAT* pf, size_t& bpp, size_t& flags) // sd points to the DDS file's header; all fields must be endian-converted // before use. // output parameters invalid on failure. -static LibError decode_sd(const DDS_HEADER* sd, size_t& w, size_t& h, size_t& bpp, size_t& flags) +static Status decode_sd(const DDS_HEADER* sd, size_t& w, size_t& h, size_t& bpp, size_t& flags) { // check header size if(read_le32(&sd->dwSize) != sizeof(*sd)) @@ -495,7 +495,7 @@ static LibError decode_sd(const DDS_HEADER* sd, size_t& w, size_t& h, size_t& bp w = (size_t)read_le32(&sd->dwWidth); // pixel format - RETURN_ERR(decode_pf(&sd->ddpf, bpp, flags)); + RETURN_STATUS_IF_ERR(decode_pf(&sd->ddpf, bpp, flags)); // if the image is not aligned with the S3TC block size, it is stored // with extra pixels on the bottom left to fill up the space, so we need @@ -588,16 +588,16 @@ static size_t dds_hdr_size(const u8* UNUSED(file)) } -static LibError dds_decode(DynArray* RESTRICT da, Tex* RESTRICT t) +static Status dds_decode(DynArray* RESTRICT da, Tex* RESTRICT t) { u8* file = da->base; const DDS_HEADER* sd = (const DDS_HEADER*)(file+4); - RETURN_ERR(decode_sd(sd, t->w, t->h, t->bpp, t->flags)); + RETURN_STATUS_IF_ERR(decode_sd(sd, t->w, t->h, t->bpp, t->flags)); return INFO::OK; } -static LibError dds_encode(Tex* RESTRICT UNUSED(t), DynArray* RESTRICT UNUSED(da)) +static Status dds_encode(Tex* RESTRICT UNUSED(t), DynArray* RESTRICT UNUSED(da)) { // note: do not return ERR::NOT_IMPLEMENTED et al. because that would // break tex_write (which assumes either this, 0 or errors are returned). @@ -607,7 +607,7 @@ static LibError dds_encode(Tex* RESTRICT UNUSED(t), DynArray* RESTRICT UNUSED(da TIMER_ADD_CLIENT(tc_dds_transform); -static LibError dds_transform(Tex* t, size_t transforms) +static Status dds_transform(Tex* t, size_t transforms) { TIMER_ACCRUE(tc_dds_transform); @@ -628,7 +628,7 @@ static LibError dds_transform(Tex* t, size_t transforms) // requesting decompression if(dxt && transform_dxt) { - RETURN_ERR(s3tc_decompress(t)); + RETURN_STATUS_IF_ERR(s3tc_decompress(t)); return INFO::OK; } // both are DXT (unsupported; there are no flags we can change while diff --git a/source/lib/tex/tex_internal.h b/source/lib/tex/tex_internal.h index 641beb4ee5..f063c664fd 100644 --- a/source/lib/tex/tex_internal.h +++ b/source/lib/tex/tex_internal.h @@ -37,9 +37,9 @@ * tex_codec_plain_transform. * @param bpp bits per pixel * @param flags TexFlags - * @return LibError + * @return Status **/ -extern LibError tex_validate_plain_format(size_t bpp, size_t flags); +extern Status tex_validate_plain_format(size_t bpp, size_t flags); /** diff --git a/source/lib/tex/tex_jpg.cpp b/source/lib/tex/tex_jpg.cpp index fc918bb6ec..77541e76eb 100644 --- a/source/lib/tex/tex_jpg.cpp +++ b/source/lib/tex/tex_jpg.cpp @@ -426,7 +426,7 @@ JpgErrorMgr::JpgErrorMgr(jpeg_decompress_struct& cinfo) //----------------------------------------------------------------------------- -static LibError jpg_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) +static Status jpg_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) { return INFO::TEX_CODEC_CANNOT_HANDLE; } @@ -443,7 +443,7 @@ static LibError jpg_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) // due to less copying. -static LibError jpg_decode_impl(DynArray* da, jpeg_decompress_struct* cinfo, Tex* t) +static Status jpg_decode_impl(DynArray* da, jpeg_decompress_struct* cinfo, Tex* t) { src_prepare(cinfo, da); @@ -502,7 +502,7 @@ static LibError jpg_decode_impl(DynArray* da, jpeg_decompress_struct* cinfo, Tex // mem data source. (void)jpeg_finish_decompress(cinfo); - LibError ret = INFO::OK; + Status ret = INFO::OK; if(cinfo->err->num_warnings != 0) ret = WARN::TEX_INVALID_DATA; @@ -519,7 +519,7 @@ static LibError jpg_decode_impl(DynArray* da, jpeg_decompress_struct* cinfo, Tex } -static LibError jpg_encode_impl(Tex* t, jpeg_compress_struct* cinfo, DynArray* da) +static Status jpg_encode_impl(Tex* t, jpeg_compress_struct* cinfo, DynArray* da) { dst_prepare(cinfo, da); @@ -538,7 +538,7 @@ static LibError jpg_encode_impl(Tex* t, jpeg_compress_struct* cinfo, DynArray* d jpeg_start_compress(cinfo, TRUE); // if BGR, convert to RGB. - WARN_ERR(tex_transform_to(t, t->flags & ~TEX_BGR)); + WARN_IF_ERR(tex_transform_to(t, t->flags & ~TEX_BGR)); const size_t pitch = t->w * t->bpp / 8; u8* data = tex_get_data(t); @@ -559,7 +559,7 @@ static LibError jpg_encode_impl(Tex* t, jpeg_compress_struct* cinfo, DynArray* d jpeg_finish_compress(cinfo); - LibError ret = INFO::OK; + Status ret = INFO::OK; if(cinfo->err->num_warnings != 0) ret = WARN::TEX_INVALID_DATA; @@ -588,7 +588,7 @@ static size_t jpg_hdr_size(const u8* UNUSED(file)) } -static LibError jpg_decode(DynArray* RESTRICT da, Tex* RESTRICT t) +static Status jpg_decode(DynArray* RESTRICT da, Tex* RESTRICT t) { // contains the JPEG decompression parameters and pointers to // working space (allocated as needed by the JPEG library). @@ -600,7 +600,7 @@ static LibError jpg_decode(DynArray* RESTRICT da, Tex* RESTRICT t) jpeg_create_decompress(&cinfo); - LibError ret = jpg_decode_impl(da, &cinfo, t); + Status ret = jpg_decode_impl(da, &cinfo, t); jpeg_destroy_decompress(&cinfo); // releases a "good deal" of memory @@ -609,7 +609,7 @@ static LibError jpg_decode(DynArray* RESTRICT da, Tex* RESTRICT t) // limitation: palette images aren't supported -static LibError jpg_encode(Tex* RESTRICT t, DynArray* RESTRICT da) +static Status jpg_encode(Tex* RESTRICT t, DynArray* RESTRICT da) { // contains the JPEG compression parameters and pointers to // working space (allocated as needed by the JPEG library). @@ -621,7 +621,7 @@ static LibError jpg_encode(Tex* RESTRICT t, DynArray* RESTRICT da) jpeg_create_compress(&cinfo); - LibError ret = jpg_encode_impl(t, &cinfo, da); + Status ret = jpg_encode_impl(t, &cinfo, da); jpeg_destroy_compress(&cinfo); // releases a "good deal" of memory diff --git a/source/lib/tex/tex_png.cpp b/source/lib/tex/tex_png.cpp index fbe0001ed2..450ac2b0a5 100644 --- a/source/lib/tex/tex_png.cpp +++ b/source/lib/tex/tex_png.cpp @@ -76,7 +76,7 @@ static void io_flush(png_structp UNUSED(png_ptr)) //----------------------------------------------------------------------------- -static LibError png_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) +static Status png_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) { return INFO::TEX_CODEC_CANNOT_HANDLE; } @@ -87,7 +87,7 @@ static LibError png_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) // split out of png_decode to simplify resource cleanup and avoid // "dtor / setjmp interaction" warning. -static LibError png_decode_impl(DynArray* da, png_structp png_ptr, png_infop info_ptr, Tex* t) +static Status png_decode_impl(DynArray* da, png_structp png_ptr, png_infop info_ptr, Tex* t) { png_set_read_fn(png_ptr, da, io_read); @@ -137,7 +137,7 @@ static LibError png_decode_impl(DynArray* da, png_structp png_ptr, png_infop inf // split out of png_encode to simplify resource cleanup and avoid // "dtor / setjmp interaction" warning. -static LibError png_encode_impl(Tex* t, png_structp png_ptr, png_infop info_ptr, DynArray* da) +static Status png_encode_impl(Tex* t, png_structp png_ptr, png_infop info_ptr, DynArray* da) { const png_uint_32 w = (png_uint_32)t->w, h = (png_uint_32)t->h; const size_t pitch = w * t->bpp / 8; @@ -200,11 +200,11 @@ static size_t png_hdr_size(const u8* UNUSED(file)) TIMER_ADD_CLIENT(tc_png_decode); // limitation: palette images aren't supported -static LibError png_decode(DynArray* RESTRICT da, Tex* RESTRICT t) +static Status png_decode(DynArray* RESTRICT da, Tex* RESTRICT t) { TIMER_ACCRUE(tc_png_decode); - LibError ret = ERR::FAIL; + Status ret = ERR::FAIL; png_infop info_ptr = 0; // allocate PNG structures; use default stderr and longjmp error handlers @@ -231,9 +231,9 @@ fail: // limitation: palette images aren't supported -static LibError png_encode(Tex* RESTRICT t, DynArray* RESTRICT da) +static Status png_encode(Tex* RESTRICT t, DynArray* RESTRICT da) { - LibError ret = ERR::FAIL; + Status ret = ERR::FAIL; png_infop info_ptr = 0; // allocate PNG structures; use default stderr and longjmp error handlers diff --git a/source/lib/tex/tex_tga.cpp b/source/lib/tex/tex_tga.cpp index f179736d12..0309b1bbd3 100644 --- a/source/lib/tex/tex_tga.cpp +++ b/source/lib/tex/tex_tga.cpp @@ -67,7 +67,7 @@ TgaHeader; #pragma pack(pop) -static LibError tga_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) +static Status tga_transform(Tex* UNUSED(t), size_t UNUSED(transforms)) { return INFO::TEX_CODEC_CANNOT_HANDLE; } @@ -112,7 +112,7 @@ static size_t tga_hdr_size(const u8* file) // requirements: uncompressed, direct colour, bottom up -static LibError tga_decode(DynArray* RESTRICT da, Tex* RESTRICT t) +static Status tga_decode(DynArray* RESTRICT da, Tex* RESTRICT t) { u8* file = da->base; @@ -146,7 +146,7 @@ static LibError tga_decode(DynArray* RESTRICT da, Tex* RESTRICT t) } -static LibError tga_encode(Tex* RESTRICT t, DynArray* RESTRICT da) +static Status tga_encode(Tex* RESTRICT t, DynArray* RESTRICT da) { u8 img_desc = 0; if(t->flags & TEX_TOP_DOWN) diff --git a/source/lib/timer.cpp b/source/lib/timer.cpp index 83bd063ce9..227d67fdab 100644 --- a/source/lib/timer.cpp +++ b/source/lib/timer.cpp @@ -139,7 +139,7 @@ double timer_Time() // cached because the default implementation may take several milliseconds static double resolution; -static LibError InitResolution() +static Status InitResolution() { #if OS_WIN resolution = whrt_Resolution(); diff --git a/source/lib/utf8.cpp b/source/lib/utf8.cpp index 6d2d49225a..e9d14827f8 100644 --- a/source/lib/utf8.cpp +++ b/source/lib/utf8.cpp @@ -23,10 +23,10 @@ #include "precompiled.h" #include "lib/utf8.h" -ERROR_ASSOCIATE(ERR::UTF8_SURROGATE, L"UTF-16 surrogate pairs aren't supported", -1); -ERROR_ASSOCIATE(ERR::UTF8_OUTSIDE_BMP, L"Code point outside BMP (> 0x10000)", -1); -ERROR_ASSOCIATE(ERR::UTF8_NONCHARACTER, L"Noncharacter (e.g. WEOF)", -1); -ERROR_ASSOCIATE(ERR::UTF8_INVALID_UTF8, L"Invalid UTF-8 sequence", -1); +STATUS_DEFINE(ERR, UTF8_SURROGATE, L"UTF-16 surrogate pairs aren't supported", -1); +STATUS_DEFINE(ERR, UTF8_OUTSIDE_BMP, L"Code point outside BMP (> 0x10000)", -1); +STATUS_DEFINE(ERR, UTF8_NONCHARACTER, L"Noncharacter (e.g. WEOF)", -1); +STATUS_DEFINE(ERR, UTF8_INVALID_UTF8, L"Invalid UTF-8 sequence", -1); // adapted from http://unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c @@ -70,7 +70,7 @@ typedef u32 UTF32; // called from ReplaceIfInvalid and UTF8Codec::Decode -static UTF32 RaiseError(LibError err, LibError* perr) +static UTF32 RaiseError(Status err, Status* perr) { if(perr) // caller wants return code, not warning dialog { @@ -84,7 +84,7 @@ static UTF32 RaiseError(LibError err, LibError* perr) } -static UTF32 ReplaceIfInvalid(UTF32 u, LibError* err) +static UTF32 ReplaceIfInvalid(UTF32 u, Status* err) { // disallow surrogates if(0xD800ul <= u && u <= 0xDFFFul) @@ -122,7 +122,7 @@ public: } // @return decoded scalar, or replacementCharacter on error - static UTF32 Decode(const UTF8*& srcPos, const UTF8* const srcEnd, LibError* err) + static UTF32 Decode(const UTF8*& srcPos, const UTF8* const srcEnd, Status* err) { const size_t size = SizeFromFirstByte(*srcPos); if(!IsValid(srcPos, size, srcEnd)) @@ -202,7 +202,7 @@ private: //----------------------------------------------------------------------------- -std::string utf8_from_wstring(const std::wstring& src, LibError* err) +std::string utf8_from_wstring(const std::wstring& src, Status* err) { if(err) *err = INFO::OK; @@ -219,7 +219,7 @@ std::string utf8_from_wstring(const std::wstring& src, LibError* err) } -std::wstring wstring_from_utf8(const std::string& src, LibError* err) +std::wstring wstring_from_utf8(const std::string& src, Status* err) { if(err) *err = INFO::OK; diff --git a/source/lib/utf8.h b/source/lib/utf8.h index c47f9b2496..7cad322a09 100644 --- a/source/lib/utf8.h +++ b/source/lib/utf8.h @@ -26,10 +26,10 @@ // note: error codes are returned via optional output parameter. namespace ERR { - const LibError UTF8_SURROGATE = -100700; - const LibError UTF8_OUTSIDE_BMP = -100701; - const LibError UTF8_NONCHARACTER = -100702; - const LibError UTF8_INVALID_UTF8 = -100703; + const Status UTF8_SURROGATE = -100700; + const Status UTF8_OUTSIDE_BMP = -100701; + const Status UTF8_NONCHARACTER = -100702; + const Status UTF8_INVALID_UTF8 = -100703; } /** @@ -42,11 +42,11 @@ namespace ERR * otherwise, the function raises a warning dialog for every * error/warning. **/ -LIB_API std::wstring wstring_from_utf8(const std::string& s, LibError* err = 0); +LIB_API std::wstring wstring_from_utf8(const std::string& s, Status* err = 0); /** * opposite of wstring_from_utf8 **/ -LIB_API std::string utf8_from_wstring(const std::wstring& s, LibError* err = 0); +LIB_API std::string utf8_from_wstring(const std::wstring& s, Status* err = 0); #endif // #ifndef INCLUDED_UTF8 diff --git a/source/main.cpp b/source/main.cpp index 4c27224e74..c252baa88e 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -32,7 +32,7 @@ that of Atlas depending on commandline parameters. #include "lib/precompiled.h" #include "lib/debug.h" -#include "lib/lib_errors.h" +#include "lib/status.h" #include "lib/secure_crt.h" #include "lib/frequency_filter.h" #include "lib/input.h" @@ -186,7 +186,7 @@ static int ProgressiveLoad() int progress_percent; try { - LibError ret = LDR_ProgressiveLoad(10e-3, description, ARRAY_SIZE(description), &progress_percent); + Status ret = LDR_ProgressiveLoad(10e-3, description, ARRAY_SIZE(description), &progress_percent); switch(ret) { // no load active => no-op (skip code below) @@ -205,7 +205,7 @@ static int ProgressiveLoad() break; // error! default: - CHECK_ERR(ret); + WARN_RETURN_STATUS_IF_ERR(ret); // can't do this above due to legit ERR::TIMED_OUT break; } diff --git a/source/ps/ArchiveBuilder.cpp b/source/ps/ArchiveBuilder.cpp index 21afecb32d..9c6aaee01a 100644 --- a/source/ps/ArchiveBuilder.cpp +++ b/source/ps/ArchiveBuilder.cpp @@ -81,7 +81,7 @@ void CArchiveBuilder::Build(const OsPath& archive) for (size_t i = 0; i < m_Files.size(); ++i) { - LibError ret; + Status ret; const VfsPath path = m_Files[i]; OsPath realPath; @@ -134,7 +134,7 @@ void CArchiveBuilder::Build(const OsPath& archive) } } -LibError CArchiveBuilder::CollectFileCB(const VfsPath& pathname, const FileInfo& UNUSED(fileInfo), const uintptr_t cbData) +Status CArchiveBuilder::CollectFileCB(const VfsPath& pathname, const FileInfo& UNUSED(fileInfo), const uintptr_t cbData) { CArchiveBuilder* self = static_cast((void*)cbData); self->m_Files.push_back(pathname); diff --git a/source/ps/ArchiveBuilder.h b/source/ps/ArchiveBuilder.h index b4671ce39a..4bef4ff333 100644 --- a/source/ps/ArchiveBuilder.h +++ b/source/ps/ArchiveBuilder.h @@ -56,7 +56,7 @@ public: void Build(const OsPath& archive); private: - static LibError CollectFileCB(const VfsPath& pathname, const FileInfo& fileInfo, const uintptr_t cbData); + static Status CollectFileCB(const VfsPath& pathname, const FileInfo& fileInfo, const uintptr_t cbData); PIVFS m_VFS; std::vector m_Files; diff --git a/source/ps/CLogger.cpp b/source/ps/CLogger.cpp index 445d5f8c37..b5ed7ee917 100644 --- a/source/ps/CLogger.cpp +++ b/source/ps/CLogger.cpp @@ -142,7 +142,7 @@ CLogger::~CLogger() static std::string ToHTML(const wchar_t* message) { - LibError err; + Status err; std::string cmessage = utf8_from_wstring(message, &err); boost::algorithm::replace_all(cmessage, "&", "&"); boost::algorithm::replace_all(cmessage, "<", "<"); @@ -394,7 +394,7 @@ TestLogger::~TestLogger() std::wstring TestLogger::GetOutput() { - LibError err; + Status err; return wstring_from_utf8(m_Stream.str(), &err); } diff --git a/source/ps/CStr.cpp b/source/ps/CStr.cpp index 2797d3895d..b018d5ce25 100644 --- a/source/ps/CStr.cpp +++ b/source/ps/CStr.cpp @@ -47,7 +47,7 @@ **/ CStr8 CStrW::ToUTF8() const { - LibError err; + Status err; return utf8_from_wstring(*this, &err); } @@ -58,7 +58,7 @@ CStr8 CStrW::ToUTF8() const **/ CStrW CStr8::FromUTF8() const { - LibError err; + Status err; return wstring_from_utf8(*this, &err); } diff --git a/source/ps/CacheLoader.cpp b/source/ps/CacheLoader.cpp index 681ee121fe..0a28aed99f 100644 --- a/source/ps/CacheLoader.cpp +++ b/source/ps/CacheLoader.cpp @@ -29,7 +29,7 @@ CCacheLoader::CCacheLoader(PIVFS vfs, const std::wstring& fileExtension) : { } -LibError CCacheLoader::TryLoadingCached(const VfsPath& sourcePath, const MD5& initialHash, u32 version, VfsPath& loadPath) +Status CCacheLoader::TryLoadingCached(const VfsPath& sourcePath, const MD5& initialHash, u32 version, VfsPath& loadPath) { VfsPath archiveCachePath = ArchiveCachePath(sourcePath); @@ -41,7 +41,7 @@ LibError CCacheLoader::TryLoadingCached(const VfsPath& sourcePath, const MD5& in } // Fail if no source or archive cache - LibError err = m_VFS->GetFileInfo(sourcePath, NULL); + Status err = m_VFS->GetFileInfo(sourcePath, NULL); if (err < 0) { LOGERROR(L"Failed to find file: \"%ls\"", sourcePath.string().c_str()); diff --git a/source/ps/CacheLoader.h b/source/ps/CacheLoader.h index 8219cf0b11..1495e792ca 100644 --- a/source/ps/CacheLoader.h +++ b/source/ps/CacheLoader.h @@ -48,7 +48,7 @@ public: * Returns INFO::SKIPPED and sets loadPath to the desire loose cache name if there isn't one. * Returns a value < 0 on error (e.g. the source file doesn't exist). */ - LibError TryLoadingCached(const VfsPath& sourcePath, const MD5& initialHash, u32 version, VfsPath& loadPath); + Status TryLoadingCached(const VfsPath& sourcePath, const MD5& initialHash, u32 version, VfsPath& loadPath); /** * Determines whether we can safely use the archived cache file, or need to diff --git a/source/ps/ConfigDB.cpp b/source/ps/ConfigDB.cpp index 2c917c6b11..c268f804de 100644 --- a/source/ps/ConfigDB.cpp +++ b/source/ps/ConfigDB.cpp @@ -348,10 +348,10 @@ bool CConfigDB::Reload(EConfigNamespace ns) else { LOGMESSAGE(L"Loading config file \"%ls\"", m_ConfigFile[ns].string().c_str()); - LibError ret = g_VFS->LoadFile(m_ConfigFile[ns], buffer, buflen); + Status ret = g_VFS->LoadFile(m_ConfigFile[ns], buffer, buflen); if (ret != INFO::OK) { - LOGERROR(L"CConfigDB::Reload(): vfs_load for \"%ls\" failed: return was %ld", m_ConfigFile[ns].string().c_str(), ret); + LOGERROR(L"CConfigDB::Reload(): vfs_load for \"%ls\" failed: return was %lld", m_ConfigFile[ns].string().c_str(), ret); return false; } } @@ -436,7 +436,7 @@ bool CConfigDB::WriteFile(EConfigNamespace ns, const VfsPath& path) } const size_t len = pos - (char*)buf.get(); - LibError ret = g_VFS->CreateFile(path, buf, len); + Status ret = g_VFS->CreateFile(path, buf, len); if(ret < 0) { LOGERROR(L"CConfigDB::WriteFile(): CreateFile \"%ls\" failed (error: %d)", path.string().c_str(), (int)ret); diff --git a/source/ps/Filesystem.cpp b/source/ps/Filesystem.cpp index 379b2e9445..197b7fa462 100644 --- a/source/ps/Filesystem.cpp +++ b/source/ps/Filesystem.cpp @@ -70,26 +70,26 @@ static bool CanIgnore(const DirWatchNotification& notification) return false; } -LibError ReloadChangedFiles() +Status ReloadChangedFiles() { std::vector notifications; - RETURN_ERR(dir_watch_Poll(notifications)); + RETURN_STATUS_IF_ERR(dir_watch_Poll(notifications)); for(size_t i = 0; i < notifications.size(); i++) { if(!CanIgnore(notifications[i])) { VfsPath pathname; - RETURN_ERR(g_VFS->GetVirtualPath(notifications[i].Pathname(), pathname)); - RETURN_ERR(g_VFS->Invalidate(pathname)); + RETURN_STATUS_IF_ERR(g_VFS->GetVirtualPath(notifications[i].Pathname(), pathname)); + RETURN_STATUS_IF_ERR(g_VFS->Invalidate(pathname)); // Tell each hotloadable system about this file change: - RETURN_ERR(g_GUI->ReloadChangedFiles(pathname)); + RETURN_STATUS_IF_ERR(g_GUI->ReloadChangedFiles(pathname)); for (size_t j = 0; j < g_ReloadFuncs.size(); ++j) g_ReloadFuncs[j].first(g_ReloadFuncs[j].second, pathname); - RETURN_ERR(h_reload(g_VFS, pathname)); + RETURN_STATUS_IF_ERR(h_reload(g_VFS, pathname)); } } return INFO::OK; @@ -113,10 +113,10 @@ PSRETURN CVFSFile::Load(const PIVFS& vfs, const VfsPath& filename) return PSRETURN_CVFSFile_AlreadyLoaded; } - LibError ret = vfs->LoadFile(filename, m_Buffer, m_BufferSize); + Status ret = vfs->LoadFile(filename, m_Buffer, m_BufferSize); if (ret != INFO::OK) { - LOGERROR(L"CVFSFile: file %ls couldn't be opened (vfs_load: %ld)", filename.string().c_str(), ret); + LOGERROR(L"CVFSFile: file %ls couldn't be opened (vfs_load: %lld)", filename.string().c_str(), ret); return PSRETURN_CVFSFile_LoadFailed; } diff --git a/source/ps/Filesystem.h b/source/ps/Filesystem.h index afe3864ff5..39fc218326 100644 --- a/source/ps/Filesystem.h +++ b/source/ps/Filesystem.h @@ -36,7 +36,7 @@ extern bool VfsFileExists(const VfsPath& pathname); /** * callback function type for file change notifications */ -typedef LibError (*FileReloadFunc)(void* param, const VfsPath& path); +typedef Status (*FileReloadFunc)(void* param, const VfsPath& path); /** * register a callback function to be called by ReloadChangedFiles @@ -55,7 +55,7 @@ void UnregisterFileReloadFunc(FileReloadFunc func, void* obj); * may be lost. * note: polling is much simpler than asynchronous notifications. **/ -extern LibError ReloadChangedFiles(); +extern Status ReloadChangedFiles(); ERROR_GROUP(CVFSFile); ERROR_TYPE(CVFSFile, LoadFailed); diff --git a/source/ps/GameSetup/Config.cpp b/source/ps/GameSetup/Config.cpp index 36c04cae47..3500409624 100644 --- a/source/ps/GameSetup/Config.cpp +++ b/source/ps/GameSetup/Config.cpp @@ -80,7 +80,7 @@ static void LoadGlobals() float gain = -1.0f; CFG_GET_USER_VAL("sound.mastergain", Float, gain); if(gain >= 0.0f) - WARN_ERR(snd_set_master_gain(gain)); + WARN_IF_ERR(snd_set_master_gain(gain)); } diff --git a/source/ps/GameSetup/HWDetect.cpp b/source/ps/GameSetup/HWDetect.cpp index 9af1555e61..002191243a 100644 --- a/source/ps/GameSetup/HWDetect.cpp +++ b/source/ps/GameSetup/HWDetect.cpp @@ -149,7 +149,7 @@ void RunHardwareDetection() return; } - LibError err; // ignore encoding errors + Status err; // ignore encoding errors std::wstring code = wstring_from_utf8(file.GetAsString(), &err); scriptInterface.LoadScript(scriptName, code); diff --git a/source/ps/GameSetup/Paths.cpp b/source/ps/GameSetup/Paths.cpp index d75509b32c..18b009df1c 100644 --- a/source/ps/GameSetup/Paths.cpp +++ b/source/ps/GameSetup/Paths.cpp @@ -79,12 +79,12 @@ Paths::Paths(const CmdLineArgs& args) errno = 0; pathname = wrealpath(argv0); if(pathname.empty()) - WARN_ERR(LibError_from_errno(false)); + WARN_IF_ERR(StatusFromErrno()); } // make sure it's valid if(!fs_util::FileExists(pathname)) - WARN_ERR(LibError_from_errno(false)); + WARN_IF_ERR(StatusFromErrno()); fs::wpath components = pathname.string(); for(size_t i = 0; i < 3; i++) // remove "system/name.exe" diff --git a/source/ps/Loader.cpp b/source/ps/Loader.cpp index 49b45b6c16..06c239011f 100644 --- a/source/ps/Loader.cpp +++ b/source/ps/Loader.cpp @@ -190,9 +190,9 @@ static bool HaveTimeForNextTask(double time_left, double time_budget, int estima // persistent, we can't just store a pointer. returning a pointer to // our copy of the description doesn't work either, since it's freed when // the request is de-queued. that leaves writing into caller's buffer. -LibError LDR_ProgressiveLoad(double time_budget, wchar_t* description, size_t max_chars, int* progress_percent) +Status LDR_ProgressiveLoad(double time_budget, wchar_t* description, size_t max_chars, int* progress_percent) { - LibError ret; // single exit; this is returned + Status ret; // single exit; this is returned double progress = 0.0; // used to set progress_percent double time_left = time_budget; @@ -267,7 +267,7 @@ LibError LDR_ProgressiveLoad(double time_budget, wchar_t* description, size_t ma // error that came up so we can report all errors that happen. else if(status < 0) { - ret = (LibError)status; + ret = (Status)status; goto done; } // .. succeeded; continue and process next queued task. @@ -298,7 +298,7 @@ done: // immediately process all queued load requests. // returns 0 on success or a negative error code. -LibError LDR_NonprogressiveLoad() +Status LDR_NonprogressiveLoad() { const double time_budget = 100.0; // large enough so that individual functions won't time out @@ -308,7 +308,7 @@ LibError LDR_NonprogressiveLoad() for(;;) { - LibError ret = LDR_ProgressiveLoad(time_budget, description, ARRAY_SIZE(description), &progress_percent); + Status ret = LDR_ProgressiveLoad(time_budget, description, ARRAY_SIZE(description), &progress_percent); switch(ret) { case INFO::OK: @@ -319,7 +319,7 @@ LibError LDR_NonprogressiveLoad() case ERR::TIMED_OUT: break; // continue loading default: - CHECK_ERR(ret); // failed; complain + WARN_RETURN_STATUS_IF_ERR(ret); // failed; complain } } } diff --git a/source/ps/Loader.h b/source/ps/Loader.h index 18a733cb62..be00999ddf 100644 --- a/source/ps/Loader.h +++ b/source/ps/Loader.h @@ -158,11 +158,11 @@ extern void LDR_Cancel(); // persistent, we can't just store a pointer. returning a pointer to // our copy of the description doesn't work either, since it's freed when // the request is de-queued. that leaves writing into caller's buffer. -extern LibError LDR_ProgressiveLoad(double time_budget, wchar_t* next_description, size_t max_chars, int* progress_percent); +extern Status LDR_ProgressiveLoad(double time_budget, wchar_t* next_description, size_t max_chars, int* progress_percent); // immediately process all queued load requests. // returns 0 on success or a negative error code. -extern LibError LDR_NonprogressiveLoad(); +extern Status LDR_NonprogressiveLoad(); // boilerplate check-if-timed-out and return-progress-percent code. diff --git a/source/ps/Preprocessor.cpp b/source/ps/Preprocessor.cpp index 38e83ec924..6d1e91395c 100644 --- a/source/ps/Preprocessor.cpp +++ b/source/ps/Preprocessor.cpp @@ -151,7 +151,7 @@ bool CPreprocessor::Token::GetValue (long &oValue) const void CPreprocessor::Token::SetValue (long iValue) { char tmp [21]; - int len = snprintf (tmp, sizeof (tmp), "%ld", iValue); + int len = snprintf (tmp, sizeof (tmp), "%lld", iValue); Length = 0; Append (tmp, len); Type = TK_NUMBER; diff --git a/source/ps/Util.cpp b/source/ps/Util.cpp index 080e352849..13edd21fb2 100644 --- a/source/ps/Util.cpp +++ b/source/ps/Util.cpp @@ -180,7 +180,7 @@ no_ip: static const wchar_t* HardcodedErrorString(int err) { static wchar_t description[200]; - error_description_r((LibError)err, description, ARRAY_SIZE(description)); + StatusDescription((Status)err, description, ARRAY_SIZE(description)); return description; } @@ -198,20 +198,20 @@ const wchar_t* ErrorString(int err) // write the specified texture to disk. // note: cannot be made const because the image may have to be // transformed to write it out in the format determined by 's extension. -LibError tex_write(Tex* t, const VfsPath& filename) +Status tex_write(Tex* t, const VfsPath& filename) { DynArray da; - RETURN_ERR(tex_encode(t, filename.Extension(), &da)); + RETURN_STATUS_IF_ERR(tex_encode(t, filename.Extension(), &da)); // write to disk - LibError ret = INFO::OK; + Status ret = INFO::OK; { shared_ptr file = DummySharedPtr(da.base); const ssize_t bytes_written = g_VFS->CreateFile(filename, file, da.pos); if(bytes_written > 0) ENSURE(bytes_written == (ssize_t)da.pos); else - ret = (LibError)bytes_written; + ret = (Status)bytes_written; } (void)da_free(&da); @@ -309,7 +309,10 @@ void WriteBigScreenshot(const VfsPath& extension, int tiles) const size_t hdr_size = tex_hdr_size(filename); void* tile_data = malloc(tile_size); if(!tile_data) - WARN_ERR_RETURN(ERR::NO_MEM); + { + WARN_IF_ERR(ERR::NO_MEM); + return; + } shared_ptr img_buf; AllocateAligned(img_buf, hdr_size+img_size, maxSectorSize); diff --git a/source/ps/Util.h b/source/ps/Util.h index 73b20d078b..b187dd26a1 100644 --- a/source/ps/Util.h +++ b/source/ps/Util.h @@ -29,6 +29,6 @@ extern const wchar_t* ErrorString(int err); extern void WriteScreenshot(const VfsPath& extension); extern void WriteBigScreenshot(const VfsPath& extension, int tiles); -extern LibError tex_write(Tex* t, const VfsPath& filename); +extern Status tex_write(Tex* t, const VfsPath& filename); #endif // PS_UTIL_H diff --git a/source/ps/XML/XMLWriter.cpp b/source/ps/XML/XMLWriter.cpp index ba460e7696..efe9aaee54 100644 --- a/source/ps/XML/XMLWriter.cpp +++ b/source/ps/XML/XMLWriter.cpp @@ -99,10 +99,10 @@ bool XMLWriter_File::StoreVFS(const PIVFS& vfs, const VfsPath& pathname) shared_ptr data; AllocateAligned(data, size, maxSectorSize); memcpy(data.get(), m_Data.data(), size); - LibError ret = vfs->CreateFile(pathname, data, size); + Status ret = vfs->CreateFile(pathname, data, size); if (ret < 0) { - LOGERROR(L"Error saving XML data through VFS: %ld", ret); + LOGERROR(L"Error saving XML data through VFS: %lld", ret); return false; } return true; diff --git a/source/ps/XML/Xeromyces.cpp b/source/ps/XML/Xeromyces.cpp index 286b35b847..d39e92dbb9 100644 --- a/source/ps/XML/Xeromyces.cpp +++ b/source/ps/XML/Xeromyces.cpp @@ -82,7 +82,7 @@ PSRETURN CXeromyces::Load(const PIVFS& vfs, const VfsPath& filename) PrepareCacheKey(hash, version); VfsPath xmbPath; - LibError ret = cacheLoader.TryLoadingCached(filename, MD5(), version, xmbPath); + Status ret = cacheLoader.TryLoadingCached(filename, MD5(), version, xmbPath); if (ret == INFO::OK) { diff --git a/source/ps/scripting/JSInterface_VFS.cpp b/source/ps/scripting/JSInterface_VFS.cpp index 76d649b105..f7a22306dc 100644 --- a/source/ps/scripting/JSInterface_VFS.cpp +++ b/source/ps/scripting/JSInterface_VFS.cpp @@ -65,7 +65,7 @@ struct BuildDirEntListState }; // called for each matching directory entry; add its full pathname to array. -static LibError BuildDirEntListCB(const VfsPath& pathname, const FileInfo& UNUSED(fileINfo), uintptr_t cbData) +static Status BuildDirEntListCB(const VfsPath& pathname, const FileInfo& UNUSED(fileINfo), uintptr_t cbData) { BuildDirEntListState* s = (BuildDirEntListState*)cbData; @@ -140,7 +140,7 @@ JSBool JSI_VFS::GetFileMTime(JSContext* cx, uintN argc, jsval* vp) return JS_FALSE; FileInfo fileInfo; - LibError err = g_VFS->GetFileInfo(filename, &fileInfo); + Status err = g_VFS->GetFileInfo(filename, &fileInfo); JS_CHECK_FILE_ERR(err); JS_SET_RVAL(cx, vp, ToJSVal((double)fileInfo.MTime())); @@ -161,7 +161,7 @@ JSBool JSI_VFS::GetFileSize(JSContext* cx, uintN argc, jsval* vp) return JS_FALSE; FileInfo fileInfo; - LibError err = g_VFS->GetFileInfo(filename, &fileInfo); + Status err = g_VFS->GetFileInfo(filename, &fileInfo); JS_CHECK_FILE_ERR(err); JS_SET_RVAL(cx, vp, ToJSVal( (unsigned)fileInfo.Size() )); @@ -183,7 +183,7 @@ JSBool JSI_VFS::ReadFile(JSContext* cx, uintN argc, jsval* vp) shared_ptr buf; size_t size; - LibError err = g_VFS->LoadFile(filename, buf, size); + Status err = g_VFS->LoadFile(filename, buf, size); JS_CHECK_FILE_ERR( err ); CStr contents((const char*)buf.get(), size); @@ -215,7 +215,7 @@ JSBool JSI_VFS::ReadFileLines(JSContext* cx, uintN argc, jsval* vp) shared_ptr buf; size_t size; - LibError err = g_VFS->LoadFile(filename, buf, size); + Status err = g_VFS->LoadFile(filename, buf, size); JS_CHECK_FILE_ERR( err ); CStr contents((const char*)buf.get(), size); diff --git a/source/renderer/Renderer.cpp b/source/renderer/Renderer.cpp index c315351309..ec0b7acbe1 100644 --- a/source/renderer/Renderer.cpp +++ b/source/renderer/Renderer.cpp @@ -1744,7 +1744,7 @@ int CRenderer::LoadAlphaMaps() // note: these individual textures can be discarded afterwards; // we cache the composite. textures[i] = ogl_tex_load(g_VFS, path / fnames[i]); - RETURN_ERR(textures[i]); + RETURN_STATUS_IF_ERR(textures[i]); // get its size and make sure they are all equal. // (the packing algo assumes this) @@ -1835,7 +1835,7 @@ void CRenderer::UnloadAlphaMaps() -LibError CRenderer::ReloadChangedFileCB(void* param, const VfsPath& path) +Status CRenderer::ReloadChangedFileCB(void* param, const VfsPath& path) { CRenderer* renderer = static_cast(param); diff --git a/source/renderer/Renderer.h b/source/renderer/Renderer.h index 57a79c9e61..b953a5fc90 100644 --- a/source/renderer/Renderer.h +++ b/source/renderer/Renderer.h @@ -357,7 +357,7 @@ protected: void ReloadShaders(); // hotloading - static LibError ReloadChangedFileCB(void* param, const VfsPath& path); + static Status ReloadChangedFileCB(void* param, const VfsPath& path); // RENDERER DATA: /// Private data that is not needed by inline functions diff --git a/source/scriptinterface/ScriptInterface.cpp b/source/scriptinterface/ScriptInterface.cpp index 7f95e14123..24c20bc115 100644 --- a/source/scriptinterface/ScriptInterface.cpp +++ b/source/scriptinterface/ScriptInterface.cpp @@ -926,7 +926,7 @@ struct Stringifier utf16string str(buf, buf+len); std::wstring strw(str.begin(), str.end()); - LibError err; // ignore Unicode errors + Status err; // ignore Unicode errors static_cast(data)->stream << utf8_from_wstring(strw, &err); return JS_TRUE; } diff --git a/source/simulation2/Simulation2.cpp b/source/simulation2/Simulation2.cpp index 707ff72d4f..11fc6ba5f3 100644 --- a/source/simulation2/Simulation2.cpp +++ b/source/simulation2/Simulation2.cpp @@ -111,9 +111,9 @@ public: } bool LoadScripts(const VfsPath& path); - LibError ReloadChangedFile(const VfsPath& path); + Status ReloadChangedFile(const VfsPath& path); - static LibError ReloadChangedFileCB(void* param, const VfsPath& path) + static Status ReloadChangedFileCB(void* param, const VfsPath& path) { return static_cast(param)->ReloadChangedFile(path); } @@ -157,7 +157,7 @@ bool CSimulation2Impl::LoadScripts(const VfsPath& path) return ok; } -LibError CSimulation2Impl::ReloadChangedFile(const VfsPath& path) +Status CSimulation2Impl::ReloadChangedFile(const VfsPath& path) { const VfsPath& filename = path; @@ -482,7 +482,7 @@ int CSimulation2::ProgressiveLoad() return m->ProgressiveLoad(); } -LibError CSimulation2::ReloadChangedFile(const VfsPath& path) +Status CSimulation2::ReloadChangedFile(const VfsPath& path) { return m->ReloadChangedFile(path); } @@ -526,7 +526,7 @@ std::vector CSimulation2::GetRMSData() std::vector data; // Find all ../maps/random/*.json - LibError ret = fs_util::GetPathnames(g_VFS, path, L"*.json", pathnames); + Status ret = fs_util::GetPathnames(g_VFS, path, L"*.json", pathnames); if (ret == INFO::OK) { for (VfsPaths::iterator it = pathnames.begin(); it != pathnames.end(); ++it) @@ -548,7 +548,7 @@ std::vector CSimulation2::GetRMSData() { // Some error reading directory wchar_t error[200]; - LOGERROR(L"Error reading directory '%ls': %hs", path.string().c_str(), error_description_r(ret, error, ARRAY_SIZE(error))); + LOGERROR(L"Error reading directory '%ls': %hs", path.string().c_str(), StatusDescription(ret, error, ARRAY_SIZE(error))); } return data; @@ -562,7 +562,7 @@ std::vector CSimulation2::GetCivData() std::vector data; // Load all JSON files in civs directory - LibError ret = fs_util::GetPathnames(g_VFS, path, L"*.json", pathnames); + Status ret = fs_util::GetPathnames(g_VFS, path, L"*.json", pathnames); if (ret == INFO::OK) { for (VfsPaths::iterator it = pathnames.begin(); it != pathnames.end(); ++it) @@ -584,7 +584,7 @@ std::vector CSimulation2::GetCivData() { // Some error reading directory wchar_t error[200]; - LOGERROR(L"Error reading directory '%ls': %hs", path.string().c_str(), error_description_r(ret, error, ARRAY_SIZE(error))); + LOGERROR(L"Error reading directory '%ls': %hs", path.string().c_str(), StatusDescription(ret, error, ARRAY_SIZE(error))); } // Convert from vector to array and stringify diff --git a/source/simulation2/Simulation2.h b/source/simulation2/Simulation2.h index b9ce02eaaa..61f51d6248 100644 --- a/source/simulation2/Simulation2.h +++ b/source/simulation2/Simulation2.h @@ -118,7 +118,7 @@ public: * Reload any scripts that were loaded from the given filename. * (This is used to implement hotloading.) */ - LibError ReloadChangedFile(const VfsPath& path); + Status ReloadChangedFile(const VfsPath& path); /** * Initialise (or re-initialise) the complete simulation state. diff --git a/source/simulation2/components/CCmpTemplateManager.cpp b/source/simulation2/components/CCmpTemplateManager.cpp index 443e481b2b..e63d1b027c 100644 --- a/source/simulation2/components/CCmpTemplateManager.cpp +++ b/source/simulation2/components/CCmpTemplateManager.cpp @@ -375,7 +375,7 @@ void CCmpTemplateManager::ConstructTemplateActor(const std::string& actorName, C CParamNode::LoadXMLString(out, xml.c_str()); } -static LibError AddToTemplates(const VfsPath& pathname, const FileInfo& UNUSED(fileInfo), const uintptr_t cbData) +static Status AddToTemplates(const VfsPath& pathname, const FileInfo& UNUSED(fileInfo), const uintptr_t cbData) { std::vector& templates = *(std::vector*)cbData; @@ -392,7 +392,7 @@ static LibError AddToTemplates(const VfsPath& pathname, const FileInfo& UNUSED(f return INFO::OK; } -static LibError AddActorToTemplates(const VfsPath& pathname, const FileInfo& UNUSED(fileInfo), const uintptr_t cbData) +static Status AddActorToTemplates(const VfsPath& pathname, const FileInfo& UNUSED(fileInfo), const uintptr_t cbData) { std::vector& templates = *(std::vector*)cbData; @@ -411,17 +411,17 @@ std::vector CCmpTemplateManager::FindAllTemplates(bool includeActor std::vector templates; - LibError ok; + Status ok; // Find all the normal entity templates first ok = fs_util::ForEachFile(g_VFS, TEMPLATE_ROOT, AddToTemplates, (uintptr_t)&templates, L"*.xml", fs_util::DIR_RECURSIVE); - WARN_ERR(ok); + WARN_IF_ERR(ok); if (includeActors) { // Add all the actors too ok = fs_util::ForEachFile(g_VFS, ACTOR_ROOT, AddActorToTemplates, (uintptr_t)&templates, L"*.xml", fs_util::DIR_RECURSIVE); - WARN_ERR(ok); + WARN_IF_ERR(ok); } return templates; diff --git a/source/simulation2/components/ICmpAIManager.cpp b/source/simulation2/components/ICmpAIManager.cpp index bb04a34e80..7bea21dc56 100644 --- a/source/simulation2/components/ICmpAIManager.cpp +++ b/source/simulation2/components/ICmpAIManager.cpp @@ -45,7 +45,7 @@ public: fs_util::ForEachFile(g_VFS, L"simulation/ai/", Callback, (uintptr_t)this, L"*.json", fs_util::DIR_RECURSIVE); } - static LibError Callback(const VfsPath& pathname, const FileInfo& UNUSED(fileInfo), const uintptr_t cbData) + static Status Callback(const VfsPath& pathname, const FileInfo& UNUSED(fileInfo), const uintptr_t cbData) { GetAIsHelper* self = (GetAIsHelper*)cbData; diff --git a/source/simulation2/serialization/IDeserializer.cpp b/source/simulation2/serialization/IDeserializer.cpp index 1560e9a9a5..fb96e02647 100644 --- a/source/simulation2/serialization/IDeserializer.cpp +++ b/source/simulation2/serialization/IDeserializer.cpp @@ -179,7 +179,7 @@ void IDeserializer::String(const char* UNUSED(name), std::wstring& out, uint32_t str.resize(len); // TODO: should check len <= bytes remaining in stream Get((u8*)str.data(), len); - LibError err; + Status err; out = wstring_from_utf8(str, &err); if (err) throw PSERROR_Deserialize_InvalidCharInString(); diff --git a/source/simulation2/serialization/ISerializer.cpp b/source/simulation2/serialization/ISerializer.cpp index 201bf81d95..8c4b429062 100644 --- a/source/simulation2/serialization/ISerializer.cpp +++ b/source/simulation2/serialization/ISerializer.cpp @@ -84,7 +84,7 @@ void ISerializer::String(const char* name, const std::wstring& value, uint32_t m if (!(minlength <= value.length() && value.length() <= maxlength)) throw PSERROR_Serialize_OutOfBounds(); - LibError err; + Status err; std::string str = utf8_from_wstring(value, &err); if (err) throw PSERROR_Serialize_InvalidCharInString(); diff --git a/source/sound/SoundGroup.cpp b/source/sound/SoundGroup.cpp index 7624a0f8bd..cb6227ecad 100644 --- a/source/sound/SoundGroup.cpp +++ b/source/sound/SoundGroup.cpp @@ -118,7 +118,7 @@ void CSoundGroup::UploadPropertiesAndPlay(Handle hSound, const CVector3D& positi } -static void HandleError(const std::wstring& message, const VfsPath& pathname, LibError err) +static void HandleError(const std::wstring& message, const VfsPath& pathname, Status err) { if(err == ERR::AGAIN) return; // open failed because sound is disabled (don't log this) @@ -136,7 +136,7 @@ void CSoundGroup::PlayNext(const CVector3D& position) m_hReplacement = snd_open(g_VFS, pathname); if(m_hReplacement < 0) { - HandleError(L"PlayNext: snd_open for replacement file failed", pathname, (LibError)m_hReplacement); + HandleError(L"PlayNext: snd_open for replacement file failed", pathname, (Status)m_hReplacement); return; } @@ -157,7 +157,7 @@ void CSoundGroup::PlayNext(const CVector3D& position) Handle hs = snd_open(g_VFS, pathname); if(hs < 0) { - HandleError(L"PlayNext: snd_open failed", pathname, (LibError)hs); + HandleError(L"PlayNext: snd_open failed", pathname, (Status)hs); return; }