Skip to content

Commit 74892a4

Browse files
committed
Fixes #2903. Removing event hooks can AIOOB
1 parent 5fd659d commit 74892a4

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

core/src/main/java/org/jruby/Ruby.java

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3051,17 +3051,25 @@ public synchronized void addEventHook(EventHook hook) {
30513051

30523052
public synchronized void removeEventHook(EventHook hook) {
30533053
EventHook[] hooks = eventHooks;
3054+
30543055
if (hooks.length == 0) return;
3055-
EventHook[] newHooks = new EventHook[hooks.length - 1];
3056-
boolean found = false;
3057-
for (int i = 0, j = 0; i < hooks.length; i++) {
3058-
if (!found && hooks[i] == hook && !found) { // exclude first found
3059-
found = true;
3060-
continue;
3056+
3057+
int pivot = -1;
3058+
for (int i = 0; i < hooks.length; i++) {
3059+
if (hooks[i] == hook) {
3060+
pivot = i;
3061+
break;
30613062
}
3062-
newHooks[j] = hooks[i];
3063-
j++;
30643063
}
3064+
3065+
if (pivot == -1) return; // No such hook found.
3066+
3067+
EventHook[] newHooks = new EventHook[hooks.length - 1];
3068+
// copy before and after pivot into the new array but don't bother
3069+
// to arraycopy if pivot is first/last element of the old list.
3070+
if (pivot != 0) System.arraycopy(hooks, 0, newHooks, 0, pivot);
3071+
if (pivot != hooks.length-1) System.arraycopy(hooks, pivot + 1, newHooks, pivot, hooks.length - (pivot + 1));
3072+
30653073
eventHooks = newHooks;
30663074
hasEventHooks = newHooks.length > 0;
30673075
}

0 commit comments

Comments
 (0)