Skip to content

Fix bugs and improve input validation across MemNet library#2

Closed
MrDevBot wants to merge 2 commits intomasterfrom
claude/improve-code-quality-36pNW
Closed

Fix bugs and improve input validation across MemNet library#2
MrDevBot wants to merge 2 commits intomasterfrom
claude/improve-code-quality-36pNW

Conversation

@MrDevBot
Copy link
Owner

@MrDevBot MrDevBot commented Feb 3, 2026

Summary

This PR addresses several bugs, improves input validation, and fixes incorrect constant values throughout the MemNet library. The changes enhance code robustness and correctness while maintaining backward compatibility.

Key Changes

Bug Fixes

  • AllocationType.MEM_SHARED: Corrected value from 0x00001000 to 0x08000000 (the previous value overlapped with MEM_COMMIT)
  • ProcessAccessRights.PROCESS_QUERY_LIMITED_INFORMATION: Fixed value from 0x2000 to 0x1000 and updated comment to reflect Windows Vista introduction
  • Library.Search(): Fixed default chunk size from 8196 to 8192 (correct power of 2)
  • Library.EnumerateMemoryRegions(): Added overflow check before adding baseAddress + regionSize to prevent integer overflow on address enumeration

Input Validation Improvements

  • Library.Open(IntPtr): Added validation to reject invalid handles (zero or -1)
  • Library.Search(string): Enhanced pattern validation with null/whitespace checks and proper token parsing using StringSplitOptions.RemoveEmptyEntries
  • Wildcard struct: Converted from primary constructor to explicit constructor with comprehensive validation:
    • Validates token is not null or empty
    • Validates token is exactly 2 characters
    • Provides clear error messages for invalid inputs

Error Message Improvements

  • Library.Read(): Clarified error message from "non-negative" to "positive"
  • Library.Write(): Clarified error message from "non-negative" to "positive"
  • Library.Open(): Added ArgumentException to XML documentation

Code Cleanup

  • PatternScanner/Program.cs: Removed unnecessary unsafe modifier from Main() method

Implementation Details

The overflow check in EnumerateMemoryRegions() prevents potential crashes when enumerating memory regions near the end of the address space. The pattern validation improvements ensure that malformed patterns fail fast with clear error messages rather than causing cryptic failures downstream.

- Wildcard.cs: Add input validation for token length to prevent
  IndexOutOfRangeException on malformed tokens
- AllocationType.cs: Fix MEM_SHARED value conflict (was 0x00001000,
  now 0x08000000) to avoid collision with MEM_COMMIT
- ProcessAccessRights.cs: Fix PROCESS_QUERY_LIMITED_INFORMATION value
  (was 0x2000, now 0x1000) to avoid collision with PROCESS_SET_CONTEXT
- Library.cs: Add handle validation in Open(IntPtr) to reject invalid
  handles (zero or -1)
- Library.cs: Fix misleading error messages ("non-negative" -> "positive")
- Library.cs: Fix integer overflow check in Query() with proper bounds
- Library.cs: Fix default chunk size from 8196 to 8192 (power of 2)
- Library.cs: Add pattern validation in Search() method
- Program.cs: Remove unnecessary unsafe keyword

https://claude.ai/code/session_01TJUYtWajTHrmWrhTco8sBS
Copilot AI review requested due to automatic review settings February 3, 2026 16:23
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes several correctness issues in MemNet’s constants and memory scanning utilities, and strengthens public API input validation/error messaging.

Changes:

  • Corrects Win32 constant values and improves related documentation/comments.
  • Improves input validation for handle hijacking and pattern search parsing (including Wildcard token handling).
  • Adds a safety guard against address arithmetic overflow during memory region enumeration and cleans up an example entry point.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
