Skip to content

Commit 80bab69

Browse files
ctruedenclaude
andcommitted
One opens, to the container
A plugin author now writes `opens com.example to org.scijava.context;` and nothing more. Context.privateLookupIn(Class) hands out a lookup created inside the container, and the execution layer reads and writes @parameter fields through it, since reflective access is checked against the lookup's module rather than the module calling. Two things measured rather than assumed, both of which would have been easy to get wrong: - privateLookupIn also requires the lookup's module to READ the target's module. A container never declares that -- plugins depend on it, not the reverse -- so it must add the edge at runtime with addReads, and only a module's own code may do that. That is the second reason this method has to live in Context. - The capability is scoped to one class. Exposing the container's general-purpose lookup would let any holder reflect into anything opened to the container; returning privateLookupIn(type, ...) instead yields a lookup limited to that class, and makes the execution layer's side simpler too. Field access moves from Field.setAccessible to a VarHandle obtained from the lookup, resolved once per member. A test asserts the command package is not open to org.scijava.execute, so that a regression names itself instead of surfacing as a puzzling access error at run time. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gJpzGd3ksbME4CN6Tu2ni
1 parent 0e4ac38 commit 80bab69

10 files changed

Lines changed: 194 additions & 28 deletions

File tree

‎scijava-command/src/main/java/module-info.java‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,11 @@
3131

3232
exports org.scijava.command;
3333

34-
// NB: a command's package must be opened to both modules that reflect into
35-
// it: the context constructs the command, and the execution layer reads and
36-
// writes its @Parameter fields. `opens` is not `exports` -- the classes stay
37-
// invisible to ordinary callers either way.
38-
opens org.scijava.command to org.scijava.context, org.scijava.execute;
34+
// NB: one opens, to the container alone. The execution layer reads
35+
// @Parameter fields through a lookup the context supplies, so it needs no
36+
// opens of its own. `opens` is not `exports` -- these classes stay invisible
37+
// to ordinary callers regardless.
38+
opens org.scijava.command to org.scijava.context;
3939

4040
requires transitive org.scijava.context;
4141
requires transitive org.scijava.execute;

‎scijava-command/src/main/java/org/scijava/command/CommandInfo.java‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import java.util.Map;
3333
import java.util.Optional;
3434

35+
import org.scijava.context.Context;
3536
import org.scijava.discovery.Discovery;
3637
import org.scijava.execute.Executable;
3738
import org.scijava.execute.ExecutableInstance;
@@ -60,13 +61,15 @@ public class CommandInfo implements Executable {
6061

6162
private final Discovery<Command> discovery;
6263
private final Map<String, String> menu;
64+
private final Context context;
6365
private Executable delegate;
6466

6567
CommandInfo(final Discovery<Command> discovery,
66-
final Map<String, String> menu)
68+
final Map<String, String> menu, final Context context)
6769
{
6870
this.discovery = discovery;
6971
this.menu = menu;
72+
this.context = context;
7073
}
7174

7275
// -- Metadata, readable without loading the class --
@@ -153,7 +156,10 @@ public String toString() {
153156
private synchronized Executable delegate() {
154157
if (delegate == null) {
155158
final Class<? extends Command> type = discovery.type();
156-
delegate = Executables.of(type);
159+
// NB: the lookup comes from the context, so a command's package need
160+
// only be opened to org.scijava.context -- not additionally to the
161+
// execution layer that reads its @Parameter fields.
162+
delegate = Executables.of(type, context.privateLookupIn(type));
157163
}
158164
return delegate;
159165
}

‎scijava-command/src/main/java/org/scijava/command/Commands.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ public static List<CommandInfo> discover(final Context context) {
7171
final List<CommandInfo> commands = new ArrayList<>();
7272
for (final Discovery<Command> discovery : context.plugins(Command.class)) {
7373
commands.add(new CommandInfo(discovery, menus.getOrDefault( //
74-
discovery.implClassName(), Map.of())));
74+
discovery.implClassName(), Map.of()), context));
7575
}
7676
commands.sort(Comparator.comparingDouble(CommandInfo::weight) //
7777
.thenComparing(CommandInfo::label));

‎scijava-command/src/test/java/org/scijava/command/CommandsTest.java‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,28 @@ public void testEachRunHasItsOwnInstance() throws Exception {
148148
}
149149
}
150150

