Skip to content

Fix UInt32 underflow when sizing the address allocator for small subnets#1864

Open
radheradhe01 wants to merge 1 commit into
apple:mainfrom
radheradhe01:fix/subnet-uint32-underflow
Open

Fix UInt32 underflow when sizing the address allocator for small subnets#1864
radheradhe01 wants to merge 1 commit into
apple:mainfrom
radheradhe01:fix/subnet-uint32-underflow

Conversation

@radheradhe01

Copy link
Copy Markdown
Contributor

Problem

DefaultNetworkService.init computes the allocatable address count as:

let size = Int(subnet.upper.value - subnet.lower.value - 3)

upper.value and lower.value are UInt32, so the subtraction happens in UInt32 before the widening to Int. For a subnet where upper - lower < 3 (e.g. a /31), this underflows and traps at runtime instead of producing a negative/zero count.

Fix

Widen to Int before subtracting, and guard that the resulting size is positive — throwing invalidState for a subnet too small to allocate from, rather than trapping.

Notes

No change for normally-sized subnets; this only affects degenerate small subnets that previously crashed.

### Problem
`DefaultNetworkService.init` computes the allocatable address count as:

```swift
let size = Int(subnet.upper.value - subnet.lower.value - 3)
```

`upper.value` and `lower.value` are `UInt32`, so the subtraction happens in `UInt32` **before** the widening to `Int`. For a subnet where `upper - lower < 3` (e.g. a `/31`), this underflows and traps at runtime instead of producing a negative/zero count.

### Fix
Widen to `Int` before subtracting, and guard that the resulting size is positive — throwing `invalidState` for a subnet too small to allocate from, rather than trapping.

### Notes
No change for normally-sized subnets; this only affects degenerate small subnets that previously crashed.
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