MemNet/Wildcard.cs Reworks Wildcard construction to validate token shape up-front.
MemNet/Native/ProcessAccessRights.cs Adjusts PROCESS_QUERY_LIMITED_INFORMATION value/comment.
MemNet/Library.cs Adds handle validation, improves pattern parsing, adjusts default chunk size, adds overflow guard, and refines error messages.
MemNet/Enum/AllocationType.cs Updates MEM_SHARED constant value.
Examples/PatternScanner/Program.cs Removes unsafe modifier from Main().

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 192 to 214
/// <exception cref="ArgumentNullException">Thrown if the pattern is null or empty.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown if addresses or chunk size are invalid.</exception>
public List<IntPtr> Search(string pattern, IntPtr startAddress, IntPtr endAddress, int chunkSize = 8196)
public List<IntPtr> Search(string pattern, IntPtr startAddress, IntPtr endAddress, int chunkSize = 8192)
{
var patternTokens = pattern.Split(' ');
if (string.IsNullOrWhiteSpace(pattern))
throw new ArgumentNullException(nameof(pattern), "The search pattern cannot be null or empty.");

var patternTokens = pattern.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (patternTokens.Length == 0)
throw new ArgumentException("The search pattern contains no valid tokens.", nameof(pattern));
Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

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

string.IsNullOrWhiteSpace(pattern) throws ArgumentNullException even when pattern is non-null (e.g., " "). This is inconsistent with .NET exception guidelines and also with the XML docs that say "null or empty". Consider throwing ArgumentNullException only when pattern is null, and using ArgumentException for empty/whitespace patterns (or update the docs/messages to explicitly include whitespace).

Copilot uses AI. Check for mistakes.
Comment on lines 26 to 27
PROCESS_GET_CONTEXT = 0x1000,
PROCESS_SET_CONTEXT = 0x2000,
Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

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

PROCESS_QUERY_LIMITED_INFORMATION is now 0x1000, which duplicates the value of PROCESS_GET_CONTEXT in the same [Flags] enum. This makes the flag set ambiguous and can lead to requesting unintended rights. Consider removing/relocating PROCESS_GET_CONTEXT/PROCESS_SET_CONTEXT (they are thread rights, not process rights) or correcting their values so each process right has a unique bit per the Windows docs linked in the header.

Suggested change
PROCESS_GET_CONTEXT = 0x1000,
PROCESS_SET_CONTEXT = 0x2000,

Copilot uses AI. Check for mistakes.
Comment on lines 16 to 19
_highNibble = token[0] == '?' ? null : Convert.ToInt32(token[0].ToString(), 16);
_lowNibble = token[1] == '?' ? null : Convert.ToInt32(token[1].ToString(), 16);
}

Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

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

The constructor validates null/length, but it can still throw a FormatException from Convert.ToInt32(..., 16) for tokens like "G?"/"ZZ". Since this PR is aiming for clearer input validation, consider explicitly validating each nibble is either '?' or a hex digit and throwing an ArgumentException with a clear message when invalid.

Suggested change
_highNibble = token[0] == '?' ? null : Convert.ToInt32(token[0].ToString(), 16);
_lowNibble = token[1] == '?' ? null : Convert.ToInt32(token[1].ToString(), 16);
}
_highNibble = token[0] == '?' ? null : ParseHexNibble(token[0], 0);
_lowNibble = token[1] == '?' ? null : ParseHexNibble(token[1], 1);
}
private static int ParseHexNibble(char c, int position)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
throw new ArgumentException(
$"Invalid character '{c}' at position {position} in token. Expected '?' or a hexadecimal digit.",
"token");
}

Copilot uses AI. Check for mistakes.
- Library.cs: Fix exception types - ArgumentNullException only for null,
  ArgumentException for empty/whitespace patterns per .NET guidelines
- Program.cs: Replace sizeof(IntPtr) with IntPtr.Size to avoid requiring
  unsafe context
- ProcessAccessRights.cs: Remove PROCESS_GET_CONTEXT and PROCESS_SET_CONTEXT
  as they are thread rights, not process rights (avoids value collision)
- Wildcard.cs: Add explicit hex digit validation with clear error message
  instead of letting Convert.ToInt32 throw FormatException

https://claude.ai/code/session_01TJUYtWajTHrmWrhTco8sBS
@MrDevBot
Copy link
Owner Author

MrDevBot commented Feb 8, 2026

@copilot Review this amendment.

Copy link

Copilot AI commented Feb 8, 2026

@MrDevBot I've opened a new pull request, #3, to work on those changes. Once the pull request is ready, I'll request review from you.

@MrDevBot MrDevBot closed this Feb 8, 2026
@MrDevBot MrDevBot deleted the claude/improve-code-quality-36pNW branch February 8, 2026 04:12
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.

3 participants