Java bytecode: Difference between revisions

Content deleted Content added
Removing link(s) to "Byte Code Engineering Library": Removing links to deleted page Byte Code Engineering Library.
 
(143 intermediate revisions by more than 100 users not shown)
Line 1:
{{Short description|Instruction set of the Java virtual machine}}
'''Java bytecode''' is the [[instruction set]] of the [[Java virtual machine]]. Each [[bytecode]] is composed by one, or in some cases two, bytes that represent the instruction ([[opcode]]), along with zero or more bytes for passing parameters. Of the possible 256 byte-long [[opcode]]s, 198 are currently in use, 51 are reserved for future use, and 3 are set aside as permanently unimplemented.<ref name="reserved_opcodes">[http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.2 VM Spec - Reserved Opcodes]</ref>
{{Use dmy dates|date=November 2023}}
{{Use American English|date=November 2023}}
 
'''Java bytecode''' is the instruction set of the [[Java virtual machine]] (JVM), the language to which [[Java (programming language)|Java]] and other JVM-compatible [[source code]] is [[compiler|compiled]].<ref name="oracle jvm spec">{{Cite web|url=http://docs.oracle.com/javase/specs/jvms/se8/html/|title=Java Virtual Machine Specification|publisher=Oracle|access-date=14 November 2023}}</ref> Each instruction is represented by a single [[byte]], hence the name [[bytecode]], making it a compact form of [[data]].<ref name="JVM Book">{{Cite book|last=Lindholm|first=Tim|title=The Java Virtual Machine Specification|year=2015|publisher=Oracle|isbn=978-0133905908}}</ref>
 
Due to the nature of bytecode, a Java bytecode [[computer program|program]] is runnable on any machine with a compatible JVM, without the lengthy process of compiling from source code.
 
Java bytecode is used at [[Runtime (program lifecycle phase)|runtime]] either [[interpreter (computing)|interpreted]] by a JVM or compiled to machine code via [[Just-in-time compilation|just-in-time]] (JIT) compilation and run as a native application.
 
As Java bytecode is designed for a cross-platform compatibility and security, a Java bytecode application tends to run consistently across various [[computer hardware|hardware]] and [[software]] configurations.<ref>{{Cite journal|last=Arnold|first=Ken|title=The Java Programming Language|journal=Sun Microsystems|year=1996|volume=1|issue=1|pages=30–40}}</ref>
 
== Relation to Java ==
AIn [[Javageneral, (programminga language)|Java [[programmer]] programmer does not need to beunderstand awareJava ofbytecode or understandeven Javabe bytecodeaware atof allit. However, as suggested in the [[IBM]] developerWorks journal, "Understanding bytecode and what bytecode is likely to be generated by a [[Java compiler]] helps the Java programmer in the same way that knowledge of [[assembly Languagelanguage|assembly]] helps the [[C (programming language)|C]] or [[C++]] programmer."<ref>[http{{Cite web |title=IBM Developer |url=https://wwwdeveloper.ibm.com/developerworkslanguages/ibmjava/library/it |access-haggar_bytecode/date=20 UnderstandingFebruary bytecode2006 makes you a better programmer]|website=developer.ibm.com}}</ref>
 
== Instruction set architecture ==
 
The bytecode comprises various instruction types, including data manipulation, control transfer, object creation and manipulation, and method invocation, all integral to Java's object-oriented programming model.<ref name="oracle jvm spec"/>
 
The JVM is both a [[stack machine]] and a [[register machine]]. Each [[Call stack#STACK-FRAME|frame]] for a method call has an "operand stack" and an array of "local variables".<ref name="jvm">{{cite book |last1=Lindholm |first1=Tim |last2=Yellin |first2=Frank |last3=Bracha |first3=Gilad |last4=Buckley |first4=Alex |title=The Java Virtual Machine Specification |edition=Java SE 8 |date=2015-02-13 |url=http://docs.oracle.com/javase/specs/jvms/se8/html/}}</ref>{{rp|2.6}} <ref name="JVM Book"/> The operand stack is used for passing operands to computations and for receiving the return value of a called method, while local variables serve the same purpose as [[Processor register|registers]] and are also used to pass method arguments. The maximum size of the operand stack and local variable array, computed by the compiler, is part of the attributes of each method.<ref name="jvm"/>{{rp|4.7.3}} Each can be independently sized from 0 to 65535 values, where each value is 32 bits. {{code|lang="java"|long}} and {{code|lang="java"|double}} types, which are 64 bits, take up two consecutive local variables<ref name="jvm"/>{{rp|2.6.1}} (which need not be 64-bit aligned in the local variables array) or one value in the operand stack (but are counted as two units in the depth of the stack).<ref name="jvm"/>{{rp|2.6.2}}
 
=== Instruction set ===
 
{{further|List of Java bytecode instructions}}
 
Each [[bytecode]] is composed of one byte that represents the [[opcode]], along with zero or more bytes for operands.<ref name="jvm"/>{{rp|2.11}}
== Instructions ==
{{See also|Java bytecode instruction listings}}
 
Of the 256 possible byte-long [[opcode]]s, {{as of|2015|lc=y}}, 202 are in use (~79%), 51 are reserved for future use (~20%), and 3 instructions (~1%) are permanently reserved for JVM implementations to use.<ref name="jvm"/>{{rp|6.2}} Two of these (<code>impdep1</code> and <code>impdep2</code>) are to provide traps for implementation-specific software and hardware, respectively. The third is used for debuggers to implement breakpoints.
As each byte has 256 potential values, there are 256 possible opcodes. Of these, <code>0x00</code> through <code>0xca</code>, <code>0xfe</code>, and <code>0xff</code> are assigned values. 0xca is reserved as a breakpoint instruction for Java debuggers and its type is not used by the language. Similarly, <code>0xfe</code> and <code>0xff</code> are not used by the language and are reserved for internal use by the Java virtual machine.
 
Instructions fall into a number of broad groups:
* Load and store (e.g. <code>aload_0</code>, <code>istore</code>)
* Arithmetic and logic (e.g. <code>ladd</code>, <code>fcmpl</code>)
* Type conversion (e.g. <code>i2b</code>, <code>d2i</code>)
* Object creation and manipulation (<code>new</code>, <code>putfield</code>)
* Operand stack management (e.g. <code>swap</code>, <code>dup2</code>)
* Control transfer (e.g. <code>ifeq</code>, <code>goto</code>)
* Method invocation and return (e.g. <code>invokespecial</code>, <code>areturn</code>)
 
There are also a few instructions for a number of more specialized tasks such as exception throwing, synchronization, etc.
 
Many instructions have [[Opcode prefix|prefixes]] and/or suffixes referring to the types of operands they operate on.<ref name="jvm"/>{{rp|2.11.1}} These are as follows:
 
{| class="wikitable"
|-
! Prefix/Suffixsuffix !! Operand Typetype
|-
| <code>i</code> || integer
Line 39 ⟶ 58:
|-
| <code>d</code> || double
|-
| <code>z</code> || boolean
|-
| <code>a</code> || reference
|}
 
For example, "<code>iadd"</code> will add two integers, while "<code>dadd"</code> will add two doubles. The "<code>const"</code>, "<code>load"</code>, and "<code>store"</code> instructions may also take a suffix of the form "<code>_''n''"</code>, where ''n'' is a number from 0–3 for "<code>load"</code> and "<code>store"</code>. The maximum ''n'' for "<code>const"</code> differs by type.
 
The "<code>const"</code> instructions push a value of the specified type onto the stack. For example, "<code>iconst_5"</code> will push an integer (32 bit value) with the value 5 onto the stack, while "<code>dconst_1"</code> will push a double (64 bit floating point value) with the value 1 onto the stack. There is also an "<code>aconst_null"</code>, which pushes "a {{code|lang=java|null"}} reference. The ''n'' for the "<code>load"</code> and "<code>store"</code> instructions specifies the ___locationindex in the local variable table{{clarify|date=October 2010}}array to load from or store to. The "<code>aload_0"</code> instruction pushes the object in local variable 0 onto the stack (this is usually the "<code>[[this" (computer programming)|this]]</code> object). "<code>istore_1"</code> stores the integer on the top of the stack into local variable 1. For variableslocal withvariables higherbeyond numbers3 the suffix is dropped and operands must be used.
 
== Model of computation ==
The [[model of computation]] of Java bytecode is that of a [[stack-oriented programming language]]. For example, [[Assembly language|assembly code]] for an [[x86|x86 processor]] might look like this:
<source lang="asm">
mov eax, byte [ebp-4]
mov edx, byte [ebp-8]
add eax, edx
mov ecx, eax</source>
This code would add two values and move the result to a different ___location. Similar disassembled bytecode might look like this:
<code>
0 iload_1
1 iload_2
2 iadd
3 istore_3</code>
Here, the two values to be added are pushed onto the stack, where they are retrieved by the addition instruction, summed, and the result placed back on the stack. The storage instruction then moves the top value of the stack into a variable ___location. The numbers in front of the instructions simply represent the offset of each instruction from the beginning of the method.
This stack-oriented model extends to the object oriented aspects of the language as well. A method call called "getName()", for example, may look like the following:
<source lang="java">
Method java.lang.String getName()
0 aload_0 // The "this" object is stored in ___location 0 of the variable table
1 getfield #5 <Field java.lang.String name>
// This instruction pops an object from the top of the stack, retrieves the specified
// field from it, and pushes the field onto the stack.
// In this example, the "name" field corresponds to the fifth constant in the
// constant pool of the class.
4 areturn // Returns the object on top of the stack from the method.</source>
 
== Example ==
 
Consider the following Java code:
 
<source lang="java">
<syntaxhighlight lang="java">
outer:
for (int i = 2; i < 1000; i++) {
Line 84 ⟶ 77:
continue outer;
}
System.out.println (i);
}
</syntaxhighlight>
</source>
 
A Java compiler might translate the Java code above into byte codebytecode as follows, assuming the above was put in a method:
<syntaxhighlight lang="jasmin">
<pre>
0: iconst_2
1: istore_1
Line 112 ⟶ 105:
38: iinc 1, 1
41: goto 2
44: return</presyntaxhighlight>
 
== Generation ==
{{Further|List of JVM languages}}
 
The most common language targeting [[Java virtual machine]] by producing Java bytecode is Java. Originally only one compiler existed, the [[javac]] compiler from [[Sun Microsystems]], which compiles [[Java source code]] to Java bytecode; but because all the specifications for Java bytecode are now available, other parties have supplied compilers that produce Java bytecode. Examples of other compilers include:
{{Main|List of JVM languages}}
*Eclipse compiler for Java (ECJ)
 
*[[Jikes]], compiles from Java to Java bytecode (developed by [[IBM]], implemented in [[C++]])
The most common language targeting [[Java Virtual Machine]] by producing Java bytecode is Java. Originally only one compiler existed, the [[javac]] compiler from Sun Microsystems, which compiles [[Java source code]] to Java bytecode; but because all the specifications for Java bytecode are now available, other parties have supplied compilers that produce Java bytecode. Examples of other compilers include:
*Espresso, compiles from Java to Java bytecode (Java 1.0 only)
 
* [[JikesGNU Compiler for Java]] (GCJ), compiles from Java to Java bytecode; (developedit bycan also compile to native [[IBMmachine code]], implementedand inwas part of the [[C++GNU Compiler Collection]] (GCC) up until version 6.
* Espresso, compiles from Java to Java bytecode (Java 1.0 only)
* [[GNU Compiler for Java|GCJ]], the GNU Compiler for Java, compiles from Java to Java bytecode; it is also able to compile to native machine code and is available as part of the [[GNU Compiler Collection]] (GCC).
 
Some projects provide Java assemblers to enable writing Java bytecode by hand. Assembly code may be also generated by machine, for example by a compiler targeting a [[Java virtual machine]]. Notable Java assemblers include:
*[[Jasmin (Java assembler)|Jasmin]], takes text descriptions for Java classes, written in a simple assembly-like syntax using Java virtual machine instruction set and generates a Java class file<ref>{{Cite web|url=https://jasmin.sourceforge.net/|title=Jasmin Home Page|website=jasmin.sourceforge.net|accessdate=2 June 2024}}</ref>
*Jamaica, a [[Macro (computer science)|macro]] [[assembly language]] for the [[Java virtual machine]]. Java syntax is used for class or interface definition. Method bodies are specified using bytecode instructions.<ref>{{Cite web|url=https://www.javaworld.com/article/2072355/core-java/learn-to-speak-jamaican.html|title=Jamaica: The Java virtual machine (JVM) macro assembler<!-- Bot generated title -->|archive-url=https://web.archive.org/web/20231114000632/https://www.infoworld.com/article/2072355/learn-to-speak-jamaican.html|archive-date=14 November 2023|work=JavaWorld |accessdate=2 June 2024 |last1=Huang |first1=James Jianbo }}</ref>
*Krakatau Bytecode Tools, currently contains three tools: a decompiler and disassembler for Java classfiles and an assembler to create classfiles.<ref>{{Cite web|url=https://github.com/Storyyeller/Krakatau|title=Storyyeller/Krakatau|date=1 June 2024|accessdate=2 June 2024|via=GitHub}}</ref>
*Lilac, an assembler and disassembler for the [[Java virtual machine]].<ref>{{Cite web|url=https://lilac.sourceforge.net/|title=Lilac - a Java assembler|website=lilac.sourceforge.net|accessdate=2 June 2024}}</ref>
 
Others have developed compilers, for different programming languages, to target the Java virtual machine, such as:
* [[Jasmin (Java assembler)|Jasmin]], takes textual descriptions for Java classes, written in a simple assembly-like syntax using Java Virtual Machine instruction set and generates a Java class file <ref>[http://jasmin.sourceforge.net Jasmin Home Page<!-- Bot generated title -->]</ref>
*[[ColdFusion Markup Language|ColdFusion]]
* [[Jamaica (Java assembler)|Jamaica]], a [[Macro (computer science)|macro]] [[assembly language]] for the [[Java virtual machine]]. Java syntax is used for class or interface definition. Method bodies are specified using bytecode instructions.<ref>[http://www.judoscript.org/jamaica.html Jamaica: The Java Virtual Machine (JVM) Macro Assembler<!-- Bot generated title -->]</ref>
*[[JRuby]] and [[Jython]], two [[scripting language]]s based on [[Ruby (programming language)|Ruby]] and [[Python (programming language)|Python]]
 
*[[Groovy (programming language)|Apache Groovy]], optionally typed and dynamic general-purpose language, with static-typing and static compilation capabilities
Others have developed compilers, for different programming languages, in order to target the Java virtual machine, such as:
*[[Scala (programming language)|Scala]], a type-safe general-purpose programming language supporting object-oriented and functional programming
 
*[[JGNAT]] and AppletMagic, compile from the language [[Ada (programming language)|Ada]] to Java bytecode
* [[ColdFusion]]
*[[Java virtual machine#C to bytecode compilers|C to Java byte-code compiler]]s {{dead link|date=December 2018}}
* [[JRuby]] and [[Jython]], two [[scripting language]]s based on [[Ruby (programming language)|Ruby]] and [[Python (programming language)|Python]]
*[[Clojure]], a functional, immutable, general-purpose programming language in the [[GroovyLisp (programming language)|GroovyLisp]], afamily [[scriptingwith language]]a strong basedemphasis on Javaconcurrency
* [[ScalaKawa (programmingScheme languageimplementation)|ScalaKawa]], aan type-safeimplementation general-purposeof the [[Scheme (programming language)|Scheme]] supportingprogramming object-orientedlanguage, andalso functionala dialect of [[Lisp (programming language)|Lisp]].
*MIDletPascal
* [[JGNAT]] and [[AdaMagic|AppletMagic]], compile from the [[Ada programming language]] to Java bytecode
*[[JavaFX Script]] code is compiled to Java bytecode
* [[Java Virtual Machine#C to bytecode compilers|C to Java byte-code compiler]]s
* [[ClojureKotlin (programming language)|Kotlin]], a functional, immutable,statically-typed general-purpose programming language in the LISP family with a strong emphasis ontype concurrencyinference
*[[Object Pascal]] source code is compiled to Java bytecode using the [[Free Pascal]] 3.0+ compiler.<ref>{{Cite web|url=https://wiki.freepascal.org/FPC_New_Features_3.0|title=FPC New Features 3.0.0 - Free Pascal wiki|website=wiki.freepascal.org|accessdate=2 June 2024}}</ref><ref>{{Cite web|url=https://wiki.freepascal.org/FPC_JVM|title=FPC JVM - Free Pascal wiki|website=wiki.freepascal.org|accessdate=2 June 2024}}</ref>
* [[MIDletPascal]]
* [[JavaFX Script]] code is also compiled to Java bytecode.
 
== Execution ==
 
There are several virtual machines available today, both free and commercial products.
 
{{Further|Java virtual machine}}
 
IfThere executingare several Java virtual machines available today to execute Java bytecode, both free and commercial products. If executing bytecode in a Java virtual machine is not desirableundesirable, a developer can also compile Java source code or Java bytecode directly to native machine code with tools such as the [[GCJ|GNU Compiler for Java]] (GCJ). Some processors can execute Java bytecode natively. Such processors are known astermed ''[[Java processor]]s''.
 
== Support for dynamic languages ==
{{MainFurther|List of JVM languages}}
 
The [[Java Virtualvirtual Machinemachine]] provides some support for [[Type system#Dynamic typing|dynamically typed languages]]. Most of the existingextant JVM instruction set is [[Type system#Static typing|statically typed]] - in the sense that method calls have their signatures type-checked at [[compile time]], without a mechanism to defer this decision to [[Run time (program lifecycle phase)|run time]], or to choose the method dispatch by an alternative approach.<ref>{{cite web
| url=httphttps://headius.blogspot.com/2007/01/invokedynamic-actually-useful.html
| title=InvokeDynamic: Actually Useful?
| date=2007-01-03
|last=Nutter|first=Charles
| accessdateaccess-date=2008-01-25}}</ref>
 
[[Java Community Process|JSR]] 292 (''Supporting Dynamically Typed Languages on the Java&trade; Platform'')<ref>[http{{Cite web|url=https://www.jcp.org/en/jsr/detail?id=292|title=The seeJava Community Process(SM) Program - JSRs: Java Specification Requests - detail JSR# 292]|website=www.jcp.org|accessdate=2 June 2024}}</ref> added a new <code>invokedynamic</code> instruction at the JVM level, to allow method invocation relying on dynamic [[Type system#Type checking|type checking]] (instead of the existingextant statically type-checked <code>invokevirtual</code> instruction). The [[Da Vinci Machine]] is a prototype virtual machine implementation that hosts JVM extensions aimed at supporting dynamic languages. All JVMs supporting [[Java Platform, Standard Edition|JSE]] 7 also include the <code>invokedynamic</code> opcode.
 
== See also ==
{{Portal|JavaComputer programming}}
<!---♦♦♦ Please keep the list in alphabetical order ♦♦♦--->
* [[Java bytecode instruction listings]]
* Byte Code Engineering Library
* [[Common Intermediate Language]] (CIL), Microsoft's rival to Java bytecode
* [[Java backporting tools]]
* [[Java class file]]
* [[ListJava ofvirtual JVM languagesmachine]]
* [[Java backporting tools]]
* [[C to Java Virtual Machine compilers]]
* [[JStik]]
* [[ObjectWeb ASM]]
* [[Common Intermediate Language]] (CIL), Microsoft's rival to Java bytecode
* [[List of Java bytecode instructions]]
* [[List of JVM languages]]
 
== References ==
Line 176 ⟶ 171:
== External links ==
{{Wikibooks|Java Programming|Byte Code|Java bytecode}}
* [http://docs.oracle.com/javase/specs/jvms/se7se8/html/ Oracle's Java Virtual Machine Specification]
* [http://www.is-research.de/info/vmlanguages/ Programming Languages for the Java Virtual Machine]
* [https://web.archive.org/web/20130618025348/http://www.drgarbage.com/bytecode-visualizer.html Bytecode Visualizer – bytecode viewer and debugger (free Eclipse plugin)]
* [https://web.archive.org/web/20090809232522/http://www.adaptj.com/main/stacktrace AdaptJ StackTrace – bytecode level debugging with a full control of the stack, the local variables, and the execution flow]
* [http://lulachronicles.blogspot.com Java Class Unpacker – plugin for Total Commander, it lets open class files as compressed archives and see fields and methods as files. The bytecode can be viewed as text using F3]
 
{{Java (Sun)}}
 
[[Category:Java platform|Bytecodes]]
[[Category:Assembly languages]]
[[Category:Java platform|Bytecodes]]
[[Category:Bytecodes]]