Skip to content

[None][fix] Fix: Add missing va_end(args0) in fmtstr_ to prevent potential resource leak #6758

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

fyf2016
Copy link
Contributor

@fyf2016 fyf2016 commented Aug 8, 2025

Problem

The fmtstr_ function in the current implementation(cpp/tensorrt_llm/common/stringUtils.cpp) uses va_copy(args0, args) to duplicate the va_list for safe usage in vsnprintf. However, it does not call va_end(args0) to clean up the copied va_list, which can lead to:

  • Resource leaks on certain platforms where va_list requires explicit cleanup.

  • Undefined behavior (UB) per the C/C++ standard, since va_copy must always be paired with va_end.

image

Current Implementation

cpp/tensorrt_llm/common/stringUtils.cpp

void fmtstr_(char const* format, fmtstr_allocator alloc, void* target, va_list args)
{
    va_list args0;
    va_copy(args0, args);

    size_t constexpr init_size = 2048;
    char fixed_buffer[init_size];
    auto const size = std::vsnprintf(fixed_buffer, init_size, format, args0);
    TLLM_CHECK_WITH_INFO(size >= 0, std::string(std::strerror(errno)));
    if (size == 0)
    {
        return;
    }

    auto* memory = alloc(target, size);

    if (static_cast<size_t>(size) < init_size)
    {
        std::memcpy(memory, fixed_buffer, size + 1);
    }
    else
    {
        auto const size2 = std::vsnprintf(memory, size + 1, format, args);
        TLLM_CHECK_WITH_INFO(size2 == size, std::string(std::strerror(errno)));
    }
}

Solution

Add va_end(args0) after vsnprintf finishes using args0. This ensures:

  • Compliance with the C/C++ standard (va_copy + va_end pairing).

  • No resource leaks on platforms where va_list manages allocated memory (e.g., some ABIs for variadic functions).

void fmtstr_(char const* format, fmtstr_allocator alloc, void* target, va_list args)
{
    va_list args0;
    va_copy(args0, args);
    
    size_t constexpr init_size = 2048;
    char fixed_buffer[init_size];
    auto const size = std::vsnprintf(fixed_buffer, init_size, format, args0);
+   va_end(args0);  // Clean up copied va_list
    TLLM_CHECK_WITH_INFO(size >= 0, std::string(std::strerror(errno)));
    // ... rest unchanged ...
}

Summary by CodeRabbit

  • Bug Fixes
    • Improved internal resource management to prevent potential issues during string formatting operations.

Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

📝 Walkthrough

Walkthrough

A call to va_end(args0) was added immediately after the use of the copied va_list in cpp/tensorrt_llm/common/stringUtils.cpp to ensure proper cleanup. No other logic or control flow was modified.

Changes

Cohort / File(s) Change Summary
va_list Cleanup Update
cpp/tensorrt_llm/common/stringUtils.cpp
Added va_end(args0) after vsnprintf to clean up the copied va_list.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @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 or @coderabbitai title anywhere in the PR title to generate the title automatically.

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.

@fyf2016 fyf2016 changed the title [None][Fix] Fix: Add missing va_end(args0) in fmtstr_ to prevent potential resource leak [None][fix] Fix: Add missing va_end(args0) in fmtstr_ to prevent potential resource leak Aug 8, 2025
Copy link
Contributor

@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: 0

🔭 Outside diff range comments (1)
cpp/tensorrt_llm/common/stringUtils.cpp (1)

46-55: Document fmtstr_allocator’s null-terminator contract
The default allocator (std::string::resize(count)) guarantees storage for count characters plus a trailing '\0', so callers of alloc(target, n) get at least n+1 bytes. Make this explicit in the hot path to prevent future one-byte overflows:

File: cpp/tensorrt_llm/common/stringUtils.cpp
Lines: 46

-    auto* memory = alloc(target, size);
+    // alloc(target, size) is required to return a buffer of at least (size + 1) bytes
+    // so we can safely write size characters plus the null terminator.
+    auto* memory = alloc(target, size);
🧹 Nitpick comments (1)
cpp/tensorrt_llm/common/stringUtils.cpp (1)

2-2: Nit: Update copyright year

Guidelines require headers to include the current year. Consider updating to 2025.

- * Copyright (c) 2022-2024, NVIDIA CORPORATION.  All rights reserved.
+ * Copyright (c) 2022-2025, NVIDIA CORPORATION.  All rights reserved.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d45236b and 0bb3e99.

📒 Files selected for processing (1)
  • cpp/tensorrt_llm/common/stringUtils.cpp (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,h,hpp,cc,cxx}: Closing braces of namespaces should have a comment saying the namespace it closes (e.g., } // namespace foo).