151+
/**
152+
* A command author writes one {@code opens}, to the container.
153+
* <p>
154+
* The execution layer reads {@code @Parameter} fields through a lookup the
155+
* context supplies, so it needs no access of its own. Were that to regress,
156+
* running a command would fail - but this asserts the intent directly, so
157+
* the reason is obvious rather than inferred from a stack trace.
158+
* </p>
159+
*/
160+
@Test
161+
public void testOneOpensIsEnough() {
162+
final Module module = Command.class.getModule();
163+
assertTrue(module.isNamed(), "not running on the module path");
164+
final Module context = Context.class.getModule();
165+
final Module execute = org.scijava.execute.Executables.class.getModule();
166+
167+
assertTrue(module.isOpen("org.scijava.command", context),
168+
"commands must be open to the container");
169+
assertFalse(module.isOpen("org.scijava.command", execute),
170+
"commands should not need opening to the execution layer as well");
171+
}
172+
151173
private static CommandInfo find(final Context context, final Class<?> type) {
152174
return Commands.discover(context).stream() //
153175
.filter(c -> type.getName().equals(c.className())) //

‎scijava-context/.factorypath‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<factorypath>
2+
<factorypathentry kind="VARJAR" id="M2_REPO/org/scijava/scijava-discovery/1.0.1-SNAPSHOT/scijava-discovery-1.0.1-SNAPSHOT.jar" enabled="true" runInBatchMode="false"/>
3+
<factorypathentry kind="VARJAR" id="M2_REPO/org/scijava/scijava-index/1.0.0-SNAPSHOT/scijava-index-1.0.0-SNAPSHOT.jar" enabled="true" runInBatchMode="false"/>
4+
<factorypathentry kind="VARJAR" id="M2_REPO/org/scijava/scijava-common3/1.0.0/scijava-common3-1.0.0.jar" enabled="true" runInBatchMode="false"/>
5+
<factorypathentry kind="VARJAR" id="M2_REPO/org/scijava/scijava-priority/1.0.1-SNAPSHOT/scijava-priority-1.0.1-SNAPSHOT.jar" enabled="true" runInBatchMode="false"/>
6+
<factorypathentry kind="VARJAR" id="M2_REPO/org/scijava/scijava-spi/1.0.0-SNAPSHOT/scijava-spi-1.0.0-SNAPSHOT.jar" enabled="true" runInBatchMode="false"/>
7+
</factorypath>

‎scijava-context/src/main/java/org/scijava/context/Context.java‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030
package org.scijava.context;
3131

32+
import java.lang.invoke.MethodHandles;
3233
import java.lang.reflect.Field;
3334
import java.lang.reflect.InvocationTargetException;
3435
import java.lang.reflect.Method;
@@ -253,6 +254,52 @@ public List<Subscription> subscribe(final Object target) {
253254
return subscriptions;
254255
}
255256

257+
/**
258+
* Gets a {@link java.lang.invoke.MethodHandles.Lookup} able to reflect into
259+
* the given class, for a collaborator that cannot obtain one itself.
260+
* <p>
261+
* This exists so that a plugin author writes <em>one</em> line rather than
262+
* two:
263+
* </p>
264+
*
265+
* <pre>
266+
* opens com.example to org.scijava.context;
267+
* </pre>
268+
* <p>
269+
* Reflective access is checked against the module performing it, so any
270+
* other SciJava module that must read a plugin's fields - the execution
271+
* layer, reading {@code @Parameter} values - would otherwise need its own
272+
* {@code opens}. Handing it a lookup created here means the single
273+
* {@code opens} to this module covers them all.
274+
* </p>
275+
* <p>
276+
* NB: the returned lookup is scoped to {@code type} alone, not a
277+
* general-purpose capability: its holder can reflect into that one class
278+
* and nothing else.
279+
* </p>
280+
* <p>
281+
* NB: {@code privateLookupIn} also requires this module to <em>read</em> the
282+
* target's module, which a container never declares - plugins depend on it,
283+
* not the reverse. A module may only add that edge from its own code, which
284+
* is the other reason this method has to live here.
285+
* </p>
286+
*
287+
* @param type the class to be reflected into
288+
* @return a lookup with private access to that class
289+
* @throws ServiceException if the class's package is not open to this module
290+
*/
291+
public MethodHandles.Lookup privateLookupIn(final Class<?> type) {
292+
try {
293+
Context.class.getModule().addReads(type.getModule());
294+
return MethodHandles.privateLookupIn(type, MethodHandles.lookup());
295+
}
296+
catch (final IllegalAccessException exc) {
297+
throw new ServiceException("Cannot reflect into " + type.getName() + //
298+
". Does its module declare `opens " + type.getPackageName() + //
299+
" to org.scijava.context;`?", exc);
300+
}
301+
}
302+
256303
/** Gets this context's event bus. */
257304
public EventBus events() {
258305
return events;

‎scijava-execute/src/main/java/org/scijava/execute/Executables.java‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,21 @@ public static Executable of(final Class<? extends Runnable> type) {
6969
return new JavaExecutable(type);
7070
}
7171

72+
/**
73+
* Describes the given class as an {@link Executable}, reflecting into it
74+
* through the given lookup.
75+
*
76+
* @param type a class whose {@link Parameter} fields declare its parameters
77+
* @param lookup a lookup with private access to it, as
78+
* {@code Context.privateLookupIn} provides
79+
* @return a description of it
80+
*/
81+
public static Executable of(final Class<? extends Runnable> type,
82+
final java.lang.invoke.MethodHandles.Lookup lookup)
83+
{
84+
return new JavaExecutable(type, lookup);
85+
}
86+
7287
/**
7388
* Describes an already-constructed object as an {@link Executable} whose
7489
* {@code create} yields that same object.
@@ -118,7 +133,18 @@ public void run() {
118133

119134
/** Describes the inputs and outputs of the given class. */
120135
public static Struct struct(final Class<?> type) {
121-
return Structs.from(type, type, PARSER);
136+
return struct(type, null);
137+
}
138+
139+
/**
140+
* Describes the inputs and outputs of the given class, reflecting into it
141+
* through the given lookup.
142+
*/
143+
public static Struct struct(final Class<?> type,
144+
final java.lang.invoke.MethodHandles.Lookup lookup)
145+
{
146+
return Structs.from(type, type, lookup == null ? PARSER //
147+
: new FieldParameterMemberParser(lookup));
122148
}
123149

124150
/**

‎scijava-execute/src/main/java/org/scijava/execute/FieldParameterMember.java‎

Lines changed: 46 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@
2929

3030
package org.scijava.execute;
3131

32+
import java.lang.invoke.MethodHandles;
33+
import java.lang.invoke.MethodHandles.Lookup;
34+
import java.lang.invoke.VarHandle;
3235
import java.lang.reflect.Field;
3336
import java.lang.reflect.Type;
3437

@@ -49,8 +52,31 @@ public class FieldParameterMember<T> implements Member<T>, ValueAccessible<T> {
4952
private final Field field;
5053
private final Parameter parameter;
5154
private final Type itemType;
55+
private final Lookup lookup;
56+
private VarHandle handle;
5257

5358
public FieldParameterMember(final Field field, final Type structType) {
59+
this(field, structType, null);
60+
}
61+
62+
/**
63+
* Creates a member whose value is read and written through the given lookup.
64+
* <p>
65+
* NB: reflective access is checked against the module that performs it, so
66+
* a lookup supplied by the container is what lets a plugin author open
67+
* their package to the container alone, rather than to every SciJava module
68+
* that might touch their fields.
69+
* </p>
70+
*
71+
* @param field the annotated field
72+
* @param structType the type declaring it
73+
* @param lookup a lookup with private access to the declaring class, or
74+
* null to reflect with this module's own access
75+
*/
76+
public FieldParameterMember(final Field field, final Type structType,
77+
final Lookup lookup)
78+
{
79+
this.lookup = lookup;
5480
this.field = field;
5581
this.parameter = field.getAnnotation(Parameter.class);
5682
if (parameter == null) {
@@ -101,31 +127,34 @@ public String label() {
101127
@Override
102128
@SuppressWarnings("unchecked")
103129
public T get(final Object o) {
104-
try {
105-
field.setAccessible(true);
106-
return (T) field.get(o);
107-
}
108-
catch (final RuntimeException | IllegalAccessException exc) {
109-
throw new IllegalStateException(cannotAccess(o), exc);
110-
}
130+
return (T) handle().get(o);
111131
}
112132

113133
@Override
114134
public void set(final T value, final Object o) {
115-
try {
116-
field.setAccessible(true);
117-
field.set(o, value);
118-
}
119-
catch (final RuntimeException | IllegalAccessException exc) {
120-
throw new IllegalStateException(cannotAccess(o), exc);
135+
handle().set(o, value);
136+
}
137+
138+
/** Gets the handle for this field, resolving it on first use. */
139+
private synchronized VarHandle handle() {
140+
if (handle == null) {
141+
try {
142+
final Lookup access = lookup != null ? lookup //
143+
: MethodHandles.privateLookupIn(field.getDeclaringClass(),
144+
MethodHandles.lookup());
145+
handle = access.unreflectVarHandle(field);
146+
}
147+
catch (final RuntimeException | IllegalAccessException exc) {
148+
throw new IllegalStateException(cannotAccess(), exc);
149+
}
121150
}
151+
return handle;
122152
}
123153

124-
private String cannotAccess(final Object o) {
125-
// NB: the same qualified-opens requirement as everywhere else that
126-
// reflects into user classes.
154+
private String cannotAccess() {
127155
return "Cannot access " + field.getDeclaringClass().getName() + "." + //
128156
field.getName() + ". Does its module declare `opens " + field
129-
.getDeclaringClass().getPackageName() + " to org.scijava.execute;`?";
157+
.getDeclaringClass().getPackageName() + " to org.scijava.context;`?" + //
158+
" A caller with no container must open to org.scijava.execute instead.";
130159
}
131160
}

‎scijava-execute/src/main/java/org/scijava/execute/FieldParameterMemberParser.java‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030
package org.scijava.execute;
3131

32+
import java.lang.invoke.MethodHandles.Lookup;
3233
import java.lang.reflect.Type;
3334
import java.util.ArrayList;
3435
import java.util.List;
@@ -46,6 +47,20 @@ public class FieldParameterMemberParser implements
4647
MemberParser<Class<?>, Member<?>>
4748
{
4849

50+
private final Lookup lookup;
51+
52+
public FieldParameterMemberParser() {
53+
this(null);
54+
}
55+
56+
/**
57+
* @param lookup a lookup with private access to the classes being parsed,
58+
* or null to reflect with this module's own access
59+
*/
60+
public FieldParameterMemberParser(final Lookup lookup) {
61+
this.lookup = lookup;
62+
}
63+
4964
@Override
5065
public List<Member<?>> parse(final Class<?> source, final Type structType) {
5166
if (source == null) return List.of();
@@ -55,7 +70,7 @@ public List<Member<?>> parse(final Class<?> source, final Type structType) {
5570
for (Class<?> c = source; c != null; c = c.getSuperclass()) {
5671
for (final var field : c.getDeclaredFields()) {
5772
if (!field.isAnnotationPresent(Parameter.class)) continue;
58-
members.add(new FieldParameterMember<>(field, structType));
73+
members.add(new FieldParameterMember<>(field, structType, lookup));
5974
}
6075
}
6176
return members;

‎scijava-execute/src/main/java/org/scijava/execute/JavaExecutable.java‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929

3030
package org.scijava.execute;
3131

32+
import java.lang.invoke.MethodHandles.Lookup;
33+
3234
import org.scijava.struct.Struct;
3335
import org.scijava.struct.StructInstance;
3436

@@ -44,8 +46,20 @@ public class JavaExecutable implements Executable {
4446
private final Struct struct;
4547

4648
public JavaExecutable(final Class<? extends Runnable> type) {
49+
this(type, null);
50+
}
51+
52+
/**
53+
* @param type the class to describe
54+
* @param lookup a lookup with private access to it, or null to reflect with
55+
* this module's own access. A container supplies one so that the
56+
* class's package need only be opened to the container.
57+
*/
58+
public JavaExecutable(final Class<? extends Runnable> type,
59+
final Lookup lookup)
60+
{
4761
this.type = type;
48-
this.struct = Executables.struct(type);
62+
this.struct = Executables.struct(type, lookup);
4963
}
5064

5165
@Override

0 commit comments

Comments
 (0)