Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

orkaudio: Fix leak in ConfigManager #112

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from

Conversation

kingster
Copy link
Member

@kingster kingster commented Jun 29, 2022

Leak Info

==16187== 54,336 (224 direct, 54,112 indirect) bytes in 1 blocks are definitely lost in loss record 2,012 of 2,023
==16187==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==16187==    by 0x4FDF968: xercesc_3_1::MemoryManagerImpl::allocate(unsigned long) (in /usr/lib/x86_64-linux-gnu/libxerces-c-3.1.so)
==16187==    by 0x4F64BE7: xercesc_3_1::XMemory::operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/libxerces-c-3.1.so)
==16187==    by 0x57E3AD9: ConfigManager::Initialize() (ConfigManager.cpp:113)
==16187==    by 0x40F062: MainThread() (OrkAudio.cpp:227)
==16187==    by 0x40C87F: main (OrkAudio.cpp:440)

Attempted Fix

diff --git a/orkbasecxx/ConfigManager.cpp b/orkbasecxx/ConfigManager.cpp
index f0653766..aa16f482 100644
--- a/orkbasecxx/ConfigManager.cpp
+++ b/orkbasecxx/ConfigManager.cpp

@@ -150,11 +150,13 @@ void ConfigManager::Initialize()
 				LOG4CXX_ERROR(LOG.configLog, CStdString("Could not parse config file:") + CONFIG_FILE_NAME);
 				failed = true;
 			}
+			doc->release();
 		}
 		else
 		{
 			LOG4CXX_WARN(LOG.configLog, CStdString("Could not find config file:") + CONFIG_FILE_NAME);
 		}