Prefer const or constexpr variables over #defines whenever possible.
A variable that is not modified after its initialization should be declared as const.
Except 0 (used for checking signness/existence/emptiness), nullptr, true, false, all other literals should only be used for variable initialization.
Use the Allman indentation style for braces in C++ code.
Put the semicolon for an empty for or while loop in a new line.
The statement forming the body of a switch, while, do..while, or for statement shall be a compound statement (use brace-delimited statements).
If and else should always be followed by brace-delimited statements, even if empty or a single statement.
C++ filenames should use camel case with the first letter lowercase (e.g., thisIsAFilename.cpp), and all files involved in a compilation target must have case-insensitive unique filenames.
All types (including class names) should use camel case with uppercase first letter (e.g., FooBarClass).
Local variables, methods, and namespaces should use camel case with first letter lowercase (e.g., localFooBar).
Non-magic-number global variables that are non-static and not defined in anonymous namespace should use camel case prefixed by 'g' (e.g., gDontUseGlobalFoos).
Non-magic-number global variables that are static or defined in an anonymous namespace should use camel case prefixed by 's' (e.g., sMutableStaticGlobal).
Locally visible static variables should use camel case with lowercase prefix 's' as the first letter (e.g., static std::once_flag sFlag;).
Class member variables should use camel case prefixed with 'm' (e.g., mNbFooValues). Public member variables do not require the 'm' prefix but it is encouraged for clarity.
Enumerations, global constants, static constants at class-scope, and function-scope magic-number/literal constants should be uppercase snake case with prefix...

Files:

  • cpp/tensorrt_llm/common/stringUtils.cpp
**/*.{cpp,h,hpp,cc,cxx,cu,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the current year. This includes .cpp, .h, .cu, .py, and any other source files which are compiled or interpreted.

Files:

  • cpp/tensorrt_llm/common/stringUtils.cpp
🧠 Learnings (3)
📓 Common learnings
Learnt from: fyf2016
PR: NVIDIA/TensorRT-LLM#6679
File: cpp/include/tensorrt_llm/common/logger.h:63-68
Timestamp: 2025-08-07T01:45:23.301Z
Learning: In C++ variadic template functions, the compiler implicitly inserts positional placeholders for template parameter packs during __attribute__((format(printf, ...))) processing, causing an offset in parameter numbering. The format string parameter index should account for this template expansion mechanism rather than the nominal parameter position.
📚 Learning: 2025-08-07T01:45:23.301Z
Learnt from: fyf2016
PR: NVIDIA/TensorRT-LLM#6679
File: cpp/include/tensorrt_llm/common/logger.h:63-68
Timestamp: 2025-08-07T01:45:23.301Z
Learning: In C++ variadic template functions, the compiler implicitly inserts positional placeholders for template parameter packs during __attribute__((format(printf, ...))) processing, causing an offset in parameter numbering. The format string parameter index should account for this template expansion mechanism rather than the nominal parameter position.

Applied to files:

  • cpp/tensorrt_llm/common/stringUtils.cpp
📚 Learning: 2025-08-07T01:45:23.301Z
Learnt from: fyf2016
PR: NVIDIA/TensorRT-LLM#6679
File: cpp/include/tensorrt_llm/common/logger.h:63-68
Timestamp: 2025-08-07T01:45:23.301Z
Learning: In GCC/Clang, printf format attributes with C++ variadic templates use the same parameter numbering as C-style variadics: parameter 1 is the format string, parameter 2 is where the template parameter pack begins. There are no implicit positional placeholders that offset the numbering. The syntax is __attribute__((format(printf, fmt_idx, args_idx))) where fmt_idx and args_idx are 1-based indices.

Applied to files:

  • cpp/tensorrt_llm/common/stringUtils.cpp
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Pre-commit Check
🔇 Additional comments (1)
cpp/tensorrt_llm/common/stringUtils.cpp (1)

37-39: Correct: Pair va_copy with va_end to avoid UB/resource leaks

Good fix. This correctly matches the va_copy(args0, args) with va_end(args0) and prevents UB on ABIs where va_list requires cleanup. Placement right after the first vsnprintf ensures cleanup even on error paths.

@fyf2016
Copy link
Contributor Author

fyf2016 commented Aug 8, 2025

Dear @tongyuantongyu ,I noticed that you have made some related modifications to the stringUtils.cpp file (a139eae), so I was wondering if you could take a look at this PR I submitted when you have some free time?

image

By the way, I have another PR(https://github.com/NVIDIA/TensorRT-LLM/pull/6723) that needs your review.

@tongyuantongyu
Copy link
Member

Thank you for the contribution. Can you fix the issue in fmtstr as well?

Notice that if fmtstr_ throws, va_end will never be called.

@fyf2016
Copy link
Contributor Author

fyf2016 commented Aug 11, 2025

Thank you for the contribution. Can you fix the issue in fmtstr as well?

Notice that if fmtstr_ throws, va_end will never be called.

Of course, I'll update the code later tonight to fix this part. Thank you for your review ~

image

( By the way, I have another PR about the const modifier(#6679) that needs your review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Community want to contribute PRs initiated from Community
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants