Urgent.News

What's breaking now, across thousands of outlets.

Tech

Hacking in the 'nameOf'

When validating arguments, including parameter names in the exception message can clarify which parameter received a bad value. However, the parameter name is often hardcoded in exception messages. To avoid this duplication, some programming languages like C# have a nameof expression that retrieves the textual name of an identifier as a string.

This prevents inconsistencies when refactoring code. Intrigued by this concept, a programmer decided to implement a pure library solution for Java, solving a tiny problem in a complex way. To do this, they first needed to understand how the Java Virtual Machine (JVM) operates. The JVM reads instructions from bytecode, pushing arguments onto an operand stack and popping them off to perform operations.

When compiling with -parameters, the bytecode also includes parameter names. The programmer used the StackWalker API and the ClassFile API to implement the nameOf method. This method uses the StackWalker API to determine the frame from which the nameOf method was called, including the calling class, method name, descriptor, and bytecode index within the method.

By parsing the .class resource for the calling class, the programmer could locate the method and simulate a stack machine to find the symbolic name of the argument at the bytecode index. Although the implementation seems to work, it is mostly untested and can be prone to breaking due to changes in JVM configurations, compiler implementations, and optional debug symbols. Therefore, this implementation should not be used in production.

Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at committing-crimes.com →

More in Tech

More from Wednesday 12 August →