@@ -267,7 +267,12 @@ inline NTSTATUS RtlInitUnicodeString(
267267 return STATUS_NAME_TOO_LONG ;
268268 }
269269 DestinationString -> Length = (USHORT )Length ;
270- DestinationString -> MaximumLength = (USHORT )(Length + sizeof (UNICODE_NULL ));
270+ /* Cap MaximumLength to avoid USHORT overflow when Length == UNICODE_STRING_MAX_BYTES */
271+ if (Length + sizeof (UNICODE_NULL ) > UNICODE_STRING_MAX_BYTES ) {
272+ DestinationString -> MaximumLength = (USHORT )Length ;
273+ } else {
274+ DestinationString -> MaximumLength = (USHORT )(Length + sizeof (UNICODE_NULL ));
275+ }
271276 } else {
272277 DestinationString -> Length = 0 ;
273278 DestinationString -> MaximumLength = 0 ;
@@ -454,11 +459,11 @@ RtlAppendUnicodeToString(
454459 // Update destination length
455460 Destination -> Length += sourceLength ;
456461
457- // Null terminate if there's room
458- if (Destination -> Length < Destination -> MaximumLength ) {
462+ // Null terminate if there's room for a full WCHAR
463+ if (Destination -> Length + sizeof ( WCHAR ) <= Destination -> MaximumLength ) {
459464 Destination -> Buffer [Destination -> Length / sizeof (WCHAR )] = UNICODE_NULL ;
460465 }
461- return STATUS_SUCCESS ;
466+ return STATUS_SUCCESS ;
462467}
463468
464469// Implementation of RtlAppendUnicodeStringToString
@@ -516,12 +521,11 @@ RtlAppendUnicodeStringToString(
516521 // Update destination length
517522 Destination -> Length += Source -> Length ;
518523
519- // Add null terminator if there's space (note: this is not required by the API contract
520- // but is a courtesy for debugging and compatibility with C-style strings)
521- if (Destination -> Length < Destination -> MaximumLength ) {
524+ // Add null terminator if there's space for a full WCHAR
525+ if (Destination -> Length + sizeof (WCHAR ) <= Destination -> MaximumLength ) {
522526 Destination -> Buffer [Destination -> Length / sizeof (WCHAR )] = UNICODE_NULL ;
523527 }
524- return STATUS_SUCCESS ;
528+ return STATUS_SUCCESS ;
525529}
526530
527531/**
0 commit comments