From 9cfcbc46e6bcd585916732c027fe844ffae060bd Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Sat, 10 Dec 2022 21:09:50 -0800 Subject: [PATCH] Global: Cleanup initialization/pointer checks. Cleaning up a lot of cases of uninitialized data, unchecked return values for failures, and similar. --- Common/Arm64Emitter.h | 2 +- Common/ArmEmitter.h | 29 ++++++------- Common/CPUDetect.cpp | 5 ++- Common/ConsoleListener.h | 4 +- Common/Data/Format/JSONReader.h | 8 ++-- Common/File/FileUtil.cpp | 5 ++- Common/GPU/D3D11/thin3d_d3d11.cpp | 6 ++- Common/GPU/D3D9/thin3d_d3d9.cpp | 9 ++-- Common/GPU/Vulkan/VulkanQueueRunner.cpp | 9 ++-- Common/GPU/Vulkan/thin3d_vulkan.cpp | 12 ++---- Common/Math/expression_parser.cpp | 4 +- Common/Net/HTTPClient.cpp | 2 +- Common/Render/Text/draw_text_win.cpp | 1 + Common/RiscVEmitter.h | 2 +- Common/UI/ViewGroup.cpp | 2 +- Core/Debugger/DisassemblyManager.cpp | 2 +- Core/Debugger/SymbolMap.cpp | 8 ++-- Core/ELF/ElfReader.cpp | 6 +-- Core/FileSystems/MetaFileSystem.h | 2 +- Core/HLE/sceIo.cpp | 5 ++- Core/HW/Camera.cpp | 6 ++- Core/MIPS/IR/IRCompVFPU.cpp | 4 +- Core/Util/BlockAllocator.cpp | 1 + Core/Util/PortManager.cpp | 6 +++ GPU/Common/TextureShaderCommon.cpp | 2 +- GPU/D3D11/DrawEngineD3D11.cpp | 55 +++++++++++++++++-------- GPU/D3D11/TextureCacheD3D11.cpp | 6 ++- GPU/Debugger/Record.cpp | 2 + Windows/DSoundStream.cpp | 2 + Windows/Debugger/Debugger_Disasm.cpp | 4 +- Windows/Debugger/DumpMemoryWindow.cpp | 4 +- Windows/GPU/WindowsGLContext.h | 3 -- Windows/MainWindow.cpp | 2 +- Windows/RawInput.cpp | 10 ++++- Windows/TouchInputHandler.cpp | 15 +++---- Windows/W32Util/Misc.cpp | 12 +++--- Windows/W32Util/ShellUtil.cpp | 8 +++- Windows/WASAPIStream.cpp | 21 ++++++---- Windows/WindowsHost.cpp | 14 ++++--- Windows/XinputDevice.cpp | 6 +-- Windows/main.cpp | 22 ++++------ 41 files changed, 190 insertions(+), 138 deletions(-) diff --git a/Common/Arm64Emitter.h b/Common/Arm64Emitter.h index 66add4e269..aaeb24fb1d 100644 --- a/Common/Arm64Emitter.h +++ b/Common/Arm64Emitter.h @@ -253,7 +253,7 @@ public: private: ARM64Reg m_destReg; WidthSpecifier m_width; - ExtendSpecifier m_extend; + ExtendSpecifier m_extend = EXTEND_UXTB; TypeSpecifier m_type; ShiftType m_shifttype; u32 m_shift; diff --git a/Common/ArmEmitter.h b/Common/ArmEmitter.h index d71c1efdf2..46a36c8805 100644 --- a/Common/ArmEmitter.h +++ b/Common/ArmEmitter.h @@ -112,32 +112,29 @@ private: OpType Type; // IMM types - u8 Rotation; // Only for u8 values + u8 Rotation = 0; // Only for u8 values // Register types - u8 IndexOrShift; - ShiftType Shift; + u8 IndexOrShift = 0; + ShiftType Shift = ST_LSL; public: - OpType GetType() const - { + OpType GetType() const { return Type; } - Operand2() {} - Operand2(u32 imm, OpType type = TYPE_IMM) - { - Type = type; - Value = imm; - Rotation = 0; + Operand2() { + Type = TYPE_IMM; + Value = 0; + } + Operand2(u32 imm, OpType type = TYPE_IMM) { + Type = type; + Value = imm; } - Operand2(ARMReg Reg) - { + Operand2(ARMReg Reg) { Type = TYPE_REG; Value = Reg; - Rotation = 0; } - Operand2(u8 imm, u8 rotation) - { + Operand2(u8 imm, u8 rotation) { Type = TYPE_IMM; Value = imm; Rotation = rotation; diff --git a/Common/CPUDetect.cpp b/Common/CPUDetect.cpp index 262bbf4def..ebf78012b6 100644 --- a/Common/CPUDetect.cpp +++ b/Common/CPUDetect.cpp @@ -321,7 +321,10 @@ void CPUInfo::Detect() { #if PPSSPP_PLATFORM(WINDOWS) #if !PPSSPP_PLATFORM(UWP) typedef BOOL (WINAPI *getLogicalProcessorInformationEx_f)(LOGICAL_PROCESSOR_RELATIONSHIP RelationshipType, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX Buffer, PDWORD ReturnedLength); - auto getLogicalProcessorInformationEx = (getLogicalProcessorInformationEx_f)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "GetLogicalProcessorInformationEx"); + getLogicalProcessorInformationEx_f getLogicalProcessorInformationEx = nullptr; + HMODULE kernel32 = GetModuleHandle(L"kernel32.dll"); + if (kernel32) + getLogicalProcessorInformationEx = (getLogicalProcessorInformationEx_f)GetProcAddress(kernel32, "GetLogicalProcessorInformationEx"); #else void *getLogicalProcessorInformationEx = nullptr; #endif diff --git a/Common/ConsoleListener.h b/Common/ConsoleListener.h index 32a32b7981..99c6730750 100644 --- a/Common/ConsoleListener.h +++ b/Common/ConsoleListener.h @@ -66,8 +66,8 @@ private: static std::atomic logPendingReadPos; static std::atomic logPendingWritePos; - int openWidth_; - int openHeight_; + int openWidth_ = 0; + int openHeight_ = 0; std::wstring title_; #endif bool bHidden; diff --git a/Common/Data/Format/JSONReader.h b/Common/Data/Format/JSONReader.h index 4156650301..792d6a669a 100644 --- a/Common/Data/Format/JSONReader.h +++ b/Common/Data/Format/JSONReader.h @@ -47,9 +47,11 @@ public: JsonReader(const std::string &filename); JsonReader(const void *data, size_t size) { buffer_ = (char *)malloc(size + 1); - memcpy(buffer_, data, size); - buffer_[size] = 0; - parse(); + if (buffer_) { + memcpy(buffer_, data, size); + buffer_[size] = 0; + parse(); + } } JsonReader(const JsonNode *node) { ok_ = true; diff --git a/Common/File/FileUtil.cpp b/Common/File/FileUtil.cpp index 8bab82ae6e..e8088e90bc 100644 --- a/Common/File/FileUtil.cpp +++ b/Common/File/FileUtil.cpp @@ -141,7 +141,7 @@ FILE *OpenCFile(const Path &path, const char *mode) { return nullptr; } FILE *f = fdopen(descriptor, "wb"); - if (!strcmp(mode, "at") || !strcmp(mode, "a")) { + if (f && (!strcmp(mode, "at") || !strcmp(mode, "a"))) { // Append mode. fseek(f, 0, SEEK_END); } @@ -250,7 +250,8 @@ static bool ResolvePathVista(const std::wstring &path, wchar_t *buf, DWORD bufSi #else if (!getFinalPathNameByHandleW) { HMODULE kernel32 = GetModuleHandle(L"kernel32.dll"); - getFinalPathNameByHandleW = (getFinalPathNameByHandleW_f)GetProcAddress(kernel32, "GetFinalPathNameByHandleW"); + if (kernel32) + getFinalPathNameByHandleW = (getFinalPathNameByHandleW_f)GetProcAddress(kernel32, "GetFinalPathNameByHandleW"); } #endif diff --git a/Common/GPU/D3D11/thin3d_d3d11.cpp b/Common/GPU/D3D11/thin3d_d3d11.cpp index 43e6c2b653..faafc4998e 100644 --- a/Common/GPU/D3D11/thin3d_d3d11.cpp +++ b/Common/GPU/D3D11/thin3d_d3d11.cpp @@ -1476,6 +1476,7 @@ void D3D11DrawContext::CopyFramebufferImage(Framebuffer *srcfb, int level, int x dstTex = dst->depthStencilTex; break; } + _assert_(srcTex && dstTex); // TODO: Check for level too! if (width == src->Width() && width == dst->Width() && height == src->Height() && height == dst->Height() && x == 0 && y == 0 && z == 0 && dstX == 0 && dstY == 0 && dstZ == 0) { @@ -1534,7 +1535,7 @@ bool D3D11DrawContext::CopyFramebufferToMemorySync(Framebuffer *src, int channel bool useGlobalPacktex = (bx + bw <= 512 && by + bh <= 512) && channelBits == FB_COLOR_BIT; - ID3D11Texture2D *packTex; + ID3D11Texture2D *packTex = nullptr; if (!useGlobalPacktex) { D3D11_TEXTURE2D_DESC packDesc{}; packDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; @@ -1573,6 +1574,9 @@ bool D3D11DrawContext::CopyFramebufferToMemorySync(Framebuffer *src, int channel packTex = packTexture_; } + if (!packTex) + return false; + D3D11_BOX srcBox{ (UINT)bx, (UINT)by, 0, (UINT)(bx + bw), (UINT)(by + bh), 1 }; DataFormat srcFormat = DataFormat::UNDEFINED; switch (channelBits) { diff --git a/Common/GPU/D3D9/thin3d_d3d9.cpp b/Common/GPU/D3D9/thin3d_d3d9.cpp index 94bce31760..bc0135e834 100644 --- a/Common/GPU/D3D9/thin3d_d3d9.cpp +++ b/Common/GPU/D3D9/thin3d_d3d9.cpp @@ -1072,16 +1072,16 @@ void D3D9Context::UpdateBuffer(Buffer *buffer, const uint8_t *data, size_t offse return; } if (buf->vbuffer_) { - void *ptr; + void *ptr = nullptr; HRESULT res = buf->vbuffer_->Lock((UINT)offset, (UINT)size, &ptr, (flags & UPDATE_DISCARD) ? D3DLOCK_DISCARD : 0); - if (!FAILED(res)) { + if (!FAILED(res) && ptr) { memcpy(ptr, data, size); buf->vbuffer_->Unlock(); } } else if (buf->ibuffer_) { - void *ptr; + void *ptr = nullptr; HRESULT res = buf->ibuffer_->Lock((UINT)offset, (UINT)size, &ptr, (flags & UPDATE_DISCARD) ? D3DLOCK_DISCARD : 0); - if (!FAILED(res)) { + if (!FAILED(res) && ptr) { memcpy(ptr, data, size); buf->ibuffer_->Unlock(); } @@ -1438,6 +1438,7 @@ bool D3D9Context::CopyFramebufferToMemorySync(Framebuffer *src, int channelBits, LPDIRECT3DSURFACE9 offscreen = nullptr; HRESULT hr = E_UNEXPECTED; + _assert_(fb != nullptr); if (channelBits == FB_COLOR_BIT) { fb->tex->GetLevelDesc(0, &desc); diff --git a/Common/GPU/Vulkan/VulkanQueueRunner.cpp b/Common/GPU/Vulkan/VulkanQueueRunner.cpp index ec38cabecd..53f5615931 100644 --- a/Common/GPU/Vulkan/VulkanQueueRunner.cpp +++ b/Common/GPU/Vulkan/VulkanQueueRunner.cpp @@ -1324,7 +1324,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c { VKRGraphicsPipeline *graphicsPipeline = c.graphics_pipeline.pipeline; if (graphicsPipeline != lastGraphicsPipeline) { - VkSampleCountFlagBits fbSampleCount = step.render.framebuffer ? step.render.framebuffer->sampleCount : VK_SAMPLE_COUNT_1_BIT; + VkSampleCountFlagBits fbSampleCount = fb ? fb->sampleCount : VK_SAMPLE_COUNT_1_BIT; if (RenderPassTypeHasMultisample(rpType) && fbSampleCount != graphicsPipeline->SampleCount()) { // should have been invalidated. @@ -1421,12 +1421,13 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c case VKRRenderCommand::SELF_DEPENDENCY_BARRIER: { _assert_(step.render.pipelineFlags & PipelineFlags::USES_INPUT_ATTACHMENT); + _assert_(fb); VulkanBarrier barrier; - if (step.render.framebuffer->sampleCount != VK_SAMPLE_COUNT_1_BIT) { + if (fb->sampleCount != VK_SAMPLE_COUNT_1_BIT) { // Rendering is happening to the multisample buffer, not the color buffer. - SelfDependencyBarrier(step.render.framebuffer->msaaColor, VK_IMAGE_ASPECT_COLOR_BIT, &barrier); + SelfDependencyBarrier(fb->msaaColor, VK_IMAGE_ASPECT_COLOR_BIT, &barrier); } else { - SelfDependencyBarrier(step.render.framebuffer->color, VK_IMAGE_ASPECT_COLOR_BIT, &barrier); + SelfDependencyBarrier(fb->color, VK_IMAGE_ASPECT_COLOR_BIT, &barrier); } barrier.Flush(cmd); break; diff --git a/Common/GPU/Vulkan/thin3d_vulkan.cpp b/Common/GPU/Vulkan/thin3d_vulkan.cpp index bb57abdea4..4cc760f429 100644 --- a/Common/GPU/Vulkan/thin3d_vulkan.cpp +++ b/Common/GPU/Vulkan/thin3d_vulkan.cpp @@ -1184,16 +1184,12 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc, const char } } - if (input) { - for (int i = 0; i < (int)input->bindings.size(); i++) { - pipeline->stride[i] = input->bindings[i].stride; - } - } else { - pipeline->stride[0] = 0; - } - _dbg_assert_(input->bindings.size() == 1); + _dbg_assert_(input && input->bindings.size() == 1); _dbg_assert_((int)input->attributes.size() == (int)input->visc.vertexAttributeDescriptionCount); + for (int i = 0; i < (int)input->bindings.size(); i++) { + pipeline->stride[i] = input->bindings[i].stride; + } gDesc.ibd = input->bindings[0]; for (size_t i = 0; i < input->attributes.size(); i++) { gDesc.attrs[i] = input->attributes[i]; diff --git a/Common/Math/expression_parser.cpp b/Common/Math/expression_parser.cpp index 75e0720c60..b591845bce 100644 --- a/Common/Math/expression_parser.cpp +++ b/Common/Math/expression_parser.cpp @@ -406,8 +406,8 @@ bool parsePostfixExpression(PostfixExpression& exp, IExpressionFunctions* funcs, size_t num = 0; uint32_t opcode; std::vector valueStack; - unsigned int arg[5]; - float fArg[5]; + unsigned int arg[5]{}; + float fArg[5]{}; bool useFloat = false; while (num < exp.size()) diff --git a/Common/Net/HTTPClient.cpp b/Common/Net/HTTPClient.cpp index fec31dabb8..bac18da12d 100644 --- a/Common/Net/HTTPClient.cpp +++ b/Common/Net/HTTPClient.cpp @@ -224,7 +224,7 @@ void DeChunk(Buffer *inbuffer, Buffer *outbuffer, int contentLength, float *prog inbuffer->TakeLineCRLF(&line); if (!line.size()) return; - unsigned int chunkSize; + unsigned int chunkSize = 0; sscanf(line.c_str(), "%x", &chunkSize); if (chunkSize) { std::string data; diff --git a/Common/Render/Text/draw_text_win.cpp b/Common/Render/Text/draw_text_win.cpp index d5af5af762..6cd9885fee 100644 --- a/Common/Render/Text/draw_text_win.cpp +++ b/Common/Render/Text/draw_text_win.cpp @@ -69,6 +69,7 @@ TextDrawerWin32::TextDrawerWin32(Draw::DrawContext *draw) : TextDrawer(draw), ct bmi.bmiHeader.biBitCount = 32; ctx_->hbmBitmap = CreateDIBSection(ctx_->hDC, &bmi, DIB_RGB_COLORS, (VOID**)&ctx_->pBitmapBits, NULL, 0); + _assert_(ctx_->hbmBitmap != nullptr); SetMapMode(ctx_->hDC, MM_TEXT); SelectObject(ctx_->hDC, ctx_->hbmBitmap); diff --git a/Common/RiscVEmitter.h b/Common/RiscVEmitter.h index f2e512a32c..e1b8266a56 100644 --- a/Common/RiscVEmitter.h +++ b/Common/RiscVEmitter.h @@ -113,7 +113,7 @@ struct FixupBranch { ~FixupBranch(); const u8 *ptr = nullptr; - FixupBranchType type; + FixupBranchType type = FixupBranchType::B; }; class RiscVEmitter { diff --git a/Common/UI/ViewGroup.cpp b/Common/UI/ViewGroup.cpp index de556ad5d9..f7b6f49d11 100644 --- a/Common/UI/ViewGroup.cpp +++ b/Common/UI/ViewGroup.cpp @@ -963,7 +963,7 @@ bool ScrollView::SubviewFocused(View *view) { float visibleSize = orientation_ == ORIENT_VERTICAL ? bounds_.h : bounds_.w; float visibleEnd = scrollPos_ + visibleSize; - float viewStart, viewEnd; + float viewStart = 0.0f, viewEnd = 0.0f; switch (orientation_) { case ORIENT_HORIZONTAL: viewStart = layoutScrollPos_ + vBounds.x - bounds_.x; diff --git a/Core/Debugger/DisassemblyManager.cpp b/Core/Debugger/DisassemblyManager.cpp index b57e52610d..667ba134ab 100644 --- a/Core/Debugger/DisassemblyManager.cpp +++ b/Core/Debugger/DisassemblyManager.cpp @@ -122,7 +122,7 @@ void parseDisasm(const char* disasm, char* opcode, char* arguments, bool insertS // parse symbol if (disasm == jumpAddress) { - u32 branchTarget; + u32 branchTarget = 0; sscanf(disasm+3,"%08x",&branchTarget); const std::string addressSymbol = g_symbolMap->GetLabelString(branchTarget); diff --git a/Core/Debugger/SymbolMap.cpp b/Core/Debugger/SymbolMap.cpp index 63e087d7a8..93a3d238e2 100644 --- a/Core/Debugger/SymbolMap.cpp +++ b/Core/Debugger/SymbolMap.cpp @@ -127,9 +127,9 @@ bool SymbolMap::LoadSymbolMap(const Path &filename) { if (!started) continue; - u32 address = -1, size, vaddress = -1; + u32 address = -1, size = 0, vaddress = -1; int moduleIndex = 0; - int typeInt; + int typeInt = ST_NONE; SymbolType type; char name[128] = {0}; @@ -145,7 +145,9 @@ bool SymbolMap::LoadSymbolMap(const Path &filename) { continue; } - sscanf(line, "%08x %08x %x %i %127c", &address, &size, &vaddress, &typeInt, name); + int matched = sscanf(line, "%08x %08x %x %i %127c", &address, &size, &vaddress, &typeInt, name); + if (matched < 1) + continue; type = (SymbolType) typeInt; if (!hasModules) { if (!Memory::IsValidAddress(vaddress)) { diff --git a/Core/ELF/ElfReader.cpp b/Core/ELF/ElfReader.cpp index a4a6bfb856..2baf2690d6 100644 --- a/Core/ELF/ElfReader.cpp +++ b/Core/ELF/ElfReader.cpp @@ -128,7 +128,7 @@ bool ElfReader::LoadRelocations(const Elf32_Rel *rels, int numRelocs) { if (log) { DEBUG_LOG(LOADER, "rel at: %08x info: %08x type: %i", addr, info, type); } - u32 relocateTo = segmentVAddr[relative]; + u32 relocateTo = relative >= (int)ARRAY_SIZE(segmentVAddr) ? 0 : segmentVAddr[relative]; switch (type) { case R_MIPS_32: @@ -289,9 +289,9 @@ void ElfReader::LoadRelocations2(int rel_seg) } }else{ addr_seg = seg; - relocate_to = segmentVAddr[addr_seg]; + relocate_to = addr_seg >= (int)ARRAY_SIZE(segmentVAddr) ? 0 : segmentVAddr[addr_seg]; if (!Memory::IsValidAddress(relocate_to)) { - ERROR_LOG(LOADER, "ELF: Bad address to relocate to: %08x", relocate_to); + ERROR_LOG(LOADER, "ELF: Bad address to relocate to: %08x (segment %d)", relocate_to, addr_seg); continue; } diff --git a/Core/FileSystems/MetaFileSystem.h b/Core/FileSystems/MetaFileSystem.h index 545f21bddc..e574423dd6 100644 --- a/Core/FileSystems/MetaFileSystem.h +++ b/Core/FileSystems/MetaFileSystem.h @@ -91,7 +91,7 @@ public: int MapFilePath(const std::string &inpath, std::string &outpath, MountPoint **system); inline int MapFilePath(const std::string &_inpath, std::string &outpath, IFileSystem **system) { - MountPoint *mountPoint; + MountPoint *mountPoint = nullptr; int error = MapFilePath(_inpath, outpath, &mountPoint); if (error == 0) { *system = mountPoint->system.get(); diff --git a/Core/HLE/sceIo.cpp b/Core/HLE/sceIo.cpp index e6fbd166e7..d2cf9ec311 100644 --- a/Core/HLE/sceIo.cpp +++ b/Core/HLE/sceIo.cpp @@ -271,8 +271,9 @@ public: if (p.mode == p.MODE_READ) { pgdInfo = (PGD_DESC*) malloc(sizeof(PGD_DESC)); } - p.DoVoid(pgdInfo, sizeof(PGD_DESC)); - if (p.mode == p.MODE_READ) { + if (pgdInfo) + p.DoVoid(pgdInfo, sizeof(PGD_DESC)); + if (p.mode == p.MODE_READ && pgdInfo) { pgdInfo->block_buf = (u8 *)malloc(pgdInfo->block_size * 2); } } diff --git a/Core/HW/Camera.cpp b/Core/HW/Camera.cpp index 3b99eab646..9cf8138e21 100644 --- a/Core/HW/Camera.cpp +++ b/Core/HW/Camera.cpp @@ -60,7 +60,11 @@ void convert_frame(int inw, int inh, unsigned char *inData, AVPixelFormat inForm void __cameraDummyImage(int width, int height, unsigned char** outData, int* outLen) { #ifdef USE_FFMPEG - unsigned char* rgbData = (unsigned char*)malloc(3 * width * height); + unsigned char *rgbData = (unsigned char *)malloc(3 * width * height); + if (!rgbData) { + *outData = nullptr; + return; + } for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { rgbData[3 * (y * width + x) + 0] = x*255/width; diff --git a/Core/MIPS/IR/IRCompVFPU.cpp b/Core/MIPS/IR/IRCompVFPU.cpp index 11050c44cc..bfdcf69bed 100644 --- a/Core/MIPS/IR/IRCompVFPU.cpp +++ b/Core/MIPS/IR/IRCompVFPU.cpp @@ -184,7 +184,7 @@ namespace MIPSComp { return; int n = GetNumVectorElements(sz); - u8 origV[4]; + u8 origV[4]{}; static const float constantArray[8] = { 0.f, 1.f, 2.f, 0.5f, 3.f, 1.f / 3.f, 0.25f, 1.f / 6.f }; for (int i = 0; i < n; i++) @@ -1697,7 +1697,7 @@ namespace MIPSComp { GetVectorRegs(tregs, sz, _VT); GetVectorRegs(dregs, sz, _VD); - u8 tempregs[4]; + u8 tempregs[4]{}; for (int i = 0; i < n; ++i) { if (!IsOverlapSafe(dregs[i], n, sregs, n, tregs)) { tempregs[i] = IRVTEMP_PFX_T + i; // using IRTEMP0 for other things diff --git a/Core/Util/BlockAllocator.cpp b/Core/Util/BlockAllocator.cpp index 696a43513d..270cca6508 100644 --- a/Core/Util/BlockAllocator.cpp +++ b/Core/Util/BlockAllocator.cpp @@ -462,6 +462,7 @@ void BlockAllocator::DoState(PointerWrap &p) } else { + _assert_(bottom_ != nullptr); for (const Block *bp = bottom_; bp != NULL; bp = bp->next) ++count; Do(p, count); diff --git a/Core/Util/PortManager.cpp b/Core/Util/PortManager.cpp index 79120053c8..b0c2bfe487 100644 --- a/Core/Util/PortManager.cpp +++ b/Core/Util/PortManager.cpp @@ -127,7 +127,13 @@ bool PortManager::Initialize(const unsigned int timeout) { m_leaseDuration = "43200"; // 12 hours m_InitState = UPNP_INITSTATE_BUSY; urls = (UPNPUrls*)malloc(sizeof(struct UPNPUrls)); + if (!urls) + return false; datas = (IGDdatas*)malloc(sizeof(struct IGDdatas)); + if (!datas) { + free(urls); + return false; + } memset(urls, 0, sizeof(struct UPNPUrls)); memset(datas, 0, sizeof(struct IGDdatas)); diff --git a/GPU/Common/TextureShaderCommon.cpp b/GPU/Common/TextureShaderCommon.cpp index b706edae66..93428a2238 100644 --- a/GPU/Common/TextureShaderCommon.cpp +++ b/GPU/Common/TextureShaderCommon.cpp @@ -233,7 +233,7 @@ std::vector TextureShaderCache::DebugGetShaderIDs(DebugShaderType t } std::string TextureShaderCache::DebugGetShaderString(std::string idstr, DebugShaderType type, DebugShaderStringType stringType) { - uint32_t id; + uint32_t id = 0; sscanf(idstr.c_str(), "%08x", &id); auto iter = depalCache_.find(id); if (iter == depalCache_.end()) diff --git a/GPU/D3D11/DrawEngineD3D11.cpp b/GPU/D3D11/DrawEngineD3D11.cpp index 304d325ea9..87b7d866b8 100644 --- a/GPU/D3D11/DrawEngineD3D11.cpp +++ b/GPU/D3D11/DrawEngineD3D11.cpp @@ -760,6 +760,14 @@ TessellationDataTransferD3D11::~TessellationDataTransferD3D11() { } } +template +static void DoRelease(T *&ptr) { + if (ptr) { + ptr->Release(); + ptr = nullptr; + } +} + void TessellationDataTransferD3D11::SendDataToShader(const SimpleVertex *const *points, int size_u, int size_v, u32 vertType, const Spline::Weight2D &weights) { struct TessData { float pos[3]; float pad1; @@ -769,19 +777,24 @@ void TessellationDataTransferD3D11::SendDataToShader(const SimpleVertex *const * int size = size_u * size_v; - if (prevSize < size) { + if (prevSize < size || !buf[0]) { prevSize = size; - if (buf[0]) buf[0]->Release(); - if (view[0]) view[0]->Release(); + DoRelease(buf[0]); + DoRelease(view[0]); desc.ByteWidth = size * sizeof(TessData); desc.StructureByteStride = sizeof(TessData); device_->CreateBuffer(&desc, nullptr, &buf[0]); - device_->CreateShaderResourceView(buf[0], nullptr, &view[0]); + if (buf[0]) + device_->CreateShaderResourceView(buf[0], nullptr, &view[0]); + if (!buf[0] || !view[0]) + return; context_->VSSetShaderResources(0, 1, &view[0]); } - D3D11_MAPPED_SUBRESOURCE map; - context_->Map(buf[0], 0, D3D11_MAP_WRITE_DISCARD, 0, &map); + D3D11_MAPPED_SUBRESOURCE map{}; + HRESULT hr = context_->Map(buf[0], 0, D3D11_MAP_WRITE_DISCARD, 0, &map); + if (FAILED(hr)) + return; uint8_t *data = (uint8_t *)map.pData; float *pos = (float *)(data); @@ -796,34 +809,42 @@ void TessellationDataTransferD3D11::SendDataToShader(const SimpleVertex *const * using Spline::Weight; // Weights U - if (prevSizeWU < weights.size_u) { + if (prevSizeWU < weights.size_u || !buf[1]) { prevSizeWU = weights.size_u; - if (buf[1]) buf[1]->Release(); - if (view[1]) view[1]->Release(); + DoRelease(buf[1]); + DoRelease(view[1]); desc.ByteWidth = weights.size_u * sizeof(Weight); desc.StructureByteStride = sizeof(Weight); device_->CreateBuffer(&desc, nullptr, &buf[1]); - device_->CreateShaderResourceView(buf[1], nullptr, &view[1]); + if (buf[1]) + device_->CreateShaderResourceView(buf[1], nullptr, &view[1]); + if (!buf[1] || !view[1]) + return; context_->VSSetShaderResources(1, 1, &view[1]); } - context_->Map(buf[1], 0, D3D11_MAP_WRITE_DISCARD, 0, &map); - memcpy(map.pData, weights.u, weights.size_u * sizeof(Weight)); + hr = context_->Map(buf[1], 0, D3D11_MAP_WRITE_DISCARD, 0, &map); + if (SUCCEEDED(hr)) + memcpy(map.pData, weights.u, weights.size_u * sizeof(Weight)); context_->Unmap(buf[1], 0); // Weights V if (prevSizeWV < weights.size_v) { prevSizeWV = weights.size_v; - if (buf[2]) buf[2]->Release(); - if (view[2]) view[2]->Release(); + DoRelease(buf[2]); + DoRelease(view[2]); desc.ByteWidth = weights.size_v * sizeof(Weight); desc.StructureByteStride = sizeof(Weight); device_->CreateBuffer(&desc, nullptr, &buf[2]); - device_->CreateShaderResourceView(buf[2], nullptr, &view[2]); + if (buf[2]) + device_->CreateShaderResourceView(buf[2], nullptr, &view[2]); + if (!buf[2] || !view[2]) + return; context_->VSSetShaderResources(2, 1, &view[2]); } - context_->Map(buf[2], 0, D3D11_MAP_WRITE_DISCARD, 0, &map); - memcpy(map.pData, weights.v, weights.size_v * sizeof(Weight)); + hr = context_->Map(buf[2], 0, D3D11_MAP_WRITE_DISCARD, 0, &map); + if (SUCCEEDED(hr)) + memcpy(map.pData, weights.v, weights.size_v * sizeof(Weight)); context_->Unmap(buf[2], 0); } diff --git a/GPU/D3D11/TextureCacheD3D11.cpp b/GPU/D3D11/TextureCacheD3D11.cpp index 486ad9417f..b8e799b476 100644 --- a/GPU/D3D11/TextureCacheD3D11.cpp +++ b/GPU/D3D11/TextureCacheD3D11.cpp @@ -314,7 +314,7 @@ void TextureCacheD3D11::BuildTexture(TexCacheEntry *const entry) { // We don't yet have mip generation, so clamp the number of levels to the ones we can load directly. levels = std::min(plan.levelsToCreate, plan.levelsToLoad); - ID3D11Texture2D *tex; + ID3D11Texture2D *tex = nullptr; D3D11_TEXTURE2D_DESC desc{}; desc.CPUAccessFlags = 0; desc.Usage = D3D11_USAGE_DEFAULT; @@ -329,7 +329,7 @@ void TextureCacheD3D11::BuildTexture(TexCacheEntry *const entry) { ASSERT_SUCCESS(device_->CreateTexture2D(&desc, nullptr, &tex)); texture = tex; } else { - ID3D11Texture3D *tex; + ID3D11Texture3D *tex = nullptr; D3D11_TEXTURE3D_DESC desc{}; desc.CPUAccessFlags = 0; desc.Usage = D3D11_USAGE_DEFAULT; @@ -504,6 +504,8 @@ bool TextureCacheD3D11::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int level ID3D11Texture2D *stagingCopy = nullptr; device_->CreateTexture2D(&desc, nullptr, &stagingCopy); + if (!stagingCopy) + return false; context_->CopyResource(stagingCopy, texture); D3D11_MAPPED_SUBRESOURCE map; diff --git a/GPU/Debugger/Record.cpp b/GPU/Debugger/Record.cpp index e5fa0b7d1d..391b031974 100644 --- a/GPU/Debugger/Record.cpp +++ b/GPU/Debugger/Record.cpp @@ -373,6 +373,8 @@ static u32 GetTargetFlags(u32 addr, u32 sizeInRAM) { bool isDrawnVRAM = false; uint32_t start = (addr >> DIRTY_VRAM_SHIFT) & DIRTY_VRAM_MASK; uint32_t blocks = (sizeInRAM + DIRTY_VRAM_ROUND) >> DIRTY_VRAM_SHIFT; + if (start + blocks >= DIRTY_VRAM_SIZE) + return 0; bool startEven = (addr & DIRTY_VRAM_ROUND) == 0; bool endEven = ((addr + sizeInRAM) & DIRTY_VRAM_ROUND) == 0; for (uint32_t i = 0; i < blocks; ++i) { diff --git a/Windows/DSoundStream.cpp b/Windows/DSoundStream.cpp index 96265d5eac..9144a3be4f 100644 --- a/Windows/DSoundStream.cpp +++ b/Windows/DSoundStream.cpp @@ -183,6 +183,8 @@ bool DSoundAudioBackend::Init(HWND window, StreamCallback _callback, int sampleR sampleRate_ = sampleRate; threadData_ = 0; hThread_ = (HANDLE)_beginthreadex(0, 0, soundThread, (void *)this, 0, 0); + if (!hThread_) + return false; SetThreadPriority(hThread_, THREAD_PRIORITY_ABOVE_NORMAL); return true; } diff --git a/Windows/Debugger/Debugger_Disasm.cpp b/Windows/Debugger/Debugger_Disasm.cpp index c7b98f52c5..00a7b1ed51 100644 --- a/Windows/Debugger/Debugger_Disasm.cpp +++ b/Windows/Debugger/Debugger_Disasm.cpp @@ -901,8 +901,8 @@ void CDisasm::ProcessUpdateDialog() { // Update Debug Counter if (PSP_IsInited()) { - wchar_t tempTicks[24]; - _snwprintf(tempTicks, 24, L"%lld", CoreTiming::GetTicks() - lastTicks); + wchar_t tempTicks[24]{}; + _snwprintf(tempTicks, 23, L"%lld", CoreTiming::GetTicks() - lastTicks); SetDlgItemText(m_hDlg, IDC_DEBUG_COUNT, tempTicks); } diff --git a/Windows/Debugger/DumpMemoryWindow.cpp b/Windows/Debugger/DumpMemoryWindow.cpp index 1f852611c2..884ba3bccf 100644 --- a/Windows/Debugger/DumpMemoryWindow.cpp +++ b/Windows/Debugger/DumpMemoryWindow.cpp @@ -229,8 +229,8 @@ void DumpMemoryWindow::changeMode(HWND hwnd, Mode newMode) if (filenameChosen_ == false) SetWindowTextA(GetDlgItem(hwnd,IDC_DUMP_FILENAME),"Custom.dump"); } else { - u32 start, size; - const char* defaultFileName; + u32 start = 0, size = 0; + const char *defaultFileName = ""; switch (selectedMode) { diff --git a/Windows/GPU/WindowsGLContext.h b/Windows/GPU/WindowsGLContext.h index df8190f9dc..2909be60f1 100644 --- a/Windows/GPU/WindowsGLContext.h +++ b/Windows/GPU/WindowsGLContext.h @@ -47,7 +47,4 @@ private: volatile bool resumeRequested; HANDLE pauseEvent; HANDLE resumeEvent; - - int xres; - int yres; }; diff --git a/Windows/MainWindow.cpp b/Windows/MainWindow.cpp index 1eb68f441f..9f3a66e090 100644 --- a/Windows/MainWindow.cpp +++ b/Windows/MainWindow.cpp @@ -195,7 +195,7 @@ namespace MainWindow if (g_Config.UseFullScreen() || inFullscreenResize) return; - WINDOWPLACEMENT placement; + WINDOWPLACEMENT placement{}; GetWindowPlacement(hwndMain, &placement); if (placement.showCmd == SW_SHOWNORMAL) { RECT rc; diff --git a/Windows/RawInput.cpp b/Windows/RawInput.cpp index b9853c1a79..6a5d779203 100644 --- a/Windows/RawInput.cpp +++ b/Windows/RawInput.cpp @@ -379,15 +379,21 @@ namespace WindowsRawInput { } LRESULT Process(HWND hWnd, WPARAM wParam, LPARAM lParam) { - UINT dwSize; + UINT dwSize = 0; GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER)); if (!rawInputBuffer) { rawInputBuffer = malloc(dwSize); + if (!rawInputBuffer) + return DefWindowProc(hWnd, WM_INPUT, wParam, lParam); memset(rawInputBuffer, 0, dwSize); rawInputBufferSize = dwSize; } if (dwSize > rawInputBufferSize) { - rawInputBuffer = realloc(rawInputBuffer, dwSize); + void *newBuf = realloc(rawInputBuffer, dwSize); + if (!newBuf) + return DefWindowProc(hWnd, WM_INPUT, wParam, lParam); + rawInputBuffer = newBuf; + rawInputBufferSize = dwSize; memset(rawInputBuffer, 0, dwSize); } GetRawInputData((HRAWINPUT)lParam, RID_INPUT, rawInputBuffer, &dwSize, sizeof(RAWINPUTHEADER)); diff --git a/Windows/TouchInputHandler.cpp b/Windows/TouchInputHandler.cpp index d27850c759..d0f00e59f6 100644 --- a/Windows/TouchInputHandler.cpp +++ b/Windows/TouchInputHandler.cpp @@ -15,15 +15,12 @@ #include "Windows/MainWindow.h" TouchInputHandler::TouchInputHandler() { - touchInfo = (getTouchInputProc) GetProcAddress( - GetModuleHandle(TEXT("User32.dll")), - "GetTouchInputInfo"); - closeTouch = (closeTouchInputProc) GetProcAddress( - GetModuleHandle(TEXT("User32.dll")), - "CloseTouchInputHandle"); - registerTouch = (registerTouchProc) GetProcAddress( - GetModuleHandle(TEXT("User32.dll")), - "RegisterTouchWindow"); + HMODULE user32 = GetModuleHandle(TEXT("User32.dll")); + if (!user32) + return; + touchInfo = (getTouchInputProc)GetProcAddress(user32, "GetTouchInputInfo"); + closeTouch = (closeTouchInputProc)GetProcAddress(user32, "CloseTouchInputHandle"); + registerTouch = (registerTouchProc)GetProcAddress(user32, "RegisterTouchWindow"); } int TouchInputHandler::ToTouchID(int windowsID, bool allowAllocate) { diff --git a/Windows/W32Util/Misc.cpp b/Windows/W32Util/Misc.cpp index 4d9d101e41..2d7399f2e2 100644 --- a/Windows/W32Util/Misc.cpp +++ b/Windows/W32Util/Misc.cpp @@ -71,12 +71,14 @@ namespace W32Util // Lock the handle and copy the text to the buffer. wchar_t *lptstrCopy = (wchar_t *)GlobalLock(hglbCopy); - wcscpy(lptstrCopy, wtext.c_str()); - lptstrCopy[wtext.size()] = (wchar_t) 0; // null character - GlobalUnlock(hglbCopy); - SetClipboardData(CF_UNICODETEXT, hglbCopy); + if (lptstrCopy) { + wcscpy(lptstrCopy, wtext.c_str()); + lptstrCopy[wtext.size()] = (wchar_t) 0; // null character + GlobalUnlock(hglbCopy); + SetClipboardData(CF_UNICODETEXT, hglbCopy); + } CloseClipboard(); - return TRUE; + return lptstrCopy ? TRUE : FALSE; } void MakeTopMost(HWND hwnd, bool topMost) { diff --git a/Windows/W32Util/ShellUtil.cpp b/Windows/W32Util/ShellUtil.cpp index bd53935d27..2111a24674 100644 --- a/Windows/W32Util/ShellUtil.cpp +++ b/Windows/W32Util/ShellUtil.cpp @@ -33,7 +33,9 @@ namespace W32Util auto idList = SHBrowseForFolder(&info); HMODULE shell32 = GetModuleHandle(L"shell32.dll"); typedef BOOL (WINAPI *SHGetPathFromIDListEx_f)(PCIDLIST_ABSOLUTE pidl, PWSTR pszPath, DWORD cchPath, GPFIDL_FLAGS uOpts); - SHGetPathFromIDListEx_f SHGetPathFromIDListEx_ = (SHGetPathFromIDListEx_f)GetProcAddress(shell32, "SHGetPathFromIDListEx"); + SHGetPathFromIDListEx_f SHGetPathFromIDListEx_ = nullptr; + if (shell32) + SHGetPathFromIDListEx_ = (SHGetPathFromIDListEx_f)GetProcAddress(shell32, "SHGetPathFromIDListEx"); std::string result; if (SHGetPathFromIDListEx_) { @@ -156,7 +158,9 @@ namespace W32Util std::string result; HMODULE shell32 = GetModuleHandle(L"shell32.dll"); typedef HRESULT(WINAPI *SHGetKnownFolderPath_f)(REFKNOWNFOLDERID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath); - SHGetKnownFolderPath_f SHGetKnownFolderPath_ = (SHGetKnownFolderPath_f)GetProcAddress(shell32, "SHGetKnownFolderPath"); + SHGetKnownFolderPath_f SHGetKnownFolderPath_ = nullptr; + if (shell32) + SHGetKnownFolderPath_ = (SHGetKnownFolderPath_f)GetProcAddress(shell32, "SHGetKnownFolderPath"); if (SHGetKnownFolderPath_) { PWSTR path = nullptr; if (SHGetKnownFolderPath_(FOLDERID_Documents, 0, nullptr, &path) == S_OK) { diff --git a/Windows/WASAPIStream.cpp b/Windows/WASAPIStream.cpp index 6079c030de..53f02245b9 100644 --- a/Windows/WASAPIStream.cpp +++ b/Windows/WASAPIStream.cpp @@ -159,16 +159,13 @@ public: __uuidof(IMMDeviceEnumerator), (void**)&_pEnumerator); } - if (hr == S_OK) - { + if (hr == S_OK && _pEnumerator) { hr = _pEnumerator->GetDevice(pwstrId, &pDevice); } - if (hr == S_OK) - { + if (hr == S_OK && pDevice) { hr = pDevice->OpenPropertyStore(STGM_READ, &pProps); } - if (hr == S_OK) - { + if (hr == S_OK && pProps) { // Get the endpoint device's friendly-name property. hr = pProps->GetValue(PKEY_Device_FriendlyName, &varString); } @@ -224,6 +221,8 @@ bool WASAPIAudioBackend::Init(HWND window, StreamCallback callback, int sampleRa callback_ = callback; sampleRate_ = sampleRate; hThread_ = (HANDLE)_beginthreadex(0, 0, soundThread, (void *)this, 0, 0); + if (!hThread_) + return false; SetThreadPriority(hThread_, THREAD_PRIORITY_ABOVE_NORMAL); return true; } @@ -333,7 +332,7 @@ void WASAPIAudioThread::ShutdownAudioDevice() { } bool WASAPIAudioThread::DetectFormat() { - if (!ValidateFormat(deviceFormat_)) { + if (deviceFormat_ && !ValidateFormat(deviceFormat_)) { // Last chance, let's try to ask for one we support instead. WAVEFORMATEXTENSIBLE fmt{}; fmt.Format.cbSize = sizeof(fmt); @@ -356,7 +355,8 @@ bool WASAPIAudioThread::DetectFormat() { CoTaskMemFree(closest); CoTaskMemFree(deviceFormat_); deviceFormat_ = (WAVEFORMATEXTENSIBLE *)CoTaskMemAlloc(sizeof(fmt)); - memcpy(deviceFormat_, &fmt, sizeof(fmt)); + if (deviceFormat_) + memcpy(deviceFormat_, &fmt, sizeof(fmt)); // In case something above gets out of date. return ValidateFormat(deviceFormat_); @@ -387,6 +387,8 @@ bool WASAPIAudioThread::ValidateFormat(const WAVEFORMATEXTENSIBLE *fmt) { // Don't know if PCM16 ever shows up here, the documentation only talks about float... but let's blindly // try to support it :P format_ = Format::UNKNOWN; + if (!fmt) + return false; if (fmt->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) { if (!memcmp(&fmt->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(fmt->SubFormat))) { @@ -572,7 +574,8 @@ void WASAPIAudioThread::Run() { } int WASAPIAudioBackend::RunThread() { - CoInitializeEx(nullptr, COINIT_MULTITHREADED); + HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + _dbg_assert_(SUCCEEDED(hr)); SetCurrentThreadName("WASAPI_audio"); if (threadData_ == 0) { diff --git a/Windows/WindowsHost.cpp b/Windows/WindowsHost.cpp index 610b79890b..06e9ef1662 100644 --- a/Windows/WindowsHost.cpp +++ b/Windows/WindowsHost.cpp @@ -269,7 +269,7 @@ void WindowsHost::BootDone() { } static Path SymbolMapFilename(const Path ¤tFilename, const char *ext) { - File::FileInfo info; + File::FileInfo info{}; // can't fail, definitely exists if it gets this far File::GetFileInfo(currentFilename, &info); if (info.isDirectory) { @@ -311,14 +311,16 @@ bool WindowsHost::IsDebuggingEnabled() { // http://msdn.microsoft.com/en-us/library/aa969393.aspx HRESULT CreateLink(LPCWSTR lpszPathObj, LPCWSTR lpszArguments, LPCWSTR lpszPathLink, LPCWSTR lpszDesc) { HRESULT hres; - IShellLink* psl; - CoInitializeEx(NULL, COINIT_MULTITHREADED); + IShellLink *psl = nullptr; + hres = CoInitializeEx(NULL, COINIT_MULTITHREADED); + if (FAILED(hres)) + return hres; // Get a pointer to the IShellLink interface. It is assumed that CoInitialize // has already been called. hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl); - if (SUCCEEDED(hres)) { - IPersistFile* ppf; + if (SUCCEEDED(hres) && psl) { + IPersistFile *ppf = nullptr; // Set the path to the shortcut target and add the description. psl->SetPath(lpszPathObj); @@ -329,7 +331,7 @@ HRESULT CreateLink(LPCWSTR lpszPathObj, LPCWSTR lpszArguments, LPCWSTR lpszPathL // shortcut in persistent storage. hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); - if (SUCCEEDED(hres)) { + if (SUCCEEDED(hres) && ppf) { // Save the link by calling IPersistFile::Save. hres = ppf->Save(lpszPathLink, TRUE); ppf->Release(); diff --git a/Windows/XinputDevice.cpp b/Windows/XinputDevice.cpp index b9d73c8ecd..3e82015921 100644 --- a/Windows/XinputDevice.cpp +++ b/Windows/XinputDevice.cpp @@ -38,7 +38,7 @@ static XInputGetState_t PPSSPP_XInputGetState = nullptr; static XInputSetState_t PPSSPP_XInputSetState = nullptr; static XInputGetCapabilitiesEx_t PPSSPP_XInputGetCapabilitiesEx = nullptr; static DWORD PPSSPP_XInputVersion = 0; -static HMODULE s_pXInputDLL = 0; +static HMODULE s_pXInputDLL = nullptr; static int s_XInputDLLRefCount = 0; static void UnloadXInputDLL(); @@ -105,7 +105,7 @@ static void UnloadXInputDLL() { if ( s_pXInputDLL ) { if (--s_XInputDLLRefCount == 0) { FreeLibrary( s_pXInputDLL ); - s_pXInputDLL = NULL; + s_pXInputDLL = nullptr; } } } @@ -206,7 +206,7 @@ void XinputDevice::UpdatePad(int pad, const XINPUT_STATE &state, XINPUT_VIBRATIO if (!notified[pad]) { notified[pad] = true; #if !PPSSPP_PLATFORM(UWP) - XINPUT_CAPABILITIES_EX caps; + XINPUT_CAPABILITIES_EX caps{}; if (PPSSPP_XInputGetCapabilitiesEx != nullptr && PPSSPP_XInputGetCapabilitiesEx(1, pad, 0, &caps) == ERROR_SUCCESS) { KeyMap::NotifyPadConnected(DEVICE_ID_XINPUT_0 + pad, StringFromFormat("Xbox 360 Pad: %d/%d", caps.vendorId, caps.productId)); } else { diff --git a/Windows/main.cpp b/Windows/main.cpp index 6584f0cf65..dc790cd7f8 100644 --- a/Windows/main.cpp +++ b/Windows/main.cpp @@ -113,7 +113,7 @@ void OpenDirectory(const char *path) { // SHParseDisplayName can't handle relative paths, so normalize first. std::string resolved = ReplaceAll(File::ResolvePath(path), "/", "\\"); - SFGAOF flags; + SFGAOF flags{}; PIDLIST_ABSOLUTE pidl = nullptr; HRESULT hr = SHParseDisplayName(ConvertUTF8ToWString(resolved).c_str(), nullptr, &pidl, 0, &flags); @@ -174,8 +174,8 @@ std::string GetVideoCardDriverVersion() { IEnumWbemClassObject* pEnum; hr = pIWbemServices->ExecQuery(bstrWQL, bstrPath, WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum); - ULONG uReturned; - VARIANT var; + ULONG uReturned = 0; + VARIANT var{}; IWbemClassObject* pObj = NULL; if (!FAILED(hr)) { hr = pEnum->Next(WBEM_INFINITE, 1, &pObj, &uReturned); @@ -372,16 +372,8 @@ void System_SendMessage(const char *command, const char *parameter) { std::wstring title = ConvertUTF8ToWString(err->T("GenericGraphicsError", "Graphics Error")); MessageBox(MainWindow::GetHWND(), full_error.c_str(), title.c_str(), MB_OK); } else if (!strcmp(command, "setclipboardtext")) { - if (OpenClipboard(MainWindow::GetDisplayHWND())) { - std::wstring data = ConvertUTF8ToWString(parameter); - HANDLE handle = GlobalAlloc(GMEM_MOVEABLE, (data.size() + 1) * sizeof(wchar_t)); - wchar_t *wstr = (wchar_t *)GlobalLock(handle); - memcpy(wstr, data.c_str(), (data.size() + 1) * sizeof(wchar_t)); - GlobalUnlock(wstr); - SetClipboardData(CF_UNICODETEXT, handle); - GlobalFree(handle); - CloseClipboard(); - } + std::wstring data = ConvertUTF8ToWString(parameter); + W32Util::CopyTextToClipboard(MainWindow::GetDisplayHWND(), data); } else if (!strcmp(command, "browse_file")) { MainWindow::BrowseAndBoot(""); } else if (!strcmp(command, "browse_folder")) { @@ -411,6 +403,8 @@ void EnableCrashingOnCrashes() { const DWORD EXCEPTION_SWALLOWING = 0x1; HMODULE kernel32 = LoadLibrary(L"kernel32.dll"); + if (!kernel32) + return; tGetPolicy pGetPolicy = (tGetPolicy)GetProcAddress(kernel32, "GetProcessUserModeExceptionPolicy"); tSetPolicy pSetPolicy = (tSetPolicy)GetProcAddress(kernel32, @@ -773,7 +767,7 @@ int WINAPI WinMain(HINSTANCE _hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLin break; } - if (!TranslateAccelerator(wnd, accel, &msg)) { + if (!wnd || !accel || !TranslateAccelerator(wnd, accel, &msg)) { if (!DialogManager::IsDialogMessage(&msg)) { //and finally translate and dispatch TranslateMessage(&msg);