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

Fix error in ACE_Process_Options::inherit_environment () #2006

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

viktor-ch
Copy link

@viktor-ch viktor-ch commented Jan 2, 2023

While using ACE_Wide_To_Ascii string conversion class (and correspondingly ::WideCharToMultiByte) there must be expected that the length of the output multi-byte string is not equal to the length of the input Unicode string. That's why the variable iter used to iterate over the original Unicode environment variables must be increased by the source string length (and not by the length of the converted string).

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced the way environment settings are processed to improve overall system stability and reliability.

…ingly ::WideCharToMultiByte) there must be expected that the length of the ouput multi-byte string is not equal to the length of the input unicode string. That's why we the variable iter used to iterate over the original unicode environment varaiables must be increased by the source string length (and not by the length of converted string).
@jwillemsen
Copy link
Member

Please extend one of the unit tests under ACE/tests in such a way that it reproduces the issue you found

@jwillemsen jwillemsen added the needs review Needs to be reviewed label Jan 2, 2023
@viktor-ch
Copy link
Author

The error was found in conjunction with Implementation Repository Activator. On one Chinese Windows machine the Activator could not start a managed server.
Activator starts a server by calling Win API function ::CreateProcess. One of the parameters of ::CreateProcess is the list of environment variables. While preparing the list the Activator:

  1. reads the environment variables using ::GetEnvironmentStringsW as Unicode string
  2. iterates over all variables and converts individual Unicode strings to multi-byte strings using ::WideCharToMultiByte (ACE_Wide_To_Ascii )
  3. adds extra required variables like TAO_USE_IMR = 1
  4. converts variables to Unicode and calls ::CreateProcess

The error occurs on the step 2. The variables occupy a continuous book of memory and are separated by '\0' char in that block. Mistakenly inherit_environment() assumes that the length of the output string of ::WideCharToMultiByte equals to the length of the input string in characters, what is only try for ASCII strings. But if the input string contains characters which cannot be presented with 1 byte (like Chinese) these characters will be presented with 2 bytes in the output string and the length of this string in chars will be longer.
inherit_environment() moves the pointer to the next variable in the memory by adding the length of the currently converted variable so that the pointer will point not to the beginning of the next variable but further. As a result of this issue the next variable will be added incorrectly to the list and passed to ::CreateProcess. Then Windows will recognize invalid environment variable and refuse starting the process.

Consider variables:
PATH=c:\windows;c:\中国人民共和国;
PATHEXT=.COM,.EXE,.BAT

They are passed to ::CreateProcess as:
PATH=c:\windows;c:\中国人民共和国;
=.COM,.EXE,.BAT

(Note that The name PATHEXT is cut from the result list.)


ACE was built with ACE_HAS_WCHAR only. (ACE_USES_WCHAR was not defined)

@jwillemsen
Copy link
Member

Please extend one of the unit tests as reproducer

@jwillemsen
Copy link
Member

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

✅ Actions performed

Full review triggered.

Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

Walkthrough

The changes update the iterator advancement in the ACE_Process_Options::inherit_environment method within the ACE/ace/Process.cpp file. The iterator now advances based on the length determined by ACE_OS::strlen(iter) rather than a fixed length value. This adjustment ensures that the function accurately progresses through each string in the environment array. No modifications to public or exported entity signatures were made.

Changes

File Change Summary
ACE/ace/Process.cpp Updated inherit_environment in ACE_Process_Options to increment the iterator using ACE_OS::strlen(iter) instead of a predefined length value.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Process as ACE_Process_Options
    participant OS as ACE_OS

    Caller->>Process: Call inherit_environment()
    loop Process Environment Array
        Process->>OS: Call ACE_OS::strlen(iter)
        OS-->>Process: Return string length
        Process->>Process: Increment iterator by returned length
    end
Loading

Poem

I'm a little rabbit, hopping through the code,
Adjusting each string where the pointers once strode.
My nose twitches with each careful leap,
Keeping environments aligned and neat.
Banishing bugs like carrots out of sight,
In ACE's fields, I code with delight!

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.
✨ 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.

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

🧹 Nitpick comments (1)
ACE/ace/Process.cpp (1)

924-939: Add error handling and improve documentation.

The code could benefit from:

  1. Error handling for memory allocation failures
  2. Documentation explaining the multi-byte character handling
  3. Bounds checking for string operations

Consider applying these improvements:

 ACE_Vector<char> temp_narrow_env;
+// Convert wide environment strings to narrow, handling multi-byte characters
+// Note: Each wide character may convert to multiple bytes
 if (this->use_unicode_environment_)
   {
     existing_wide_env = ::GetEnvironmentStringsW ();
+    if (!existing_wide_env)
+      {
+        ACELIB_ERROR ((LM_ERROR,
+                    ACE_TEXT ("Failed to get environment strings")));
+        return;
+      }
     for (WCHAR *iter = existing_wide_env; *iter; ++iter)
       {
         ACE_Wide_To_Ascii wta (iter);
+        if (!wta.char_rep())
+          {
+            ACELIB_ERROR ((LM_ERROR,
+                        ACE_TEXT ("Failed to convert environment string")));
+            ::FreeEnvironmentStringsW (existing_wide_env);
+            return;
+          }
         size_t const len = ACE_OS::strlen (wta.char_rep ());
         size_t const idx = temp_narrow_env.size ();
+        try {
           temp_narrow_env.resize (idx + len + 1, 0);
+        } catch (const std::bad_alloc&) {
+          ACELIB_ERROR ((LM_ERROR,
+                      ACE_TEXT ("Failed to allocate memory for environment")));
+          ::FreeEnvironmentStringsW (existing_wide_env);
+          return;
+        }
         ACE_OS::strncpy (&temp_narrow_env[idx], wta.char_rep (), len);
         iter += ACE_OS::strlen(iter);
       }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6756ee1 and 89de0eb.

📒 Files selected for processing (1)
  • ACE/ace/Process.cpp (1 hunks)
🔇 Additional comments (2)
ACE/ace/Process.cpp (2)

935-935: Correct fix for environment variable handling with multi-byte characters.

The change correctly advances the iterator using the source string length instead of the converted string length. This is essential for proper handling of multi-byte characters (e.g., Chinese) where the converted string length can be different from the source string length.

Please add a test case to verify this fix. The test should:

  1. Set up environment variables containing multi-byte characters
  2. Call inherit_environment()
  3. Verify that all environment variables are correctly inherited

Would you like me to help create a test case that reproduces the issue and verifies the fix?


913-969: Extend test coverage for environment inheritance.

As requested by jwillemsen, please extend the unit tests to cover:

  1. Environment inheritance with multi-byte characters
  2. Error conditions (memory allocation, conversion failures)
  3. Mixed ASCII and multi-byte environment variables

Let's verify the existing test coverage:

Would you like me to help create comprehensive test cases that cover these scenarios?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs review Needs to be reviewed
Development

Successfully merging this pull request may close these issues.

2 participants