+		delete m_parser;
 	}
 	catch (const CStdString& e)
 	{

Throws this exception when run without debug mode

Stack trace (most recent call last):
#1    Object "", at 0x9a80ff, in
#0    Object "/usr/lib/x86_64-linux-gnu/libxerces-c-3.1.so", at 0x7f85f4550230, in xercesc_3_1::AbstractDOMParser::cleanUp()
Segmentation fault (Invalid permissions for mapped object [0x7f85f2b52cc8])
Segmentation fault (core dumped)

Summary by CodeRabbit

  • Refactor
    • Streamlined the configuration setup process to enhance state persistence and reliability during initialization.
  • Style
    • Adjusted internal formatting for improved readability while preserving error handling and control flow.

@kingster
Copy link
Member Author

kingster commented Jun 29, 2022

Fixed by removing

doc->release(); 

Seems like this is not required, delete takes care of that release itself.

Before

==137388== LEAK SUMMARY:
==137388==    definitely lost: 224 bytes in 1 blocks
==137388==    indirectly lost: 51,988 bytes in 248 blocks
==137388==      possibly lost: 395,866 bytes in 2,834 blocks
==137388==    still reachable: 203,256 bytes in 1,013 blocks
==137388==         suppressed: 0 bytes in 0 blocks

After

==136663== LEAK SUMMARY:
==136663==    definitely lost: 0 bytes in 0 blocks
==136663==    indirectly lost: 0 bytes in 0 blocks
==136663==      possibly lost: 278,018 bytes in 2,826 blocks
==136663==    still reachable: 203,294 bytes in 1,013 blocks
==136663==         suppressed: 0 bytes in 0 blocks

possibly lost are mostly other xercesc internal references.

@kingster kingster marked this pull request as ready for review June 29, 2022 20:19
@kingster
Copy link
Member Author

Crashes on orkaudio debug on ubuntu16.04

2022-06-30 02:01:18,439  INFO root:109 - Loaded plugin: /usr/lib/libvoip.so
Stack trace (most recent call last):
#3    Object "", at 0x6e68, in
#2    Object "", at 0x9, in
#1    Object "/lib/x86_64-linux-gnu/ld-2.23.so", at 0x7ffeef1e61df, in
#0    Source "/oreka-src/orkbasecxx/serializers/DomSerializer.cpp", line 185, in FindElementByName [0x7f0bc06d99af]
Segmentation fault (Invalid permissions for mapped object [0x9dce30])
Segmentation fault (core dumped)

@kingster kingster marked this pull request as draft June 29, 2022 20:39
kingster added 2 commits June 30, 2022 02:25
…to fix-leak-config-manager

* 'fix-leak-config-manager' of github.com:voiceip/oreka:
  orkaudio: Fix leak in Opus Header Write (#110)
@kingster
Copy link
Member Author

Not exactly sure, but this looked like a case of shadow variable. Changing it to class reference, both resolves the leak & seg fault.

@voiceip voiceip deleted a comment from coderabbitai bot Feb 6, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
orkbasecxx/ConfigManager.cpp (1)

176-179: Improve error handling to ensure proper cleanup.

The current implementation exits the program on failure without proper cleanup. This could lead to resource leaks.

Consider using RAII or ensuring cleanup on all exit paths:

void ConfigManager::Initialize() {
    struct Cleanup {
        XercesDOMParser** parser;
        bool* failed;
        Cleanup(XercesDOMParser** p, bool* f) : parser(p), failed(f) {}
        ~Cleanup() {
            if (*failed) {
                delete *parser;
                *parser = nullptr;
                XMLPlatformUtils::Terminate();
            }
        }
    } cleanup(&m_parser, &failed);
    
    // ... rest of the function ...
    
    if (failed) {
        throw std::runtime_error("Configuration initialization failed");
    }
}
🧹 Nitpick comments (1)
orkbasecxx/ConfigManager.cpp (1)

113-119: LGTM! Memory management looks correct.

The change to make m_parser a member variable and removing doc->release() is the right approach, as the parser owns the document's memory. This fixes both the memory leak and segmentation fault mentioned in the PR objectives.

Consider initializing m_parser in the constructor's initialization list and adding nullptr checks:

class ConfigManager {
private:
    XercesDOMParser* m_parser;
public:
    ConfigManager() : m_parser(nullptr) {}
    // ... rest of the class
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4744bf2 and 2bad620.

📒 Files selected for processing (1)
  • orkbasecxx/ConfigManager.cpp (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build Image
  • GitHub Check: Build Orkweb & Orktrack

@@ -100,7 +100,7 @@ void ConfigManager::Initialize()
}
}

XMLPlatformUtils::Initialize();
XMLPlatformUtils::Initialize();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add corresponding XMLPlatformUtils::Terminate() call.

While XMLPlatformUtils::Initialize() is now correctly active, there's no matching Terminate() call. This could lead to resource leaks.

Consider adding cleanup in the destructor:

ConfigManager::~ConfigManager() {
    if (m_parser) {
        delete m_parser;
        m_parser = nullptr;
    }
    XMLPlatformUtils::Terminate();
}

@voiceip voiceip deleted a comment from coderabbitai bot Feb 6, 2025
Copy link

coderabbitai bot commented Feb 6, 2025

Walkthrough

The pull request updates the ConfigManager class's initialization logic. It removes the local declaration of m_parser in favor of directly assigning to the class member, ensuring its persistence beyond the Initialize method. Additionally, the initialization of XMLPlatformUtils has been reformatted by reducing unnecessary indentation. The exception handling and overall control flow for parsing and error reporting remain unchanged.

Changes

File Change Summary
orkbasecxx/ConfigManager.cpp Directly assigns m_parser to the class member (removing the local variable) and adjusts XMLPlatformUtils indentation for improved readability; error handling remains intact.

Poem

🐇 In code I hop with paws so light,
Changing paths from local to a lasting site.
My parser now lives where memory can stay,
With tidy lines that brighten the day.
A joyful update in our digital play!

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 523705a and bdccf9e.

📒 Files selected for processing (1)
  • orkbasecxx/ConfigManager.cpp (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build Orkaudio (focal)
  • GitHub Check: Build Orkaudio (bionic)
  • GitHub Check: Build Orkaudio (xenial)
  • GitHub Check: Build Image
🔇 Additional comments (1)
orkbasecxx/ConfigManager.cpp (1)

103-103: Add corresponding XMLPlatformUtils::Terminate() call.

While XMLPlatformUtils::Initialize() is now correctly active, there's no matching Terminate() call. This could lead to resource leaks.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant