Skip to content

Commit

Permalink
[JENKINS-68930] Fix Java17 Error on agent start (#206)
Browse files Browse the repository at this point in the history
* Fix JENKINS-68930. Use WA to work with modifiers filtered since JDK12.
--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED

* Update src/main/java/org/jenkinsci/plugins/envinject/service/EnvInjectMasterEnvVarsSetter.java

Co-authored-by: Alexander Brandes <[email protected]>

* Throw NoSuchFieldException exception if there is no modifiers field

Co-authored-by: Alexander Brandes <[email protected]>
  • Loading branch information
bulanovk and NotMyFault authored Aug 1, 2022
1 parent d41b38d commit 9b9e962
Showing 1 changed file with 24 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
import org.jenkinsci.lib.envinject.EnvInjectException;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import edu.umd.cs.findbugs.annotations.NonNull;

/**
Expand All @@ -21,6 +24,23 @@ public EnvInjectMasterEnvVarsSetter(@NonNull EnvVars enVars) {
this.enVars = enVars;
}

private Field getModifiers() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
Method getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class);
getDeclaredFields0.setAccessible(true);
Field[] fields = (Field[]) getDeclaredFields0.invoke(Field.class, false);
Field modifiers = null;
for (Field each : fields) {
if ("modifiers".equals(each.getName())) {
modifiers = each;
break;
}
}
if (modifiers == null) {
throw new NoSuchFieldException();
}
return modifiers;
}

@Override
public Void call() throws EnvInjectException {
try {
Expand All @@ -32,14 +52,14 @@ public Void call() throws EnvInjectException {
}
Field masterEnvVarsFiled = EnvVars.class.getDeclaredField("masterEnvVars");
masterEnvVarsFiled.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
Field modifiersField = getModifiers();
modifiersField.setAccessible(true);
modifiersField.setInt(masterEnvVarsFiled, masterEnvVarsFiled.getModifiers() & ~Modifier.FINAL);
masterEnvVarsFiled.set(null, enVars);
} catch (IllegalAccessException iae) {
} catch (IllegalAccessException | NoSuchFieldException iae) {
throw new EnvInjectException(iae);
} catch (NoSuchFieldException nsfe) {
throw new EnvInjectException(nsfe);
} catch (InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}

return null;
Expand Down

0 comments on commit 9b9e962

Please sign in to comment.